@mcy2015/pi-web 0.13.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +1 -1
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/required-server-files.js +1 -1
  5. package/.next/required-server-files.json +1 -1
  6. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  7. package/.next/server/app/_global-error.html +1 -1
  8. package/.next/server/app/_global-error.rsc +1 -1
  9. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  12. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  13. package/.next/server/app/_not-found.html +1 -1
  14. package/.next/server/app/_not-found.rsc +2 -2
  15. package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  16. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
  17. package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  18. package/.next/server/app/api/app-update/route.js +1 -1
  19. package/.next/server/app/api/mcp/route.js +1 -1
  20. package/.next/server/app/api/mcp/sign-in/route.js +1 -1
  21. package/.next/server/app/api/mcp/test/route.js +1 -1
  22. package/.next/server/app/index.html +1 -1
  23. package/.next/server/app/index.rsc +4 -4
  24. package/.next/server/app/index.segments/__PAGE__.segment.rsc +4 -4
  25. package/.next/server/app/index.segments/_full.segment.rsc +4 -4
  26. package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  27. package/.next/server/app/login/page_client-reference-manifest.js +1 -1
  28. package/.next/server/app/login.html +1 -1
  29. package/.next/server/app/login.rsc +2 -2
  30. package/.next/server/app/login.segments/_full.segment.rsc +2 -2
  31. package/.next/server/app/login.segments/_tree.segment.rsc +1 -1
  32. package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +2 -2
  33. package/.next/server/app/page.js +22 -22
  34. package/.next/server/app/page.js.nft.json +1 -1
  35. package/.next/server/app/page_client-reference-manifest.js +1 -1
  36. package/.next/server/app/share/[code]/page.js +1 -1
  37. package/.next/server/app/share/[code]/page.js.nft.json +1 -1
  38. package/.next/server/app/share/[code]/page_client-reference-manifest.js +1 -1
  39. package/.next/server/app-paths-manifest.json +1 -1
  40. package/.next/server/chunks/{6367.js → 2728.js} +2 -2
  41. package/.next/server/chunks/3010.js +1 -1
  42. package/.next/server/chunks/5545.js +1 -1
  43. package/.next/server/chunks/6487.js +3 -3
  44. package/.next/server/chunks/8383.js +1 -1
  45. package/.next/server/middleware-build-manifest.js +1 -1
  46. package/.next/server/pages/404.html +1 -1
  47. package/.next/server/pages/500.html +1 -1
  48. package/.next/server/route-cache/APP_PAGE/c6377dd9ce6a1c2cd100eb4344e843eb4639b9ed26f84643f77680e9eb454c4b/$/index.html +1 -0
  49. package/.next/server/route-cache/APP_PAGE/c6377dd9ce6a1c2cd100eb4344e843eb4639b9ed26f84643f77680e9eb454c4b/$/index.meta +1 -0
  50. package/.next/server/route-cache/APP_PAGE/c6377dd9ce6a1c2cd100eb4344e843eb4639b9ed26f84643f77680e9eb454c4b/$/index.rsc +23 -0
  51. package/.next/server/route-cache/APP_PAGE/c6377dd9ce6a1c2cd100eb4344e843eb4639b9ed26f84643f77680e9eb454c4b/$/index.segments/__PAGE__.segment.rsc +27 -0
  52. package/.next/server/route-cache/APP_PAGE/c6377dd9ce6a1c2cd100eb4344e843eb4639b9ed26f84643f77680e9eb454c4b/$/index.segments/_full.segment.rsc +23 -0
  53. package/.next/server/route-cache/APP_PAGE/c6377dd9ce6a1c2cd100eb4344e843eb4639b9ed26f84643f77680e9eb454c4b/$/index.segments/_tree.segment.rsc +8 -0
  54. package/.next/static/chunks/8909-c18f5a2f20e8f798.js +2 -0
  55. package/.next/static/chunks/app/{layout-09edb2b4f71317e3.js → layout-19228ee6a08d83ea.js} +1 -1
  56. package/.next/static/chunks/app/page-18dd62d21c3bda10.js +285 -0
  57. package/.next/static/chunks/app/share/[code]/page-ee5b90b5f0930a77.js +1 -0
  58. package/.next/trace +9 -8
  59. package/.next/trace-build +1 -1
  60. package/package.json +1 -1
  61. package/.next/static/chunks/1798-64b3fd24c6ac6063.js +0 -2
  62. package/.next/static/chunks/app/page-d922df5980ec931c.js +0 -285
  63. package/.next/static/chunks/app/share/[code]/page-ff418745312c304f.js +0 -1
  64. /package/.next/static/{YXWav-5PFkxPJMeIuTSGb → sN1YhVy-LPqPUdH9cLpTi}/_buildManifest.js +0 -0
  65. /package/.next/static/{YXWav-5PFkxPJMeIuTSGb → sN1YhVy-LPqPUdH9cLpTi}/_ssgManifest.js +0 -0
@@ -1,285 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{11340:(e,t,n)=>{Promise.resolve().then(n.bind(n,73549)),Promise.resolve().then(n.bind(n,74251))},55520:e=>{e.exports={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",heading:"ChatMinimap_heading__djZbv",paragraph:"ChatMinimap_paragraph__EqWlO",lock:"ChatMinimap_lock__9WDY5"}},73549:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>my});var r=n(53228),i=n(35456),s=n(41792);let o=null;function a(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,o=null;for(;;){if(n.has(s)){o=n.get(s)??null;break}if(i.has(s))break;i.add(s),e.push(s);let r=t.get(s);if(!r)break;if(r.relation?.kind!=="subagent"){o=r.id;break}s=r.relation.parentSessionId}for(let t of e)n.set(t,o)}return n}(e),n=new Map;for(let t of e)t.relation?.kind!=="subagent"&&n.set(t.id,{root:t,subagents:[],latestModified:t.modified});for(let r of e){if(r.relation?.kind!=="subagent")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 l(e,t){return e.filter(e=>t.has(e.id)).length}function c(e){return`?session=${encodeURIComponent(e)}`}let d="pi-web:last-open-by-workspace";function u(){try{return window.localStorage}catch{return null}}function p(e){let t=e.getItem(d);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function h(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:u();if(t)try{let n=p(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(d):t.setItem(d,JSON.stringify(n))}catch{}}function f(e){return e.projectKey??e.projectRoot??e.cwd}function m(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=f(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 g=/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/,x=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function v(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function b(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function y(e){return"string"==typeof e&&e.length>0&&e.length<=4096&&"__proto__"!==e}let j=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;function k(e){if(null===e)return null;if("string"!=typeof e)return;let t=e.trim();return t?j.test(t)||[...t].length>80?void 0:t:null}let w=new TextEncoder;function S(e){return w.encode(JSON.stringify(e)).length+1}function C(e){let t=1;for(let n of e)t+=S(n);return t}function N(e,t){return e<=1e3&&t<=262144}function E(e){let t=[],n=1;for(let r of e){if(t.length>=1e3)break;let e=S(r);n+e>262144||(t.push(r),n+=e)}return t}function I(e,t){return w.encode(JSON.stringify(e)).length+w.encode(JSON.stringify(t)).length+2}function T(e,t){return e<=1e3&&t<=262144}function $(){return{version:1,revision:0,sessions:{},projects:{}}}function M(e,t,n){let r=x(e,t)?e[t]:void 0;return void 0===n.pinnedAt&&void 0===n.archivedAt?!!r&&(delete e[t],!0):(r?.pinnedAt!==n.pinnedAt||r?.archivedAt!==n.archivedAt)&&(e[t]=n,!0)}function R(e,t){var n;return n=e.projectOrder??[],!(n.length===t.length&&n.every((e,n)=>e===t[n]))&&(0===t.length?delete e.projectOrder:e.projectOrder=t,!0)}function L(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 A(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 P={desktop:{"pinned-header":28,session:28,"pinned-more":26,group:28,"group-more":26,"group-empty":28,spacer:8,"footer-open":28,"footer-archived":28,"archive-group":28},mobile:{"pinned-header":44,session:44,"pinned-more":36,group:44,"group-more":36,"group-empty":44,spacer:8,"footer-open":44,"footer-archived":44,"archive-group":44}},z="pinned";function W(e,t){return Object.hasOwn(e.sessions,t)?e.sessions[t]:void 0}function O(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function D(e,t){return e===t?0:e>t?-1:1}function F(e){return[e.root.id,...e.subagents.map(e=>e.id)]}function B(e,t){return 0!==t.size&&(t.has(e.root.id)||e.subagents.some(e=>t.has(e.id)))}function H(e,t,n){let r=O(W(t,e.root.id)?.archivedAt);if(null===r||B(e,n))return!1;if(e.root.detailsPending)return!0;let i=Date.parse(e.root.modified);return Number.isNaN(i)||r>=i}function U(e,t,n){return null!==O(W(t,e.root.id)?.pinnedAt)&&!H(e,t,n)}function _(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e.charAt(0);let n=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return t.slice(n+1)}function q(e,t){if(Object.hasOwn(t,e.key)){let n=t[e.key];if("boolean"==typeof n)return n}return e.current||e.pinned}function K(e,t){var n;return{running:B(e,t.runningIds),awaiting:!!t.awaitingIds&&B(e,t.awaitingIds),unread:B(e,t.unreadIds),selected:!!(n=t.selectedSessionId)&&(e.root.id===n||e.subagents.some(e=>e.id===n)),transient:!0===e.root.transient}}function V(e){return f(e.root)}function Z(e,t){let n=new Map,r=new Map;return{noteFamily(e){let t=V(e);n.has(t)||n.set(t,e.root.projectRoot??e.root.cwd)},get(i){let s,o=r.get(i);if(o)return o;let a=Object.hasOwn(e.projects,i)?e.projects[i]:void 0,l=null!==t&&t.key===i,c=n.get(i)??(l?t.root:void 0)??a?.root??i,d=((s=e.projectNames)&&x(s,i)?s[i]:void 0)??null,u={key:i,root:c,name:d??_(c),customName:d,pinned:void 0!==a,current:l};return r.set(i,u),u}}}function J(e,t,n,r,i){return{kind:"session",key:`session:${t}:${e.root.id}`,family:e,context:t,project:n,status:K(e,r),archivedAt:i}}function G(e,t,n,r){let i=e.map((e,n)=>{if(n<t)return!1;let i=K(e,r);return i.running||i.unread||i.selected}),s=t+n,o=0,a=e.filter((e,n)=>n<t||!!i[n]||n<s&&(o++,!0)),l=Math.max(t,Math.min(s,e.length));for(let t=0;l<e.length&&t<20;l++)!i[l]&&t++;return{visible:a,revealed:o,nextShown:l-t}}function Y(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 X(e,t){if(!Object.hasOwn(e,t))return e;let n={...e};return delete n[t],n}function Q(e,t,n){let r=e-t,i=n>0;return r>0||i?{hidden:r,canShowLess:i}:null}function ee(e,t,n,r){let i=r-n,s=[];for(let n of a(e.sessions)){if(V(n)!==t||H(n,e.uiState,e.runningIds)||U(n,e.uiState,e.runningIds))continue;let r=K(n,e);if(r.running||r.unread||r.selected||r.transient)continue;let o=Date.parse(n.latestModified);Number.isNaN(o)||o>=i||s.push(n.root.id)}return s}function et(e,t){let n=[],r=0;for(let i of a(e.sessions))if(V(i)===t&&!i.root.transient){if(B(i,e.runningIds)||e.awaitingIds&&B(i,e.awaitingIds)){r++;continue}n.push(i.root.id)}return{ids:n,running:r}}function en(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),o=i["up"===n?s-1:s+1];return o?{anchorKey:o.key,position:"up"===n?"before":"after"}:null}function er(e,t,n,r,i){if(!Number.isInteger(t)||t<0||t>=e.length-1)return null;let s=e[t],o=e[t+1];return"start"===i?s===n?null:s:s>=n&&o<=n+r?null:Math.max(0,s-Math.max(0,(r-(o-s))/2))}let ei="pi-web:sidebar-tab",es="pi-web:sidebar-groups-v2",eo="pi-web:sidebar-groups",ea="pi-web:sidebar-archive-collapsed",el="pi-web:sidebar-pins-collapsed",ec="pi-web:sidebar-files-show-ignored",ed="pi-web:sidebar-files-collapsed",eu="pi-web:sidebar-non-git-cwds",ep=["pi-web:file-explorer:open","pi-web:sidebar-session-pane-height",eo];function eh(){try{return window.localStorage}catch{return null}}function ef(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 em(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eh();if(t)try{let n=Object.entries(ef(e)),r=n.length>300?n.slice(n.length-300):n;t.setItem(es,JSON.stringify(Object.fromEntries(r)))}catch{}}function eg(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eh();if(t)try{t.setItem(ea,JSON.stringify([...new Set(e)].slice(-300)))}catch{}}function ex(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:eh();if(!e)return[];try{let t=e.getItem(eu),n=null===t?[]:JSON.parse(t);if(!Array.isArray(n))return[];return n.filter(e=>"string"==typeof e&&""!==e).slice(-50)}catch{return[]}}async function ev(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}let eb=/ · [0-9a-f]{4}$/;function ey(e){let t=eb.exec(e);return t&&0!==t.index?{base:e.slice(0,t.index),suffix:t[0]}:null}function ej(e,t){return{cwd:e.current&&t?t:e.root,projectKey:e.key,projectRoot:e.root}}function ek(e){let t=e.project;return!t||e.projects.some(e=>e.key===t.key)?[...e.projects]:[t,...e.projects]}function ew(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 eS(e){let t=e.map(e=>({choice:e,name:e.alias??_(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?_(t.slice(0,r)):null}})}function eC(e){return e.isComposing||229===e.keyCode}function eN(e,t){let n=e.activeElement;return!!t&&(!n||n===e.body)&&(t.focus({preventScroll:!0}),!0)}let eE="pi-web:sidebar-files-placement",eI="below";function eT(){try{var e;return e=window.localStorage.getItem(eE),"tab"===e?"tab":eI}catch{return eI}}let e$=null,eM=new Set;function eR(){return null===e$&&(e$=eT()),e$}function eL(){eM.forEach(e=>e())}function eA(e){if(null!==e.key&&e.key!==eE)return;let t=eT();t!==e$&&(e$=t,eL())}function eP(e){return 0===eM.size&&(window.addEventListener("storage",eA),e$=eT()),eM.add(e),()=>{eM.delete(e),0===eM.size&&window.removeEventListener("storage",eA)}}function ez(e){if(e!==eR()){e$=e;try{window.localStorage.setItem(eE,e)}catch{}eL()}}function eW(){return(0,i.useSyncExternalStore)(eP,eR,()=>eI)}var eO=n(74251),eD=n(16988);function eF(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 eB(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function eH(e){let{ariaLabel:t,axis:n="horizontal",cssVariable:r,defaultWidth:s,getDefaultWidth:o,getMaxWidth:a,growthDirection:l,maxWidth:c,minWidth:d,persistClamp:u=!0,storageKey:p,widthRef:h}=e,f=(0,i.useRef)(null),m=(0,i.useRef)(null),g=(0,i.useRef)(!1),x=(0,i.useRef)(s),[v,b]=(0,i.useState)(s),[y,j]=(0,i.useState)(!1),[k,w]=(0,i.useState)(!1);(0,i.useEffect)(()=>{w(!0)},[]);let S=(0,i.useCallback)(()=>Math.min(c,Math.max(d,a())),[a,c,d]),C=(0,i.useCallback)(e=>eF(e,d,S()),[S,d]),N=(0,i.useCallback)(e=>{h.current=e,f.current?.style.setProperty(r,`${e}px`)},[r,h]),E=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{forcePersist:n=!1,persist:r=!0}=t,i=C(e),s=i!==h.current;return N(i),b(i),u?r&&(s||n)&&eB(p,i):n&&(x.current=eF(e,d,c),eB(p,x.current)),i},[N,C,c,d,u,p,h]),I=(0,i.useCallback)(()=>{E(u||m.current?h.current:x.current)},[E,u,h]),T=(0,i.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),$=(0,i.useCallback)(e=>{let t=m.current;if(t&&t.pointerId===e){m.current=null,T(t),j(!1),E(h.current,{forcePersist:u||h.current!==t.startWidth});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[E,u,T,h]),M=(0,i.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=m.current;t&&$(t.pointerId);let r=e.currentTarget;r.focus({preventScroll:!0}),r.setPointerCapture(e.pointerId),m.current={pointerId:e.pointerId,startPosition:"vertical"===n?e.clientY:e.clientX,startWidth:h.current,target:r,previousCursor:document.body.style.cursor,previousUserSelect:document.body.style.userSelect},document.body.style.cursor="vertical"===n?"row-resize":"col-resize",document.body.style.userSelect="none",j(!0)},[n,$,h]),R=(0,i.useCallback)(e=>{let t=m.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void $(e.pointerId);e.preventDefault();let r="right"===l||"down"===l?1:-1,i="vertical"===n?e.clientY:e.clientX,s=C(t.startWidth+(i-t.startPosition)*r);N(s),e.currentTarget.setAttribute("aria-valuenow",String(s)),e.currentTarget.setAttribute("aria-valuetext",`${s} px`)},[N,n,C,$,l]),L=(0,i.useCallback)(e=>{$(e.pointerId)},[$]),A=(0,i.useCallback)(e=>{$(e.pointerId)},[$]),P=(0,i.useCallback)(e=>{$(e.pointerId)},[$]),z=(0,i.useCallback)(()=>{E(o?.()??s,{forcePersist:!0})},[E,s,o]),W=(0,i.useCallback)(e=>{let t=e.shiftKey?32:12,r="right"===l||"down"===l,i="vertical"===n?"ArrowDown":"ArrowRight",s="vertical"===n?"ArrowUp":"ArrowLeft",o=u?h.current:Math.max(h.current,x.current);e.key===(r?i:s)?(e.preventDefault(),E(o+t,{forcePersist:!0})):e.key===(r?s:i)?(e.preventDefault(),E(h.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),E(d,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),E(Math.max(o,S()),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),z())},[n,E,S,l,d,u,z,h]);return(0,i.useEffect)(()=>{if(g.current)return;g.current=!0;let e=function(e){try{let t=window.localStorage.getItem(e);if(null===t)return null;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:null}catch{return null}}(p),t=e??o?.()??s;if(!u){x.current=eF(t,d,c),E(x.current,{persist:!1});return}let n=E(t,{persist:!1});null!==e&&e!==n&&eB(p,n)},[E,s,o,c,d,u,p]),(0,i.useEffect)(()=>{if(!g.current)return;I();let e=()=>{I()};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[I]),(0,i.useEffect)(()=>{if(!y)return;let e=()=>{let e=m.current;e&&$(e.pointerId)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[$,y]),(0,i.useEffect)(()=>()=>{let e=m.current;e&&(m.current=null,T(e))},[T]),{isResizing:y,panelRef:f,reclampWidth:I,resetWidth:z,separatorProps:{"aria-label":t,"aria-orientation":"vertical"===n?"horizontal":"vertical","aria-valuemax":k?S():c,"aria-valuemin":d,"aria-valuenow":v,"aria-valuetext":`${v} px`,onDoubleClick:z,onKeyDown:W,onLostPointerCapture:P,onPointerCancel:A,onPointerDown:M,onPointerMove:R,onPointerUp:L,role:"separator",tabIndex:0},width:v}}function eU(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];(0,i.useEffect)(()=>{if(!t)return;let n=null,r=null,i=!1,s=null,o=()=>{null!==s&&(clearTimeout(s),s=null)},a=()=>{n&&(o(),n.classList.add("scrollbar-visible"))},l=()=>{n&&(o(),s=setTimeout(()=>{s=null,n?.classList.remove("scrollbar-visible")},500))},c=()=>{a(),l()},d=()=>{if(!i){if(!(n=e.current)){r=requestAnimationFrame(d);return}n.addEventListener("pointerenter",a),n.addEventListener("pointerleave",l),n.addEventListener("scroll",c)}};return d(),()=>{i=!0,null!==r&&cancelAnimationFrame(r),n?.removeEventListener("pointerenter",a),n?.removeEventListener("pointerleave",l),n?.removeEventListener("scroll",c),o(),n?.classList.remove("scrollbar-visible")}},[t,e])}let e_="/api/sessions/ui-state";async function eq(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 eK(e){return e instanceof Error?e.message:String(e)}async function eV(e){if(!e.ok)throw Error(await eq(e));let t=await e.json(),n=t&&"object"==typeof t?function(e){if(!v(e)||void 0!==e.version&&1!==e.version||void 0!==e.sessions&&!v(e.sessions)||void 0!==e.projects&&!v(e.projects))return null;let t=$(),n=e.revision;for(let[r,i]of("number"==typeof n&&Number.isSafeInteger(n)&&n>=0&&(t.revision=n),Object.entries(e.sessions??{}))){if(!("string"==typeof r&&g.test(r)))continue;let e=function(e){if(!v(e))return null;let t={};return b(e.pinnedAt)&&(t.pinnedAt=e.pinnedAt),b(e.archivedAt)&&(t.archivedAt=e.archivedAt),void 0===t.pinnedAt&&void 0===t.archivedAt?null:t}(i);e&&(t.sessions[r]=e)}for(let[n,r]of Object.entries(e.projects??{})){if(!y(n))continue;let e=v(r)&&b(r.pinnedAt)&&y(r.root)?{pinnedAt:r.pinnedAt,root:r.root}:null;e&&(t.projects[n]=e)}if(Array.isArray(e.projectOrder)){let n=new Set,r=E(e.projectOrder.filter(e=>!(!y(e)||n.has(e))&&(n.add(e),!0)));r.length>0&&(t.projectOrder=r)}if(v(e.projectNames)){let n={},r=0,i=1;for(let[t,s]of Object.entries(e.projectNames)){let e=k(s);if(!y(t)||"string"!=typeof e)continue;let o=I(t,e);T(r+1,i+o)&&(n[t]=e,r++,i+=o)}r>0&&(t.projectNames=n)}return t}(t.state):null;if(!n)throw Error("Invalid session UI state response");return n}function eZ(){let[e,t]=(0,i.useState)(null),n=(0,i.useRef)(null),r=(0,i.useCallback)(()=>{null!==n.current&&(clearTimeout(n.current),n.current=null)},[]),s=(0,i.useCallback)(()=>{r(),t(null)},[r]),o=(0,i.useCallback)(e=>{(r(),function(){try{return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}catch{return!1}}())?t(null):(t(e),n.current=setTimeout(()=>{n.current=null,t(null)},300))},[r]);return(0,i.useEffect)(()=>r,[r]),{phase:e,start:o,end:s}}var eJ=n(57969);let eG={overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},eY={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},eX={padding:"6px 16px",borderRadius:6,fontSize:13},eQ={...eX,border:0,background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600},e0={...eX,border:"1px solid var(--border)",background:"none",color:"var(--text-muted)"};async function e1(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);return r}async function e2(e,t){let n=await fetch("/api/cwd/browse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e,name:t})}),r=await n.json();if(!n.ok||r.error||!r.path)throw Error(r.error??`HTTP ${n.status}`);return r.path}function e4(){return(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function e8(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,r.jsx)("path",{d:"M2 9h12"}),(0,r.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function e5(e){let{onCancel:t,onSelect:n,initialPath:s,busy:o=!1,error:a}=e,{t:l}=(0,eO.s)(),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(""),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(s??""),[x,v]=(0,i.useState)([]),[b,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(null),[w,S]=(0,i.useState)(!0),[C,N]=(0,i.useState)(!1),[E,I]=(0,i.useState)(""),[T,$]=(0,i.useState)(null),[M,R]=(0,i.useState)(!1),L=(0,i.useCallback)(async e=>{S(!0),k(null);try{let t=await e1(e),n=t.path??e??"/";p(n),f(t.parentPath??null),g(n),v(t.directories??[]),y(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{d(document.body),L(s||void 0)},[s,L]);let A=()=>{M||(N(!1),I(""),$(null))},P=async()=>{let e=E.trim();if(u&&e&&!M){R(!0),$(null);try{let t=await e2(u,e);N(!1),I(""),await L(t)}catch(e){$(e instanceof Error?e.message:String(e))}finally{R(!1)}}},z=m.trim()!==u,W=!!u&&!z&&!o,O=W&&!w,D=!!h||/^[a-zA-Z]:[\\/]?$/.test(u);return c?(0,eJ.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":l("directoryPicker.selectDirectory"),onClick:e=>{e.target!==e.currentTarget||o||t()},onKeyDown:e=>{"Escape"!==e.key||o||t()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{...eG,position:"relative",width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:l("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:t,disabled:o,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:o?"default":"pointer",opacity:o?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=m.trim();t&&L(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void L(h??void 0),disabled:w||!D,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:D?"pointer":"default",opacity:D?1:.45},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:l("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:m,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),k(null)},style:{...eY,minWidth:0,flex:1}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:w||!m.trim(),title:l("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:w||!m.trim()?"default":"pointer",opacity:w||!m.trim()?.6:1},children:l("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[w?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.loadingDirectories")}):null!==b?(0,r.jsx)(r.Fragment,{children:b.length>0?b.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void L(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(e8,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void L(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(e4,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.noSubdirectories")}),(j||a)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:j??a})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>{N(!0),$(null)},disabled:!O,style:{...e0,marginRight:"auto",opacity:O?1:.6,cursor:O?"pointer":"default"},children:l("directoryPicker.newDirectory")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:t,disabled:o,style:{...e0,cursor:o?"default":"pointer"},children:l("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>n(u),disabled:!W,title:l(z?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{...eQ,opacity:W?1:.6,cursor:W?"pointer":"default"},children:l(o?"i18n.checking":"directoryPicker.selectThisFolder")})]}),C&&(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:12,background:"rgba(0,0,0,0.35)"},onClick:e=>{e.target===e.currentTarget&&A()},onKeyDown:e=>{e.stopPropagation(),"Escape"===e.key&&A()},children:(0,r.jsxs)("form",{role:"dialog","aria-modal":"true","aria-label":l("directoryPicker.createDirectory"),onSubmit:e=>{e.preventDefault(),P()},style:{...eG,width:400,maxWidth:"100%"},children:[(0,r.jsx)("div",{style:{padding:"12px 18px",borderBottom:"1px solid var(--border)",color:"var(--text)",fontSize:15,fontWeight:700},children:l("directoryPicker.createDirectory")}),(0,r.jsxs)("div",{style:{padding:"12px 18px"},children:[(0,r.jsx)("label",{htmlFor:"new-directory-name",style:{display:"block",marginBottom:6,color:"var(--text-muted)",fontSize:11},children:l("directoryPicker.directoryName")}),(0,r.jsx)("input",{id:"new-directory-name",value:E,autoFocus:!0,autoComplete:"off",spellCheck:!1,placeholder:l("directoryPicker.directoryNamePlaceholder"),onChange:e=>{I(e.target.value),$(null)},disabled:M,className:"directory-picker-path",style:{...eY,width:"100%",boxSizing:"border-box"}}),T&&(0,r.jsx)("div",{style:{marginTop:7,color:"#dc2626",fontSize:11,lineHeight:1.35},children:T}),(0,r.jsxs)("div",{style:{display:"flex",gap:6,marginTop:10},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:M||!E.trim(),style:{...eQ,flex:1,opacity:M?.65:1,cursor:M||!E.trim()?"default":"pointer"},children:l(M?"directoryPicker.creating":"directoryPicker.create")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:A,disabled:M,style:{...e0,flex:1,cursor:M?"default":"pointer"},children:l("i18n.cancel")})]})]})]})})]})}),c):null}function e6(e){let{onClick:t,title:n}=e;return(0,r.jsx)("button",{type:"button",onClick:t,title:n,"aria-label":n,style:{width:24,height:24,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"none",borderRadius:4,background:"none",color:"var(--text-dim)",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m6 6 12 12"}),(0,r.jsx)("path",{d:"m18 6-12 12"})]})})}var e3=n(30121),e9=n(23573);function e7(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 te(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function tt(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 tn(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function tr(e,t,n,r){return new Promise((i,s)=>{let o=new FormData;t.forEach(e=>o.append("files",e,e.name));let a=new XMLHttpRequest;a.open("POST",`/api/files/${(0,e9.HG)(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(o)})}function ti(e){return Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)}function ts(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 to=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 ta(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 tl(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=(0,e9.HG)(e),r=await fetch(`/api/files/${n}?type=list${t?"&hidden=1":""}`);if(!r.ok)throw await ta(r,"Failed to load files");return((await r.json()).entries??[]).map(t=>({name:t.name,fullPath:(0,e9.e_)(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 tc(e,t){let n=await fetch(`/api/files/${(0,e9.HG)(e)}?type=allow-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:t})});if(!n.ok)throw await ta(n,"Failed to allow the linked folder")}async function td(e){let t=new URLSearchParams({cwd:e}),n=await fetch(`/api/git/status?${t.toString()}`);if(!n.ok)throw Error(`Failed to load Git status (HTTP ${n.status})`);return n.json()}let tu={modified:"files.modified",added:"files.added",deleted:"files.deleted",renamed:"files.renamed",untracked:"files.untracked",conflict:"files.conflict"},tp={modified:"#d6a84b",added:"#4ade80",deleted:"#f87171",renamed:"#60a5fa",untracked:"#4ade80",conflict:"#f87171"};function th(e){let{status:t,t:n}=e;return(0,r.jsx)("span",{title:n(tu[t.status]),"aria-label":n(tu[t.status]),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:tp[t.status],fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600},children:t.code})}function tf(e){let{size:t=11}=e;return(0,r.jsxs)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function tm(e){let{size:t=11}=e;return(0,r.jsxs)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M15 3h6v6"}),(0,r.jsx)("path",{d:"M10 14 21 3"}),(0,r.jsx)("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]})}let tg={ignored:"files.hiddenIgnored",excluded:"files.hiddenExcluded"};function tx(e){let{node:t,depth:n,cwd:s,onOpenFile:o,onAtMention:a,expandedPaths:l,onToggleExpanded:c,refreshToken:d,highlightedPaths:u,gitStatusByPath:p,changedDirectoryPaths:h,showHidden:f=!1,parentHidden:m,dropTargetPath:g,onDropFiles:x,onDropTargetChange:v,t:b}=e,y=l.has(t.fullPath),j=t.hidden??m,k=t.isDir&&g===t.fullPath,w=u.has(t.fullPath),S=(0,e9.A0)(t.fullPath),C=p.get(S),N=t.isDir&&(void 0!==C||h.has(S)),[E,I]=(0,i.useState)(t.children??[]),[T,$]=(0,i.useState)(t.loaded??!1),[M,R]=(0,i.useState)(!1),[L,A]=(0,i.useState)(null),[P,z]=(0,i.useState)(!1),[W,O]=(0,i.useState)(null),[D,F]=(0,i.useState)(!1),[B,H]=(0,i.useState)(null),U=t.outsideLinkTarget&&t.outsideLinkTarget!==W?t.outsideLinkTarget:null;(0,i.useEffect)(()=>{O(null),H(null)},[t.outsideLinkTarget]);let _=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!T||e){R(!0),A(null);try{let e=await tl(t.fullPath,f);I(e),$(!0)}catch(e){A(e instanceof Error?e.message:String(e))}finally{R(!1)}}},[T,t.fullPath,f]),q=(0,i.useRef)(f);(0,i.useEffect)(()=>{q.current===f||(q.current=f,T&&(y&&!U?_(!0):$(!1)))},[f]),(0,i.useEffect)(()=>{t.isDir&&y&&!T&&!U&&_()},[]),(0,i.useEffect)(()=>{void 0!==d&&T&&!U&&(y?_(!0):$(!1))},[d]);let K=(0,i.useCallback)(()=>{if(t.isDir){let e=!y;c(t.fullPath,e),!e||T||U||_()}else o(t.fullPath,t.name)},[t.isDir,t.fullPath,t.name,T,y,U,_,o,c]),V=(0,i.useCallback)(async e=>{if((e.stopPropagation(),U)&&(!t.outsideLinkEncloses||window.confirm(b("files.allowEnclosingLinkConfirm",{target:U})))){F(!0),H(null);try{await tc(t.fullPath,U),O(U),await _(!0)}catch(e){H(e instanceof Error?e.message:String(e))}finally{F(!1)}}},[t.fullPath,t.outsideLinkEncloses,U,_,b]);return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{onClick:K,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,ts(e.dataTransfer)))}:void 0,style:{position:"relative",display:"flex",alignItems:"center",gap:4,paddingLeft:8+14*n,paddingRight:8,height:24,cursor:"pointer",background:k?"color-mix(in srgb, var(--accent) 16%, transparent)":P?"var(--bg-hover)":"transparent",outline:k?"1px dashed var(--accent)":"none",outlineOffset:-1,borderRadius:4,userSelect:"none"},children:[t.isDir&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:y?"rotate(90deg)":"none",transition:"transform 0.1s"},children:(0,r.jsx)("polyline",{points:"3 2 7 5 3 8"})}),!t.isDir&&(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",opacity:j?.55:1},children:t.isDir?(0,r.jsx)(e3.sj,{size:14,open:y}):(0,e3.I3)(t.name,14)}),(0,r.jsx)("span",{"data-hidden-reason":j,style:{fontSize:12,color:j?"var(--text-muted)":"var(--text)",opacity:j?.55:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},title:j?`${t.fullPath}
2
- ${b(tg[j])}`:t.fullPath,children:t.name}),!P&&U&&(0,r.jsx)("span",{title:b("files.outsideLink",{target:U}),"aria-label":b("files.outsideLink",{target:U}),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)"},children:(0,r.jsx)(tm,{})}),w&&(0,r.jsx)("span",{title:b("files.newlyUploaded"),"aria-label":b("files.newlyUploaded"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#3b82f6"}})}),!P&&!t.isDir&&C&&(0,r.jsx)(th,{status:C,t:b}),!P&&N&&(0,r.jsx)("span",{title:b("files.containsChangedFiles"),"aria-label":b("files.containsChangedFiles"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#d6a84b"}})}),M&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",children:(0,r.jsx)("path",{d:"M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4"})}),a&&P&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),a((0,e9.qP)(t.fullPath,s),t.isDir)},title:b("files.insertPath"),style:{position:"absolute",right:t.isDir?4:28,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(tf,{}),b("files.mention")]}),P&&!t.isDir&&(0,r.jsx)("a",{href:`/api/files/${(0,e9.HG)(t.fullPath)}?type=download`,download:!0,onClick:e=>e.stopPropagation(),title:b("files.download"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 5px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap",textDecoration:"none"},children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})]}),t.isDir&&y&&U&&(0,r.jsxs)("div",{style:{paddingLeft:8+(n+1)*14,paddingRight:8,paddingTop:3,paddingBottom:5,display:"flex",flexDirection:"column",alignItems:"flex-start",gap:4,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{wordBreak:"break-all"},children:b("files.outsideLink",{target:U})}),t.outsideLinkEncloses&&(0,r.jsx)("span",{style:{color:"#f59e0b"},children:b("files.outsideLinkEncloses")}),(0,r.jsx)("button",{type:"button",onClick:V,disabled:D,title:b("files.allowOutsideLinkTitle",{target:U}),style:{height:20,padding:"0 8px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:D?"default":"pointer",opacity:D?.6:1,fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:b("files.allowOutsideLink")}),B&&(0,r.jsx)("span",{role:"alert",style:{color:"#f87171",wordBreak:"break-word"},children:B})]}),t.isDir&&y&&!U&&(0,r.jsxs)("div",{children:[E.map(e=>(0,r.jsx)(tx,{node:e,depth:n+1,cwd:s,onOpenFile:o,onAtMention:a,expandedPaths:l,onToggleExpanded:c,refreshToken:d,highlightedPaths:u,gitStatusByPath:p,changedDirectoryPaths:h,showHidden:f,parentHidden:j,dropTargetPath:g,onDropFiles:x,onDropTargetChange:v,t:b},e.fullPath)),0===E.length&&T&&!L&&(0,r.jsx)("div",{style:{paddingLeft:8+(n+1)*14,fontSize:11,color:"var(--text-dim)",height:22,display:"flex",alignItems:"center"},children:"empty"}),L&&(0,r.jsx)("div",{role:"alert",style:{paddingLeft:8+(n+1)*14,paddingRight:8,paddingTop:3,paddingBottom:3,fontSize:11,color:"#f87171",wordBreak:"break-word"},children:L})]})]})}function tv(e){let{status:t,cwd:n,onOpenFile:s,onAtMention:o,checked:a,onToggleSelected:l,t:c}=e,[d,u]=(0,i.useState)(!1),p=(0,e9.WP)(t.filePath),h=(0,e9.qP)(t.filePath,n),f=h.lastIndexOf("/"),m=f>=0?h.slice(0,f+1):"",g=f>=0?h.slice(f+1):h;return(0,r.jsxs)("div",{onClick:()=>s(t.filePath,p,{modeHint:"diff"}),onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),title:t.filePath,style:{display:"flex",alignItems:"center",gap:6,paddingLeft:l?6:10,paddingRight:8,height:24,cursor:"pointer",background:d?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none",position:"relative"},children:[l&&(0,r.jsx)("input",{type:"checkbox",checked:a,onClick:e=>e.stopPropagation(),onChange:e=>l(e.target.checked),title:c("files.commitToggleFile"),"aria-label":c("files.commitToggleFile"),style:{flexShrink:0,width:13,height:13,margin:0,accentColor:"var(--accent)",cursor:"pointer"}}),(0,r.jsx)(th,{status:t,t:c}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",opacity:.85},children:(0,e3.I3)(p,13)}),(0,r.jsxs)("span",{title:t.filePath,style:{fontSize:12,color:"var(--text)",display:"flex",alignItems:"center",minWidth:0,flex:1},children:[m&&(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:"0 1 auto",minWidth:0,color:"var(--text-dim)"},children:m}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:0,maxWidth:"100%"},children:g})]}),o&&d&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),o(h,!1)},title:c("files.insertPath"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(tf,{}),c("files.mention")]})]})}let tb=(0,i.forwardRef)(function(e,t){let{cwd:n,onOpenFile:s,refreshKey:o,onAtMention:a,onAtMentions:l,onUploadBusyChange:c,changesCollapsed:d,onChangesCountChange:u,fileSearchOpen:p=!1,onFileSearchOpenChange:h,showHidden:f=!1}=e,{t:m}=(0,eO.s)(),[g,x]=(0,i.useState)([]),[v,b]=(0,i.useState)(!0),[y,j]=(0,i.useState)(null),[k,w]=(0,i.useState)(new Set),[S,C]=(0,i.useState)(0),[N,E]=(0,i.useState)(new Set),[I,T]=(0,i.useState)([]),[$,M]=(0,i.useState)({additions:0,deletions:0}),[R,L]=(0,i.useState)(!1),[A,P]=(0,i.useState)(""),[z,W]=(0,i.useState)(!1),[O,D]=(0,i.useState)(!1),[F,B]=(0,i.useState)(null),[H,U]=(0,i.useState)(null),[_,q]=(0,i.useState)(new Set),[K,V]=(0,i.useState)("idle"),[Z,J]=(0,i.useState)(0),[G,Y]=(0,i.useState)(null),[X,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(null),[en,er]=(0,i.useState)(""),[ei,es]=(0,i.useState)([]),[eo,ea]=(0,i.useState)(!1),[el,ec]=(0,i.useState)(!1),[ed,eu]=(0,i.useState)(new Set),ep=(0,i.useRef)(null),[eh,ef]=(0,i.useState)(!1),[em,eg]=(0,i.useState)(null),ex=(0,i.useRef)(0),ev=(0,i.useRef)(null),eb=(0,i.useRef)(k),ey=(0,i.useRef)(null),ej=`${o??0}:${S}`,ek="idle"!==K,ew=en.trim().length>0;(0,i.useEffect)(()=>{if(!p)return;let e=en.trim();if(!e){es([]),ea(!1),ec(!1);return}let t=new AbortController;ea(!0),ec(!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=>es((e.matches??[]).filter(e=>!e.isDir).map(e=>e.path))).catch(()=>{t.signal.aborted||(es([]),ec(!0))}).finally(()=>{t.signal.aborted||ea(!1)})},150);return()=>{clearTimeout(r),t.abort()}},[n,p,en]),(0,i.useEffect)(()=>{p&&ep.current?.focus()},[p]),(0,i.useEffect)(()=>{if(0===ei.length)return;let e=new Set;for(let t of ei){let r=t.split("/"),i="";for(let t=0;t<r.length-1;t++)i=i?`${i}/${r[t]}`:r[t],e.add((0,e9.e_)(n,i))}eu(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,ei]);let eS=(0,i.useMemo)(()=>{let e=t=>({name:t.name,fullPath:(0,e9.e_)(n,t.path),isDir:t.isDir,size:0,children:t.children.map(e),loaded:!0});return(function(e){let t=[],n=new Map;for(let r of e){let e=r.split("/"),i=t,s="";for(let t=0;t<e.length;t++){s=s?`${s}/${e[t]}`:e[t];let r=n.get(s);r||(r={name:e[t],path:s,isDir:t<e.length-1,children:[]},n.set(s,r),i.push(r)),i=r.children}}let r=e=>{e.sort((e,t)=>e.isDir!==t.isDir?e.isDir?-1:1:e.name.localeCompare(t.name)),e.forEach(e=>r(e.children))};return r(t),t})(ei).map(e)},[n,ei]),eC=(0,i.useMemo)(()=>new Map(I.map(e=>[(0,e9.A0)(e.filePath),e])),[I]),eN=(0,i.useMemo)(()=>{let e=new Set,t=(0,e9.A0)(n).replace(/\/$/,"");for(let n of I){let r=(0,e9.gX)((0,e9.A0)(n.filePath));for(;(r===t||r.startsWith(`${t}/`))&&(e.add(r),r!==t);){let e=(0,e9.gX)(r);if(e===r)break;r=e}}return e},[n,I]),eE=(0,i.useCallback)((e,t)=>{w(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},[]),eI=(0,i.useCallback)((e,t)=>{let n=e.uploaded??[];Q({directory:t,uploaded:n,skipped:e.skipped??[],errors:e.errors??[]}),n.length>0&&(E(new Set(n.map(e=>(0,e9.e_)(t,e)))),C(e=>e+1))},[]),eT=(0,i.useCallback)(async(e,t,n)=>{et(null),Y(null),J(0),V("uploading");try{let{status:r,data:i}=await tr(n,e,t,J);if(409===r&&i.conflicts?.length)return void et({directory:n,files:e,conflicts:i.conflicts,nonReplaceable:i.nonReplaceable??[]});if(r<200||r>=300)throw Error(i.error??`Upload failed (HTTP ${r})`);J(100),eI(i,n)}catch(e){Y(e instanceof Error?e.message:String(e))}finally{V("idle")}},[eI]),e$=(0,i.useCallback)(async(e,t)=>{if(0!==e.length&&!ek){Q(null),E(new Set),et(null),Y(null),J(0),V("checking");try{let n=await fetch(`/api/files/${(0,e9.HG)(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 et({directory:t,files:e,conflicts:r.conflicts,nonReplaceable:r.nonReplaceable??[]});await eT(e,"error",t)}catch(e){Y(e instanceof Error?e.message:String(e))}finally{V("idle")}}},[eT,ek]),eM=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",e$(t,n)},[n,e$]);(0,i.useImperativeHandle)(t,()=>({openUploadPicker(){ek||ey.current?.click()}}),[ek]);let eR=(0,i.useCallback)(()=>{ex.current=0,ef(!1),eg(null)},[]),eL=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),ex.current+=1,ef(!0))},[]),eA=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.dataTransfer.dropEffect="copy",eg(e=>null===e?e:null))},[]),eP=(0,i.useCallback)(()=>{ex.current<=0||(ex.current-=1,0===ex.current&&(ex.current=0,ef(!1),eg(null)))},[]),ez=(0,i.useCallback)((e,t)=>{eR();let n=t.flatMap(e=>"file"===e.kind?[e.file]:[]),r=t.flatMap(e=>"folder"===e.kind?[e.name]:[]);e$(n,e).then(()=>{if(0===r.length)return;let e=m("chat.dropFoldersUnsupported",{names:r.join(", ")});Y(t=>t&&n.length>0?t:e)})},[e$,eR,m]),eW=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.stopPropagation(),ez(em??n,ts(e.dataTransfer)))},[n,em,ez]),eD=(0,i.useCallback)(e=>{eg(t=>t===e?t:e)},[]);(0,i.useEffect)(()=>{c?.(ek)},[c,ek]),(0,i.useEffect)(()=>()=>c?.(!1),[c]),(0,i.useEffect)(()=>{eb.current=k},[k]),(0,i.useEffect)(()=>()=>{null!==ev.current&&to.save(ev.current,eb.current)},[]),(0,i.useEffect)(()=>{let e=ev.current,t=e!==n;if(ev.current=n,t){null!==e&&to.save(e,eb.current);let t=to.restore(n);eb.current=t,w(t),E(new Set),Q(null),et(null),Y(null)}b(t),j(null);let r=!1;return tl(n,f).then(e=>{r||x(e)}).catch(e=>{r||j(e instanceof Error?e.message:String(e))}).finally(()=>{r||b(!1)}),()=>{r=!0}},[n,o,S,f]),(0,i.useEffect)(()=>{let e=()=>C(e=>e+1);return window.addEventListener("focus",e),()=>window.removeEventListener("focus",e)},[]),(0,i.useEffect)(()=>{let e=!1;return td(n).then(t=>{e||(T(t.isGitRepository?t.files:[]),M(t.isGitRepository?{additions:t.additions,deletions:t.deletions}:{additions:0,deletions:0}))}).catch(()=>{e||(T([]),M({additions:0,deletions:0}))}),()=>{e=!0}},[n,o,S]),(0,i.useEffect)(()=>{u?.(I.length)},[I,u]);let eF=(0,i.useMemo)(()=>I.filter(e=>!_.has(e.filePath)),[I,_]),eB=(0,i.useCallback)((e,t)=>{q(n=>{let r=new Set(n);return t?r.delete(e):r.add(e),r})},[]),eH=(0,i.useCallback)(async()=>{if(O)return;if(0===eF.length)return void B(m("files.commitNoFilesSelected"));let e=eF.flatMap(e=>e.originalPath?[e.filePath,e.originalPath]:[e.filePath]);D(!0),B(null),U(null);try{let t=await fetch("/api/git/commit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n,paths:e,message:A,push:z})}),r=await t.json();t.ok&&r.ok?(P(""),q(new Set),U({commit:r.commit??"",pushed:!0===r.pushed,pushError:r.pushError}),C(e=>e+1)):B(function(e,t,n){switch(e){case"empty-message":return n("files.commitErrorEmptyMessage");case"no-files":return n("files.commitNoFilesSelected");case"no-repository":return n("files.commitErrorNoRepository");case"outside-repository":return n("files.commitErrorOutside");case"nothing-to-commit":return n("files.commitErrorNothing");default:return t?.trim()||n("files.commitErrorGeneric")}}(r.kind,r.error,m))}catch(e){B(e instanceof Error?e.message:String(e))}finally{D(!1)}},[O,A,z,n,eF,m]),eU=H?(0,r.jsxs)("span",{children:[m("files.commitDone",{sha:H.commit}),H.pushed?` \xb7 ${m("files.commitPushed")}`:"",H.pushError?` \xb7 ${"no-upstream"===H.pushError?m("files.commitPushNoUpstream"):m("files.commitPushFailed",{error:H.pushError})}`:""]}):null,e_=ek||null!==ee||null!==G||null!==X,eq=(0,i.useCallback)(()=>{X&&0!==X.uploaded.length&&l?.(X.uploaded.map(e=>(0,e9.qP)((0,e9.e_)(X.directory,e),n)))},[n,l,X]);return(0,r.jsxs)("div",{style:{minHeight:"100%"},onDragEnter:eL,onDragOver:eA,onDragLeave:eP,onDrop:eW,children:[(0,r.jsx)("input",{ref:ey,type:"file",multiple:!0,hidden:!0,onChange:eM}),e_&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[ek&&(0,r.jsxs)("div",{role:"status","aria-live":"polite","aria-label":"checking"===K?m("files.checking"):m("files.uploading",{progress:Z}),children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,minHeight:14,color:"var(--text-muted)"},children:["checking"===K?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite"},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-5.7-8.4"})}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 16V4"}),(0,r.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,r.jsx)("path",{d:"M5 20h14"})]}),"uploading"===K&&(0,r.jsxs)("span",{style:{fontSize:10},children:[Z,"%"]})]}),"uploading"===K&&(0,r.jsx)("div",{style:{height:3,marginTop:4,overflow:"hidden",borderRadius:2,background:"var(--border)"},children:(0,r.jsx)("div",{style:{width:`${Z}%`,height:"100%",background:"var(--text-muted)",transition:"width 120ms ease"}})})]}),ee&&(0,r.jsxs)("div",{role:"alert",style:{padding:7,border:"1px solid color-mix(in srgb, #f59e0b 55%, var(--border))",borderRadius:4,background:"color-mix(in srgb, #f59e0b 9%, var(--bg-panel))"},children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text)",lineHeight:1.35,overflowWrap:"anywhere"},children:m("files.conflictSummary",{count:ee.conflicts.length,countSuffix:1===ee.conflicts.length?"":"s",files:ee.conflicts.join(", ")})}),ee.nonReplaceable.length>0&&(0,r.jsx)("div",{style:{marginTop:3,fontSize:10,color:"#f59e0b",lineHeight:1.35,overflowWrap:"anywhere"},children:m("files.cannotReplace",{files:ee.nonReplaceable.join(", ")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:7},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void eT(ee.files,"overwrite",ee.directory),style:{height:22,padding:"0 7px",border:"1px solid #ef4444",borderRadius:4,background:"transparent",color:"#ef4444",cursor:"pointer",fontSize:10},children:m("files.replace")}),(0,r.jsx)("button",{type:"button",onClick:()=>void eT(ee.files,"skip",ee.directory),style:{height:22,padding:"0 7px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",fontSize:10},children:m("files.skipExisting")}),(0,r.jsx)("button",{type:"button",onClick:()=>et(null),style:{height:22,padding:"0 7px",border:"none",borderRadius:4,background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:10},children:m("files.cancel")})]})]}),G&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,fontSize:11,lineHeight:1.35,color:"#f87171"},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflowWrap:"anywhere"},children:G}),(0,r.jsx)(e6,{onClick:()=>Y(null),title:m("files.dismissError")})]}),X&&(0,r.jsxs)("div",{"aria-live":"polite",children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:22,fontSize:11},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1,display:"flex",alignItems:"center",gap:8},children:[X.uploaded.length>0&&(0,r.jsxs)("span",{title:`${X.uploaded.length} uploaded`,"aria-label":`${X.uploaded.length} uploaded`,style:{display:"flex",alignItems:"center",gap:3,color:"#22c55e"},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m5 12 4 4L19 6"})}),(0,r.jsx)("span",{children:X.uploaded.length})]}),X.skipped.length>0&&(0,r.jsxs)("span",{title:`${X.skipped.length} skipped`,"aria-label":`${X.skipped.length} skipped`,style:{display:"flex",alignItems:"center",gap:3,color:"var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M8 12h8"})]}),(0,r.jsx)("span",{children:X.skipped.length})]}),X.errors.length>0&&(0,r.jsxs)("span",{title:`${X.errors.length} failed`,"aria-label":`${X.errors.length} failed`,style:{display:"flex",alignItems:"center",gap:3,color:"#f87171"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 3 2.5 20h19L12 3Z"}),(0,r.jsx)("path",{d:"M12 9v4"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{children:X.errors.length})]})]}),X.uploaded.length>0&&l&&(0,r.jsxs)("button",{type:"button",onClick:eq,title:1===X.uploaded.length?m("files.addUploadedFile"):m("files.addAllUploadedFiles"),"aria-label":1===X.uploaded.length?m("files.addUploadedFile"):m("files.addAllUploadedFiles"),style:{height:22,padding:"0 7px",display:"flex",alignItems:"center",justifyContent:"center",gap:4,flexShrink:0,border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(tf,{}),m("files.mention")]}),(0,r.jsx)(e6,{onClick:()=>Q(null),title:m("files.dismissUploadResults")})]}),X.errors.map(e=>(0,r.jsxs)("div",{title:e.error,style:{display:"flex",alignItems:"center",gap:4,marginTop:3,minWidth:0,fontSize:10,color:"#f87171"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 8v5"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.name))]})]}),p&&(0,r.jsxs)("div",{style:{padding:"2px 8px 6px"},children:[(0,r.jsxs)("div",{style:{position:"relative"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]}),(0,r.jsx)("input",{ref:ep,id:"file-search-input",value:en,onChange:e=>er(e.target.value),onKeyDown:e=>{"Escape"===e.key&&h?.(!1)},placeholder:m("sidebar.searchFilesPlaceholder"),"aria-label":m("sidebar.searchFiles"),style:{width:"100%",boxSizing:"border-box",padding:"6px 24px",border:"1px solid var(--border)",borderRadius:8,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}}),en&&(0,r.jsx)("button",{type:"button",onClick:()=>er(""),title:m("sidebar.clearSearch"),"aria-label":m("sidebar.clearSearch"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:18,height:18,padding:0,border:"none",borderRadius:4,background:"none",color:"var(--text-dim)",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]}),ew&&(0,r.jsxs)("div",{style:{paddingTop:3},children:[eo&&(0,r.jsx)("div",{role:"status",style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:m("sidebar.searchingFiles")}),!eo&&el&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 2px",fontSize:10,color:"#f87171"},children:m("i18n.networkError")}),!eo&&!el&&0===ei.length&&(0,r.jsx)("div",{style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:m("sidebar.noMatchingFiles")}),!eo&&!el&&ei.length>0&&(0,r.jsx)("div",{children:eS.map(e=>(0,r.jsx)(tx,{node:e,depth:0,cwd:n,onOpenFile:s,onAtMention:a,expandedPaths:ed,onToggleExpanded:(e,t)=>{eu(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},highlightedPaths:N,gitStatusByPath:eC,changedDirectoryPaths:eN,dropTargetPath:em,onDropFiles:ez,onDropTargetChange:eD,t:m},`${en}:${e.fullPath}`))})]})]}),!d&&(I.length>0||H)&&(0,r.jsxs)("div",{style:{padding:"0 4px 2px"},children:[I.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{"aria-label":m("files.changeStats",{count:I.length,additions:$.additions,deletions:$.deletions}),style:{display:"flex",alignItems:"center",gap:6,height:24,padding:"0 10px",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",flexShrink:0},children:m("files.changedCount",{count:I.length})}),(0,r.jsxs)("span",{style:{color:tp.added,fontFamily:"var(--font-mono)"},children:["+",$.additions]}),(0,r.jsxs)("span",{style:{color:tp.deleted,fontFamily:"var(--font-mono)"},children:["-",$.deletions]}),(0,r.jsx)("span",{style:{flex:1}}),(0,r.jsx)("button",{onClick:()=>{L(e=>!e),B(null),U(null)},disabled:O,style:{height:20,padding:"0 7px",display:"flex",alignItems:"center",gap:4,flexShrink:0,border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--accent)",cursor:O?"default":"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:m("files.commit")})]}),R&&(0,r.jsxs)("div",{style:{padding:"2px 8px 6px",display:"flex",flexDirection:"column",gap:6},children:[(0,r.jsx)("textarea",{value:A,onChange:e=>P(e.target.value),placeholder:m("files.commitMessagePlaceholder"),rows:3,disabled:O,style:{width:"100%",boxSizing:"border-box",resize:"vertical",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,padding:"4px 6px",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.4}}),(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11,color:"var(--text-dim)",cursor:"pointer",userSelect:"none"},children:[(0,r.jsx)("input",{type:"checkbox",checked:z,onChange:e=>W(e.target.checked),disabled:O,style:{accentColor:"var(--accent)"}}),m("files.commitPush")]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("button",{onClick:eH,disabled:O||0===eF.length,style:{height:22,padding:"0 10px",border:"none",borderRadius:4,background:"var(--accent)",color:"var(--accent-contrast)",cursor:O?"default":"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:O?m("files.committing"):m("files.commit")}),(0,r.jsx)("button",{onClick:()=>{L(!1),B(null),U(null)},disabled:O,style:{height:22,padding:"0 10px",border:"1px solid var(--border)",borderRadius:4,background:"transparent",color:"var(--text-muted)",cursor:O?"default":"pointer",fontSize:11,whiteSpace:"nowrap"},children:m("files.commitCancel")}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap"},children:m("files.commitSelectedCount",{count:eF.length})})]}),F&&(0,r.jsx)("div",{role:"alert",style:{fontSize:11,color:"#f87171",whiteSpace:"pre-wrap"},children:F}),eU&&(0,r.jsx)("div",{role:"status",style:{fontSize:11,color:"var(--text-dim)"},children:eU})]}),I.map(e=>(0,r.jsx)(tv,{status:e,cwd:n,onOpenFile:s,onAtMention:a,checked:!_.has(e.filePath),onToggleSelected:t=>eB(e.filePath,t),t:m},e.filePath))]}),0===I.length&&H&&(0,r.jsxs)("div",{role:"status",style:{display:"flex",alignItems:"center",gap:6,margin:"2px 2px 0",padding:"4px 6px",fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0},children:eU}),(0,r.jsx)(e6,{onClick:()=>U(null),title:m("files.commitDismiss")})]})]}),(d||0===I.length)&&(!p||!ew)&&(0,r.jsxs)("div",{style:{padding:"2px 4px"},children:[v?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:"Loading files..."}):y?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"#f87171"},children:y}):g.map(e=>(0,r.jsx)(tx,{node:e,depth:0,cwd:n,onOpenFile:s,onAtMention:a,expandedPaths:k,onToggleExpanded:eE,refreshToken:ej,highlightedPaths:N,gitStatusByPath:eC,changedDirectoryPaths:eN,showHidden:f,dropTargetPath:em,onDropFiles:ez,onDropTargetChange:eD,t:m},e.fullPath)),!v&&!y&&0===g.length&&(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:m("files.noFiles")})]}),eh&&(0,r.jsxs)("div",{role:"status","aria-live":"polite",style:{position:"sticky",bottom:0,zIndex:1,display:"flex",alignItems:"center",gap:6,padding:"6px 8px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)",fontSize:11,color:"var(--accent)",userSelect:"none",pointerEvents:"none"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M12 16V4"}),(0,r.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,r.jsx)("path",{d:"M5 20h14"})]}),m("files.dropToUpload",{directory:em?(0,e9.qP)(em,n)||em:(0,e9.WP)(n)||n})]})]})});var ty=n(86692);let tj="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function tk(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Math.random,r=4*e.length;if(t>=r)return e;let i=Math.floor(t/r*e.length),s="";for(let t=0;t<e.length;t++){let r=e[t];s+=" "===r||t<i?r:tj[Math.floor(n()*tj.length)]}return s}function tw(e){let{onWidthChange:t}=e,{t:n}=(0,eO.s)(),[s,o]=(0,i.useState)(!1),a=(0,i.useRef)(null),l="0.13.0",c="1.2.0",d=function(e){let[t,n]=(0,i.useState)(e),r=(0,i.useRef)(e);return(0,i.useEffect)(()=>{if(r.current===e)return;if(r.current=e,window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return void n(e);let t=4*e.length,i=0,s=0,o=()=>{n(tk(e,i+=1)),i<t&&(s=requestAnimationFrame(o))};return n(tk(e,0)),s=requestAnimationFrame(o),()=>cancelAnimationFrame(s)},[e]),t}(s?`${l??"0.0.0"}p${c??"0.0.0"}`:"Pi Web");return(0,i.useLayoutEffect)(()=>{t?.()},[d.length,t]),(0,i.useEffect)(()=>()=>{a.current&&clearTimeout(a.current)},[]),(0,r.jsx)("button",{type:"button",className:`sidebar-brand${s?" is-version":""}`,"aria-label":n("sidebar.brandLabel",{app:l??"0.0.0",pi:c??"0.0.0"}),onClick:()=>{(a.current&&clearTimeout(a.current),a.current=null,s)?o(!1):(o(!0),a.current=setTimeout(()=>{a.current=null,o(!1)},3e3))},children:d})}var tS=n(55840),tC=n(31516);let tN={desktop:32,mobile:48};function tE(e,t,n,r){return Math.hypot(n-e,r-t)}function tI(e){return e.getClientRects().length>0}function tT(e){let{size:t=13,className:n,label:i,strokeWidth:s=2,children:o}=e;return(0,r.jsx)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:s,strokeLinecap:"round",strokeLinejoin:"round",className:n,...i?{role:"img","aria-label":i}:{"aria-hidden":!0},children:o})}function t$(e){return(0,r.jsx)(tT,{...e,children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})}function tM(e){return(0,r.jsxs)(tT,{...e,children:[(0,r.jsx)("circle",{cx:"5",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"}),(0,r.jsx)("circle",{cx:"19",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"})]})}function tR(e){return(0,r.jsxs)(tT,{...e,children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"5",rx:"1"}),(0,r.jsx)("path",{d:"M5 9v9a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V9"}),(0,r.jsx)("path",{d:"M10 13h4"})]})}function tL(e){return(0,r.jsxs)(tT,{...e,children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}function tA(e){return(0,r.jsxs)(tT,{...e,children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M9 10.8a2 2 0 0 1-1.1 1.8l-1.8.9A2 2 0 0 0 5 15.2V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.8a2 2 0 0 0-1.1-1.8l-1.8-.9a2 2 0 0 1-1.1-1.8V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z"})]})}function tP(e){return(0,r.jsxs)(tT,{...e,children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M15 9.3V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8.5"}),(0,r.jsx)("path",{d:"m2 2 20 20"}),(0,r.jsx)("path",{d:"M9 9v1.8a2 2 0 0 1-1.1 1.8l-1.8.9A2 2 0 0 0 5 15.2V16a1 1 0 0 0 1 1h11"})]})}function tz(e){let{strokeWidth:t,...n}=e;return(0,r.jsx)(tT,{...n,strokeWidth:t,children:(0,r.jsx)("path",{d:"m9 6 6 6-6 6"})})}function tW(e){return(0,r.jsxs)(tT,{...e,children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function tO(e){return(0,r.jsxs)(tT,{...e,children:[(0,r.jsx)("circle",{cx:"6",cy:"5",r:"2.5"}),(0,r.jsx)("circle",{cx:"18",cy:"5",r:"2.5"}),(0,r.jsx)("circle",{cx:"12",cy:"19",r:"2.5"}),(0,r.jsx)("path",{d:"M6 7.5v1.5a3 3 0 0 0 3 3h6a3 3 0 0 0 3-3V7.5"}),(0,r.jsx)("path",{d:"M12 12v4.5"})]})}function tD(e){return(0,r.jsxs)(tT,{...e,children:[(0,r.jsx)("path",{d:"M14 4h6v6"}),(0,r.jsx)("path",{d:"M20 4 11 13"}),(0,r.jsx)("path",{d:"M18 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4"})]})}function tF(e){return(0,r.jsxs)(tT,{...e,children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})}function tB(e){return(0,r.jsx)(tT,{...e,children:(0,r.jsx)("path",{d:"M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"})})}function tH(e){return(0,r.jsx)(tT,{...e,children:(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4.5",fill:"currentColor",stroke:"none"})})}function tU(e){return(0,r.jsx)(tT,{...e,children:(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4.5"})})}function t_(e){return(0,r.jsx)(tT,{...e,children:(0,r.jsx)("path",{d:"M20 6 9 17l-5-5"})})}function tq(e){return(0,r.jsx)(tT,{...e,children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})}function tK(e){return(0,r.jsx)(tT,{...e,children:(0,r.jsx)("path",{d:"M3 8a2 2 0 0 1 2-2h3.4l1.9 1.9H19a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"})})}function tV(e){return(0,r.jsxs)(tT,{...e,children:[(0,r.jsx)("path",{d:"M3 8a2 2 0 0 1 2-2h3.4l1.9 1.9H19a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"}),(0,r.jsx)("path",{d:"M12 11v5M9.5 13.5h5"})]})}function tZ(e){return(0,r.jsxs)(tT,{...e,children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function tJ(e){return(0,r.jsxs)(tT,{...e,children:[(0,r.jsx)("circle",{cx:"5",cy:"6",r:"2.5"}),(0,r.jsx)("circle",{cx:"5",cy:"18",r:"2.5"}),(0,r.jsx)("circle",{cx:"19",cy:"12",r:"2.5"}),(0,r.jsx)("path",{d:"M5 8.5v7"}),(0,r.jsx)("path",{d:"M7.5 6H12a7 7 0 0 1 7 7v.01"}),(0,r.jsx)("path",{d:"M7.5 18H12"})]})}function tG(e){return(0,r.jsxs)(tT,{...e,children:[(0,r.jsx)("path",{d:"M18 8a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Z"}),(0,r.jsx)("path",{d:"M6 21a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Z"}),(0,r.jsx)("path",{d:"M15.5 5.5 8.5 18.5"})]})}function tY(e){return(0,r.jsxs)(tT,{...e,children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})}function tX(e){return(0,r.jsxs)(tT,{...e,children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]})}function tQ(e){return(0,r.jsxs)(tT,{...e,children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("path",{d:"m17 8-5-5-5 5"}),(0,r.jsx)("path",{d:"M12 3v12"})]})}function t0(e){return(0,r.jsxs)(tT,{...e,children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}function t1(e){return(0,r.jsxs)(tT,{...e,children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,r.jsx)("path",{d:"M3 12h6M15 12h6"})]})}function t2(e){return(0,r.jsxs)(tT,{...e,children:[(0,r.jsx)("path",{d:"M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})}function t4(e){return(0,r.jsx)(tT,{...e,children:(0,r.jsx)("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function t8(e){let{className:t,...n}=e;return(0,r.jsx)(tT,{...n,strokeWidth:2.8,className:t?`sidebar-spin ${t}`:"sidebar-spin",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4"})})}function t5(e){let t=(0,tC.d)(e.firstMessage)??e.firstMessage;return e.name||t.slice(0,50)||e.id.slice(0,12)}function t6(e){return e.nativeEvent.isComposing||229===e.keyCode}function t3(e){let{rows:t,layout:n,emptyLabel:s,loading:o,error:a,renamingRootId:l,renamingProjectKey:c,confirmDeleteRootId:d,activeMenuRowKey:u,reveal:p}=e,{t:h}=(0,eO.s)(),f=(0,i.useRef)(e);f.current=e;let m=(0,i.useRef)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(null);eU(g);let[b,y]=(0,i.useState)(0),[j,k]=(0,i.useState)(0),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(()=>Date.now()),E=(0,i.useRef)(null),I=(0,i.useCallback)(()=>{null===E.current&&(E.current=requestAnimationFrame(()=>{E.current=null;let e=g.current;e&&y(e.scrollTop)}))},[]);(0,i.useLayoutEffect)(()=>{let e=g.current;if(!e)return;let t=()=>{let t=`${Math.max(0,e.offsetWidth-e.clientWidth)}px`;e.style.setProperty("--session-tree-scrollbar",t),e.offsetWidth>0&&e.closest(".session-sidebar")?.style.setProperty("--session-tree-scrollbar",t)};if(t(),k(e.clientHeight),y(e.scrollTop),"u"<typeof ResizeObserver)return;let n=new ResizeObserver(()=>{t(),k(e.clientHeight),y(e.scrollTop)});return n.observe(e),()=>n.disconnect()},[]),(0,i.useEffect)(()=>()=>{null!==E.current&&cancelAnimationFrame(E.current)},[]),(0,i.useEffect)(()=>{let e=window.setInterval(()=>N(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let T=(0,i.useCallback)(e=>{let t=e.target instanceof Element?e.target.closest("[data-row-key]"):null;S(t?.getAttribute("data-row-key")??null)},[]),$=(0,i.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||S(null)},[]),M=(0,i.useMemo)(()=>(function(e,t){let n=P[t],r=Array(e.length+1);r[0]=0;for(let t=0;t<e.length;t++)r[t+1]=r[t]+n[e[t].kind];return r})(t,n),[t,n]),R=!!e.onMoveGroup,L=(0,i.useMemo)(()=>{let e={pinned:0,other:0};for(let n of t)"group"===n.kind&&e[n.project.pinned?"pinned":"other"]++;return e},[t]),A=function(e){let{rows:t,offsets:n,enabled:r}=e,s=(0,i.useRef)(e);s.current=e;let o=(0,i.useMemo)(()=>(function(e,t){let n=[],r=0;for(;r<e.length;){var i;let s=e[r];if("group"!==s.kind){r++;continue}let o=r;for(;o>0&&"spacer"===e[o-1].kind;)o--;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 l=a;for(;l<e.length&&"spacer"===e[l].kind;)l++;n.push({key:s.project.key,pinned:s.project.pinned,top:t[r],bottom:t[a],gapAbove:t[r]-t[o],gapBelow:t[l]-t[a]}),r=a}return n})(t,n),[t,n]),a=(0,i.useRef)(o);a.current=o;let l=(0,i.useRef)(null),c=(0,i.useRef)(0),[d,u]=(0,i.useState)(null),p=(0,i.useMemo)(()=>{let e=e=>{u("armed"===e.phase||"dragging"===e.phase?{projectKey:e.projectKey,phase:e.phase,drop:e.drop}:null)},t=e=>{let t=s.current.innerRef.current;return t?function(e,t,n){let r=e.find(e=>e.key===t);if(!r)return null;let i=e.filter(e=>e.pinned===r.pinned),s=i.indexOf(r),o=i.filter(e=>e!==r);if(0===o.length)return null;let a=o.filter(e=>(e.top+e.bottom)/2<n).length;if(a===s)return null;let l=o[o.length-1],c=Math.max(3,a<o.length?o[a].top-o[a].gapAbove/2:l.bottom+l.gapBelow/2);return a>0?{anchorKey:o[a-1].key,position:"after",lineY:c}:{anchorKey:o[0].key,position:"before",lineY:c}}(a.current,e.projectKey,e.clientY-t.getBoundingClientRect().top):null},n=()=>{let e=l.current,t=s.current.ghostRef.current,n=s.current.treeRef.current,r=s.current.innerRef.current,i=s.current.scrollRef.current;if(!e?.ghost||!t||!n||!i)return;let o=n.getBoundingClientRect().top,a=i.getBoundingClientRect(),c=t.offsetHeight,d=function(e){let{pointerY:t,lineY:n,ghostHeight:r,pointerGap:i,lineGap:s,minTop:o,maxTop:a}=e,l=Math.max(o,a),c=t-i-r,d=null!==n&&n>=o&&n<=l+r?n:null,u=e=>e>=o&&e<=l,p=e=>null!==d&&e>d-s-r&&e<d+s,h=null===d?[c,o,t+i,l]:[c,d-s-r,o,t+i,d+s,l],f=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 f(e=>u(e)&&!(e>c&&e<t+i)&&!p(e))??f(e=>u(e)&&!p(e))??Math.min(l,Math.max(o,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:a.top,maxTop:a.bottom-c});t.style.top=`${d-o}px`,t.style.left=`${e.ghost.left}px`},r=e=>{null!==e.timer&&window.clearTimeout(e.timer),null!==e.frame&&cancelAnimationFrame(e.frame),e.timer=null,e.frame=null,s.current.scrollRef.current?.removeEventListener("scroll",p);try{e.element.hasPointerCapture(e.pointerId)&&e.element.releasePointerCapture(e.pointerId)}catch{}},i=()=>{let e=l.current;e&&(l.current=null,r(e),window.removeEventListener("pointermove",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",j,!0),window.removeEventListener("blur",k),document.removeEventListener("visibilitychange",w),u(null))},o=()=>{let e=l.current;if(e){if("armed"!==e.phase&&"dragging"!==e.phase){"pending"===e.phase&&i();return}e.phase="cancelled",e.drop=null,r(e),u(null)}},d=function(){var r;let i=arguments.length>0&&void 0!==arguments[0]&&arguments[0],a=l.current;if(!a||"dragging"!==a.phase)return;let c=s.current.scrollRef.current;if(!c||!tI(c))return void o();let d=t(a),u=i||d!==(r=a.drop)&&(null===d||null===r||d.anchorKey!==r.anchorKey||d.position!==r.position||d.lineY!==r.lineY);a.drop=d,n(),u&&e(a)};function p(){d()}let h=()=>{let e=l.current;if(!e||"dragging"!==e.phase)return;e.frame=null;let t=s.current.scrollRef.current;if(!t||!tI(t))return void o();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,tN[s.current.layout]);if(0!==r){let n=Math.min(Math.max(0,(s.current.offsets[s.current.offsets.length-1]??0)-t.clientHeight),Math.max(0,t.scrollTop+r));n!==t.scrollTop&&(t.scrollTop=n,e.expectedScrollTop=t.scrollTop,d())}l.current===e&&"dragging"===e.phase&&(e.frame=requestAnimationFrame(h))},f=e=>{let t=s.current.scrollRef.current,n=s.current.treeRef.current;if(!t||!n||!tI(t)||!e.element.isConnected)return void o();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),d(!0)},m=()=>{let t=l.current;t&&"pending"===t.phase&&(t.timer=null,t.phase="armed",t.armX=t.clientX,t.armY=t.clientY,t.expectedScrollTop=s.current.scrollRef.current?.scrollTop??0,e(t))};function g(e){let t=l.current;if(!t||e.pointerId!==t.pointerId)return;if("mouse"===t.pointerType&&0===e.buttons)return void i();t.clientX=e.clientX,t.clientY=e.clientY;let n=tE(t.startX,t.startY,e.clientX,e.clientY);switch(t.phase){case"pending":"mouse"===t.pointerType?n>=4&&f(t):n>8&&i();break;case"armed":tE(t.armX,t.armY,e.clientX,e.clientY)>=4&&f(t);break;case"dragging":d()}}function x(e){let n=l.current;if(n&&e.pointerId===n.pointerId){if("dragging"===n.phase){n.clientX=e.clientX,n.clientY=e.clientY;let r=t(n);r&&s.current.onMove(n.projectKey,r.anchorKey,r.position)}"pending"!==n.phase&&(c.current=e.timeStamp+600),i()}}function v(e){l.current&&e.pointerId===l.current.pointerId&&i()}function b(e){l.current&&e.pointerId!==l.current.pointerId&&o()}function y(e){let t=l.current;t&&"Escape"===e.key&&("armed"===t.phase||"dragging"===t.phase)&&(e.preventDefault(),e.stopPropagation(),o())}function j(e){let t=l.current;if(t){if("pending"===t.phase)return void i();e.preventDefault(),e.stopPropagation()}}function k(){i()}function w(){"hidden"===document.visibilityState&&i()}return{handlers:{onPointerDown(e,t){if(!s.current.enabled||l.current||!e.isPrimary||0!==e.button||e.ctrlKey||e.target instanceof Element&&e.target.closest(".session-tree-group-actions"))return;let n=e.currentTarget,r={pointerId:e.pointerId,pointerType:e.pointerType,projectKey:t,element:n,startX:e.clientX,startY:e.clientY,armX:e.clientX,armY:e.clientY,clientX:e.clientX,clientY:e.clientY,phase:"pending",timer:null,frame:null,expectedScrollTop:0,drop:null,ghost:null};l.current=r,window.addEventListener("pointermove",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",j,!0),window.addEventListener("blur",k),document.addEventListener("visibilitychange",w),"mouse"!==e.pointerType&&(r.timer=window.setTimeout(m,350))},onTouchMove(e){let t=l.current;if(!t||"armed"!==t.phase&&"dragging"!==t.phase)return;if(e.cancelable)return void e.preventDefault();let n=s.current.scrollRef.current;n&&n.scrollTop!==t.expectedScrollTop&&i()}},cancel:o,teardown:i,updateDrag:d,placeGhost:n}},[]);(0,i.useLayoutEffect)(()=>{let e=l.current;e&&("armed"===e.phase||"dragging"===e.phase)&&(t.some(t=>"group"===t.kind&&t.project.key===e.projectKey)?p.updateDrag():p.cancel())},[t,n,p]),(0,i.useEffect)(()=>{r||p.cancel()},[r,p]);let h=d?.phase==="dragging";(0,i.useLayoutEffect)(()=>{h&&p.placeGhost()},[h,p]),(0,i.useEffect)(()=>()=>p.teardown(),[p]);let f=(0,i.useCallback)(e=>{let t=c.current;0===t||(c.current=0,e.timeStamp>t||(e.preventDefault(),e.stopPropagation()))},[]),m=(0,i.useCallback)(()=>{c.current=0},[]);return{view:(0,i.useMemo)(()=>{if(!d)return null;let e="dragging"===d.phase?o.find(e=>e.key===d.projectKey)??null:null;return{...d,source:e}},[d,o]),handlers:p.handlers,onClickCapture:f,onPointerDownCapture:m}}({rows:t,offsets:M,layout:n,enabled:R&&!o,scrollRef:g,innerRef:x,treeRef:m,ghostRef:v,onMove:(e,t,n)=>f.current.onMoveGroup?.(e,t,n)}),W=A.view,O=W?`group:${W.projectKey}`:null,[D,F]=(0,i.useState)(null),B=p&&p.id!==D?p:null,H=B?.rowKey??null,U=(0,i.useMemo)(()=>{let e=[];return t.forEach((t,n)=>{t.key===w||t.key===u||t.key===H||t.key===O||"session"===t.kind&&(t.family.root.id===l||t.family.root.id===d)?e.push(n):"group"===t.kind&&t.project.key===c&&e.push(n)}),e},[t,w,u,H,O,l,c,d]),_=(0,i.useMemo)(()=>o?[]:function(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],s=Math.max(0,e.length-1),o=Number.isFinite(t)?Math.max(0,t):0,a=Number.isFinite(n)&&n>0?n:600,l=Number.isFinite(r)&&r>0?r:0,c=o-l,d=o+a+l,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 f=u,m=[];for(let e=h;e<f;e++)m.push(e);if(0===i.length)return m;let g=i.filter(e=>Number.isInteger(e)&&e>=0&&e<s&&(e<h||e>=f));return 0===g.length?m:[...new Set([...m,...g])].sort((e,t)=>e-t)}(M,b,j,240,U),[o,M,b,j,U]),q=(0,i.useRef)(null),K=(0,i.useRef)(null),V=(0,i.useCallback)((e,t,n,r)=>{let i=document.activeElement===r,s=i&&r.matches(":focus-visible");q.current={rowKey:e,fallbackKey:t===z?"pinned-header":`group:${t}`,focus:i,scroll:"less"===n||s},"more"===n?f.current.onShowMore(t):f.current.onShowLess(t)},[]);(0,i.useLayoutEffect)(()=>{let e=q.current;if(!e)return;q.current=null;let n=g.current,r=t.findIndex(t=>t.key===e.rowKey);if(r<0&&(r=t.findIndex(t=>t.key===e.fallbackKey)),e.scroll&&n&&r>=0){let e=er(M,r,n.scrollTop,n.clientHeight);null!==e&&(n.scrollTop=e),y(n.scrollTop)}e.focus&&(K.current={rowKey:e.rowKey,fallbackKey:e.fallbackKey,tries:0})},[t,M]);let Z=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{if(!B)return;let e=t.findIndex(e=>e.key===B.rowKey),n=function(e,t,n,r){let i=e?.id===t.id?e:{id:t.id,misses:0};if(!(r-t.at<=3e3))return{misses:i,action:"drop"};if(n)return{misses:i,action:"reveal"};let s={id:t.id,misses:i.misses+1};return{misses:s,action:s.misses>=3?"drop":"wait"}}(Z.current,B,e>=0,Date.now());if(Z.current=n.misses,"wait"!==n.action){if("reveal"===n.action){let t=g.current;if(t&&t.getClientRects().length>0){let n=er(M,e,t.scrollTop,t.clientHeight,B.block);null!==n&&(t.scrollTop=n),y(t.scrollTop)}B.takeFocusFrom&&(K.current={rowKey:B.rowKey,fallbackKey:B.rowKey,tries:0,takeFocusFrom:B.takeFocusFrom})}F(B.id),f.current.onRevealHandled?.(B.id)}},[B,t,M]),(0,i.useLayoutEffect)(()=>{let e=K.current;if(!e)return;let t=document.activeElement;if(t&&t!==document.body&&document.contains(t)&&!e.takeFocusFrom?.(t)){K.current=null;return}let n=g.current,r=e=>n?.querySelector(`[data-row-key="${CSS.escape(e)}"]`)??null,i=r(e.rowKey),s=i?.querySelector('[data-more-action="more"]')??i?.querySelector("a[href], button")??r(e.fallbackKey)?.querySelector("a[href], button");s?(s.focus({preventScroll:!0}),K.current=null):++e.tries>2&&(K.current=null)},[_]);let J=t.some(e=>"session"===e.kind||"group"===e.kind),G=!o&&!a&&null!==s&&!J,Y=W?.source??null,X=W?.drop?.lineY??null,Q=W?.phase==="dragging"?t.find(e=>"group"===e.kind&&e.project.key===W.projectKey)?.project??null:null;return(0,r.jsxs)("div",{ref:m,className:`session-tree${"mobile"===n?" is-mobile":""}${Q?" is-group-dragging":""}`,children:[o&&(0,r.jsx)("div",{className:"session-tree-message",children:h("sidebar.loading")}),a&&(0,r.jsx)("div",{className:"session-tree-message is-error",children:a}),G&&(0,r.jsx)("div",{className:"session-tree-message",children:s}),(0,r.jsx)("div",{ref:g,className:"session-tree-scroll scrollbar-subtle",onScroll:I,onFocus:T,onBlur:$,onPointerDownCapture:A.onPointerDownCapture,onClickCapture:A.onClickCapture,children:!o&&(0,r.jsxs)("div",{ref:x,className:"session-tree-inner",style:{height:M[t.length]},children:[_.map(e=>{let i=t[e];if("spacer"===i.kind)return null;let s=M[e],o=M[e+1]-s,a=i.key===u;if("session"===i.kind)return(0,r.jsx)(t7,{row:i,layout:n,top:s,height:o,now:C,renaming:i.family.root.id===l,confirming:i.family.root.id===d,menuOpen:a,handlers:f},i.key);if("archive-group"===i.kind)return(0,r.jsx)(ns,{row:i,top:s,height:o,menuOpen:a,handlers:f},i.key);if("group"===i.kind){let e=i.project.key===c;return(0,r.jsx)(nr,{row:i,top:s,height:o,menuOpen:a,renaming:e,canDrag:R&&!e&&L[i.project.pinned?"pinned":"other"]>1,dragPhase:W?.projectKey===i.project.key?W.phase:null,drag:A.handlers,handlers:f},i.key)}return(0,r.jsx)(ni,{row:i,top:s,height:o,handlers:f,onMoreAction:V},i.key)}),Y&&(0,r.jsx)("div",{className:"session-tree-drag-source","aria-hidden":"true",style:{top:Y.top,height:Y.bottom-Y.top}}),null!==X&&(0,r.jsx)("div",{className:"session-tree-drop-line","aria-hidden":"true",style:{top:X}})]})}),Q&&(0,r.jsx)("div",{ref:v,className:"session-tree-drag-ghost","aria-hidden":"true",children:(0,r.jsx)("span",{className:"session-tree-group-name",children:Q.name})})]})}function t9(e,t){return{top:e,height:t}}let t7=(0,i.memo)(function(e){let t,n,{row:i,layout:s,top:o,height:a,now:l,renaming:d,confirming:u,menuOpen:p,handlers:h}=e,{locale:f,t:m}=(0,eO.s)(),{family:g,context:x,status:v}=i,b=g.root,y=t5(b),j=new Date(l),k=["session-tree-row session-tree-session",v.selected?"is-selected":"",v.running?"is-running":"","archive"===x?"is-archived":"",p?"is-menu-open":"",u?"is-confirming":"",d?"is-renaming":""].filter(Boolean).join(" ");if(u){let e=y.slice(0,22)+(y.length>22?"…":"");return(0,r.jsx)("div",{className:k,style:t9(o,a),"data-row-key":i.key,onKeyDown:e=>{"Escape"!==e.key||t6(e)||(e.preventDefault(),e.stopPropagation(),h.current.onDeleteCancel())},children:(0,r.jsx)(nt,{label:m("sidebar.deleteSession",{title:e}),deleteLabel:m("sidebar.delete"),cancelLabel:m("sidebar.cancel"),onConfirm:e=>{e.stopPropagation(),h.current.onDeleteConfirm(g,e)},onCancel:e=>{e.stopPropagation(),h.current.onDeleteCancel()}})})}if(d)return(0,r.jsx)("div",{className:k,style:t9(o,a),"data-row-key":i.key,children:(0,r.jsx)(ne,{initialValue:y,label:m("sidebar.rename"),onCommit:e=>h.current.onRenameCommit(g,e),onCancel:()=>h.current.onRenameCancel()})});let w=b.isWorktree&&b.branch?b.branch:null,S=b.name&&b.relation?.kind==="fork"?ey(b.name):null,C=b.detailsPending?"…":m("sidebar.messagesCount",{count:b.messageCount}),N=`${y}
3
- ${C} \xb7 ${(0,tS.fw)(b.modified,f,j)}${w?` \xb7 ⑂ ${w}`:""}`,E="";v.awaiting?(t=(0,r.jsx)("span",{className:"session-tree-awaiting",role:"img","aria-label":m("sidebar.agentAwaitingInput")}),E=" is-awaiting",n=m("sidebar.agentAwaitingInput")):v.running?(t=(0,r.jsx)(t8,{size:12,label:m("sidebar.agentRunning")}),E=" is-running",n=m("sidebar.agentRunning")):v.unread?(t=(0,r.jsx)("span",{className:"session-tree-unread",role:"img","aria-label":m("sidebar.newSessionActivity")}),E=" is-unread",n=m("sidebar.newActivity")):t="pinned"===x?(0,r.jsx)("span",{className:"session-tree-project",children:i.project.name}):"archive"===x&&null!==i.archivedAt?(0,tS.Rg)(new Date(i.archivedAt),f,j):(0,tS.Rg)(g.latestModified,f,j);let I="desktop"===s&&("archive"===x||!v.running),T=(0,r.jsxs)(r.Fragment,{children:[S?(0,r.jsxs)("span",{className:"session-tree-title has-fork-suffix",children:[(0,r.jsx)("span",{className:"session-tree-title-base",children:S.base}),(0,r.jsx)("span",{className:"session-tree-title-suffix",children:S.suffix})]}):(0,r.jsx)("span",{className:"session-tree-title",children:y}),w&&(0,r.jsxs)("span",{className:"session-tree-branch",children:[(0,r.jsx)(tW,{size:10,className:"session-tree-branch-icon"}),w]}),(0,r.jsx)("span",{className:`session-tree-meta${E}`,title:n,children:t})]});return(0,r.jsxs)("div",{className:k,style:t9(o,a),"data-row-key":i.key,onClick:()=>h.current.onSelectFamily(g),onContextMenu:e=>h.current.onRowContextMenu(i,e),children:[v.transient?(0,r.jsx)("button",{type:"button",className:"session-tree-main",title:N,"aria-current":v.selected?"true":void 0,children:T}):(0,r.jsx)("a",{className:"session-tree-main",href:c(b.id),title:N,"aria-current":v.selected?"true":void 0,onClick:e=>{e.stopPropagation(),e.defaultPrevented||0!==e.button||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||(e.preventDefault(),h.current.onSelectFamily(g))},children:T}),!v.transient&&(0,r.jsxs)("span",{className:"session-tree-actions",children:[I&&("archive"===x?(0,r.jsx)("button",{type:"button",className:"session-tree-action session-tree-quick-action","aria-label":m("sidebar.restore"),title:m("sidebar.restore"),onClick:e=>{e.stopPropagation(),h.current.onRestoreFamily(g)},children:(0,r.jsx)(tL,{size:13})}):(0,r.jsx)("button",{type:"button",className:"session-tree-action session-tree-quick-action","aria-label":m("sidebar.archive"),title:m("sidebar.archive"),onClick:e=>{e.stopPropagation(),h.current.onArchiveFamily(g)},children:(0,r.jsx)(tR,{size:13})})),(0,r.jsx)("button",{type:"button",className:`session-tree-action session-tree-more-action${p?" is-active":""}`,"aria-label":m("sidebar.moreActions"),title:m("sidebar.moreActions"),"aria-haspopup":"menu","aria-expanded":p,onClick:e=>{let t;e.stopPropagation();let n=e.currentTarget;h.current.onOpenRowMenu(i,{kind:"rect",rect:{left:(t=n.getBoundingClientRect()).left,top:t.top,right:t.right,bottom:t.bottom},align:"end"},n)},children:(0,r.jsx)(tM,{size:14})})]})]})});function ne(e){let{initialValue:t,label:n,maxLength:s,onCommit:o,onCancel:a}=e,[l,c]=(0,i.useState)(t),d=(0,i.useRef)(null),u=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=d.current;e&&(e.focus(),e.select())},[]);let p=e=>{u.current||(u.current=!0,o(e))};return(0,r.jsx)("input",{ref:d,className:"session-tree-rename",value:l,"aria-label":n,maxLength:s,onChange:e=>c(e.target.value),onBlur:e=>p(e.currentTarget.value),onKeyDown:e=>{if(!t6(e)){if("Enter"===e.key)e.preventDefault(),p(e.currentTarget.value);else if("Escape"===e.key){if(e.preventDefault(),e.stopPropagation(),u.current)return;u.current=!0,a()}}}})}function nt(e){let{label:t,deleteLabel:n,cancelLabel:s,onConfirm:o,onCancel:a}=e,l=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=document.activeElement;e&&e!==document.body||l.current?.focus()},[]),(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"session-tree-confirm-text",children:t}),(0,r.jsxs)("button",{type:"button",className:"session-tree-confirm-delete",onClick:o,children:[(0,r.jsx)(tF,{size:12}),n]}),(0,r.jsx)("button",{ref:l,type:"button",className:"session-tree-confirm-cancel",onClick:a,children:s})]})}function nn(e){let{running:t,unread:n,t:i}=e;return 0===t&&0===n?null:(0,r.jsxs)("span",{className:"session-tree-summary",children:[t>0&&(0,r.jsxs)("span",{className:"session-tree-summary-running",role:"img",title:i("sidebar.agentRunning"),"aria-label":`${i("sidebar.agentRunning")} (${t})`,children:[(0,r.jsx)(t8,{size:10}),t]}),n>0&&(0,r.jsxs)("span",{className:"session-tree-summary-unread",role:"img",title:i("sidebar.newSessionActivity"),"aria-label":`${i("sidebar.newSessionActivity")} (${n})`,children:[(0,r.jsx)("span",{className:"session-tree-summary-dot"}),n]})]})}let nr=(0,i.memo)(function(e){let{row:t,top:n,height:s,menuOpen:o,renaming:a,canDrag:l,dragPhase:c,drag:d,handlers:u}=e,{t:p}=(0,eO.s)(),{project:h,expanded:f}=t,m=(0,i.useRef)(null),g=["session-tree-row session-tree-group",h.current?"is-current":"",o?"is-active":"","armed"===c?"is-drag-armed":""].filter(Boolean).join(" ");return((0,i.useEffect)(()=>{let e=m.current;if(!l||!e)return;let t=e=>d.onTouchMove(e);return e.addEventListener("touchmove",t,{passive:!1}),()=>e.removeEventListener("touchmove",t)},[l,d]),a)?(0,r.jsx)("div",{ref:m,className:`${g} is-renaming`,style:t9(n,s),"data-row-key":t.key,children:(0,r.jsx)(ne,{initialValue:h.name,label:p("sidebar.projectName"),maxLength:80,onCommit:e=>u.current.onRenameProjectCommit(h,e),onCancel:()=>u.current.onRenameProjectCancel()})}):(0,r.jsxs)("div",{ref:m,className:g,style:t9(n,s),"data-row-key":t.key,onPointerDown:l?e=>d.onPointerDown(e,h.key):void 0,children:[(0,r.jsxs)("button",{type:"button",className:"session-tree-group-toggle","aria-expanded":f,title:h.root,onClick:e=>u.current.onToggleGroup(h.key,e.altKey),children:[(0,r.jsx)(tz,{size:12,strokeWidth:3,className:`session-tree-chevron${f?" is-open":""}`}),(0,r.jsx)("span",{className:"session-tree-group-name",children:h.name}),h.pinned&&(0,r.jsx)(tA,{size:10,className:"session-tree-group-pin",label:p("sidebar.pinnedProject")}),!f&&(0,r.jsx)(nn,{running:t.running,unread:t.unread,t:p})]}),(0,r.jsxs)("span",{className:"session-tree-group-actions",children:[(0,r.jsx)("button",{type:"button",className:"session-tree-group-action","aria-label":p("sidebar.newSessionInProject",{name:h.name}),title:p("sidebar.newSessionInProject",{name:h.name}),onClick:e=>{e.stopPropagation(),u.current.onGroupNew(h)},children:(0,r.jsx)(t$,{size:13})}),(0,r.jsx)("button",{type:"button",className:`session-tree-group-action${o?" is-active":""}`,"aria-label":p("sidebar.projectActions",{name:h.name}),title:p("sidebar.projectActions",{name:h.name}),"aria-haspopup":"menu","aria-expanded":o,onClick:e=>{e.stopPropagation(),u.current.onGroupMenu(h,e.currentTarget)},children:(0,r.jsx)(tM,{size:13})})]})]})}),ni=(0,i.memo)(function(e){let{row:t,top:n,height:i,handlers:s,onMoreAction:o}=e,{t:a}=(0,eO.s)(),l=t9(n,i);switch(t.kind){case"pinned-header":return(0,r.jsx)("div",{className:"session-tree-row session-tree-pinned-header",style:l,"data-row-key":t.key,children:(0,r.jsxs)("button",{type:"button",className:"session-tree-pinned-toggle","aria-expanded":!t.collapsed,onClick:()=>s.current.onTogglePinned(),children:[(0,r.jsx)(tz,{size:12,strokeWidth:3,className:`session-tree-chevron${t.collapsed?"":" is-open"}`}),(0,r.jsx)("span",{className:"session-tree-pinned-label",children:a("sidebar.pinned")}),(0,r.jsxs)("span",{className:"session-tree-pinned-count",children:["\xb7 ",t.count]}),t.collapsed&&t.running>0&&(0,r.jsx)("span",{className:"session-tree-pinned-dot is-running",role:"img",title:a("sidebar.agentRunning"),"aria-label":`${a("sidebar.agentRunning")} (${t.running})`}),t.collapsed&&t.unread>0&&(0,r.jsx)("span",{className:"session-tree-pinned-dot is-unread",role:"img",title:a("sidebar.newSessionActivity"),"aria-label":`${a("sidebar.newSessionActivity")} (${t.unread})`})]})});case"pinned-more":case"group-more":{let e="pinned-more"===t.kind?z:t.projectKey;return(0,r.jsxs)("div",{className:"session-tree-row session-tree-more",style:l,"data-row-key":t.key,children:[t.hidden>0&&(0,r.jsx)("button",{type:"button",className:"session-tree-more-toggle","data-more-action":"more",onClick:n=>o(t.key,e,"more",n.currentTarget),children:a("sidebar.showMore",{count:t.hidden})}),t.canShowLess&&(0,r.jsx)("button",{type:"button",className:"session-tree-more-toggle","data-more-action":"less",onClick:n=>o(t.key,e,"less",n.currentTarget),children:a("sidebar.showLess")})]})}case"group-empty":return(0,r.jsx)("div",{className:"session-tree-row session-tree-group-empty",style:l,"data-row-key":t.key,children:a("sidebar.noLiveSessions")});case"footer-open":return(0,r.jsx)("div",{className:"session-tree-row session-tree-footer",style:l,"data-row-key":t.key,children:(0,r.jsxs)("button",{type:"button",className:"session-tree-footer-button",onClick:e=>s.current.onOpenOtherProject(e.currentTarget),children:[(0,r.jsx)(tV,{size:12}),(0,r.jsx)("span",{className:"session-tree-footer-label",children:a("sidebar.openOtherProject")})]})});case"footer-archived":return(0,r.jsx)("div",{className:"session-tree-row session-tree-footer",style:l,"data-row-key":t.key,children:(0,r.jsxs)("button",{type:"button",className:"session-tree-footer-button",onClick:()=>s.current.onOpenArchive(),children:[(0,r.jsx)(tR,{size:12}),(0,r.jsx)("span",{className:"session-tree-footer-label",children:a("sidebar.archivedCount",{count:t.count})}),(0,r.jsx)(tz,{size:10,className:"session-tree-footer-chevron"})]})})}}),ns=(0,i.memo)(function(e){let{row:t,top:n,height:i,menuOpen:s,handlers:o}=e,{t:a}=(0,eO.s)(),{project:l,expanded:c}=t,d=["session-tree-row session-tree-group session-tree-archive-group",l.current?"is-current":"",s?"is-active":""].filter(Boolean).join(" ");return(0,r.jsxs)("div",{className:d,style:t9(n,i),"data-row-key":t.key,children:[(0,r.jsxs)("button",{type:"button",className:"session-tree-group-toggle","aria-expanded":c,title:l.root,onClick:e=>o.current.onToggleArchiveGroup?.(l.key,e.altKey),children:[(0,r.jsx)(tz,{size:12,strokeWidth:3,className:`session-tree-chevron${c?" is-open":""}`}),(0,r.jsx)("span",{className:"session-tree-group-name",children:l.name}),(0,r.jsxs)("span",{className:"session-tree-archive-group-count",children:["\xb7 ",t.count]})]}),(0,r.jsx)("span",{className:"session-tree-group-actions",children:(0,r.jsx)("button",{type:"button",className:`session-tree-group-action${s?" is-active":""}`,"aria-label":a("sidebar.archivedProjectActions",{name:l.name}),title:a("sidebar.archivedProjectActions",{name:l.name}),"aria-haspopup":"menu","aria-expanded":s,onClick:e=>{e.stopPropagation(),o.current.onArchiveGroupMenu?.(l,e.currentTarget)},children:(0,r.jsx)(tM,{size:13})})})]})}),no="[data-sidebar-menu-filter]",na="[data-sidebar-menu-autofocus]",nl="button, input, textarea, select, a[href], [tabindex]";function nc(e){return i.Children.toArray(e).length>0}function nd(e){return"item"===e.type&&void 0!==e.checked}function nu(e){return e.getClientRects().length>0}function np(e){return!e.disabled&&"true"!==e.getAttribute("aria-disabled")&&nu(e)}function nh(e){return Array.from(e.querySelectorAll("[data-sidebar-menu-item]")).filter(np)}function nf(e){let t=Array.from(e.querySelectorAll(na)).find(np);if(t)return t;let n=nh(e);return n.length>0?n[0]:Array.from(e.querySelectorAll(nl)).filter(e=>e.tabIndex>=0&&np(e))[0]??null}function nm(e){e.stopPropagation()}let ng={onClick:nm,onDoubleClick:nm,onMouseDown:nm,onMouseUp:nm,onPointerDown:nm,onPointerUp:nm,onKeyDown:nm,onKeyUp:nm,onFocus:nm,onBlur:nm,onContextMenu:function(e){e.preventDefault(),e.stopPropagation()}};function nx(e,t){return n=>{"Enter"!==n.key||n.nativeEvent.isComposing||229===n.keyCode||(n.preventDefault(),t(e,n.shiftKey))}}function nv(e){let{item:t,onActivate:n}=e,i=void 0!==t.checked,s=["sidebar-menu-item",i?"is-choice":"",t.danger?"is-danger":"",t.checked?"is-checked":""].filter(Boolean).join(" "),o=["sidebar-menu-label",t.mono?"is-mono":"",t.path?"is-path":""].filter(Boolean).join(" "),a=null;t.disabled&&t.disabledReason?a=(0,r.jsx)("span",{className:"sidebar-menu-note",children:t.disabledReason}):t.note?a=(0,r.jsx)("span",{className:"sidebar-menu-note",children:t.note}):t.shortcut&&(a=(0,r.jsx)("kbd",{className:"sidebar-menu-shortcut",children:t.shortcut}));let l=(0,r.jsxs)("button",{type:"button",role:i?"menuitemradio":"menuitem","aria-checked":i?t.checked:void 0,"aria-disabled":!!t.disabled||void 0,"aria-keyshortcuts":t.shortcut&&!t.disabled?t.shortcut.toUpperCase():void 0,tabIndex:-1,title:t.title,"data-sidebar-menu-item":"",className:s,onClick:e=>n(t,e.shiftKey),onKeyDown:nx(t,n),children:[(0,r.jsx)("span",{className:"sidebar-menu-icon",children:i?t.checked?(0,r.jsx)(t_,{size:13}):null:t.icon}),(0,r.jsx)("span",{className:o,children:t.path?(0,r.jsx)("span",{children:t.label}):t.label}),t.badge,a]}),c=t.secondary;return c?(0,r.jsxs)("div",{className:i?"sidebar-menu-row is-choice":"sidebar-menu-row",role:"none",children:[l,(0,r.jsx)("button",{type:"button",role:"menuitem","aria-label":c.label,"aria-disabled":!!c.disabled||void 0,tabIndex:-1,title:c.label,"data-sidebar-menu-item":"",className:c.danger?"sidebar-menu-secondary is-danger":"sidebar-menu-secondary",onClick:e=>n(c,e.shiftKey),onKeyDown:nx(c,n),children:c.icon})]}):l}function nb(e){var t;let n,{sheet:i,ariaLabel:s,title:o,items:a,filter:l,filterQuery:c="",onFilterQueryChange:d,children:u,cancelLabel:p,focusCancel:h=!1,width:f=208,classic:m=!1,footer:g,surfaceRef:x,onActivate:v,onClose:b}=e,y=nc(u),j=!y&&nc(g),k=void 0!==l&&!y&&function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;return(e??[]).filter(nd).length>=t}(a,l.minChoices),w=k?(t=a??[],(n=c.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]):a??[],S=w.map(e=>"separator"===e.type?(0,r.jsx)("div",{className:"sidebar-menu-separator",role:"separator"},e.id):"header"===e.type?(0,r.jsx)("div",{className:"sidebar-menu-header",role:"presentation",children:e.label},e.id):"custom"===e.type?(0,r.jsx)("div",{className:"sidebar-menu-custom",role:"none",children:e.content},e.id):(0,r.jsx)(nv,{item:e,onActivate:v},e.id)),C=y?u:k||j?(0,r.jsxs)(r.Fragment,{children:[k&&(0,r.jsx)("div",{className:"sidebar-menu-filter",children:(0,r.jsx)("input",{className:"sidebar-menu-filter-input",value:c,placeholder:l.placeholder,"aria-label":l.placeholder,autoComplete:"off",spellCheck:!1,"data-sidebar-menu-filter":"","data-sidebar-menu-autofocus":i?void 0:"",onChange:e=>d?.(e.target.value)})}),k&&(0,r.jsx)("div",{role:"status",children:c.trim()&&!w.some(nd)&&(0,r.jsx)("div",{className:"sidebar-menu-empty",children:l.emptyLabel})}),(0,r.jsx)("div",{role:"menu","aria-label":s,children:S}),j&&g]}):S,N=y||k||j?void 0:"menu";return i?(0,r.jsxs)("div",{className:"sidebar-sheet-layer",...ng,children:[(0,r.jsx)("div",{className:"sidebar-sheet-backdrop","aria-hidden":"true",onClick:()=>b("outside")}),(0,r.jsxs)("div",{ref:x,className:"sidebar-sheet",role:"dialog","aria-modal":"true","aria-label":s,children:[o?(0,r.jsx)("div",{className:"sidebar-sheet-title",children:o}):null,(0,r.jsx)("div",{className:"sidebar-sheet-body",role:N,"aria-label":N?s:void 0,children:C}),(0,r.jsx)("button",{type:"button",className:"sidebar-sheet-cancel","data-sidebar-menu-autofocus":h?"":void 0,onClick:()=>b("cancel"),children:p})]})]}):(0,r.jsx)("div",{ref:x,className:m?"sidebar-menu is-classic":"sidebar-menu",role:N??"dialog","aria-label":s,style:{width:f},...ng,children:C})}function ny(e){let{open:t,anchor:n,sheet:s,ariaLabel:o,title:a,items:l,filter:c,children:d,cancelLabel:u,focusCancel:p,onClose:h,returnFocusTo:f,width:m,classic:g=!1,footer:x,focusKey:v=""}=e,[b,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(""),w=(0,i.useRef)(j);w.current=j;let S=(0,i.useRef)(null),C=(0,i.useRef)(h);C.current=h;let N=(0,i.useRef)(l);N.current=l;let E=(0,i.useRef)(f??null);E.current=f??null;let I=(0,i.useRef)(n);I.current=n,(0,i.useEffect)(()=>{y(document.body)},[]);let T=t&&null!==b&&(s||null!==n),$=nc(d),M=n?JSON.stringify(n):"",R=(e,t)=>{if(e.disabled)return;let n=!1;e.onSelect({shiftKey:t,keepOpen:()=>{n=!0}}),n||C.current("select")},L=(0,i.useRef)(R);L.current=R,(0,i.useLayoutEffect)(()=>{let e=S.current;if(!T||s||!e)return;let t=window.visualViewport,n=()=>{let n=I.current;if(!n)return;let r=e.getBoundingClientRect(),{left:i,top:s}=function(e,t,n){let r,i,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8,o=n.left+s,a=n.top+s,l=n.left+n.width-s,c=n.top+n.height-s;if("point"===e.kind)r=e.x+t.width>l&&e.x-t.width>=o?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,o=n.top-4-t.height;i=s+t.height>c&&o>=a?o:s}return{left:Math.max(o,Math.min(r,l-t.width)),top:Math.max(a,Math.min(i,c-t.height))}}(n,{width:r.width,height:r.height},{left:t?.offsetLeft??0,top:t?.offsetTop??0,width:t?.width??window.innerWidth,height:t?.height??window.innerHeight});e.style.left=`${i}px`,e.style.top=`${s}px`};n();let r="u"<typeof ResizeObserver?null:new ResizeObserver(n);return r?.observe(e),window.addEventListener("resize",n),t?.addEventListener("resize",n),t?.addEventListener("scroll",n),()=>{r?.disconnect(),window.removeEventListener("resize",n),t?.removeEventListener("resize",n),t?.removeEventListener("scroll",n)}},[T,s,M,$]),(0,i.useEffect)(()=>{k("")},[T,$]);let A=(0,i.useRef)(!1);return((0,i.useLayoutEffect)(()=>{let e=S.current;if(!T||!e){A.current=!1;return}let t=!A.current;A.current=!0,(t?nf(e):Array.from(e.querySelectorAll(na)).filter(e=>!e.matches(no)&&np(e))[0]??nf(e))?.focus({preventScroll:!0})},[T,s,$,v]),(0,i.useLayoutEffect)(()=>{let e=S.current;if(!T||!e)return;let t=E.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(nu(e))return e;let t=e.closest("[data-row-key]");if(!t)return null;for(let e of Array.from(t.querySelectorAll(nl)))if(e.tabIndex>=0&&np(e))return e;return null}(t);r&&(r.focus({preventScroll:!0}),t&&r!==t&&nu(t)&&t.focus({preventScroll:!0}))}},[T,s]),(0,i.useEffect)(()=>{if(!T)return;let e=e=>{let t=S.current;if(!t||e.isComposing||229===e.keyCode)return;if("Escape"===e.key){e.preventDefault(),e.stopPropagation();let n=t.querySelector(no);if(n&&w.current){k(""),n.focus({preventScroll:!0});return}C.current("escape");return}let n=e.target instanceof Element?e.target:null,r=null!==n&&t.contains(n),i=null===n||n===document.body||n===document.documentElement;if(!r&&!i)return;if("Tab"===e.key){var s;let i,o;r&&(s=e.shiftKey,i=Array.from(t.querySelectorAll(nl)).filter(e=>e!==n&&e.tabIndex>=0&&np(e)),o=s?Node.DOCUMENT_POSITION_PRECEDING:Node.DOCUMENT_POSITION_FOLLOWING,i.some(e=>(n.compareDocumentPosition(e)&o)!=0))||C.current("outside");return}let o=("ArrowDown"===e.key||"ArrowUp"===e.key)&&n?.matches(no);if(r&&function(e){if(!e)return!1;if(e.isContentEditable)return!0;let t=e.tagName;return"TEXTAREA"===t||"SELECT"===t||"INPUT"===t&&!["button","checkbox","radio","range","reset","submit","image","color","file"].includes((e.type||"text").toLowerCase())}(n)&&!o)return;if("ArrowDown"===e.key||"ArrowUp"===e.key||"Home"===e.key||"End"===e.key){let r,i=nh(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}(N.current,e.key);a&&!$&&(e.preventDefault(),e.stopPropagation(),L.current(a,e.shiftKey))};return document.addEventListener("keydown",e,!0),()=>document.removeEventListener("keydown",e,!0)},[T,$]),(0,i.useEffect)(()=>{if(!T||s)return;let e=e=>{let t=S.current,n=e.target instanceof Node?e.target:null;if(!t||n&&t.contains(n))return;let r=E.current;r&&n&&0===e.button&&r.contains(n)&&function(e){let t=e.ownerDocument,n=t.defaultView;if(!n)return;let r=0,i=()=>{t.removeEventListener("click",s,!0),n.clearTimeout(r)};function s(t){i(),t.target instanceof Node&&e.contains(t.target)&&(t.preventDefault(),t.stopPropagation())}t.addEventListener("click",s,!0),r=n.setTimeout(i,1e3)}(r),C.current("outside")};return document.addEventListener("pointerdown",e,!0),()=>document.removeEventListener("pointerdown",e,!0)},[T,s]),T&&b)?(0,eJ.createPortal)((0,r.jsx)(nb,{sheet:s,ariaLabel:o,title:a,items:l,filter:c,filterQuery:j,onFilterQueryChange:k,cancelLabel:u,focusCancel:p,width:m,classic:g,footer:x,surfaceRef:S,onActivate:(e,t)=>L.current(e,t),onClose:e=>C.current(e),children:d}),b):null}function nj(e){let{heading:t,busy:n,error:s,showCancel:o,onCreate:a,onCancel:l}=e,{t:c}=(0,eO.s)(),[d,u]=(0,i.useState)(""),p=d.trim(),h=()=>{p&&!n&&a(p)};return(0,r.jsxs)("div",{className:"sidebar-worktree-form",children:[t&&(0,r.jsx)("div",{className:"sidebar-menu-header",children:t}),(0,r.jsx)("input",{className:"sidebar-worktree-input","data-sidebar-menu-autofocus":"",value:d,readOnly:n,placeholder:c("sidebar.branchName"),"aria-label":c("sidebar.branchName"),onChange:e=>u(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.preventDefault(),h())}}),(0,r.jsxs)("div",{className:"sidebar-worktree-form-buttons",children:[(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-create",disabled:n||!p,onClick:h,children:c(n?"sidebar.creating":"sidebar.create")}),o&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-cancel",onClick:l,children:c("sidebar.cancel")})]}),s&&(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:s})]})}function nk(e,t){return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function nw(e){return e.branch??_(e.path)}function nS(e){let{heading:t,dirty:n,busy:i,error:s,showCancel:o,onForce:a,onCancel:l}=e,{t:c}=(0,eO.s)();return(0,r.jsxs)("div",{className:"sidebar-worktree-form",children:[t&&(0,r.jsx)("div",{className:"sidebar-menu-header",children:t}),n&&(0,r.jsx)("div",{className:"sidebar-worktree-message",children:c("sidebar.forceRemoveCheckout")}),(n||o)&&(0,r.jsxs)("div",{className:"sidebar-worktree-form-buttons",children:[n&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-force",disabled:i,onClick:a,children:c("sidebar.force")}),o&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-cancel","data-sidebar-menu-autofocus":"",onClick:l,children:c("sidebar.cancel")})]}),s&&(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:s})]})}function nC(e){let{busy:t,onForce:n,onCancel:s}=e,{t:o}=(0,eO.s)(),a=(0,i.useId)();return(0,r.jsxs)("div",{className:"sidebar-worktree-confirm",children:[(0,r.jsx)("span",{id:a,className:"sidebar-worktree-confirm-text",title:o("sidebar.forceRemoveCheckout"),children:o("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{type:"button",role:"menuitem",tabIndex:-1,"data-sidebar-menu-item":"","aria-describedby":a,"aria-disabled":!!t||void 0,className:"sidebar-worktree-force",onClick:()=>{t||n()},children:o("sidebar.force")}),(0,r.jsx)("button",{type:"button",role:"menuitem",tabIndex:-1,"data-sidebar-menu-item":"","data-sidebar-menu-autofocus":"",className:"sidebar-worktree-cancel",onClick:s,children:o("sidebar.cancel")})]})}function nN(e){let t,n,{layout:s,context:o,mobile:a,label:l,placeholder:c="",homeDir:d,projectActivity:u,worktreeHint:p=null,newWorktreeTitle:h,handleRef:f,onPick:m,onUseDefaultDirectory:g,onOpenFolder:x,onRefreshWorktrees:v,onCreateWorktree:b,onRemoveWorktree:y}=e,{t:j}=(0,eO.s)(),[k,w]=(0,i.useState)(null),S=(0,i.useRef)(k);S.current=k;let C=(0,i.useRef)(0),N=(0,i.useRef)(null),E=(0,i.useRef)(null),I=(0,i.useRef)(!1),T=(0,i.useRef)(m);T.current=m;let $="inline"!==s,M=!$,R=!a,{project:L,worktrees:A}=o,P=(t=o.worktrees??[]).find(e=>e.path===o.currentWorktreePath)??t.find(e=>e.isMain)??null,z=M&&L?eS(ek(o)).find(e=>{let{choice:t}=e;return t.key===L.key}):void 0;(0,i.useEffect)(()=>(I.current=!0,()=>{I.current=!1}),[]);let W=()=>(C.current+=1,C.current),O=()=>w(null),D=(e,t)=>{let n=t.getBoundingClientRect(),r=Math.max($?220:"project"===e?260:240,Math.round(n.width));w({id:W(),kind:e,anchor:{kind:"rect",rect:{left:n.left,top:n.top,right:n.right,bottom:n.bottom},align:"row"===s&&"worktree"===e?"end":"start"},opener:t,width:r,body:null,removing:!1}),"worktree"===e&&v()},F=(0,i.useRef)(D);F.current=D,(0,i.useImperativeHandle)(f,()=>({button:e=>("worktree"===e?E:N).current,openMenu:e=>{let t=("worktree"===e?E:N).current;t&&F.current(e,t)}}),[]);let B=(e,t)=>{w(n=>n?.id===e?t(n):n)},H=e=>{let t=W();w(n=>n?.kind==="worktree"?{...n,id:t,body:e,removing:!1}:n)},U=async e=>{let t,n=S.current;if(!n||n.body?.kind!=="create"||!L)return;let{id:r}=n,i=(e,t)=>{B(r,n=>({...n,body:{kind:"create",busy:e,error:t}}))};i(!0,null);try{t=await b(L,e)}catch(e){t={error:e instanceof Error?e.message:String(e)}}I.current&&("error"in t?i(!1,t.error):S.current?.id===r&&(w(null),T.current({cwd:t.path,projectKey:L.key,projectRoot:L.root},"worktree")))},q=async(e,t)=>{let n,r=S.current;if(!r||!L||!y)return;let{id:i}=r;B(i,e=>({...e,removing:!0,body:e.body?.kind==="remove"?{...e.body,busy:!0,error:null}:e.body}));try{n=await y(L,e.path,t)}catch(e){n={error:e instanceof Error?e.message:String(e)}}I.current&&B(i,t=>{if("removed"===n)return{...t,removing:!1,body:null};let r="dirty"===n||t.body?.kind==="remove"&&t.body.dirty;return{...t,removing:!1,body:{kind:"remove",worktree:e,dirty:r,busy:!1,error:"dirty"===n?null:n.error}}})},K=()=>[...(A??[]).map(e=>R&&V?.kind==="remove"&&V.dirty&&V.worktree.path===e.path?{type:"custom",id:`worktree:${e.path}`,content:(0,r.jsx)(nC,{busy:V.busy,onForce:()=>{q(e,!0)},onCancel:()=>H(null)})}:{type:"item",id:`worktree:${e.path}`,label:R?e.branch??nk(e.path,d):nw(e),mono:R,path:R,note:e.isMain?j("sidebar.main"):void 0,title:e.path,checked:e.path===P?.path,secondary:y&&!e.isMain?{label:j("sidebar.removeWorktreeTitle",{path:e.path}),icon:(0,r.jsx)(tF,{size:12}),danger:!0,disabled:k?.removing,onSelect:t=>{let{keepOpen:n}=t;n(),q(e,!1)}}:void 0,onSelect:()=>{L&&e.path!==P?.path&&m({cwd:e.path,projectKey:L.key,projectRoot:L.root},"worktree")}}),...R?[]:[{type:"separator",id:"separator"}],...R&&V?.kind==="create"?[]:[{type:"item",id:"new-worktree",label:j("sidebar.newWorktree"),icon:(0,r.jsx)(t$,{size:13}),onSelect:e=>{let{keepOpen:t}=e;t(),H({kind:"create",busy:!1,error:null})}}]],V=k?.kind==="worktree"?k.body:null,Z="",J=null,G=null;if(R&&k?.kind==="worktree")Z=j("sidebar.switchWorktree"),n=K(),V?.kind==="create"?G=(0,r.jsx)(nj,{heading:null,busy:V.busy,error:V.error,showCancel:!0,onCreate:e=>{U(e)},onCancel:()=>H(null)}):V?.kind==="remove"&&V.error&&(G=(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:V.error}));else if(V?.kind==="create")Z=h,J=(0,r.jsx)(nj,{heading:a?null:Z,busy:V.busy,error:V.error,showCancel:!a,onCreate:e=>{U(e)},onCancel:O});else if(V?.kind==="remove")Z=j("sidebar.removeWorktreeHeading",{name:nw(V.worktree)}),J=(0,r.jsx)(nS,{heading:a?null:Z,dirty:V.dirty,busy:V.busy,error:V.error,showCancel:!a,onForce:()=>{q(V.worktree,!0)},onCancel:O});else if(k?.kind==="project"){let e,t;Z=j("workspace.project"),t=(e=eS(ek(o)).map(e=>{let{choice:t,name:n,note:i}=e,s=u?.get(t.key),o=R&&void 0===t.alias;return{type:"item",id:`project:${t.key}`,label:o?nk(t.root,d):n,note:o?void 0:i??void 0,mono:R,path:o,title:t.root,checked:t.key===L?.key,badge:s?(0,r.jsx)(nn,{running:s.running,unread:s.unread,t:j}):void 0,onSelect:()=>{t.key===L?.key&&A||m({cwd:t.root,projectKey:t.key,projectRoot:t.root},"project")}}})).length>0?[{type:"separator",id:"separator"}]:[],n=[...e,...t,{type:"item",id:"default-directory",label:j("sidebar.useDefaultDirectory"),icon:(0,r.jsx)(tK,{size:13}),onSelect:()=>g()},{type:"item",id:"open-folder",label:j(R?"sidebar.customPath":"sidebar.openOtherProject"),icon:R?(0,r.jsx)(t$,{size:13}):(0,r.jsx)(tV,{size:13}),onSelect:()=>x(k?.opener??null)}]}else k?.kind==="worktree"&&(Z=j("sidebar.switchWorktree"),n=K());let Y=k?.kind==="project"?{placeholder:j("sidebar.filterProjects"),emptyLabel:j("sidebar.noMatchingProjects"),minChoices:R?9:void 0}:{placeholder:j("sidebar.filterWorktrees"),emptyLabel:j("sidebar.noMatchingWorktrees")},X=$&&void 0!==u&&[...u].some(e=>{let[t,{running:n,unread:r}]=e;return t!==L?.key&&(n>0||r>0)});return(0,r.jsxs)("div",{className:`project-picker is-${s}`,role:"group","aria-label":l,children:[(0,r.jsxs)("button",{ref:N,type:"button",className:L?"project-picker-button is-project":"project-picker-button is-project is-empty",title:L?.root??"","aria-haspopup":"menu","aria-expanded":k?.kind==="project",onClick:e=>D("project",e.currentTarget),children:[M&&(0,r.jsx)(tK,{size:12,className:"project-picker-icon"}),M&&L?(0,r.jsxs)("span",{className:"project-picker-name",children:[void 0===L.alias&&z?.note&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"project-picker-parent",children:z.note}),"/"]}),(0,r.jsx)("span",{className:"project-picker-leaf",children:L.alias??z?.name??_(L.root)})]}):L?.alias!==void 0?(0,r.jsx)("span",{className:"project-picker-label is-alias",children:L.alias}):L?(0,r.jsx)("span",{className:"project-picker-path",children:(0,r.jsx)("span",{children:nk(L.root,d)})}):(0,r.jsx)("span",{className:"project-picker-label",children:c}),X&&(0,r.jsx)("span",{className:"project-picker-activity",role:"img",title:j("sidebar.newActivity"),"aria-label":j("sidebar.newActivity")}),M&&(0,r.jsx)(tz,{size:9,className:"project-picker-chevron sidebar-icon-down"})]}),A&&(0,r.jsxs)("button",{ref:E,type:"button",className:"project-picker-button",title:P?j("sidebar.worktreePath",{path:P.path}):j("sidebar.switchWorktree"),"aria-haspopup":"menu","aria-expanded":k?.kind==="worktree",onClick:e=>D("worktree",e.currentTarget),children:[(0,r.jsx)(tW,{size:11,className:P&&!P.isMain?"project-picker-icon is-linked":"project-picker-icon"}),(0,r.jsx)("span",{className:"project-picker-path",children:(0,r.jsx)("span",{children:P?P.branch??nk(P.path,d):"…"})}),P?.isMain&&"stacked"===s&&(0,r.jsx)("span",{className:"project-picker-note",children:j("sidebar.main")}),$&&A.length>1&&(0,r.jsx)("span",{className:"project-picker-note",children:A.length}),(0,r.jsx)(tz,{size:9,className:"project-picker-chevron sidebar-icon-down"})]}),!A&&$&&p&&(0,r.jsxs)("button",{type:"button","aria-disabled":"true",tabIndex:-1,title:p.title,className:"project-picker-button is-inactive",children:[(0,r.jsx)(tW,{size:11,className:"project-picker-icon"}),(0,r.jsx)("span",{className:"project-picker-label",children:p.label})]}),(0,r.jsx)(ny,{open:null!==k,anchor:k?.anchor??null,sheet:a,ariaLabel:Z,title:Z,items:n,filter:Y,cancelLabel:j("sidebar.cancel"),focusCancel:V?.kind==="remove",onClose:O,returnFocusTo:k?.opener??null,width:k?.width,classic:R,footer:G,focusKey:V?`${V.kind}:${"remove"===V.kind&&V.dirty}`:"list",children:J})]})}function nE(e){let{open:t,query:n,children:s,selectedSessionId:o,onSelectSession:a,archivedSessionIds:l}=e,{t:c,locale:d}=(0,eO.s)(),[u,p]=(0,i.useState)({query:""}),h=n.trim(),f=u.query===h?u.response:void 0,m=u.query===h&&u.failed;return(0,i.useEffect)(()=>{if(!t||!h)return;let e=new AbortController;p({query:h});let n=setTimeout(async()=>{try{let t=await fetch(`/api/sessions/search?${new URLSearchParams({q:h})}`,{signal:e.signal});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();e.signal.aborted||p({query:h,response:n})}catch{e.signal.aborted||p({query:h,failed:!0})}},300);return()=>{clearTimeout(n),e.abort()}},[t,h]),t&&h?(0,r.jsxs)("div",{className:"min-h-20 flex-1 overflow-y-auto","aria-busy":!f&&!m,children:[(0,r.jsx)("div",{role:"status",className:"px-3 py-2 text-xs text-text-muted",children:m?c("sidebar.sessionSearchFailed"):f?0===f.results.length?c("sidebar.sessionSearchEmpty"):c("sidebar.sessionSearchCount",{count:f.results.length}):c("sidebar.sessionSearching")}),f?.truncated&&(0,r.jsx)("div",{role:"status",className:"px-3 pb-2 text-xs text-text-muted",children:c("sidebar.sessionSearchPartial")}),f?.results.map(e=>{let{session:t,entryId:n,blockIndex:i,titleMatch:s,before:u,match:p,after:h}=e;return(0,r.jsxs)("button",{type:"button",onClick:()=>a(t,n,i),"aria-current":t.id===o?"true":void 0,className:`block w-full cursor-pointer border-b border-border px-3 py-2 text-left hover:bg-bg-hover focus-visible:outline-2 focus-visible:outline-accent ${t.id===o?"bg-bg-selected":""}`,children:[(0,r.jsxs)("span",{className:"flex min-w-0 items-center gap-1.5",children:[(0,r.jsx)("span",{className:"min-w-0 truncate text-xs font-medium text-text",children:s?(0,r.jsxs)(r.Fragment,{children:[u,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:p}),h]}):t.name||t.firstMessage}),l?.has(t.id)&&(0,r.jsx)("span",{className:"shrink-0 rounded-[4px] border border-border px-1 text-[10px] leading-[14px] text-text-dim",children:c("sidebar.archived")})]}),(0,r.jsxs)("span",{className:"mt-1 flex min-w-0 gap-2 text-[10px] text-text-dim",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate",title:t.cwd,children:t.cwd}),(0,r.jsx)("span",{className:"shrink-0",children:(0,tS.fw)(t.modified,d)})]}),!s&&(0,r.jsxs)("span",{className:"mt-1 block text-xs leading-relaxed wrap-anywhere text-text-muted",children:[u,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:p}),h]})]},t.id)})]}):s}function nI(e,t){return`${e}/share/${t}`}function nT(e){return e instanceof Error?e.message:String(e)}function n$(e){let{sessionId:t,origin:n,fetchImpl:s,onCopied:o,onStopped:a}=e,{t:l}=(0,eO.s)(),[c,d]=(0,i.useState)({status:"loading"}),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(!1),[x,v]=(0,i.useState)(null),b=s??fetch,y=n??window.location.origin,j=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!0;return d({status:"loading"}),f(null),g(!1),b(`/api/sessions/${encodeURIComponent(t)}/share`,{cache:"no-store"}).then(async t=>{let n=await t.json().catch(()=>({}));if(e){if(!t.ok)return void d({status:"load-failed",error:n.error??`HTTP ${t.status}`});d(n.share?{status:"shared",share:n.share}:{status:"unshared"})}}).catch(t=>{e&&d({status:"load-failed",error:nT(t)})}),()=>{e=!1}},[b,t]),(0,i.useEffect)(()=>{let e=!0;return b(`/api/sessions/${encodeURIComponent(t)}`,{cache:"no-store"}).then(async t=>{let n=await t.json().catch(()=>({}));e&&t.ok&&"number"==typeof n.info?.messageCount&&v(n.info.messageCount)}).catch(()=>{}),()=>{e=!1}},[b,t]);let k=(0,i.useCallback)(()=>{j.current||(j.current=!0,p("create"),f(null),b(`/api/sessions/${encodeURIComponent(t)}/share`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}).then(async e=>{var t,n;let r=await e.json().catch(()=>({}));if("string"!=typeof(t=r).code||"string"!=typeof t.createdAt||"string"!=typeof t.title){let{key:t,params:i}=(n=e.status,"too_large"===r.code||"too_large"===r.error?{key:"share.tooLarge"}:{key:"share.createError",params:{error:r.error??`HTTP ${n}`}});f(l(t,i));return}d({status:"shared",share:{code:r.code,createdAt:r.createdAt,title:r.title}}),g(!1)}).catch(e=>{f(l("share.createError",{error:nT(e)}))}).finally(()=>{j.current=!1,p(null)}))},[b,t,l]),w=(0,i.useCallback)(()=>{if(!j.current){if(!m)return void g(!0);j.current=!0,p("stop"),f(null),b(`/api/sessions/${encodeURIComponent(t)}/share`,{method:"DELETE"}).then(async e=>{let t=await e.json().catch(()=>({}));e.ok&&!0===t.ok?(d({status:"unshared"}),g(!1),v(null),a()):f(l("share.stopError",{error:t.error??`HTTP ${e.status}`}))}).catch(e=>{f(l("share.stopError",{error:nT(e)}))}).finally(()=>{j.current=!1,p(null)})}},[a,b,t,m,l]),S=(0,i.useCallback)(()=>{d(e=>("shared"===e.status&&(0,ty.D)(nI(y,e.share.code)).then(()=>o(),()=>{}),e))},[o,y]);return(0,r.jsx)(nM,{state:c,messageCount:x,busy:u,error:h,stopArmed:m,origin:y,onCopy:S,onCreate:k,onRefresh:k,onStop:w})}function nM(e){let{state:t,messageCount:n,busy:i,error:s,stopArmed:o,origin:a,onCopy:l,onCreate:c,onRefresh:d,onStop:u}=e,{t:p}=(0,eO.s)();return(0,r.jsxs)("div",{className:"sidebar-share-panel",children:[(0,r.jsx)("div",{className:"sidebar-menu-header",children:p("share.title")}),"loading"===t.status&&(0,r.jsx)("p",{role:"status",className:"sidebar-share-status",children:p("sidebar.loading")}),"load-failed"===t.status&&(0,r.jsx)("div",{role:"alert",className:"sidebar-share-error",children:p("share.loadError",{error:t.error})}),"unshared"===t.status&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"sidebar-share-text",children:p("share.description")}),null!==n&&(0,r.jsx)("p",{className:"sidebar-share-note",children:p("share.summary",{count:n})}),(0,r.jsx)("div",{className:"sidebar-share-buttons",children:(0,r.jsx)("button",{type:"button",className:"sidebar-share-create",disabled:null!==i,"data-sidebar-menu-autofocus":"",onClick:c,children:p("create"===i?"share.creating":"share.create")})})]}),"shared"===t.status&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"sidebar-share-link-label",children:p("share.linkLabel")}),(0,r.jsx)("code",{className:"sidebar-share-link",children:nI(a,t.share.code)}),(0,r.jsxs)("div",{className:"sidebar-share-buttons",children:[(0,r.jsx)("button",{type:"button",className:"sidebar-share-copy","data-sidebar-menu-autofocus":"",onClick:l,children:p("share.copy")}),(0,r.jsx)("button",{type:"button",className:"sidebar-share-refresh",disabled:null!==i,onClick:d,children:p("create"===i?"share.creating":"share.refresh")})]}),(0,r.jsx)("div",{className:"sidebar-share-buttons",children:(0,r.jsx)("button",{type:"button",className:`sidebar-share-stop${o?" is-armed":""}`,disabled:null!==i,onClick:u,children:p(o?"share.confirmStop":"share.stop")})})]}),s&&(0,r.jsx)("div",{role:"alert",className:"sidebar-share-error",children:s})]})}function nR(e){let{toast:t,dismissLabel:n,durationMs:s,onDismissRef:o}=e,a=(0,i.useRef)(null),[l,c]=(0,i.useState)(!1),[d,u]=(0,i.useState)(!1),p=l||d;return(0,i.useLayoutEffect)(()=>{let e=a.current;e&&window.matchMedia?.("(hover: hover)").matches&&e.matches(":hover")&&c(!0)},[]),(0,i.useEffect)(()=>{if(p)return;let e=window.setTimeout(()=>o.current(),s);return()=>window.clearTimeout(e)},[p,s,o]),(0,r.jsxs)("div",{ref:a,className:"sidebar-toast",onPointerEnter:e=>{"mouse"===e.pointerType&&c(!0)},onPointerLeave:()=>c(!1),onFocus:()=>u(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||u(!1)},children:[t.tail?(0,r.jsxs)("span",{className:"sidebar-toast-message has-tail",title:t.message+t.tail,children:[(0,r.jsx)("span",{className:"sidebar-toast-message-head",children:t.message}),(0,r.jsx)("span",{className:"sidebar-toast-message-tail",children:t.tail})]}):(0,r.jsx)("span",{className:"sidebar-toast-message",title:t.message,children:t.message}),t.actions.map(e=>(0,r.jsx)("button",{type:"button",className:"sidebar-toast-action",onClick:()=>{o.current(),e.onClick()},children:e.label},e.id)),(0,r.jsx)("button",{type:"button",className:"sidebar-toast-dismiss","aria-label":n,title:n,onClick:()=>o.current(),children:(0,r.jsx)(tq,{size:12})})]})}function nL(e){let{toast:t,onDismiss:n,dismissLabel:s,durationMs:o=1e4}=e,a=(0,i.useRef)(n);return a.current=n,(0,r.jsx)("div",{className:"sidebar-toast-region",role:"status","aria-live":"polite",children:t?(0,r.jsx)(nR,{toast:t,dismissLabel:s,durationMs:o,onDismissRef:a},t.id):null})}let nA={remote:"sidebar.openInExplorerRemoteOnly","unsupported-platform":"sidebar.openInExplorerUnsupported"};function nP(e){let{ref:t,onClick:n,title:i,disabled:s,pressed:o,expanded:a,controls:l,done:c,className:d,children:u}=e;return(0,r.jsx)("button",{ref:t,type:"button",onClick:n,disabled:s,title:i,"aria-label":i,"aria-pressed":o,"aria-expanded":a,"aria-controls":l,className:`sidebar-tool-button${o||a?" is-active":""}${c?" is-done":""}${d?` ${d}`:""}`,children:u})}let nz="pi-web:unread-session-ids",nW="pi-web:last-custom-cwd",nO={"open-new-tab":"sidebar.openInNewTab",pin:"sidebar.pin",unpin:"sidebar.unpin",rename:"sidebar.rename",fork:"sidebar.fork",share:"sidebar.sessionShare","copy-session-id":"sidebar.copySessionId","mark-read":"sidebar.markRead","mark-unread":"sidebar.markUnread",archive:"sidebar.archive",unarchive:"sidebar.unarchive",delete:"sidebar.delete"};function nD(){try{return window.localStorage.getItem(nW)??""}catch{return""}}function nF(e){if(!e)return new Set;try{let t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(e=>"string"==typeof e))}catch{}return new Set}function nB(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 nH(e,t){return e.length>t?`${e.slice(0,t)}…`:e}function nU(e){let t=document.activeElement;e&&t instanceof HTMLElement&&t!==document.body&&(0===t.getClientRects().length||null!==t.closest("[inert]"))?e.focus({preventScroll:!0}):eN(document,e)}function n_(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 nq(e){var t,n,s;let o,l,d,u,p,h,g,v,{selectedSessionId:b,onSelectSession:y,onNewSession:j,controlRef:w,onNewSessionContextChange:P,initialSessionId:K,initialSessionLinked:er,skipInitialProjectSelection:eb,onInitialRestoreDone:ek,refreshKey:eS,onSessionDeleted:eC,selectedCwd:eE,onCwdChange:eI,onOpenFile:eT,onOpenTerminal:e$,onOpenGitGraph:eM,explorerRefreshKey:eR,onExplorerRefresh:eL,onAtMention:eA,onAtMentions:eP,onBackgroundTaskDone:ez,onRunningSessionIdsChange:eF,onSessionsChange:eB}=e,{t:eq}=(0,eO.s)(),eJ=(0,eD.a)(),[eG,eY]=(0,i.useState)([]),eX=(0,i.useRef)(null),eQ=(0,i.useRef)(0),[e0,e1]=(0,i.useState)(!0),[e2,e4]=(0,i.useState)(!1),[e8,e3]=(0,i.useState)(null),[e9,e7]=(0,i.useState)(null),[te,tt]=(0,i.useState)(""),[tn,tr]=(0,i.useState)(!1),[ti,ts]=(0,i.useState)(nD),[to,ta]=(0,i.useState)(null),[tl,tc]=(0,i.useState)(!1),[td,tu]=(0,i.useState)(null),tp=(0,i.useRef)(null),[th,tf]=(0,i.useState)(null),[tm,tg]=(0,i.useState)(null),tx=(0,i.useRef)(null);tx.current??=new Set(ex());let[tv,tj]=(0,i.useState)(0),[tk,tS]=(0,i.useState)(!1),[tC,tN]=(0,i.useState)(!1),[tE,tI]=(0,i.useState)(!1),[tT,tW]=(0,i.useState)(""),[tq,tV]=(0,i.useState)(0),[t8,t6]=(0,i.useState)(!0),[t9,t7]=(0,i.useState)(!1),[ne,nt]=(0,i.useState)(!1),[nn,nr]=(0,i.useState)(null),[ni,ns]=(0,i.useState)(null),[no,na]=(0,i.useState)(()=>new Set),[nl,nc]=(0,i.useState)(()=>new Set),[nd,nu]=(0,i.useState)(()=>(function(){try{return nF(window.localStorage.getItem(nz))}catch{return new Set}})()),np=(0,i.useRef)(new Set),nh=(0,i.useRef)(new Set),nf=(0,i.useRef)(new Set),nm=(0,i.useRef)(!1),ng=(0,i.useRef)(null),nx=(0,i.useRef)(null),nv=(0,i.useRef)(null),nb=eW(),nj=!eJ&&"below"===nb,[nk,nw]=(0,i.useState)("sessions"),[nS,nC]=(0,i.useState)(!1),nI=(0,i.useRef)(null),nT=(0,i.useRef)(null),nM=(0,i.useRef)(null),nR=(0,i.useRef)(null),nq=(0,i.useRef)(new WeakMap),[nK,nV]=(0,i.useState)({}),[nZ,nJ]=(0,i.useState)(()=>new Set),[nG,nY]=(0,i.useState)({}),[nX,nQ]=(0,i.useState)(!1),[n0,n1]=(0,i.useState)([]),[n2,n4]=(0,i.useState)(!1),{phase:n8,start:n5,end:n6}=eZ(),{phase:n3,start:n9,end:n7}=eZ(),re=(0,i.useRef)(nS);re.current=nS;let rt=(0,i.useRef)(n2);rt.current=n2;let rn=(0,i.useCallback)(e=>{e!==rt.current&&n9(e?"in":"out"),n4(e)},[n9]),rr=(o=nS&&"out"===n8,l=!nS&&"in"===n8,{bodyHidden:nS&&!o,bodyInert:o,moving:o||l,open:!nS&&!l}),ri=(d=n2&&"in"===n3,u=!n2&&"out"===n3,{mainHidden:n2&&!d,mainInert:d,archiveMounted:n2||u,archiveInert:u,archiveClass:d?"is-entering":u?"is-leaving":null}),[rs,ro]=(0,i.useState)(null),[ra,rl]=(0,i.useState)(null),[rc,rd]=(0,i.useState)(null),[ru,rp]=(0,i.useState)(null),[rh,rf]=(0,i.useState)(null),rm=(0,i.useRef)(0),rg=(0,i.useCallback)(e=>{rf(t=>t?.id===e?null:t)},[]),[rx,rv]=(0,i.useState)(null),rb=(0,i.useCallback)(e=>{rv(t=>t?.id===e?null:t)},[]),ry=(0,i.useRef)(b);ry.current=b;let[rj,rk]=(0,i.useState)(null),rw=(0,i.useRef)(0),rS=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2?arguments[2]:void 0;rw.current+=1,rk({id:rw.current,message:e,...n?{tail:n}:{},actions:t})},[]),[rC,rN]=(0,i.useState)(0),rE=(0,i.useRef)(0),rI=(0,i.useRef)(null),[rT,r$]=(0,i.useState)(0),rM=(0,i.useRef)(null),rR=(0,i.useRef)(null),rL=(0,i.useRef)(null),rA=(0,i.useRef)(null),[rP,rz]=(0,i.useState)(0),rW=(0,i.useCallback)(e=>{rA.current=e,rz(e=>e+1)},[]);(0,i.useEffect)(()=>{let e=rA.current;rA.current=null,e&&eN(document,e())},[rP]);let{state:rO,loaded:rD,synced:rF,error:rB,apply:rH,snapshot:rU,noteRevision:r_}=function(){let[e,t]=(0,i.useState)($),[n,r]=(0,i.useState)(!1),[s,o]=(0,i.useState)(!1),[a,l]=(0,i.useState)(null),c=(0,i.useRef)(e),d=(0,i.useRef)(e),u=(0,i.useRef)([]),p=(0,i.useRef)(Promise.resolve()),h=(0,i.useRef)(0),f=(0,i.useRef)(null),m=(0,i.useCallback)(()=>{let e=c.current;for(let{request:t,now:n}of u.current)e=function(e,t,n){var r,i,s,o;let a=function(e){let t={};for(let[n,r]of Object.entries(e.sessions))t[n]={...r};let n={};for(let[t,r]of Object.entries(e.projects))n[t]={...r};let r={...e,sessions:t,projects:n};return e.projectOrder&&(r.projectOrder=[...e.projectOrder]),e.projectNames&&(r.projectNames={...e.projectNames}),r}(e),l=!1;switch(t.action){case"set":for(let e of t.ids){let r=x(a.sessions,e)?a.sessions[e]:void 0;M(a.sessions,e,function(e,t,n){let r={...e};return"pinned"in t?t.pinned?(void 0===r.pinnedAt||void 0!==r.archivedAt)&&(r.pinnedAt=n,delete r.archivedAt):delete r.pinnedAt:t.archived?(r.archivedAt=n,delete r.pinnedAt):delete r.archivedAt,r}(r,t,n))&&(l=!0)}break;case"restore":for(let e of t.entries){let t={};null!==e.pinnedAt&&(t.pinnedAt=e.pinnedAt),null!==e.archivedAt&&(t.archivedAt=e.archivedAt),M(a.sessions,e.id,t)&&(l=!0)}break;case"pin-project":{let{projectKey:e,root:o}=t,c=x(a.projects,e)?a.projects[e]:void 0;if(t.pinned?c?.root!==o&&(a.projects[e]={pinnedAt:n,root:o},l=!0):c&&(delete a.projects[e],l=!0),(t.pinned?void 0===c:void 0!==c)&&a.projectOrder){let n,o,c=(r=a.projectOrder,i=a.projects,s=t.pinned,o=r.filter(t=>t!==e),s?(n=0,o.forEach((e,t)=>{x(i,e)&&(n=t+1)})):(n=o.findIndex(e=>!x(i,e)))<0&&(n=o.length),o.splice(n,0,e),o);N(c.length,C(c))&&R(a,c)&&(l=!0)}break}case"add-projects":R(a,function(e,t){let n=L(e,t),r=e.length,i=C(e),s=n.length;for(;s>0;){let e=S(n[s-1]);if(!N(r+1,i+e))break;r++,i+=e,s--}return[...n.slice(s),...e]}(a.projectOrder??[],t.keys))&&(l=!0);break;case"move-project":{let e,n,{projectKey:r,anchorKey:i,position:s,add:c}=t,d=a.projectOrder??[];R(a,function(e,t){let n=e.length,r=C(e);if(N(n,r))return e;let i=new Set;for(let s=e.length-1;s>=0&&!N(n,r);s--)t.has(e[s])||(i.add(s),n--,r-=S(e[s]));let s=e.filter((e,t)=>!i.has(t));return N(n,r)?s:E(s)}((o=[...L(d,c),...d],(e=o.filter(e=>e!==r)).includes(i)||e.unshift(i),n=e.indexOf(i),e.splice("before"===s?n:n+1,0,r),e),new Set([r,i,...c])))&&(l=!0);break}case"rename-project":{let e=k(t.name);void 0!==e&&function(e,t,n){let r={...e.projectNames};if((x(r,t)?r[t]:void 0)===(n??void 0))return!1;if(null===n)delete r[t];else if(r[t]=n,!T(Object.keys(r).length,function(e){let t=1;for(let[n,r]of Object.entries(e))t+=I(n,r);return t}(r)))return!1;return 0===Object.keys(r).length?delete e.projectNames:e.projectNames=r,!0}(a,t.projectKey,e)&&(l=!0)}}return{state:a,changed:l}}(e,t,n).state;d.current=e,t(e)},[]),g=(0,i.useCallback)(async e=>{let t=++h.current;f.current=t;try{let n=await fetch(e_,{cache:"no-store"}),i=await eV(n);if(t!==h.current)return;c.current=i,m(),e||l(null),r(!0),o(!0)}catch(e){if(t!==h.current)return;l(eK(e)),r(!0)}finally{f.current===t&&(f.current=null)}},[m]),v=(0,i.useCallback)(()=>g(!1),[g]),b=(0,i.useCallback)(e=>{"number"!=typeof e||!Number.isFinite(e)||u.current.length>0||e===c.current.revision||(null===f.current||f.current!==h.current)&&v()},[v]),y=(0,i.useCallback)(e=>{let t={request:e,now:Date.now()};u.current=[...u.current,t],m();let n=async()=>{let n=!1;try{let t=await fetch(e_,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store"}),i=await eV(t);h.current++,c.current=i,l(null),r(!0),o(!0),n=!0}catch(e){l(eK(e))}return u.current=u.current.filter(e=>e!==t),m(),n||await g(!0),n},i=p.current.then(n,n);return p.current=i,i},[g,m]),j=(0,i.useCallback)(e=>(function(e,t){let n=new Set,r=[];for(let i of t){if(n.has(i))continue;n.add(i);let t=x(e.sessions,i)?e.sessions[i]:void 0;r.push({id:i,pinnedAt:t?.pinnedAt??null,archivedAt:t?.archivedAt??null})}return r})(d.current,e),[]);return(0,i.useEffect)(()=>{v()},[v]),(0,i.useMemo)(()=>({state:e,loaded:n,synced:s,error:a,refresh:v,noteRevision:b,apply:y,snapshot:j}),[e,n,s,a,v,b,y,j])}(),rq=(0,i.useRef)(null),rK=(0,i.useRef)(null);eU(rK);let rV=(0,i.useRef)(null),rZ=(0,i.useRef)(null),rJ=(0,i.useRef)(320),rG=(0,i.useCallback)(()=>{let e=rZ.current,t=rq.current;return e&&t&&0!==e.clientHeight?e.clientHeight-t.offsetHeight:window.innerHeight-36},[]),rY=(0,i.useCallback)(()=>Math.round(.45*rG()),[rG]),rX=(0,i.useCallback)(()=>rG()-120,[rG]),rQ=eH({ariaLabel:eq("sidebar.resizeFiles"),axis:"vertical",cssVariable:"--sidebar-files-height",defaultWidth:320,getDefaultWidth:rY,getMaxWidth:rX,growthDirection:"up",maxWidth:2e3,minWidth:220,persistClamp:!1,storageKey:"pi-web:sidebar-files-height",widthRef:rJ}),r0=rQ.panelRef,r1=(0,i.useCallback)(e=>{rZ.current=e,r0.current=e},[r0]),r2=rQ.reclampWidth;(0,i.useEffect)(()=>{let e=rZ.current;if(!nj||!e||"u"<typeof ResizeObserver)return;let t=new ResizeObserver(()=>r2());return t.observe(e),()=>t.disconnect()},[r2,nj]),(0,i.useEffect)(()=>{let e=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:eh();if(!e)return"sessions";try{return"files"===e.getItem(ei)?"files":"sessions"}catch{return"sessions"}}();"sessions"!==e&&nw(e);let t=function(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:eh();if(!t)return{};try{let e=t.getItem(es);if(null!==e)return ef(JSON.parse(e))}catch{return{}}try{let n=t.getItem(eo);if(null===n)return{};e=ef(JSON.parse(n))}catch{e={}}let n=Object.fromEntries(Object.entries(e).filter(e=>{let[,t]=e;return!t}));return em(n,t),n}();Object.keys(t).length>0&&nV(t),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:eh();if(!e)return!1;try{return"true"===e.getItem(el)}catch{return!1}}()&&nQ(!0);let n=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:eh();if(!e)return[];try{let t=e.getItem(ea),n=null===t?[]:JSON.parse(t);if(!Array.isArray(n))return[];let r=n.filter(e=>"string"==typeof e&&""!==e);return[...new Set(r)].slice(-300)}catch{return[]}}();n.length>0&&n1(n),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:eh();if(!e)return!1;try{return"true"===e.getItem(ed)}catch{return!1}}()&&nC(!0),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:eh();if(!e)return!1;try{return"true"===e.getItem(ec)}catch{return!1}}()&&t7(!0),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:eh();if(e)for(let t of ep)try{e.removeItem?.(t)}catch{}}()},[]);let r4=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=++eQ.current;try{e&&e1(!0);let i=await fetch(n?"/api/sessions?summary=1":t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json();if(r!==eQ.current)return;eX.current=s.sessionListVersion,eY(s.sessions),n||e4(!0),nm.current||(nh.current=new Set(s.completionNotificationSuppressedSessionIds??[]),na(e=>nB(e,s.runningSessionIds??[])),nc(e=>nB(e,s.awaitingInputSessionIds??[])));let o=new Set(s.sessions.filter(e=>e.relation?.kind!=="subagent").map(e=>e.id));nu(e=>{if(0===e.size)return e;let t=new Set([...e].filter(e=>o.has(e)));return t.size===e.size?e:t}),e3(null)}catch(e){r===eQ.current&&e3(String(e))}finally{r===eQ.current&&e1(!1)}},[]),r8=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!r8.current;r8.current=!0;let t=!0;return e?r4(!0,!1,!0).then(()=>{t&&(ng.current=setTimeout(()=>{ng.current=null,t&&r4(!1,!0)},750))}):r4(),()=>{t=!1,ng.current&&(clearTimeout(ng.current),ng.current=null)}},[r4,eS]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/open-in-explorer").then(e=>e.ok?e.json():null).then(t=>{!e&&t&&nr(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{ns(null)},[e9,eE]);let r5=(0,i.useCallback)(async()=>{let e=e9??eE;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 ns(null),!1;let n=await t.json().catch(()=>({}));ns(n.error??`HTTP ${t.status}`)}catch(e){ns(e instanceof Error?e.message:String(e))}return!0},[e9,eE]),r6=eq(nn?.platform==="darwin"?"sidebar.openInFinder":nn?.platform==="win32"?"sidebar.openInExplorer":"sidebar.openInFileManager"),r3=nn?.supported===!1,r9=ni?eq(nA[ni]??ni):null;(0,i.useEffect)(()=>{try{0===nd.size?window.localStorage.removeItem(nz):window.localStorage.setItem(nz,JSON.stringify([...nd]))}catch{}},[nd]),(0,i.useEffect)(()=>{let e=e=>{(null===e.key||e.key===nz)&&nu(t=>nB(t,[...nF(e.newValue)]))};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[]),(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let s=new AbortController;n?.abort(),n=s;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:s.signal});if(!t.ok)return;let r=await t.json();if(e||n!==s)return;nm.current=!0,nh.current=new Set(r.completionNotificationSuppressedSessionIds??[]),na(e=>nB(e,r.runningSessionIds??[])),nc(e=>nB(e,r.awaitingInputSessionIds??[])),r_(r.sessionUiStateRevision),r.sessionListVersion!==eX.current&&await r4()}catch{}finally{n===s&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},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)}},[r4,r_]),(0,i.useEffect)(()=>{eF?.(no)},[eF,no]),(0,i.useEffect)(()=>{eB?.(eG)},[eG,eB]),(0,i.useEffect)(()=>{let e=np.current,t=[...e].filter(e=>!no.has(e)&&e!==b),n=new Set(eG.filter(e=>e.relation?.kind==="subagent").map(e=>e.id)),r=t.filter(e=>!nf.current.has(e)&&!n.has(e)),i=[...no].filter(t=>!e.has(t));(r.length>0||i.length>0)&&nu(e=>{let t=new Set(e);return no.forEach(e=>t.delete(e)),r.forEach(e=>t.add(e)),t});let s=i.some(e=>!eG.some(t=>t.id===e));(t.length>0||s)&&r4(),r.length>0&&ez?.(),np.current=no,nf.current=new Set([...no].filter(e=>nh.current.has(e)||n.has(e)))},[no,b,eG,r4,ez]),(0,i.useEffect)(()=>{b&&nu(e=>{if(!e.has(b))return e;let t=new Set(e);return t.delete(b),t})},[b]),(0,i.useEffect)(()=>{void 0!==eR&&tj(e=>e+1)},[eR]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&tt(e.home)}).catch(()=>{})},[]);let r7=(0,i.useRef)(!1),ie=(0,i.useCallback)(e=>e?function(e,t){let{validated:n,listing:r,sessions:i}=t;if(n?.cwd===e)return{root:n.root,key:n.key};if(r?.forCwd===e||r?.isTopLevel&&r.worktrees.some(t=>t.path===e))return{root:r.projectRoot,key:r.projectKey};let s=i.find(t=>t.cwd===e||(t.projectRoot??t.cwd)===e);return s?{root:s.projectRoot??s.cwd,key:f(s)}:{root:e,key:e}}(e,{validated:td,listing:th,sessions:eG}):null,[td,th,eG]),it=(0,i.useMemo)(()=>ie(e9),[ie,e9]),ir=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=ie(e9),t=ir.current;(t?.cwd!==e9||t.key!==(e?.key??null))&&(ir.current={cwd:e9,key:e?.key??null},eI?.(e9,e?.root??null,e?.key??null))},[e9,eI,ie]);let ii=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!eE){ii.current=null;return}eE!==ii.current&&(ii.current=eE,e7(eE))},[eE]);let[is,io]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!e9){tf(null),tg(null);return}let e=!1;return tg(e9),fetch(`/api/worktrees?cwd=${encodeURIComponent(e9)}`).then(e=>e.json()).then(t=>{if(!e){if(tg(null),t.error||!t.projectRoot)return void tf(null);t.isGit?tx.current?.delete(e9):tx.current?.add(e9),function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:eh();if(!n||!e)return;let r=ex(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(eu,JSON.stringify(s.slice(-50)))}catch{}}(e9,!!t.isGit),tf({forCwd:e9,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||(tg(null),tf(null))}),()=>{e=!0}},[e9,is,eS]),(0,i.useEffect)(()=>{if(0!==eG.length&&!eb&&null===e9){if(K&&!r7.current){r7.current=!0;let e=eG.find(e=>e.id===K);if(e){e7(e.cwd),y(e,!0);return}ek?.(),er&&rS(eq("sidebar.sessionNotFound"))}let e=m(eG);e.length>0&&e7(e[0].root)}},[eG,e9,K,er,eb,y,ek,rS,eq]);let ia=th?th.worktrees.find(e=>e.path===e9)??(th.forCwd===e9&&th.currentWorktreePath?th.worktrees.find(e=>e.path===th.currentWorktreePath):void 0)??th.worktrees.find(e=>e.isMain):void 0,il=ia?.path??null,ic=(0,i.useCallback)(async function(e){let{remember:t=!0,purpose:n=tn}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=(e??ti).trim();if(r&&!tl){tc(!0),ta(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r})}),s=await e.json().catch(()=>({}));if(!e.ok||s.error||!s.cwd||!s.projectRoot||!s.projectKey)return void ta(s.error??`HTTP ${e.status}`);if(t){var i=s.cwd;try{window.localStorage.setItem(nW,i)}catch{}ts(s.cwd)}if(tr(!1),"new-session"===n){let e=rR.current,t=rL.current;rR.current=null,rL.current=null,e?.({cwd:s.cwd,projectKey:s.projectKey,projectRoot:s.projectRoot}),rW(()=>t?.isConnected?t:null);return}tu({cwd:s.cwd,root:s.projectRoot,key:s.projectKey}),e7(s.cwd)}catch(e){ta(e instanceof Error?e.message:String(e))}finally{tc(!1)}}},[tn,ti,tl,rW]),id=(0,i.useCallback)(()=>{tr("files"),ta(null)},[]),iu=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"files";try{let t=await fetch("/api/default-cwd",{method:"POST"}),n=await t.json();n.cwd&&await ic(n.cwd,{remember:!1,purpose:e})}catch{}},[ic]),ip=(0,i.useRef)(iu);ip.current=iu;let ih=(0,i.useCallback)(async(e,t)=>{try{let n=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e.root,branch:t})}),r=await n.json().catch(()=>({}));if(!n.ok||r.error||!r.path)return{error:r.error??`HTTP ${n.status}`};let i=r.path;return tf(n=>n&&n.projectKey===e.key&&!n.worktrees.some(e=>e.path===i)?{...n,worktrees:[...n.worktrees,{path:i,branch:t,isMain:!1}]}:n),io(e=>e+1),{path:i}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},[]),im=(0,i.useCallback)(async(e,t,n)=>{try{let r=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e.root,path:t,force:n})}),i=await r.json().catch(()=>({}));if(!r.ok){if(i.dirty&&!n)return"dirty";return{error:i.error??`HTTP ${r.status}`}}return il===t&&e7(e.root),io(e=>e+1),"removed"}catch(e){return{error:e instanceof Error?e.message:String(e)}}},[il]),ig=(0,i.useCallback)(()=>io(e=>e+1),[]),ix=(0,i.useCallback)(e=>{let{cwd:t,projectKey:n,projectRoot:r}=e;n&&r&&tu({cwd:t,root:r,key:n}),e7(t)},[]),iv=(0,i.useCallback)((e,t,n,r)=>{eY(t=>t.some(t=>t.id===e.id)?t:[e,...t]),e.cwd&&e7(e.cwd),y(e,!1,t,n,r)},[y]),ib=(0,i.useCallback)(e=>{let{cwd:t,projectKey:n,projectRoot:r,carryComposer:i}=e;n&&r&&tu({cwd:t,root:r,key:n}),e7(t),j?.("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)},[j]),iy=(0,i.useRef)(ib);iy.current=ib,(0,i.useImperativeHandle)(w,()=>({startNewSessionIn:e=>iy.current(e),openFolderForNewSession:(e,t)=>{rR.current=e,rL.current=t,ta(null),tr("new-session")},openDefaultDirectoryForNewSession:e=>{rR.current=e,rL.current=null,ip.current("new-session")},refreshWorktrees:ig,createWorktree:ih}),[ih,ig]);let ij=(0,i.useCallback)(()=>{e9&&ib({cwd:e9})},[e9,ib]),ik=(0,i.useMemo)(()=>m(eG),[eG]),iw=(0,i.useMemo)(()=>a(eG),[eG]),iS=(0,i.useMemo)(()=>new Map(iw.map(e=>[e.root.id,e])),[iw]),iC=(0,i.useMemo)(()=>{let e=new Set,t=new Map;for(let n of iw){if(!H(n,rO,no))continue;for(let t of F(n))e.add(t);let r=f(n.root);t.set(r,(t.get(r)??0)+1)}return{ids:e,countByProject:t}},[iw,rO,no]),iN=(0,i.useMemo)(()=>(function(e,t,n){let r=new Map;for(let i of e){let e=f(i);if(!e)continue;let s=r.get(e);s||(s={running:0,unread:0},r.set(e,s)),t.has(i.id)&&s.running++,n.has(i.id)&&s.unread++}return r})(0===iC.ids.size?eG:eG.filter(e=>!iC.ids.has(e.id)),no,nd),[eG,iC,no,nd]),iE=!!(th?.isGit&&th.isTopLevel&&e9&&it?.key===th.projectKey),iI=e9&&th?.isGit&&it?.key===th.projectKey&&!iE?{label:eq("sidebar.openRepoRoot"),title:eq("sidebar.openRepoRootTitle")}:null,iT=!!(e9&&tm===e9),i$=iI??(!iT||iE||e9&&tx.current?.has(e9)?null:{label:eq("sidebar.worktrees"),title:eq("sidebar.checkingWorktrees")}),iM=it?.key??null,iR=it?.root??null,iL=(0,i.useMemo)(()=>iM&&iR?{key:iM,root:iR}:null,[iM,iR]),iA=(0,i.useMemo)(()=>0===nZ.size?nK:Object.fromEntries([...[...nZ].filter(e=>!Object.hasOwn(nK,e)).map(e=>[e,!0]),...Object.entries(nK)]),[nK,nZ]),iP=(0,i.useMemo)(()=>(function(e){let{uiState:t,runningIds:n,currentProject:r}=e,i=a(e.sessions),s=Z(t,r),o=0,l=[],c=new Map,d=new Map,u=new Set;for(let e of i){if(H(e,t,n)){o++;continue}s.noteFamily(e);let r=V(e),i=function(e){let t=Date.parse(e);return Number.isNaN(t)?-1/0:t}(e.latestModified);if(d.set(r,Math.max(d.get(r)??-1/0,i)),e.root.transient||u.add(r),U(e,t,n)){l.push(e);continue}let a=c.get(r);a?a.push(e):c.set(r,[e])}let p=[];if(l.length>0){let r=e=>O(W(t,e.root.id)?.pinnedAt)??0,i=l.map((e,t)=>({family:e,index:t})).sort((e,t)=>D(r(e.family),r(t.family))||e.index-t.index).map(e=>{let{family:t}=e;return t}),o=0,a=0;for(let t of i)B(t,n)&&o++,B(t,e.unreadIds)&&a++;if(p.push({kind:"pinned-header",key:"pinned-header",count:i.length,collapsed:e.pinnedCollapsed,running:o,unread:a}),!e.pinnedCollapsed){let{visible:t,revealed:n,nextShown:r}=G(i,8,Y(e.moreShown,z),e);for(let n of t)p.push(J(n,"pinned",s.get(V(n)),e,null));let o=Q(i.length,t.length,n);o&&p.push({kind:"pinned-more",key:"pinned-more",...o,nextShown:r})}p.push({kind:"spacer",key:"pinned-spacer"})}let h=[...c.keys()],f=new Set(h),m=e=>{f.has(e)||(f.add(e),h.push(e))};for(let e of(r&&m(r.key),Object.keys(t.projects)))m(e);let g=h.map(e=>s.get(e)),x=new Map;(t.projectOrder??[]).forEach((e,t)=>{x.has(e)||x.set(e,t)});let v=e=>e.pinned||u.has(e.key),b=(e,t)=>[...e.filter(e=>{let{project:t}=e;return!x.has(t.key)}).sort((e,n)=>Number(v(e.project))-Number(v(n.project))||t(e,n)),...e.filter(e=>{let{project:t}=e;return x.has(t.key)}).sort((e,t)=>(x.get(e.project.key)??0)-(x.get(t.project.key)??0))].map(e=>{let{project:t}=e;return t}),y=e=>d.get(e.key)??(e.current?1/0:-1/0),j=e=>O(t.projects[e.key]?.pinnedAt)??0,k=g.map((e,t)=>({project:e,index:t})),w=b(k.filter(e=>{let{project:t}=e;return t.pinned}),(e,t)=>D(j(t.project),j(e.project))||e.index-t.index),S=b(k.filter(e=>{let{project:t}=e;return!t.pinned}),(e,t)=>D(y(e.project),y(t.project))||e.index-t.index),C=[...w,...S],N=e=>e.filter(e=>!x.has(e.key)).map(e=>e.key),E={pinned:N(w),other:N(S)},I=C.filter(e=>!x.has(e.key)&&v(e)).map(e=>e.key);for(let t of C){let r=c.get(t.key)??[],i=q(t,e.groupExpansion),s=0,o=0;for(let t of r)B(t,n)&&s++,B(t,e.unreadIds)&&o++;if(p.push({kind:"group",key:`group:${t.key}`,project:t,expanded:i,running:s,unread:o}),i)if(0===r.length)p.push({kind:"group-empty",key:`empty:${t.key}`,project:t});else{let{visible:n,revealed:i,nextShown:s}=G(r,6,Y(e.moreShown,t.key),e);for(let r of n)p.push(J(r,"group",t,e,null));let o=Q(r.length,n.length,i);o&&p.push({kind:"group-more",key:`more:${t.key}`,projectKey:t.key,...o,nextShown:s})}}return C.length>0&&p.push({kind:"spacer",key:"footer-spacer"}),p.push({kind:"footer-open",key:"footer-open"}),o>0&&p.push({kind:"footer-archived",key:"footer-archived",count:o}),{rows:p,projects:C,archivedCount:o,unorderedKeysByBand:E,projectKeysToRecord:I}})({sessions:eG,uiState:rO,runningIds:no,awaitingIds:nl,unreadIds:nd,selectedSessionId:b,currentProject:iL,groupExpansion:iA,moreShown:nG,pinnedCollapsed:nX}),[eG,rO,no,nl,nd,b,iL,iA,nG,nX]),iz=ri.archiveMounted,iW=(0,i.useMemo)(()=>new Set(n0),[n0]),iO=(0,i.useMemo)(()=>iz?function(e){let{uiState:t,runningIds:n}=e,r=Z(t,e.currentProject),i=new Map;for(let s of a(e.sessions)){if(!H(s,t,n))continue;r.noteFamily(s);let e=O(W(t,s.root.id)?.archivedAt)??0,o=V(s),a=i.get(o);a?(a.families.push({family:s,archivedAt:e}),a.newest=Math.max(a.newest,e)):i.set(o,{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)=>D(e.group.newest,t.group.newest)||e.index-t.index)){let i=r.get(t),o=!e.collapsed?.has(t);if(s.push({kind:"archive-group",key:`archive:${t}`,project:i,count:n.families.length,expanded:o}),o)for(let{family:t,archivedAt:r}of n.families.map((e,t)=>({...e,index:t})).sort((e,t)=>D(e.archivedAt,t.archivedAt)||e.index-t.index))s.push(J(t,"archive",i,e,r))}return s}({sessions:eG,uiState:rO,runningIds:no,awaitingIds:nl,unreadIds:nd,selectedSessionId:b,currentProject:iL,collapsed:iW}):[],[iz,eG,rO,no,nl,nd,b,iL,iW]),iD=(0,i.useMemo)(()=>iO.flatMap(e=>"archive-group"===e.kind?[e]:[]),[iO]),iF=(0,i.useMemo)(()=>new Map(iP.projects.map(e=>[e.key,e])),[iP.projects]),iB=(0,i.useRef)(new Set),iH=iP.projectKeysToRecord,iU=rO.projectOrder?.length??0;(0,i.useEffect)(()=>{if(e0||!rF||!e2||iU>=1e3)return;let e=iB.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)}(iH,e);if(0!==t.length){for(let n of t)e.add(n);rH({action:"add-projects",keys:t})}},[rH,e0,iH,e2,iU,rF]);let i_=rO.projectNames,iq=(0,i.useMemo)(()=>(function(e,t,n){let r=new Set,i=[];for(let s of[...e,...t])r.has(s.key)||(r.add(s.key),i.push(ew(s,n)));return i})(iP.projects,ik,i_),[iP.projects,ik,i_]),iK=(0,i.useMemo)(()=>{if(!e9||!it)return null;let e=iE&&null!==th;return{cwd:e9,project:ew(it,i_),worktrees:e?th.worktrees.map(e=>{let{path:t,branch:n,isMain:r}=e;return{path:t,branch:n,isMain:r}}):null,currentWorktreePath:e?il:null,projects:iq}},[e9,it,iE,th,il,iq,i_]),iV=(0,i.useRef)(iK);iV.current=iK;let iZ=iK?JSON.stringify([iK.cwd,iK.project.key,iK.project.root,iK.project.alias??null,iK.currentWorktreePath,iK.worktrees?.map(e=>[e.path,e.branch,e.isMain])??null,iK.projects.map(e=>[e.key,e.root,e.alias??null])]):"";(0,i.useEffect)(()=>{P?.(iV.current)},[iZ,P]);let iJ=(0,i.useRef)(iM);(0,i.useLayoutEffect)(()=>{let e=iJ.current;if(iJ.current=iM,null===e||e===iM)return;let t=iF.get(e);nJ(e=>!t||t.current||t.pinned||e.has(t.key)||Object.hasOwn(nK,t.key)?e:new Set(e).add(t.key))},[iM,nK,iF]);let iG=(0,i.useCallback)((e,t)=>{nV(e),em(e),nJ(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)),nY(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))},[]),iY=(0,i.useCallback)(()=>(nM.current?.hidden?nT:nI).current??rV.current,[]),iX=(0,i.useCallback)(e=>{let t=nM.current;for(let n of["pinned","group","archive"]){let r=CSS.escape(`session:${n}:${e}`),i=t?.querySelector(`[data-row-key="${r}"] .session-tree-main`);if(i&&i.getClientRects().length>0)return i}return iY()},[iY]),iQ=(0,i.useCallback)(e=>{let t=CSS.escape(`group:${e}`),n=nM.current?.querySelector(`[data-row-key="${t}"] .session-tree-group-toggle`);return n&&n.getClientRects().length>0?n:iY()},[iY]),i0=(0,i.useCallback)(async e=>{let t=await rH(e);return t||rN(e=>e+1),t},[rH]);(0,i.useEffect)(()=>{rC!==rE.current&&(rE.current=rC,rS(eq("sidebar.uiStateFailed",{error:rB??""})))},[rC,rB,rS,eq]);let i1=(0,i.useCallback)((e,t,n)=>{let r=iF.get(e),i=iF.get(t);r&&i&&r!==i&&r.pinned===i.pinned&&(i0({action:"move-project",projectKey:e,anchorKey:t,position:n,add:iP.unorderedKeysByBand[r.pinned?"pinned":"other"].slice(-500)}),rm.current+=1,rf({id:rm.current,at:Date.now(),rowKey:`group:${e}`}))},[i0,iP.unorderedKeysByBand,iF]),i2=(0,i.useCallback)(e=>{nj||(nw(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eh();if(t)try{t.setItem(ei,e)}catch{}}(e))},[nj]),i4=(0,i.useCallback)(e=>{e!==re.current&&n5(e?"out":"in"),nC(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eh();if(t)try{t.setItem(ed,String(e))}catch{}}(e)},[n5]),i8=(0,i.useCallback)(e=>{let t=e.target;t instanceof Element&&nq.current.set(t,t.scrollTop)},[]);(0,i.useLayoutEffect)(()=>{for(let e of[nM.current,nR.current])if(e&&!e.hidden)for(let t of e.querySelectorAll(".session-tree-scroll, .sidebar-files-scroll")){let e=nq.current.get(t);void 0!==e&&t.scrollTop!==e&&(t.scrollTop=e)}},[nk,n2,nj,nS]);let i5=(0,i.useCallback)(e=>{if(rp(null),rn(!0),tI(!1),i2("sessions"),void 0!==e){if(n0.includes(e)){let t=n0.filter(t=>t!==e);n1(t),eg(t)}rm.current+=1,rv({id:rm.current,at:Date.now(),rowKey:`archive:${e}`,block:"start"})}},[n0,rn,i2]),i6=(0,i.useRef)(null),i3=(0,i.useRef)(n2),i9=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(i3.current===n2)return;if(i3.current=n2,n2)return void nU(i6.current);let e=nM.current?.querySelector('[data-row-key="footer-archived"] button'),t=e&&e.getClientRects().length>0?e:iY();nU(t),t&&document.activeElement===t&&(i9.current=t)},[n2,iY]);let i7=(0,i.useRef)(null),se=(0,i.useRef)(nj);(0,i.useLayoutEffect)(()=>{if(se.current===nj)return;se.current=nj;let e=i7.current;e&&(!e.isConnected||0===e.getClientRects().length)&&nU(iY())},[nj,iY]);let st=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"===nk?"files":"sessions";i2(t),("sessions"===t?nI:nT).current?.focus()},sn=(0,i.useCallback)((e,t)=>{i0({action:"set",ids:[e.root.id],pinned:t})},[i0]),sr=(0,i.useCallback)((e,t)=>{nu(n=>{let r=new Set(n);if(t)for(let t of F(e))r.delete(t);else r.add(e.root.id);return r})},[]),si=(0,i.useCallback)(e=>{0!==e.length&&nu(t=>{let n=new Set(t);for(let t of e)t!==ry.current&&n.add(t);return n.size===t.size?t:n})},[]),ss=(0,i.useCallback)(e=>{let t=e.filter(e=>!e.root.transient);if(0===t.length)return;let n=rU(t.map(e=>e.root.id)),r=t.flatMap(e=>F(e)),i=r.filter(e=>nd.has(e));for(let e of A(t))i0({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=>F(e)));si(i.filter(e=>n.has(e)))});i.length>0&&nu(e=>{let t=new Set(e);for(let e of r)t.delete(e);return t}),rS(1===t.length?eq("sidebar.archivedToast",{title:nH(t5(t[0].root),28)}):eq("sidebar.archivedManyToast",{count:t.length}),[{id:"undo",label:eq("sidebar.undo"),onClick:()=>{for(let e of A(n))i0({action:"restore",entries:e});si(i),rW(()=>iX(t[0].root.id))}},{id:"view",label:eq("sidebar.viewArchive"),onClick:()=>i5()}])},[i0,rW,iX,i5,si,rS,rU,eq,nd]),so=(0,i.useCallback)(e=>{F(e).some(e=>no.has(e))||ss([e])},[ss,no]),sa=(0,i.useCallback)(e=>{if(0===e.length)return;let t=e.map(e=>e.root.id),n=rU(t);for(let e of A(t))i0({action:"set",ids:e,archived:!1});rS(1===e.length?eq("sidebar.restoredToast",{title:nH(t5(e[0].root),28)}):eq("sidebar.restoredManyToast",{count:e.length}),[{id:"undo",label:eq("sidebar.undo"),onClick:()=>{for(let e of A(n))i0({action:"restore",entries:e});rW(()=>iX(e[0].root.id))}}])},[i0,iX,rW,rS,rU,eq]),sl=(0,i.useCallback)(e=>sa([e]),[sa]),sc=(0,i.useCallback)(e=>{e.root.transient||(rd(null),ro(e.root.id))},[]),sd=(0,i.useCallback)(async(e,t)=>{let n=e.root,r=t5(n),i=t.trim();if(ro(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})}),r4()}catch{}},[r4]),su=(0,i.useCallback)(e=>{rl(e.key)},[]),sp=(0,i.useCallback)(e=>{rl(t=>t===e?null:t),rW(()=>iQ(e))},[rW,iQ]),sh=(0,i.useCallback)((e,t)=>{sp(e.key);let n=function(e,t){let n=t.trim();if(n===e.name)return null;let r=""===n||n===_(e.root);return r&&null===e.customName?null:{action:"rename-project",projectKey:e.key,name:r?null:n}}(e,t);n&&i0(n)},[i0,sp]),sf=(0,i.useCallback)(async e=>{let t=e.root;if(!t.transient){rd(e=>e===t.id?null:e);try{await fetch(`/api/sessions/${encodeURIComponent(t.id)}`,{method:"DELETE"}),eC?.(t.id),r4()}catch{}}},[r4,eC]),sm=(0,i.useCallback)((e,t)=>{t?sf(e):(ro(null),rd(e.root.id))},[sf]),sg=(e,t)=>{if(i9.current=null,n2){let e=nM.current?.querySelector(".sidebar-sessions-view .session-tree-scroll");e&&nq.current.delete(e),rn(!1)}let n=f(e);if(Object.hasOwn(iA,n)&&!1===iA[n]){let e={...nK};delete e[n],e[n]=!0,iG(e,[n])}iv(e,void 0,void 0,{keepSidebarOpen:null!==t}),r4();let r=t?`[data-row-key="${CSS.escape(t)}"]`:null;rm.current+=1,rf({id:rm.current,at:Date.now(),rowKey:`session:group:${e.id}`,takeFocusFrom:e=>null!==r&&null!==e.closest(r)||e===i9.current})},sx=(0,i.useRef)(sg);sx.current=sg;let sv=(0,i.useRef)(new Set),sb=(0,i.useCallback)(async e=>{let t=e.family.root;if(t.transient||sv.current.has(t.id))return;sv.current.add(t.id);let n=ry.current;try{var r;let i,s,o=await fetch(`/api/sessions/${encodeURIComponent(t.id)}/fork`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),a=await o.json().catch(()=>({}));if(!o.ok||!a.session){let{key:e,params:t}=function(e,t){switch(e){case"not_found":return{key:"sidebar.forkNotFound"};case"unsaved":return{key:"sidebar.forkUnsaved"};case"empty":return{key:"sidebar.forkEmpty"};case"subagent":case"request-denied":return{key:"sidebar.forkUnavailable"};default:return{key:"sidebar.forkFailed",params:{error:t}}}}(a.code,a.error??`HTTP ${o.status}`);rS(eq(e,t)),"not_found"===a.code&&r4();return}let l=a.session,c=t5(l),{head:d,tail:u}=(r=eq("sidebar.forkedToast",{title:c}),((s=(i=ey(c)?.suffix)?r.lastIndexOf(i):-1)>0?{head:r.slice(0,s),tail:r.slice(s)}:null)??{head:eq("sidebar.forkedToast",{title:nH(c,28)}),tail:void 0});if(ry.current!==n){eY(e=>e.some(e=>e.id===l.id)?e:[l,...e]),nu(e=>new Set(e).add(l.id)),r4(),rS(d,[{id:"open",label:eq("sidebar.open"),onClick:()=>sx.current(l,null)}],u);return}sx.current(l,e.key),rS(d,[],u)}catch(e){rS(eq("sidebar.forkFailed",{error:e instanceof Error?e.message:String(e)}))}finally{sv.current.delete(t.id)}},[r4,rS,eq]),sy=(0,i.useCallback)(e=>{e.root.transient||window.open(c(e.root.id),"_blank","noopener,noreferrer")},[]),sj=(0,i.useCallback)((e,t,n)=>{e.status.transient||rp({kind:"row",row:e,anchor:t,opener:n})},[]),sk=(0,i.useCallback)((e,t)=>{let n=e.family.root;if(n.id===rs||n.id===rc)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:()=>{r4()}})){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?n_(r,"start"):{kind:"point",x:t.clientX,y:t.clientY},s=document.activeElement,o=s instanceof HTMLElement&&null!==r&&r.contains(s);rM.current=!o&&s instanceof HTMLElement&&s!==document.body?s:null,sj(e,i,o?s:null)},[rc,r4,sj,rs]),sw=(0,i.useMemo)(()=>({sessions:eG,uiState:rO,runningIds:no,awaitingIds:nl,unreadIds:nd,selectedSessionId:b}),[eG,rO,no,nl,nd,b]),sS=(0,i.useCallback)((e,t)=>{let n=ee(sw,e.key,6048e5,Date.now()).length;rp({kind:"group",project:e,olderCount:n,anchor:n_(t,"end"),opener:t})},[sw]),sC=(0,i.useCallback)(e=>{ss(ee(sw,e.key,6048e5,Date.now()).flatMap(e=>{let t=iS.get(e);return t?[t]:[]}))},[ss,iS,sw]),sN=(0,i.useCallback)((e,t)=>{rp(n=>n?.kind==="group"&&n.project.key===e?{...n,askDelete:t}:n)},[]),sE=(0,i.useRef)(new Set),sI=(0,i.useCallback)(async(e,t,n)=>{if(rp(null),!(0===t.length||sE.current.has(e))){sE.current.add(e),rS(eq("sidebar.deletingSessions"));try{let e=await ev(t,fetch);for(let t of e.deleted)eC?.(t);if(r4().then(()=>rW(n)),null!==e.error)return void rS(eq("sidebar.deleteFailed",{error:e.error}));let r=e.deletedRoots.length,i=[1===r?eq("sidebar.deletedOneToast"):eq("sidebar.deletedManyToast",{count:r})];e.running.length>0&&i.push(eq("sidebar.keptRunningToast",{count:e.running.length})),rS(i.join(" \xb7 "))}finally{sE.current.delete(e)}}},[rW,r4,eC,rS,eq]),sT=(0,i.useCallback)(e=>{let{ids:t}=et(sw,e.key);sI(`project:${e.key}`,t,()=>iQ(e.key))},[sI,iQ,sw]),s$=(0,i.useCallback)(e=>{let t=null===e?null:CSS.escape(`archive:${e}`),n=null===t?null:nM.current?.querySelector(`[data-row-key="${t}"] .session-tree-group-toggle`);if(n&&n.getClientRects().length>0)return n;let r=i6.current;return r&&r.getClientRects().length>0?r:iY()},[iY]),sM=(0,i.useCallback)(e=>e.flatMap(e=>{let t=iS.get(e);return t?[t]:[]}),[iS]),sR=(0,i.useCallback)((e,t)=>{rp({kind:"archive-group",project:e,anchor:n_(t,"end"),opener:t})},[]),sL=(0,i.useCallback)(e=>{rp(t=>t?.kind==="archive"?null:{kind:"archive",anchor:n_(e,"end"),opener:e})},[]),sA=(0,i.useCallback)(e=>{rp(t=>t?.kind==="archive"?{...t,askDelete:e}:t?.kind==="archive-group"?{...t,askDelete:void 0!==e}:t)},[]),sP=(0,i.useCallback)(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=[];for(let r of a(e.sessions))if((void 0===t.projectKey||V(r)===t.projectKey)&&H(r,e.uiState,e.runningIds)){if(void 0!==t.archivedBefore){let n=O(W(e.uiState,r.root.id)?.archivedAt);if(null===n||n>=t.archivedBefore)continue}n.push(r.root.id)}return n})(sw,"all"===e?{}:"old"===e?{archivedBefore:Date.now()-2592e6}:e),[sw]),sz=(0,i.useCallback)(e=>{let t=sP(e);sI("string"==typeof e?`archive:${e}`:`archive-project:${e.projectKey}`,t,()=>"string"==typeof e?s$(null):s$(e.projectKey))},[sP,s$,sI]),sW=(0,i.useCallback)(e=>{n1(e),eg(e)},[]),sO=(0,i.useCallback)(e=>{let t=iD.map(e=>e.project.key),n=n0.filter(e=>!t.includes(e));sW(e?n:[...n,...t])},[n0,iD,sW]),sD=(0,i.useCallback)((e,t)=>{let n=n0.includes(e);if(t)return void sO(n);let r=n0.filter(t=>t!==e);sW(n?r:[...r,e])},[n0,sW,sO]),sF=(0,i.useCallback)(e=>{rp(null),ib(ej(e,e9))},[e9,ib]),sB=(0,i.useCallback)(()=>rp(null),[]);(0,i.useEffect)(()=>{if(null!==ru)return;let e=rM.current;if(rM.current=null,!e?.isConnected)return;let t=document.activeElement;t&&t!==document.body||e.focus({preventScroll:!0})},[ru]);let sH=n2?iO:iP.rows;(0,i.useEffect)(()=>{ru?.kind!=="row"||sH.some(e=>e.key===ru.row.key)||rp(null),ru?.kind!=="archive-group"||sH.some(e=>e.key===`archive:${ru.project.key}`)||rp(null)},[ru,sH]);let sU=ru?.kind==="row"?sH.find(e=>"session"===e.kind&&e.key===ru.row.key)??ru.row:null,s_=(0,i.useCallback)(e=>{iv(e.root)},[iv]),sq=(0,i.useCallback)(e=>{let t={...nK};for(let n of iP.projects)delete t[n.key],t[n.key]=e(n);iG(t,null)},[nK,iP.projects,iG]),sK=(0,i.useCallback)((e,t)=>{let n=iF.get(e);if(!n)return;let r=!q(n,iA);if(t)return void sq(()=>r);let i={...nK};delete i[e],i[e]=r,iG(i,[e])},[nK,iF,iG,sq,iA]),sV=(0,i.useCallback)(e=>{let t=iP.rows.find(t=>"group-more"===t.kind&&t.projectKey===e||"pinned-more"===t.kind&&e===z);(t?.kind==="group-more"||t?.kind==="pinned-more")&&nY(n=>{var r;return r=t.nextShown,{...n,[e]:Math.max(Y(n,e),Math.floor(r))}})},[iP.rows]),sZ=(0,i.useCallback)(e=>{nY(t=>X(t,e))},[]),sJ=(0,i.useCallback)(e=>{rI.current=e,r$(e=>e+1),nj?i4(!1):i2("files")},[i4,nj,i2]),sG=nj?rr.open:"files"===nk;(0,i.useEffect)(()=>{let e=rI.current;e&&sG&&(rI.current=null,"project-list"===e?tp.current?.openMenu("project"):"file-search"===e?document.getElementById("file-search-input")?.focus({preventScroll:!0}):tp.current?.button("project")?.focus({preventScroll:!0}))},[sG,rT]);let sY=e=>{let{heading:t,headingTitle:n,notes:i,count:s,onConfirm:o,onCancel:a}=e;return(0,r.jsxs)("div",{className:"sidebar-menu-question",children:[(0,r.jsx)("div",{className:"sidebar-menu-header",title:n,children:t}),i.map(e=>(0,r.jsx)("p",{className:"sidebar-menu-question-text",children:e},e)),(0,r.jsxs)("div",{className:"sidebar-menu-question-buttons",children:[(0,r.jsx)("button",{type:"button",className:"sidebar-menu-question-confirm",disabled:0===s,onClick:o,children:eq("sidebar.deleteCount",{count:s})}),!eJ&&(0,r.jsx)("button",{type:"button",className:"sidebar-menu-question-cancel","data-sidebar-menu-autofocus":"",onClick:a,children:eq("sidebar.cancel")})]})]})},sX=(e,t)=>sY({heading:t?eq("sidebar.deleteArchivedInProjectHeading",{name:t.name}):eq("old"===e?"sidebar.deleteOldArchivedHeading":"sidebar.deleteAllArchivedHeading"),headingTitle:t?.root,notes:[eq("sidebar.deleteArchivedMessage")],count:sP(e).length,onConfirm:()=>sz(e),onCancel:()=>sA(void 0)}),sQ="",s0=null;if(ru?.kind==="row"&&sU)h=t5(sU.family.root),sQ=eq("sidebar.sessionActions"),v=(function(e,t){if(t.transient)return[];let n={kind:"action",id:"open-new-tab",shortcut:"T"};return"archive"===e?[{kind:"action",id:"unarchive",shortcut:"A"},{kind:"action",id:"pin",shortcut:"P"},{kind:"action",id:"rename",shortcut:"R"},{kind:"action",id:"fork",shortcut:"F"},{kind:"action",id:"share",shortcut:"S"},{kind:"action",id:"copy-session-id",shortcut:"I"},n,{kind:"separator"},{kind:"action",id:"delete",shortcut:"D"}]:[{kind:"action",id:"pinned"===e?"unpin":"pin",shortcut:"P"},{kind:"action",id:"rename",shortcut:"R"},{kind:"action",id:"fork",shortcut:"F"},{kind:"action",id:"share",shortcut:"S"},{kind:"action",id:"copy-session-id",shortcut:"I"},{kind:"action",id:t.unread?"mark-read":"mark-unread",shortcut:"U"},t.running?{kind:"action",id:"archive",shortcut:"A",disabledReason:"running"}:{kind:"action",id:"archive",shortcut:"A"},n,{kind:"separator"},{kind:"action",id:"delete",shortcut:"D"}]})(sU.context,sU.status).map((e,t)=>{if("separator"===e.kind)return{type:"separator",id:`separator-${t}`};let n=eq(nO[e.id]);return{type:"item",id:e.id,label:"delete"===e.id||"share"===e.id?`${n}…`:n,icon:function(e){switch(e){case"open-new-tab":return(0,r.jsx)(tD,{});case"pin":return(0,r.jsx)(tA,{});case"unpin":return(0,r.jsx)(tP,{});case"rename":return(0,r.jsx)(tB,{});case"fork":return(0,r.jsx)(tO,{});case"share":return(0,r.jsx)(tG,{});case"copy-session-id":return(0,r.jsx)(tY,{});case"mark-read":return(0,r.jsx)(tU,{});case"mark-unread":return(0,r.jsx)(tH,{});case"archive":return(0,r.jsx)(tR,{});case"unarchive":return(0,r.jsx)(tL,{});case"delete":return(0,r.jsx)(tF,{})}}(e.id),shortcut:e.shortcut,danger:"delete"===e.id,disabled:void 0!==e.disabledReason,disabledReason:"running"===e.disabledReason?eq("sidebar.cannotArchiveRunning"):void 0,onSelect:t=>{let{shiftKey:n,keepOpen:r}=t;return((e,t,n,r)=>{let{family:i}=t;switch(e){case"open-new-tab":sy(i);break;case"pin":sn(i,!0);break;case"unpin":sn(i,!1);break;case"rename":sc(i);break;case"fork":sb(t);break;case"share":r?.(),rp(e=>e?.kind==="row"&&e.row.key===t.key?{...e,share:!0}:e);break;case"copy-session-id":(0,ty.D)(i.root.id).then(()=>rS(eq("sidebar.sessionIdCopied")),()=>{});break;case"mark-read":sr(i,!0);break;case"mark-unread":sr(i,!1);break;case"archive":so(i);break;case"unarchive":sl(i);break;case"delete":sm(i,n)}})(e.id,sU,n,r)}}}),ru.share&&(v=void 0,s0=(0,r.jsx)(n$,{sessionId:sU.family.root.id,onCopied:()=>rS(eq("share.copiedToast")),onStopped:()=>rS(eq("share.stoppedToast"))}),g=320);else if(ru?.kind==="group"){let e,t,i,o,a,l=iF.get(ru.project.key)??ru.project;h=l.name,sQ=eq("sidebar.projectActions",{name:l.name}),n=l,s=ru.olderCount,e=iC.countByProject.get(n.key)??0,t=et(sw,n.key),i=en(iP.projects,n.key,"up"),o=en(iP.projects,n.key,"down"),a=(null===n.customName?["rename-project"]:["rename-project","reset-project-name"]).map(e=>"rename-project"===e?{type:"item",id:e,label:eq("sidebar.renameProject"),icon:(0,r.jsx)(tB,{}),onSelect:()=>su(n)}:{type:"item",id:e,label:eq("sidebar.resetProjectName"),icon:(0,r.jsx)(tL,{}),onSelect:()=>{i0({action:"rename-project",projectKey:n.key,name:null})}}),v=[{type:"item",id:"pin-project",label:eq(n.pinned?"sidebar.unpinProject":"sidebar.pinProject"),icon:n.pinned?(0,r.jsx)(tP,{}):(0,r.jsx)(tA,{}),onSelect:()=>{i0({action:"pin-project",projectKey:n.key,root:n.root,pinned:!n.pinned})}},...a,{type:"item",id:"open-in-files",label:eq("sidebar.openInFilesTab"),icon:(0,r.jsx)(tK,{}),onSelect:()=>{n.current||e7(n.root),sJ("project-button")}},{type:"item",id:"open-new-tab",label:eq("sidebar.openInNewTab"),icon:(0,r.jsx)(tD,{}),shortcut:"T",onSelect:()=>(e=>{let{cwd:t}=ej(e,e9);window.open(`?cwd=${encodeURIComponent(t)}`,"_blank","noopener,noreferrer")})(n)},{type:"separator",id:"separator-layout"},{type:"item",id:"move-up",label:eq("sidebar.moveProjectUp"),icon:(0,r.jsx)(tz,{className:"sidebar-icon-up"}),disabled:null===i,onSelect:()=>{i&&i1(n.key,i.anchorKey,i.position)}},{type:"item",id:"move-down",label:eq("sidebar.moveProjectDown"),icon:(0,r.jsx)(tz,{className:"sidebar-icon-down"}),disabled:null===o,onSelect:()=>{o&&i1(n.key,o.anchorKey,o.position)}},{type:"item",id:"collapse-others",label:eq("sidebar.collapseOtherGroups"),icon:(0,r.jsx)(tz,{}),disabled:iP.projects.every(e=>q(e,iA)===(e.key===n.key)),onSelect:()=>sq(e=>e.key===n.key)},{type:"item",id:"expand-all",label:eq("sidebar.expandAllGroups"),icon:(0,r.jsx)(tz,{className:"sidebar-icon-down"}),disabled:iP.projects.every(e=>q(e,iA)),onSelect:()=>sq(()=>!0)},{type:"separator",id:"separator-sessions"},{type:"item",id:"archive-older",label:eq("sidebar.archiveOlderThanWeek",{count:s}),icon:(0,r.jsx)(tR,{}),disabled:0===s,onSelect:()=>sC(n)},{type:"item",id:"view-archived",label:eq("sidebar.viewArchived",{count:e}),icon:(0,r.jsx)(tR,{}),disabled:0===e,onSelect:()=>i5(n.key)},{type:"item",id:"delete-all",label:eq("sidebar.deleteProjectSessions",{count:t.ids.length}),icon:(0,r.jsx)(tF,{}),danger:!0,disabled:0===t.ids.length,onSelect:e=>{let{keepOpen:t}=e;t(),sN(n.key,!0)}}],ru.askDelete&&(s0=(e=>{let{ids:t,running:n}=et(sw,e.key);return sY({heading:eq("sidebar.deleteProjectSessionsHeading",{name:e.name}),headingTitle:e.root,notes:[eq("sidebar.deleteProjectSessionsMessage"),...n>0?[eq("sidebar.deleteProjectSessionsRunning",{count:n})]:[]],count:t.length,onConfirm:()=>sT(e),onCancel:()=>sN(e.key,!1)})})(l)),g=264}else if(ru?.kind==="archive-group"){let e,t=iD.find(e=>e.project.key===ru.project.key)?.project??ru.project;h=t.name,sQ=eq("sidebar.archivedProjectActions",{name:t.name}),v=[{type:"item",id:"restore-all",label:eq("sidebar.restoreAllArchived",{count:(e=sP({projectKey:t.key})).length}),icon:(0,r.jsx)(tL,{}),disabled:0===e.length,onSelect:()=>sa(sM(e))},{type:"separator",id:"separator-delete"},{type:"item",id:"delete-all",label:eq("sidebar.deleteAllArchived",{count:e.length}),icon:(0,r.jsx)(tF,{}),danger:!0,disabled:0===e.length,onSelect:e=>{let{keepOpen:t}=e;t(),sA("all")}}],ru.askDelete&&(s0=sX({projectKey:t.key},t)),g=248}else if(ru?.kind==="archive"){let e,t,n;h=eq("sidebar.archived"),sQ=eq("sidebar.archiveActions"),e=sP("all"),t=sP("old"),n=iD.filter(e=>!e.expanded).length,v=[{type:"item",id:"collapse-all",label:eq("sidebar.collapseAllGroups"),icon:(0,r.jsx)(tz,{}),disabled:n===iD.length,onSelect:()=>sO(!1)},{type:"item",id:"expand-all",label:eq("sidebar.expandAllGroups"),icon:(0,r.jsx)(tz,{className:"sidebar-icon-down"}),disabled:0===n,onSelect:()=>sO(!0)},{type:"separator",id:"separator-sessions"},{type:"item",id:"restore-all",label:eq("sidebar.restoreAllArchived",{count:e.length}),icon:(0,r.jsx)(tL,{}),disabled:0===e.length,onSelect:()=>sa(sM(e))},{type:"item",id:"delete-old",label:eq("sidebar.deleteOldArchived",{count:t.length}),icon:(0,r.jsx)(tF,{}),danger:!0,disabled:0===t.length,onSelect:e=>{let{keepOpen:t}=e;t(),sA("old")}},{type:"item",id:"delete-all",label:eq("sidebar.deleteAllArchived",{count:e.length}),icon:(0,r.jsx)(tF,{}),danger:!0,disabled:0===e.length,onSelect:e=>{let{keepOpen:t}=e;t(),sA("all")}}],ru.askDelete&&(s0=sX(ru.askDelete,null)),g=280}let s1={layout:eJ?"mobile":"desktop",loading:e0||!rD,error:e8,renamingRootId:rs,renamingProjectKey:ra,confirmDeleteRootId:rc,activeMenuRowKey:ru?.kind==="row"?ru.row.key:ru?.kind==="group"?`group:${ru.project.key}`:ru?.kind==="archive-group"?`archive:${ru.project.key}`:null,onSelectFamily:s_,onToggleGroup:sK,onShowMore:sV,onShowLess:sZ,onTogglePinned:()=>{let e=!nX;nQ(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eh();if(t)try{t.setItem(el,String(e))}catch{}}(e),e&&nY(e=>X(e,z))},onArchiveFamily:so,onRestoreFamily:sl,onOpenRowMenu:sj,onRowContextMenu:sk,onRenameCommit:(e,t)=>{sd(e,t)},onRenameCancel:()=>ro(null),onRenameProjectCommit:sh,onRenameProjectCancel:()=>{ra&&sp(ra)},onDeleteConfirm:e=>{sf(e)},onDeleteCancel:()=>{rd(null),rc&&rW(()=>iX(rc))},onGroupNew:sF,onGroupMenu:sS,onToggleArchiveGroup:sD,onArchiveGroupMenu:sR,onOpenOtherProject:()=>{sJ("project-list")},onOpenArchive:()=>i5(),onMoveGroup:i1},s2=e9??eE??null,s4=s2&&tq>0?eq("sidebar.changedFiles",{count:tq}):void 0,s8=(0,i.useRef)(null),s5=!s2||0===tq;(0,i.useLayoutEffect)(()=>{let e=s8.current;if(s5&&e&&i7.current===e){var t,n;let r;t=document,n=iY(),(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}):eN(t,r)}},[s5,iY]);let s6=nj||"sessions"===nk,s3=!nj&&"files"===nk&&null!==s2,s9=(t=(nj?["below",eq("sidebar.new")]:["tabs",eq("sidebar.tabSessions"),eq("sidebar.tabFiles"),eq("sidebar.new"),s2&&tq>0?tq:"",nk]).join("\n"),p=(0,i.useCallback)(()=>{let e=rq.current;if(e){for(let t of["0","1","2"])if(e.dataset.fit=t,e.scrollWidth<=e.clientWidth)return}},[rq]),(0,i.useLayoutEffect)(()=>{let e=rq.current;if(!e)return;p();let t=new ResizeObserver(p);return t.observe(e),()=>t.disconnect()},[rq,p,t]),p),s7=iP.archivedCount,oe=nj?13:14,ot=(0,r.jsx)(nP,{onClick:()=>{s2&&e$?.(s2)},disabled:!s2||!e$,title:eq("terminal.open"),children:(0,r.jsx)(tZ,{size:oe})}),on=(0,r.jsx)(nP,{onClick:()=>{r5().then(e=>{e&&nj&&i4(!1)})},disabled:!s2||r3,title:r3?eq(nn?.reason==="remote"?"sidebar.openInExplorerRemoteOnly":"sidebar.openInExplorerUnsupported"):r6,children:(0,r.jsx)(tK,{size:oe})}),or=(0,r.jsx)(nP,{onClick:()=>{nj&&nS&&i4(!1),nv.current?.openUploadPicker()},disabled:!s2||tk,title:eq("sidebar.uploadFilesTitle"),children:(0,r.jsx)(tQ,{size:oe})}),oi=(0,r.jsx)(nP,{onClick:()=>{eL?eL():tj(e=>e+1),nt(!0),nx.current&&clearTimeout(nx.current),nx.current=setTimeout(()=>nt(!1),2e3)},disabled:!s2,title:eq("sidebar.refreshExplorer"),done:ne,children:ne?(0,r.jsx)(t_,{size:oe}):(0,r.jsx)(t0,{size:oe})}),os=e=>(0,r.jsx)(nP,{onClick:()=>{let e=!t9;t7(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eh();if(t)try{t.setItem(ec,String(e))}catch{}}(e)},disabled:!s2,title:eq("sidebar.showIgnoredFiles"),pressed:t9,className:e,children:(0,r.jsx)(t2,{size:oe})}),oo=(0,r.jsx)(nP,{ref:s8,onClick:()=>{if(nj&&nS){i4(!1),t6(!1);return}t6(e=>!e)},disabled:s5,title:eq("sidebar.changedFiles",{count:tq}),pressed:!s5&&!t8,children:(0,r.jsx)(t1,{size:oe})}),oa=(0,r.jsx)(nP,{onClick:()=>{s2&&eM?.(s2)},disabled:!s2||!eM,title:eq("sidebar.openGitGraph"),children:(0,r.jsx)(tJ,{size:oe})});return(0,r.jsxs)("div",{ref:r1,className:`session-sidebar${nj?" is-files-below":""}${nj&&nS?" is-files-collapsed":""}${nj&&rr.moving?" is-files-folding":""}${rj?" has-toast":""}`,style:{"--sidebar-files-height":`${rQ.width}px`},onFocus:e=>{i7.current=e.target},onBlur:e=>{(null!==e.relatedTarget||document.hasFocus())&&(e.currentTarget.contains(e.relatedTarget)||(i7.current=null))},children:[tn&&(0,r.jsx)(e5,{initialPath:ti,busy:tl,error:to,onCancel:()=>{let e="new-session"===tn?rL.current:null;rR.current=null,rL.current=null,tr(!1),ta(null),e&&rW(()=>e.isConnected?e:null)},onSelect:e=>void ic(e)}),(0,r.jsxs)("div",{ref:rq,className:"sidebar-header",children:[nj&&(0,r.jsx)(tw,{onWidthChange:s9}),!nj&&(0,r.jsxs)("div",{className:"sidebar-tabs-list",role:"tablist","aria-label":eq("sidebar.tabsLabel"),children:[(0,r.jsxs)("button",{ref:nI,type:"button",role:"tab",id:"session-sidebar-tab-sessions","aria-selected":"sessions"===nk,"aria-controls":"session-sidebar-panel-sessions",tabIndex:"sessions"===nk?0:-1,className:`sidebar-tab${"sessions"===nk?" is-selected":""}`,onClick:()=>i2("sessions"),onKeyDown:st,children:[(0,r.jsx)(t4,{size:13,className:"sidebar-tab-icon"}),(0,r.jsx)("span",{className:"sidebar-tab-label",children:eq("sidebar.tabSessions")})]}),(0,r.jsxs)("button",{ref:nT,type:"button",role:"tab",id:"session-sidebar-tab-files","aria-selected":"files"===nk,"aria-controls":"session-sidebar-panel-files",tabIndex:"files"===nk?0:-1,title:s4,className:`sidebar-tab${"files"===nk?" is-selected":""}`,onClick:()=>i2("files"),onKeyDown:st,children:[(0,r.jsx)(tK,{size:13,className:"sidebar-tab-icon"}),(0,r.jsx)("span",{className:"sidebar-tab-label",children:eq("sidebar.tabFiles")}),s2&&tq>0&&(0,r.jsx)("span",{className:"sidebar-tab-count","aria-hidden":"true",children:tq})]})]}),(0,r.jsx)("span",{className:"sidebar-header-spacer"}),(0,r.jsxs)("button",{type:"button",className:"sidebar-new-button",onClick:ij,disabled:!e9,title:e9?eq("sidebar.newSessionTitle",{path:e9}):eq("sidebar.selectProject"),children:[(0,r.jsx)(t$,{size:12}),(0,r.jsx)("span",{className:"sidebar-new-label",children:eq("sidebar.new")})]}),(0,r.jsx)("button",{ref:rV,type:"button",onClick:()=>{if(s3)return void tN(e=>!e);if(!s6){i2("sessions"),tI(!0);return}tI(e=>!e)},title:s3?eq("sidebar.searchFiles"):eq("sidebar.toggleSessionSearch"),"aria-label":s3?eq("sidebar.searchFiles"):eq("sidebar.toggleSessionSearch"),"aria-expanded":s3?tC:tE,"aria-controls":s3?"file-search-input":"session-search-input",className:`sidebar-search-toggle${(s3?tC:tE)?" is-active":""}`,children:(0,r.jsx)(tX,{size:16})})]}),(0,r.jsxs)("div",{ref:nM,id:"session-sidebar-panel-sessions",role:nj?"region":"tabpanel","aria-label":nj?eq("sidebar.tabSessions"):void 0,"aria-labelledby":nj?void 0:"session-sidebar-tab-sessions",hidden:!nj&&"sessions"!==nk,className:"sidebar-panel sidebar-sessions-panel",onScrollCapture:i8,children:[tE&&(0,r.jsx)("div",{className:"sidebar-search",children:(0,r.jsx)("input",{id:"session-search-input",type:"search",autoFocus:!0,value:tT,maxLength:200,"aria-label":eq("sidebar.searchSessions"),placeholder:eq("sidebar.searchSessions"),onChange:e=>tW(e.target.value),onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.stopPropagation(),tW(""))},className:"sidebar-search-input"})}),(0,r.jsx)(nE,{open:tE,query:tT,selectedSessionId:b,onSelectSession:iv,archivedSessionIds:iC.ids,children:(0,r.jsxs)("div",{className:"sidebar-sessions-views",children:[(0,r.jsx)("div",{className:"sidebar-sessions-view",hidden:ri.mainHidden,inert:ri.mainInert,children:(0,r.jsx)(t3,{...s1,rows:iP.rows,emptyLabel:eq("sidebar.noSessions"),reveal:rh,onRevealHandled:rg})}),ri.archiveMounted&&(0,r.jsxs)("div",{className:`sidebar-sessions-view sidebar-archive-view${ri.archiveClass?` ${ri.archiveClass}`:""}`,inert:ri.archiveInert,onAnimationEnd:e=>{e.target===e.currentTarget&&n7()},children:[(0,r.jsxs)("div",{className:"sidebar-archive-bar",children:[(0,r.jsxs)("button",{ref:i6,type:"button",className:"sidebar-archive-back",title:eq("sidebar.backToSessions"),"aria-label":`${eq("sidebar.backToSessions")}: ${eq("sidebar.archivedCount",{count:s7})}`,onClick:()=>rn(!1),children:[(0,r.jsx)(tz,{size:13,className:"sidebar-icon-back"}),(0,r.jsx)("span",{children:eq("sidebar.archived")}),(0,r.jsxs)("span",{className:"sidebar-archive-count",children:["\xb7 ",s7]})]}),(0,r.jsx)("button",{type:"button",className:`sidebar-archive-menu-button${ru?.kind==="archive"?" is-active":""}`,title:eq("sidebar.archiveActions"),"aria-label":eq("sidebar.archiveActions"),"aria-haspopup":"menu","aria-expanded":ru?.kind==="archive",disabled:0===iD.length,onClick:e=>sL(e.currentTarget),children:(0,r.jsx)(tM,{size:13})})]}),(0,r.jsx)(t3,{...s1,rows:iO,emptyLabel:eq("sidebar.noArchived"),reveal:rx,onRevealHandled:rb})]})]})})]}),nj&&rr.open&&(0,r.jsx)("div",{...rQ.separatorProps,"aria-controls":"session-sidebar-panel-files",className:`panel-resize-handle sidebar-files-resize-handle${rQ.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar-files",title:`${eq("sidebar.resizeFiles")}: ${eq("sidebar.resizeFilesHint")}`}),(0,r.jsxs)("div",{ref:nR,id:"session-sidebar-panel-files",role:nj?"region":"tabpanel","aria-label":nj?eq("sidebar.tabFiles"):void 0,"aria-labelledby":nj?void 0:"session-sidebar-tab-files",hidden:!nj&&"files"!==nk,className:"sidebar-panel sidebar-files-panel",onScrollCapture:i8,onTransitionEnd:e=>{e.target===e.currentTarget&&"height"===e.propertyName&&n6()},children:[nj&&(0,r.jsxs)("div",{className:"sidebar-files-section",children:[(0,r.jsxs)("button",{type:"button",className:"sidebar-files-section-toggle","aria-expanded":!nS,"aria-controls":"session-sidebar-files-body",title:s4,onClick:()=>i4(!nS),children:[(0,r.jsx)(tz,{size:12,strokeWidth:3,className:`session-tree-chevron${nS?"":" is-open"}`}),(0,r.jsx)("span",{className:"sidebar-files-section-label",children:eq("sidebar.tabFiles")}),s4&&(0,r.jsxs)("span",{className:"sidebar-files-section-count","aria-hidden":"true",children:["\xb7 ",tq]})]}),(0,r.jsxs)("div",{className:"sidebar-files-keys",role:"group","aria-label":eq("sidebar.fileActions"),children:[ot,on,or,oi,os(),oo,oa,(0,r.jsx)(nP,{onClick:()=>{if(nS){tN(!0),sJ("file-search");return}tN(e=>!e)},disabled:!s2,title:eq("sidebar.searchFiles"),expanded:tC,controls:"file-search-input",children:(0,r.jsx)(tX,{size:13})})]})]}),(0,r.jsxs)("div",{id:"session-sidebar-files-body",className:"sidebar-files-body",hidden:nj&&rr.bodyHidden,inert:nj&&rr.bodyInert,children:[(0,r.jsxs)("div",{className:"sidebar-files-head",children:[(0,r.jsx)(nN,{handleRef:tp,layout:nj?"row":"stacked",context:iK??{project:null,worktrees:null,currentWorktreePath:null,projects:iq},mobile:eJ,label:eq("sidebar.projectAndWorktree"),placeholder:K&&!r7.current?"":eq("sidebar.selectProject"),homeDir:te,projectActivity:iN,worktreeHint:i$,newWorktreeTitle:eq("sidebar.createWorktreeTitle"),onPick:ix,onUseDefaultDirectory:()=>{iu()},onOpenFolder:id,onRefreshWorktrees:ig,onCreateWorktree:ih,onRemoveWorktree:im}),!nj&&s2&&(0,r.jsxs)("div",{className:"sidebar-files-actions",role:"group","aria-label":eq("sidebar.fileActions"),children:[e$&&ot,on,or,oi,os("sidebar-files-views-start"),oo,oa]})]}),s2&&r9&&(0,r.jsxs)("div",{role:"alert",className:"sidebar-files-error",children:[(0,r.jsx)("span",{className:"sidebar-files-error-text",children:r9}),(0,r.jsx)(e6,{onClick:()=>ns(null),title:eq("files.dismissError")})]}),(0,r.jsx)("div",{ref:rK,className:"sidebar-files-scroll scrollbar-subtle",children:s2&&(0,r.jsx)(tb,{ref:nv,cwd:s2,onOpenFile:eT??(()=>{}),refreshKey:tv,onAtMention:eA,onAtMentions:eP,onUploadBusyChange:tS,changesCollapsed:t8,onChangesCountChange:tV,fileSearchOpen:tC,onFileSearchOpenChange:tN,showHidden:t9})})]})]}),(0,r.jsx)(ny,{open:null!==ru,anchor:ru?.anchor??null,sheet:eJ,ariaLabel:sQ,title:h,items:v,cancelLabel:eq("sidebar.cancel"),focusCancel:null!==s0,onClose:sB,returnFocusTo:ru?.opener??null,width:g,children:s0}),(0,r.jsx)(nL,{toast:rj,onDismiss:()=>rk(null),dismissLabel:eq("sidebar.dismiss")})]})}var nK=n(16011);let nV=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,nZ=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,nJ=/\x1B_pi:c\x07/g;function nG(e){return e.replace(nJ,"").replace(nV,"")}function nY(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(nZ);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 nX(e,t){let n=nY(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function nQ(e){return nY(e)[0]?.char}let n0=/[▀-▟]/,n1={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:""},n2={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"};var n4=n(27874),n8=n(53996),n5=n(61825);function n6(e,t){let n,r=t.shortWithArg??new Set,i=t.longWithArg??new Set,s=t.inPlace??new Set,o=[],a=!1,l=!1,c=e=>{t.targetDir&&(n=e)};for(let d=1;d<e.length;d++){let u=e[d],p=u.text;if(!u.quoted&&"--"===p){for(let t=d+1;t<e.length;t++)o.push(e[t].text);break}if(!u.quoted&&p.startsWith("--")){let r=p.indexOf("=");if(-1!==r){let e=p.slice(0,r);s.has(e)?a=!0:t.expression&&("--expression"===e||"--file"===e)?l=!0:"--target-directory"===e&&t.targetDir&&(n=p.slice(r+1));continue}if(s.has(p)){a=!0;continue}t.expression&&("--expression"===p||"--file"===p)&&(l=!0),i.has(p)&&d+1<e.length&&("--target-directory"===p&&c(e[d+1].text),d+=1);continue}if(!u.quoted&&p.startsWith("-")&&p.length>1&&!/^\d/.test(p.slice(1))){let n=p.slice(1);for(let i=0;i<n.length;i++){let o=`-${n[i]}`;if(s.has(o)&&(a=!0),t.expression&&("-e"===o||"-f"===o)&&(l=!0),r.has(o)){let t=n.slice(i+1);t.length>0?"-t"===o&&c(t):d+1<e.length&&("-t"===o&&c(e[d+1].text),d+=1);break}}continue}o.push(p)}return{operands:o,targetDirectory:n,inPlace:a,expressionSeen:l}}var n3=n(11242),n9=n(90953);function n7(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}function re(e){return e?e.map(e=>e.newPath).filter(e=>"string"==typeof e&&e.length>0):[]}function rt(e,t,n){let r=new Set,i=[],s=e=>{let t=(0,n8.XK)(e,n);!t||r.has(t)||(r.add(t),i.push({filePath:t}))};for(let n of e){var o;let e;if("toolCall"!==n.type||(o=n.toolName,!((0,n5.V4)(o)||(0,n5.iG)(o))&&!(0,n5.aP)(n.toolName)&&!(0,n5.Y2)(n.toolName)&&n.toolName!==n3.sp))continue;let r=t?.get(n.toolCallId);if(r&&!r.isError){if((0,n5.aP)(n.toolName))e=function(e,t){let n=t?.details,r=function(e,t){let n=new Set;if(t&&"object"==typeof t&&!Array.isArray(t)){let e=t.preview;if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.files;if(Array.isArray(t))for(let e of t)!(!e||"object"!=typeof e||Array.isArray(e))&&"delete"===e.operation&&"string"==typeof e.filePath&&e.filePath.length>0&&n.add(e.filePath)}}for(let t of(0,n9.IN)(e).matchAll(/^\*\*\* Delete File: (.+)$/gm)){let e=(t[1]??"").trim();e&&n.add(e)}return n}(e,n),i=(0,n9.dc)(n);if(i)return i.filter(e=>!r.has(e));if((0,n9.FK)(n))return[];if(n&&"object"==typeof n&&!Array.isArray(n)){let e=re((0,n9.ND)(n.preview));if(e.length>0)return e}return re((0,n9.oC)((0,n9.IN)(e)))}(n.input,r);else if((0,n5.Y2)(n.toolName)){let t=function(e){if(!e)return null;let t=e.command??e.cmd??e.script;return"string"==typeof t&&t.length>0?t:null}(n.input);e=t?function(e){if("string"!=typeof e||0===e.length||e.length>2e5)return[];let t=new Set,n=[];for(let r of function(e){let t=[],n=[],r="",i=!1,s="",o=()=>{(r.length>0||i)&&n.push({text:r,quoted:i}),r="",i=!1},a=()=>{o(),n.length>0&&t.push(n),n=[]};for(let t=0;t<e.length;t++){let n=e[t];if(s){if("\\"===n&&'"'===s&&e[t+1]){r+=e[t+1],t+=1;continue}if(n===s){s="";continue}r+=n;continue}if("'"===n||'"'===n){s=n,i=!0;continue}if("\\"===n){e[t+1]&&(r+=e[t+1],i=i||/[^\w./-]/.test(e[t+1]),t+=1);continue}if(";"===n||"|"===n||"&"===n||"\n"===n){("|"===e[t+1]||"&"===e[t+1])&&(t+=1),a();continue}if("#"===n&&0===r.length){let n=e.indexOf("\n",t);t=-1===n?e.length-1:n-1,a();continue}if(/\s/.test(n)){o();continue}r+=n}return a(),t}(e)){let e=function(e){let t=function(e){let t=0;for(;t<e.length;){let n=e[t].text,r=n.slice(n.lastIndexOf("/")+1);if("sudo"===r||"nohup"===r||"env"===r||"command"===r||"exec"===r||/^[\w]+=/.test(n)&&t+1<e.length){t+=1;continue}break}return e.slice(t)}(e);if(0===t.length)return null;let n=t[0].text,r=n.slice(n.lastIndexOf("/")+1),i=[];for(let e=0;e<t.length;e++){let n=t[e];if(n.quoted)continue;if(">"===n.text||">>"===n.text||"&>"===n.text||"&>>"===n.text){let n=t[e+1];n&&!n.text.startsWith("&")&&i.push(n.text),e+=1;continue}let r=n.text.match(/^(?:\d*>>|\d*>|&>>|&>|>&)(.+)$/);if(r){let e=r[1];e.startsWith("&")||i.push(e);continue}}let s=[];switch(r){case"tee":s=n6(t,{}).operands;break;case"touch":s=n6(t,{shortWithArg:new Set(["-d","-t","-r"]),longWithArg:new Set(["--date","--reference","--time"])}).operands;break;case"mv":case"cp":s=function(e){if(e.targetDirectory)return e.operands.map(t=>{let n=t.slice(t.lastIndexOf("/")+1)||t;return`${e.targetDirectory.replace(/\/+$/,"")}/${n}`});if(e.operands.length<2)return[];let t=e.operands[e.operands.length-1];return t.endsWith("/")?e.operands.slice(0,-1).map(e=>{let n=e.slice(e.lastIndexOf("/")+1)||e;return`${t.replace(/\/+$/,"")}/${n}`}):[t]}(n6(t,{shortWithArg:new Set(["-t","-S","-Z"]),longWithArg:new Set(["--target-directory","--suffix","--context"]),targetDir:!0}));break;case"sed":{let e=n6(t,{shortWithArg:new Set(["-e","-f"]),longWithArg:new Set(["--expression","--file"]),inPlace:new Set(["-i","--in-place"]),expression:!0});e.inPlace&&(s=e.expressionSeen?e.operands:e.operands.slice(1));break}case"truncate":s=n6(t,{shortWithArg:new Set(["-s","-r"]),longWithArg:new Set(["--size","--reference"])}).operands;break;case"dd":s=t.slice(1).flatMap(e=>{let t=e.text.match(/^of=(.+)$/);return t?[t[1]]:[]})}let o=[...i,...s].filter(e=>!(0===e.length||/[\$`]/.test(e)||/[*?\[]/.test(e)||e.startsWith("-")||e.startsWith("~")||e.startsWith("/dev/")));return o.length>0?o:null}(r);if(e){for(let r of e)if(!t.has(r)&&(t.add(r),n.push(r),n.length>=100))return n}}return n}(t):[]}else e=n.toolName===n3.sp?function(e){let{calls:t}=(0,n3.or)(e?.details),n=[];for(let e of t){if("ok"!==e.status||!(0,n5.V4)(e.name)&&!(0,n5.iG)(e.name))continue;let t=function(e){try{let t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return n7(t);return null}catch{let t=e.match(/"(?:file_path|path)"\s*:\s*"((?:[^"\\]|\\.)*)"/);return t?t[1].replace(/\\(.)/g,(e,t)=>"n"===t?"\n":"t"===t?" ":"r"===t?"\r":t):null}}(e.args);t&&n.push(t)}return n}(r):[n7(n.input)];for(let t of e)t&&s(t)}}return i}var rn=n(20817);function rr(e,t){let n=[],r=new Set;for(let i of e)if("assistant"===i.role)for(let e of i.content??[]){if("toolCall"!==e.type)continue;let i=t.get(e.toolCallId),s=(0,rn.G)(i?.details)?i?.details:null;s&&"starting"!==s.status&&"queued"!==s.status&&"running"!==s.status&&(r.has(s.sessionId)||(r.add(s.sessionId),n.push({sessionId:s.sessionId,cwd:s.worktreePath})))}return n}async function ri(e,t){let n,r=[],i=null;for(let s=0;s<t;s++){let t=new URLSearchParams({tail:"1000",deferThinking:"",deferMedia:""});n&&t.set("before",n);let s=await fetch(`/api/sessions/${encodeURIComponent(e)}/context?${t}`,{cache:"no-store"});if(!s.ok)throw Error(`context ${s.status}`);let o=await s.json();i??=o.cwd??null;let a=o.context??{},l=Array.isArray(a.messages)?a.messages:[];if(r.unshift(...l),!a.hasMore||!a.oldestEntryId)break;n=a.oldestEntryId}return{messages:r,cwd:i}}let rs=new Map,ro=new Map;function ra(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={...e,content:t};return n.omitUsage&&(r.usage=void 0),r}var rl=n(19028);function rc(e,t,n){let r=e.trim().split("\n").map(e=>`> ${e}`).join("\n");return`${t}
4
-
5
- ${r}
6
-
7
- ${n}`}var rd=n(61798),ru=n(7325);function rp(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 rh=new Map;function rf(e){return{value:e.value,images:e.images.map(e=>({...e}))}}function rm(e){return!e.value&&0===e.images.length}function rg(e){let t=rh.get(e);return t?rf(t):null}function rx(e,t){rm(t)?rh.delete(e):rh.set(e,rf(t))}function rv(e){rh.delete(e)}function rb(e,t){return e.trim()?t.trim()?`${e}
8
-
9
- ${t}`:e:t}function ry(e,t,n,r){let i=[...t??[],...r].filter(rp).slice(0,10).map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});return{value:rb(e,n),images:i}}function rj(e,t,n){if(e===t)return n?rf(n):rg(t);let r=rg(e),i=n&&!rm(n)?rf(n):r??(n?rf(n):null),s=rg(t);if(rv(e),!i)return s;let o=s?ry(s.value,s.images,i.value,i.images):i;return rx(t,o),rf(o)}let rk=/^([ \t]*)([-*+])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,rw=/^([ \t]*)(\d{1,9})([.)])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,rS=/^([ \t]*)(\d{1,3})(、)([ \t]*)/,rC=/^[ \t]*([-*_])(?:[ \t]*\1){2,}[ \t]*$/,rN=/^[ \t]{0,3}(`{3,}|~{3,})/;function rE(e){return"mcp"===e.name&&e.sourceInfo?.path==="builtin:mcp"}function rI(e){return"/mcp"===e.trim()}var rT=n(82702);let r$="pi-enter-send-mode",rM="enter",rR=null,rL=new Set;function rA(){return null===rR&&(rR=function(){try{let e=window.localStorage.getItem(r$);return"ctrlEnter"===e?"ctrlEnter":"enter"}catch{return rM}}()),rR}function rP(e){return rL.add(e),()=>{rL.delete(e)}}function rz(e){rR=e;try{window.localStorage.setItem(r$,e)}catch{}rL.forEach(e=>e())}function rW(){return(0,i.useSyncExternalStore)(rP,rA,()=>rM)}let rO="pi-chat-content-width",rD="pi-chat-content-font-size",rF={width:820,fontSize:14},rB=null,rH=new Set;function rU(e){let t=Number(e);return Number.isFinite(t)?Math.max(820,Math.min(2e3,Math.round(t))):820}function r_(e){let t=Number(e??14);return Number.isFinite(t)?Math.max(12,Math.min(24,Math.round(t))):14}function rq(e){try{return window.localStorage.getItem(e)}catch{return null}}function rK(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 rV(){return rB||rK(rB={width:rU(rq(rO)),fontSize:r_(rq(rD))}),rB}function rZ(e){return rH.add(e),()=>{rH.delete(e)}}function rJ(e,t){let n="width"===e?rU(t):r_(t);rK(rB={...rV(),[e]:n});try{window.localStorage.setItem("width"===e?rO:rD,String(n))}catch{}rH.forEach(e=>e())}let rG=e=>rJ("width",e),rY=e=>rJ("fontSize",e);function rX(){return{...(0,i.useSyncExternalStore)(rZ,rV,()=>rF),setWidth:rG,setFontSize:rY}}let rQ=[{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"}],r0={ui:"pi-ui-font-family",mono:"pi-mono-font-family",uiWeight:"pi-ui-font-weight",monoWeight:"pi-mono-font-weight"},r1={ui:"",mono:"",uiWeight:400,monoWeight:400};function r2(e){let t="string"==typeof e?Number(e):e;return rQ.find(e=>e.value===t)?.value??400}function r4(e){return"string"==typeof e&&e.length<=500?e:""}let r8=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded"]),r5=["ui","mono"],r6=Object.keys(r0),r3=null,r9=new Set;function r7(){let e={...r1};for(let t of r5)try{e[t]=r4(window.localStorage.getItem(r0[t]));let n=`${t}Weight`;e[n]=r2(window.localStorage.getItem(r0[n]))}catch{}return e}function ie(e){for(let t of r5){let n=`--font-${t}`,r=function(e,t){let n=r4(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&&r8.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 it(){return r3||ie(r3=r7()),r3}function ir(){r9.forEach(e=>e())}function ii(e){if(null!==e.key&&!Object.values(r0).includes(e.key))return;let t=r7(),n=it();r6.every(e=>t[e]===n[e])||(r3=t,ie(t),ir())}function is(e){return 0===r9.size&&window.addEventListener("storage",ii),r9.add(e),it(),()=>{r9.delete(e),0===r9.size&&window.removeEventListener("storage",ii)}}function io(e){let t=it(),n=r6.filter(n=>t[n]!==e[n]);if(n.length){for(let t of(r3=e,ie(e),n))try{e[t]===r1[t]?window.localStorage.removeItem(r0[t]):window.localStorage.setItem(r0[t],String(e[t]))}catch{}ir()}}function ia(e,t){io({...it(),[e]:r4(t)})}function il(e,t){io({...it(),[`${e}Weight`]:r2(t)})}function ic(e){io({...it(),[e]:"",[`${e}Weight`]:400})}function id(){return{...(0,i.useSyncExternalStore)(is,it,()=>r1),setFontPreference:ia,setFontWeight:il,resetFontPreference:ic}}function iu(e){let{filled:t,size:n}=e;return(0,r.jsx)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:t?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:(0,r.jsx)("polygon",{points:"12 2.5 14.9 8.6 21.5 9.4 16.6 13.9 17.9 20.5 12 17.2 6.1 20.5 7.4 13.9 2.5 9.4 9.1 8.6"})})}function ip(e){let{active:t,onSelect:n,star:s,gutter:o=!!s,children:a}=e,l=(0,eD.a)(),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=!!(s&&!s.isDefault),f=h&&(c||u||l);return(0,r.jsxs)("div",{onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),onFocus:()=>p(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||p(!1)},style:{position:"relative",background:t?"var(--bg-selected)":c?"var(--bg-hover)":"transparent",transition:"background 0.1s"},children:[(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":t,onClick:n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minWidth:0,padding:o?"7px 36px 7px 12px":"7px 12px",border:"none",background:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:t?600:400,textAlign:"left",whiteSpace:"nowrap"},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),a]}),s?.isDefault&&(0,r.jsx)("span",{role:"img","aria-label":s.defaultLabel,title:s.defaultLabel,style:{position:"absolute",top:"50%",right:6,transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,color:"var(--text-dim)"},children:(0,r.jsx)(iu,{filled:!0,size:10})}),s&&h&&(0,r.jsx)("button",{type:"button",title:s.saveLabel,"aria-label":s.saveLabel,tabIndex:f?0:-1,onClick:e=>{e.stopPropagation(),s.onSave()},style:{position:"absolute",top:"50%",right:6,transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,padding:0,background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",opacity:+!!f,pointerEvents:f?"auto":"none",transition:"opacity 0.1s, background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="rgba(37,99,235,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},children:(0,r.jsx)(iu,{filled:!1,size:12})})]})}function ih(e){let t,n,s,o,a,l,c,d,u,p,h,{options:f,value:m,onChange:g,onReselect:x,onClear:v,emptyLabel:b,selectedLabel:y,disabled:j=!1,busy:k=!1,isAutoSelection:w=!1,ariaLabel:S,variant:C="toolbar",placement:N="up",defaultValue:E,onSetDefault:I}=e,{t:T}=(0,eO.s)(),$=(0,eD.a)(),M=(0,i.useRef)(null),R=(0,i.useRef)(null),[L,A]=(0,i.useState)(!1),[P,z]=(0,i.useState)(null),[W,O]=(0,i.useState)(""),D=j||k,F=(t=W.trim().toLocaleLowerCase())?f.filter(e=>`${e.name} ${e.modelId} ${e.provider}/${e.modelId}`.toLocaleLowerCase().includes(t)):f,B=f.length>8,H=[];for(let e of F){let t=H.find(t=>t.provider===e.provider);t?t.options.push(e):H.push({provider:e.provider,options:[e]})}let U=y??(m?f.find(e=>e.modelId===m.modelId&&e.provider===m.provider)?.name??m.modelId:b??(f.length>0?"Select model":"No models"));(0,i.useEffect)(()=>{let e=e=>{M.current&&!M.current.contains(e.target)&&R.current&&!R.current.contains(e.target)&&(A(!1),O(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{if(!L)return;let e=()=>{let e=M.current?.querySelector("button")?.getBoundingClientRect();e?.height&&z({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)}},[L]),(0,i.useEffect)(()=>{D&&(A(!1),O(""))},[D]);let _="field"===C?{display:"flex",alignItems:"center",gap:7,width:"100%",minWidth:0,height:34,padding:"0 9px",overflow:"hidden",border:"1px solid var(--border)",borderRadius:5,background:D?"var(--bg-panel)":"var(--bg)",color:D?"var(--text-dim)":"var(--text)",cursor:D?"default":"pointer",fontSize:12,textAlign:"left"}:{display:"flex",alignItems:"center",justifyContent:$?"flex-start":void 0,gap:6,width:$?"100%":void 0,maxWidth:$?"100%":220,height:32,padding:$?"8px 10px":"8px 12px",overflow:"hidden",border:"none",borderRadius:9,background:L?"var(--bg-hover)":"none",color:"var(--text-muted)",cursor:D?"not-allowed":"pointer",fontSize:12,opacity:D?.5:1,transition:"background 0.12s, color 0.12s"};return(0,r.jsxs)("div",{ref:M,className:`model-selector is-${C}${D?" is-disabled":""}`,style:{position:"relative",width:"field"===C||$?"100%":void 0,minWidth:0,flex:"toolbar"===C&&$?"1 1 auto":void 0},onKeyDown:e=>{"Escape"===e.key&&L&&(e.preventDefault(),e.stopPropagation(),O(""),A(!1))},children:[(0,r.jsxs)("button",{type:"button","aria-label":S,"aria-haspopup":"listbox","aria-expanded":L,"aria-busy":k||void 0,disabled:D,title:k?"Switching model":D?U:f.length>0||v?"Change model":"No available models",style:_,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();z({top:t.top,right:t.right,bottom:t.bottom,left:t.left,width:t.width}),A(e=>(e&&O(""),!e))},onMouseEnter:e=>{D||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{if(D){e.currentTarget.style.background="field"===C?"var(--bg-panel)":"none",e.currentTarget.style.color="field"===C?"var(--text-dim)":"var(--text-muted)";return}e.currentTarget.style.background=L?"var(--bg-hover)":"field"===C?"var(--bg)":"none",e.currentTarget.style.color="field"===C?"var(--text)":"var(--text-muted)"},children:[k?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:U}),"field"===C&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--text-dim)"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),L&&P&&(n=window.visualViewport?.offsetTop??0,s=window.visualViewport?.height??window.innerHeight,o=window.visualViewport?.width??window.innerWidth,l=(a=Math.min(P.top-6,n+s-8))-n-8,c=n+s-P.bottom-6-8,u=Math.max(120,Math.min((d="up"===N||l>c)?l:c,.6*s)),p=d?{top:a,transform:"translateY(-100%)"}:{top:P.bottom+6},h=$?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:P.left,width:"max-content",minWidth:P.width,maxWidth:Math.max(P.width,o-P.left-8)},(0,r.jsxs)("div",{ref:R,role:"listbox","aria-label":S,style:{position:"fixed",...p,...h,zIndex:500,display:"flex",flexDirection:"column",maxHeight:u,overflow:"hidden",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:d?"0 -4px 16px rgba(0,0,0,0.10)":"0 4px 16px rgba(0,0,0,0.10)"},children:[B&&(0,r.jsx)("div",{style:{flexShrink:0,padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:W,onChange:e=>O(e.target.value),placeholder:T("chat.filterModels"),"aria-label":T("chat.filterModels"),autoFocus:!$,autoComplete:"off",spellCheck:!1,style:{boxSizing:"border-box",width:"100%",minWidth:220*!$,padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})}),(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[v&&!W.trim()&&(0,r.jsx)(ip,{active:!m,gutter:!!I,onSelect:()=>{A(!1),O(""),v()},children:(0,r.jsx)(im,{label:b??"Default"})}),0===H.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:W.trim()?T("chat.noMatchingModels"):"No available models"}):H.map((e,t)=>(0,r.jsxs)("div",{children:[H.length>1&&(0,r.jsx)("div",{style:{padding:"6px 12px 4px",borderTop:t>0||v?"1px solid var(--border)":"none",color:"var(--text-dim)",fontSize:10,fontWeight:600,letterSpacing:0,textTransform:"uppercase"},children:e.provider}),e.options.map(e=>(0,r.jsx)(ip,{active:e.modelId===m?.modelId&&e.provider===m?.provider,onSelect:()=>{let t;return t=e.modelId===m?.modelId&&e.provider===m?.provider,void(A(!1),O(""),!t||w?g(e.provider,e.modelId):x?.(e.provider,e.modelId))},star:I?{isDefault:e.modelId===E?.modelId&&e.provider===E?.provider,saveLabel:T("chat.saveDefaultModel"),defaultLabel:T("chat.defaultModel"),onSave:()=>{A(!1),O(""),I?.(e.provider,e.modelId)}}:void 0,children:(0,r.jsx)(im,{label:e.name})},`${e.provider}:${e.modelId}`))]},e.provider))]})]}))]})}function im(e){let{label:t}=e;return(0,r.jsx)("span",{title:t,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})}let ig=["configured","chat-only","read-only","default","full"],ix={configured:"configured","chat-only":"none","read-only":"read-only",default:"default",full:"full"},iv=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function ib(e,t,n){return t<=0?0:((e+n)%t+t)%t}function iy(e,t,n,r){e.setRangeText(r,t,n,"end"),e.dispatchEvent(new Event("input",{bubbles:!0}))}function ij(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:r.length,s=e.selectionStart,o=e.selectionEnd;if(e.focus(),s===o&&t<=s&&n>=o){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-o;t>0&&e.value.length>i&&document.execCommand("forwardDelete");t--);else iy(e,t,e.selectionStart+(n-o),r)}else e.setSelectionRange(t,n),document.execCommand("insertText",!1,r)||iy(e,t,n,r);i!==r.length&&e.setSelectionRange(t+i,t+i)}function ik(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,o=s?.parentElement,a="u">typeof ResizeObserver&&s?new ResizeObserver(i):null;s&&a?.observe(s),o&&a?.observe(o);let l=window.visualViewport;return l?.addEventListener("resize",i),l?.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("scroll",i,!0),()=>{a?.disconnect(),l?.removeEventListener("resize",i),l?.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("scroll",i,!0),null!==n&&cancelAnimationFrame(n)}}let iw=["auto","off","minimal","low","medium","high","xhigh","max"],iS={auto:"chat.thinkingUseDefault",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"};function iC(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let iN=[{name:"compact",description:"chat.commandCompact",source:"builtin"},{name:"auto-compact",description:"chat.commandAutoCompact",source:"builtin"},{name:"reload",description:"chat.commandReload",source:"builtin"},{name:"name",description:"chat.commandName",source:"builtin"},{name:"session",description:"chat.commandSession",source:"builtin",availableWhileStreaming:!0},{name:"copy",description:"chat.commandCopy",source:"builtin",availableWhileStreaming:!0},{name:"clone",description:"chat.commandClone",source:"builtin"}];function iE(e){return function(e){let t=e.trim().match(/^\/([^\s]+)(?:\s|$)/);if(t)return iN.find(e=>e.name===t[1])}(e)?.availableWhileStreaming===!0}let iI=["builtin","extension","prompt","skill"],iT={builtin:"chat.builtIn",extension:"chat.extensions",prompt:"chat.prompts",skill:"chat.skills"},i$={builtin:0,extension:1,prompt:2,skill:3};function iM(e,t,n){let r=e.name.toLowerCase(),i=iR(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function iR(e,t){return"builtin"===e.source?t(e.description):e.description??""}function iL(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}async function iA(e){let t=()=>{var t;return 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)})};if(!(e.size>1048576&&"image/gif"!==e.type)||"function"!=typeof createImageBitmap)return t();let n=await createImageBitmap(e).catch(()=>null);if(!n)return t();try{let r=Math.min(1,1024/Math.max(n.width,n.height)),i=document.createElement("canvas");i.width=Math.max(1,Math.round(n.width*r)),i.height=Math.max(1,Math.round(n.height*r));let s=i.getContext("2d");if(!s)return t();s.fillStyle="#fff",s.fillRect(0,0,i.width,i.height),s.drawImage(n,0,0,i.width,i.height);let o=i.toDataURL("image/jpeg",.85).split(",")[1];return o&&o.length<4*Math.ceil(e.size/3)?{data:o,mimeType:"image/jpeg"}:t()}catch{return t()}finally{n.close()}}function iP(e){return{data:e.data,mimeType:e.mimeType}}function iz(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function iW(e){return(e??[]).filter(rp).slice(0,10).map(iz)}function iO(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function iD(e){let{kind:t,text:n}=e;return(0,r.jsxs)("div",{title:n,style:{display:"flex",alignItems:"center",gap:8,padding:"3px 10px",fontSize:12,color:"var(--text-muted)",minWidth:0},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontSize:10,fontFamily:"var(--font-mono)",padding:"1px 7px",borderRadius:999,border:`1px solid ${"steer"===t?"color-mix(in srgb, var(--accent) 45%, transparent)":"var(--border)"}`,color:"steer"===t?"var(--accent)":"var(--text-dim)"},children:t}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n})]})}function iF(e){let{tone:t,title:n,body:i,onClose:s}=e,o="error"===t?"239,68,68":"234,179,8";return(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid rgba(${o},0.3)`,borderRadius:6,background:`rgba(${o},0.07)`,color:`rgb(${o})`,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:n}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:i})]}),s&&(0,r.jsx)("button",{type:"button",onClick:s,"aria-label":"Dismiss",style:{flexShrink:0,background:"none",border:"none",padding:"0 2px",cursor:"pointer",color:"inherit",opacity:.7,fontSize:13,lineHeight:1},children:"\xd7"})]})}function iB(e){let{error:t}=e,{t:n}=(0,eO.s)();return t?(0,r.jsx)(iF,{tone:"error",title:n("chat.modelError"),body:t}):null}function iH(e){let{warnings:t}=e,{t:n}=(0,eO.s)();return t&&0!==t.length?(0,r.jsx)(iF,{tone:"warning",title:n(t.length>1?"chat.modelScopeWarnings":"chat.modelScopeWarning"),body:t.join("\n")}):null}let iU=(0,i.memo)((0,i.forwardRef)(function(e,t){let n,s,o,a,l,c,d,{onSend:u,onAbort:p,onSteer:h,onFollowUp:f,isStreaming:m,model:g,isAutoModelSelection:x,modelNames:v,modelList:b,modelError:y,modelScopeWarnings:j,onModelChange:k,modelSwitching:w,defaultModel:S,onSetDefaultModel:C,onCompact:N,onAbortCompaction:E,isCompacting:I,compactError:T,onDismissCompactError:$,compactResult:M,toolPreset:R,onToolPresetChange:L,thinkingLevel:A,isAutoThinkingSelection:P=!1,onThinkingLevelChange:z,availableThinkingLevels:W,thinkingLevelMap:O,savedDefaultThinkingLevel:D,onSetDefaultThinkingLevel:F,retryInfo:B,queuedMessages:H,inputHistory:U=[],onRecallQueue:_,slashCommands:q,slashCommandsLoading:K,onLoadSlashCommands:V,onBuiltinCommand:Z,soundEnabled:J,onSoundToggle:G,onAudioUnlock:Y,onPromptWithStreamingBehavior:X,draftKey:Q,cwd:ee,onAttachFiles:et,compact:en=!1}=e,{t:er}=(0,eO.s)(),{fontSize:ei}=rX(),{ui:es,uiWeight:eo}=id(),ea=(0,eD.a)(),el=rW(),[ec,ed]=(0,i.useState)(()=>Q?rg(Q)?.value??"":""),[eu,ep]=(0,i.useState)(!1),[eh,ef]=(0,i.useState)(!1),[em,eg]=(0,i.useState)(!1),[ex,ev]=(0,i.useState)(()=>Q?iW(rg(Q)?.images):[]),eb=ec.trimStart(),ey=0===ex.length&&eb.startsWith("!"),ej=ey&&eb.startsWith("!!"),[ek,ew]=(0,i.useState)(!1),[eS,eC]=(0,i.useState)(0),[eN,eE]=(0,i.useState)(null),[eI,eT]=(0,i.useState)(null),[e$,eM]=(0,i.useState)(!1),[eR,eL]=(0,i.useState)(null),[eA,eP]=(0,i.useState)(0),[ez,eW]=(0,i.useState)(!1),[eF,eB]=(0,i.useState)(!1),[eH,eU]=(0,i.useState)(0),[e_,eq]=(0,i.useState)(!1),eK=(0,i.useRef)(!1),[eV,eZ]=(0,i.useState)(null),[eJ,eG]=(0,i.useState)(!1),[eY,eX]=(0,i.useState)(null),[eQ,e0]=(0,i.useState)(null),e1=ee&&eQ?.cwd===ee?eQ.values:{},e2=(0,i.useRef)(null),e4=(0,i.useRef)(null),e8=(0,i.useRef)(null),e5=(0,i.useRef)(null),e9=(0,i.useRef)(null),tn=(0,i.useRef)(null),tr=(0,i.useRef)(!1),ti=(0,i.useRef)(0),ts=(0,i.useRef)(!1),to=(0,i.useRef)(null),ta=(0,i.useRef)([]),tl=(0,i.useRef)(null),tc=(0,i.useRef)([]),td=(0,i.useRef)([]),tu=(0,i.useRef)(null),tp=(0,i.useRef)(null),th=(0,i.useRef)(Q),tf=(0,i.useRef)(ec),tm=(0,i.useRef)(ex),tg=(0,i.useRef)(0);tf.current=ec,tm.current=ex,(0,i.useImperativeHandle)(t,()=>({insertIfEmpty(e){let t=e2.current;(t?t.value:ec).trim()||(tf.current=e,ed(e),eT(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){var t,n,r;let i=e2.current;if(t=i?i.value:ec,n=tm.current.length,r=tg.current,t.trim()||0!==n||0!==r)return;let s="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),o=iW("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 rp(r)?[r]:[]}));tf.current=s,tm.current=o,ed(s),eT(null),eB(!1),ev(e=>(e.forEach(iO),o)),requestAnimationFrame(()=>{i&&(i.focus(),i.style.height="auto",i.style.height=`${Math.min(i.scrollHeight,200)}px`)})},prependText(e){if(!e.trim())return;let t=e2.current,n=[e,t?t.value:ec].filter(e=>e.trim()).join("\n\n");tf.current=n,ed(n),eT(null),requestAnimationFrame(()=>{t&&(t.focus(),t.setSelectionRange(n.length,n.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(th.current!==e)return void rj(e,t);let n={value:tf.current,images:tm.current.map(iP)},r=rj(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(th.current=t,i)return;let s=iW(r.images);tf.current=r.value,tm.current=s,ed(r.value),ev(e=>(e.forEach(iO),s)),eT(null),eB(!1)},restoreSubmission(e,t,n){if(!e.trim()&&!t?.length)return;let r=th.current,i=n??r,s=i===r,o=!s&&i?rg(i):null,a=ry(e,t,s?tf.current:o?.value??"",s?tm.current.map(iP):o?.images??[]);if(i&&rx(i,a),!s)return;let l=t?.length?[...iW(t).slice(0,Math.max(0,10-tm.current.length)),...tm.current].slice(0,10):tm.current;tf.current=a.value,tm.current=l,ed(t=>{let n=rb(e,t);return tf.current=n,n}),eT(null),eB(!1),t?.length&&ev(e=>{let n=Math.max(0,10-e.length),r=iW(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tm.current=i,i}),requestAnimationFrame(()=>{let e=e2.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},focus(){let e=e2.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length))},insertText(e){let t=e2.current;if(!t)return void ed(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n);ij(t,n,r,(i.length>0&&!i.endsWith(" ")?" ":"")+e),eT(null)},addImages(e){tx(e)}}));let tx=(0,i.useCallback)(async e=>{if(en)return;let t=Math.max(0,10-tm.current.length-tg.current),n=e.filter(e=>e.type.startsWith("image/")&&e.size<=0xa00000).slice(0,t);if(n.length){tg.current+=n.length;try{let e=await Promise.all(n.map(async e=>({...await iA(e),previewUrl:URL.createObjectURL(e)})));ev(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(iO);let r=[...t,...n];return tm.current=r,r})}finally{tg.current-=n.length}}},[en]),tv=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",et?et(t):tx(t)},[et,tx]),tb=(0,i.useCallback)(e=>{ev(t=>{let n=[...t],[r]=n.splice(e,1);return r&&iO(r),tm.current=n,n})},[]),ty=(0,i.useCallback)(()=>{tm.current=[],ev(e=>(e.forEach(iO),[]))},[]),tj=(0,i.useCallback)(()=>{tf.current="",ed(""),eT(null),eB(!1),Q&&rv(Q),th.current&&th.current!==Q&&rv(th.current),ty(),e2.current&&(e2.current.style.height="auto")},[ty,Q]);(0,i.useEffect)(()=>{Q&&th.current===Q&&rx(Q,{value:ec,images:ex.map(iP)})},[ex,Q,ec]),(0,i.useEffect)(()=>{let e=th.current;if(e===Q)return;e&&rx(e,{value:tf.current,images:tm.current.map(iP)});let t=Q?rg(Q):null;th.current=Q;let n=t?.value??"",r=iW(t?.images);tf.current=n,tm.current=r,ed(n),eT(null),eB(!1),ev(e=>(e.forEach(iO),r))},[Q]);let tk=(0,i.useCallback)(()=>{let e=e2.current;e&&(e.style.height="auto",e.value&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[]);(0,i.useLayoutEffect)(tk,[ec,ei,es,eo,tk]),(0,i.useEffect)(()=>{let e=e2.current;if(!e)return;let t=-1,n=new ResizeObserver(e=>{let[n]=e;n.contentRect.width!==t&&(t=n.contentRect.width,tk())});return n.observe(e),()=>n.disconnect()},[tk]),(0,i.useEffect)(()=>{let e=e2.current;if(!e)return;let t=t=>{if("insertLineBreak"!==t.inputType||t.isComposing)return;let n=function(e,t,n){let r;if(t!==n)return null;let i=e.lastIndexOf("\n",t-1)+1,s=e.indexOf("\n",t),o=-1===s?e.length:s,a=e.slice(i,o),l=function(e){if(rC.test(e))return null;let t=rk.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=rw.exec(e)??rS.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!l||t-i<l.length||function(e){let t=null;for(let n of e.split("\n")){let e=rN.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(l.length).trim()?{start:i,end:o,text:""}:{start:t,end:t,text:`
10
- ${r=null===l.number?l.marker:`${String(Number(l.number)+1).padStart(l.number.length,"0")}${l.delimiter}`,`${l.indent}${r}${l.spacing}${l.task?"[ ] ":""}`}`}}(e.value,e.selectionStart,e.selectionEnd);n&&(t.preventDefault(),e.setSelectionRange(n.start,n.end),document.execCommand(n.text?"insertText":"delete",!1,n.text))};return e.addEventListener("beforeinput",t),()=>e.removeEventListener("beforeinput",t)},[]),(0,i.useEffect)(()=>()=>{tm.current.forEach(iO)},[]);let tw=(0,i.useCallback)(async e=>{if(ex.length||!e.startsWith("/")||!Z)return!1;if(eK.current)return!0;eK.current=!0,eq(!0);try{var t,n;let r=await Z(e);if(!r.handled)return!1;return r.error||(t=tf.current,n=tm.current.length,0!==n||t.trim()!==e)||tj(),!0}finally{eK.current=!1,eq(!1)}},[ex.length,tj,Z]),tS=(0,i.useCallback)(async()=>{var e;let t=ec.trim();(t||ex.length)&&(Y?.(),(!m||iE(e=t)||rI(e))&&await tw(t)||m||(tj(),u(t,ex.length?ex:void 0)))},[ec,ex,m,tw,u,tj,Y]),tC=!en&&ec.startsWith("/")&&!/\s/.test(ec.slice(1))?ec.slice(1).toLowerCase():null,tN=null===tC?[]:[...m?iN.filter(e=>e.availableWhileStreaming):iN,...q??[]].filter(e=>{let t=e.name.toLowerCase(),n=iR(e,er).toLowerCase();return t.includes(tC)||n.includes(tC)}).sort((e,t)=>{let n=iM(e,tC,er)-iM(t,tC,er);return 0!==n?n:i$[e.source]-i$[t.source]||iv.compare(e.name,t.name)}),{commands:tE,groups:tI}=(n=0,{commands:(s=iI.map(e=>{let t=tN.filter(t=>t.source===e),r="skill"===e?[...t.filter(e=>!iL(e,e1)),...t.filter(e=>iL(e,e1))]:t;return{source:e,items:r.map(e=>({command:e,index:n++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(e=>{let{command:t}=e;return t})),groups:s}),tT=1===tN.length?er(tC?"chat.match":"chat.command"):er(tC?"chat.matches":"chat.commands",{count:tN.length}),t$=!!ec.trim()||ex.length>0,tM=en||ea&&m,tR=ex.length>0&&!function(e,t){if(!e)return!0;let n=t?.find(t=>t.provider===e.provider&&t.id===e.modelId);return!n||!n.input||n.input.includes("image")}(g,b)&&!ez;(0,i.useEffect)(()=>{0===ex.length&&eW(!1)},[ex.length]);let tL=(0,i.useCallback)((e,t)=>{if(!ee)return void eT(null);let n=t??e.length;eT(e7(e.slice(0,n)))},[ee]),tA=eI?.query??null,tP=i.useMemo(()=>null!==tA&&eV&&eV.cwd===ee?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:tt(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:tt(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||te(e.entry.path)-te(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(eV.entries,tA):[],[tA,eV,ee]),tz=!!(tA&&eV?.truncated&&eV.cwd===ee);(0,i.useEffect)(()=>{if(!tz||!ee||!tA)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}&q=${encodeURIComponent(tA)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>eX({cwd:ee,query:tA,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tz,tA,ee]);let tW=tz&&null!==eY&&eY.cwd===ee&&eY.query===tA,tO=tW?eY.matches:tP,tD=null===eI?null:`${eI.start}:${+!!eI.quoted}:${eI.query}`;(0,i.useEffect)(()=>{if(null===tD){eM(!1),eP(0);return}eM(!0),eP(0)},[tD]);let tF=null!==eI;(0,i.useEffect)(()=>{if(!tF||!ee)return;let e=tu.current;e&&e.cwd===ee&&Date.now()-e.fetchedAt<1e4||tp.current===ee||(tp.current=ee,eG(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{eZ({cwd:ee,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)=>te(e.path)-te(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tu.current={cwd:ee,fetchedAt:Date.now()}}).catch(()=>{tu.current=null}).finally(()=>{tp.current=null,eG(!1)}))},[tF,ee]);let tB=(0,i.useCallback)(e=>{if(!eI)return;let t=e2.current;if(!t)return;let n=t.selectionStart??t.value.length,r=n+(eI.quoted&&'"'===t.value[n]?1:0),i=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let s=i?`@"${r}" `:`@${r} `;return{text:s,cursorOffset:s.length}}(e.path,e.isDir,eI.quoted),s=eI.start+i.cursorOffset;ij(t,eI.start,r,i.text,i.cursorOffset),eT(e7(t.value.slice(0,s)))},[eI]);(0,i.useEffect)(()=>{eA>=tO.length&&eP(Math.max(0,tO.length-1))},[tO.length,eA]),(0,i.useEffect)(()=>{tc.current.length=tO.length},[tO.length]),(0,i.useEffect)(()=>{e$&&tc.current[eA]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eA,e$]),(0,i.useEffect)(()=>{eH>=U.length&&eU(Math.max(0,U.length-1))},[U.length,eH]),(0,i.useEffect)(()=>{td.current.length=U.length},[U.length]),(0,i.useEffect)(()=>{eF&&td.current[eH]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eH,eF]);let tH=(0,i.useCallback)(e=>{ed(e),eB(!1),eU(0),eT(null),requestAnimationFrame(()=>{let t=e2.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),tU=(0,i.useCallback)(e=>{let t=`/${e.name} `;ed(t),ew(!1),eC(0),requestAnimationFrame(()=>{let e=e2.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),t_=(0,i.useCallback)(e=>{let t=ec.trim();if(!t&&!ex.length)return;Y?.();let n=ex.length?ex:void 0,r=()=>{if(t.startsWith("/")&&X){tj(),X(t,"steer"===e?"steer":"followUp",n);return}tj(),"steer"===e&&h?h(t,n):"followup"===e&&f&&f(t,n)};!ex.length&&Z&&iE(t)?tw(t):!ex.length&&Z&&rI(t)?tw(t).then(e=>{e||r()},()=>r()):r()},[ec,ex,Z,X,h,f,tj,Y,tw]),tq=(0,i.useCallback)(e=>{let t=tE.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eS-1);if("right"===e)return Math.min(t,eS+1);let n=ta.current[eS];if(!n)return"down"===e?Math.min(t,eS+1):Math.max(0,eS-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,s=r.top+r.height/2,o=-1,a=1/0;for(let n=0;n<=t;n+=1){if(n===eS)continue;let t=ta.current[n];if(!t)continue;let r=t.getBoundingClientRect(),l=r.top+r.height/2-s;if("down"===e?l<=4:l>=-4)continue;let c=1e3*Math.abs(l)+Math.abs(r.left+r.width/2-i);c<a&&(o=n,a=c)}return o>=0?o:"down"===e?Math.min(t,eS+1):Math.max(0,eS-1)},[tE.length,eS]),tK=(0,i.useCallback)(e=>{let t=e.nativeEvent,n="Enter"===e.key&&!e.shiftKey,r=ea||"ctrlEnter"===el?n&&(e.ctrlKey||e.metaKey):n,i=ea?r:n,s=Date.now()-ti.current<100,o=tr.current||t.isComposing||229===t.keyCode;if(i&&(o||s)){s&&e.preventDefault();return}if(eF&&!o){if("ArrowDown"===e.key){e.preventDefault(),eU(e=>Math.min(Math.max(0,U.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eU(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),eB(!1);return}if(("Tab"===e.key||i)&&U[eH]){e.preventDefault(),tH(U[eH]);return}}if(ek&&null!==tC){if("ArrowDown"===e.key){e.preventDefault(),eC(tq("down"));return}if("ArrowUp"===e.key){e.preventDefault(),eC(tq("up"));return}if("ArrowRight"===e.key){e.preventDefault(),eC(tq("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),eC(tq("left"));return}if("Escape"===e.key){e.preventDefault(),ew(!1);return}let t=tE[eS];if("Tab"===e.key&&t){e.preventDefault(),tU(t);return}if(i&&t){e.preventDefault(),r&&function(e,t,n){if("builtin"===t.source)return"builtin"===t.source&&e.trim()===`/${t.name}`&&(!n||!0===t.availableWhileStreaming);return rE(t)&&rI(e)}(ec,t,m)?(ew(!1),tS()):tU(t);return}}if(e$&&null!==eI&&!o){if("ArrowDown"===e.key){e.preventDefault(),eP(e=>ib(e,tO.length,1));return}if("ArrowUp"===e.key){e.preventDefault(),eP(e=>ib(e,tO.length,-1));return}if("Escape"===e.key){e.preventDefault(),eM(!1);return}if(("Tab"===e.key||i)&&tO[eA]){e.preventDefault(),tB(tO[eA]);return}}if("ArrowUp"===e.key&&!o&&!m&&U.length>0&&0===ec.trim().length){e.preventDefault(),ew(!1),eM(!1),eU(U.length-1),eB(!0);return}if("Escape"===e.key&&!o&&m&&p){e.preventDefault(),p();return}r&&(e.preventDefault(),m&&(h||f)?t_(e.altKey&&f||!h?"followup":"steer"):tS())},[ea,el,m,h,f,p,ek,tC,tE,eS,tU,t_,tS,tq,e$,eI,tO,eA,tB,eF,U,eH,tH,ec]),tV=(0,i.useCallback)(()=>{let e=e2.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),tZ=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!en&&t.length){e.preventDefault(),tx(t.map(e=>e.getAsFile()).filter(e=>null!==e));return}let n=e.clipboardData.getData("text/html"),r=e.clipboardData.getData("text/plain");if(!n||!r)return;let i=new DOMParser().parseFromString(n,"text/html"),s=function(e,t){let n="",r=0,i=!1;for(let{label:s,href:o,occurrence:a}of t){if(!s||!o)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 l=s.replace(/([\\[\]])/g,"\\$1"),c=o.replace(/([\\()])/g,"\\$1");n+=`${e.slice(r,t)}[${l}](${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 o=e.currentTarget,a=o.selectionStart,l=o.value.slice(0,a)+s+o.value.slice(o.selectionEnd);e.preventDefault(),tf.current=l,ed(l),eB(!1),tL(l,a+s.length),requestAnimationFrame(()=>{o.focus(),o.setSelectionRange(a+s.length,a+s.length)})},[en,tx,tL]);(0,i.useEffect)(()=>{if(null===tC){ew(!1),eC(0),ts.current=!1;return}ew(!0),eC(0),!ts.current&&V&&(ts.current=!0,Promise.resolve(V()).catch(()=>{ts.current=!1}))},[tC,V]),(0,i.useEffect)(()=>{if(!ek||!ee)return;let e=!1;return e0({cwd:ee,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(ee)}`).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;e0({cwd:ee,values:n})}).catch(()=>{e||e0({cwd:ee,values:{}})}),()=>{e=!0}},[ek,ee]),(0,i.useEffect)(()=>{eS>=tE.length&&eC(Math.max(0,tE.length-1))},[tE.length,eS]),(0,i.useEffect)(()=>{ta.current.length=tE.length},[tE.length]),(0,i.useEffect)(()=>{ek&&ta.current[eS]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eS,ek]),(0,i.useLayoutEffect)(()=>{if(!ek||null===tC)return void eE(null);let e=to.current;if(e)return ik(e,e=>{eE(t=>t===e?t:e)})},[ek,tC]),(0,i.useLayoutEffect)(()=>{if(!e$||null===eI)return void eL(null);let e=tl.current;if(e)return ik(e,e=>{eL(t=>t===e?t:e)})},[e$,eI]);let tJ=b&&b.length>0?b.map(e=>({provider:e.provider,modelId:e.id,name:e.name})):Object.entries(v??{}).map(e=>{let[t,n]=e;return{provider:g?.provider??"unknown",modelId:t,name:n}}),tG=M?Math.max(0,M.tokensBefore-M.estimatedTokensAfter):0,tY=M?`${M.reason&&"manual"!==M.reason?`${M.reason[0].toUpperCase()}${M.reason.slice(1)} `:er("chat.compacted")} ${iC(M.tokensBefore)} -> ${iC(M.estimatedTokensAfter)} tokens (${er("chat.tokensSaved",{saved:iC(tG)})})`:null,tX=A&&"auto"!==A?A:null,tQ="auto"!==(o=tX??"auto")&&O?O[o]??o:o,t0=Object.entries(ix).find(e=>{let[,t]=e;return t===(R??"configured")})?.[0]??"configured",t1="chat-only"===t0?er("chat.chatOnly"):t0;(0,i.useEffect)(()=>{let e=e=>{e4.current&&!e4.current.contains(e.target)&&ep(!1),e8.current&&!e8.current.contains(e.target)&&ef(!1),e5.current&&!e5.current.contains(e.target)&&eg(!1),!e9.current||e9.current.contains(e.target)||e2.current?.contains(e.target)||eB(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{m&&ep(!1)},[m]);let t2=(0,i.useRef)(-1/0);(0,i.useLayoutEffect)(()=>{if(m)return()=>{t2.current=performance.now()}},[m]);let t4=e=>{var t,n;return t=e.detail,n=performance.now()-t2.current,t>0&&n<600};return(0,i.useEffect)(()=>{ea||eg(!1)},[ea]),(0,r.jsxs)("fieldset",{disabled:e_,"aria-busy":e_,className:en?void 0:"chat-input-shell",style:{flexShrink:0,minWidth:0,margin:0,border:0,background:"transparent",padding:en?0:"0 16px 8px",paddingRight:en?0:ea?16:52,opacity:e_?.5:1,transition:"opacity 0.15s"},children:[!en&&(0,r.jsx)("input",{ref:tn,type:"file",accept:et?void 0:"image/*",multiple:!0,style:{display:"none"},onChange:tv}),(0,r.jsxs)("div",{style:{maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(0,r.jsx)(iB,{error:y}),(0,r.jsx)(iH,{warnings:j}),tR&&(a=b?.find(e=>e.provider===g?.provider&&e.id===g?.modelId),(0,r.jsx)(iF,{tone:"warning",title:er("chat.imageNotSupportedTitle"),body:er("chat.imageNotSupportedBody",{model:a?.name||g?.modelId||""}),onClose:()=>eW(!0)})),(H?.steering.length??0)+(H?.followUp.length??0)>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:er("chat.queued",{count:(H?.steering.length??0)+(H?.followUp.length??0)})}),_&&(0,r.jsxs)("button",{onClick:_,title:er("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:7,cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),er("chat.recall")]})]}),H?.steering.map((e,t)=>(0,r.jsx)(iD,{kind:"steer",text:e},`steer-${t}`)),H?.followUp.map((e,t)=>(0,r.jsx)(iD,{kind:"follow-up",text:e},`followup-${t}`))]}),B&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"rgba(234,179,8,0.08)",border:"1px solid rgba(234,179,8,0.25)",borderRadius:6,fontSize:12,color:"rgba(180,130,0,0.9)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),er("chat.retrying",{attempt:B.attempt,max:B.maxAttempts}),B.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",B.errorMessage]})]}),tY&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"rgba(16,185,129,0.08)",border:"1px solid rgba(16,185,129,0.24)",borderRadius:6,fontSize:12,color:"rgba(5,150,105,0.95)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),tY]}),T&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,marginBottom:8,padding:$?"3px 3px 3px 10px":"7px 10px",background:"rgba(239,68,68,0.07)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:6,color:"#ef4444",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,padding:$?"4px 0":0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:T}),$&&(0,r.jsx)(e6,{onClick:$,title:er("chat.dismissCompactError")})]}),ex.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:ex.map((e,t)=>(0,r.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,r.jsx)(rT.k,{src:e.previewUrl,children:(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:6,border:"1px solid var(--border)",display:"block"}})},e.previewUrl),(0,r.jsx)("button",{type:"button",onClick:()=>tb(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},t))}),(0,r.jsxs)("div",{style:{position:"relative",minWidth:0},children:[eF&&U.length>0&&(0,r.jsxs)("div",{ref:e9,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",maxHeight:"min(44vh, 360px)"},children:[(0,r.jsx)("div",{title:er("chat.inputHistory"),style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:"calc(min(44vh, 360px) - 31px)",overflowY:"auto",padding:4},children:U.map((e,t)=>{let n=t===eH;return(0,r.jsxs)("button",{ref:e=>{td.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tH(e)},onMouseEnter:()=>eU(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),ek&&null!==tC&&(0,r.jsxs)("div",{ref:to,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===eN?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${eN}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:K?er("chat.loadingCommands"):er("chat.slashCommands",{label:tT})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:er("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:10},children:K||0!==tN.length?tI.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:er(iT[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(e=>{let{command:t,index:n}=e,i=n===eS,s=iL(t,e1);return(0,r.jsxs)("button",{ref:e=>{ta.current[n]=e},type:"button",onMouseDown:e=>{e.preventDefault(),tU(t)},onMouseEnter:()=>eC(n),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${i?"var(--accent)":"var(--border)"}`,borderRadius:7,background:i?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:i?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:s?"var(--text-dim)":void 0},children:["/",t.name,s&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:er("chat.dormant")})]}),t.description&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:iR(t,er)})]},`${t.source}:${t.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:er("chat.noCommands")})})]}),e$&&null!==eI&&(l=eJ&&(!eV||eV.cwd!==ee),c=1===tO.length?er("chat.match"):er("chat.matches",{count:tO.length}),d=eV?.truncated&&!tW?eI.query?er("chat.searchingAll"):er("chat.indexTruncated"):"",(0,r.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",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eR?"min(48vh, 400px)":`min(48vh, 400px, ${eR}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:l?er("chat.loadingFiles"):er("chat.files",{label:c,hint:d})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:er("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:l||0!==tO.length?tO.map((e,t)=>{let n=t===eA,i=e.path.split("/").pop()??e.path,s=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tc.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tB(e)},onMouseEnter:()=>eP(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(e3.sj,{size:14}):(0,e3.I3)(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[s&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:s}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:tz&&!tW?er("chat.searching"):er("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{style:{minWidth:0,display:"flex",flexDirection:tM?"column":"row",gap:8,alignItems:tM?"stretch":"center",background:"var(--bg)",border:en?"none":`1px solid ${ey?"var(--tool-bg)":m&&(h||f)?"rgba(234,179,8,0.4)":"color-mix(in srgb, var(--border) 70%, transparent)"}`,borderRadius:14*!en,padding:en?0:ea?"6px 6px 6px 12px":"10px 10px 10px 14px",boxShadow:en?"none":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("textarea",{ref:e2,className:"chat-input-textarea","aria-label":en?er("chat.quoteQuestion"):void 0,value:ec,onChange:e=>{tf.current=e.target.value,ed(e.target.value),eB(!1),tL(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;tL(t.value,t.selectionStart)},onKeyDown:tK,onCompositionStart:()=>{tr.current=!0},onCompositionEnd:e=>{tr.current=!1,ti.current=Date.now();let t=e.currentTarget;tL(t.value,t.selectionStart)},onInput:tV,onPaste:tZ,placeholder:m&&(h||f)?er("chat.steerPlaceholder"):m?er("chat.agentPlaceholder"):er("chat.messagePlaceholder"),rows:1,style:{flex:tM?"none":1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:"var(--chat-content-font-size, 14px)",lineHeight:1.6,fontFamily:"inherit",minHeight:en?96:24,maxHeight:200,overflow:"auto"}}),m?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[h&&(0,r.jsxs)("button",{onClick:()=>t_("steer"),disabled:!t$,title:er("chat.steerHint"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:t$?"rgba(234,179,8,0.12)":"none",border:"1px solid rgba(234,179,8,0.35)",borderRadius:8,color:t$?"rgba(180,130,0,1)":"var(--text-dim)",cursor:t$?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),er("chat.steer")]}),f&&(0,r.jsxs)("button",{onClick:()=>t_("followup"),disabled:!t$,title:`${er("chat.followUpHint")} (${ea?"Ctrl/Cmd+":""}Alt/Option+Enter)`,"aria-keyshortcuts":ea?"Control+Alt+Enter Meta+Alt+Enter":"Alt+Enter",style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:t$?"rgba(129,140,248,0.12)":"none",border:"1px solid rgba(129,140,248,0.35)",borderRadius:8,color:t$?"rgba(99,102,241,1)":"var(--text-dim)",cursor:t$?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),er("chat.followUp")]})]}):(0,r.jsxs)("button",{onClick:tS,disabled:!ec.trim()&&!ex.length,title:er("chat.send"),"aria-label":er("chat.send"),style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,...ea?{width:36,height:36,padding:0}:{padding:"7px 14px"},background:ec.trim()||ex.length?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:ec.trim()||ex.length?"var(--accent-contrast)":"var(--text-dim)",cursor:ec.trim()||ex.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:ec.trim()||ex.length?"0 1px 3px color-mix(in srgb, var(--accent) 25%, transparent)":"none",transition:"background 0.15s, box-shadow 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),!ea&&er("chat.send")]})]})]}),ey&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:ej?"var(--text-muted)":"var(--accent)",marginTop:4},children:[er("chat.shell")," \xb7 ",ej?er("chat.outputLocal"):er("chat.outputModel")]}),!en&&(0,r.jsxs)("div",{className:"chat-input-controls",style:{marginTop:ea?4:8,display:ea?"grid":"flex",gridTemplateColumns:ea?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:ea?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2},children:[(0,r.jsx)("button",{onClick:()=>tn.current?.click(),title:er("chat.attachFiles"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:ex.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=ex.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=ex.length?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),(tJ.length>0||g||y)&&k&&(0,r.jsx)(ih,{options:tJ,value:g,onChange:k,onReselect:k,disabled:m,busy:w,isAutoSelection:x,defaultValue:S,onSetDefault:C})]}),!ea&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsxs)("div",{ref:e5,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:ea?0:"auto"},children:[ea&&(0,r.jsx)("button",{type:"button",title:em?void 0:er("chat.moreControls"),"aria-label":er("chat.moreControls"),"aria-expanded":em,"aria-hidden":em||void 0,tabIndex:em?-1:void 0,onClick:()=>{eg(!0)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:32,padding:"8px 10px",background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:em?"default":"pointer",fontSize:12,fontWeight:500,visibility:em?"hidden":"visible",pointerEvents:em?"none":"auto",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{em||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{em||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:er("chat.moreControls")}),(0,r.jsxs)("div",{style:{display:ea?em?"flex":"none":"flex",alignItems:"center",gap:ea?1:2,...ea?{position:"absolute",right:0,bottom:0,zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"nowrap",justifyContent:"flex-end",border:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:10,background:"color-mix(in srgb, var(--bg-panel) 92%, var(--bg))",boxShadow:"0 8px 24px rgba(0,0,0,0.14)",backdropFilter:"blur(10px)"}:null},children:[z&&(0,r.jsxs)("div",{ref:e8,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>ef(e=>!e),title:m?er("chat.currentReasoning",{level:tQ}):er("chat.changeReasoning",{level:tQ}),"aria-label":er("chat.changeReasoningLabel"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ea?"0 6px":"8px 12px",width:ea?"auto":void 0,height:32,background:eh?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=eh?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),(!ea||em)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:tQ})]}),eh&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",...ea?{left:0}:{right:0},zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:180},children:iw.filter(e=>!W||"auto"===e||W.includes(e)).map(e=>{let t="auto"===e?P:!P&&tX===e,n=er(iS[e]),i="auto"!==e&&O?O[e]:void 0,s=null!=i&&i!==e?i:e,o=null!=i&&i!==e;return(0,r.jsxs)(ip,{active:t,onSelect:()=>{if(ef(!1),"auto"===e){P||z("auto");return}(!t||P)&&z(e)},gutter:!!F,star:F&&"auto"!==e?{isDefault:D===e,saveLabel:er("chat.saveDefaultThinking"),defaultLabel:er("chat.defaultThinking"),onSave:()=>{ef(!1),F(e)}}:void 0,children:[(0,r.jsxs)("span",{style:{flex:1},children:[s,o&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",e,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:n})]},e)})})]}),!m&&L&&(0,r.jsxs)("div",{ref:e4,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:e=>{m||t4(e)||ep(e=>!e)},disabled:m,title:er("chat.changeToolPreset")+`: ${t1}`,"aria-label":er("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ea?"0 6px":"8px 12px",width:ea?"auto":void 0,height:32,background:eu?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:m?"not-allowed":"pointer",fontSize:12,opacity:m?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{m||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eu?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(!ea||em)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t1})]}),eu&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:ea?void 0:0,left:ea?0: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:ig.map(e=>{let t,n=ix[e],i=(R??"configured")===n;return t="configured"===e?er("chat.configuredTools"):"chat-only"===e?er("chat.chatOnly"):"read-only"===e?er("chat.readOnlyTools",{count:4}):"default"===e?er("chat.builtInTools",{count:4}):er("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{ep(!1),i||L(n)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:t})]},e)})})]}),(!m||I)&&N&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{onClick:I?E:e=>{t4(e)||N()},style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ea?"0 6px":"8px 12px",width:ea?"auto":void 0,height:32,background:I?"rgba(239,68,68,0.08)":"none",border:"none",borderRadius:9,color:I?"#ef4444":"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=I?"rgba(239,68,68,0.16)":"var(--bg-hover)",e.currentTarget.style.color=I?"#ef4444":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=I?"rgba(239,68,68,0.08)":"none",e.currentTarget.style.color=I?"#ef4444":"var(--text-muted)"},title:I?er("chat.stopCompaction"):er("chat.compactContext"),"aria-label":I?er("chat.stopCompaction"):er("chat.compactContext"),children:I?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(!ea||em)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:er("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(!ea||em)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:er("chat.compact")})]})})}),m&&(0,r.jsxs)("button",{onClick:p,title:er("chat.stopAgent"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:32,background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:9,color:"#ef4444",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.16)"},onMouseLeave:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),er("chat.stop")]}),void 0!==G&&(0,r.jsx)("button",{onClick:G,title:J?er("chat.disableSound"):er("chat.enableSound"),"aria-label":J?er("chat.disableSound"):er("chat.enableSound"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:J?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",opacity:J?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=J?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.opacity=J?"1":"0.55"},children:J?(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),(0,r.jsx)("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),(0,r.jsx)("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})}),ea&&em&&(0,r.jsx)("button",{type:"button",title:er("chat.collapseControls"),"aria-label":er("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{ep(!1),ef(!1),eg(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]})]})]})]})}));var i_=n(34039),iq=n(86453),iK=n(89983);let iV="pi-web:minimap-preview-locked";function iZ(){try{return window.localStorage}catch{return null}}function iJ(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:iZ();if(!e)return!1;try{return"true"===e.getItem(iV)}catch{return!1}}var iG=n(55520),iY=n.n(iG);function iX(e){let{level:t,children:n,headingIndex:i,onClick:s}=e;return(0,r.jsx)("button",{type:"button",className:iY().heading,"data-level":t,"data-preview-heading-index":i??void 0,disabled:null===i||!s,onClick:e=>{e.stopPropagation(),null!==i&&s?.(i)},children:n})}let iQ=[...iK.iA??[],function(){return e=>{if(!Array.isArray(e.children))return;let t=e.children.filter(e=>"heading"===e.type&&"number"==typeof e.depth&&e.depth<=3);if(t.length>0){t.forEach((e,t)=>{e.data={...e.data,hProperties:{...e.data?.hProperties,"data-preview-heading-index":t}}}),e.children=t;return}let n=e.children.find(e=>"paragraph"===e.type);e.children=n?[n]:[]}}],i0=[[iq.A,{throwOnError:!1,strict:!1}]];function i1(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 i2=(0,i.memo)(function(e){let{markdown:t,onHeadingClick:n,onAnswerClick:s}=e,o=(0,i.useMemo)(()=>(0,iK.Ep)(t),[t]);return t?(0,r.jsx)("div",{className:iY().outline,children:(0,r.jsx)(i_.oz,{remarkPlugins:iQ,rehypePlugins:i0,components:{h1:e=>{let{children:t,node:i}=e;return(0,r.jsx)(iX,{level:1,headingIndex:i1(i),onClick:n,children:t})},h2:e=>{let{children:t,node:i}=e;return(0,r.jsx)(iX,{level:2,headingIndex:i1(i),onClick:n,children:t})},h3:e=>{let{children:t,node:i}=e;return(0,r.jsx)(iX,{level:3,headingIndex:i1(i),onClick:n,children:t})},h4:()=>null,h5:()=>null,h6:()=>null,p:e=>{let{children:t}=e;return(0,r.jsx)("button",{type:"button",className:iY().paragraph,onClick:s,children:t})},blockquote:()=>null,ul:()=>null,ol:()=>null,pre:()=>null,table:()=>null,hr:()=>null,a:e=>{let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})},code:e=>{let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})}},children:o})}):null}),i4=(0,i.memo)(function(e){let{messages:t,getStreamingMessage:n,scrollContainer:s,messageRefs:o,onRevealHistory:a,turnsBefore:l}=e,{t:c}=(0,eO.s)(),[d,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)([]),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(600),[v,b]=(0,i.useState)(!1),[y,j]=(0,i.useState)(iJ),[k,w]=(0,i.useState)(null),S=(0,i.useRef)(!1),C=(0,i.useRef)(null),N=(0,i.useRef)([]),E=(0,i.useRef)({nodes:[],gap:50,fillsHeight:!1}),I=(0,i.useRef)(null),T=(0,i.useRef)(new Map),$=(0,i.useRef)(null),M=(0,i.useRef)(null),R=(0,i.useRef)(null),L=(0,i.useRef)(t);L.current=t;let A=(0,i.useMemo)(()=>(function(e,t){if(0===e.length)return{nodes:[],gap:50,fillsHeight:!1};let n=Math.max(1,t),r=Math.max(0,n-12-48);if(1===e.length)return{nodes:[{...e[0],topRatio:12/n}],gap:50,fillsHeight:!1};let i=r/(e.length-1),s=Math.min(50,i);return{nodes:e.map((e,t)=>({...e,topRatio:(12+t*s)/n})),gap:s,fillsHeight:i<=50}})(p,g),[p,g]),{nodes:P,gap:z}=A;E.current=A;let W=(0,i.useCallback)(e=>{M.current={index:e,until:Date.now()+1600},m(e)},[]),O=(0,i.useCallback)((e,t)=>{let n=M.current;if(n&&Date.now()<n.until)return void m(n.index);M.current=null;let r=t.filter(e=>null!==e.targetTurn.scrollTop);if(0===r.length)return void m(null);let i=e.scrollTop+.3*e.clientHeight;m(r.reduce((e,t)=>Math.abs((t.targetTurn.scrollTop??0)-i)<Math.abs((e.targetTurn.scrollTop??0)-i)?t:e,r[0]).index)},[]),D=(0,i.useCallback)(()=>{let e=s.current;if(!e)return;let t=e.scrollHeight-e.clientHeight,n=N.current;u(t>20),O(e,n)},[s,O]),F=(0,i.useRef)(null),B=(0,i.useCallback)(()=>{F.current||(F.current=setTimeout(()=>{F.current=null;let e=s.current,t=C.current;if(!e||!t)return;let r=o.current,i=e.getBoundingClientRect(),a=[],l=0,c=null,d=n();for(let t of d?[...L.current,d]:L.current){let n=(0,n4.Y0)(t);if(!n&&"assistant"!==t.role)continue;let s=r?.[l];if(l++,n){c=null;let n=s?.getBoundingClientRect();c={userMessage:t,assistantPreviews:[],scrollTop:n?n.top-i.top+e.scrollTop:null,toolCount:0},a.push(c);continue}if(!c)continue;c.toolCount+="assistant"===t.role&&Array.isArray(t.content)?t.content.reduce((e,t)=>e+ +("toolCall"===t.type),0):0;let o=function(e){if("assistant"!==e.role)return"";let{answerBlocks:t}=(0,n4.dQ)(e);return t.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n").trim()}(t);o&&c.assistantPreviews.push({markdown:o,element:s})}let p=a.map((e,t)=>({topRatio:0,targetTurn:e,index:t}));x(t.clientHeight),N.current=p,h(p),u(e.scrollHeight-e.clientHeight>20),O(e,p);let f=R.current,m=f?p[f.nodeIndex]:null;if(f&&m){let t=void 0===f.assistantIndex?null:m.targetTurn.assistantPreviews[f.assistantIndex],n=m.targetTurn.scrollTop;if("assistant"===f.target){let r=t?.element?.getBoundingClientRect();n=r?r.top-i.top+e.scrollTop:null}else if("heading"===f.target){let r=void 0===f.headingIndex?null:t?.element?.querySelectorAll("h1, h2, h3").item(f.headingIndex),s=r?.getBoundingClientRect();n=s?s.top-i.top+e.scrollTop:null}if(null===n)return;R.current=null,W(m.index);let r=.3*e.clientHeight;e.scrollTo({top:Math.max(0,n-r),behavior:"smooth"})}},150))},[n,W,o,s,O]);(0,i.useEffect)(()=>{let e=s.current;if(e)return e.addEventListener("scroll",D,{passive:!0}),()=>e.removeEventListener("scroll",D)},[s,D]),(0,i.useEffect)(()=>{let e=s.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(),F.current&&(clearTimeout(F.current),F.current=null)}},[B,s,D]),(0,i.useEffect)(()=>{let e=setTimeout(()=>{B(),D()},50);return()=>clearTimeout(e)},[t.length,B,D]);let H=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;if(W(e.index),null===e.targetTurn.scrollTop){R.current={nodeIndex:e.index,target:"user"},a();return}let r=Math.max(0,e.targetTurn.scrollTop-.3*n.clientHeight);n.scrollTo({top:r,behavior:t})},[W,a,s]),U=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;let r=e.targetTurn.assistantPreviews[t]?.element;if(!r){R.current={nodeIndex:e.index,target:"assistant",assistantIndex:t},a();return}let i=n.getBoundingClientRect(),o=r.getBoundingClientRect().top-i.top+n.scrollTop-.3*n.clientHeight;W(e.index),n.scrollTo({top:Math.max(0,o),behavior:"smooth"})},[W,a,s]),_=(0,i.useCallback)(e=>{let{nodes:t,gap:n,fillsHeight:r}=E.current,i=C.current?.clientHeight??0;if(0===t.length||i<=0)return null;let s=Math.max(0,Math.min(i,e*i)),o=t[0].topRatio*i,a=n>0?Math.round((s-o)/n):0,l=Math.max(0,Math.min(t.length-1,a)),c=t[l];if(!r&&Math.abs(s-c.topRatio*i)>Math.max(10,n/2))return null;return c},[]),q=(0,i.useCallback)((e,t,n)=>{let r=s.current;if(!r)return;let i=e.targetTurn.assistantPreviews[t]?.element;if(!i){R.current={nodeIndex:e.index,target:"heading",assistantIndex:t,headingIndex:n},a();return}let o=i.querySelectorAll("h1, h2, h3").item(n);if(!o)return;let l=r.getBoundingClientRect(),c=o.getBoundingClientRect().top-l.top+r.scrollTop-.3*r.clientHeight;W(e.index),r.scrollTo({top:Math.max(0,c),behavior:"smooth"})},[W,a,s]),K=(0,i.useCallback)(()=>{$.current&&(clearTimeout($.current),$.current=null)},[]),V=(0,i.useCallback)(()=>{y||(K(),b(!0))},[K,y]),Z=(0,i.useCallback)(()=>{let e=!y;j(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:iZ();if(t)try{t.setItem(iV,String(e))}catch{}}(e),e&&(K(),b(!1),w(null))},[K,y]),J=(0,i.useCallback)(()=>{K(),$.current=setTimeout(()=>{$.current=null,b(!1),w(null)},250)},[K]);(0,i.useEffect)(()=>()=>K(),[K]);let G=(0,i.useCallback)(e=>{if(!d)return;S.current=!0,V();let t=e.currentTarget.getBoundingClientRect();w(Math.max(0,Math.min(1,(e.clientY-t.top)/t.height)));let n=(e,n)=>{let r=_(Math.max(0,Math.min(1,(e-t.top)/t.height)));r&&H(r,n)};n(e.clientY,"smooth");let r=e=>{S.current&&n(e.clientY,"auto")},i=()=>{S.current=!1,window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",i)};window.addEventListener("mousemove",r),window.addEventListener("mouseup",i)},[_,H,V,d]),Y=null===k?null:_(k),X=Y?.index??null;if((0,i.useEffect)(()=>{if(!v||null===X)return;let e=I.current,t=T.current.get(X);if(!e||!t)return;let n=t.offsetTop-(e.clientHeight-t.offsetHeight)/2;e.scrollTop=Math.max(0,n)},[p,v,X]),!d)return null;let Q=Math.max(1,(P.length>0?P[P.length-1].topRatio*g:12)-12);return(0,r.jsxs)("div",{ref:C,onMouseDown:G,onMouseEnter:V,onMouseLeave:J,onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();w((e.clientY-t.top)/t.height)},style:{width:36,flexShrink:0,position:"relative",cursor:"pointer",userSelect:"none",borderLeft:"1px solid var(--border)",background:"var(--bg-panel)",overflow:"visible"},children:[l>0&&(0,r.jsx)("div",{"data-minimap-earlier":"",style:{position:"absolute",left:"50%",top:0,height:12,width:1,background:"repeating-linear-gradient(to bottom, var(--text-dim) 0 2px, transparent 2px 4px)",transform:"translateX(-50%)",zIndex:0}}),(0,r.jsx)("div",{style:{position:"absolute",left:"50%",top:12,height:Q,width:1,background:"var(--border)",transform:"translateX(-50%)",zIndex:0}}),P.map(e=>{let t=v&&Y?.index===e.index,n=f===e.index;return(0,r.jsx)("div",{"data-minimap-node-index":e.index,"data-minimap-node-active":n?"":void 0,style:{position:"absolute",top:`${100*e.topRatio}%`,transform:"translateY(-50%)",left:0,right:0,height:Math.max(1,z),display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none",zIndex:2},children:(0,r.jsx)("div",{style:{width:8,height:8,borderRadius:2,background:n?"rgba(128,128,128,0.42)":"rgba(128,128,128,0.16)",border:`1.5px solid ${n?"rgba(128,128,128,0.95)":"rgba(128,128,128,0.58)"}`,boxShadow:n?"0 0 0 2px var(--bg-panel)":"none",transition:"transform 0.1s, background 0.1s",transform:t?"scale(1.25)":"scale(1)"}})},e.index)}),(0,r.jsx)("button",{type:"button",className:iY().lock,"data-minimap-lock":y?"on":"off","aria-pressed":y,title:c(y?"chatMinimap.unlockPreview":"chatMinimap.lockPreview"),"aria-label":c("chatMinimap.lockPreview"),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),Z()},children:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"4",y:"11",width:"16",height:"10",rx:"2"}),y?(0,r.jsx)("path",{d:"M8 11V7a4 4 0 0 1 8 0v4"}):(0,r.jsx)("path",{d:"M8 11V7a4 4 0 0 1 7.9-.9"})]})}),v&&p.length>0&&(0,r.jsxs)("div",{ref:I,className:iY().preview,"data-minimap-preview-box":"",onMouseEnter:V,onMouseDown:e=>e.stopPropagation(),onMouseMove:e=>e.stopPropagation(),children:[l>0&&(0,r.jsx)("button",{type:"button",className:iY().earlier,"data-minimap-preview-earlier":"",onClick:()=>s.current?.scrollTo({top:0,behavior:"smooth"}),children:c("chatMinimap.earlierTurns",{count:l})}),p.map(e=>{var t;let n=X===e.index;return(0,r.jsxs)("div",{ref:t=>{t?T.current.set(e.index,t):T.current.delete(e.index)},className:iY().turn,"data-minimap-preview-index":e.index,"data-located":n?"true":void 0,children:[(0,r.jsxs)("span",{className:iY().number,children:[(0,r.jsx)("span",{"aria-hidden":"true",children:String(l+e.index+1).padStart(2,"0")}),e.targetTurn.toolCount>0&&(0,r.jsx)("span",{className:iY().toolBadge,role:"img",title:c("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),"aria-label":c("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),children:e.targetTurn.toolCount>99?"99+":e.targetTurn.toolCount})]}),(0,r.jsxs)("div",{className:iY().content,children:[(0,r.jsx)("button",{type:"button",className:iY().user,"data-minimap-preview-user":e.index,onClick:()=>{H(e,"smooth")},children:(0,r.jsx)("span",{className:iY().userText,children:"string"==typeof(t=e.targetTurn.userMessage).content?t.content.trim():t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim()})}),e.targetTurn.assistantPreviews.map((t,n)=>(0,r.jsxs)("div",{className:iY().assistant,children:[(0,r.jsx)("button",{type:"button",className:iY().assistantJump,"data-minimap-preview-assistant":`${e.index}-${n}`,onClick:()=>U(e,n),"aria-label":c("chatMinimap.locateAssistant"),title:c("chatMinimap.locateAssistant"),children:"A"}),(0,r.jsx)(i2,{markdown:t.markdown,onAnswerClick:()=>U(e,n),onHeadingClick:t=>q(e,n,t)})]},n))]})]},e.index)})]})]})});var i8=n(52861);function i5(e){let{text:t}=e,n=(0,i.useMemo)(()=>new i8.v().ansi_to_html(t),[t]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:n}})}function i6(e){let t,n,s,{widgets:o,children:a}=e,{t:l}=(0,eO.s)(),c=(0,i.useId)(),d=(0,i.useRef)(null),u=(0,i.useRef)(new Map),[p,h]=(0,i.useState)(()=>o.find(e=>{let t=e.lines.length;return t>1&&t<=3})?.key??null),[f,m]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{var e;let t=new Map(o.map(e=>[e.key,[...e.lines]])),n=(e=d.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(d.current=t,u.current))t.has(e)||(clearTimeout(n),u.current.delete(e));for(let e of(m(e=>{let r=new Set(Array.from(e).filter(e=>t.has(e)));for(let e of n)r.add(e);return r.size===e.size&&Array.from(r).every(t=>e.has(t))?e:r}),n)){let t=u.current.get(e);t&&clearTimeout(t),u.current.set(e,setTimeout(()=>{u.current.delete(e),m(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},1100))}},[o]),(0,i.useEffect)(()=>()=>{for(let e of u.current.values())clearTimeout(e);u.current.clear()},[]),0===o.length)return null;let g=o.find(e=>e.key===p&&e.lines.length>0);return(0,r.jsxs)(r.Fragment,{children:[g&&(0,r.jsx)("div",{className:"extension-widget-panels",children:(t=o.indexOf(g),n=`${c}-trigger-${t}`,s=`${c}-panel-${t}`,(0,r.jsxs)("section",{id:s,className:"extension-widget-panel","aria-labelledby":n,children:[(0,r.jsx)("div",{className:"extension-widget-panel-heading",children:g.key}),(0,r.jsx)("pre",{className:"extension-widget-content",children:(0,r.jsx)(i5,{text:g.lines.join("\n")})})]},g.key))}),(0,r.jsxs)("div",{className:"extension-status-row",children:[(0,r.jsx)("div",{className:"extension-widget-triggers","aria-label":l("chat.extensionWidgets"),children:o.map((e,t)=>{let n=e.lines.length>0,i=n&&e.key===g?.key,s=f.has(e.key),o=l(1===e.lines.length?"chat.extensionWidgetLine":"chat.extensionWidgetLines",{count:e.lines.length}),a=l("belowEditor"===e.placement?"chat.extensionWidgetBelow":"chat.extensionWidgetAbove"),d=`${c}-trigger-${t}`,u=`${c}-panel-${t}`,p=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"extension-widget-update-pulse","aria-hidden":"true"}),(0,r.jsx)("span",{className:"extension-widget-placement","aria-hidden":"true",children:(0,r.jsx)("svg",{className:"extension-widget-placement-icon",viewBox:"0 0 8 6",width:"8",height:"6","data-direction":"belowEditor"===e.placement?"down":"up",focusable:"false",children:(0,r.jsx)("path",{d:"belowEditor"===e.placement?"M0 0h8L4 6z":"M4 0l4 6H0z"})})}),(0,r.jsx)("span",{className:"extension-widget-key",children:e.key})]});return n?(0,r.jsx)("button",{id:d,type:"button",className:`extension-widget-trigger${i?" is-expanded":""}${s?" is-updating":""}`,"aria-controls":u,"aria-expanded":i,"aria-label":`${a}: ${e.key}, ${o}`,title:`${e.key} - ${a} - ${i?l("i18n.collapse"):l("i18n.expand")}`,onClick:()=>{h(t=>{var n;return t===(n=e.key)?null:n})},children:p},e.key):(0,r.jsx)("div",{className:`extension-widget-trigger${s?" is-updating":""}`,"aria-label":`${a}: ${e.key}, ${o}`,title:`${e.key} - ${a}`,children:p},e.key)})}),a]})]})}let i3="command:";function i9(e){let{statuses:t,widgets:n=[],onCommand:i,commandsDisabled:s=!1}=e,o=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(i3))return null;let t=e.slice(i3.length).trim();return t.length>1&&t.startsWith("/")?t:null}(n.key);if(r){let n=nG(e).replace(/\s+/g," ").trim();t.push({kind:"command",command:r,label:n||r})}else nG(e).trim()&&t.push({kind:"text",text:e})}return t}(t);if(0===o.length&&0===n.length)return null;let a=o.some(e=>"command"===e.kind),l=o.map(e=>"text"===e.kind?nG(e.text):e.label).join(" "),c=o.length>0?(0,r.jsx)("div",{role:"status",className:"extension-status-line","aria-label":l,title:l,children:(0,r.jsx)("span",{className:"extension-status-text",children:o.map((e,t)=>"text"===e.kind?(0,r.jsx)("span",{className:"extension-status-item",children:(0,r.jsx)(i5,{text:e.text})},t):(0,r.jsx)("button",{type:"button",className:"extension-status-item extension-status-command",disabled:!i||s,title:`${e.label} \xb7 ${e.command}`,"aria-label":`${e.label} (${e.command})`,onClick:()=>i?.(e.command),children:e.label},t))})}):null;return(0,r.jsx)("div",{className:`extension-status-shelf${n.length>0?" has-widgets":""}${o.length>0?" has-status":""}${a?" has-commands":""}`,children:n.length>0?(0,r.jsx)(i6,{widgets:n,children:c}):c})}function i7(e){switch(e.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==e.closed;default:return!1}}function se(e,t){return e.every(e=>t.has(e.id))?e:e.filter(e=>t.has(e.id))}function st(e,t){return e.some(e=>e.id===t)?e.filter(e=>e.id!==t):e}function sn(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sr(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(!sn(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=sn(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=sn(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}}class si extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}function ss(e){return e instanceof si&&"prompt_rejected"===e.code&&!1===e.accepted}function so(e){return`/api/agent/${encodeURIComponent(e)}?systemPrompt=0`}async function sa(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 si(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}function sl(){return globalThis.__piSessionViewCache||(globalThis.__piSessionViewCache=new Map),globalThis.__piSessionViewCache}let sc=new WeakMap;function sd(e){let t,n=sc.get(e);if(void 0!==n)return n;try{t=JSON.stringify(e).length}catch{t=Number.MAX_SAFE_INTEGER}return sc.set(e,t),t}function su(e){let t=sl().get(e);return t?Date.now()-t.savedAt>6e5?(sl().delete(e),null):(sl().delete(e),sl().set(e,t),t):null}function sp(e){if(!e.sessionId||!e.revision)return!1;let t=sl();t.delete(e.sessionId);let n={...e,savedAt:Date.now()};return!(sd(n)>0x2000000)&&(t.set(n.sessionId,n),!function(){let e=sl();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+=sd(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-=sd(r))}}(),sl().has(n.sessionId))}function sh(e){sl().delete(e)}var sf=n(82725);let sm="pi-tool-preset";function sg(){try{return window.localStorage}catch{return null}}function sx(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 sv(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,sx(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),sx(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function sb(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 sy(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(sb).filter(Boolean)}):JSON.stringify({text:"",images:[]})}let sj=(e,t)=>`live:${e??""}:${t}`;class sk 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 sw{constructor(e){this.options=e,this.current=null,this.retry=null,this.retryGeneration=0}close(){this.stopRetrying(),this.current&&this.discard(this.current,new sk("closed"))}maintain(e){if(!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof sk?"startup_error"===n.status?this.stopRetrying():this.scheduleRetry(e):this.options.onUnexpectedError?.(n))})}async ensureConnected(e){for(;;){let t=this.current;if(t&&t.sessionId===e){if(t.attempt.ready&&1===t.source.readyState)return}else t=this.open(e);if(await t.attempt.promise,this.current!==t){if(this.current?.sessionId===e)continue;throw new sk("closed")}if(1===t.source.readyState)return;this.discard(t,new sk("closed"))}}open(e){let t,n,r;this.current&&this.discard(this.current,new sk("closed"));try{t=this.options.createSource(e)}catch(e){throw new sk("closed",e instanceof Error?e.message:String(e))}let i=!1,s=new Promise((e,t)=>{n=e,r=t}),o=setTimeout(()=>{this.fail(l,new sk("ready_timeout"))},this.options.readinessTimeoutMs),a={promise:s,ready:!1,succeed(){i||(i=!0,clearTimeout(o),n())},fail(e){i||(i=!0,clearTimeout(o),r(e))}},l={sessionId:e,source:t,attempt:a,watchdog:null};this.current=l;let c=Date.now();return t.onmessage=e=>{let t;if(this.current===l){c=Date.now();try{t=JSON.parse(e.data)}catch{return}if("heartbeat"!==t.type){if("connected"===t.type){a.ready=!0,a.succeed(),this.stopRetrying();let e=this.options.staleAfterMs;e&&null===l.watchdog&&(l.watchdog=setInterval(()=>{Date.now()-c>e&&this.fail(l,new sk("closed"))},Math.max(1e3,Math.floor(e/3))))}else if("startup_error"===t.type){let e="string"==typeof t.errorMessage?t.errorMessage:void 0;this.fail(l,new sk("startup_error",e));return}this.options.onEvent(t)}}},t.onerror=()=>{this.fail(l,new sk("closed"))},l}fail(e,t){this.current===e&&(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.maintain(e))},this.options.reconnectDelayMs);this.retry={sessionId:e,timer:t}}stopRetrying(){this.retryGeneration+=1,this.clearRetry()}clearRetry(){this.retry&&clearTimeout(this.retry.timer),this.retry=null}}function sS(e){return!!e&&"unanswered"!==e&&!!(e.running||e.awaitingInput||e.subagentsActive)}function sC(e){return"u"<typeof document?()=>{}:(document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e))}let sN=()=>"hidden"===document.visibilityState,sE=()=>!1;function sI(e){return("tool_execution_start"===e.type||"tool_execution_update"===e.type||"tool_execution_end"===e.type)&&"string"==typeof e.parentToolCallId&&""!==e.parentToolCallId}function sT(e){var t;return("message_start"===e.type||"message_end"===e.type)&&"object"==typeof(t=e.message)&&null!==t&&!Array.isArray(t)&&"system"===e.message.role}function s$(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var sM=n(15452);function sR(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return e+t>=n-r}let sL={isStreaming:!1,streamingMessage:null};function sA(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 sP(){let e=sL,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=sr(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 sA(e,n.contentIndex,()=>({type:"text",text:""}));case"text_delta":return sA(e,n.contentIndex,e=>e?.type==="text"?{...e,text:e.text+n.delta}:null);case"text_end":return sA(e,n.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:n.content}));case"thinking_start":return sA(e,n.contentIndex,()=>({type:"thinking",thinking:""}));case"thinking_delta":return sA(e,n.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+n.delta}:null);case"thinking_end":return sA(e,n.contentIndex,e=>({...e?.type==="thinking"?e:{},type:"thinking",thinking:n.content}));case"toolcall_start":return sA(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 sA(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 sA(e,n.contentIndex,()=>({type:"toolCall",toolCallId:n.toolCall.id,toolName:n.toolCall.name,input:n.toolCall.arguments}));default:return e}case"end":return sL;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 sz(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function sW(e){return e&&"auto"!==e?e:null}let sO=new Map,sD=null,sF=[2e3,5e3,1e4];function sB(e){return new Promise(t=>setTimeout(t,e))}function sH(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function sU(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:sH(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:sH(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=sH(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function s_(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 sq(e,t){let[n,r]=(0,i.useState)(()=>t(e.getState()));return(0,i.useLayoutEffect)(()=>{let n=()=>r(t(e.getState()));return n(),e.subscribe(n)},[e,t]),n}let sK=e=>e.isStreaming,sV=e=>!!e.streamingMessage?.content.length,sZ=e=>e.streamingMessage;var sJ=n(13916);let sG=null,sY=null;function sX(e){let{label:t}=e,[n,s]=(0,i.useState)(()=>sY);if((0,i.useEffect)(()=>{if(sY)return;let e=!1;return(sG??=fetch("/api/app-update").then(async e=>{if(!e.ok)return null;let t=await e.json();return t.updateAvailable&&t.latestVersion&&t.releaseUrl?t:null}).then(e=>(sY=e,e)).catch(()=>(sG=null,null))).then(t=>{!e&&t&&s(t)}),()=>{e=!0}},[]),!n)return null;let o=t(n.latestVersion);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"new-session-meta-arrow","aria-hidden":"true",children:"→"}),(0,r.jsxs)("a",{className:"new-session-update",href:n.releaseUrl,target:"_blank",rel:"noopener noreferrer",title:o,"aria-label":o,children:["v",n.latestVersion,(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M7 17 17 7"}),(0,r.jsx)("path",{d:"M7 7h10v10"})]})]})]})}function sQ(e){let{messageCount:t,toolCallCount:n,durationMs:s,cacheMisses:o,defaultExpanded:a=!1,reveal:l=!1,children:c,t:d}=e,[u,p]=(0,i.useState)(a);(0,i.useLayoutEffect)(()=>{l&&p(!0)},[l]);let h=[`${t} ${d(1===t?"chat.message":"chat.messages")}`];n>0&&h.push(`${n} ${d(1===n?"chat.toolCall":"chat.toolCalls")}`),void 0!==s&&h.push(d("chat.turnDuration",{time:(0,rl.J)(s)}));let f=o&&!(u||l)?(0,sJ.YL)(d,o):void 0;return(0,r.jsxs)("div",{style:{marginBottom:14},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":u||l,"aria-label":[d("chat.processDetails"),...h,...f?[f]:[]].join(" \xb7 "),onClick:()=>p(e=>!e),style:{display:"flex",alignItems:"center",gap:8,width:"auto",maxWidth:"100%",minHeight:24,padding:"2px 0",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},title:d(u?"chat.collapseProcess":"chat.expandProcess"),children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:u?"rotate(90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"4 2.5 7.5 6 4 9.5"})}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[h.join(" \xb7 "),f&&(0,r.jsx)("span",{style:{color:sJ.lV},children:` \xb7 ${f}`})]})]}),(u||l)&&(0,r.jsx)("div",{style:{marginTop:8},children:c})]})}function s0(e){var t;let s,{session:a,searchTarget:l,onSearchTargetHandled:c,initialScrollPosition:d,onScrollPositionChange:u,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:f,newSessionContextBar:m,initialNewSessionChoices:g,onNewSessionChoicesChange:x,onAgentEnd:v,onToolEnd:b,onAttentionNeeded:y,onSessionCreated:j,onSessionForked:k,modelsRefreshKey:w,chatInputRef:S,onBranchDataChange:C,onSystemPromptChange:N,onSystemToolsChange:E,onSystemInfoLoaderChange:I,onSessionStatsChange:T,onSessionStatsPanelOpen:$,onOpenSettings:M,onContextUsageChange:R,onOpenFile:L,onFilesUploaded:A,onOpenSubagent:P,onEnterSubagent:z,onAskInNewChat:W,quoteSelectionEnabled:O=!1,initialPrompt:D,onInitialPromptConsumed:F,soundEnabled:B=!0,onSoundToggle:H,playDoneSound:U=()=>{},unlockAudio:_,holdAudio:q}=e,{t:K}=(0,eO.s)(),V=(0,eD.a)(),Z=a?.relation?.kind!=="subagent",J=(0,i.useRef)(U);J.current=U;let G=(0,i.useRef)(B);G.current=B;let Y=(0,i.useRef)(!1),X=(0,i.useCallback)(e=>{Z&&G.current&&!e.aborted&&J.current(),v?.(e)},[Z,v]),Q=(0,i.useRef)(l?null:d??null),[ee,et]=(0,i.useState)(()=>{let e=Q.current;return e&&!e.atBottom?e:null}),[en,er]=(0,i.useState)(!1),{loading:ei,error:es,messages:eo,activeToolResults:ea,entryIds:el,messageKeys:ec,historyCursor:ed,hasEarlierMessages:eu,earlierTurnCount:ep,streamingStore:eh,agentRunning:ef,bashRunning:em,pendingBash:eg,modelNames:ex,modelList:ev,modelError:eb,modelScopeWarnings:ey,modelThinkingLevels:ej,modelThinkingLevelMaps:ek,toolPreset:ew,thinkingLevel:eS,retryInfo:eC,contextUsage:eN,forkingEntryId:eE,isCompacting:eI,compactError:eT,compactResult:e$,displayModel:eM,modelSwitching:eR,sessionStats:eL,slashCommands:eA,slashCommandsLoading:eP,queuedMessages:ez,notices:eW,extensionDialog:eF,waitingExtensionDialogCount:eB,extensionCustomUi:eH,waitingExtensionCustomUiCount:e_,extensionStatuses:eq,extensionWidgets:eK,respondToExtensionUi:eV,sendExtensionCustomInput:eZ,setNoticePaused:eG,addNotice:eY,isAutoModelSelection:eX,isAutoThinkingSelection:eQ,defaultModel:e0,savedDefaultThinkingLevel:e1,agentPhase:e2,isNew:e4,editEntryId:e8,showScrollToBottom:e5,sessionIdRef:e6,scrollContainerRef:e3,lastUserMsgRef:e9,promptAnchorActive:e7,handleSend:te,handleAbort:tt,handleFork:to,handleEditContent:ta,cancelEdit:tl,handleModelChange:tc,handleCompact:td,handleSteer:tu,handleFollowUp:tp,handlePromptWithStreamingBehavior:th,handleAbortCompaction:tf,dismissCompactError:tm,handleRecallQueue:tg,handleBuiltinSlashCommand:tx,handleToolPresetChange:tv,handleThinkingLevelChange:tb,handleSetDefaultModel:ty,handleSetDefaultThinkingLevel:tj,loadSlashCommands:tk,scrollUserMsgToTop:tw,loadContext:tS,activeLeafId:tC,scrollToBottom:tN,scrollToMessage:tE}=function(e){let{session:t,newSessionCwd:r,newSessionDraftKey:s,onAgentEnd:o,onToolEnd:a,onAttentionNeeded:l,onSessionCreated:c,onSessionForked:d,modelsRefreshKey:u,onBranchDataChange:p,onSystemPromptChange:h,onSystemToolsChange:f,onSystemInfoLoaderChange:m,onSessionStatsPanelOpen:g,onOpenSettings:x}=e,v=null===t&&null!==r,b=v?e.initialNewSessionChoices??null:null,[y,j]=(0,i.useState)(null),[k,w]=(0,i.useState)(!v),[S,C]=(0,i.useState)(null),[N,E]=(0,i.useState)(null),[I,T]=(0,i.useState)([]),[$,M]=(0,i.useState)(new Map),[R,L]=(0,i.useState)([]),[A,P]=(0,i.useState)(()=>new Map),[z,W]=(0,i.useState)(null),[O,D]=(0,i.useState)(!1),[F,B]=(0,i.useState)(0),[H]=(0,i.useState)(sP),U=H.dispatch,[_,q]=(0,i.useState)(!1),[K,V]=(0,i.useState)(!1),[Z,J]=(0,i.useState)(null),[G,Y]=(0,i.useState)({}),[X,Q]=(0,i.useState)([]),[ee,et]=(0,i.useState)(null),[en,er]=(0,i.useState)([]),[ei,es]=(0,i.useState)({}),[eo,ea]=(0,i.useState)({}),[el,ec]=(0,i.useState)(()=>b?.model??null),[ed,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(sf.Q8),[ef,em]=(0,i.useState)(()=>b?.thinkingLevel??null),[eg,ex]=(0,i.useState)(null),[ev,eb]=(0,i.useState)(null),[ey,ej]=(0,i.useState)(null),[ek,ew]=(0,i.useState)(null),[eS,eC]=(0,i.useState)(null),[eN,eE]=(0,i.useState)(null),[eI,eT]=(0,i.useState)(null),e$=(0,i.useRef)(0),eM=(0,i.useRef)(0),[eR,eL]=(0,i.useState)(null),[eA,eP]=(0,i.useState)(null),[ez,eW]=(0,i.useState)(null),[eO,eD]=(0,i.useState)(null),[eF,eB]=(0,i.useState)(null),[eH,eU]=(0,i.useState)(!1),[e_,eq]=(0,i.useState)(!1),[eK,eV]=(0,i.useState)(!0),[eZ,eJ]=(0,i.useState)(null),[eG,eY]=(0,i.useState)(null),[eX,eQ]=(0,i.useState)(null),[e0,e1]=(0,i.useState)(!1),[e2,e4]=(0,i.useState)(!1),[e8,e5]=(0,i.useState)([]),[e6,e3]=(0,i.useState)(!1),[e9,e7]=(0,i.useReducer)(sU,{visible:[],pending:[]}),[te,tt]=(0,i.useState)(null),[tn,tr]=(0,i.useState)([]),[ti,ts]=(0,i.useState)([]),[to,ta]=(0,i.useState)([]),[tl,tc]=(0,i.useState)([]),[td,tu]=(0,i.useState)({steering:[],followUp:[]}),tp=(0,i.useRef)(null),th=(0,i.useRef)(null),tf=(0,i.useRef)(0),tm=(0,i.useRef)(!1),tg=(0,i.useRef)(!1),[tx,tv]=(0,i.useState)(0),tb=(0,i.useRef)(null),ty=(0,i.useRef)(()=>{}),tj=(0,i.useRef)(t?.id??null),tk=(0,i.useRef)(t?.id??null),tw=(0,i.useRef)(!1),tS=(0,i.useRef)(!1),tC=(0,i.useRef)(!1),tN=(0,i.useRef)(!1),tE=(0,i.useRef)(-1),tI=(0,i.useRef)(!1),tT=(0,i.useRef)(0),t$=(0,i.useRef)(null),tM=(0,i.useRef)(!!e.deferInitialScroll),tR=(0,i.useRef)(null),tL=(0,i.useRef)(!1),tA=(0,i.useRef)(!0),tP=(0,i.useRef)(0),tz=(0,i.useRef)(null),tW=(0,i.useRef)(void 0),tO=(0,i.useRef)(void 0),tD=(0,i.useRef)(null),tF=(0,i.useRef)(null),tB=(0,i.useRef)([]),tH=(0,i.useRef)(null),tU=(0,i.useRef)(0),t_=(0,i.useRef)(!1),tq=(0,i.useRef)(b?.model??null),tK=(0,i.useRef)(b?.thinkingLevel??null),tV=(0,i.useRef)({}),tZ=(0,i.useRef)(null),tJ=(0,i.useRef)(0),tG=(0,i.useRef)(null),tY=(0,i.useRef)(!1),tX=(0,i.useRef)(new Map),tQ=(0,i.useRef)(!0),t0=(0,i.useRef)(new Map),t1=(0,i.useRef)(null),t2=(0,i.useRef)([]),t4=(0,i.useRef)([]),t8=(0,i.useRef)(null),t5=(0,i.useRef)(null),t6=(0,i.useRef)(!1),t3=(0,i.useRef)(0);tk.current=t?.id??null,t1.current=y,t2.current=I,t4.current=R,t8.current=N,t5.current=z,t6.current=O,t3.current=F,tp.current||(tp.current=new sw({createSource:e=>new EventSource(`/api/agent/${encodeURIComponent(e)}/events`),onEvent:e=>t$.current?.(e),shouldMaintain:e=>tQ.current&&tj.current===e&&(tS.current||tm.current||tk.current===e&&!tg.current),readinessTimeoutMs:6e4,reconnectDelayMs:1e3,staleAfterMs:75e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let t9=e.setToolPreset??eh,t7=t?.id;(0,i.useLayoutEffect)(()=>{(t7||v&&!tj.current)&&t9(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:sg();if(!e)return sf.Q8;try{let t=e.getItem(sm);return(0,sf.sn)(t)?t:sf.Q8}catch{return sf.Q8}}())},[t7,v,t9]);let ne=e.onNewSessionChoicesChange;(0,i.useEffect)(()=>{v&&ne?.({model:el,thinkingLevel:ef})},[v,el,ef,ne]);let nt=(0,i.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"smooth",t=tD.current;t&&(t.scrollTo({top:t.scrollHeight,behavior:e}),tP.current=t.scrollTop)},[]),nn=ez??eO??y?.context.model??eF??null,nr=v?el??ed:nn??(y?.context.messages.length===0?ed:null),ni=sW(y?.context.thinkingLevel&&"off"!==y.context.thinkingLevel?y.context.thinkingLevel:null),ns=v?ef??eg:ey??ek??ni??(y?.context.messages.length===0?eg:null),no=t?.id??s??void 0,na=(0,i.useCallback)(e=>{eD(e?.model?{provider:e.model.provider,modelId:e.model.id}:null),e?.thinkingLevel!==void 0&&ew(sW(e.thinkingLevel))},[]),nl=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=tX.current.get(t);if(!e)break;t=e}return t},[]),nc=(0,i.useCallback)((t,n,r)=>{let i=n?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}}),o=nl(r);if(!tQ.current&&!t_.current&&r===s)return;let a=e.chatInputRef?.current;if(a)a.restoreSubmission(t,i,o);else{let e,n;o&&(n=ry(t,i,(e=rg(o)??{value:"",images:[]}).value,e.images),rx(o,n))}},[s,e.chatInputRef,nl]),[nd,nu]=(0,i.useState)(()=>{let e=t?.id;return e&&!rg(e)&&sO.delete(e),e&&sO.get(e)||null}),np=(0,i.useCallback)(e=>{t?.id&&(e?sO.set(t.id,e):sO.delete(t.id),nu(e))},[t?.id]),nh=(0,i.useCallback)((n,r)=>{t?.id&&(e.chatInputRef?.current?.replaceMessage(n),np(r))},[e.chatInputRef,t?.id,np]),nf=(0,i.useCallback)(()=>np(null),[np]),nm=(0,i.useMemo)(()=>{let e=y?.totalActiveMs,n=eI&&eI.sessionId===y?.sessionId?eI.value:void 0,r=void 0===e&&void 0===n?void 0:Math.max(e??0,n??0);if(te)return{...te,totalActiveMs:r,...eN?{contextUsage:eN}:{}};let i=y?.stats,s=function(e,t,n){let r=sv(n);if(!e)return r;let i=sv(t),s=(e,t)=>Math.max(0,e-t),o={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 o.total=o.input+o.output+o.cacheRead+o.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:o,cost:e.cost+s(r.cost,i.cost)}}(i,y?.context.messages??[],I);return 0!==s.tokens.total||0!==I.length||i?{sessionFile:y?.filePath||void 0,sessionId:tj.current??t?.id??"",sessionName:t?.name,...s,totalActiveMs:r,...eN?{contextUsage:eN}:{}}:null},[I,te,eN,eI,y?.sessionId,y?.context.messages,y?.filePath,y?.totalActiveMs,y?.stats,t?.id,t?.name]),ng=(0,i.useCallback)((e,t,n,r)=>{tQ.current&&tj.current===t&&tJ.current===n&&!(r<=eM.current)&&(eM.current=r,e?.contextUsage!==void 0&&eE(e.contextUsage??null),"number"==typeof e?.totalActiveMs&&eT({sessionId:t,value:e.totalActiveMs}))},[]),nx=(0,i.useCallback)(async e=>{let t=tJ.current,n=++e$.current;try{let r=await fetch(so(e));if(!r.ok)return;let i=await r.json();ng(i.state,e,t,n)}catch{}},[ng]),nv=(0,i.useCallback)(async function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3?arguments[3]:void 0,i=r?.force?`force:${e}`:e,s=r?.force?void 0:t0.current.get(i);if(s)return await s;let o=(async()=>{let i=!1;try{t&&w(!0);let s=new URLSearchParams({deferThinking:"1",deferMedia:"1",tree:"summary"});r?.force&&s.set("force","1");let o=await fetch(`/api/sessions/${encodeURIComponent(e)}?${s}`);if(404===o.status)return t&&(j(null),E(null),T([]),L([]),W(null),D(!1),B(0),C(null)),sh(e),null;if(!o.ok)throw Error(`HTTP ${o.status}`);let a=await o.json();if(tj.current!==e)return null;let l=su(e),c=!!(a.snapshotRevision&&l?.revision===a.snapshotRevision&&l.entryIds.length>=(a.context.entryIds??[]).length),d=c?t2.current:a.context.messages;if(j(c?{...a,context:{...a.context,messages:t2.current,entryIds:t4.current,oldestEntryId:t5.current,hasMore:t6.current,turnsBefore:t3.current}}:a),E(a.leafId),c)sp({sessionId:e,revision:a.snapshotRevision,messages:t2.current,entryIds:t4.current,leafId:a.leafId,oldestEntryId:t5.current,hasMore:t6.current,turnsBefore:t3.current,summaryTree:a.tree,thinkingLevel:a.context.thinkingLevel,model:a.context.model,stats:a.stats,totalActiveMs:a.totalActiveMs,loadedEntryIds:t4.current});else{let e={messages:t2.current,entryIds:t4.current},t={messages:d,entryIds:a.context.entryIds??[]};P(n=>(function(e,t){let n=new Set(t.entryIds),r=new Map([...e.aliases].filter(e=>{let[t]=e;return n.has(t)})),i=e.entryIds.length,s=e.entryIds[i-1],o=void 0===s?0:t.entryIds.indexOf(s)+1;if(0===o&&void 0!==s)return r;for(let n=0;i+n<e.messages.length;n++){var a,l;let c=t.entryIds[o+n];if(void 0===c||(a=e.messages[i+n],l=t.messages[o+n],a.role!==l.role||("user"===a.role?sy(a)!==sy(l):"custom"===a.role?a.customType!==l.customType:a.timestamp!==l.timestamp)))break;r.set(c,sj(s,n))}return r})({...e,aliases:n},t)),T(t.messages),L(t.entryIds),W(a.context.oldestEntryId),D(a.context.hasMore),B(a.context.turnsBefore??0)}if(tw.current=void 0!==a.toolNames,t9(void 0!==a.toolNames?(0,sf.YO)(a.toolNames):sf.Q8),eW(e=>tY.current?e:null),ej(null),C(null),"summary"===a.treeFormat&&a.snapshotRevision&&sp({sessionId:e,revision:a.snapshotRevision,messages:d,entryIds:a.context.entryIds??[],leafId:a.leafId,oldestEntryId:a.context.oldestEntryId,hasMore:a.context.hasMore,turnsBefore:a.context.turnsBefore??0,summaryTree:a.tree,thinkingLevel:a.context.thinkingLevel,model:a.context.model,stats:a.stats,totalActiveMs:a.totalActiveMs,loadedEntryIds:a.context.entryIds??[]}),a.wrapperRebuilt&&(tp.current?.close(),tp.current?.maintain(e)),!n&&a.context.thinkingLevel&&"off"!==a.context.thinkingLevel&&ew(sW(a.context.thinkingLevel)),i=!0,t&&w(!1),!n)return null;try{let t=tJ.current,n=++e$.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(tj.current!==e)return null;let s=i.state;return na(s),s?(ng(s,e,t,n),void 0!==s.systemPrompt&&eL(s.systemPrompt??null),void 0!==s.extensionStatuses&&ta(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tc(s.extensionWidgets??[]),void 0!==s.queuedMessages&&tu(sz(s.queuedMessages)),void 0!==s.autoCompactionEnabled&&eV(s.autoCompactionEnabled??!0)):i.running||tu({steering:[],followUp:[]}),i}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return C(String(e)),"error"}finally{t&&!i&&w(!1)}})();return r?.force||t0.current.set(i,o),o.finally(()=>{t0.current.get(i)===o&&t0.current.delete(i)}),await o},[ng,t9,na]),nb=(0,i.useCallback)(async(e,t,n,r)=>{try{let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&i.set("leafId",t),n&&i.set("before",n),r?.tail&&i.set("tail",String(r.tail));let s=`/api/sessions/${encodeURIComponent(e)}/context?${i}`,o=await fetch(s,{signal:r?.signal});if(!o.ok)throw Error(`HTTP ${o.status}`);let a=await o.json();if(tj.current!==e||r?.signal?.aborted||!tQ.current)return;return W(a.context.oldestEntryId),D(a.context.hasMore),B(a.context.turnsBefore??0),j(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?(T(e=>[...a.context.messages,...e]),L(e=>[...a.context.entryIds,...e])):(T(a.context.messages),L(a.context.entryIds??[])),a.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),ny=(0,i.useCallback)(async e=>{try{let t=await sa(e,{type:"get_tools"});if(!t||!tQ.current||tj.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,82725));return t9(tw.current?r(t):sf.Q8),f?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[f,t9]),nj=(0,i.useCallback)(function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"(no messages)",i=tj.current;if(v&&r&&i&&!t_.current&&(t_.current=!0,s)){if(s!==i){tX.current.set(s,i);let t=e.chatInputRef?.current;t?t.rekeyDraft(s,i):rj(s,i)}c?.({id:i,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0},s)}},[v,r,s,c,e.chatInputRef]),nk=(0,i.useCallback)(async()=>{if(tj.current||!v||!r)return tj.current;if(tF.current)return tF.current;let e=(async()=>{let e=tq.current,t=tK.current;e&&eB(e);let n=(0,sf.xG)(ep);tw.current=void 0!==n;let i=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r,type:"ensure_session",...void 0!==n?{toolNames:n}:{},...e?{provider:e.provider,modelId:e.modelId}:{},...t?{thinkingLevel:t}:{}})});if(!i.ok){let e=await i.json().catch(()=>null);throw Error("string"==typeof e?.error?e.error:`HTTP ${i.status}`)}let s=await i.json(),o=s.sessionId;return tj.current=o,s.model&&tq.current===e&&(eB(s.model),e||eu(s.model)),s.thinkingLevel&&tK.current===t&&(ew(sW(s.thinkingLevel)),t||ex(sW(s.thinkingLevel))),o})();tF.current=e;try{return await e}finally{tF.current=null}},[v,r,ep]),nw=(0,i.useCallback)(async()=>{let e=tj.current??await nk();if(!e)return;let[t]=await Promise.all([sa(e,{type:"get_state"}),ny(e)]);tQ.current&&tj.current===e&&(na(t),eL(t.systemPrompt??""))},[nk,ny,na]),nS=(0,i.useCallback)(e=>{tB.current=e,e5(e)},[]),nC=(0,i.useCallback)(()=>{tU.current+=1,tH.current=null,nS([])},[nS]),nN=(0,i.useCallback)(()=>{let e=++tU.current,t=(async()=>{let t=tj.current??await nk();if(!t)return tU.current===e&&nS([]),[];e3(!0);try{let n=await sa(t,{type:"get_commands"}),r=n?.commands??[];return tU.current===e&&nS(r),r}catch(t){return console.error("Failed to load slash commands:",t),tU.current===e&&nS([]),null}finally{tU.current!==e&&tH.current||e3(!1)}})();tH.current=t;let n=()=>{tH.current===t&&(tH.current=null)};return t.then(n,n),t},[nk,nS]),nE=(0,i.useCallback)(async()=>await nN()??[],[nN]),nI=(0,i.useCallback)(async()=>{let e=tH.current,t=tB.current;return!e&&t.length>0?t:await (e??nN()).catch(()=>null)??(t.length>0?t:null)},[nN]),nT=(0,i.useCallback)(()=>{tf.current+=1,tm.current=!1,th.current&&(clearTimeout(th.current),th.current=null)},[]),n$=(0,i.useCallback)(()=>{tp.current?.close()},[]),nM=(0,i.useCallback)(e=>tp.current.ensureConnected(e),[]),nR=(0,i.useCallback)(e=>{tp.current.maintain(e)},[]);(0,i.useEffect)(()=>{let e=t?.id;if(e)return tQ.current=!0,tg.current=!1,nR(e),()=>{tj.current===e&&tp.current?.close()}},[nR,t?.id]);let nL=(0,i.useCallback)(e=>{let t=tb.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()=>{try{let t=await fetch((sD??=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,`/api/agent/${encodeURIComponent(e)}/lease?holder=${sD}`),{method:"POST",cache:"no-store",signal:n.signal});return t.ok?await t.json():null}catch(e){return n.signal.aborted||e instanceof TypeError?"unanswered":null}finally{clearTimeout(r),tb.current===i&&(tb.current=null)}})(),tb.current=i,i.promise},[]),nA=!_&&!K&&!e_&&0===tn.length&&0===ti.length;(0,i.useEffect)(()=>{let e=t?.id;if(!e||!nA)return;let n=!1,r=null,i=()=>!n&&"hidden"===document.visibilityState&&!tg.current&&tj.current===e&&tk.current===e&&!tS.current&&!tI.current,s=async()=>{if(r=null,!i())return;let t=await nL(e);if(i()){if(!("unanswered"===t||t&&!sS(t)))return void o();tg.current=!0,n$()}},o=()=>{r??=setTimeout(()=>void s(),3e4)},a=()=>{"hidden"===document.visibilityState?o():r&&(clearTimeout(r),r=null)};return"hidden"===document.visibilityState&&o(),document.addEventListener("visibilitychange",a),()=>{n=!0,r&&clearTimeout(r),document.removeEventListener("visibilitychange",a)}},[n$,nA,tx,nL,t?.id]);let nP=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(tr(t=>st(t,e.id)),n)try{await sa(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e)}},[]),nz=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{await sa(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),nW=(0,i.useCallback)(e=>{let t=e.message.trim();t&&e7({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"}})},[]),nO=(0,i.useCallback)(t=>{switch(i7(t)&&l?.(t),t.method){case"select":case"confirm":case"input":case"editor":tr(e=>e.some(e=>e.id===t.id)?e:[...e,t]);break;case"notify":nW({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":ta(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":tc(e=>(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"aboveEditor";if(void 0===n)return e.filter(e=>e.key!==t);let i={key:t,lines:n,placement:r},s=e.findIndex(e=>e.key===t);return -1===s?[...e,i]:e.map((e,t)=>t===s?i:e)})(e,t.widgetKey,t.widgetLines,t.widgetPlacement));break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":ts(e=>{let n;return t.closed?st(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)})}},[nW,l,e.chatInputRef]),nD=(0,i.useCallback)(()=>{let e=tS.current;return tS.current=!1,q(!1),eQ(null),eC(null),M(new Map),U({type:"end"}),e},[U]),nF=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return tE.current!==e&&(tE.current=e,o?.({aborted:t}),!0)},[o]),nB=(0,i.useCallback)(e=>{if(tk.current===e)return void nT();nT(),tm.current=!0;let t=tf.current,n=async()=>{if(t===tf.current&&tj.current===e&&tm.current)try{let r=await fetch(so(e));if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(t!==tf.current||tj.current!==e||!tm.current)return;let s=i.state;if(na(s),i.running&&s&&(s.isStreaming||s.isPromptRunning)){tm.current=!1,th.current=null,tC.current=!!s?.isStreaming,tN.current=!!s?.isPromptRunning,tS.current=!0,q(!0),eQ(s?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(i.running&&s?.isCompacting){eq(!0),th.current=setTimeout(()=>void n(),600);return}tm.current=!1,th.current=null,n$()}catch{if(t!==tf.current||tj.current!==e||!tm.current)return;th.current=setTimeout(()=>void n(),600)}};th.current=setTimeout(()=>void n(),3e4)},[nT,n$,na]),nH=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tj.current,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tJ.current;if(tJ.current===t)try{e&&await nv(e)}finally{if(tJ.current!==t)return;let n=tN.current,r=tC.current;tN.current=!1,tC.current=!1,tG.current=null;let i=nD();n?nF(t):r&&i&&o?.({aborted:!1}),e&&nB(e)}},[nv,nF,o,nB,nD]),nU=(0,i.useCallback)(async(e,t)=>{await sB(800);let n=Date.now();for(;tS.current&&Date.now()-n<2e4;){if(void 0!==t&&tJ.current!==t)return;try{let n=await fetch(so(e));if(n.ok){let r=await n.json(),i=r.state;if(na(i),!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await nH(e,t)}}catch{}await sB(600)}},[nH,na]),n_=(0,i.useCallback)(async e=>{let t=tT.current+1;for(tT.current=t;tI.current&&tT.current===t&&tj.current===e;){await sB(1e3);try{let n=await fetch(so(e));if(!n.ok)continue;let r=await n.json();if(na(r.state),r.state?.isBashRunning)continue;if(await nv(e),tT.current!==t||tj.current!==e)return;tI.current=!1,V(!1),J(null);return}catch{}}},[nv,na]),nq=(0,i.useCallback)(async e=>{if(!tS.current||tj.current!==e)return;let t=tJ.current,n=++e$.current;try{let r=await fetch(so(e));if(!r.ok)return;let i=await r.json();if(tj.current!==e||tJ.current!==t)return;let s=i.state;if(ng(s,e,t,n),na(s),eq(s?.isCompacting??!1),eV(s?.autoCompactionEnabled??!0),tu(sz(s?.queuedMessages)),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isCompacting)){tC.current=!!s.isStreaming,tN.current=!!s.isPromptRunning;return}if(!tS.current)return;s&&(void 0!==s.extensionStatuses&&ta(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tc(s.extensionWidgets??[]),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(t=>{t&&tQ.current&&tj.current===e&&t.state?.systemPrompt!==void 0&&eL(t.state.systemPrompt??null)}).catch(()=>{})),await nH(e,t)}catch{}},[ng,nH,na]);(0,i.useEffect)(()=>{if(!_)return;let e=()=>{let e=tj.current;e&&nq(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)}},[_,nq]),(0,i.useEffect)(()=>{tS.current=_},[_]),t$.current=(0,i.useCallback)(e=>{switch(e.type){case"connected":if(U({type:"end"}),Array.isArray(e.pendingExtensionUiIds)){let t=new Set(e.pendingExtensionUiIds);tr(e=>se(e,t)),ts(e=>se(e,t))}!0===e.isStreaming&&(nT(),tC.current=!0,tS.current=!0,q(!0),eQ({kind:"waiting_model"})),tj.current&&nx(tj.current);break;case"agent_start":nT(),tC.current=!0,tS.current=!0,q(!0),eQ({kind:"waiting_model"}),eC(null),U({type:"start"});break;case"agent_end":if(!tS.current)break;if(eQ(null),eC(null),U({type:"end"}),tj.current){let e=tj.current,t=tJ.current,n=++e$.current;nv(e),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(r=>{r&&tQ.current&&tj.current===e&&tJ.current===t&&(na(r.state),ng(r.state,e,t,n),r.state?.systemPrompt!==void 0&&eL(r.state.systemPrompt??null),r.state?.extensionStatuses!==void 0&&ta(r.state.extensionStatuses??[]),r.state?.extensionWidgets!==void 0&&tc(r.state.extensionWidgets??[]),tu(sz(r.state?.queuedMessages)))}).catch(()=>{})}break;case"agent_settled":{let t=tC.current;if(tC.current=!1,!t||tN.current)break;let n=tj.current,r=nD();eq(!1),n&&(nv(n),nB(n)),r&&o?.({aborted:!0===e.aborted});break}case"prompt_done":{let t=tJ.current,n=tN.current;tN.current=!1,tG.current=null;let r=nF(t,!0===e.aborted);if(!n&&!r)break;let i=tj.current;i&&nv(i),!tC.current&&(nD(),i&&nB(i))}break;case"prompt_error":nW({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":nW({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":if(!tS.current||sT(e))break;if("message_start"===e.type){let t=e.message;if(t?.role==="user")break;t?.role==="assistant"?(U({type:"snapshot",message:t}),t.content.length>0&&eQ(null)):t&&eQ(null)}else{let t=e.assistantMessageEvent;t&&(U({type:"delta",event:t}),"toolcall_start"!==t.type&&"toolcall_delta"!==t.type&&eQ(null))}!tL.current&&tA.current&&null===tz.current&&(tz.current=requestAnimationFrame(()=>{tz.current=null,tA.current&&nt("auto")}));break;case"message_end":{if(!tS.current||sT(e))break;let t=e.message;if(t&&"user"===t.role){let e=sr(t),n=sy(e),r=tG.current;tG.current=null,T(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&sy(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]})}else if(t){let n=Array.isArray(e.transcriptNotices)?e.transcriptNotices:void 0;if(T(e=>[...e,(0,sM.mO)(sr(t),n)]),"assistant"===t.role){let e=tj.current;e&&nx(e)}}U({type:"end"}),eQ({kind:"waiting_model"});break}case"tool_execution_start":{if(sI(e))break;let t=e.toolCallId,n=e.toolName;eQ(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[];return r.some(e=>e.id===t)||r.push({id:t,name:n}),{kind:"running_tools",tools:r}});break}case"tool_execution_update":{if(sI(e))break;let t=e.toolCallId,n=e.toolName,r=e.partialResult,i=r?.content;Array.isArray(i)&&("bash"===n||"powershell"===n||n===n3.sp||(0,rn.G)(r?.details))&&M(e=>{let s=new Map(e);return s.set(t,{role:"toolResult",toolCallId:t,toolName:n,content:i,isError:r?.isError,details:r?.details}),s});let s=n===n3.sp?(0,n3.ky)(e.partialResult):function(e){if(!s$(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>s$(e)&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n").split(/\r?\n/),r="";for(let e=n.length-1;e>=0&&!(r=n[e].trim());e-=1);if(!r)return null;let i=r.replace(/\s+/g," ");return i.length<=500?i:`...${i.slice(-497)}`}(e.partialResult);eQ(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[],i=r.find(e=>e.id===t),o={id:t,name:n||i?.name||"tool",progress:s??i?.progress};return{kind:"running_tools",tools:[...r.filter(e=>e.id!==t),o]}});break}case"tool_execution_end":{if(sI(e))break;let t=e.toolCallId;a?.(e.toolName),M(e=>{if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}),eQ(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"queue_update":tu({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":eC({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":eC(null);break;case"auto_compaction_start":case"compaction_start":eq(!0),eJ(null),eY(null);break;case"auto_compaction_end":case"compaction_end":eq(!1),e.errorMessage?(eJ(e.errorMessage),eY(null)):!e.aborted&&(eY(s_(e.result,e.reason??"auto")),tj.current&&nv(tj.current));break;case"extension_ui_request":nO(e);break;case"extension_ui_closed":tr(t=>st(t,e.id))}},[nW,ng,nT,U,nO,nv,nF,o,a,nx,nB,nt,nD,na]);let nK=(0,i.useCallback)(async(e,n)=>{let i=e.trim();if(!i&&!n?.length)return;if(tS.current||tI.current)return void nc(e,n,no);if(nd&&(np(null),!await tO.current?.(nd))){np(nd),nc(e,n,no);return}let s=!n?.length&&i.startsWith("/");if(!n?.length&&i.startsWith("!")){let t=i.startsWith("!!"),r=(t?i.slice(2):i.slice(1)).trim();return r?void await tW.current?.(r,t):void nc(e,n,no)}let o=tJ.current+1;nT(),tN.current=!0;let a=n?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),l={role:"user",content:a?.length?[...e.trim()?[{type:"text",text:e}]:[],...a]:e,timestamp:Date.now()};T(e=>[...e,l]),tG.current=sy(l),tJ.current=o,tS.current=!0,q(!0),eQ(s?{kind:"running_command"}:{kind:"waiting_model"}),U({type:"start"}),tL.current=!0,e1(!0);let c=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),d=null,u=!1;try{if(v&&r){let t=tj.current??await tF.current,n=t??await nk();if(!n)throw Error("Unable to create a session for the prompt");d=n,el&&(eB(el),t&&await sa(n,{type:"set_model",provider:el.provider,modelId:el.modelId})),tQ.current&&await nM(n).catch(e=>{if(tQ.current)throw e}),u=!0,await sa(n,{type:"prompt",message:e,...c?.length?{images:c}:{}}),nj(1,e)}else if(t)d=t.id,await nM(t.id),u=!0,await sa(t.id,{type:"prompt",message:e,...c?.length?{images:c}:{}});else throw Error("No active session for the prompt");s&&d&&nU(d,o)}catch(t){if(console.error("Failed to send message:",t),!(!u||ss(t))&&d)return void nU(d,o);if(tN.current=!1,T(e=>{let t=e.lastIndexOf(l);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),nW({type:"error",message:t instanceof Error?t.message:String(t)}),nc(e,n,no),tG.current=null,d)return void nq(d);tS.current=!1,n$(),q(!1),eQ(null),U({type:"end"})}},[v,r,el,t,nk,nM,nj,nU,nW,nT,n$,no,U,nq,nc,nd,np]);tW.current=(0,i.useCallback)(async(e,n)=>{if(tS.current||tI.current)return;let r=`${n?"!!":"!"}${e}`;tI.current=!0,J({command:e,excludeFromContext:n}),V(!0);try{let i=tj.current??t?.id??await nk();if(!i)throw Error("Unable to create a session for the shell command");await sa(i,{type:"bash",command:e,excludeFromContext:n}),await nv(i),nj(1,r)}catch(e){console.error("Failed to execute shell command:",e),nW({type:"error",message:e instanceof Error?e.message:String(e)}),nc(r,void 0,no)}finally{tI.current=!1,J(null),V(!1)}},[nW,no,nk,nv,nj,nc,t]);let nV=(0,i.useCallback)(async()=>{let e=tj.current;if(e){if(tI.current){try{await sa(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await sa(e,{type:"abort"})}catch(e){console.error("Failed to abort:",e)}}},[]),nZ=(0,i.useCallback)(async e=>{if(tI.current)return;let t=tj.current;if(t){eP(e);try{let{cancelled:n,newSessionId:r}=await sa(t,{type:"fork",entryId:e})??{};!n&&r&&d?.(r)}catch(e){console.error("Fork failed:",e),nW({type:"error",message:e instanceof Error?e.message:String(e)})}finally{eP(null)}}},[nW,d]),nJ=(0,i.useCallback)(async e=>{if(tI.current)return!1;let t=tj.current;if(!t)return!1;try{let n=await sa(t,{type:"navigate_tree",targetId:e});if(n?.cancelled||tj.current!==t)return!1;return await nv(t),tj.current===t}catch(e){return console.error("Failed to navigate:",e),!1}},[nv]);tO.current=nJ;let nG=(0,i.useCallback)(async e=>{if(tI.current||tS.current||e_)return;E(e);let t=tj.current;t&&(await nb(t,e),e&&sa(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[e_,nb]),nY=(0,i.useCallback)(async(e,t)=>{if(v){let n={provider:e,modelId:t};tq.current=n,ec(n),eB(n),null===tK.current&&ex(sW(tV.current[`${e}/${t}`])??tZ.current);let r=tj.current??await tF.current;if(!r)return;try{await sa(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tj.current;if(n&&!tY.current){tY.current=!0,eW({provider:e,modelId:t}),eU(!0);try{let r=await sa(n,{type:"set_model",provider:e,modelId:t});eD({provider:r.provider,modelId:r.id}),tY.current=!1,await nv(n)}catch(e){console.error("Failed to set model:",e),tY.current=!1,eW(ez),nW({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nv(n,!1,!0)}finally{tY.current=!1,eU(!1)}}},[nW,ez,v,nv,ec]),nX=(0,i.useCallback)(async()=>{let e=tj.current;if(e&&!e_){eq(!0),eJ(null),eY(null);try{let t=await sa(e,{type:"compact"});eY(s_(t,"manual")),await nv(e,!0)}catch(e){eJ(e instanceof Error?e.message:String(e)),eY(null)}finally{eq(!1)}}},[e_,nv]),nQ=(0,i.useCallback)(()=>eJ(null),[]),n0=(0,i.useCallback)(async e=>{let n,i=r??t?.cwd??"",s=i?`/api/models?cwd=${encodeURIComponent(i)}`:"/api/models";try{let t=await fetch(s,e?{signal:e}:void 0);if(!t.ok){let e="";try{let n=await t.json();n&&"object"==typeof n&&"error"in n&&"string"==typeof n.error&&(e=n.error)}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw e}throw Error(e||`Failed to load models (HTTP ${t.status})`)}n=await t.json(),e?.throwIfAborted()}catch(t){throw e?.aborted||t instanceof DOMException&&"AbortError"===t.name||et(t instanceof Error?t.message:String(t)),t}Y(n.models),et(n.modelError??null),er(n.modelScopeWarnings??[]),es(n.thinkingLevels??{}),ea(n.thinkingLevelMaps??{});let o=n.modelList??[];Q(o);let a=n.defaultModel?o.find(e=>e.id===n.defaultModel?.modelId&&e.provider===n.defaultModel?.provider):void 0;if(eu(a?{provider:a.provider,modelId:a.id}:null),tV.current=n.thinkingLevelPins??{},tZ.current=sW(n.defaultThinkingLevel),eb(sW(n.savedDefaultThinkingLevel)),v&&!tj.current){let e=tq.current,t=e&&(0===o.length||o.some(t=>t.provider===e.provider&&t.id===e.modelId));e&&!t&&(tq.current=null,ec(null));let r=t?e:a&&{provider:a.provider,modelId:a.id},i=r&&n.thinkingLevelPins?.[`${r.provider}/${r.modelId}`];null===tK.current&&ex(sW(i)??tZ.current)}},[v,r,t?.cwd]),n1=(0,i.useCallback)(async e=>{let n=r??t?.cwd,i=await fetch("/api/models/default",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...n?{cwd:n}:{},...e})});if(i.ok)return;let s="";try{let e=await i.json();e&&"object"==typeof e&&"error"in e&&"string"==typeof e.error&&(s=e.error)}catch{}throw Error(s||`HTTP ${i.status}`)},[r,t?.cwd]),n2=(0,i.useCallback)(()=>{n0().catch(()=>{})},[n0]),n4=(0,i.useCallback)(async(e,t)=>{try{await n1({provider:e,modelId:t})}catch(e){nW({type:"error",message:`Failed to save default model: ${e instanceof Error?e.message:String(e)}`});return}nW({type:"success",message:`Default model: ${e}/${t}`}),eu({provider:e,modelId:t}),(nr?.provider!==e||nr?.modelId!==t)&&await nY(e,t),n2()},[nW,nr,nY,n2,n1]),n8=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,n,r=""]=t,i=r.trim(),s=tj.current??await nk(),o=e=>(e.handled&&(e.error?nW({type:"error",message:e.error}):e.action||nW({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!s||e_)return o({handled:!0,error:"No active session to compact"});eq(!0),eJ(null),eY(null);let e=await sa(s,{type:"compact",...i?{customInstructions:i}:{}});return eY(s_(e,"manual")),await nv(s,!0)&&nj(),o({handled:!0,message:"Compacted context"})}case"auto-compact":{if(!s)return o({handled:!0,error:"No active session"});let e=await sa(s,{type:"get_state"}),t=!(e?.autoCompactionEnabled??!0);return await sa(s,{type:"set_auto_compaction",enabled:t}),eV(t),o({handled:!0,message:t?"Auto-compaction enabled":"Auto-compaction disabled"})}case"reload":if(!s)return o({handled:!0,error:"No active session to reload"});return await sa(s,{type:"reload"}),await Promise.all([nv(s,!1,!0),ny(s),nE(),n0()]),o({handled:!0,message:"Reloaded session resources"});case"name":if(!s)return o({handled:!0,error:"No active session to name"});if(!i)return o({handled:!0,error:"Usage: /name <name>"});return await sa(s,{type:"set_session_name",name:i}),await nv(s)&&nj(),o({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!s)return o({handled:!0,error:"No active session"});let e=await sa(s,{type:"get_session_stats"});return e&&tt(e),g?.(),o({handled:!0,action:"openSessionStats"})}case"mcp":{if(i||!x)return{handled:!1};let e=await nI();if(!e||!(e.some(rE)||!e.some(e=>"mcp"===e.name)))return{handled:!1};return x("mcp"),o({handled:!0,action:"openSettings"})}case"copy":{if(!s)return o({handled:!0,error:"No active session"});let e=await sa(s,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return o({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),o({handled:!0,message:"Copied last assistant message"})}case"clone":{if(!s)return o({handled:!0,error:"No active session to clone"});if(tS.current||tI.current)return o({handled:!0,error:"Cannot clone while the session is running"});let e=await sa(s,{type:"clone",leafId:N});if(e?.cancelled||!e?.newSessionId)return o({handled:!0,error:"Cannot clone an empty or unsaved session"});let t=o({handled:!0,message:"Cloned current session branch"});return d?.(e.newSessionId),t}default:return{handled:!1}}}catch(e){return o({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&eq(!1)}},[N,nW,nk,e_,n0,nv,nE,ny,nj,x,d,g,nI]),n5=(0,i.useCallback)(async(e,t,n)=>{let r=tj.current;if(nd)return void nc(e,n,no);if(!r){nc(e,n,no),nW({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 sa(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){console.error("Failed to submit streaming prompt:",t),ss(t)&&nc(e,n,no),nW({type:"error",message:t instanceof Error?t.message:String(t)})}},[nW,no,nd,nc]),n6=(0,i.useCallback)(async(e,t)=>{await n5(e,"steer",t)},[n5]),n9=(0,i.useCallback)(async(e,t,n)=>{await n5(e,t,n)},[n5]),n7=(0,i.useCallback)(async(e,t)=>{await n5(e,"followUp",t)},[n5]),re=(0,i.useCallback)(async()=>{let e=tj.current;if(e)try{await sa(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),rt=(0,i.useCallback)(async()=>{let t=tj.current;if(t)try{let n=await sa(t,{type:"clear_queue"});tu({steering:[],followUp:[]});let r=[...n?.steering??[],...n?.followUp??[]];r.length>0&&e.chatInputRef?.current?.prependText(r.join("\n\n"))}catch(e){console.error("Failed to recall queued messages:",e),nW({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,nW]),rr=(0,i.useCallback)(async e=>{if("auto"===e){tK.current=null,em(null),ej(null);return}v?(tK.current=e,em(e)):ej(e);let t=tj.current??await tF.current;if(t)try{await sa(t,{type:"set_thinking_level",level:e}),tQ.current&&tj.current===t&&(ew(e),ej(null))}catch(e){console.error("Failed to set thinking level:",e),ej(null)}},[v]),ri=(0,i.useCallback)(async e=>{try{await n1({thinkingLevel:e})}catch(e){nW({type:"error",message:`Failed to save default reasoning level: ${e instanceof Error?e.message:String(e)}`});return}nW({type:"success",message:`Default reasoning level: ${e}`}),eb(e),ns!==e&&await rr(e),n2()},[nW,ns,rr,n2,n1]),rs=(0,i.useCallback)(async e=>{let t=(0,sf.xG)(e);!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sg();if(t)try{t.setItem(sm,e)}catch{}}(e),t9(e);let n=tj.current??await tF.current;if(!n){tw.current=void 0!==t;return}try{let e=await sa(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});tw.current=void 0!==t;let r=e?.sessionId??n;(r!==n||e?.recreated)&&(nT(),n$(),tr([]),ts([]),tj.current=r,e?.recreated&&tk.current===r&&nR(r)),nC(),ta([]),tc([]);let[i]=await Promise.all([sa(r,{type:"get_state"}),ny(r)]);tQ.current&&tj.current===r&&(eL(i.systemPrompt??""),na(i))}catch(e){console.error("Failed to set tools:",e)}},[nT,nC,n$,ny,nR,t9,na]),ro=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=tD.current;n&&(null!==tz.current&&(cancelAnimationFrame(tz.current),tz.current=null),tM.current=!0,tL.current=!1,tA.current=!1,e1(!1),n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),tP.current=n.scrollTop)},[]),ra=(0,i.useCallback)(()=>{let e=tD.current,t=tR.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!==tz.current&&(cancelAnimationFrame(tz.current),tz.current=null),tA.current=!0,tP.current=n,e.scrollTo({top:n,behavior:"auto"})},[]),rl=(0,i.useCallback)(()=>{let e=tD.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=tS.current,s=tA.current,o=function(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:96;return!!sR(n,r,i)||!(n<t)&&(!!(!e&&n>t&&sR(n,r,i,s))||e)}(s,tP.current,t,n,r,i?96:8);tA.current=o,tP.current=t;let a=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return!(n<=t)&&!sR(e,t,n,r)}(t,n,r);e4(e=>e===a?e:a),!s&&o&&i?nt("auto"):o||null===tz.current||(cancelAnimationFrame(tz.current),tz.current=null)}},[nt]),rc=(0,i.useCallback)((e,t)=>{t?.running&&(ny(e),(t.state?.isStreaming||t.state?.isPromptRunning)&&(tC.current=!!t.state.isStreaming,tN.current=!!t.state.isPromptRunning,tS.current=!0,q(!0),eQ(t.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),U({type:"resume"}),!t.state.isStreaming&&t.state.isPromptRunning&&nU(e)),t.state?.isBashRunning&&(tI.current=!0,V(!0),n_(e))),t?.state&&(void 0!==t.state.isCompacting&&eq(t.state.isCompacting),void 0!==t.state.systemPrompt&&eL(t.state.systemPrompt??null),void 0!==t.state.extensionStatuses&&ta(t.state.extensionStatuses??[]),void 0!==t.state.extensionWidgets&&tc(t.state.extensionWidgets??[]),void 0!==t.state.queuedMessages&&tu(sz(t.state.queuedMessages)))},[U,ny,n_,nU]);ty.current=e=>{!tg.current||(tg.current=!1,tv(e=>e+1),tQ.current&&tj.current===e&&tk.current===e&&(nR(e),nv(e,!1,!0).then(t=>{tQ.current&&tj.current===e&&rc(e,t)})))},(0,i.useEffect)(()=>{let e=t?.id;if(!e)return;let n=!1,r=async()=>{let t=await nL(e);!n&&"hidden"===document.visibilityState&&sS(t)&&ty.current(e)};r();let i=setInterval(()=>void r(),3e4),s=()=>{"visible"===document.visibilityState&&(ty.current(e),r())};return document.addEventListener("visibilitychange",s),()=>{n=!0,clearInterval(i),document.removeEventListener("visibilitychange",s)}},[nL,t?.id]),(0,i.useEffect)(()=>{if(tQ.current=!0,eM.current=e$.current,t){tj.current=t.id;let e=su(t.id);e&&(j({sessionId:t.id,filePath:"",totalActiveMs:e.totalActiveMs??0,tree:e.summaryTree,leafId:e.leafId,context:{messages:e.messages,entryIds:e.entryIds,oldestEntryId:e.oldestEntryId,hasMore:e.hasMore,turnsBefore:e.turnsBefore,thinkingLevel:e.thinkingLevel,model:e.model},stats:e.stats}),E(e.leafId),T(e.messages),L(e.entryIds),W(e.oldestEntryId),D(e.hasMore),B(e.turnsBefore),C(null),w(!1)),nv(t.id,!e,!0,{force:!0}).then(e=>{rc(t.id,e)})}return()=>{tQ.current=!1;let e=v?s:null;e&&queueMicrotask(()=>{tQ.current||t_.current||rv(e)});let t=tj.current,n=t1.current;if(t&&n&&n.sessionId===t&&n.snapshotRevision){let e=su(t),r=t4.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)?sp({sessionId:t,revision:n.snapshotRevision,messages:t2.current,entryIds:t4.current,leafId:t8.current,oldestEntryId:t5.current,hasMore:t6.current,turnsBefore:t3.current,summaryTree:n.tree,thinkingLevel:n.context.thinkingLevel,model:n.context.model,stats:n.stats,totalActiveMs:n.totalActiveMs,loadedEntryIds:t4.current}):sh(t)}null!==tz.current&&(cancelAnimationFrame(tz.current),tz.current=null),tT.current+=1,nT(),n$()}},[]),(0,i.useEffect)(()=>{h?.(eR)},[eR,h]),(0,i.useEffect)(()=>(m?.(nw),()=>m?.(null)),[nw,m]);let rd=_||K||e_;(0,i.useEffect)(()=>{p&&p(y?.tree??[],N,nG,rd)},[y?.tree,N,nG,rd,p]),(0,i.useEffect)(()=>{let e=tD.current;if(e)return tP.current=e.scrollTop,e.addEventListener("scroll",rl,{passive:!0}),()=>{e.removeEventListener("scroll",rl)}},[I.length,k,rl]),(0,i.useEffect)(()=>{_||e1(!1)},[_]),(0,i.useLayoutEffect)(()=>{I.length>0&&(tL.current?(tL.current=!1,tM.current=!0,ra()):tM.current?!tS.current&&tA.current&&nt("auto"):(tM.current=!0,nt("instant")))},[I.length,_,nt,ra]),(0,i.useEffect)(()=>{let e=new AbortController;return(async()=>{for(let t=0;;t++)try{await n0(e.signal);return}catch(n){if(e.signal.aborted||n instanceof DOMException&&"AbortError"===n.name||t>=sF.length||(await sB(sF[t]),e.signal.aborted))return}})(),()=>e.abort()},[n0,u]),(0,i.useEffect)(()=>{if(!eG)return;let e=setTimeout(()=>eY(null),6e3);return()=>clearTimeout(e)},[eG]);let[ru,rp]=(0,i.useState)(null),rh=(0,i.useRef)(5e3),rf=(0,i.useRef)(null),rm=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(0===e9.visible.length){rm.current=null;return}let e=e9.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{e7({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=e9.visible[0];if(!t||(rm.current!==t.id&&(rm.current=t.id,rh.current=5e3),e9.visible.some(e=>e.id===ru)))return;rf.current=Date.now();let n=setTimeout(()=>{e7({type:"mark_oldest_exiting"})},rh.current);return()=>{clearTimeout(n),null!==rf.current&&(rh.current=Math.max(0,rh.current-(Date.now()-rf.current)),rf.current=null)}},[e9.visible,ru]),(0,i.useEffect)(()=>{tt(null)},[I.length,eN?.tokens,eN?.percent,eN?.contextWindow]);let rb=ns??"auto",rk=tn[0]??null,rw=Math.max(0,tn.length-1),rS=ti[0]??null,rC=Math.max(0,ti.length-1),rN=(0,i.useMemo)(()=>(function(e,t,n){let r=e[e.length-1],i=[];for(let s=0;s<t;s++){let t=e[s];i.push(void 0===t?sj(r,s-e.length):n.get(t)??t)}return i})(R,I.length,A),[R,I.length,A]);return{data:y,loading:k,error:S,activeLeafId:N,messages:I,activeToolResults:$,entryIds:R,messageKeys:rN,historyCursor:z,hasEarlierMessages:O,earlierTurnCount:F,streamingStore:H,agentRunning:_,modelNames:G,modelList:X,modelError:ee,modelScopeWarnings:en,modelThinkingLevels:ei,modelThinkingLevelMaps:eo,newSessionModel:el,toolPreset:ep,thinkingLevel:rb,retryInfo:eS,contextUsage:eN,systemPrompt:eR,forkingEntryId:eA,isCompacting:e_,compactError:eZ,compactResult:eG,currentModel:nn,displayModel:nr,modelSwitching:eH,sessionStats:nm,autoCompactionEnabled:eK,slashCommands:e8,slashCommandsLoading:e6,queuedMessages:td,notices:e9.visible,extensionDialog:rk,waitingExtensionDialogCount:rw,extensionCustomUi:rS,waitingExtensionCustomUiCount:rC,extensionStatuses:to,extensionWidgets:tl,respondToExtensionUi:nP,sendExtensionCustomInput:nz,isAutoModelSelection:v&&null===el,isAutoThinkingSelection:v&&null===ef,defaultModel:ed,savedDefaultThinkingLevel:ev,agentPhase:eX,isNew:v,editEntryId:nd,promptAnchorActive:e0,showScrollToBottom:e2,sessionIdRef:tj,scrollContainerRef:tD,lastUserMsgRef:tR,pendingScrollToUserRef:tL,initialScrollDoneRef:tM,handleSend:nK,handleAbort:nV,handleFork:nZ,handleNavigate:nJ,handleModelChange:nY,handleCompact:nX,handleSteer:n6,handleFollowUp:n7,handlePromptWithStreamingBehavior:n9,handleAbortCompaction:re,dismissCompactError:nQ,handleRecallQueue:rt,handleBuiltinSlashCommand:n8,handleEditContent:nh,cancelEdit:nd?nf:void 0,addNotice:nW,setNoticePaused:rp,handleToolPresetChange:rs,handleThinkingLevelChange:rr,handleSetDefaultModel:n4,handleSetDefaultThinkingLevel:ri,loadTools:ny,loadSlashCommands:nE,setActiveLeafId:E,setData:j,setMessages:T,loadContext:nb,scrollToBottom:nt,scrollUserMsgToTop:ra,scrollToMessage:ro,dispatch:U,setAgentRunning:q,setForkingEntryId:eP,bashRunning:K,pendingBash:Z,handleAgentEventRef:t$}}({session:a,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:f,initialNewSessionChoices:g,onNewSessionChoicesChange:x,onAgentEnd:X,onToolEnd:b,onAttentionNeeded:y,onSessionCreated:j,onSessionForked:k,modelsRefreshKey:w,chatInputRef:S,onBranchDataChange:C,onSystemPromptChange:N,onSystemToolsChange:E,onSystemInfoLoaderChange:I,onSessionStatsPanelOpen:$,onOpenSettings:M,deferInitialScroll:!!ee}),tI=sq(eh,sK),tT=sq(eh,sV),t$=(0,i.useCallback)(()=>eh.getState().streamingMessage,[eh]),tM=ef||em;(0,i.useEffect)(()=>{if(ef&&q)return q()},[ef,q]);let[tR,tL]=(0,i.useState)(null),[tA,tP]=(0,i.useState)(!1),[tz,tW]=(0,i.useState)(!1),[tO,tD]=(0,i.useState)(null),tF=(0,i.useRef)(null),tB=(0,i.useRef)(null),tH=(0,i.useCallback)(()=>{tL(null),tP(!1),tD(null)},[]);(0,i.useEffect)(()=>{O||tH()},[O,tH]);let tU=(0,i.useCallback)(()=>{if(!O||tA)return;let e=window.getSelection(),t=e?.rangeCount?e.getRangeAt(0):null,n=tY.current;if(!e||e.isCollapsed||!t||!n||!n.contains(t.commonAncestorContainer))return void tL(null);let r=e.toString().trim();if(!r)return void tL(null);let i=t.getBoundingClientRect(),s=[t.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?t.commonAncestorContainer:t.commonAncestorContainer.parentElement,t.startContainer.nodeType===Node.ELEMENT_NODE?t.startContainer:t.startContainer.parentElement,t.endContainer.nodeType===Node.ELEMENT_NODE?t.endContainer:t.endContainer.parentElement].map(e=>e?.closest('[data-message-role="assistant"]')?.dataset.entryId).find(e=>!!e);tL({text:r,top:Math.min(window.innerHeight-44,i.bottom+8),left:Math.max(64,Math.min(window.innerWidth-64,i.left+i.width/2)),sourceEntryId:s})},[O,tA]);(0,i.useEffect)(()=>{tA&&tR&&tB.current?.insertIfEmpty(rc(tR.text,K("chat.quoteIntro"),K("chat.quoteQuestion")))},[tA,tR,K]),(0,i.useLayoutEffect)(()=>{let e=tF.current;if(!e||!tR)return;let t=window.visualViewport,n=()=>{let n=e.getBoundingClientRect(),r=t?.offsetTop??0,i=t?.offsetLeft??0;e.style.top=`${Math.max(r+8,Math.min(tR.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(tR.left-n.width/2,i+(t?.width??window.innerWidth)-n.width-8))}px`};n();let r=new ResizeObserver(n);return r.observe(e),window.addEventListener("resize",n),t?.addEventListener("resize",n),t?.addEventListener("scroll",n),()=>{r.disconnect(),window.removeEventListener("resize",n),t?.removeEventListener("resize",n),t?.removeEventListener("scroll",n)}},[tR,tA,tO]),(0,i.useEffect)(()=>{if(!tR)return;let e=e=>{tA||tF.current?.contains(e.target)||tH()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),tz||tH())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[tR,tA,tz,tH]);let t_=(0,i.useCallback)(()=>{tR&&(S?.current?.insertText(rc(tR.text,K("chat.quoteIntro"),K("chat.quoteQuestion"))),tH())},[S,tR,tH,K]),tq=(0,i.useCallback)(async e=>{let t=e6.current??a?.id;if(!tz&&e.trim()&&tR?.sourceEntryId&&t&&W){tW(!0),tD(null),_?.();try{await W(e,t,tR.sourceEntryId),tH()}catch(t){tB.current?.restoreSubmission(e),tD(t instanceof Error?t.message:String(t))}finally{tW(!1)}}},[W,tR,tz,a?.id,e6,tH,_]),tK=(0,i.useRef)(!1);(0,i.useEffect)(()=>{ei||es||!D||tK.current||(tK.current=!0,F?.(),te(D))},[D,ei,es,te,F]),(0,i.useEffect)(()=>{let e=!!eF&&!Y.current;Y.current=!!eF,Z&&e&&J.current()},[Z,eF]),(0,i.useEffect)(()=>{o=tM?tt:null},[tM,tt]);let[tV,tZ]=(0,i.useState)(50),[tJ,tG]=(0,i.useState)(null),tY=(0,i.useRef)(null),tX=(0,i.useRef)(null),tQ=(0,i.useRef)(!1),t0=(0,i.useRef)(!1),t1=(0,i.useRef)(ee);t1.current=ee;let[t2,t4]=(0,i.useState)(null),t8=eo[el.indexOf(t2?.entryId??"")],t5=t8?.role==="assistant"?t2?.blockIndex===void 0?t8.content.find(e=>"text"===e.type):t8.content[t2.blockIndex]:void 0,t6=(0,i.useRef)({entryIds:el,historyCursor:ed,hasEarlierMessages:eu});t6.current={entryIds:el,historyCursor:ed,hasEarlierMessages:eu};let t3=(0,i.useRef)(null),t9=(0,i.useCallback)(async(e,t,n)=>{t3.current=t;let r=await tS(e,tC,t,n);return r||t3.current!==t||(t3.current=null),r},[tC,tS]);(0,i.useEffect)(()=>{ed!==t3.current&&(t3.current=null)},[ed]),(0,i.useLayoutEffect)(()=>{let e=a?.id,t=e3.current,n=tY.current;if(e&&u&&t&&n)return()=>{if(t1.current)return;if(sR(t.scrollTop,t.clientHeight,t.scrollHeight))return void u(e,{atBottom:!0});let r=t.getBoundingClientRect().top,i=function(e,t){let n=e[0];for(let r of e){if(r.top>t)break;n=r}return n?{anchorEntryId:n.entryId,anchorOffset:n.top-t}:null}(Array.from(n.children).flatMap(e=>{if(!(e instanceof HTMLElement)||!e.dataset.entryId)return[];let t=e.getBoundingClientRect();return[{entryId:e.dataset.entryId,top:t.top,bottom:t.bottom}]}),r);i&&u(e,{atBottom:!1,...i,oldestEntryId:t6.current.historyCursor})}},[ei,u,e3,a?.id]),(0,i.useEffect)(()=>{l&&et(null)},[l]),(0,i.useEffect)(()=>{let e=a?.id;if(!ee||!e||ei||l||t0.current)return;t0.current=!0;let t=new AbortController;return(async()=>{let n=t6.current;if(n.entryIds.includes(ee.anchorEntryId)){tZ(e=>Math.max(e,2*n.entryIds.length)),er(!0);return}tQ.current=!0;let r=n.historyCursor,i=n.hasEarlierMessages;try{for(;i&&r&&!t.signal.aborted;){let n=await t9(e,r,{signal:t.signal});if(t.signal.aborted)return;if(!n){tN("instant"),et(null);return}if(tZ(e=>e+Math.max(50,2*n.messages.length)),n.entryIds.includes(ee.anchorEntryId))return void er(!0);if(n.oldestEntryId===ee.oldestEntryId)break;r=n.oldestEntryId,i=n.hasMore}t.signal.aborted||(tN("instant"),et(null))}finally{tQ.current=!1}})(),()=>{t.abort(),et(null)}},[tC,t9,ei,ee,tN,l,a?.id]),(0,i.useLayoutEffect)(()=>{let e=tY.current;if(!ee||!e||l)return;let t=Array.from(e.children).find(e=>e instanceof HTMLElement&&e.dataset.entryId===ee.anchorEntryId);if(t instanceof HTMLElement){tE(t,ee.anchorOffset),et(null);return}en&&(tN("instant"),et(null))},[el,ee,en,tN,tE,l,tV]),(0,i.useEffect)(()=>{if(!l||ei)return;let e=new AbortController;return(async()=>{let t=t6.current,n=t.entryIds.includes(l.entryId);if(!n&&!tM&&t.hasEarlierMessages&&t.historyCursor&&!tQ.current){tQ.current=!0;let r=e3.current;r&&(tX.current=r.scrollHeight-r.scrollTop);let i=await t9(l.sessionId,t.historyCursor,{tail:200,signal:e.signal});tQ.current=!1,n=!!i?.entryIds.includes(l.entryId)}e.signal.aborted||(n?(tX.current=null,tZ(e=>Math.max(e,(t6.current.entryIds.length+200)*2)),t4(l)):c?.(l))})(),()=>e.abort()},[l,ei,tM,t9,c,e3]),(0,i.useLayoutEffect)(()=>{if(!t2||t2!==l)return;let e=`[data-entry-id="${CSS.escape(t2.entryId)}"]`,t=e3.current?.querySelector(t8?.role==="user"?e:`${e} [data-search-target]`);t&&(tE(t),t.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500})),t4(null),c?.(t2)},[t2,l,t8,e3,tE,c]),(0,i.useEffect)(()=>{let e=e3.current;if(!tJ||!e)return;let t=new IntersectionObserver(t=>{if(!t[0]?.isIntersecting||tQ.current)return;if(!eu){tX.current=e.scrollHeight-e.scrollTop,tZ(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50;return e+t})(e));return}if(!ed||ed===t3.current)return;let n=a?.id??e6.current;n&&(tQ.current=!0,tX.current=e.scrollHeight-e.scrollTop,t9(n,ed).finally(()=>{tQ.current=!1}))},{root:e,threshold:0});return t.observe(tJ),()=>t.disconnect()},[tJ,tV,ed,eu,a,t9,e6,e3]),(0,i.useEffect)(()=>{tZ(e=>Math.max(e,eo.length))},[eo.length]),(0,i.useEffect)(()=>{if(null==tX.current)return;let e=e3.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-tX.current),tX.current=null}},[tV,e3]);let t7=eL?[eL.sessionId,eL.sessionFile??"",eL.sessionName??"",eL.userMessages,eL.assistantMessages,eL.toolCalls,eL.toolResults,eL.totalMessages,eL.tokens.input,eL.tokens.output,eL.tokens.cacheRead,eL.tokens.cacheWrite,eL.tokens.total,eL.cost??0,eL.totalActiveMs??0].join("|"):null,ne=(0,i.useRef)(eL);ne.current=eL,(0,i.useEffect)(()=>{T?.(ne.current)},[t7,T]),(0,i.useEffect)(()=>()=>{T?.(null)},[T]);let nt=eN?`${eN.percent??"null"}|${eN.contextWindow}|${eN.tokens??"null"}`:null,nn=(0,i.useRef)(eN);nn.current=eN,(0,i.useEffect)(()=>{R?.(nn.current)},[nt,R]),(0,i.useEffect)(()=>()=>{R?.(null)},[R]);let nr=(0,i.useCallback)(async e=>{let t=a?.cwd??h;if(!t)return void eY({type:"warning",message:K("chat.dropNeedsCwd")});try{var n;let r,{status:i,data:s}=await tr(t,e,"skip");if(200!==i&&207!==i)throw Error(s.error??`HTTP ${i}`);let o=s.uploaded??[],a=s.skipped??[],l=(n=[...o,...a],r=new Set(n),e.filter(e=>r.has(e.name)).map(e=>tn(e.name,!1)).join(""));for(let e of(l&&S?.current?.insertText(l),o.length>0&&(eY({type:"success",message:K("chat.dropUploaded",{count:o.length})}),A?.()),a.length>0&&eY({type:"warning",message:K("chat.dropAlreadyExists",{names:a.join(", ")})}),s.errors??[]))eY({type:"error",message:K("chat.dropFailed",{message:`${e.name}: ${e.error}`})})}catch(e){eY({type:"error",message:K("chat.dropFailed",{message:e instanceof Error?e.message:String(e)})})}},[eY,S,h,A,a?.cwd,K]),ni=(0,i.useCallback)(e=>{let{images:t,files:n,folders:r}=function(e){let t=[],n=[],r=[];for(let i of e)"folder"===i.kind?r.push(i.name):i.file.type.startsWith("image/")?t.push(i.file):n.push(i.file);return{images:t,files:n,folders:r}}(e);t.length>0&&S?.current?.addImages(t),r.length>0&&eY({type:"warning",message:K("chat.dropFoldersUnsupported",{names:r.join(", ")})}),n.length>0&&nr(n)},[eY,S,K,nr]),ns=(0,i.useCallback)(e=>{ni(e.map(e=>({kind:"file",file:e})))},[ni]),{isDragOver:no,handleDragEnter:na,handleDragOver:nl,handleDragLeave:nc,handleDrop:nd}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),s=(0,i.useCallback)(e=>{ti(e)&&(e.preventDefault(),r.current+=1,n(!0))},[]),o=(0,i.useCallback)(e=>{ti(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},[]);return{isDragOver:t,handleDragEnter:s,handleDragOver:o,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(ts(t.dataTransfer))},[e])}}(ni),nu=eo.filter(e=>(0,n4.Y0)(e)||"assistant"===e.role),np=(0,i.useMemo)(()=>{let e=new Map(ea);for(let t of eo)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[ea,eo]),nh=(0,i.useMemo)(()=>new WeakMap,[]),nf=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=eo.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}(eo[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[eo]),nm=(t=nu.length,(s=(0,i.useRef)([])).current=Array(t).fill(null).map((e,t)=>s.current[t]??null),s),ng=(0,i.useCallback)(()=>{tZ(e=>Math.max(e,2*eo.length))},[eo.length]),nx=e4&&0===eo.length&&!tI&&!tM;eU(e3,!!a?.id||!nx);let nv=a?.cwd??h??void 0,nb=function(e,t,n){let[r,s]=(0,i.useState)(()=>new Map);return(0,i.useEffect)(()=>{let r=rr(e,t);if(0===r.length)return;let i=!1;return Promise.allSettled(r.map(async e=>({sessionId:e.sessionId,entry:await function(e,t,n){let r=rs.get(e);if(r)return r;let i=ro.get(e);if(void 0!==i&&Date.now()-i<3e4)return Promise.resolve(null);let s=(async()=>{try{var r;let{messages:i,cwd:s}=await ri(e,5),o=new Map;for(let e of i)"toolResult"===e.role&&o.set(e.toolCallId,e);return{files:(r=t??s??n,rt(i.flatMap(e=>"assistant"===e.role?e.content??[]:[]),o,r))}}catch{return ro.set(e,Date.now()),null}})();return rs.set(e,s),s.catch(()=>ro.set(e,Date.now())),s}(e.sessionId,e.cwd,n)}))).then(e=>{i||s(t=>{let n=null;for(let r of e){if("fulfilled"!==r.status)continue;let{sessionId:e,entry:i}=r.value;!i||t.get(e)||(n??=new Map(t)).set(e,i.files)}return n??t})}),()=>{i=!0}},[e,t,n]),r}(eo,np,nv),ny=(0,i.useRef)(null),nj=(0,i.useRef)(0),nk=(0,i.useRef)(null),nw=(0,i.useRef)(!1),nS=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=ny.current;if(!ef||!e7){nS.current=null,nj.current=0,nw.current=!1,e&&(e.style.height="");return}let t=e3.current,n=tY.current,r=e9.current;if(!t||!n||!r||!e)return;let i=!1,s=()=>{var s;let o;if(i||e3.current!==t||tY.current!==n||e9.current!==r||ny.current!==e)return;let a=t.getBoundingClientRect().top,l=Math.max(0,r.getBoundingClientRect().top-a+t.scrollTop-16),c=e.getBoundingClientRect().top-a+t.scrollTop,d=(s=t.clientHeight,0===(o=Math.max(0,l))?0:Math.max(0,Math.ceil(o+s-Math.max(0,c)))),u=!nw.current;u&&(nw.current=!0),d!==nj.current&&(nj.current=d,e.style.height=d>0?`${d}px`:"",u&&d>0&&tw())};nS.current=s,s();let o="u"<typeof ResizeObserver?null:new ResizeObserver(()=>{i||null!==nk.current||(nk.current=requestAnimationFrame(()=>{nk.current=null,s()}))});return o?.observe(t),o?.observe(n),o?.observe(r),()=>{i=!0,nS.current===s&&(nS.current=null),o?.disconnect(),null!==nk.current&&(cancelAnimationFrame(nk.current),nk.current=null)}},[ef,e9,eo.length,e7,e3,tw]);let nC=(0,i.useCallback)(()=>{nS.current?.()},[]);(0,i.useLayoutEffect)(nC,[tI,tT,nC]);let nN=eM?ej[`${eM.provider}:${eM.modelId}`]??null:null,nE=eM?ek[`${eM.provider}:${eM.modelId}`]??null:null,nI=(0,r.jsx)(iU,{ref:S,onSend:te,onAbort:tt,onSteer:ef?tu:void 0,onFollowUp:ef?tp:void 0,onPromptWithStreamingBehavior:ef?th:void 0,isStreaming:tM,model:eM,isAutoModelSelection:eX,modelNames:ex,modelList:ev,modelError:eb,modelScopeWarnings:ey,onModelChange:tc,modelSwitching:eR,defaultModel:e0,onSetDefaultModel:ty,onCompact:a||e4?td:void 0,onAbortCompaction:tf,isCompacting:eI,compactError:eT,onDismissCompactError:tm,compactResult:e$,toolPreset:ew,onToolPresetChange:a||e4?tv:void 0,thinkingLevel:eS,isAutoThinkingSelection:eQ,onThinkingLevelChange:a||e4?tb:void 0,availableThinkingLevels:nN,thinkingLevelMap:nE,savedDefaultThinkingLevel:e1,onSetDefaultThinkingLevel:a||e4?tj:void 0,retryInfo:eC,queuedMessages:ez,inputHistory:nf,onRecallQueue:tg,slashCommands:eA,slashCommandsLoading:eP,onLoadSlashCommands:tk,onBuiltinCommand:tx,soundEnabled:B,onSoundToggle:H,onAudioUnlock:_,draftKey:a?.id??f??void 0,cwd:a?.cwd??h,onAttachFiles:ns});return ei?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:K("chat.loadingSession")}):es?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:es}):(0,r.jsxs)("div",{className:"chat-content relative flex h-full min-w-0 flex-col overflow-hidden",style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:na,onDragOver:nl,onDragLeave:nc,onDrop:nd,children:[no&&(0,r.jsxs)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center bg-[rgba(37,99,235,0.06)] backdrop-blur-[1px]",children:[(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:[0,.8,1.6].map(e=>(0,r.jsx)("div",{className:"absolute h-[720px] w-[720px] rounded-full border-[1.5px] border-solid border-[rgba(37,99,235,0.5)] animate-[drop-ripple_2.4s_ease-out_infinite_backwards]",style:{transformOrigin:"center",animationDelay:`${e}s`}},e))}),(0,r.jsxs)("svg",{width:"280",height:"280",viewBox:"0 0 140 140",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"drop-shadow-[0_6px_18px_rgba(37,99,235,0.18)]",children:[(0,r.jsx)("rect",{x:"28",y:"44",width:"84",height:"60",rx:"8",fill:"rgba(37,99,235,0.08)",stroke:"rgba(37,99,235,0.50)",strokeWidth:"1.8"}),(0,r.jsx)("path",{d:"M36 100 L54 72 L68 88 L80 74 L104 100Z",fill:"rgba(37,99,235,0.16)",stroke:"rgba(37,99,235,0.40)",strokeWidth:"1.4",strokeLinejoin:"round"}),(0,r.jsx)("circle",{cx:"96",cy:"58",r:"8",fill:"rgba(37,99,235,0.22)",stroke:"rgba(37,99,235,0.55)",strokeWidth:"1.6"}),(0,r.jsxs)("g",{stroke:"rgba(37,99,235,0.45)",strokeWidth:"1.4",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"96",y1:"46",x2:"96",y2:"43"}),(0,r.jsx)("line",{x1:"96",y1:"70",x2:"96",y2:"73"}),(0,r.jsx)("line",{x1:"84",y1:"58",x2:"81",y2:"58"}),(0,r.jsx)("line",{x1:"108",y1:"58",x2:"111",y2:"58"}),(0,r.jsx)("line",{x1:"87.5",y1:"49.5",x2:"85.4",y2:"47.4"}),(0,r.jsx)("line",{x1:"104.5",y1:"66.5",x2:"106.6",y2:"68.6"}),(0,r.jsx)("line",{x1:"104.5",y1:"49.5",x2:"106.6",y2:"47.4"}),(0,r.jsx)("line",{x1:"87.5",y1:"66.5",x2:"85.4",y2:"68.6"})]})]})]}),(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:36*!V,zIndex:40,display:"flex",justifyContent:"flex-end",padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)(s2,{notices:eW,floating:!0,onPauseChange:eG})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[eF&&(0,r.jsx)(s5,{request:eF,waitingCount:eB,onRespond:eV},eF.id),eH&&(0,r.jsx)(s6,{request:eH,waitingCount:e_,onInput:eZ},eH.id),!nx&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:e3,className:"scrollbar-subtle min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-gutter:stable]",style:{visibility:ee?"hidden":void 0},children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{ref:tY,onPointerUp:tU,style:{width:"100%",minWidth:0,maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(()=>{var e;let t,n,s=-1;for(let e=eo.length-1;e>=0;e--)if("user"===eo[e].role){s=e;break}let o=-1;for(let e=eo.length-1;e>=0;e--)if((0,n4.Y0)(eo[e])){o=e;break}let l=new Map,c=0;eo.forEach((e,t)=>{((0,n4.Y0)(e)||"assistant"===e.role)&&l.set(t,c++)});let d=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.messageOverride??eo[e];if((0,n4.zZ)(n))return null;let o=!1===t.withNotices?[]:(0,sM.YQ)(eo[e]),c=(0,n4.Y0)(n)||"assistant"===n.role,d=l.get(e),u=t.keyPrefix??"message",p=ec[e],h=!1;if("assistant"===n.role){h=!0;for(let t=e+1;t<eo.length;t++){let e=eo[t].role;if("user"===e)break;if("assistant"===e){h=!1;break}}h&&tI&&e===eo.length-1&&(h=!1)}void 0!==t.showTimestamp&&(h=t.showTimestamp);let f=(0,r.jsx)(rd.Dx,{message:n,toolResults:np,modelNames:ex,cwd:nv,onOpenFile:L,onOpenSubagent:P,onEnterSubagent:z,entryId:el[e],searchBlock:el[e]===t2?.entryId?t5:void 0,onFork:em||e4?void 0:to,forking:eE===el[e],onEditContent:tM?void 0:ta,onCancelEdit:tl,isEditing:e8===el[e],showTimestamp:h,prevTimestamp:e>0?eo[e-1].timestamp:void 0,sessionId:a?.id??e6.current??void 0,writtenFiles:t.writtenFiles,turnDurationMs:t.turnDurationMs,onCompact:t.recoverTruncation?td:void 0,isCompacting:t.recoverTruncation?eI:void 0,compactError:t.recoverTruncation?eT:void 0},`${u}-view-${p}`),m=o.length>0?(0,r.jsx)(sJ.yt,{notices:o},`${u}-notices-${p}`):null;return c&&void 0!==d?(0,r.jsxs)("div",{"data-entry-id":el[e],ref:!1===t.attachRef?void 0:t=>{nm.current[d]=t,e===s&&(e9.current=t)},children:[f,m]},`${u}-${p}`):(0,r.jsxs)(i.Fragment,{children:[f,m]},`${u}-${p}`)},u=[];for(let e=0;e<eo.length;){let t,n=eo[e],i=(0,n4.Y0)(n);if(!i&&0!==e){u.push(d(e)),e+=1;continue}let s=i?e:-1,a=i?e:0,c=e+1;for(;c<eo.length&&!(0,n4.Y0)(eo[c]);)c+=1;let p=function(e,t,n){for(let i=n-1;i>t;i--){var r;if("assistant"===(r=e[i]).role&&(0,n4.dQ)(r).answerBlocks.some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0))return i}for(let r=n-1;r>t;r--)if(e[r]?.role==="assistant")return r;return -1}(eo,s,c);if(-1===p||(tM||tI)&&c===eo.length&&s===o){for(let e=a;e<c;e++)u.push(d(e));e=c;continue}i&&u.push(d(s));let h=i&&el[s]?(0,rl.G)(eo,s,c):void 0,f=function(e,t){let n=e.get(t);if(n)return n;let{answerBlocks:r}=(0,n4.dQ)(t),i=r.length>0||(0,n4.mc)(t)||(0,n4.PC)(t)?ra(t,r):null,s=t.content.indexOf(r[0]),o={answer:i,process:ra(t,t.content.slice(0,s<0?void 0:s),{omitUsage:!!i})};return e.set(t,o),o}(nh,eo[p]),m=f.answer,g=[],x=0,v=0,b=!1;for(let e=s+1;e<=p;e++){let n=eo[e];if("custom"===n.role){if((0,n4.zZ)(n))continue;b||=!!(t2&&t2.entryId===el[e]),x+=1,g.push(d(e,{attachRef:!1,keyPrefix:"process"}));continue}if("assistant"!==n.role)continue;let i=e===p?f.process:n,s=e!==p||!m,o=(0,n4.TC)(i);if(0===o.length){let t=s?(0,sM.YQ)(n):[];t.length>0&&g.push((0,r.jsx)(sJ.yt,{notices:t},`process-notices-${ec[e]}`));continue}t??=l.get(e),v+=(0,n4._q)(o),x+=1,b||=!!(t2&&el[e]===t2.entryId&&(!t5||o.includes(t5))),g.push(d(e,{attachRef:!1,keyPrefix:"process",messageOverride:i,showTimestamp:!1,withNotices:s}))}if(0===x)u.push(...g);else if(g.length>0){let e=(0,n4.sE)(m),n=(0,sM.Uv)(eo.slice(s+1,m?p:p+1));u.push((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{nm.current[t]=e},children:(0,r.jsx)(sQ,{messageCount:x,toolCallCount:v,durationMs:h,cacheMisses:n,defaultExpanded:!e,reveal:b,t:K,children:g},e?"answered":"unanswered")},`process-group-${ec[a]}`))}if(m){let e=[];for(let t=s+1;t<=p;t++){let n=eo[t];if(n?.role==="assistant")for(let t of n.content??[])e.push(t)}let t=rt(e,np,nv);for(let e of rr(eo.slice(s+1,p+1),np))for(let n of nb.get(e.sessionId)??[])t.some(e=>e.filePath===n.filePath)||t.push(n);let n=function(e,t){let n=e.writtenFiles;return n&&n.length===t.length&&n.every((e,n)=>e.filePath===t[n].filePath)?n:(e.writtenFiles=t,t)}(f,t);u.push(d(p,{messageOverride:m,writtenFiles:n,turnDurationMs:0===g.length?h:void 0,recoverTruncation:c===eo.length&&!tI&&!(0,n4.D6)(m)}))}for(let e=p+1;e<c;e++)u.push(d(e));e=c}let{startIndex:p}=(t=Math.min(Math.max(tV,0),Math.max(e=u.length,0)),{startIndex:n=Math.max(0,e-t),hasMore:n>0}),h=p>0||eu;return(0,r.jsxs)(r.Fragment,{children:[h&&(0,r.jsx)("div",{ref:tG,className:"py-3 text-center text-xs text-text-muted",children:K("chat.loadEarlier")}),u.slice(p)]})})(),tI&&tT&&(0,r.jsx)(s1,{store:eh,onCommit:nC,toolResults:np,modelNames:ex,cwd:nv,onOpenFile:L,onOpenSubagent:P,onEnterSubagent:z}),ef&&!tT&&(e2||eI)&&(0,r.jsx)("div",{className:"break-words py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:function(e,t,n){if(n)return 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}(e2,K,eI)})}),em&&!eg&&(0,r.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:K("chat.runningCommand")})}),eg&&(0,r.jsx)(rd.Dx,{message:{role:"bashExecution",command:eg.command,output:"",excludeFromContext:eg.excludeFromContext},sessionId:a?.id??e6.current??void 0,onOpenSubagent:P,onEnterSubagent:z}),(0,r.jsx)("div",{ref:ny,"aria-hidden":"true"})]})})}),V||ee?null:(0,r.jsx)(i4,{messages:eo,getStreamingMessage:t$,scrollContainer:e3,messageRefs:nm,onRevealHistory:ng,turnsBefore:ep})]})]}),O&&tR&&(0,eJ.createPortal)((0,r.jsx)("div",{ref:tF,role:tA?"dialog":"toolbar","aria-label":K(tA?"chat.newQuoteChat":"chat.askSelection"),style:{position:"fixed",top:tR.top,left:tR.left,zIndex:260,display:"flex",flexWrap:"wrap",gap:3,width:tA?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:tA?12:3,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",boxShadow:"0 2px 10px rgba(0,0,0,0.12)"},children:tA?(0,r.jsxs)("fieldset",{disabled:tz,"aria-busy":tz,style:{width:"100%",minWidth:0,margin:0,padding:0,border:"none",display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,fontSize:12,fontWeight:600},children:K("chat.askInNewChat")}),(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button",title:K("i18n.close"),"aria-label":K("i18n.close"),disabled:tz,onClick:tH,style:{border:"none"},children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 6 12 12M18 6 6 18"})})})]}),(0,r.jsx)(iU,{ref:tB,compact:!0,onSend:tq,onAbort:tH,isStreaming:!1}),tO&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:tO})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:K("chat.askInCurrent"),"aria-label":K("chat.askInCurrent"),onPointerDown:e=>e.preventDefault(),onClick:t_,style:{width:"auto",height:35,flex:"0 0 auto",gap:5,padding:"0 10px",border:"none",fontSize:12,fontWeight:500},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{fontSize:15},children:"@"}),(0,r.jsx)("span",{children:K("chat.askInCurrent")})]}),W&&tR.sourceEntryId&&!em&&(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:K("chat.askInNewChat"),"aria-label":K("chat.askInNewChat"),onPointerDown:e=>e.preventDefault(),onClick:()=>{tP(!0),window.getSelection()?.removeAllRanges()},style:{width:"auto",height:35,flex:"0 0 auto",gap:5,padding:"0 10px",border:"none",fontSize:12,fontWeight:500},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M6 3v12M18 9a9 9 0 0 1-9 9"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"})]}),(0,r.jsx)("span",{children:K("chat.askInNewChat")})]})]})}),document.body),(0,r.jsxs)("div",{className:"relative shrink-0",children:[!nx&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"100%",left:0,right:36*!V,display:"flex",justifyContent:"center",paddingBottom:10,pointerEvents:"none",zIndex:20},children:(0,r.jsx)("button",{type:"button",className:`chat-scroll-to-bottom${e5&&!ee?" is-visible":""}`,title:K("chat.scrollToLatest"),"aria-label":K("chat.scrollToLatest"),onClick:()=>tN("smooth"),children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12l7 7 7-7"})})})}),nx&&(0,r.jsx)("div",{className:"new-session-hero",style:{paddingLeft:16,paddingRight:V?16:52},children:(0,r.jsxs)("div",{className:"new-session-hero-inner",style:{maxWidth:"var(--chat-content-max-width, 820px)"},children:[(0,r.jsxs)("div",{className:"new-session-brand",children:[(0,r.jsx)(nK.default,{src:"/icons/apple-touch-icon.png",width:40,height:40,alt:"",priority:!0,className:"new-session-logo"}),(0,r.jsxs)("div",{className:"new-session-brand-text",children:[(0,r.jsx)("span",{className:"new-session-brand-name",children:"Pi Web"}),(0,r.jsxs)("span",{className:"new-session-meta",children:[(0,r.jsxs)("span",{children:["web v","0.13.0"]}),(0,r.jsx)(sX,{label:e=>K("appUpdate.releaseNotes",{version:e})}),(0,r.jsx)("span",{"aria-hidden":"true",children:"\xb7"}),(0,r.jsxs)("span",{className:"new-session-meta-pi",children:["pi v","1.2.0"]})]})]})]}),m]})}),nI,(0,r.jsx)(i9,{statuses:eq,widgets:eK,onCommand:te,commandsDisabled:tM})]}),nx&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}let s1=(0,i.memo)(function(e){let{store:t,onCommit:n,toolResults:s,modelNames:o,cwd:a,onOpenFile:l,onOpenSubagent:c,onEnterSubagent:d}=e,u=sq(t,sZ);return((0,i.useLayoutEffect)(n,[u,n]),u)?(0,r.jsx)(rd.Dx,{message:u,toolResults:s,isStreaming:!0,modelNames:o,cwd:a,onOpenFile:l,onOpenSubagent:c,onEnterSubagent:d}):null});function s2(e){let{notices:t,floating:n=!1,onPauseChange:i}=e;return 0===t.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",marginBottom:10*!n},children:t.map((e,s)=>{var o;let a,l,c,d="error"===e.type?"#ef4444":"warning"===e.type?"#d97706":"success"===e.type?"#10b981":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",onMouseEnter:()=>i?.(e.id),onMouseLeave:e=>{e.currentTarget.contains(document.activeElement)||i?.(null)},onFocus:()=>i?.(e.id),onBlur:e=>{e.currentTarget.matches(":hover")||i?.(null)},style:{display:"flex",alignItems:"flex-start",gap:10,minHeight:60,height:"auto",maxHeight:500,pointerEvents:"auto",marginBottom:6*(s!==t.length-1),overflow:"hidden",borderRadius:14,border:"1px solid color-mix(in srgb, var(--border) 70%, transparent)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:n?"0 1px 2px rgba(15,23,42,0.05), 0 10px 28px -14px rgba(15,23,42,0.24)":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",fontSize:14,lineHeight:1.5,transformOrigin:"top right",animation:e.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out backwards",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:d,flexShrink:0,marginTop:25.5}}),(0,r.jsx)("span",{tabIndex:0,style:{padding:"18.5px 0",minWidth:0,maxWidth:"100%",maxHeight:498,overflowY:"auto",scrollbarWidth:"thin",whiteSpace:"pre-line",wordBreak:"break-word"},children:(o=e.message,a=[],l=(e,t)=>{if(!t)return;let n=a[a.length-1];n?.kind===e?n.text+=t:a.push({kind:e,text:t})},c=!1,o.split("\n").forEach((e,t)=>{let n=n0.test(e);t>0&&l(n&&c?"art":"text","\n"),l(n?"art":"text",e),c=n}),a).map((e,t)=>"art"===e.kind?(0,r.jsx)("span",{style:{display:"inline-block",verticalAlign:"top",maxWidth:"100%",overflowX:"auto",whiteSpace:"pre",fontFamily:"Menlo, Consolas, 'DejaVu Sans Mono', monospace",lineHeight:1,color:"var(--text)"},children:e.text},t):e.text)})]},e.id)})})}function s4(e){let{count:t}=e,{t:n}=(0,eO.s)();return t<=0?null:(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",whiteSpace:"nowrap",flexShrink:0},children:n("chat.extensionMoreWaiting",{count:t})})}function s8(e){let{expanded:t}=e;return(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:1.6,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:t?(0,r.jsx)("path",{d:"M3.5 1v2.5H1M6.5 1v2.5H9M6.5 9v-2.5H9M3.5 9v-2.5H1"}):(0,r.jsx)("path",{d:"M1 3.5V1h2.5M6.5 1H9v2.5M9 6.5V9H6.5M3.5 9H1V6.5"})})}function s5(e){let{request:t,waitingCount:n,onRespond:s}=e,{t:o}=(0,eO.s)(),[a,l]=(0,i.useState)("editor"===t.method?t.prefill??"":""),[c,d]=(0,i.useState)(!1),u=(0,i.useRef)(null),p=(0,i.useRef)(null),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(!1),x=(0,i.useCallback)(()=>g(e=>!e),[]),[v,b]=(0,i.useState)(()=>Date.now()),y=(0,i.useCallback)(e=>e?.focus(),[]),j=function(e){if("select"===e.method&&e.options.length>0)return e.options[0];if("confirm"===e.method){let t=e.message.split("\n").find(e=>e.trim());return t?.trim()}}(t),k=void 0===t.expiresAt?null:Math.max(0,Math.ceil((t.expiresAt-v)/1e3));(0,i.useLayoutEffect)(()=>{if(c)return;let e=u.current,t=p.current;if(!e||!t)return;let n=!1,r=()=>{if(n)return;let r=t.querySelectorAll("pre, .markdown-table-wrap");if(0===r.length)return;let i=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,Array.from(r,e=>e.scrollWidth-e.clientWidth));null!==i&&f(e=>null!==e&&e>=i?e:i)};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()}},[c]),(0,i.useEffect)(()=>{if(void 0===t.expiresAt)return;let e=setInterval(()=>b(Date.now()),1e3);return()=>clearInterval(e)},[t.expiresAt]);let w=null!==k&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:o("chat.extensionExpiresIn",{seconds:k})}),S=()=>{"confirm"===t.method?s(t,{confirmed:!0}):s(t,{value:a})};return(0,r.jsx)("div",{onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),e.stopPropagation(),s(t,{cancelled:!0}))},style:{position:"absolute",inset:0,zIndex:90,display:"flex",alignItems:c?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:c?(0,r.jsxs)("button",{type:"button",onClick:()=>d(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(560px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:o("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:t.title}),j&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:j}),(0,r.jsx)(s4,{count:n}),w,(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:o("chat.extensionExpand")})]}):(0,r.jsxs)("div",{ref:u,role:"dialog","aria-label":t.title,style:{pointerEvents:"auto",width:m?"100%":`min(${h??560}px, 100%)`,maxHeight:m?"100%":"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{flexShrink:1,minHeight:0,display:"flex",alignItems:"flex-start",gap:8,padding:"12px 14px",borderBottom:"1px solid var(--border)",maxHeight:"50vh",overflowY:"auto"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:650,lineHeight:1.45,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:t.title}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:8,marginTop:3,color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{children:o("chat.extensionRequest")}),(0,r.jsx)(s4,{count:n}),w]})]}),(0,r.jsx)("button",{type:"button",onClick:x,title:o(m?"chat.extensionRestoreSize":"chat.extensionMaximize"),"aria-label":o(m?"chat.extensionRestoreSize":"chat.extensionMaximize"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)(s8,{expanded:m})}),(0,r.jsx)("button",{type:"button",onClick:()=>d(!0),"aria-expanded":!0,title:o("chat.extensionCollapse"),"aria-label":o("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})})]}),(0,r.jsxs)("div",{ref:p,style:{padding:14,flex:"1 1 auto",minHeight:0,overflowY:"auto"},children:["confirm"===t.method&&(0,r.jsx)(ru.m,{children:t.message}),"select"===t.method&&(0,r.jsx)("div",{onKeyDown:e=>{if(!["ArrowDown","ArrowRight","ArrowUp","ArrowLeft","Home","End"].includes(e.key))return;let t=Array.from(e.currentTarget.querySelectorAll("[data-extension-option]")),n=t.indexOf(e.target);if(n<0)return;e.preventDefault();let r="Home"===e.key?0:"End"===e.key?t.length-1:(n+("ArrowDown"===e.key||"ArrowRight"===e.key?1:-1)+t.length)%t.length;t[r].focus({preventScroll:!0}),t[r].scrollIntoView({block:"nearest"})},style:{display:"grid",gap:8},children:t.options.map((e,n)=>(0,r.jsx)("div",{role:"button",tabIndex:0,"data-extension-option":!0,"aria-label":e,ref:0===n?y:void 0,onClick:()=>s(t,{value:e}),onKeyDown:n=>{("Enter"===n.key||" "===n.key)&&(n.preventDefault(),s(t,{value:e}))},style:{width:"100%",padding:"9px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:13,overflowWrap:"anywhere",scrollMargin:14},children:(0,r.jsx)("div",{inert:!0,children:(0,r.jsx)(ru.m,{children:e})})},e))}),"input"===t.method&&(0,r.jsx)("input",{autoFocus:!0,value:a,placeholder:t.placeholder,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||S()},style:{width:"100%",padding:"9px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",fontSize:13}}),"editor"===t.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:a,onChange:e=>l(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&!e.nativeEvent.isComposing&&S()},style:{width:"100%",minHeight:220,padding:10,borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:13,lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 14px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("button",{autoFocus:"confirm"===t.method||"select"===t.method&&0===t.options.length,onClick:()=>s(t,{cancelled:!0}),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"},children:o("chat.cancel")}),"confirm"===t.method?(0,r.jsx)("button",{onClick:S,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:o("chat.confirm")}):"select"!==t.method?(0,r.jsx)("button",{onClick:S,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:o("chat.submit")}):null]})]})})}function s6(e){let{request:t,waitingCount:n,onInput:s}=e,{t:o}=(0,eO.s)(),a=(0,i.useRef)(null),l=(0,i.useRef)(!1),[c,d]=(0,i.useState)(!1),u=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(nJ,""),i=nG(e).trimEnd();if(t.test(i))continue;let s=e,o=nQ(s);("│"===o||"┃"===o)&&" "===nQ(s=nX(s,0))&&(s=nX(s,0));let a=function(e){let t=nY(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(s),l=a>=0?nY(s)[a]?.char:void 0;("│"===l||"┃"===l)&&(s=nX(s,a)),n.push(function(e){let t=e;for(;;){let e=nY(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&&""===nG(n[0]).trim();)n.shift();for(;n.length>0&&""===nG(n[n.length-1]).trim();)n.pop();return n.length?n:e}(t.lines),p=u.find(e=>e.trim())?.trim();return(0,i.useEffect)(()=>{c||a.current?.focus()},[c]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:c?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:c?(0,r.jsxs)("button",{type:"button",onClick:()=>d(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(920px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:o("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:o("chat.extensionPanel")}),p&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:p}),(0,r.jsx)(s4,{count:n}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:o("chat.extensionExpand")})]}):(0,r.jsxs)("div",{role:"dialog",onClick:e=>{e.target.closest("button")||a.current?.focus()},style:{pointerEvents:"auto",position:"relative",width:"max-content",minWidth:"min(920px, 100%)",maxWidth:"100%",maxHeight:"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:a,"aria-label":o("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:e=>{if(l.current||e.nativeEvent.isComposing)return;let n=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=n2[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":" ":n1[e.key]??null}(e);n&&(e.preventDefault(),e.stopPropagation(),s(t,n))},onInput:e=>{if(l.current||e.nativeEvent.isComposing)return;let n=e.currentTarget.value;e.currentTarget.value="",n&&s(t,n)},onCompositionStart:()=>{l.current=!0},onCompositionEnd:e=>{l.current=!1;let n=e.currentTarget;queueMicrotask(()=>{let e=n.value;n.value="",e&&s(t,e)})},onPaste:e=>{e.preventDefault();let n=e.clipboardData.getData("text");n&&s(t,`\x1b[200~${n}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:o("chat.extensionPanel")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)(s4,{count:n}),(0,r.jsx)("button",{type:"button",onClick:()=>d(!0),"aria-expanded":!0,title:o("chat.extensionCollapse"),"aria-label":o("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),(0,r.jsx)("button",{onClick:()=>s(t,"\x03"),style:{padding:"5px 9px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:o("chat.close")})]})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,minHeight:0,overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(0,r.jsx)(i5,{text:u.join("\n")})})]})})}let s3=null,s9="";function s7(e){let{context:t,mobile:n,initialFocus:s,onInitialFocusDone:o,onPick:a,onUseDefaultDirectory:l,onOpenFolder:c,onRefreshWorktrees:d,onCreateWorktree:u}=e,{t:p}=(0,eO.s)(),[h,f]=(0,i.useState)(()=>s9),m=(0,i.useRef)(null),g=(0,i.useRef)(s),x=(0,i.useRef)(o);return x.current=o,(0,i.useEffect)(()=>{if(s9)return;let e=!1;return(s3??=fetch("/api/home").then(e=>e.json()).then(e=>s9=e.home??"").catch(()=>(s3=null,""))).then(t=>{!e&&t&&f(t)}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=g.current;if(!e)return;g.current=null,x.current();let t=m.current;eN(document,("worktree"===e?t?.button("worktree"):null)??t?.button("project")??null)},[]),(0,r.jsx)("div",{className:"new-session-context",children:(0,r.jsx)(nN,{handleRef:m,layout:"inline",context:t,mobile:n,label:p("workspace.newSessionContext"),homeDir:h,newWorktreeTitle:p("sidebar.newWorktreeForSession"),onPick:a,onUseDefaultDirectory:l,onOpenFolder:c,onRefreshWorktrees:d,onCreateWorktree:u})})}var oe=n(68832),ot=n(56987),on=n(37029),or=n(67823),oi=n(41366),os=n(76616);function oo(e){return e&&"number"==typeof e.size&&"string"==typeof e.mtime?`${e.size}:${e.mtime}`:null}function oa(e,t){return null===e||null===t||e!==t}var ol=n(70611);let oc=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function od(e){let t=function(e){let t=oc.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,ol.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 ou(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)}var op=n(16932);let oh=[",",";"," ","|"];function of(e){let t=/\.(csv|tsv)$/i.exec(e);return t?"tsv"===t[1].toLowerCase()?" ":",":null}function om(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.complete??!0,i=n.maxRecords??1/0,s=[],o=[],a=e.length,l=t.charCodeAt(0),c=+(65279===e.charCodeAt(0)),d=1,u=[],p=1,h=()=>{(1!==u.length||""!==u[0])&&(s.push(u),o.push(p)),u=[]};for(;c<a&&s.length<i;){let t="",n=!1;if(34===e.charCodeAt(c)){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===l||10===t)break;i+=1}let s=i<a?e.charCodeAt(i):-1,o=s!==l&&i>c&&13===e.charCodeAt(i-1)?i-1:i;t+=e.slice(c,o),u.push(t),c=i,s===l?(c+=1)===a&&(u.push(""),r&&h()):10===s?(c+=1,d+=1,h(),p=d):r&&h()}return{records:s,lines:o}}function og(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 ox={display:"flex",height:26,boxSizing:"border-box",borderBottom:"1px solid var(--border)"},ov={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"},ob={boxSizing:"border-box",flexShrink:0,padding:"0 10px",lineHeight:"25px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",borderRight:"1px solid var(--border)"};function oy(e){let{content:t,filePath:n,complete:s,scrollRef:o}=e,a=(0,i.useMemo)(()=>(function(e,t){let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2],r=of(t)??",",i=","===r?function(e){let t=e.slice(0,65536),n=t.length===e.length,r=",",i=0;for(let e of oh){let{records:s}=om(t,e,{complete:n,maxRecords:20}),o=s[0]?.length??0;if(o<2)continue;let a=1e3*s.filter(e=>e.length===o).length+Math.min(o,999);a>i&&(r=e,i=a)}return r}(e):r,{records:s,lines:o}=om(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 l=s[0];return{columns:l.length===a?l:[...l,...Array.from({length:a-l.length},()=>"")],headerLine:o[0],rows:s.slice(1),rowLines:o.slice(1)}})(t,n,s),[s,t,n]),l=(0,i.useMemo)(()=>{var e,t;let n;return e=a.columns,n=Math.max(1,Math.ceil((t=a.rows).length/500)),e.map((e,r)=>{let i=og(e);for(let e=0;e<t.length;e+=n){let n=t[e][r];if(n){let e=og(n);e>i&&(i=e)}}return Math.min(Math.max(Math.ceil(7.4*i+22),64),420)})},[a]),c=(0,i.useMemo)(()=>l.reduce((e,t)=>e+t,56),[l]),[d,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(0);if((0,i.useEffect)(()=>{let e=o.current;if(!e)return;let t=null,n=()=>{u(e.scrollTop),h(e.clientHeight)},r=()=>{null===t&&(t=requestAnimationFrame(()=>{t=null,n()}))};n(),e.addEventListener("scroll",r,{passive:!0});let i="u"<typeof ResizeObserver?null:new ResizeObserver(n);return i?.observe(e),()=>{e.removeEventListener("scroll",r),i?.disconnect(),null!==t&&cancelAnimationFrame(t)}},[o]),0===a.columns.length)return null;let{start:f,end:m}=function(e,t,n){if(e<=0)return{start:0,end:0};let r=Number.isFinite(t)?Math.max(0,t):0,i=Number.isFinite(n)&&n>0?n:800,s=Math.max(0,Math.floor(r/26)-20),o=Math.min(e,Math.ceil((r+i)/26)+20);return{start:Math.min(s,o),end:o}}(a.rows.length,d-26,p),g=[];for(let e=f;e<m;e+=1){let t=a.rows[e];g.push((0,r.jsxs)("div",{role:"row","aria-rowindex":e+2,style:{...ox,position:"absolute",top:26*e,left:0,width:c},children:[(0,r.jsx)("div",{role:"rowheader",style:ov,children:a.rowLines[e]}),l.map((e,n)=>{let i=t[n]??"";return(0,r.jsx)("div",{role:"cell",style:{...ob,width:e},title:i||void 0,children:i},n)})]},e))}return(0,r.jsxs)("div",{role:"table","aria-rowcount":a.rows.length+1,"aria-colcount":a.columns.length,style:{width:c,minWidth:"100%",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:12,color:"var(--text-muted)",background:"var(--bg)"},children:[(0,r.jsxs)("div",{role:"row","aria-rowindex":1,style:{...ox,position:"sticky",top:0,zIndex:2,width:c,background:"var(--bg-panel)",color:"var(--text)",fontWeight:600},children:[(0,r.jsx)("div",{role:"rowheader",style:ov,children:a.headerLine}),a.columns.map((e,t)=>(0,r.jsx)("div",{role:"columnheader",style:{...ob,width:l[t]},title:e||void 0,children:e},t))]}),(0,r.jsx)("div",{style:{position:"relative",height:26*a.rows.length},children:g})]})}let oj=["tags","categories","keywords","tag","category"];function ok(e){var t;let{data:n}=e;if(!n)return null;let i=Object.entries(n);if(0===i.length)return null;let s="string"==typeof(t=n.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,o=oj.find(e=>Array.isArray(n[e])),a=o?n[o].map(ou).filter(Boolean):[],l=i.filter(e=>{let[t]=e;return t!==o&&("title"!==t||!s)});return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[s&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:s}),a.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:a.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),l.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:l.map(e=>{let[t,n]=e;return(0,r.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,r.jsx)("dt",{children:t}),(0,r.jsx)("dd",{children:function(e){let t=ou(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,r.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(n)})]},t)})})]})}var ow=n(53792);let oS={source:"Source",preview:"Preview",diff:"Diff"},oC={fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:13,lineHeight:1.6},oN={...on.xJ,'pre[class*="language-"]':{...on.xJ['pre[class*="language-"]']}};delete oN['pre[class*="language-"]'].background;let oE={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"},oI={...oE,position:"sticky",left:0,zIndex:1};function oT(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function o$(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function oM(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=o$(n.startContainer),i=o$(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let s=Number(r.dataset.lineNumber),o=Number(i.dataset.lineNumber);if(!Number.isInteger(s)||!Number.isInteger(o))return null;if(s<o){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]")&&(o=Number((i=e).dataset.lineNumber))}}}return s>o?null:{startLine:s,endLine:o}}function oR(e){let{rows:t,stylesheet:n,useInlineStyles:i,wrapLines:s}=e;return t.map((e,t)=>{let o=e.children??[],a=o[0]?.properties?.className,l=Array.isArray(a)&&a.includes("react-syntax-highlighter-line-number"),c=l?o[0]:null,d=l?o.slice(1):o;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":t+1,style:{display:"flex",minWidth:"100%"},children:[c&&(0,ot.Ay)({node:c,stylesheet:n,useInlineStyles:i,key:`source-line-number-${t}`}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:s?"anywhere":"normal",whiteSpace:s?"pre-wrap":"pre"},children:d.map((e,r)=>(0,ot.Ay)({node:e,stylesheet:n,useInlineStyles:i,key:`source-token-${t}-${r}`}))})]},`source-line-${t}`)})}function oL(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=(0,e9.HG)(e),s=new URLSearchParams({type:t});for(let[e,t]of(n&&s.set("sessionId",n),Object.entries(r)))void 0!==t&&s.set(e,String(t));return`/api/files/${i}?${s.toString()}`}function oA(e){let{filePath:t,sourceSessionId:n}=e,{t:i}=(0,eO.s)();return(0,r.jsx)("a",{href:oL(t,"download",n),download:(0,e9.WP)(t),title:i("i18n.downloadFile"),"aria-label":i("i18n.downloadFile"),className:"file-viewer-icon-button",children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})}function oP(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function oz(e){let t,{patch:n}=e,{t:i}=(0,eO.s)(),s=(t=(0,ow.yg)(n))?t.flatMap(ow.jB):[],o=e=>"added"===e.type||"removed"===e.type;if(!s.some(o))return(0,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:i("i18n.noChanges")});let a=new Set(s.flatMap((e,t)=>o(e)?[t]:[])),l=new Set;for(let e of a)for(let t=Math.max(0,e-3);t<=Math.min(s.length-1,e+3);t++)l.add(t);let c=l.size<=1e3?oI:oE,d=e=>"gap"!==s[e].type&&l.has(e),u=[],p=0;for(;p<s.length;)if(d(p)){let e=[];for(;p<s.length&&d(p);){let t=s[p];"gap"!==t.type&&e.push(t),p++}u.push({hidden:!1,lines:e})}else{let e=0;for(;p<s.length&&!d(p);){let t=s[p],n="gap"===t.type?t.count:1;e=null===e||null===n?null:e+n,p++}u.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...oC},children:u.map((e,t)=>{if(e.hidden)return(0,r.jsx)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:null===e.count?"⋯":`⋯ ${(0,ow.WM)(e.count,i)}`},t);let n=e.lines.map((e,t)=>{let n="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",s="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:n,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,r.jsx)("span",{style:c,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:s,userSelect:"none",flexShrink:0,fontWeight:600},children:i}),(0,r.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},t)});return(0,r.jsx)("div",{children:n},t)})})}function oW(e){let{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:o=!0}=e,{t:a}=(0,eO.s)(),[l,c]=(0,i.useState)(!1),[d,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(0),y=(0,i.useRef)(null),j=(0,e9.WP)(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),m(null),x(null),c(!1),y.current=null},[t,s]),(0,i.useEffect)(()=>{if(c(!1),v.current&&(v.current.close(),v.current=null),!o)return;let e=!0,n=new EventSource(oL(t,"watch",s));v.current=n,n.addEventListener("connected",()=>{let n;c(!0),n=++b.current,fetch(oL(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==b.current)return;if(t.error)return void x(t.error);"number"==typeof t.size&&h(t.size),x(null);let r=oo(t);oa(y.current,r)&&(y.current=r,m(null),u(e=>e+1))}).catch(t=>{e&&n===b.current&&x(String(t))})}),n.addEventListener("change",e=>{b.current+=1,y.current=null;try{let t=JSON.parse(e.data);y.current=oo(t),"number"==typeof t.size&&h(t.size)}catch{}m(null),x(null),u(e=>e+1)});let r=()=>{c(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,s,o]);let k=oL(t,"read",s,d?{v:d}:void 0),w=null!=p?oP(p):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:t,children:(0,e9.qP)(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:j||"image"}),f&&(0,r.jsxs)("span",{children:[f.w," \xd7 ",f.h]}),w&&(0,r.jsx)("span",{children:w}),(0,r.jsxs)("span",{title:a(l?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:l?"#4ade80":"var(--text-dim)"},children:[(0,r.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,r.jsx)(oA,{filePath:t,sourceSessionId:s})]}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:g?(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13},children:g}):(0,r.jsx)("img",{src:k,alt:t,onLoad:e=>{let t=e.currentTarget;m({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>x("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function oO(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 oD(e){let{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:o=!0}=e,{t:a}=(0,eO.s)(),[l,c]=(0,i.useState)(!1),[d,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(0),y=(0,i.useRef)(null),j=(0,e9.WP)(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),m(null),x(null),c(!1),y.current=null},[t,s]),(0,i.useEffect)(()=>{if(c(!1),v.current&&(v.current.close(),v.current=null),!o)return;let e=!0,n=new EventSource(oL(t,"watch",s));v.current=n,n.addEventListener("connected",()=>{let n;c(!0),n=++b.current,fetch(oL(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==b.current)return;if(t.error)return void x(t.error);"number"==typeof t.size&&h(t.size),x(null);let r=oo(t);oa(y.current,r)&&(y.current=r,m(null),u(e=>e+1))}).catch(t=>{e&&n===b.current&&x(String(t))})}),n.addEventListener("change",e=>{b.current+=1,y.current=null;try{let t=JSON.parse(e.data);y.current=oo(t),"number"==typeof t.size&&h(t.size)}catch{}m(null),x(null),u(e=>e+1)});let r=()=>{c(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,s,o]);let k=oL(t,"read",s,d?{v:d}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:t,children:(0,e9.qP)(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:j||"audio"}),null!=f&&(0,r.jsx)("span",{children:oO(f)}),null!=p&&(0,r.jsx)("span",{children:oP(p)}),(0,r.jsxs)("span",{title:a(l?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:l?"#4ade80":"var(--text-dim)"},children:[(0,r.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,r.jsx)(oA,{filePath:t,sourceSessionId:s})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,r.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[g&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:g}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:k,onLoadedMetadata:e=>m(e.currentTarget.duration),onError:()=>x("Failed to load audio"),style:{width:"100%"}},k)]})})]})}function oF(e){let{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:o=!0}=e,{t:a}=(0,eO.s)(),[l,c]=(0,i.useState)(!1),[d,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(0),y=(0,i.useRef)(null),j=(0,e9.WP)(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),m(null),x(null),c(!1),y.current=null},[t,s]),(0,i.useEffect)(()=>{if(c(!1),v.current&&(v.current.close(),v.current=null),!o)return;let e=!0,n=new EventSource(oL(t,"watch",s));v.current=n,n.addEventListener("connected",()=>{let n;c(!0),n=++b.current,fetch(oL(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==b.current)return;if(t.error)return void x(t.error);"number"==typeof t.size&&h(t.size),x(null);let r=oo(t);oa(y.current,r)&&(y.current=r,m(null),u(e=>e+1))}).catch(t=>{e&&n===b.current&&x(String(t))})}),n.addEventListener("change",e=>{b.current+=1,y.current=null;try{let t=JSON.parse(e.data);y.current=oo(t),"number"==typeof t.size&&h(t.size)}catch{}m(null),x(null),u(e=>e+1)});let r=()=>{c(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,s,o]);let k=oL(t,"read",s,d?{v:d}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:t,children:(0,e9.qP)(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:j||"video"}),null!=f&&(0,r.jsx)("span",{children:oO(f)}),null!=p&&(0,r.jsx)("span",{children:oP(p)}),(0,r.jsxs)("span",{title:a(l?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:l?"#4ade80":"var(--text-dim)"},children:[(0,r.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,r.jsx)(oA,{filePath:t,sourceSessionId:s})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)",minHeight:0},children:(0,r.jsxs)("div",{style:{width:"min(960px, 100%)",height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:0},children:[g&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:g}),(0,r.jsx)("video",{controls:!0,playsInline:!0,preload:"metadata",src:k,onLoadedMetadata:e=>m(e.currentTarget.duration),onError:()=>x("Failed to load video"),style:{maxWidth:"100%",maxHeight:"100%"}},k)]})})]})}function oB(e){let{filePath:t,cwd:n,sourceSessionId:s,initialPage:o,watchEnabled:a=!0}=e,{t:l}=(0,eO.s)(),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(0),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(0),b=(0,i.useRef)(null),y=(0,os.GO)(t),j="pdf"===y,k=j&&o&&o>0?`#page=${o}`:"",w=j?`${oL(t,"read",s,u?{v:u}:void 0)}${k}`:oL(t,"preview",s,u?{v:u}:void 0);return(0,i.useEffect)(()=>{p(0),f(null),g(null),d(!1),b.current=null;let e=!0,n=++v.current;return fetch(oL(t,"meta",s)).then(e=>e.json()).then(t=>{e&&n===v.current&&(t.error&&g(t.error),"number"==typeof t.size&&(f(t.size),!j&&t.size>os.jL&&g("DOCX too large for preview (>10MB)")))}).catch(t=>{e&&n===v.current&&g(String(t))}),()=>{e=!1}},[t,j,s]),(0,i.useEffect)(()=>{if(d(!1),x.current&&(x.current.close(),x.current=null),!a)return;let e=!0,n=new EventSource(oL(t,"watch",s));x.current=n,n.addEventListener("connected",()=>{let n;d(!0),n=++v.current,fetch(oL(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==v.current)return;if(t.error)return void g(t.error);if("number"==typeof t.size&&(f(t.size),!j&&t.size>os.jL))return void g("DOCX too large for preview (>10MB)");g(null);let r=oo(t);oa(b.current,r)&&(b.current=r,p(e=>e+1))}).catch(t=>{e&&n===v.current&&g(String(t))})}),n.addEventListener("change",e=>{v.current+=1,b.current=null;try{let t=JSON.parse(e.data);if(b.current=oo(t),"number"==typeof t.size&&(f(t.size),!j&&t.size>os.jL))return void g("DOCX too large for preview (>10MB)")}catch{}g(null),p(e=>e+1)});let r=()=>{d(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),x.current===n&&(x.current=null)}},[t,j,s,a]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:t,children:(0,e9.qP)(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===y?"docx preview":"pdf"}),null!=h&&(0,r.jsx)("span",{children:oP(h)}),(0,r.jsx)(oA,{filePath:t,sourceSessionId:s}),(0,r.jsxs)("span",{title:l(c?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:c?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:c?"#4ade80":"var(--border)",display:"inline-block",boxShadow:c?"0 0 4px #4ade80":"none"}}),c?"live":"static"]})]}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:m?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:m}):(0,r.jsx)("iframe",{src:w,sandbox:j?void 0:"allow-same-origin",title:l("i18n.previewFile",{file:(0,e9.WP)(t)}),style:{width:"100%",height:"100%",border:"none",background:j?"var(--bg)":"#eef1f5"}},w)})]})}function oH(e){let{filePath:t,cwd:n,sourceSessionId:s,onOpenFile:o,onMentionLines:a,onAtMention:l,gitRefreshKey:c,initialDisplayMode:d,initialState:u,initialPage:p,onStateChange:h,watchEnabled:f=!0}=e,m=function(){let e=(0,i.useSyncExternalStore)(sC,sN,sE),[t,n]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{if(!e)return void n(!1);let t=setTimeout(()=>n(!0),3e4);return()=>clearTimeout(t)},[3e4,e]),e&&t}(),g=f&&!m;return(0,os.RW)(t)?(0,r.jsx)(oW,{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:g}):(0,os.EC)(t)?(0,r.jsx)(oD,{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:g}):(0,os.t9)(t)?(0,r.jsx)(oF,{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:g}):(0,os.lF)(t)?(0,r.jsx)(oB,{filePath:t,cwd:n,sourceSessionId:s,initialPage:p,watchEnabled:g}):(0,r.jsx)(oU,{filePath:t,cwd:n,sourceSessionId:s,onOpenFile:o,onMentionLines:a,onAtMention:l,gitRefreshKey:c,initialDisplayMode:d,initialState:u,onStateChange:h,watchEnabled:g})}function oU(e){let{filePath:t,cwd:n,sourceSessionId:s,onOpenFile:o,onMentionLines:a,onAtMention:l,gitRefreshKey:c,initialDisplayMode:d,initialState:u,onStateChange:p,watchEnabled:h=!0}=e,{isDark:f}=(0,or.D)(),{t:m}=(0,eO.s)(),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(null),[y,j]=(0,i.useState)(!1),[k,w]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!0),[N,E]=(0,i.useState)(!1),[I,T]=(0,i.useState)(null),$=u?.displayMode??d??"source",M=u?.wrapLines??!1,R=u?.scrollTop??0,L=u?.scrollLeft??0,[A,P]=(0,i.useState)($),[z,W]=(0,i.useState)(M),[O,D]=(0,i.useState)(!1),F=(0,i.useRef)(null),B=(0,i.useRef)(0),H=(0,i.useRef)(null),U=(0,i.useRef)(0),_=(0,i.useRef)(null),q=(0,i.useRef)(!1),K=(0,i.useRef)(void 0===u&&void 0===d),V=(0,i.useRef)(!0),Z=(0,i.useRef)({displayMode:$,wrapLines:M,scrollTop:R,scrollLeft:L}),J=(0,i.useRef)(p),[G,Y]=(0,i.useState)(null),[X,Q]=(0,i.useState)(null);J.current=p;let ee=(0,i.useCallback)(e=>{Z.current.displayMode=e,P(e)},[]),et=(0,i.useCallback)(()=>{W(e=>{let t=!e;return Z.current.wrapLines=t,t})},[]);(0,i.useEffect)(()=>(Z.current={displayMode:$,wrapLines:M,scrollTop:R,scrollLeft:L},V.current=!0,q.current=!1,P($),W(M),()=>{J.current?.({...Z.current})}),[t,s,$,M,R,L]);let en=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=++B.current;return fetch(oL(e,"read",s,{offset:t||void 0})).then(e=>e.json()).then(e=>n!==B.current?null:e.error?(T(e.error),null):(H.current=oo(e),T(null),x(n=>t&&n?{...e,content:n.content+e.content}:e),e)).catch(e=>(n!==B.current||T(String(e)),null))},[s]),er=(0,i.useCallback)(async e=>{let t=++U.current;if(j(!0),!n){b(null),j(!1),w(!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!==U.current)return;b(i.ok&&s.supported&&"string"==typeof s.patch?s:null)}catch{t===U.current&&b(null)}finally{t===U.current&&(j(!1),w(!0))}},[n]);(0,i.useEffect)(()=>{let e=!0;return C(!0),T(null),x(null),b(null),w(!1),D(!1),H.current=null,en(t).finally(()=>{e&&C(!1)}),()=>{e=!1}},[t,en,s]),(0,i.useEffect)(()=>{if(D(!1),F.current&&(F.current.close(),F.current=null),!h)return;let e=!0,n=()=>{en(t),er(t)},r=new EventSource(oL(t,"watch",s));F.current=r,r.addEventListener("connected",()=>{(D(!0),null===H.current)?n():fetch(oL(t,"meta",s)).then(e=>e.json()).then(r=>{e&&(oa(H.current,oo(r))?n():er(t))}).catch(()=>{e&&n()})}),r.addEventListener("change",n);let i=()=>{D(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{e=!1,r.close(),F.current===r&&(F.current=null)}},[t,en,er,s,h]),(0,i.useEffect)(()=>{er(t)},[er,t,c]);let ei=null!==of(t);(0,i.useEffect)(()=>{K.current&&g&&(ei||"markdown"===g.language&&!g.truncated||"html"===g.language&&(!g.truncated||g.size<=os.en))&&(K.current=!1,ee("preview"))},[g,ei,ee]);let es="preview"===A&&g?.language==="html"&&g.truncated&&g.size<=os.en;(0,i.useEffect)(()=>{if(!es)return void Q(null);let e=new AbortController;return fetch(oL(t,"download",s),{signal:e.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);Q({text:await e.text()})}).catch(t=>{e.signal.aborted||Q({error:String(t)})}),()=>e.abort()},[es,g,t,s]);let eo=v?.supported===!0&&"string"==typeof v.patch,ea=eo&&"deleted"===v.status;(0,i.useEffect)(()=>{k&&!eo&&"diff"===A&&ee("source")},[A,k,eo,ee]),(0,i.useEffect)(()=>{"diff"===$&&eo&&!q.current&&(q.current=!0,ee("diff"))},[$,eo,ee]);let el=(0,i.useMemo)(()=>g?.language==="markdown"?(0,iK.Ep)(g.content):"",[g]),ec=(0,i.useMemo)(()=>g?.language==="markdown"?od(g.content):null,[g]),ed=g?.content??"",eu=(0,i.useMemo)(()=>ed.split("\n"),[ed]),ep=g?.language??"text",eh=(0,oi.c)(!!g&&"text"!==ep),ef="html"===ep,em="markdown"===ep,eg=ei||(ef?!!g&&(!g.truncated||g.size<=os.en):em&&!g?.truncated),ex=ea?"diff":A,ev=!!g?.truncated&&!(ef&&"preview"===ex),eb=eu.length>1e3&&!("diff"===ex&&eo)&&!("preview"===ex&&eg),ey=(0,i.useMemo)(()=>(0,r.jsx)(oe.A,{className:z?"file-source-view is-wrapped":"file-source-view",language:"text"!==ep&&eh?ep:"plaintext",style:f?oN:on.vs,showLineNumbers:!0,lineNumberStyle:{...oI},customStyle:{margin:0,padding:0,border:0,backgroundColor:"var(--bg)",...oC,width:z?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",overflowWrap:z?"anywhere":"normal"}},renderer:e=>(0,r.jsx)(oR,{...e,wrapLines:z}),wrapLongLines:z,children:ed}),[f,ep,eh,ed,z]),ej=(0,i.useMemo)(()=>eb?eu.map((e,t)=>(0,r.jsxs)("span",{className:"file-source-line","data-line-number":t+1,style:{display:"flex",minWidth:"100%"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:oE,children:t+1}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:z?"anywhere":"normal",whiteSpace:z?"pre-wrap":"pre"},children:e})]},`source-line-${t}`)):null,[eu,eb,z]);(0,i.useEffect)(()=>{let e=()=>{let e=_.current;Y(t=>{let n=a&&"source"===A&&e?oM(e,window.getSelection()):null;return null===t&&null===n||t&&n&&t.startLine===n.startLine&&t.endLine===n.endLine?t:n})};if(e(),a&&"source"===A)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[g?.content,A,a]);let ek=(0,i.useCallback)(e=>{a&&e&&a((0,e9.qP)(t,n),e.startLine,e.endLine)},[n,t,a]);if((0,i.useEffect)(()=>{if(!a||"source"!==A)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=_.current,r=n?oM(n,window.getSelection()):null;r&&(e.preventDefault(),ek(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[A,ek,a]),(0,i.useEffect)(()=>{if(!V.current||S||I&&!ea||"diff"===$&&!k||"diff"===$&&eo&&"diff"!==A)return;let e=_.current;e&&(e.scrollTop=Z.current.scrollTop,e.scrollLeft=Z.current.scrollLeft,V.current=!1)},[g?.content,A,I,k,eo,ea,S,$]),S||"diff"===$&&y&&!g)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:m("i18n.loading")});if(I&&!ea)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:I});if(!g&&!ea)return null;let ew=(0,e9.gX)(t),eS=ea?["diff"]:["source",...eg?["preview"]:[],...eo?["diff"]:[]],eC=ea?m("files.deleted"):`${ep} \xb7 ${eu.length} lines \xb7 ${oP(g.size)}`;return(0,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",position:"relative"},children:[(0,r.jsxs)("div",{className:"file-viewer-toolbar",style:{display:"flex",alignItems:"center",gap:8,padding:"5px 12px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{className:"file-viewer-path",style:{fontFamily:"var(--font-mono)"},title:t,children:(0,e9.qP)(t,n)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:eC,children:eC}),!ea&&(0,r.jsx)("span",{title:O?m("i18n.liveSync"):m("i18n.notWatching"),"aria-label":O?m("i18n.liveSync"):m("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:O?"#4ade80":"var(--border)",boxShadow:O?"0 0 4px #4ade80":"none"}}),(0,r.jsxs)("div",{className:"file-viewer-controls",children:[eS.length>1&&(0,r.jsx)("div",{className:"file-viewer-mode-switch","aria-label":m("i18n.fileViewMode"),children:eS.map(e=>{let t=ex===e;return(0,r.jsx)("button",{type:"button",onClick:()=>ee(e),title:"diff"===e?m("i18n.compareHead"):void 0,"aria-pressed":t,className:"file-viewer-mode-button",style:{background:t?"var(--bg-selected)":"transparent",color:t?"var(--text)":"var(--text-muted)"},children:oS[e]},e)})}),(0,r.jsxs)("div",{className:"file-viewer-actions",children:[(l||a)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{G&&a?ek(G):l?.((0,e9.qP)(t,n),!1)},title:G&&a?`${m("i18n.mentionSelectedLines")} (L${G.startLine}${G.startLine!==G.endLine?`-L${G.endLine}`:""})`:m("files.insertPath"),"aria-label":m("files.mention"),disabled:!l&&!a,className:"file-viewer-icon-button",children:(0,r.jsx)(oT,{})}),"source"===ex&&(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("button",{type:"button",onClick:et,title:z?m("i18n.disableWrap"):m("i18n.enableWrap"),"aria-label":z?m("i18n.disableWrap"):m("i18n.enableWrap"),"aria-pressed":z,className:"file-viewer-icon-button",style:{background:z?"var(--bg-selected)":"transparent",color:z?"var(--text)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,r.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,r.jsx)("path",{d:"M3 18h7"})]})})})]}),!ea&&(0,r.jsx)(oA,{filePath:t,sourceSessionId:s})]})]}),ev&&g?.truncated&&(0,r.jsxs)("div",{className:"file-viewer-load-more",style:{display:"flex",alignItems:"center",justifyContent:"center",gap:10,padding:"5px 8px",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-dim)",fontSize:11},children:[(0,r.jsxs)("span",{children:[oP(g.nextOffset)," / ",oP(g.size)]}),(0,r.jsx)("button",{type:"button",className:"file-viewer-mode-button",disabled:N,onClick:()=>{E(!0),en(t,g.nextOffset).finally(()=>E(!1))},children:N?m("i18n.loading"):m("i18n.loadMore")})]}),(0,r.jsx)("div",{ref:_,className:"file-viewer-content",onScroll:e=>{Z.current.scrollTop=e.currentTarget.scrollTop,Z.current.scrollLeft=e.currentTarget.scrollLeft},style:{flex:1,overflow:"auto",background:"var(--bg)",paddingBottom:ev?48:void 0},children:"diff"===ex&&eo?(0,r.jsx)(oz,{patch:v.patch}):ef&&"preview"===ex&&g?.truncated&&!X?.text?(0,r.jsx)("div",{style:{padding:24,color:"var(--text-dim)",fontSize:12},children:X?.error??m("i18n.loading")}):ef&&"preview"===ex?(0,r.jsx)("iframe",{srcDoc:g?.truncated?X?.text:ed,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:m("i18n.htmlPreview")}):em&&"preview"===ex?(0,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[ec?.data&&(0,r.jsx)(ok,{data:ec.data}),(0,r.jsx)(i_.oz,{remarkPlugins:iK.iA,rehypePlugins:iK.LA,urlTransform:o?iK.t9:iK.SG,components:{code(e){let{className:t,children:n,...i}=e,s=t?.replace("language-","").toLowerCase()??"",o=String(n);return t?.includes("language-")||o.includes("\n")?"mermaid"===s?(0,r.jsx)(op.t,{code:o.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(op.NG,{code:o.replace(/\n$/,""),lang:s}):(0,r.jsx)("code",{className:t,...i,children:n})},pre(e){let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})},a(e){let{href:t,children:i,...s}=e;delete s.node;let a=o?(0,n8.Vc)(t,ew,n??ew):null;return a&&o?(0,r.jsx)("a",{href:t,...s,onClick:e=>{(0,n8.pz)(e)&&(e.preventDefault(),o(a,(0,n8.XJ)(t)??void 0))},children:i}):(0,iK.AA)(t)?(0,r.jsx)("a",{href:t,...s,target:"_blank",rel:"noopener noreferrer",children:i}):(0,r.jsx)("a",{href:t,...s,onClick:iK.xq,children:i})},img(e){let{src:t,alt:i,...o}=e;delete o.node;let a="string"==typeof t?(0,n8.Vc)(t,ew,n??ew):null,l=a?oL(a,"read",s):t;return(0,r.jsx)("img",{src:l,alt:i??"",loading:"lazy",...o})}},children:el})]}):ei&&"preview"===ex?(0,r.jsx)(oy,{content:ed,filePath:t,complete:!g?.truncated,scrollRef:_}):eb?(0,r.jsx)("div",{className:"file-source-view is-lightweight",style:{width:z?"100%":"max-content",minWidth:"100%",minHeight:"100%",background:"var(--bg)",...oC},children:ej}):ey})]})}function o_(e){let{tabs:t,activeTabId:n,onSelectTab:s,onCloseTab:o}=e,{t:a}=(0,eO.s)(),[l,c]=(0,i.useState)(null),d=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=d.current;if(!e)return;let t=t=>{t.ctrlKey||Math.abs(t.deltaY)<=Math.abs(t.deltaX)||e.scrollWidth<=e.clientWidth||(t.preventDefault(),e.scrollLeft+=t.deltaY*(1===t.deltaMode?16:2===t.deltaMode?e.clientWidth:1))};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[]),(0,i.useEffect)(()=>{let e=d.current,t=e?.querySelector('[role="tab"][aria-selected="true"]');if(!e||!t)return;let n=e.getBoundingClientRect(),{left:r,right:i}=t.getBoundingClientRect();r<n.left?e.scrollLeft-=n.left-r:i>n.right&&(e.scrollLeft+=i-n.right)},[n,t.length]),(0,r.jsx)("div",{ref:d,role:"tablist",className:"tabbar-scroll",style:{display:"flex",alignItems:"stretch",background:"var(--bg-panel)",overflowX:"auto",overflowY:"hidden",flexShrink:0,height:36},children:t.map(e=>{let i=e.id===n;return(0,r.jsxs)("div",{role:"tab","aria-label":"terminal"===e.kind?a("terminal.tabLabel",{name:e.label}):"agent"===e.kind?a("subagent.tabLabel",{name:e.label}):"git-graph"===e.kind?a("gitGraph.tabLabel",{name:e.label}):e.label,"aria-selected":i,tabIndex:i||!n&&t[0].id===e.id?0:-1,onKeyDown:n=>{if(n.target===n.currentTarget){if("Enter"===n.key||" "===n.key)n.preventDefault(),s(e.id);else if(["ArrowLeft","ArrowRight","Home","End"].includes(n.key)){n.preventDefault();let r=t.findIndex(t=>t.id===e.id),i="Home"===n.key?0:"End"===n.key?t.length-1:(r+("ArrowRight"===n.key?1:-1)+t.length)%t.length;s(t[i].id),n.currentTarget.parentElement?.children[i]?.focus()}}},onClick:()=>s(e.id),onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:t=>{1===t.button&&(t.preventDefault(),t.stopPropagation(),e.closing||o(e.id))},style:{display:"flex",alignItems:"center",gap:6,paddingLeft:12,paddingRight:6,borderRight:"1px solid var(--border)",background:i?"var(--bg)":"var(--bg-panel)",cursor:"pointer",fontSize:12,color:i?"var(--text)":"var(--text-muted)",whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,r.jsx)("span",{style:{flexShrink:0,opacity:i?1:.7,display:"flex",alignItems:"center"},children:"terminal"===e.kind?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]}):"agent"===e.kind?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]}):"git-graph"===e.kind?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"5",cy:"6",r:"2.5"}),(0,r.jsx)("circle",{cx:"5",cy:"18",r:"2.5"}),(0,r.jsx)("circle",{cx:"19",cy:"12",r:"2.5"}),(0,r.jsx)("path",{d:"M5 8.5v7"}),(0,r.jsx)("path",{d:"M7.5 6H12a7 7 0 0 1 7 7v.01"}),(0,r.jsx)("path",{d:"M7.5 18H12"})]}):(0,e3.I3)(e.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:i?500:400},title:e.filePath,children:e.label}),(0,r.jsx)("button",{disabled:e.closing,onClick:t=>{t.stopPropagation(),o(e.id)},onMouseEnter:()=>c(e.id),onMouseLeave:()=>c(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:l===e.id?"var(--bg-hover)":"transparent",border:"none",borderRadius:4,color:l===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:a("terminal"===e.kind?"terminal.close":"i18n.close"),"aria-label":`${a("terminal"===e.kind?"terminal.close":"i18n.close")} ${e.label}`,children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,r.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})})}function oq(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}var oK=n(42107);let oV=["general","models","skills","agents","plugins","mcp","channels","automations"],oZ="pi-web:settings-navigation",oJ=new Set(["skills","agents","plugins"]);function oG(e){return oJ.has(e)}function oY(){try{return window.localStorage}catch{return null}}function oX(e){let t=e.getItem(oZ);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 oQ(e,t){return"models"===e?e:t?JSON.stringify([e,t]):"mcp"===e||"channels"===e||"automations"===e?e:null}function o0(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:oY();if(t)try{let n=oX(t);n.section=e,t.setItem(oZ,JSON.stringify(n))}catch{}}function o1(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:oY();if(!n)return null;let r=oQ(e,t);if(!r)return null;try{let e=oX(n).selections?.[r];return"string"==typeof e&&e.length>0?e:null}catch{return null}}function o2(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:oY();if(!r||!t)return;let i=oQ(e,n);if(i)try{let e=oX(r);e.selections={...e.selections,[i]:t},r.setItem(oZ,JSON.stringify(e))}catch{}}var o4=n(5804);function o8(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}class o5 extends Error{constructor(e){super(`Context window of ${e} must be a positive number of tokens`),this.name="ContextWindowError",this.model=e}}function o6(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 o3=["input","output","cacheRead","cacheWrite"];function o9(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 o7(e){if(!ae(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 ae(e){return o3.some(t=>""!==e[t].trim())}function at(e,t,n){return{...e,compat:{...e.compat??{},[t]:n}}}function an(e){return new Map(Object.entries(e.providers??{}).map(e=>{let[t,n]=e;return[t,(n.models??[]).map(e=>e.id)]}))}function ar(e,t,n){if(n<=0)return;let r=e.get(t)??[];e.set(t,[...r,...Array.from({length:n},()=>null)])}function ai(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 as(e,t,n){let r=e.trim().toLowerCase();return!r||n.toLowerCase().includes(r)||t.toLowerCase().includes(r)}function ao(e){let{embedded:t,title:n,subtitle:i,closeLabel:s="Close",onClose:o,children:a,width:l=900,height:c="78vh"}=e,d=t?void 0:{"--config-panel-width":`${l}px`,"--config-panel-height":c};return(0,r.jsx)("div",{role:t?void 0:"dialog","aria-modal":t?void 0:"true","aria-label":n,className:`config-panel-root ${t?"is-embedded":"is-modal"}`,onClick:e=>{t||e.target!==e.currentTarget||o()},children:(0,r.jsxs)("div",{className:"config-panel-surface",style:d,children:[!t&&(0,r.jsxs)("div",{className:"config-panel-header",children:[(0,r.jsx)("strong",{className:"config-panel-title",children:n}),i&&(0,r.jsx)("code",{className:"config-panel-subtitle",title:i,children:i}),(0,r.jsx)("button",{type:"button",className:"config-close-button",onClick:o,title:s,"aria-label":s,children:"\xd7"})]}),a]})})}function aa(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-split-view",children:t})}function al(e){let{children:t}=e;return(0,r.jsx)("aside",{className:"config-sidebar",children:t})}function ac(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-sidebar-list",children:t})}function ad(e){let{children:t,aside:n}=e;return(0,r.jsxs)("div",{className:"config-sidebar-group-label",children:[(0,r.jsx)("span",{className:"config-sidebar-group-label-text",children:t}),n]})}function au(e){let{enabled:t,total:n,checked:i,label:s,disabled:o=!1,loading:a=!1,describedBy:l,onChange:c}=e;return(0,r.jsxs)("span",{className:"config-sidebar-group-switch",children:[(0,r.jsxs)("span",{className:"config-sidebar-group-count",children:[t,"/",n]}),(0,r.jsx)(az,{checked:i??(n>0&&t===n),disabled:o,loading:a,label:s,describedBy:l,onChange:c})]})}function ap(e){let{error:t,note:n}=e;return t||n?(0,r.jsxs)("div",{className:"config-sidebar-group-status",children:[n&&(0,r.jsx)("div",{role:"status",className:"config-sidebar-group-note",children:n}),t&&(0,r.jsx)("div",{role:"alert",className:"config-sidebar-group-error",children:t})]}):null}function ah(e){let{active:t=!1,className:n,children:i,...s}=e;return(0,r.jsx)("button",{type:"button",...s,"aria-current":t?"page":void 0,className:["config-sidebar-item",n].filter(Boolean).join(" "),children:i})}function af(e){let{className:t,...n}=e;return(0,r.jsx)("span",{...n,className:["config-sidebar-text",t].filter(Boolean).join(" ")})}function am(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-stack",t].filter(Boolean).join(" ")})}function ag(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header",t].filter(Boolean).join(" ")})}function ax(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header-info",t].filter(Boolean).join(" ")})}function av(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-actions",t].filter(Boolean).join(" ")})}function ab(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-title",children:t})}function ay(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-section-title",children:t})}function aj(e){let{label:t,children:n,style:i,ref:s}=e;return(0,r.jsxs)("div",{ref:s,className:"config-field",style:i,children:[(0,r.jsx)("span",{className:"config-field-label",children:t}),n]})}function ak(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-grid",children:t})}function aw(e){let{label:t,tone:n="muted",mono:i=!1,className:s,style:o,children:a}=e;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-detail-grid-label",children:t}),(0,r.jsx)("div",{className:["config-detail-grid-value","plain"===n?null:`is-${n}`,i?"is-mono":null,s].filter(Boolean).join(" "),style:o,children:a})]})}function aS(e){let{scope:t,children:n}=e;return(0,r.jsx)("span",{className:`config-scope-tag${"project"===t?" is-project":""}`,children:n})}function aC(e){let{value:t,options:n,label:s,disabledReason:o,size:a="default",onChange:l,children:c}=e,d=(0,i.useId)(),u=o&&n.some(e=>e.disabled)?o:null;return(0,r.jsxs)("div",{className:"config-scope-switch-field",children:[(0,r.jsxs)("div",{className:"config-scope-switch-row",children:[(0,r.jsx)("div",{role:"group","aria-label":s,className:`config-scope-switch${"small"===a?" is-small":""}`,children:n.map(e=>(0,r.jsx)("button",{type:"button","aria-pressed":e.value===t,"aria-describedby":e.disabled&&u?d:void 0,disabled:e.disabled,className:"config-scope-switch-option",onClick:()=>{e.disabled||l(e.value)},children:e.label},e.value))}),c]}),u&&(0,r.jsx)("span",{id:d,className:"config-scope-switch-reason",children:u})]})}function aN(e){let{value:t,options:n,label:s,path:o,disabledReason:a,onChange:l,children:c}=e;return(0,r.jsxs)("div",{className:"config-save-target",children:[(0,r.jsx)(aC,{value:t,options:n,label:s,disabledReason:a,size:"small",onChange:l,children:(0,r.jsx)("span",{className:"config-save-target-path",children:"string"==typeof o?o.split(/([\\/])/).map((e,t)=>"/"===e||"\\"===e?(0,r.jsxs)(i.Fragment,{children:[e,(0,r.jsx)("wbr",{})]},t):e):o})}),c]})}function aE(e){let{title:t,catalogs:n,target:i}=e;return(0,r.jsxs)("div",{className:"config-add-source-heading",children:[(0,r.jsxs)("div",{className:"config-add-source-title-row",children:[(0,r.jsx)(ab,{children:t}),(0,r.jsx)("span",{className:"config-add-source-catalogs",children:n.map(e=>(0,r.jsxs)("a",{href:e.href,target:"_blank",rel:"noopener noreferrer",className:"config-add-source-catalog",children:[e.icon,e.label]},e.href))})]}),i]})}function aI(e){let{title:t,catalogs:n,target:s,inputLabel:o,inputId:a,placeholder:l,value:c,canSubmit:d,normalizeValue:u,onValueChange:p,onSubmit:h,examplesLabel:f,examples:m,error:g,multiline:x=!1,children:v}=e,b=(0,i.useRef)(null),y=(0,i.useRef)(null);(0,i.useEffect)(()=>{x?window.matchMedia?.("(pointer: coarse)").matches||y.current?.focus():b.current?.focus()},[x]);let j=e=>{if(!u)return;let t=e.clipboardData.getData("text"),n=u(t);n!==t&&(e.preventDefault(),p(n))};return(0,r.jsxs)(am,{className:"is-fill",children:[(0,r.jsx)(aE,{title:t,catalogs:n,target:s}),(0,r.jsx)(aj,{label:o,children:x?(0,r.jsx)("textarea",{id:a,ref:y,value:c,"aria-label":o,className:"config-add-source-input is-multiline",placeholder:l,rows:5,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>p(e.target.value),onPaste:j,onBlur:e=>{u&&p(u(e.currentTarget.value))},onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&e.nativeEvent?.isComposing!==!0&&229!==e.keyCode&&(e.preventDefault(),d&&h())}}):(0,r.jsx)("input",{id:a,ref:b,value:c,"aria-label":o,className:"config-add-source-input",placeholder:l,onChange:e=>p(e.target.value),onPaste:j,onBlur:e=>{u&&p(u(e.currentTarget.value))},onKeyDown:e=>{"Enter"===e.key&&d&&h()}})}),v,m.length>0&&(0,r.jsxs)("div",{className:"config-add-source-examples",children:[(0,r.jsx)("div",{className:"config-add-source-examples-label",children:f}),(0,r.jsx)("div",{className:"config-add-source-example-list",children:m.map(e=>"string"==typeof e?(0,r.jsx)("button",{type:"button",className:"config-add-source-example",onClick:()=>p(e),children:e},e):(0,r.jsxs)("button",{type:"button",className:"config-add-source-example has-label",onClick:()=>p(e.value),children:[(0,r.jsx)("span",{className:"config-add-source-example-label",children:e.label}),(0,r.jsx)("span",{className:"config-add-source-example-value",children:e.value})]},e.value))})]}),g&&(0,r.jsx)("div",{role:"alert",className:"config-add-source-error",children:g})]})}function aT(e){let{id:t,action:n,children:i}=e;return(0,r.jsxs)("div",{id:t,role:"status",className:`config-notice${n?" has-action":""}`,children:[n?(0,r.jsx)("span",{className:"config-notice-text",children:i}):i,n]})}function a$(e){let{id:t,message:n,trustLabel:i,trusting:s=!1,onTrust:o}=e;return(0,r.jsx)(aT,{id:t,action:o&&i?(0,r.jsx)(aP,{size:"small",onClick:o,disabled:s,children:i}):void 0,children:n})}function aM(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-empty-state",children:t})}function aR(e){let{children:t,style:n}=e;return(0,r.jsx)("div",{className:"config-detail",style:n,children:t})}function aL(e){let{status:t,children:n}=e;return(0,r.jsxs)("footer",{className:"config-footer",children:[(0,r.jsx)("div",{className:"config-footer-status",children:t}),(0,r.jsx)("div",{className:"config-footer-actions",children:n})]})}function aA(e){let{summary:t,tone:n="default",details:i}=e,s=`config-footer-status-summary${"default"===n?"":` is-${n}`}`;return i?.length?(0,r.jsxs)("details",{className:"config-footer-status-details",children:[(0,r.jsx)("summary",{className:s,children:t}),(0,r.jsx)("ul",{className:"config-footer-status-list",children:i.map((e,t)=>(0,r.jsx)("li",{children:e},t))})]}):(0,r.jsx)("span",{className:s,children:t})}function aP(e){let{variant:t="secondary",size:n="default",className:i,children:s,...o}=e;return(0,r.jsx)("button",{type:"button",...o,className:["config-button",`config-button-${t}`,`config-button-${n}`,i].filter(Boolean).join(" "),children:s})}function az(e){let{checked:t,disabled:n=!1,loading:i=!1,size:s="default",label:o,describedBy:a,onChange:l}=e,c=n||i;return(0,r.jsx)("button",{type:"button",role:"switch","aria-checked":t,"aria-busy":i||void 0,"aria-label":o,"aria-describedby":a,title:o,disabled:c,className:`config-switch${"small"===s?" is-small":""}${i?" is-loading":""}`,onClick:()=>l(!t),children:(0,r.jsx)("span",{className:"config-switch-knob","aria-hidden":"true"})})}function aW(e){let{active:t=!1,children:n,className:i,...s}=e;return(0,r.jsx)("div",{className:"config-list-action",children:(0,r.jsxs)("button",{type:"button",...s,"aria-current":t?"page":void 0,className:["config-list-action-button",i].filter(Boolean).join(" "),children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})}),n]})})}function aO(e){let{active:t,color:n}=e;return(0,r.jsx)("span",{"aria-hidden":"true",className:`config-status-dot${t?" is-active":!1===t?" is-inactive":""}`,style:n?{backgroundColor:n}:void 0})}function aD(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 aF(e,t){let n=aD(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 aB(e,t){return t.enabled&&(e?.enabledTotal??0)<=1}function aH(e,t){return e?.providers.find(e=>e.id===t)}function aU(e){let{modelName:t,effective:n,value:i,onChange:s,disabled:o=!1,describedBy:a}=e,{t:l}=(0,eO.s)(),c=void 0!==i&&void 0===o6(i);return(0,r.jsx)("input",{type:"text",inputMode:"numeric",className:"model-context-input",value:void 0===i?"":String(i),placeholder:void 0===n?void 0:String(n),title:l("models.contextWindow"),"aria-label":l("models.contextForModel",{model:t}),"aria-invalid":c||void 0,"aria-describedby":a,disabled:o,onChange:e=>s(""===e.target.value.trim()?void 0:e.target.value)})}let a_={"last-model":"models.enabledLastModel","project-scope":"models.enabledProjectScope"};function aq(e){let{controller:t}=e,{t:n}=(0,eO.s)(),{view:i,pending:s}=t;if(!i)return null;let o=!i.allEnabled,a=i.stalePatterns.length;return o||0!==a?(0,r.jsxs)("div",{className:"enabled-models-banner",children:[(0,r.jsxs)("span",{className:"enabled-models-banner-text",...a>0?{title:n("models.enabledStaleHint")}:{},children:[(0,r.jsx)("code",{className:"enabled-models-banner-key",title:i.settingsPath,children:i.settingsPath}),(0,r.jsxs)("code",{className:"enabled-models-banner-facts",children:[`\xb7 enabledModels ${i.enabledTotal}/${i.availableTotal}`,a>0&&` \xb7 ${n("models.enabledStale",{count:a})}`]})]}),i.editable&&a>0&&(0,r.jsx)(aP,{size:"small",onClick:t.pruneStale,disabled:null!==s,title:n("models.enabledPruneHint"),children:n("models.enabledPrune")}),i.editable&&o&&(0,r.jsx)(aP,{size:"small",onClick:t.clearScope,disabled:null!==s,title:n("models.enabledClearHint"),children:n("models.enabledClear")})]}):null}function aK(e){let{providerId:t,controller:n,noteId:i}=e,{t:s}=(0,eO.s)(),{view:o,loading:a,pending:l,failure:c}=n,d=aH(o,t),u=c?c.messageKey?s(c.messageKey):c.message:null,p=aV(n,t)?i:void 0;if(a&&!o)return null;if(!d)return(0,r.jsx)(az,{checked:!1,disabled:!0,label:s("models.enabledProviderToggle",{provider:t}),describedBy:p,onChange:()=>{}});let h=aF(o,d);return(0,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("span",{className:"enabled-models-switch-error",children:u}),(0,r.jsx)(az,{checked:h.checked,loading:l===`provider:${d.id}`,disabled:null!==l||h.blocked,label:s("models.enabledProviderToggle",{provider:d.name}),describedBy:p,onChange:e=>n.setProvider(d.id,e)})]})}function aV(e,t){let{view:n,loading:r}=e;if(r&&!n)return null;let i=aH(n,t);if(!i)return"models.enabledCustomEmpty";let{reason:s}=aF(n,i);return s?a_[s]:null}function aZ(e){let{providerId:t,controller:n,id:i}=e,{t:s}=(0,eO.s)(),o=aV(n,t);return o?(0,r.jsx)("div",{id:i,className:"config-detail-heading-note",children:s(o)}):null}function aJ(e){var t;let n,{providerId:s,controller:o,contextSettings:a}=e,{t:l}=(0,eO.s)(),[c,d]=(0,i.useState)(""),{view:u,loading:p,pending:h,failure:f}=o,m=aH(u,s),g=function(e,t){let[n,r]=(0,i.useState)(!1),[s,o]=(0,i.useState)(null);return(0,i.useEffect)(()=>o(null),[e]),{refreshing:n,note:s,refresh:(0,i.useCallback)(()=>{r(!0),o(null),(async()=>{try{let n=await fetch("/api/models/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);"offline"===r.reason?o("models.catalogOffline"):r.completed?o(r.changed?"models.catalogUpdated":"models.catalogUnchanged"):o("models.catalogUnreachable"),r.changed&&t()}catch{o("models.catalogUnreachable")}finally{r(!1)}})()},[e,t])}}(s,o.refresh),x=(0,i.useId)();if((0,i.useEffect)(()=>d(""),[s]),p&&!u)return(0,r.jsx)("div",{className:"enabled-models-empty",children:l("agents.modelsLoading")});if(!m)return f?.message?(0,r.jsx)("div",{className:"enabled-models-error",children:f.message}):(0,r.jsx)("div",{className:"enabled-models-empty",children:l("models.enabledUnavailable")});let v=(t=m.models,(n=c.trim().toLowerCase())?t.filter(e=>e.id.toLowerCase().includes(n)||e.name.toLowerCase().includes(n)):[...t]),b=aD(u,v),y=v.length!==m.models.length,j=null!==h,k=`provider:${m.id}`,w=u?.editable===!0,S=`${x}-scope`,C=`${x}-last`,N=`${x}-context`,E=w&&!b.canDisable&&b.disableRefs.length>0,I=E||w&&v.some(e=>aB(u,e)),T=(e,t)=>{y?o.setModels(k,t,e):o.setProvider(m.id,e)};return(0,r.jsxs)("div",{className:"enabled-models-section",children:[(0,r.jsxs)("div",{className:"enabled-models-header",children:[(0,r.jsx)("span",{className:"enabled-models-title",children:l("models.enabledSection")}),(0,r.jsx)("span",{className:"enabled-models-count",children:l("models.enabledCount",{enabled:m.enabledCount,total:m.models.length})}),(0,r.jsx)(aP,{size:"small",disabled:j||!b.canEnable,"aria-describedby":w?void 0:S,onClick:()=>T(!0,b.enableRefs),children:y?l("models.enableShown"):l("models.enableAll")}),(0,r.jsx)(aP,{size:"small",disabled:j||!b.canDisable,"aria-describedby":w?E?C:void 0:S,onClick:()=>T(!1,b.disableRefs),children:y?l("models.disableShown"):l("models.disableAll")}),(0,r.jsx)(aP,{size:"small",disabled:j||g.refreshing,title:l("models.refreshCatalogHint"),onClick:g.refresh,children:g.refreshing?l("models.refreshingCatalog"):l("models.refreshCatalog")})]}),g.note&&(0,r.jsx)("div",{className:"enabled-models-note",children:l(g.note)}),!w&&(0,r.jsx)("div",{id:S,className:"enabled-models-note",children:l("models.enabledProjectScope")}),I&&(0,r.jsx)("div",{id:C,className:"enabled-models-note",children:l("models.enabledLastModel")}),f&&(0,r.jsx)("div",{className:"enabled-models-error",children:f.messageKey?l(f.messageKey):f.message}),m.models.length>8&&(0,r.jsx)("input",{value:c,onChange:e=>d(e.target.value),placeholder:l("models.enabledFilterPlaceholder",{count:m.models.length}),"aria-label":l("models.enabledFilter"),className:"enabled-models-filter"}),a&&(0,r.jsx)("div",{id:N,className:"enabled-models-note",children:l("models.contextOverrideHelp")}),(0,r.jsx)("div",{className:"enabled-models-list",children:0===v.length?(0,r.jsx)("div",{className:"enabled-models-empty",children:l("models.enabledNoMatches")}):v.map(e=>{let t=aB(u,e),n=a?.overrides?.[e.id],i=n&&"object"==typeof n&&!Array.isArray(n)?n.contextWindow:void 0;return(0,r.jsxs)("div",{className:"enabled-models-row",children:[(0,r.jsxs)("span",{className:"enabled-models-row-text",children:[(0,r.jsx)("span",{className:"enabled-models-row-name",children:e.name}),(0,r.jsx)("code",{className:"enabled-models-row-id",children:e.id})]}),e.thinkingPin&&(0,r.jsx)("span",{className:"enabled-models-pin",title:l("models.enabledPinHint"),children:e.thinkingPin}),a&&(0,r.jsx)(aU,{modelName:e.name,effective:e.contextWindow,value:i,disabled:a.disabled,describedBy:N,onChange:t=>a.onChange(e.id,t)}),(0,r.jsx)(az,{checked:e.enabled,loading:h===e.ref,disabled:j||!u?.editable||t,label:l("models.enabledToggle",{model:e.name}),describedBy:w?t?C:void 0:S,onChange:t=>o.setModels(e.ref,[e.ref],t)})]},e.ref)})})]})}function aG(e){let{message:t,hint:n,value:i,placeholder:s,submitLabel:o,inputLabel:a,disabled:l=!1,plainEnterSubmits:c=!0,inputRef:d,onValueChange:u,onSubmit:p}=e,h=!l&&i.trim().length>0;return(0,r.jsxs)("div",{className:"oauth-paste-panel",children:[(0,r.jsx)("p",{className:"oauth-paste-message",children:t}),n&&(0,r.jsx)("p",{className:"oauth-paste-hint",children:n}),(0,r.jsxs)("div",{className:"oauth-paste-row",children:[(0,r.jsx)("input",{ref:d,value:i,className:"oauth-paste-input",placeholder:s,"aria-label":a,disabled:l||void 0,onChange:e=>u(e.target.value),onKeyDown:e=>{var t;t={key:e.key,metaKey:e.metaKey,ctrlKey:e.ctrlKey,isComposing:e.nativeEvent.isComposing,keyCode:e.keyCode},"Enter"===t.key&&!t.isComposing&&229!==t.keyCode&&(c||t.metaKey||t.ctrlKey)&&h&&p()}}),(0,r.jsx)("button",{type:"button",className:"oauth-paste-submit",onClick:p,disabled:!h,children:o})]})]})}let aY={anthropic:{symbol:"anthropic",color:!1},openai:{symbol:"openai",color:!1},"openai-codex":{symbol:"openai",color:!1},google:{symbol:"google",color:!0},"google-vertex":{symbol:"google",color:!0},"ant-ling":{symbol:"antgroup",color:!0},deepseek:{symbol:"deepseek",color:!0},groq:{symbol:"groq",color:!1},mistral:{symbol:"mistral",color:!0},moonshotai:{symbol:"moonshot",color:!1},"moonshotai-cn":{symbol:"moonshot",color:!1},moonshot:{symbol:"moonshot",color:!1},minimax:{symbol:"minimax",color:!0},"minimax-cn":{symbol:"minimax",color:!0},fireworks:{symbol:"fireworks",color:!0},huggingface:{symbol:"huggingface",color:!0},cerebras:{symbol:"cerebras",color:!0},openrouter:{symbol:"openrouter",color:!1},xai:{symbol:"xai",color:!1},"cloudflare-ai-gateway":{symbol:"cloudflare",color:!0},"cloudflare-workers-ai":{symbol:"cloudflare",color:!0},"vercel-ai-gateway":{symbol:"vercel",color:!1},"github-copilot":{symbol:"githubcopilot",color:!1},"amazon-bedrock":{symbol:"aws",color:!0},azure:{symbol:"azure",color:!0},"azure-openai-responses":{symbol:"azure",color:!0},"kimi-coding":{symbol:"kimi",color:!0},nvidia:{symbol:"nvidia",color:!0},opencode:{symbol:"opencode",color:!1},"opencode-go":{symbol:"opencode",color:!1},qwen:{symbol:"qwen",color:!0},xiaomi:{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-ams":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-cn":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-sgp":{symbol:"xiaomimimo",color:!1},zai:{symbol:"zai",color:!1},"zai-coding-cn":{symbol:"zai",color:!1},zhipu:{symbol:"zhipu",color:!0},cohere:{symbol:"cohere",color:!0},perplexity:{symbol:"perplexity",color:!0},together:{symbol:"together",color:!0},grok:{symbol:"grok",color:!1}};function aX(e){let{id:t,size:n}=e,i=aY[t];if(i)return(0,r.jsx)("svg",{"aria-hidden":"true",width:n,height:n,viewBox:"0 0 24 24",fill:i.color?void 0:"currentColor",style:{color:"var(--text-muted)",flexShrink:0},children:(0,r.jsx)("use",{href:`/provider-icons.svg#${i.symbol}`})});let s=t.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,r.jsx)("span",{"aria-hidden":"true",style:{width:n,height:n,border:"1px solid var(--border)",borderRadius:4,color:"var(--text-dim)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:Math.max(8,Math.floor(.42*n)),fontWeight:700,lineHeight:1},children:s})}let aQ=["openai-codex","deepseek","openrouter","moonshotai","moonshotai-cn","minimax","minimax-cn","vercel-ai-gateway","opencode-go","kimi-coding"],a0="pi-web:provider-usage:";function a1(e){let{providerId:t,enabled:n}=e;return aQ.includes(t)?(0,r.jsx)(a2,{providerId:t,enabled:n}):null}function a2(e){let{providerId:t,enabled:n}=e,[s,o]=(0,i.useState)(null),[a,l]=(0,i.useState)(!1),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),h=(0,i.useRef)(null),{locale:f,t:m}=(0,eO.s)();(0,i.useEffect)(()=>{h.current&&clearTimeout(h.current),p(!1),o(null);try{let e=localStorage.getItem(`${a0}${t}`);if(e){let t=JSON.parse(e);t?.status==="ready"&&t.report&&Array.isArray(t.report.buckets)&&Array.isArray(t.report.metrics)&&o(t)}}catch{try{localStorage.removeItem(`${a0}${t}`)}catch{}}return d(null),()=>{h.current&&clearTimeout(h.current)}},[t]);let g=(0,i.useCallback)(async()=>{l(!0),d(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){o(n);try{localStorage.setItem(`${a0}${t}`,JSON.stringify(n))}catch{}p(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>p(!1),2e3)}else d(n.message??m("providerUsage.queryFailed"))}catch(e){d(e instanceof Error?e.message:m("providerUsage.queryFailed"))}finally{l(!1)}},[t,m]),x=s?.status==="ready"?s.report:void 0;return(0,r.jsxs)("section",{style:{paddingTop:10,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:13,color:"var(--text)",fontWeight:600,lineHeight:1.35},children:m("providerUsage.usage")}),(0,r.jsx)("button",{type:"button",onClick:g,disabled:!n||a,title:m(a?"providerUsage.refreshing":"providerUsage.refresh"),"aria-label":m(a?"providerUsage.refreshing":"providerUsage.refresh"),style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:32,height:30,padding:0,background:"none",border:"none",color:u?"#4ade80":"var(--text-dim)",cursor:n&&!a?"pointer":"default",borderRadius:5,flexShrink:0,opacity:n?1:.6,transition:"color 0.3s"},children:u?(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:a?{animation:"spin 0.8s linear infinite"}:void 0,"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}),x&&(0,r.jsx)("span",{title:new Date(x.capturedAt).toLocaleString(f),style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap"},children:m("providerUsage.updated",{time:(0,tS.ob)(x.capturedAt,f)})})]}),!x&&!c&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)"},children:m("providerUsage.notQueried")}),c&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171"},children:c}),x&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"180px minmax(0, 1fr)",columnGap:14,rowGap:8,alignItems:"baseline",minWidth:0,width:"min(100%, 420px)",maxWidth:"100%",fontSize:12},children:[x.buckets.map(e=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.groupLabel?`${e.groupLabel} / ${e.label}`:e.label}),(0,r.jsx)("span",{style:{color:"var(--text)",fontFamily:"var(--font-mono)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:function(e,t){if("percent"===e.unit&&void 0!==e.remaining){let t=e.resetsAt?` / ${new Date(1e3*e.resetsAt).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:"";return`${Math.round(e.remaining)}%${t}`}return"currency"===e.unit?`${"CNY"===e.currency?"CNY ":"$"}${a4(e.remaining??e.limit)}`:void 0!==e.remaining&&void 0!==e.limit?`${a4(e.remaining)} / ${a4(e.limit)}`:e.period??t}(e,m("providerUsage.available"))})]},e.id)),x.metrics.map(e=>{var t;return(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("span",{style:{color:"var(--text)",fontFamily:"var(--font-mono)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:"currency"===(t=e).unit?`${"CNY"===t.currency?"CNY ":"$"}${t.value}`:String(t.value)})]},e.id)})]})]})}function a4(e){return void 0===e?"-":Number.isInteger(e)?String(e):e.toFixed(2)}function a8(){let e=o1("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}let a5=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function a6(e){let{label:t,children:n}=e;return(0,r.jsx)(aj,{label:t,children:n})}let a3={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 a9(e){let{value:t,onChange:n,placeholder:i,mono:s}=e;return(0,r.jsx)("input",{value:t,onChange:e=>n(e.target.value),placeholder:i,style:{...a3,fontFamily:s?"var(--font-mono)":"inherit"}})}function a7(e){let{value:t,onChange:n,placeholder:s,mono:o,onKeyDown:a,autoComplete:l="off",spellCheck:c=!1,style:d}=e,[u,p]=(0,i.useState)(!1),{t:h}=(0,eO.s)();return(0,i.useEffect)(()=>{t||p(!1)},[t]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...d},children:[(0,r.jsx)("input",{type:u?"text":"password",value:t,onChange:e=>n(e.target.value),onKeyDown:a,placeholder:s,style:{...a3,paddingRight:34,fontFamily:o?"var(--font-mono)":"inherit"},autoComplete:l,spellCheck:c}),(0,r.jsx)("button",{type:"button",onClick:()=>p(e=>!e),"aria-label":h(u?"i18n.hideDetails":"i18n.showDetails"),title:h(u?"i18n.hideDetails":"i18n.showDetails"),style:{position:"absolute",right:5,top:"50%",transform:"translateY(-50%)",width:24,height:24,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:u?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C7 20 2.73 16.89 1 12a18.45 18.45 0 0 1 5.06-6.94"}),(0,r.jsx)("path",{d:"M9.9 4.24A10.94 10.94 0 0 1 12 4c5 0 9.27 3.11 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,r.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,r.jsx)("path",{d:"M1 1l22 22"})]}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function le(e){let{value:t,onChange:n,placeholder:i}=e;return(0,r.jsx)("input",{type:"number",value:t,onChange:e=>n(e.target.value),placeholder:i,style:a3})}function lt(e){let{value:t,onChange:n,options:i,required:s}=e,{t:o}=(0,eO.s)();return(0,r.jsxs)("select",{value:t,onChange:e=>n(e.target.value),style:{...a3,color:t?"var(--text)":"var(--text-dim)"},children:[!s&&(0,r.jsxs)("option",{value:"",children:["— ",o("i18n.default")," / none —"]}),i.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]})}function ln(e){let{label:t,checked:n,onChange:i}=e;return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:n,onChange:e=>i(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),t]})}function lr(e){let{children:t}=e;return(0,r.jsx)(ay,{children:t})}function li(e){let{name:t,editingName:n,provider:s,onChange:o,onEditingNameChange:a,onRename:l,onDelete:c,onAddModels:d,enabledModels:u}=e,{t:p}=(0,eO.s)(),[h,f]=(0,i.useState)({phase:"idle"}),[m,g]=(0,i.useState)(""),[x,v]=(0,i.useState)([]),b=(0,i.useRef)(0),y=(0,i.useRef)(null),j=(0,i.useId)(),k=(e,t)=>o({...s,[e]:t});(0,i.useEffect)(()=>{b.current+=1,f({phase:"idle"}),g(""),v([])},[t,s.baseUrl,s.api,s.apiKey]);let w=(0,i.useCallback)(async()=>{if("loading"===h.phase)return;let e=++b.current;f({phase:"loading"}),v([]);try{let n=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:t,provider:{...s,models:void 0}})}),r=await n.json();if(e!==b.current)return;if(!n.ok||r.error||!r.models)return void f({phase:"error",message:r.error??`HTTP ${n.status}`});f({phase:"success",models:r.models,endpoint:r.endpoint??s.baseUrl??""})}catch(t){if(e!==b.current)return;f({phase:"error",message:t instanceof Error?t.message:String(t)})}},[h.phase,t,s]),S=new Set((s.models??[]).map(e=>e.id)),C="success"===h.phase?h.models:[],N=m.trim().toLocaleLowerCase(),E=C.filter(e=>!N||e.id.toLocaleLowerCase().includes(N)||e.name?.toLocaleLowerCase().includes(N)),I=E.slice(0,300),T=I.filter(e=>!S.has(e.id)).map(e=>e.id),$=x.filter(e=>!S.has(e)).length,M=T.length>0&&T.every(e=>x.includes(e)),R=!M&&T.some(e=>x.includes(e));return(0,i.useEffect)(()=>{y.current&&(y.current.indeterminate=R)},[R]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(ag,{children:[(0,r.jsx)(ax,{children:(0,r.jsx)(lr,{children:p("i18n.provider")})}),(0,r.jsxs)(av,{children:[(0,r.jsx)(aK,{providerId:t,controller:u,noteId:j}),(0,r.jsx)(aP,{variant:"danger",size:"small",onClick:c,children:p("i18n.delete")})]})]}),(0,r.jsx)(aZ,{providerId:t,controller:u,id:j})]}),(0,r.jsxs)(a6,{label:p("i18n.providerName"),children:[(0,r.jsx)(a9,{value:n,onChange:a,placeholder:"provider-name",mono:!0}),n!==t&&n.trim()&&(0,r.jsx)("button",{onClick:()=>l(n.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--accent)",border:"none",borderRadius:4,color:"var(--accent-contrast)",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:p("i18n.rename")})]}),(0,r.jsx)(a6,{label:"Base URL",children:(0,r.jsx)(a9,{value:s.baseUrl??"",onChange:e=>k("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsx)(a6,{label:"API Key",children:(0,r.jsx)(a7,{value:s.apiKey??"",onChange:e=>k("apiKey",e||void 0),placeholder:p("models.apiKeyPlaceholder"),mono:!0})}),(0,r.jsx)(a6,{label:"API",children:(0,r.jsx)(lt,{value:s.api??"",onChange:e=>k("api",e||void 0),options:a5})}),(0,r.jsx)(a6,{label:"Headers",children:(0,r.jsx)(lu,{headers:s.headers,onChange:e=>k("headers",e)})}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==h.phase&&(0,r.jsx)("button",{onClick:w,disabled:"loading"===h.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:"loading"===h.phase?"var(--text-dim)":"var(--text-muted)",cursor:"loading"===h.phase?"not-allowed":"pointer",fontSize:11},children:"loading"===h.phase?p("models.discoveryFetching"):p("models.discoveryFetch")}),"error"===h.phase&&(0,r.jsx)("div",{style:{padding:"7px 9px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",fontSize:11,lineHeight:1.4},children:h.message}),"success"===h.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:m,onChange:e=>g(e.target.value),placeholder:p("models.discoveryFilterPlaceholder",{count:h.models.length}),"aria-label":p("models.discoveryFilter"),style:{...a3,width:"100%",minWidth:0}}),(0,r.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,r.jsxs)("label",{style:{minHeight:32,padding:"5px 9px",display:"flex",alignItems:"center",gap:8,position:"sticky",top:0,zIndex:1,borderBottom:"1px solid var(--border)",background:"var(--bg)",cursor:T.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:y,type:"checkbox",checked:M,disabled:0===T.length,onChange:()=>{let e=new Set(T);v(t=>M?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...T])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),p("models.discoverySelectShown")]}),0===I.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:p("models.discoveryNoMatches")}):I.map((e,t)=>{let n=S.has(e.id),i=x.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:i||n,disabled:n,onChange:()=>{var t;return t=e.id,void v(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),n&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:p("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:h.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:E.length>I.length?p("models.discoveryShowing",{shown:I.length,total:E.length}):p("models.discoveryFetched",{count:h.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==h.phase)return;let e=new Set(x),t=h.models.filter(t=>e.has(t.id)&&!S.has(t.id));0!==t.length&&(d(t),v([]))},disabled:0===$,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:$?"var(--accent)":"var(--bg-panel)",color:$?"var(--accent-contrast)":"var(--text-dim)",cursor:$?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:$?p("models.discoveryAddSelectedCount",{count:$}):p("models.discoveryAddSelected")})]})]})]})]})}let ls=["off","minimal","low","medium","high","xhigh","max"],lo={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function la(e){let{value:t,onChange:n}=e,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,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:ls.map(e=>{let t=i[e],n=e in i?null===t?"null":"string":"omit",o="string"==typeof t?t:"",a=lo[e],l={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},c={background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600};return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:a,flexShrink:0,opacity:"null"===n?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===n?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===n?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>s(e,"omit"),style:{...l,..."omit"===n?c:{}},children:"Default"}),(0,r.jsx)("button",{onClick:()=>s(e,null),style:{...l,borderLeft:"1px solid var(--border)",..."null"===n?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===n?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>s(e,o||e),style:{...l,..."string"===n?c:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,r.jsx)("input",{value:o,onChange:t=>s(e,t.target.value),onFocus:()=>{"string"!==n&&s(e,o||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===n?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===n?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let ll={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function lc(e){return e.compat?.thinkingFormat==="deepseek"}function ld(e,t){return{...e.compat??{},...t.compat??{}}}function lu(e){let{headers:t,onChange:n}=e,[s,o]=(0,i.useState)(()=>Object.entries(t??{}).map((e,t)=>{let[n,r]=e;return{id:t,name:n,value:r}})),a=(0,i.useRef)(s.length),l=e=>{o(e),n(function(e){let t={};for(let n of e){let e=n.name.trim();e&&(t[e]=n.value)}return Object.keys(t).length?t:void 0}(e))},c=(e,t)=>{l(s.map(n=>n.id===e?{...n,...t}:n))},d={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[s.map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{value:e.name,onChange:t=>c(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...a3,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>c(e.id,{value:t.target.value}),placeholder:"value",style:{...a3,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void l(s.filter(e=>e.id!==t))},style:d,children:"✕"})]},e.id)),(0,r.jsx)("button",{onClick:()=>o(e=>[...e,{id:a.current++,name:"",value:""}]),style:{padding:"5px 9px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,alignSelf:"flex-start"},children:"+ Add header"})]})}function lp(e){let{providerName:t,provider:n,model:s,onChange:o,onDelete:a}=e,[l,c]=(0,i.useState)({phase:"idle"}),{t:d}=(0,eO.s)(),[u,p]=(0,i.useState)({phase:"idle"}),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(()=>o9(s.cost)),x=(0,i.useRef)(m),[v,b]=(0,i.useState)(!1),y=(0,i.useRef)(0),j=s.baseUrl??n.baseUrl,k=(0,i.useRef)(0),w=(0,i.useRef)(null),S=(0,i.useRef)(s.cost),C=(e,t)=>o({...s,[e]:t}),N=(()=>{if("idle"===l.phase)return null;if("testing"===l.phase)return d("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?[d("i18n.connected"),...e,l.responseText||null].filter(Boolean).join(" \xb7 "):[d("i18n.failed"),...e,l.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>(y.current+=1,c({phase:"idle"}),()=>{y.current+=1}),[t,n,s]),(0,i.useEffect)(()=>{k.current+=1,p({phase:"idle"}),w.current=null},[t,j,s.id]);let E=(0,i.useCallback)(async()=>{if(!s.id.trim()||"testing"===l.phase)return;let e=++y.current;c({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:t,provider:n,model:s})}),i=await r.json();if(e!==y.current)return;if(!r.ok||!i.ok)return void c({phase:"error",message:i.error??`HTTP ${r.status}`,latencyMs:i.latencyMs,status:i.status});c({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(t){if(e!==y.current)return;c({phase:"error",message:t instanceof Error?t.message:String(t)})}},[s,n,t,l.phase]),I=(0,i.useCallback)(async()=>{let e=s.id.trim();if(!e||"loading"===u.phase)return;let n=++k.current;p({phase:"loading"});try{let r=new URLSearchParams({q:e,provider:t,limit:"50"});j?.trim()&&r.set("baseUrl",j.trim());let i=await fetch(`/api/models-config/catalog?${r}`),a=await i.json();if(n!==k.current)return;if(!i.ok||a.error||!a.recommendation)return void p({phase:"error",message:a.error??`HTTP ${i.status}`});let l=function(e,t){let n={...e},r=0;if(!e.name?.trim()&&t.name&&(n.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(n.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(n.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(n.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(n.maxTokens=t.maxTokens,r+=1),t.cost){let i={...e.cost??{}},s=0;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],s+=1);let o=o7(o9(i));s>0&&o&&(n.cost={...i,...o},r+=s)}return{model:n,appliedCount:r}}(s,a.recommendation.preset);l.appliedCount>0&&(w.current=s,o(l.model)),f(!1),p({phase:"success",recommendation:a.recommendation,appliedCount:l.appliedCount})}catch(e){if(n!==k.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,s,o,j,t]),T=(()=>{if("success"!==u.phase)return null;let{recommendation:e,appliedCount:n}=u,r=n>0?d("models.catalogFilled",{count:n}):d("models.catalogNoEmptyFields");if("unreliable"===e.price.status){let t="no-exact-match"===e.price.reason?d("models.catalogNoExactMatch"):d("models.catalogPriceUnreliable");return`${r} \xb7 ${t}`}let i="provider"===e.price.method?d("models.catalogPriceProvider",{provider:e.price.providerName??e.price.providerId??t}):"base-url"===e.price.method?d("models.catalogPriceBaseUrl",{provider:e.price.providerName??e.price.providerId??t}):d("models.catalogPriceConsensus",{support:e.price.support,total:e.price.total});return`${r} \xb7 ${i}`})(),$="error"===u.phase?u.message:T,M="error"===u.phase?"#ef4444":"success"===u.phase&&"unreliable"===u.recommendation.price.status?"#d97706":"var(--text-dim)",R=[{key:"input",label:d("models.costInput")},{key:"output",label:d("models.costOutput")},{key:"cacheRead",label:d("models.costCacheRead")},{key:"cacheWrite",label:d("models.costCacheWrite")}],L=new Set(Object.keys(s.compat??{})),A=0;lc(s)&&(A+=1,L.delete("thinkingFormat"),L.delete("requiresReasoningContentOnAssistantMessages")),Object.prototype.hasOwnProperty.call(s.compat??{},"supportsDeveloperRole")&&(A+=1,L.delete("supportsDeveloperRole")),A+=L.size;let P=[s.baseUrl?d("models.baseUrlOverride"):null,s.api?`API: ${s.api}`:null,Object.keys(s.headers??{}).length?d("models.headersSummary",{count:Object.keys(s.headers??{}).length}):null,A?d("models.compatSummary",{count:A}):null,Object.keys(s.thinkingLevelMap??{}).length?d("models.thinkingSummary",{count:Object.keys(s.thinkingLevelMap??{}).length}):null].filter(e=>!!e),z=P.length?P.join(" \xb7 "):d("models.providerDefaults");return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(ag,{children:[(0,r.jsx)(ax,{children:(0,r.jsx)(lr,{children:d("i18n.model")})}),(0,r.jsxs)(av,{children:[N&&(0,r.jsx)("span",{title:N,style:{maxWidth:260,height:28,padding:"0 8px",border:`1px solid ${"error"===l.phase?"#fecaca":"success"===l.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===l.phase?"#fee2e2":"success"===l.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:N}),(0,r.jsxs)(aP,{size:"small",variant:"success"===l.phase?"primary":"secondary",onClick:"success"===l.phase?()=>c({phase:"idle"}):E,disabled:!s.id.trim()||"testing"===l.phase,title:d("i18n.testConnection"),className:"success"===l.phase?"is-success":void 0,children:["success"===l.phase&&(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===l.phase?d("i18n.checking"):"success"===l.phase?d("common.ok"):d("i18n.test")]}),(0,r.jsx)(aP,{variant:"danger",size:"small",onClick:a,children:d("i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(a6,{label:"ID *",children:(0,r.jsx)(a9,{value:s.id,onChange:e=>C("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(a6,{label:"Name",children:(0,r.jsx)(a9,{value:s.name??"",onChange:e=>C("name",e||void 0),placeholder:"Display name"})})]}),(0,r.jsxs)("div",{style:{padding:"2px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>void I(),disabled:!s.id.trim()||"loading"===u.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:s.id.trim()&&"loading"!==u.phase?"var(--text-muted)":"var(--text-dim)",cursor:s.id.trim()&&"loading"!==u.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===u.phase?d("models.catalogFilling"):d("models.catalogFill")}),(0,r.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:d("models.catalogSource")})]}),$&&(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:8,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:M,fontSize:10},children:[(0,r.jsx)("span",{title:$,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:$}),w.current&&(0,r.jsx)("button",{onClick:()=>{let e=w.current;e&&(w.current=null,o(e),p({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:d("models.catalogUndo")})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(lr,{children:d("models.capabilities")}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginTop:8},children:[(0,r.jsx)(ln,{label:d("models.reasoning"),checked:s.reasoning??!1,onChange:e=>C("reasoning",e||void 0)}),(0,r.jsx)(ln,{label:d("models.imageInput"),checked:s.input?.includes("image")??!1,onChange:e=>C("input",e?["text","image"]:void 0)})]})]}),(0,r.jsxs)("section",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[(0,r.jsx)(lr,{children:d("models.modelSpecs")}),(0,r.jsx)("button",{type:"button",onClick:()=>{if(h)return void f(!1);S.current=s.cost;let e=o9(s.cost);x.current=e,g(e),f(!0)},"aria-expanded":h,style:{padding:"2px 4px",border:"none",background:"transparent",color:"var(--accent)",cursor:"pointer",fontSize:10},children:h?d("models.finishEditingCosts"):d("models.editCosts")})]}),(0,r.jsxs)("div",{style:{marginTop:10,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:10},children:[(0,r.jsx)(a6,{label:d("models.contextWindow"),children:(0,r.jsx)(le,{value:void 0!==s.contextWindow?String(s.contextWindow):"",onChange:e=>C("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(a6,{label:d("models.maxOutputTokens"),children:(0,r.jsx)(le,{value:void 0!==s.maxTokens?String(s.maxTokens):"",onChange:e=>C("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{style:{marginTop:16},children:[(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontWeight:600,textTransform:"uppercase"},children:d("models.costPerMillion")}),h?(0,r.jsxs)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(110px, 1fr))",gap:8},children:[R.map(e=>{let{key:t,label:n}=e;return(0,r.jsx)(a6,{label:n,children:(0,r.jsx)(le,{value:m[t],onChange:e=>{let n,r,i;return r=o7(n={...x.current,[t]:e}),i={...s},void(x.current=n,g(n),r?(i.cost={...S.current??{},...r},S.current=i.cost):delete i.cost,o(i))},placeholder:"0"})},t)}),ae(m)&&!o7(m)&&(0,r.jsx)("div",{"aria-live":"polite",style:{gridColumn:"1 / -1",color:"#d97706",fontSize:10},children:d("models.costAllRequired")})]}):(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(105px, 1fr))",gap:"8px 16px"},children:R.map(e=>{let t,{key:n,label:i}=e,o=s.cost?.[n]===void 0;return(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:i}),(0,r.jsx)("div",{style:{marginTop:3,color:o?"var(--text-dim)":"var(--text)",fontSize:12,fontFamily:"var(--font-mono)",fontVariantNumeric:"tabular-nums"},children:void 0===(t=s.cost?.[n])?d("models.notProvided"):`$${String(t)}`})]},n)})})]})]}),(0,r.jsxs)("section",{style:{borderTop:"1px solid var(--border)",paddingTop:4},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>b(e=>!e),"aria-expanded":v,"aria-controls":"model-advanced-settings",style:{width:"100%",minHeight:48,padding:"8px 0",border:"none",background:"transparent",display:"grid",gridTemplateColumns:"minmax(0, 1fr) 18px",alignItems:"center",gap:10,color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:11,fontWeight:600},children:d("models.advancedSettings")}),(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-dim)",fontSize:10,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:z})]}),(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{color:"var(--text-dim)",transform:v?"rotate(180deg)":"none",transition:"transform 0.15s ease"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),v&&(0,r.jsxs)("div",{id:"model-advanced-settings",style:{display:"flex",flexDirection:"column",gap:14,padding:"4px 0 16px"},children:[(0,r.jsx)(a6,{label:d("models.baseUrlOverride"),children:(0,r.jsx)(a9,{value:s.baseUrl??"",onChange:e=>C("baseUrl",e.trim()||void 0),placeholder:n.baseUrl??d("models.providerDefaults"),mono:!0})}),(0,r.jsx)(a6,{label:d("models.apiOverride"),children:(0,r.jsx)(lt,{value:s.api??"",onChange:e=>C("api",e||void 0),options:a5})}),(0,r.jsxs)(a6,{label:d("models.headers"),children:[(0,r.jsx)(lu,{headers:s.headers,onChange:e=>C("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:d("models.headersHelp")})]}),s.reasoning&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsx)(lr,{children:d("models.compatibility")}),(0,r.jsx)(ln,{label:d("models.deepSeekThinkingCompat"),checked:lc(s),onChange:e=>o(function(e,t){if(t)return{...e,compat:{...e.compat??{},...ll}};if(!e.compat)return e;let n={...e.compat};return delete n.thinkingFormat,delete n.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(n).length?n:void 0}}(s,e))}),(0,r.jsx)(ln,{label:d("models.developerRole"),checked:!1!==ld(n,s).supportsDeveloperRole,onChange:e=>o(at(s,"supportsDeveloperRole",e))}),(s.api??n.api)==="anthropic-messages"&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[(0,r.jsx)(ln,{label:d("models.adaptiveThinking"),checked:!0===ld(n,s).forceAdaptiveThinking,onChange:e=>o(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(n!==r)return at(e,t,n);if(!e.compat||!Object.prototype.hasOwnProperty.call(e.compat,t))return e;let i={...e.compat};return delete i[t],{...e,compat:Object.keys(i).length?i:void 0}}(s,"forceAdaptiveThinking",e,n.compat?.forceAdaptiveThinking===!0))}),(0,r.jsx)("code",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",paddingLeft:19},children:"compat.forceAdaptiveThinking"})]}),(0,r.jsxs)("div",{style:{marginTop:4},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,marginBottom:8},children:[(0,r.jsx)(lr,{children:d("models.thinkingLevelMap")}),s.thinkingLevelMap&&(0,r.jsx)("button",{type:"button",onClick:()=>C("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 5px",background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer"},children:d("models.clearAll")})]}),(0,r.jsx)(la,{value:s.thinkingLevelMap,onChange:e=>C("thinkingLevelMap",e)})]})]})]})]})]})}function lh(e){let{provider:t,onRefresh:n,enabledModels:s,contextSettings:o}=e,[a,l]=(0,i.useState)({phase:"idle"}),{t:c}=(0,eO.s)(),[d,u]=(0,i.useState)(""),p=(0,i.useRef)(null),h=(0,i.useRef)(null);(0,i.useEffect)(()=>{("auth"===a.phase||"prompt"===a.phase)&&setTimeout(()=>h.current?.focus(),50)},[a.phase]),(0,i.useEffect)(()=>{l({phase:"idle"}),u(""),p.current?.close(),p.current=null},[t.id]),(0,i.useEffect)(()=>()=>{p.current?.close()},[]);let f=(0,i.useCallback)(()=>{p.current?.close(),l({phase:"connecting"}),u("");let e=new EventSource(`/api/auth/login/${encodeURIComponent(t.id)}`);p.current=e,e.onmessage=t=>{let r=JSON.parse(t.data);"auth"===r.type?(l({phase:"auth",url:r.url,instructions:r.instructions??null,token:r.token}),window.open(r.url,"_blank","noopener,noreferrer")):"device_code"===r.type?(l({phase:"device_code",userCode:r.userCode,verificationUri:r.verificationUri,intervalSeconds:r.intervalSeconds??null,expiresInSeconds:r.expiresInSeconds??null}),window.open(r.verificationUri,"_blank","noopener,noreferrer")):"prompt_request"===r.type?l({phase:"prompt",message:r.message,placeholder:r.placeholder??null,token:r.token}):"select_request"===r.type?l({phase:"select",message:r.message,options:r.options??[],token:r.token}):"progress"===r.type?l({phase:"progress",message:r.message}):"success"===r.type?(e.close(),l({phase:"success"}),n()):"error"===r.type?(e.close(),l({phase:"error",message:r.message})):"cancelled"===r.type&&(e.close(),l({phase:"idle"}))},e.onerror=()=>{e.close(),l(e=>"success"===e.phase?e:{phase:"error",message:"Connection lost"})}},[t.id,n]),m=(0,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(t.id)}`,{method:"POST"}),l({phase:"idle"}),n()},[t.id,n]),g=(0,i.useCallback)(async(e,n)=>{if(n.trim()){l({phase:"progress",message:"Verifying…"});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,code:n.trim()})});if(!r.ok){let e=await r.json().catch(()=>({}));l({phase:"error",message:e.error??`Server error ${r.status}`});return}u("")}catch(e){l({phase:"error",message:e instanceof Error?e.message:"Network error"})}}},[t.id]),x=(0,i.useCallback)(async(e,n)=>{l({phase:"progress",message:"Continuing…"});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,code:n})});if(!r.ok){let e=await r.json().catch(()=>({}));l({phase:"error",message:e.error??`Server error ${r.status}`})}}catch(e){l({phase:"error",message:e instanceof Error?e.message:"Network error"})}},[t.id]),v="connecting"===a.phase||"progress"===a.phase||"auth"===a.phase||"device_code"===a.phase||"prompt"===a.phase||"select"===a.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:t.loggedIn&&"idle"===a.phase?0:16},children:[(0,r.jsxs)(ag,{children:[(0,r.jsx)(ax,{children:(0,r.jsx)(lr,{children:c("i18n.subscription")})}),(0,r.jsxs)(av,{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:t.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:t.loggedIn?"#4ade80":"var(--text-dim)"},children:c(t.loggedIn?"i18n.connected":"i18n.notConnected")})]}),v?(0,r.jsx)(aP,{size:"small",onClick:()=>{p.current?.close(),l({phase:"idle"})},children:c("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(aP,{variant:"primary",size:"small",onClick:f,children:c(t.loggedIn?"i18n.relogin":"i18n.login")}),t.loggedIn&&(0,r.jsx)(aP,{variant:"danger",size:"small",onClick:m,children:c("i18n.disconnect")})]})]})]}),(0,r.jsxs)("div",{style:{minHeight:t.loggedIn&&"idle"===a.phase?0:48},children:["idle"===a.phase&&!t.loggedIn&&(0,r.jsxs)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:["Connect your ",t.name," account."]}),"connecting"===a.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:c("i18n.openingBrowser")}),"select"===a.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:a.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:a.options.map(e=>(0,r.jsx)("button",{onClick:()=>x(a.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"===a.phase||"prompt"===a.phase)&&(0,r.jsx)(aG,{message:"auth"===a.phase?"Complete sign-in in the browser, then copy the redirect URL from the address bar and paste it below.":a.message,hint:"auth"===a.phase?(0,r.jsxs)(r.Fragment,{children:["If the browser window did not open,"," ",(0,r.jsx)("a",{href:a.url,target:"_blank",rel:"noopener noreferrer",children:"click here to open the login page"}),"."]}):void 0,value:d,placeholder:"auth"===a.phase?"http://localhost:1455/auth/callback?code=…":a.placeholder??"Enter value…",submitLabel:c("i18n.submit"),inputRef:h,onValueChange:u,onSubmit:()=>void g(a.token,d)}),"device_code"===a.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:a.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:a.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:a.verificationUri}),a.expiresInSeconds?` Expires in ${Math.ceil(a.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===a.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:a.message}),"success"===a.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:c("i18n.connectedSuccessfully")}),"error"===a.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:a.message})]}),(0,r.jsx)(a1,{providerId:t.id,enabled:t.loggedIn}),t.loggedIn&&(0,r.jsx)(aJ,{providerId:t.id,controller:s,contextSettings:o})]})}function lf(e){let{provider:t,onRefresh:n,enabledModels:s,contextSettings:o}=e,[a,l]=(0,i.useState)(""),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(!1),{t:x}=(0,eO.s)();(0,i.useEffect)(()=>{l(""),f(null),g(!1)},[t.id]);let v=(0,i.useCallback)(async()=>{if(a.trim()){d(!0),f(null),g(!1);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:a.trim()})}),r=await e.json();!e.ok||r.error?f(r.error??`HTTP ${e.status}`):(l(""),g(!0),setTimeout(()=>g(!1),2e3),n())}catch(e){f(String(e))}finally{d(!1)}}},[a,t.id,n]),b=(0,i.useCallback)(async()=>{p(!0),f(null);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"DELETE"}),r=await e.json();!e.ok||r.error?f(r.error??`HTTP ${e.status}`):n()}catch(e){f(String(e))}finally{p(!1)}},[t.id,n]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(ag,{children:[(0,r.jsx)(ax,{children:(0,r.jsx)(lr,{children:"API Key"})}),(0,r.jsxs)(av,{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:t.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:t.configured?"#4ade80":"var(--text-dim)"},children:x(t.configured?"i18n.configured":"i18n.notConfigured")})]}),t.configured&&(0,r.jsx)(aP,{variant:"danger",size:"small",onClick:b,disabled:u,children:x(u?"i18n.removing":"i18n.disconnect")})]})]}),!t.configured&&(0,r.jsxs)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:["Enter your ",t.displayName," API key to enable ",t.modelCount," model",1!==t.modelCount?"s":"","."]}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(a7,{value:a,onChange:l,onKeyDown:e=>{"Enter"===e.key&&a.trim()&&v()},placeholder:t.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:v,disabled:c||!a.trim()||m,style:{padding:"6px 12px",background:m?"#16a34a":a.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:m?"#fff":a.trim()?"var(--accent-contrast)":"var(--text-dim)",cursor:c||!a.trim()||m?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[m&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),x(m?"i18n.saved":c?"i18n.saving":"i18n.save")]})]}),h&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:h}),(0,r.jsx)(a1,{providerId:t.id,enabled:t.configured}),t.configured&&(0,r.jsx)(aJ,{providerId:t.id,controller:s,contextSettings:o})]})}function lm(e){let{oauthProviders:t,apiKeyProviders:n,onSelectOAuth:s,onSelectApiKey:o,onAddCustom:a,onClose:l}=e,[c,d]=(0,i.useState)(""),{t:u}=(0,eO.s)(),p=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>p.current?.focus(),30)},[]);let h=c.trim().toLowerCase(),f=t.filter(e=>!e.loggedIn&&as(h,e.id,e.name)),m=n.filter(e=>!e.configured&&as(h,e.id,e.displayName)),g=!h||"custom".includes(h)||"openai-compatible".includes(h)||"anthropic-compatible".includes(h),x=f.length+m.length+ +!!g,v={display:"flex",flexDirection:"row",alignItems:"center",gap:8,padding:"10px 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:7,boxSizing:"border-box",cursor:"pointer",minWidth:0,textAlign:"left",transition:"border-color 0.12s, background 0.12s",width:"100%"};return(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&l()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),l())},children:(0,r.jsxs)("div",{style:{width:820,maxWidth:"calc(100vw - 32px)",maxHeight:"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{ref:p,value:c,onChange:e=>d(e.target.value),placeholder:u("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===x?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:u("i18n.noProviders")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[g&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:u("i18n.custom")}),g&&(0,r.jsxs)("button",{onClick:()=>{a(),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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:u("i18n.customEndpoint")})]}),(0,r.jsx)("span",{style:{width:26,height:26,borderRadius:5,background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),f.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!g,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:u("i18n.subscriptions")}),f.map(e=>(0,r.jsxs)("button",{onClick:()=>{s(e.id),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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(aX,{id:e.id,size:28})]},e.id)),m.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(f.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),m.map(e=>(0,r.jsxs)("button",{onClick:()=>{o(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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[e.modelCount," models"]})]}),(0,r.jsx)(aX,{id:e.id,size:28})]},e.id))]})})]})})}function lg(e){let{onClose:t,embedded:n=!1,cwd:s=null}=e,{t:o}=(0,eO.s)(),a=function(e){let[t,n]=(0,i.useState)(null),[r,s]=(0,i.useState)(!0),[o,a]=(0,i.useState)(null),[l,c]=(0,i.useState)(null),d=(0,i.useRef)(null),u=(0,i.useRef)(null),p=(0,i.useRef)(null),[h,f]=(0,i.useState)(0);(0,i.useEffect)(()=>{let t=new AbortController;s(!0);let r=e?`?cwd=${encodeURIComponent(e)}`:"";return fetch(`/api/models/enabled${r}`,{signal:t.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);n(t),c(null)}).catch(e=>{t.signal.aborted||c({message:e instanceof Error?e.message:String(e)})}).finally(()=>{t.signal.aborted||s(!1)}),()=>t.abort()},[e,h]);let m=(0,i.useCallback)((t,r)=>{if(d.current){u.current={key:t,body:r};return}d.current=t,a(t),c(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?a_[i.reason]:void 0;c(e?{messageKey:e}:{message:i.error??`HTTP ${t.status}`});return}n(i)}catch(e){c({message:e instanceof Error?e.message:String(e)})}finally{d.current=null,a(null);let e=u.current;u.current=null,e&&p.current?.(e.key,e.body)}})()},[e]);p.current=m;let g=(0,i.useCallback)((e,t,n)=>{m(e,{op:"models",refs:t,enabled:n})},[m]),x=(0,i.useCallback)((e,t)=>{m(`provider:${e}`,{op:"provider",provider:e,enabled:t})},[m]),v=(0,i.useCallback)(()=>m("clear",{op:"clear"}),[m]),b=(0,i.useCallback)(()=>m("prune",{op:"prune"}),[m]),y=(0,i.useCallback)(()=>f(e=>e+1),[]),j=(0,i.useCallback)((e,n)=>{m("resync",{op:"resync",renames:e,modelRenames:n,fullyEnabled:(t?.providers??[]).filter(e=>e.models.length>0&&e.enabledCount===e.models.length).map(e=>e.id)})},[m,t]);return{view:t,loading:r,pending:o,failure:l,setModels:g,setProvider:x,clearScope:v,pruneStale:b,refresh:y,resync:j}}(s),[l,c]=(0,i.useState)({providers:{}}),[d,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(!1),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(!1),[y,j]=(0,i.useState)(a8),[k,w]=(0,i.useState)([]),[S,C]=(0,i.useState)([]),[N,E]=(0,i.useState)(!1),[I,T]=(0,i.useState)(!1),$=(0,i.useRef)(new Set),M=(0,i.useRef)(new Map),R=(0,i.useRef)(new Map),[L,A]=(0,i.useState)(null),P=(0,i.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>{Array.isArray(e.oauthProviders)&&w(e.oauthProviders),Array.isArray(e.apiKeyProviders)&&C(e.apiKeyProviders)}).catch(()=>{}).finally(()=>E(!0))},[]);(0,i.useEffect)(()=>{fetch("/api/models-config").then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);return t}).then(e=>{let t=e.providers?e:{...e,providers:{}};c(t),$.current=new Set(Object.keys(t.providers??{})),R.current=an(t);let n=Object.keys(t.providers??{});j(e=>e&&("provider"===e.type?t.providers?.[e.name]:"model"!==e.type||t.providers?.[e.providerName]?.models?.[e.index])?e:n[0]?{type:"provider",name:n[0]}:null)}).catch(e=>x(e instanceof Error?e.message:String(e))).finally(()=>u(!1)),P()},[P]),(0,i.useEffect)(()=>{y&&o2("models",JSON.stringify(y))},[y]),(0,i.useEffect)(()=>{if(y?.type!=="provider")return;let e=l.providers?.[y.name];e&&1===Object.keys(e).length&&e.modelOverrides&&(k.some(e=>e.id===y.name)?j({type:"oauth",providerId:y.name}):S.some(e=>e.id===y.name)&&j({type:"apikey",providerId:y.name}))},[S,l.providers,k,y]);let z=e=>({overrides:l.providers?.[e]?.modelOverrides,disabled:d||p||null!==g,onChange:(t,n)=>{try{c(function(e,t,n,r){let i={...e.providers},s={...Object.hasOwn(i,t)?i[t]:{}},o={...s.modelOverrides},a=Object.hasOwn(o,n)?o[n]:void 0;if(void 0!==a&&!o8(a))throw Error("Model override must be an object");let l={...a};return void 0===r?delete l.contextWindow:l.contextWindow=r,Object.keys(l).length?Object.defineProperty(o,n,{value:l,enumerable:!0,configurable:!0}):delete o[n],Object.keys(o).length?s.modelOverrides=o:delete s.modelOverrides,Object.keys(s).length?Object.defineProperty(i,t,{value:s,enumerable:!0,configurable:!0}):delete i[t],{...e,providers:i}}(l,e,t,n)),b(!1),m(null)}catch(e){m(String(e))}}}),W=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;l.providers?.[e];)e=`new-provider-${t++}`;c(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),j({type:"provider",name:e})},[l.providers]),O=(0,i.useCallback)((e,t)=>{c(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),D=(0,i.useCallback)((e,t,n)=>{let r=function(e,t,n,r){let i=e.providers??{};if(!Object.hasOwn(i,n))return null;if(n===r)return e;if(Object.hasOwn(i,r))return null;let{renames:s,slots:o}=t,a=ai(t,n);a===r?s.delete(a):null!==a&&s.set(a,r);let l=o.get(n);l&&(o.delete(n),o.set(r,l));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:$.current,renames:M.current,slots:R.current},t,n);return r?(c(r),A(null),j(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},[]),F=(0,i.useCallback)((e,t)=>{D(l,e,t)?m(null):m(o("models.providerNameTaken",{name:t}))},[D,l,o]),B=(0,i.useCallback)(e=>{var t;let n,r,i=(null!==(n=ai(t={savedProviders:$.current,renames:M.current,slots:R.current},e))&&(t.renames.delete(n),t.savedProviders.delete(n)),t.slots.delete(e),r={...l.providers??{}},delete r[e],{...l,providers:r}),s=Object.keys(i.providers??{});A(t=>t?.provider===e?null:t),c(i),j(s.length>0?{type:"provider",name:s[0]}:null)},[l]),H=(0,i.useCallback)(e=>{ar(R.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 j({type:"model",providerName:e,index:n}),t})},[]),U=(0,i.useCallback)((e,t)=>{c(n=>{let r=new Set((n.providers?.[e]?.models??[]).map(e=>e.id));ar(R.current,e,t.filter(e=>!r.has(e.id)).length);let i=n.providers?.[e]??{},s=[...i.models??[]],o=new Set(s.map(e=>e.id));for(let e of t)o.has(e.id)||(o.add(e.id),s.push({...e}));return{...n,providers:{...n.providers??{},[e]:{...i,models:s}}}})},[]),_=(0,i.useCallback)((e,t,n)=>{c(r=>{let i=r.providers?.[e]??{},s=[...i.models??[]];return s[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:s}}}})},[]),q=(0,i.useCallback)((e,t)=>{R.current.get(e)?.splice(t,1),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}}}}),j({type:"provider",name:e})},[]),K=(0,i.useCallback)(async()=>{if(g)return;h(!0),m(null),b(!1);let e=l,t=L?.name.trim();if(L&&t&&l.providers?.[L.provider]){let n=D(l,L.provider,t);if(!n){m(o("models.providerNameTaken",{name:t})),h(!1);return}e=n}try{e=function(e){let t=structuredClone(e);if(!o8(t.providers))return t;for(let[e,n]of Object.entries(t.providers))if(o8(n)&&o8(n.modelOverrides))for(let[t,r]of Object.entries(n.modelOverrides)){if(!o8(r)||!Object.hasOwn(r,"contextWindow"))continue;let n=o6(r.contextWindow);if(void 0===n)throw new o5(`${e}/${t}`);r.contextWindow=n}return t}(e);let t=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json();if(!t.ok||n.error)m(n.error??`HTTP ${t.status}`);else{b(!0),setTimeout(()=>b(!1),2e3);let t=[...M.current].map(e=>{let[t,n]=e;return{from:t,to:n}}),n=function(e,t,n){let r=e=>{for(let[t,r]of n)if(r===e)return t;return e},i=[];for(let[n,s]of Object.entries(e.providers??{})){let e=t.get(n);e&&(s.models??[]).forEach((t,s)=>{let o=e[s];o&&t.id&&o!==t.id&&i.push({from:`${r(n)}/${o}`,to:`${n}/${t.id}`})})}return i}(e,R.current,M.current);$.current=new Set(Object.keys(e.providers??{})),R.current=an(e),M.current.clear(),a.resync(t,n)}}catch(e){m(e instanceof o5?o("models.contextInvalid",{model:e.model}):String(e))}finally{h(!1)}},[D,l,a,g,L,o]),V=Object.entries(l.providers??{}).filter(e=>{let[t,n]=e;if(1!==Object.keys(n).length||!n.modelOverrides)return!0;let r=k.some(e=>e.id===t)||S.some(e=>e.id===t);return N&&!r}),Z=e=>{let t=function(e,t){if(!e||e.allEnabled)return null;let n=aH(e,t);return n?`${n.enabledCount}/${n.models.length}`:null}(a.view,e);return t?(0,r.jsx)("span",{className:"models-sidebar-badge",children:t}):null},J=k.filter(e=>e.loggedIn),G=S.filter(e=>e.configured),Y=(()=>{if(!y)return null;if("oauth"===y.type){let e=k.find(e=>e.id===y.providerId);return e?(0,r.jsx)(lh,{provider:e,onRefresh:P,enabledModels:a,contextSettings:z(e.id)},e.id):null}if("apikey"===y.type){let e=S.find(e=>e.id===y.providerId);return e?(0,r.jsx)(lf,{provider:e,onRefresh:P,enabledModels:a,contextSettings:z(e.id)},e.id):null}if("provider"===y.type){let e=l.providers?.[y.name];return e&&V.some(e=>{let[t]=e;return t===y.name})?(0,r.jsx)(li,{name:y.name,editingName:L?.provider===y.name?L.name:y.name,provider:e,onChange:e=>O(y.name,e),onEditingNameChange:e=>A(e===y.name?null:{provider:y.name,name:e}),onRename:e=>F(y.name,e),onDelete:()=>B(y.name),onAddModels:e=>U(y.name,e),enabledModels:a},y.name):null}let e=l.providers?.[y.providerName],t=e?.models?.[y.index];return t?(0,r.jsx)(lp,{providerName:y.providerName,provider:e,model:t,onChange:e=>_(y.providerName,y.index,e),onDelete:()=>q(y.providerName,y.index)},`${y.providerName}-${y.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(ao,{embedded:n,title:o("common.models"),subtitle:"~/.pi/agent/models.json",closeLabel:o("i18n.close"),onClose:t,children:[(0,r.jsx)(aq,{controller:a}),(0,r.jsxs)(aa,{children:[(0,r.jsxs)(al,{children:[(0,r.jsxs)(ac,{children:[J.map(e=>{let t=y?.type==="oauth"&&y.providerId===e.id;return(0,r.jsxs)(ah,{active:t,onClick:()=>j({type:"oauth",providerId:e.id}),children:[(0,r.jsx)(aX,{id:e.id,size:16}),(0,r.jsx)(af,{className:"is-grow",children:e.name}),Z(e.id)]},e.id)}),G.map(e=>{let t=y?.type==="apikey"&&y.providerId===e.id;return(0,r.jsxs)(ah,{active:t,onClick:()=>j({type:"apikey",providerId:e.id}),children:[(0,r.jsx)(aX,{id:e.id,size:16}),(0,r.jsx)(af,{className:"is-grow",children:e.displayName}),Z(e.id)]},e.id)}),(J.length>0||G.length>0)&&V.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),d?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:o("i18n.loading")}):V.map(e=>{let[t,n]=e,i=y?.type==="provider"&&y.name===t,s=n.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)(ah,{onClick:()=>j({type:"provider",name:t}),active:i,children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)(af,{className:"is-grow",children:t}),Z(t)]}),s.map((e,n)=>{let i=y?.type==="model"&&y.providerName===t&&y.index===n;return(0,r.jsxs)(ah,{active:i,className:"models-sidebar-indented-item",onClick:()=>j({type:"model",providerName:t,index:n}),children:[(0,r.jsx)(af,{className:"is-grow",style:{color:e.id?"var(--text-muted)":"var(--text-dim)"},children:e.id||o("i18n.newModel")}),e.reasoning&&(0,r.jsx)("span",{style:{fontSize:9,padding:"1px 4px",background:"rgba(99,102,241,0.12)",color:"rgba(99,102,241,0.8)",borderRadius:3,flexShrink:0},children:"T"})]},n)}),(0,r.jsx)(ah,{className:"models-sidebar-indented-item models-sidebar-add-item",onClick:e=>{e.stopPropagation(),H(t)},children:(0,r.jsxs)(af,{children:["+ ",o("i18n.model")]})})]},t)})]}),(0,r.jsx)(aW,{onClick:()=>T(!0),children:o("i18n.addProvider")})]}),(0,r.jsx)(aR,{children:(0,r.jsx)(am,{className:"is-fill",children:d?null:Y??(0,r.jsx)(aM,{children:o("i18n.selectProviderModel")})})})]}),(0,r.jsxs)(aL,{status:g||f?(0,r.jsx)("span",{style:{color:"#f87171"},children:g?o("models.configUnreadable",{error:g}):f}):o("models.applyHelp"),children:[!n&&(0,r.jsx)(aP,{onClick:t,children:o("i18n.cancel")}),(0,r.jsxs)(aP,{variant:"primary",onClick:K,disabled:p||v||null!==g,className:v?"is-success":void 0,children:[v&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:v?o("i18n.saved"):p?o("i18n.saving"):o("i18n.save")})]})]})]}),I&&(0,r.jsx)(lm,{oauthProviders:k,apiKeyProviders:S,onSelectOAuth:e=>j({type:"oauth",providerId:e}),onSelectApiKey:e=>j({type:"apikey",providerId:e}),onAddCustom:W,onClose:()=>T(!1)})]})}let lx=null;async function lv(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(lx)return lx;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 lx=null,!1}})();return lx=t,t.then(e=>{e||lx!==t||(lx=null)}),t}function lb(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function ly(e,t){let n=t.replace(/[/\\]+$/,"");return n&&(e===n||e.startsWith(`${n}/`)||e.startsWith(`${n}\\`))?`./${e.slice(n.length).replace(/^[/\\]/,"")}`:lb(e)}function lj(e,t,n,r){return e.filter(e=>n(e)!==t&&(t||!r?.(e)))}function lk(e){return e?JSON.stringify([e.requiresTrust,e.trusted,e.decision,e.decisionPath??null,e.inherited]):""}function lw(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function lS(e,t){return t("project"===e?"skills.scope.project":"global"===e?"skills.scope.global":"skills.scope.path")}function lC(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function lN(e,t){return e?e.slice(0,8):t}function lE(e){let{skill:t,cwd:n,onToggle:s,toggling:o,saveError:a,updateStatus:l,checkingUpdate:c,updating:d,updateError:u,onCheckUpdate:p,onUpdate:h}=e,{t:f}=(0,eO.s)(),m=lw(t),g=!t.disableModelInvocation,[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(null),j=t.filePath.split(/[\\/]/).pop(),[k,w]=(0,i.useState)([]),S=k.at(-1)??j,C=(0,i.useRef)(null),N=(0,i.useRef)(null),[E,I]=(0,i.useState)(0),T=(0,i.useCallback)(e=>{let t=function(e,t){let n=e.indexOf("#"),[r,i]=[n<0?e:e.slice(0,n),n<0?"":e.slice(n+1)].map(e=>{try{return decodeURIComponent(e)}catch{return e}});if(!r)return{document:t,anchor:i};if(r.startsWith("/"))return{document:r,anchor:i};let s=t.split("/").slice(0,-1);for(let e of r.split("/"))".."===e&&s.length&&".."!==s[s.length-1]?s.pop():e&&"."!==e&&s.push(e);return{document:s.join("/"),anchor:i}}(e,S);N.current=t.anchor,t.document===S?I(e=>e+1):w(e=>[...e,t.document])},[S]);return(0,i.useLayoutEffect)(()=>{let e=N.current,t=C.current;null!==e&&(null!==x||b)&&t&&(N.current=null,((e?t.querySelector(`[data-heading-anchor="${CSS.escape(e)}"]`):null)??t).scrollIntoView({block:"start"}))},[x,b,E]),(0,i.useEffect)(()=>{let e=new AbortController;return v(null),y(null),(async()=>{try{var r;let i=new URLSearchParams({cwd:n,filePath:t.filePath});S!==j&&i.set("document",S);let s=await fetch(`/api/skills/content?${i}`,{signal:e.signal}),o=await s.json();if(!s.ok||o.error||"string"!=typeof o.content)throw Error(o.error??`HTTP ${s.status}`);v((r=o.content,od(r).rest.trim()))}catch(t){if(e.signal.aborted)return;y(t instanceof Error?t.message:String(t))}})(),()=>e.abort()},[n,t.filePath,S,j]),(0,r.jsxs)(am,{children:[(0,r.jsxs)("div",{className:"skill-detail-heading",children:[(0,r.jsxs)(ag,{children:[(0,r.jsxs)(ax,{children:[(0,r.jsx)(aS,{scope:m,children:lS(m,f)}),(0,r.jsx)("span",{className:"config-detail-path",children:"project"===m?ly(t.filePath,n):lb(t.filePath)})]}),(0,r.jsx)(av,{children:(0,r.jsx)(az,{checked:g,loading:o,label:f(g?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),onChange:()=>s(t)})})]}),(0,r.jsxs)("div",{className:"skill-detail-status-row",children:[!g&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:f("i18n.hiddenButInvocable")}),a&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:a})]})]}),t.install?.skillsShUrl&&(0,r.jsx)(aj,{label:f("config.source"),children:(0,r.jsx)("a",{href:t.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:t.install.skillsShUrl,className:"skill-source-link",children:(0,r.jsxs)("span",{className:"skill-source-link-text",children:[t.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})}),t.install&&(0,r.jsxs)(aj,{label:f("i18n.version"),children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:lN(l?.currentVersion??t.install.versionHash,f("i18n.unknown"))}),t.install.canCheckForUpdates&&(0,r.jsx)(aP,{size:"small",onClick:p,disabled:c||d,children:f("i18n.check")}),l?.state==="update-available"&&(0,r.jsx)("span",{className:"skill-version-value is-update",children:lN(l.latestVersion,f("i18n.unknown"))}),(c||l&&"update-available"!==l.state)&&(0,r.jsx)("span",{className:`skill-update-status ${c?"is-checking":l?.state==="up-to-date"?"is-success":l?.state==="error"?"is-error":"is-muted"}`,children:c?f("i18n.checking"):l?.state==="up-to-date"?f("i18n.upToDate"):l?.state==="unsupported"?f("i18n.automaticChecksUnavailable"):l?.message||f("i18n.checkFailed")}),l?.state==="update-available"&&(0,r.jsx)(aP,{variant:"primary",size:"small",onClick:h,disabled:d||c,children:f(d?"i18n.updating":"i18n.update")})]}),u&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:u})]}),(0,r.jsx)(aj,{label:f("config.name"),children:(0,r.jsx)("span",{className:"skill-name-value",children:t.name})}),(0,r.jsx)(aj,{label:f("i18n.description"),children:(0,r.jsx)("span",{className:"skill-description",children:t.description})}),(0,r.jsxs)(aj,{label:f("skills.instructions"),ref:C,children:[k.length>0&&(0,r.jsx)(ag,{children:(0,r.jsxs)(ax,{children:[(0,r.jsx)(aP,{size:"small",onClick:()=>{N.current="",w(e=>e.slice(0,-1))},children:f("skills.documentBack")}),(0,r.jsx)("span",{className:"config-detail-path",title:S,children:S})]})}),b?(0,r.jsx)("span",{role:"alert",className:"skill-instructions-status is-error",children:b}):null===x?(0,r.jsx)("span",{role:"status",className:"skill-instructions-status",children:f("i18n.loading")}):x?(0,r.jsx)(ru.m,{className:"skill-instructions",cwd:[t.baseDir,...S.split("/").slice(0,-1)].join("/"),onNavigateLink:T,children:x}):(0,r.jsx)("span",{className:"skill-instructions-status",children:f("skills.noInstructions")})]})]})}function lI(e){let{cwd:t,installedPackages:n,projectResourcesLoaded:s,onInstalled:o}=e,{t:a}=(0,eO.s)(),[l,c]=(0,i.useState)(""),[d,u]=(0,i.useState)([]),[p,h]=(0,i.useState)(!1),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(null),[y,j]=(0,i.useState)(new Set),[k,w]=(0,i.useState)("global"),S=(0,i.useRef)(null);(0,i.useEffect)(()=>{S.current?.focus()},[]);let C=(0,i.useCallback)(async e=>{if(e.trim()){h(!0),m(null),u([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),n=await t.json();if(n.error)return void m(n.error);u(n.results??[]),0===(n.results??[]).length&&m(a("i18n.noSkills"))}catch(e){m(String(e))}finally{h(!1)}}},[a]),N=(0,i.useCallback)(async e=>{x(e),b(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:e,scope:k,cwd:t})}),r=await n.json();if(!n.ok||r.error)return void b(r.error??`HTTP ${n.status}`);j(t=>new Set(t).add(`${k}:${e}`)),o()}catch(e){b(String(e))}finally{x(null)}},[o,k,t]),E="global"===k?"~/.pi/agent/skills/":`${lb(t)}/.pi/skills/`;return(0,r.jsxs)(am,{className:"is-full-height",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)(aE,{title:a("i18n.addSkill"),catalogs:[{href:"https://skills.sh",label:"skills.sh"}],target:(0,r.jsx)(aN,{value:k,label:a("config.saveTo"),options:[{value:"global",label:lS("global",a)},{value:"project",label:lS("project",a),disabled:!s}],path:E,disabledReason:a("trust.projectScopeUnavailable"),onChange:w})}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:S,value:l,onChange:e=>c(e.target.value),onKeyDown:e=>{"Enter"===e.key&&C(l)},placeholder:a("i18n.skillSearchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:12,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",outline:"none"}}),(0,r.jsx)(aP,{variant:"primary",onClick:()=>C(l),disabled:p||!l.trim(),children:p?a("i18n.searching"):a("i18n.search")})]}),f&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:f}),v&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:v})]}),d.length>0&&(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:d.map(e=>{let t=n[k].has(e.package)||y.has(`${k}:${e.package}`),i=g===e.package,s=e.package.indexOf("@"),o=s>-1?e.package.slice(0,s):e.package,l=s>-1?e.package.slice(s+1):null;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:l??o}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:o}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,r.jsx)(aP,{size:"small",onClick:()=>!t&&!i&&N(e.package),disabled:t||i||null!==g,style:{flexShrink:0,background:t?"rgba(34,197,94,0.1)":"none",color:t?"#16a34a":i?"var(--accent)":"var(--text-muted)"},children:t?`✓ ${a("i18n.installed")}`:i?a("i18n.installing"):a("i18n.install")})]},e.package)})})]})}function lT(e){let{cwd:t,onClose:n,embedded:s=!1,trust:o}=e,{t:a}=(0,eO.s)(),[l,c]=(0,i.useState)([]),[d,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(()=>o1("skills",t)),[g,x]=(0,i.useState)(new Set),[v,b]=(0,i.useState)(null),[y,j]=(0,i.useState)(null),[k,w]=(0,i.useState)(null),[S,C]=(0,i.useState)(!1),[N,E]=(0,i.useState)({}),[I,T]=(0,i.useState)(new Set),[$,M]=(0,i.useState)(!1),[R,L]=(0,i.useState)(null),[A,P]=(0,i.useState)(null),[z,W]=(0,i.useState)(!0),O=(0,i.useCallback)(async()=>{u(!0),h(null);try{let e=await fetch(`/api/skills?cwd=${encodeURIComponent(t)}`),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);let r=n.skills??[];return c(r),W(n.projectResourcesLoaded??!0),m(e=>{if(e&&r.some(t=>t.filePath===e))return e;let t=r.find(e=>!e.disableModelInvocation)??r[0];return t?.filePath??null}),r}catch(e){return h(String(e)),[]}finally{u(!1)}},[t]);(0,i.useEffect)(()=>{E({}),P(null),O()},[t]);let D=lk(o),F=(0,i.useRef)(D);(0,i.useEffect)(()=>{F.current!==D&&(F.current=D,O())},[D,O]),(0,i.useEffect)(()=>{f&&o2("skills",f,t)},[t,f]);let B=(0,i.useCallback)(async e=>{let n=(e?[e]:l.filter(e=>!!e.install)).map(lC).filter(e=>!!e);if(0!==n.length){P(null),T(e=>new Set([...e,...n])),e||M(!0);try{let n=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,package:e?.install?.package,scope:e?.install?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);E(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){P(e instanceof Error?e.message:String(e))}finally{T(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),e||M(!1)}}},[t,l]),H=(0,i.useCallback)(async e=>{if(!e.install)return;let n=lC(e);L(n),P(null);try{let r=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,package:e.install.package,scope:e.install.scope})}),i=await r.json();if(!r.ok||i.error||!i.success)throw Error(i.error??`HTTP ${r.status}`);await O();let s=i.skill?.install?.versionHash;E(t=>({...t,[n]:{package:e.install.package,scope:e.install.scope,state:"up-to-date",currentVersion:s,latestVersion:s}}))}catch(e){P(e instanceof Error?e.message:String(e))}finally{L(null)}},[t,O]),U=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;x(t=>new Set(t).add(e.filePath)),b(null),w(null);try{let n=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),r=await n.json();if(!n.ok||r.error)return void b(r.error??`HTTP ${n.status}`);c(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n))}catch(e){b(String(e))}finally{x(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),_=(0,i.useCallback)(async(e,t,n)=>{let r=lj(t,n,e=>!e.disableModelInvocation);if(0===r.length)return;let i=r.map(e=>e.filePath),s=!n;x(e=>new Set([...e,...i])),j(e),b(null),w(null);try{let t=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePaths:i,disableModelInvocation:s})}),n=await t.json();if(!t.ok||n.error||!n.results)throw Error(n.error??`HTTP ${t.status}`);let o=n.results;c(e=>{let t;return t=new Set(o.filter(e=>!e.error).map(e=>e.filePath)),e.map(e=>t.has(e.filePath)?{...e,disableModelInvocation:s}:e)});let l=o.filter(e=>e.error);if(l.length>0){let t=new Map(r.map(e=>[e.filePath,e.name]));w({group:e,error:[a("skills.bulkFailed",{count:l.length,total:o.length}),...l.map(e=>`${t.get(e.filePath)??e.filePath}: ${e.error}`)].join("\n")})}}catch(t){w({group:e,error:t instanceof Error?t.message:String(t)})}finally{j(null),x(e=>{let t=new Set(e);for(let e of i)t.delete(e);return t})}},[a]),q=l.find(e=>e.filePath===f)??null,K=d||g.size>0||null!==R;return(0,r.jsxs)(ao,{embedded:s,title:a("common.skills"),subtitle:lb(t),closeLabel:a("i18n.close"),onClose:n,children:[!z&&(0,r.jsx)(a$,{message:a("trust.skillsNotLoaded")}),(0,r.jsxs)(aa,{children:[(0,r.jsxs)(al,{children:[(0,r.jsx)(ac,{children:d?(0,r.jsx)("div",{className:"config-sidebar-message",children:a("i18n.loading")}):p?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:p}):0===l.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:a("i18n.noSkills")}):(()=>{let e=[],t={project:a("skills.scope.project"),global:a("skills.scope.global"),path:a("skills.scope.path")};for(let{label:n,matches:r}of[{label:`${t.project} / skills.sh`,matches:e=>"project"===lw(e)&&!!e.install?.skillsShUrl},{label:t.project,matches:e=>"project"===lw(e)&&!e.install?.skillsShUrl},{label:`${t.global} / skills.sh`,matches:e=>"global"===lw(e)&&!!e.install?.skillsShUrl},{label:t.global,matches:e=>"global"===lw(e)&&!e.install?.skillsShUrl},{label:t.path,matches:e=>"path"===lw(e)}]){let t=l.filter(r);t.length>0&&e.push({label:n,skills:t})}let n=e=>{let t,n,i=!S&&f===e.filePath,s=e.disableModelInvocation;return(0,r.jsxs)(ah,{active:i,onClick:()=>{m(e.filePath),C(!1)},children:[(0,r.jsx)(aO,{active:!s}),(0,r.jsx)(af,{className:`is-grow${s?" is-muted":""}`,children:e.name}),(n=(t=lC(e))?N[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:a("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"}))]},e.filePath)};return e.map(e=>{let{label:t,skills:i}=e,s=i.filter(e=>!e.disableModelInvocation).length,o=s===i.length;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(ad,{aside:(0,r.jsx)(au,{enabled:s,total:i.length,disabled:K,loading:y===t,label:a(o?"skills.groupSwitchOn":"skills.groupSwitchOff",{group:t}),onChange:e=>void _(t,i,e)}),children:t}),k?.group===t&&(0,r.jsx)(ap,{error:k.error}),[...i.filter(e=>!e.disableModelInvocation),...i.filter(e=>e.disableModelInvocation)].map(n)]},t)})})()}),(0,r.jsx)(aW,{onClick:()=>C(!0),active:S,children:a("i18n.addSkill")})]}),(0,r.jsx)(aR,{children:(0,r.jsx)(am,{className:"is-fill",children:S?(0,r.jsx)(lI,{cwd:t,projectResourcesLoaded:z,installedPackages:{global:new Set(l.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(l.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{O()}}):d?null:q?(0,r.jsx)(lE,{skill:q,cwd:t,onToggle:U,toggling:g.has(q.filePath),saveError:v,updateStatus:lC(q)?N[lC(q)]:void 0,checkingUpdate:!!lC(q)&&I.has(lC(q)),updating:R===lC(q),updateError:A,onCheckUpdate:()=>void B(q),onUpdate:()=>void H(q)},q.filePath):(0,r.jsx)(aM,{children:a("i18n.selectSkill")})})})]}),(0,r.jsxs)(aL,{status:Object.values(N).filter(e=>"update-available"===e.state).length>0&&(0,r.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(N).filter(e=>"update-available"===e.state).length," ",1===Object.values(N).filter(e=>"update-available"===e.state).length?a("i18n.update"):a("i18n.updates")]}),children:[!s&&(0,r.jsx)(aP,{onClick:n,children:a("i18n.close")}),l.some(e=>!!e.install)&&(0,r.jsx)(aP,{variant:"secondary",onClick:()=>void B(),disabled:$||null!==R,children:$?a("i18n.checking"):a("i18n.checkUpdates")})]})]})}let l$={builtin:0,global:1,workspace:2,project:3},lM=["read","bash","edit","write","grep","find","ls"],lR=["","off","minimal","low","medium","high","xhigh","max"],lL={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},lA={width:"100%",minWidth:0,height:34,padding:"0 9px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text)",fontSize:12,outline:"none"},lP={background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"default"};function lz(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 lW(e){return`${e.scope}:${e.name}`}function lO(e){return"global"===e||"project"===e}function lD(e){return lO(e)||"builtin"===e}function lF(e){let{label:t,children:n}=e;return(0,r.jsx)(aj,{label:t,children:n})}function lB(e){let{checked:t,disabled:n,label:i,onChange:s}=e;return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:7,color:n?"var(--text-dim)":"var(--text-muted)",fontSize:12,cursor:n?"default":"pointer"},children:[(0,r.jsx)("input",{type:"checkbox",checked:t,disabled:n,onChange:e=>s(e.target.checked)}),i]})}function lH(e){let{cwd:t,sessionId:n=null,onClose:s,onReloaded:o,embedded:a=!1,trust:l}=e,c=(0,eD.a)(),{t:d}=(0,eO.s)(),[u,p]=(0,i.useState)([]),[h,f]=(0,i.useState)([]),[m,g]=(0,i.useState)(!0),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(()=>o1("agents",t)),[j,k]=(0,i.useState)(lL),[w,S]=(0,i.useState)("view"),[C,N]=(0,i.useState)("global"),[E,I]=(0,i.useState)(!0),[T,$]=(0,i.useState)(!1),[M,R]=(0,i.useState)(!1),[L,A]=(0,i.useState)(!1),[P,z]=(0,i.useState)(null),[W,O]=(0,i.useState)(!1),[D,F]=(0,i.useState)(10),[B,H]=(0,i.useState)(!0),[U,_]=(0,i.useState)(!1),[q,K]=(0,i.useState)(null),[V,Z]=(0,i.useState)(!1),[J,G]=(0,i.useState)(!1),Y=(0,i.useMemo)(()=>u.find(e=>lW(e)===b)??null,[u,b]),X=(0,i.useMemo)(()=>h.map(e=>({provider:e.provider,modelId:e.id,name:e.name})),[h]),Q=(0,i.useCallback)(async e=>{I(!0),z(null);try{let n=await fetch(`/api/subagents/profiles?cwd=${encodeURIComponent(t)}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);let i=r.profiles??[];p(i);let s=e??o1("agents",t),o=i.find(e=>lW(e)===s)??i.find(e=>"project"===e.scope)??i.find(e=>"global"===e.scope)??i[0]??null;y(o?lW(o):null),o&&(k(lz(o)),S(lO(o.scope)?"edit":"view"),lO(o.scope)&&N(o.scope))}catch(e){z(e instanceof Error?e.message:String(e))}finally{I(!1)}},[t]);(0,i.useEffect)(()=>{Q()},[Q]),(0,i.useEffect)(()=>{let e=new AbortController;return H(!0),K(null),(async()=>{try{let t=await fetch("/api/subagents/settings",{cache:"no-store",signal:e.signal}),n=await t.json();if(!t.ok||n.error||"boolean"!=typeof n.enabled)throw Error(n.error??`HTTP ${t.status}`);O(n.enabled),"number"==typeof n.maxConcurrent&&F(n.maxConcurrent)}catch(t){if(e.signal.aborted)return;K(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||H(!1)}})(),()=>e.abort()},[]),(0,i.useEffect)(()=>{b&&o2("agents",b,t)},[t,b]);let ee=lk(l);(0,i.useEffect)(()=>{let e=new AbortController;return g(!0),v(null),(async()=>{try{let n=await fetch(`/api/models?cwd=${encodeURIComponent(t)}`,{signal:e.signal}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);f(r.modelList??[]),v(r.modelError??null)}catch(t){if(e.signal.aborted)return;v(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||g(!1)}})(),()=>e.abort()},[t,ee]);let et=async()=>{$(!0),z(null),R(!1);try{let e=await fetch("/api/subagents/profiles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:C,profile:j})}),n=await e.json();if(!e.ok||n.error||!n.profile)throw Error(n.error??`HTTP ${e.status}`);await Q(lW(n.profile)),R(!0),setTimeout(()=>R(!1),2e3)}catch(e){z(e instanceof Error?e.message:String(e))}finally{$(!1)}},en=async()=>{if(Y&&lO(Y.scope)&&window.confirm(d("agents.deleteConfirm",{name:Y.displayName}))){$(!0),z(null);try{let e=await fetch("/api/subagents/profiles",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:Y.scope,name:Y.name})}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);await Q()}catch(e){z(e instanceof Error?e.message:String(e))}finally{$(!1)}}},er="view"!==w,ei="create"===w,es=!er||T||L,eo=ei?C:Y?.scope,ea=ei?"global"===C?`~/.pi/agent/agents/${j.name||"..."}.md`:`./.pi/agents/${j.name||"..."}.md`:Y?(Y.filePath?"project"===Y.scope||"workspace"===Y.scope?ly(Y.filePath,t):lb(Y.filePath):null)??d("agents.builtinPath"):"",el=ei?ea:Y?.filePath??ea,ec=e=>h.some(t=>`${t.provider}/${t.id}`===e),ed=j.model&&function(e,t){if(t(e))return e;let n=e.lastIndexOf(":"),r=e.slice(n+1);return n>0&&r&&lR.includes(r)?e.slice(0,n):e}(j.model,ec),eu=!ed||ec(ed),ep=(()=>{if(!ed)return null;let e=ed.indexOf("/");return e<0?{provider:"",modelId:ed}:{provider:ed.slice(0,e),modelId:ed.slice(e+1)}})(),eh=es?{...lA,...lP}:lA,ef=ei?es:!Y||!lD(Y.scope)||T||L,em=(e,t)=>{k(n=>({...n,[e]:t}))},eg=0===j.tools.length&&!j.loadSkills&&!j.loadExtensions,ex=async e=>{if(ei)return void em("enabled",e);if(Y&&lD(Y.scope)){A(!0),z(null);try{let n=await fetch("/api/subagents/profiles",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:Y.scope,name:Y.name,enabled:e})}),r=await n.json();if(!n.ok||r.error||!r.profile)throw Error(r.error??`HTTP ${n.status}`);let i=r.profile;p(e=>e.map(e=>lW(e)===lW(i)?i:e)),k(e=>({...e,enabled:i.enabled}))}catch(e){z(e instanceof Error?e.message:String(e))}finally{A(!1)}}},ev=async e=>{_(!0),K(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),r=await t.json();if(!t.ok||r.error||"boolean"!=typeof r.enabled)throw Error(r.error??`HTTP ${t.status}`);O(r.enabled),Z(!!n)}catch(e){K(e instanceof Error?e.message:String(e))}finally{_(!1)}},eb=async e=>{F(e),K(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxConcurrent:e})}),n=await t.json();if(!t.ok||n.error||"number"!=typeof n.maxConcurrent)throw Error(n.error??`HTTP ${t.status}`);F(n.maxConcurrent)}catch(e){K(e instanceof Error?e.message:String(e))}},ey=async()=>{if(n){G(!0),K(null);try{await sa(n,{type:"reload"}),Z(!1),o?.()}catch(e){K(e instanceof Error?e.message:String(e))}finally{G(!1)}}};return(0,r.jsxs)(ao,{embedded:a,title:d("common.agents"),subtitle:lb(t),closeLabel:d("agents.close"),onClose:s,children:[(0,r.jsxs)("div",{className:"agents-feature-setting",children:[(0,r.jsxs)("div",{className:"agents-feature-copy",children:[(0,r.jsx)("strong",{children:d("agents.builtInTitle")}),(0,r.jsx)("span",{children:d("agents.builtInDescription")}),V&&(0,r.jsx)("span",{role:"status",className:"agents-feature-reload-notice",children:d("agents.reloadRequired")})]}),(0,r.jsxs)("div",{className:"agents-feature-actions",children:[V&&n&&(0,r.jsx)(aP,{size:"small",onClick:()=>void ey(),disabled:J||U,children:J?d("agents.reloading"):d("agents.reloadSession")}),(0,r.jsxs)("label",{className:"agents-concurrency-control",title:d("agents.maxConcurrentDescription"),children:[(0,r.jsx)("span",{children:d("agents.maxConcurrent")}),(0,r.jsx)("input",{"aria-label":d("agents.maxConcurrent"),type:"number",min:1,max:32,value:D,disabled:B||U,onChange:e=>F(Number(e.target.value)),onBlur:()=>void eb(D)})]}),(0,r.jsx)(az,{checked:W,disabled:B||J,loading:U,label:d("agents.builtInTitle"),onChange:e=>void ev(e)})]})]}),(0,r.jsxs)(aa,{children:[(0,r.jsxs)(al,{children:[(0,r.jsx)(ac,{children:E?(0,r.jsx)("div",{style:{padding:10,color:"var(--text-dim)",fontSize:12},children:d("agents.loading")}):["project","global","workspace","builtin"].map(e=>{let t=u.filter(t=>t.scope===e);return 0===t.length?null:(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(ad,{children:d(`agents.scope.${e}`)}),t.map(e=>{let t,n,i=(t=e.name.toLowerCase(),n=l$[e.scope],u.some(e=>e.name.toLowerCase()===t&&l$[e.scope]>n));return(0,r.jsxs)(ah,{active:b===lW(e)&&!ei,onClick:()=>{y(lW(e)),k(lz(e)),S(lO(e.scope)?"edit":"view"),lO(e.scope)&&N(e.scope),z(null)},children:[(0,r.jsx)(aO,{active:e.enabled}),(0,r.jsx)(af,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.displayName}),i&&(0,r.jsx)("span",{className:"agents-overridden-label",children:d("agents.overridden")})]},lW(e))})]},e)})}),(0,r.jsx)(aW,{active:ei,onClick:()=>{let e="custom-agent",t=2;for(;u.some(t=>t.name===e);)e=`custom-agent-${t++}`;y(null),k({...lL,name:e,displayName:e}),S("create"),N("global"),z(null)},children:d("agents.new")})]}),(0,r.jsx)(aR,{children:(0,r.jsx)(am,{className:"is-fill",children:Y||ei?(0,r.jsxs)(am,{children:[(0,r.jsxs)(ag,{children:[(0,r.jsx)(ax,{children:ei?(0,r.jsx)(aN,{value:C,label:d("config.saveTo"),options:["global","project"].map(e=>({value:e,label:d(`agents.scope.${e}`),disabled:T})),path:ea,onChange:N}):(0,r.jsxs)(r.Fragment,{children:[eo&&(0,r.jsx)(aS,{scope:eo,children:d(`agents.scope.${eo}`)}),(0,r.jsx)("span",{title:el,className:"config-detail-path",children:ea})]})}),(0,r.jsxs)(av,{children:[Y&&("view"===w||"edit"===w)&&(0,r.jsx)(aP,{size:"small",onClick:()=>{if(!Y)return;let e=function(e,t){let n=new Set(t.map(e=>e.name.toLowerCase())),r=`${e}-copy`,i=r,s=2;for(;n.has(i.toLowerCase());)i=`${r}-${s++}`;return i}(Y.name,u);y(null),k({...lz(Y),name:e,displayName:d("agents.copyName",{name:Y.displayName})}),S("create"),N(lO(Y.scope)?Y.scope:"global"),z(null)},disabled:T||L,children:d("agents.duplicate")}),Y&&lO(Y.scope)&&"edit"===w&&(0,r.jsx)(aP,{variant:"danger",size:"small",onClick:()=>void en(),disabled:T||L,children:d("agents.delete")}),(0,r.jsx)(az,{checked:j.enabled,disabled:ef,label:j.enabled?d("agents.disable"):d("agents.enable"),onChange:e=>void ex(e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:c?"1fr":"minmax(0, 1fr) minmax(0, 1fr)",gap:12},children:[(0,r.jsx)(lF,{label:d("agents.name"),children:ei?(0,r.jsx)("input",{"aria-label":d("agents.name"),value:j.name,disabled:es,onChange:e=>em("name",e.target.value),style:lA}):(0,r.jsx)("code",{style:{minHeight:34,display:"flex",alignItems:"center",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:j.name})}),(0,r.jsx)(lF,{label:d("agents.displayName"),children:(0,r.jsx)("input",{"aria-label":d("agents.displayName"),value:j.displayName,disabled:es,onChange:e=>em("displayName",e.target.value),style:eh})})]}),(0,r.jsx)(lF,{label:d("agents.description"),children:(0,r.jsx)("input",{"aria-label":d("agents.description"),value:j.description,disabled:es,onChange:e=>em("description",e.target.value),style:eh})}),(0,r.jsx)(lF,{label:d("agents.prompt"),children:(0,r.jsx)("textarea",{className:"agents-system-prompt","aria-label":d("agents.prompt"),value:j.systemPrompt,disabled:es,onChange:e=>em("systemPrompt",e.target.value),style:{...eh,height:195,minHeight:195,maxHeight:"60vh",padding:9,overflow:"auto",resize:es?"none":"vertical",lineHeight:1.5}})}),(0,r.jsx)(lF,{label:d("agents.tools"),children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 16px"},children:lM.map(e=>(0,r.jsx)(lB,{label:e,disabled:es,checked:j.tools.includes(e),onChange:t=>em("tools",t?[...j.tools,e]:j.tools.filter(t=>t!==e))},e))})}),(0,r.jsxs)(lF,{label:d("agents.resources"),children:[(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 20px"},children:[(0,r.jsx)(lB,{label:d("agents.loadSkills"),disabled:es,checked:j.loadSkills,onChange:e=>em("loadSkills",e)}),(0,r.jsx)(lB,{label:d("agents.loadExtensions"),disabled:es,checked:j.loadExtensions,onChange:e=>em("loadExtensions",e)}),(0,r.jsx)(lB,{label:d("agents.mcp"),disabled:es||eg&&"on"!==j.mcp,checked:"on"===j.mcp,onChange:e=>em("mcp",e?"on":"off")})]}),j.loadSkills&&void 0!==j.skills&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:j.skills.length>0?d("agents.skillsOnly",{skills:j.skills.join(", ")}):d("agents.skillsNone")}),j.loadExtensions&&void 0!==j.extensions&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:j.extensions.length>0?d("agents.extensionsOnly",{extensions:j.extensions.join(", ")}):d("agents.extensionsNone")}),!es&&eg?(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:d("agents.mcpChatOnly")}):"on"===j.mcp&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:d("agents.mcpHint")})]}),(0,r.jsx)(lF,{label:d("agents.codemode"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[(0,r.jsxs)("select",{"aria-label":d("agents.codemode"),value:j.codemode??"off",disabled:es,onChange:e=>em("codemode",e.target.value),style:{...eh,width:"auto",minWidth:180,alignSelf:"flex-start"},children:[(0,r.jsx)("option",{value:"inherit",children:d("agents.codemode.inherit")}),(0,r.jsx)("option",{value:"on",children:d("agents.codemode.on")}),(0,r.jsx)("option",{value:"off",children:d("agents.codemode.off")})]}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:d("agents.codemodeHint")})]})}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:c?"1fr":"minmax(0, 1.5fr) minmax(120px, 0.75fr) minmax(100px, 0.5fr)",gap:12},children:[(0,r.jsx)(lF,{label:d("agents.model"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(ih,{options:X,value:ep,onChange:(e,t)=>em("model",`${e}/${t}`),onClear:()=>em("model",void 0),emptyLabel:m?d("agents.modelsLoading"):d("agents.inherit"),selectedLabel:j.model&&!eu?d("agents.modelUnavailable",{model:j.model}):j.model!==ed?j.model:void 0,disabled:es||m||0===h.length&&!j.model,ariaLabel:d("agents.model"),variant:"field",placement:"auto"}),x&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:10},children:x})]})}),(0,r.jsx)(lF,{label:d("agents.thinking"),children:(0,r.jsx)("select",{"aria-label":d("agents.thinking"),value:j.thinking??"",disabled:es,onChange:e=>em("thinking",e.target.value||void 0),style:eh,children:lR.map(e=>(0,r.jsx)("option",{value:e,children:e||d("agents.inherit")},e||"default"))})}),(0,r.jsx)(lF,{label:d("agents.maxTurns"),children:(0,r.jsx)("input",{"aria-label":d("agents.maxTurns"),type:"number",min:1,value:j.maxTurns??"",disabled:es,onChange:e=>em("maxTurns",e.target.value?Number(e.target.value):void 0),style:eh})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"10px 20px"},children:[(0,r.jsx)(lB,{label:d("agents.inheritContext"),disabled:es,checked:j.inheritContext,onChange:e=>em("inheritContext",e)}),(0,r.jsx)(lB,{label:d("agents.background"),disabled:es,checked:j.runInBackground,onChange:e=>em("runInBackground",e)})]})]}):(0,r.jsx)(aM,{children:d("agents.empty")})})})]}),(0,r.jsx)(aL,{status:(q||P)&&(0,r.jsx)("span",{role:"alert",style:{color:"#ef4444"},children:q||P}),children:er&&(0,r.jsxs)(aP,{variant:"primary",onClick:()=>void et(),disabled:T||M||L||!j.name.trim(),className:M?"is-success":void 0,children:[M&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:M?d("i18n.saved"):T?d("agents.saving"):d("agents.save")})]})})]})}let lU=["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"];function l_(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function lq(e){return`${e.scope}\0${e.source}`}function lK(e){return`extension\0${e.path}`}function lV(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function lZ(e,t){return t(`plugins.status.${e}`)}function lJ(e){return`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`}function lG(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function lY(e){let{pkg:t}=e,{t:n}=(0,eO.s)(),i=[["extension",n("i18n.extensions")],["skill",n("i18n.skills")],["prompt",n("i18n.prompts")],["theme",n("i18n.themes")]].map(e=>{let[n,r]=e;return{kind:n,label:r,resources:t.resources.filter(e=>e.kind===n)}}).filter(e=>e.resources.length>0);return 0===i.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:n(t.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:i.map((e,t)=>(0,r.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function lX(e){let{cwd:t,source:n,scope:i,projectResourcesLoaded:s,busy:o,actionError:a,onSourceChange:l,onScopeChange:c,onInstall:d}=e,{t:u}=(0,eO.s)();return(0,r.jsx)(aI,{title:u("i18n.addPlugin"),catalogs:[{href:"https://pi.dev/packages",label:"pi.dev/packages",icon:(0,r.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",children:[(0,r.jsx)("path",{fill:"#000",fillRule:"evenodd",d:"M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"}),(0,r.jsx)("path",{fill:"#000",d:"M517.36 400H634.72V634.72H517.36Z"})]})}],target:(0,r.jsx)(aN,{value:i,label:u("config.saveTo"),options:[{value:"global",label:lV("global",u)},{value:"project",label:lV("project",u),disabled:!s}],path:"project"===i?`${lb(t)}/.pi/{npm,git}`:"~/.pi/agent/{npm,git}",disabledReason:u("trust.projectScopeUnavailable"),onChange:c}),inputLabel:u("config.source"),inputId:"plugin-source",placeholder:"npm:@scope/package",value:n,canSubmit:!o&&!!n.trim(),normalizeValue:l_,onValueChange:l,onSubmit:d,examplesLabel:u("config.examples"),examples:lU,error:a,children:(0,r.jsx)(aP,{variant:"primary",onClick:d,disabled:o||!n.trim(),className:"is-pushed-right",children:u(o?"i18n.installing":"i18n.install")})})}function lQ(e){let t,{pkg:n,cwd:s,busyKey:o,actionError:a,actionMessage:l,sessionId:c,updateStatus:d,checkingUpdate:u,updateError:p,onAction:h,onCheckUpdate:f,onReloadSession:m}=e,{t:g}=(0,eO.s)(),x=lq(n),v=(o?.endsWith(x)||o?.startsWith("bulk:"))??!1,b="reload"===o,y=!n.disabled,j=n.canCheckForUpdates,k=d?.state==="update-available",w=n.description?.trim(),S=(0,i.useId)();return(0,r.jsxs)(am,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(ag,{className:"is-top-aligned",children:[(0,r.jsxs)(ax,{children:[(0,r.jsx)(aS,{scope:n.scope,children:lV(n.scope,g)}),n.disabled?(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:g("i18n.disabled")}):n.filtered&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:g("i18n.filtered")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.source})]}),(0,r.jsxs)(av,{children:[(0,r.jsx)(aP,{size:"small",variant:k?"primary":void 0,onClick:k||!j?()=>h("update",n):f,disabled:v||b||u,title:k?g("i18n.updateAvailable"):void 0,children:g(o===`update:${x}`?"i18n.updating":u?"i18n.checking":k||!j?"i18n.update":"i18n.check")}),(0,r.jsx)(aP,{size:"small",onClick:m,disabled:!c||b||v,"aria-describedby":c?void 0:S,children:g(b?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)(aP,{variant:"danger",size:"small",onClick:()=>h("remove",n),disabled:v||b,children:g(o===`remove:${x}`?"i18n.removing":"i18n.remove")}),(0,r.jsx)(az,{checked:y,loading:v||b,onChange:()=>h(n.disabled?"enable":"disable",n),label:g(n.disabled?"i18n.enablePackage":"i18n.disablePackage")})]})]}),!c&&(0,r.jsx)("div",{id:S,className:"config-detail-heading-note",children:g("i18n.openSessionToReload")})]}),(0,r.jsxs)(ak,{children:[w&&(0,r.jsx)(aw,{label:g("i18n.description"),children:w}),(0,r.jsx)(aw,{label:g("i18n.status"),tone:"plain",style:{color:lG(n.status),textTransform:"capitalize"},children:lZ(n.status,g)}),(0,r.jsxs)(aw,{label:g("i18n.version"),tone:"plain",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:(t=[],n.version&&t.push(g("i18n.installedVersion",{version:n.version})),n.configuredVersion&&t.push(g("i18n.configuredVersion",{version:n.configuredVersion})),t.length?t.join(" \xb7 "):g("i18n.unknown"))}),k&&(0,r.jsx)("span",{className:"skill-version-value is-update",title:d.displayName,children:g("i18n.updateAvailable")}),j&&(u||d&&!k)&&(0,r.jsx)("span",{className:`skill-update-status ${u?"is-checking":d?.state==="up-to-date"?"is-success":d?.state==="error"?"is-error":"is-muted"}`,children:u?g("i18n.checking"):d?.state==="up-to-date"?g("i18n.upToDate"):d?.state==="unsupported"?g("i18n.automaticChecksUnavailable"):d?.message||g("i18n.checkFailed")})]}),p&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:p})]}),(0,r.jsx)(aw,{label:g("i18n.package"),mono:!0,children:n.packageName??g("i18n.unknown")}),(0,r.jsx)(aw,{label:g("i18n.resources"),children:function(e,t){if(e.disabled)return t("i18n.disabled");let n=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t("i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t("i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t("i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t("i18n.themeShort")}):""].filter(Boolean);return n.length?n.join(" \xb7 "):t("i18n.noResources")}(n,g)}),(0,r.jsx)(aw,{label:g("i18n.installedPath"),tone:n.installedPath?"muted":"error",mono:!0,children:n.installedPath?lb(n.installedPath):g("i18n.notFound")}),(0,r.jsx)(aw,{label:g("i18n.cwd"),tone:"dim",mono:!0,children:lb(s)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)(ay,{children:g("i18n.resolvedResources")}),(0,r.jsx)(lY,{pkg:n})]}),l&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:l}),a&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:a})]})}function l0(e){let{extension:t}=e,{t:n}=(0,eO.s)(),i=t.enabled?"loaded":"disabled";return(0,r.jsxs)(am,{children:[(0,r.jsx)(ag,{children:(0,r.jsxs)(ax,{children:[(0,r.jsx)(aS,{scope:t.scope,children:lV(t.scope,n)}),(0,r.jsx)(ab,{children:t.name})]})}),(0,r.jsxs)(ak,{children:[(0,r.jsx)(aw,{label:n("i18n.status"),tone:"plain",style:{color:t.enabled?"var(--accent)":"var(--text-dim)"},children:lZ(i,n)}),(0,r.jsx)(aw,{label:n("i18n.installedPath"),mono:!0,children:lb(t.path)})]})]})}function l1(e){var t;let{cwd:n,sessionId:s,onClose:o,onReloaded:a,embedded:l=!1,trust:c}=e,{t:d}=(0,eO.s)(),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!0),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(()=>o1("plugins",n)),[b,y]=(0,i.useState)(!1),[j,k]=(0,i.useState)(""),[w,S]=(0,i.useState)("global"),[C,N]=(0,i.useState)(null),[E,I]=(0,i.useState)(null),[T,$]=(0,i.useState)(null),[M,R]=(0,i.useState)(null),[L,A]=(0,i.useState)({}),[P,z]=(0,i.useState)(new Set),[W,O]=(0,i.useState)(!1),[D,F]=(0,i.useState)(null),[B,H]=(0,i.useState)(!1),U=(0,i.useMemo)(()=>u?.packages??[],[u?.packages]),_=(0,i.useMemo)(()=>u?.standaloneExtensions??[],[u?.standaloneExtensions]),q=U.find(e=>lq(e)===x)??null,K=_.find(e=>lK(e)===x)??null,V=u?.projectResourcesLoaded??!0,Z=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:U.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[U]),J=(0,i.useCallback)(async()=>{f(!0),g(null),R(null);try{let e=await fetch(`/api/plugins?cwd=${encodeURIComponent(n)}`),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);p(t),y(e=>0===t.packages.length&&0===t.standaloneExtensions.length||e),v(e=>e&&(t.packages.some(t=>lq(t)===e)||t.standaloneExtensions.some(t=>lK(t)===e))?e:t.packages[0]?lq(t.packages[0]):t.standaloneExtensions[0]?lK(t.standaloneExtensions[0]):null)}catch(e){g(e instanceof Error?e.message:String(e))}finally{f(!1)}},[n]);(0,i.useEffect)(()=>{A({}),F(null),J()},[n]);let G=lk(c),Y=(0,i.useRef)(G);(0,i.useEffect)(()=>{Y.current!==G&&(Y.current=G,J())},[G,J]),(0,i.useEffect)(()=>{x&&o2("plugins",x,n)},[n,x]);let X=(0,i.useCallback)(async e=>{let t=(e?[e]:U.filter(e=>e.canCheckForUpdates)).map(lq);if(0!==t.length){F(null),z(e=>new Set([...e,...t])),e||O(!0);try{let t=await fetch("/api/plugins/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n,source:e?.source,scope:e?.scope})}),r=await t.json();if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);A(e=>{let t={...e};for(let e of r.updates??[])t[lq(e)]=e;return t})}catch(e){F(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||O(!1)}}},[n,U]),Q=(0,i.useCallback)(async()=>{H(!0),I(null),$(null),F(null);try{let e=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"update",cwd:n})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);p(t),A({}),$(d("i18n.packagesUpdated")),s&&$(`${d("i18n.packagesUpdated")} ${d("agents.reloadRequired")}`)}catch(e){I(e instanceof Error?e.message:String(e))}finally{H(!1)}},[n,s,d]),ee=(0,i.useCallback)(async(e,t)=>{let r=lq(t);N(`${e}:${r}`),I(null),$(null),R(null);try{let i=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,source:t.source,scope:t.scope,cwd:n})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);if(p(s),"remove"===e)v(s.packages[0]?lq(s.packages[0]):s.standaloneExtensions[0]?lK(s.standaloneExtensions[0]):null),0===s.packages.length&&0===s.standaloneExtensions.length&&y(!0),$(d("i18n.packageRemoved")),A(e=>{let t={...e};return delete t[r],t});else{let t={install:d("i18n.packageInstalled"),update:d("i18n.packageUpdated"),disable:d("i18n.packageDisabled"),enable:d("i18n.packageEnabled")};$(t[e]),"update"===e&&A(e=>{let t={...e};return delete t[r],t})}}catch(e){I(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,d]),et=(0,i.useCallback)(async(e,t,r)=>{let i=lj(t,r,e=>!e.disabled,e=>e.filtered),o=r?0:t.filter(e=>!e.disabled&&e.filtered).length,a=o>0?d("plugins.bulkKeptFiltered",{count:o}):void 0;if(I(null),$(null),R(a?{scope:e,note:a}:null),0===i.length)return;let l=r?"enable":"disable";N(`bulk:${e}`);try{let t=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:l,cwd:n,packages:i.map(t=>{let{source:n}=t;return{source:n,scope:e}})})}),o=await t.json();if(!t.ok||o.error||!o.results)throw Error(o.error??`HTTP ${t.status}`);let{results:c,...u}=o;p(u);let h=c.filter(e=>e.error);if(h.length<c.length){let e=r?d("plugins.bulkEnabled"):d("plugins.bulkDisabled");$(s?`${e} ${d("agents.reloadRequired")}`:e)}h.length>0&&R({scope:e,note:a,error:[d("plugins.bulkFailed",{count:h.length,total:c.length}),...h.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,s,d]),en=(0,i.useCallback)(async()=>{let e=l_(j).trim();if(!e)return;k(e);let t=`${w}\0${e}`;N(`install:${t}`),I(null),$(null),R(null);try{var r;let i,s,o=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:e,scope:w,cwd:n})}),a=await o.json();if(!o.ok||a.error)throw Error(a.error??`HTTP ${o.status}`);p(a);let l=(r=a.packages,s=(i=e.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===w&&e.source===i)??r.find(e=>e.scope===w&&e.source===`npm:${s}`)??r.find(e=>e.scope===w&&e.source.endsWith(i)));v(l?lq(l):t),y(!1),k(""),$(d("i18n.packageInstalled"))}catch(e){I(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,w,j,d]),er=(0,i.useCallback)(async()=>{if(s){N("reload"),I(null),$(null),R(null);try{await sa(s,{type:"reload"}),a?.(),await J(),$(d("i18n.sessionReloaded"))}catch(e){I(e instanceof Error?e.message:String(e))}finally{N(null)}}},[J,a,s,d]),ei=C?.startsWith("install:")??!1,es=Object.values(L).filter(e=>"update-available"===e.state).length,eo=U.some(e=>e.canCheckForUpdates),ea=h||null!==C||P.size>0||B;return(0,r.jsxs)(ao,{embedded:l,title:d("common.plugins"),subtitle:lb(n),closeLabel:d("i18n.close"),onClose:o,children:[!V&&(0,r.jsx)(a$,{message:d("trust.pluginsNotLoaded")}),(0,r.jsxs)(aa,{children:[(0,r.jsxs)(al,{children:[(0,r.jsx)(ac,{children:h?(0,r.jsx)("div",{className:"config-sidebar-message",children:d("i18n.loading")}):m?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:m}):0===U.length&&0===_.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:d("i18n.noPlugins")}):(0,r.jsxs)(r.Fragment,{children:[_.length>0&&(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(ad,{children:d("i18n.extensions")}),_.map(e=>{let t=lK(e);return(0,r.jsxs)(ah,{active:!b&&x===t,title:e.path,onClick:()=>{v(t),y(!1),I(null),$(null)},children:[(0,r.jsx)(aO,{active:e.enabled}),(0,r.jsx)(af,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.name})]},t)})]}),Z.map(e=>{let t=e.packages.filter(e=>!e.disabled).length,n=t===e.packages.length;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(ad,{aside:(0,r.jsx)(au,{enabled:t,total:e.packages.length,disabled:ea,loading:C===`bulk:${e.scope}`,label:d(n?"plugins.groupSwitchOn":"plugins.groupSwitchOff",{group:lV(e.scope,d)}),onChange:t=>void et(e.scope,e.packages,t)}),children:lV(e.scope,d)}),M?.scope===e.scope&&(0,r.jsx)(ap,{error:M.error,note:M.note}),e.packages.map(e=>{let t=lq(e),n=!b&&x===t;return(0,r.jsxs)(ah,{active:n,title:e.description??e.source,onClick:()=>{v(t),y(!1),I(null),$(null)},children:[(0,r.jsx)(aO,{active:!e.disabled,color:lG(e.status)}),(0,r.jsx)(af,{className:`is-grow${e.disabled?" is-muted":""}`,children:e.source}),L[lq(e)]?.state==="update-available"&&(0,r.jsx)("span",{title:d("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"})]},t)})]},e.scope)})]})}),(0,r.jsx)(aW,{active:b,onClick:()=>{y(!0),I(null),$(null)},children:d("i18n.addPlugin")})]}),(0,r.jsx)(aR,{children:(0,r.jsx)(am,{className:"is-fill",children:b?(0,r.jsx)(lX,{cwd:n,source:j,scope:w,projectResourcesLoaded:V,busy:ei,actionError:E,onSourceChange:k,onScopeChange:S,onInstall:en}):h?null:K?(0,r.jsx)(l0,{extension:K}):q?(0,r.jsx)(lQ,{pkg:q,cwd:n,busyKey:C,actionError:E,actionMessage:T,sessionId:s,updateStatus:L[lq(q)],checkingUpdate:P.has(lq(q)),updateError:D,onAction:ee,onCheckUpdate:()=>void X(q),onReloadSession:er},lq(q)):(0,r.jsx)(aM,{children:d("i18n.selectPackage")})})})]}),(0,r.jsxs)(aL,{status:es>0?(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--accent)"},children:[es," ",1===es?d("i18n.update"):d("i18n.updates")]}):u?.diagnostics.length?(0,r.jsx)(aA,{tone:u.diagnostics.some(e=>"error"===e.type)?"error":"warning",summary:1===u.diagnostics.length?d("plugins.diagnostic"):d("plugins.diagnostics",{count:u.diagnostics.length}),details:u.diagnostics.map(lJ)}):(0,r.jsx)(aA,{summary:u?[d("i18n.resourceCount",{count:(t=u.totals).extensions,label:d("i18n.extensionShort")}),d("i18n.resourceCount",{count:t.skills,label:d("i18n.skillShort")}),d("i18n.resourceCount",{count:t.prompts,label:d("i18n.promptShort")}),d("i18n.resourceCount",{count:t.themes,label:d("i18n.themeShort")})].join(" \xb7 "):""}),children:[!l&&(0,r.jsx)(aP,{onClick:o,children:d("i18n.close")}),eo&&(0,r.jsx)(aP,{variant:es>0?"primary":"secondary",onClick:()=>void(es>0?Q():X()),disabled:ea,title:es>0?d("i18n.updateAllPluginsHint"):void 0,children:B?d("i18n.updating"):W?d("i18n.checking"):es>0?`${d("i18n.updateAllPlugins")} (${es})`:d("i18n.checkUpdates")}),(0,r.jsx)(aP,{variant:"secondary",onClick:()=>void J(),disabled:ea,children:d("i18n.refresh")})]})]})}let l2="\\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",l4=RegExp(`[${l2}]`,"gu"),l8=RegExp(`[${l2}]`,"u");function l5(e){return e.replace(l4,e=>{let t=e.codePointAt(0)??0;return`\\u{${t.toString(16).toUpperCase().padStart(4,"0")}}`})}let l6=/[\s"'`$|&;<>()*?#~]/;function l3(e){let t=l8.test(e),n=l5(e);return""===n||t||l6.test(n)?`"${n.replace(/"/g,'\\"')}"`:n}function l9(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return[e,...t].map(l3).join(" ")}function l7(e){let t=void 0!==e.command?l9(e.command,e.args):void 0,n=void 0!==e.url?l5(e.url):void 0;return"http"===e.transport?n:"stdio"===e.transport?t:n??t}function ce(e){return[e.name,e.command,e.cwd,e.url,...e.args??[],...e.envNames,...e.headerNames].some(e=>void 0!==e&&l8.test(e))}function ct(e){return"oauth-client-secret"===e.kind?{key:"mcp.field.oauthClientSecret"}:{key:"env"===e.kind?"mcp.field.env":"mcp.field.header",params:{name:l5(e.name??"")}}}function cn(e){return"http"===e.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables"}function cr(e){return e.length>0?{key:"mcp.server.overridesGlobal",params:{keys:e.join(", ")}}:{key:"mcp.server.overridesGlobalNothing"}}function ci(e){return e.flatMap(e=>{let{variables:t,...n}=e;return t.map(e=>({variable:e,field:n}))})}function cs(e,t){return"unparsable"===e.reason||"unreadable"===e.reason?l5(e.error):"link-outside"===e.reason?void 0===t?void 0:l5(t):void 0}let co="codemode";function ca(e){return`${e.scope}\0${e.name}`}function cl(e){return e?.trust?.decision===!0}function cc(e){return"test"===e.origin?e.state:void 0!==e.closedAt||"not-trusted"===e.state?"on":e.state}function cd(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?cc(e.status):"on":"mcp-off":"not-trusted":"disabled"}let cu={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"},cp={connected:"mcp.state.session.connected",failed:"mcp.state.session.failed"};function ch(e,t){return(t?.origin==="session"?cp[e]:void 0)??cu[e]}let cf={disconnected:"mcp.stateDetail.disconnected",conflict:"mcp.stateDetail.conflict"},cm={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 cg(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 cx(e){return"on"===e?{active:!0}:"off"===e?{active:!1}:{color:"error"===e?"#ef4444":"#f59e0b"}}function cv(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 cb={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"},cy={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"},cj={connecting:"off",connected:"on","needs-auth":"warning",failed:"error",disconnected:"warning",conflict:"error","not-trusted":"warning"},ck={codemode:"mcp.exposure.codemode",deferred:"mcp.exposure.deferred",direct:"mcp.exposure.direct",hidden:"mcp.exposure.hidden"},cw=["codemode","deferred","direct","hidden"],cS={codemode:"mcp.exposureShort.codemode",deferred:"mcp.exposureShort.deferred",direct:"mcp.exposureShort.direct",hidden:"mcp.exposureShort.hidden"};function cC(e){return"auto-enable-codemode-invalid"!==e.reason}function cN(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 cE(e){return{enabled:e.filter(e=>e.enabled).length,total:e.length}}function cI(e,t){let n=e.flatMap(e=>e.servers.map(ca));return t===co||null!==t&&n.includes(t)?t:n[0]??null}function cT(e){let t=e?.trust;return void 0!==t&&t.requiresTrust&&!t.trusted}function c$(e){return e.projectOverride?.preference??e.preference}let cM={always:"mcp.codemode.projectOverride.always",automatic:"mcp.codemode.projectOverride.automatic"},cR={on:"mcp.codemode.toolMode.onDescription",only:"mcp.codemode.toolMode.onlyDescription"},cL={on:"mcp.codemode.toolMode.projectOverride.on",only:"mcp.codemode.toolMode.projectOverride.only"},cA={automatic:"mcp.codemode.automatic",always:"mcp.codemode.always",unavailable:"mcp.codemode.unavailable",unknown:"i18n.unknown"};function cP(e){return"unavailable"===e?"error":"unknown"===e?"off":"on"}let cz=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e);function cW(e,t){let n=e??{},r=n.breadth,i=n.trust;return{error:"string"==typeof n.error?n.error:`HTTP ${t}`,..."string"==typeof n.reason?{reason:n.reason}:{},..."string"==typeof n.path?{path:n.path}:{},..."string"==typeof n.name?{name:n.name}:{},..."string"==typeof n.suggestedName?{suggestedName:n.suggestedName}:{},...cz(n.names)?{names:n.names}:{},...cz(n.fields)?{fields:n.fields}:{},...Array.isArray(n.notes)?{notes:n.notes.filter(e=>"string"==typeof e?.code)}:{},..."string"==typeof r?.kind&&"string"==typeof r.path?{breadth:r}:{},..."boolean"==typeof i?.requiresTrust&&"boolean"==typeof i.trusted?{trust:i}:{},...!0===n.trustKept?{trustKept:!0}:{}}}async function cO(e,t,n,r){let i,{abortAtDeadline:s=!0}=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},o=new AbortController,a=()=>o.abort();r?.aborted?o.abort():r?.addEventListener("abort",a,{once:!0});let l=new Promise(e=>{i=setTimeout(()=>{e(t()),s&&o.abort()},n)});try{return await Promise.race([e(o.signal),l])}finally{clearTimeout(i),r?.removeEventListener("abort",a)}}function cD(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 cF(e,t,n){let r,i;try{r=await t(e?`/api/mcp?cwd=${encodeURIComponent(e)}`:"/api/mcp",{cache:"no-store",signal:n})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{i=await r.json()}catch{return{ok:!1,error:{error:`HTTP ${r.status}`}}}return r.ok&&cD(i)?{ok:!0,data:i}:{ok:!1,error:cW(i,r.status)}}let cB=new Set(["cwd-invalid","cwd-denied","cwd-not-directory"]);async function cH(e,t,n){let r=await cF(e,t,n);if(r.ok||!e||!r.error.reason||!cB.has(r.error.reason))return r;let i=await cF(null,t,n);return i.ok?{...i,projectError:r.error}:i}async function cU(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 cO(n=>cH(e,t,n),()=>({ok:!1,error:{error:`GET /api/mcp did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function c_(e,t,n,r){let i,s;try{i=await n("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store",signal:r})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{s=await i.json()}catch{return{ok:!1,error:{error:`HTTP ${i.status}`}}}let o=i.ok&&null!==s&&"object"==typeof s?t(s):void 0;return void 0!==o?{ok:!0,stored:o}:{ok:!1,error:cW(s,i.status)}}async function cq(e,t,n){let r=await c_({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 cK(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 cO(n=>cq(e,t,n),()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function cV(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 cO(async n=>{let r=await c_({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 cZ(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 cO(async n=>{let r=await c_({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 cJ(e){return!e.available&&"builtin-disabled"!==e.reason}function cG(e,t){if(cJ(t.mcp))return"mcp-off";if("project"===e){if(!t.project?.trust)return"trust-unreadable";if(!cl(t.project))return"project-untrusted"}}let cY={"mcp-off":"mcp.readOnly.mcp-off","project-untrusted":"mcp.readOnly.project-untrusted","trust-unreadable":"mcp.readOnly.trust-unreadable"};function cX(e){return!0!==e.notAnObject}function cQ(e){return cX(e)&&void 0===e.webPasswordField}async function c0(e,t,n){let r,i;try{r=await t("/api/mcp",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store",signal:n})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{i=await r.json()}catch{return{ok:!1,error:{error:`HTTP ${r.status}`}}}return r.ok&&cD(i)?{ok:!0,data:i}:{ok:!1,error:cW(i,r.status)}}async function c1(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 cO(e=>c0(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp did not answer within ${i} ms`,timedOut:!0}}),i,r)}let c2={"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 c4(e,t){let n=cG(e.scope,t);return n||(void 0===e.invalidError&&e.validated?e.webPasswordField?"web-password":void 0:"invalid")}let c8={"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"},c5={connected:"mcp.test.state.connected","needs-auth":"mcp.test.state.needs-auth",failed:"mcp.test.state.failed",timedOut:"mcp.test.state.timedOut"},c6={connected:"mcp.test.summary.connected","needs-auth":"mcp.test.summary.needs-auth",failed:"mcp.test.summary.failed",timedOut:"mcp.test.summary.timedOut"},c3={connected:"mcp.signIn.summary.connected","needs-auth":"mcp.signIn.summary.needs-auth",failed:"mcp.signIn.summary.failed",timedOut:"mcp.signIn.summary.timedOut"};function c9(e){return(Math.max(0,e)/1e3).toFixed(1)}async function c7(e,t,n){let r,i;try{r=await t("/api/mcp/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store",signal:n})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{i=await r.json()}catch{return{ok:!1,error:{error:`HTTP ${r.status}`}}}return r.ok&&function(e){if(null===e||"object"!=typeof e)return!1;let t=e.result;return"string"==typeof e.configKey&&"string"==typeof e.name&&("global"===e.scope||"project"===e.scope)&&"object"==typeof t&&null!==t&&"string"==typeof t.state&&Array.isArray(t.tools)&&"number"==typeof t.testedAt}(i)?{ok:!0,data:i}:{ok:!1,error:cW(i,r.status)}}async function de(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 cO(e=>c7(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp/test did not answer within ${i} ms`,timedOut:!0}}),i,r,{abortAtDeadline:!1})}let dt="•••",dn=new Set(["key","apikey","token","secret","password","passwd","passphrase","pwd","pass","credential","credentials","authorization","bearer","jwt","cookie","signature","pat"]),dr=new Set([...dn,"auth","sig","code","pw"]),di=["token","secret","password","passwd","apikey"],ds=new Set(["file","path","dir","url","uri","endpoint","id","name","type","header","env","var","length","ttl","expiry","expires","timeout","mode","format"]),da=new Set(["-k"]);function dl(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 dc(e,t){let n=dl(e);return!(n.length>1&&ds.has(n[n.length-1]))&&n.some(e=>t.has(e)||di.some(t=>e.length>t.length&&e.endsWith(t)))}function dd(e){return dc(e,dn)}let du=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,})"),dp=/^eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*$/,dh=/^[A-Za-z0-9_\-+/=.~]+$/;function df(e){return!(/\s/.test(e)||db(e))&&(!!(du.test(e)||dp.test(e))||!(e.length<24||!dh.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 dm=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Za-z_][A-Za-z0-9_]*/,dg=RegExp(dm.source,"g"),dx=/^(?:bearer|basic|token)\s+/i;function dv(e,t,n){let r=e.replace(dx,"");return t.test(r)&&/^[^A-Za-z0-9]*$/.test(r.replace(n,""))}function db(e){return dv(e.replace(/\$[$!]/g,"_x"),dm,dg)}let dy=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Z_][A-Z0-9_]*(?![A-Za-z0-9_])/,dj=RegExp(dy.source,"g");function dk(e){return dv(e,dy,dj)}function dw(e,t){if(!e||""===t)return;e.push(t);let n=dN(t);n!==t&&e.push(n)}let dS=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#]*)/;function dC(e,t,n){let r=!1,i=e,s="",o=dS.exec(e);if(o){let[a,l,c]=o,d=c.lastIndexOf("@");if(d>=0&&!t(dN(c.slice(0,d)))){s=`${l}${dt}${c.slice(d)}`,r=!0;let e=c.slice(0,d);dw(n,e);let t=e.indexOf(":");t>=0&&dw(n,e.slice(t+1))}else s=a;i=e.slice(a.length)}let a=i.search(/[?#]/),l=a<0?i:i.slice(0,a),c=a<0?"":i.slice(a),d=l.split("/").map(e=>df(dN(e))?(r=!0,dw(n,e),dt):e).join("/");return c=c.replace(/([?&#;])([^&#;]*)/g,(e,i,s)=>{let o=s.indexOf("=");if(o<0){let o=dN(s);return!df(o)||t(o)?e:(r=!0,dw(n,s),`${i}${dt}`)}let a=s.slice(0,o),l=dN(s.slice(o+1));return""===l||t(l)||!function(e){let t=e;try{t=decodeURIComponent(e)}catch{}return dc(t,dr)}(a)&&!df(l)?e:(r=!0,dw(n,s.slice(o+1)),`${i}${a}=${dt}`)}),{value:`${s}${d}${c}`,masked:r}}function dN(e){try{return decodeURIComponent(e)}catch{return e}}let dE=/^(\s*[A-Za-z][A-Za-z0-9 _.-]*=)([\s\S]*)$/;function dI(e,t,n){let r=/^([A-Za-z0-9_-]+):(\s*)([\s\S]*)$/.exec(e);if(r&&""!==r[3]&&!r[3].startsWith("//")&&dd(r[1])){let[,i,s,o]=r;return t(o)?{value:e,masked:!1}:(dw(n,o.trim()),{value:`${i}:${s}${dt}`,masked:!0})}let i=e.includes(";")?function(e,t,n){let r=e.split(";");if(r.length<2||!r.every(e=>""===e.trim()||dE.test(e)))return;let i=!1;return{value:r.map(e=>{let r=dE.exec(e);if(!r)return e;let[,s,o]=r;if(""===o.trim()||t(o))return e;if(dd(s.slice(0,-1).trim()))return i=!0,dw(n,o.trim()),`${s}${dt}`;let a=dI(o,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]&&dd(s[1]))return t(s[2])?{value:e,masked:!1}:(dw(n,s[2]),{value:`${s[1]}=${dt}`,masked:!0});if(/\s/.test(e)){var o,a,l;let r,i;return o=e,a=t,l=n,i=dM((r=o.split(/(\s+)/)).filter((e,t)=>t%2==0),a,!0,l),{value:r.map((e,t)=>t%2==0?i.values[t/2]:e).join(""),masked:i.masked}}if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(e))return dC(e,t,n);if(s&&""!==s[2]){let e=dI(s[2],t,n);return{value:`${s[1]}=${e.value}`,masked:e.masked}}return df(e)&&!t(e)?(dw(n,e),{value:dt,masked:!0}):{value:e,masked:!1}}function dT(e){if(da.has(e))return!0;if(!/^--?[A-Za-z]/.test(e))return!1;let t=e.replace(/^-+/,"");return dd(t)||"auth"===dl(t).at(-1)}let d$=/^(?:bearer|basic|token)$/i;function dM(e,t,n,r){let i=!1,s=!1;return{values:e.map(e=>{if(""===e)return e;if(s){if(n&&d$.test(e))return e;if(s=!1,!/^-[A-Za-z-]/.test(e))return t(e)?e:(i=!0,dw(r,e),dt)}let o=/^(--?[A-Za-z][A-Za-z0-9_.-]*)=([\s\S]*)$/.exec(e);if(o){let[,e,n]=o;if(""!==n&&dT(e)&&!t(n))return i=!0,dw(r,n),`${e}=${dt}`;let s=dI(n,t,r);return i||=s.masked,`${e}=${s.value}`}if(/^--?[A-Za-z][A-Za-z0-9_.-]*$/.test(e))return s=dT(e),e;if(n){let t=/^([A-Za-z0-9_-]+):$/.exec(e);if(d$.test(e)||t&&dd(t[1]))return s=!0,e}let a=dI(e,t,r);return i||=a.masked,a.value}),masked:i}}function dR(e){let{values:t,masked:n}=dM(e,dk,!1);return{args:t,masked:n}}function dL(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function dA(e){return!e.startsWith("!")&&!db(e)}function dP(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 dz={"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(dz);let dW={dollarBrace:!1,bareDollar:!1,percent:!1,braceEnv:!1},dO={dollarBrace:!0,bareDollar:!1,percent:!0,braceEnv:!0},dD={...dO,bareDollar:!0},dF={...dW,braceEnv:!0},dB=/^[A-Za-z_][A-Za-z0-9_]*$/,dH=/\$\{([^{}]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)|%([A-Za-z_][A-Za-z0-9_]*)%|\{(env|file):([^{}]*)\}/g;function dU(e,t){if(!t)return;let n=e[e.length-1];n?.kind==="text"?n.text+=t:e.push({kind:"text",text:t})}function d_(e,t,n){let r=[],i=0;dH.lastIndex=0;for(let s=dH.exec(e);s;s=dH.exec(e)){let[o,a,l,c,d,u]=s,p=o;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(dB.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,o);else if(void 0!==l&&t.bareDollar)p={kind:"env",name:l,from:o};else if(void 0!==c&&t.percent&&n)p={kind:"env",name:c,from:o};else if(void 0!==d&&t.braceEnv)p="env"===d&&dB.test(u)?{kind:"env",name:u,from:o}:{kind:"unsupported",from:o};else if(void 0!==c||void 0!==d){dU(r,e.slice(i,s.index+1)),i=s.index+1,dH.lastIndex=s.index+1;continue}dU(r,e.slice(i,s.index)),"string"==typeof p?dU(r,p):r.push(p),i=s.index+o.length}return dU(r,e.slice(i)),r}function dq(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 dK(e){return e.startsWith("!")}function dV(e){if(dK(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);dB.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 dZ=/<[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,dJ=/^(?:\.\.\.|…|\*{3,}|x{3,}|TODO|FIXME|changeme|change[-_]me|replace[-_]?me|placeholder|redacted|\[[^\]]+\])$/i,dG=/(?:^|[\\/])(?:path[\\/]to(?:[\\/]|$)|Users[\\/](?:username|yourname|your[-_][A-Za-z_-]+|user[-_]?name|<[^>]+>)(?:[\\/]|$)|home[\\/](?:username|yourname|your[-_][A-Za-z_-]+|<[^>]+>)(?:[\\/]|$))/i,dY=/^(Bearer|Basic|Token|Bot|ApiKey|Api-Key)\s+(.+)$/i;function dX(e){return e.join("\0")}function dQ(e){return"args"===e[0]?`args[${e[1]}]`:e.join(".")}function d0(e){return"env"===e[0]||"headers"===e[0]||"oauth"===e[0]&&"clientSecret"===e[1]}function d1(e){return"command"===e[0]||"args"===e[0]||"cwd"===e[0]}let d2=new Set(["HOME","USERPROFILE"]);class d4{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 d8(e){return e.map(e=>"text"in e?e.text:e.from).join("")}let d5=/\$\{[^{}]*\}/g,d6=new Set(["variable","home","workspace-basename","unsupported-variable","input"]);class d3{constructor(e){this.draft=e,this.fields=new Map,this.argTexts=e.args.map(d8),this.urlText=d8(e.url??[])}encode(e,t){let n,r=d0(e),i=dQ(e),s=d8(t),o=[],a=!1,l=()=>o.every(e=>""===e),c=e=>{if(!r)return void o.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=dq(e,{atStart:l()});n!==e&&(a=!0),o.push(n)},d=e=>o.push(e),u=e=>o.push({field:e});if(!r&&d1(e)&&1===t.length&&"text"in t[0]&&dG.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(dG.test(n))return t&&d(t),u(this.field(e,"placeholder-path",n,n,"text")),this.target(e,o,void 0)}let p=0;return t.forEach((o,a)=>{let h=t[a+1],f=void 0===h||"text"in h&&/^[\\/]/.test(h.text),m=(t,r,i)=>{let o=0;for(let[c,d]of function(e){let t=e.trim();if(dJ.test(t)){let n=e.indexOf(t);return[[n,n+t.length]]}let n=dY.exec(t);if(n&&dJ.test(n[2].trim())){let t=e.lastIndexOf(n[2].trim());return[[t,t+n[2].trim().length]]}let r=[];dZ.lastIndex=0;for(let t=dZ.exec(e);t;t=dZ.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,l;if(i.some(e=>{let[t,n]=e;return c<n&&d>t}))continue;c>o&&r(t.slice(o,c)),"url"===e[0]&&d9(s,p+c)&&(n="uri-component");let h=t.slice(c,d);u(this.field(e,"placeholder",(a=e,l=h,"env"===a[0]||"headers"===a[0]?a[1]:l.replace(/^[<{\s]+|[>}\s]+$/g,"")||dQ(a)),h)),o=d}o<t.length&&r(t.slice(o))};switch(o.kind){case"text":m(o.text,c,[]);break;case"pi":{var g;let e=h?(g=o.text,(/\$+$/.exec(g)?.[0].length??0)%2==1?`${g}$`:g):o.text;if(r&&l()&&dK(e)){this.draft.note("shell-command-value",{field:i}),d(e);break}let t=[...e.matchAll(d5)].map(e=>[e.index,e.index+e[0].length]);m(e,d,t);break}case"env":r?(d(`\${${o.name}}`),void 0!==o.fallback&&this.draft.note("variable-fallback-dropped",{field:i,name:o.name,fallback:o.fallback}),o.shell?this.draft.note("shell-variable",{field:i,name:o.name}):o.from!==`\${${o.name}}`&&this.draft.note("variable-translated",{field:i,from:o.from,to:`\${${o.name}}`})):d1(e)&&l()&&d2.has(o.name)&&f?(d("~"),this.draft.note("home-translated",{field:i,from:o.from})):(u(this.field(e,"variable",o.name,o.from,void 0,o.fallback)),this.draft.note(o.shell?"shell-variable":"variable-unsupported-here",{field:i,name:o.name}));break;case"input":u(this.inputField(e,o));break;case"home":r?(d("${HOME}"),this.draft.note("home-variable-translated",{field:i,from:o.from,to:"${HOME}"})):d1(e)&&l()&&f?(d("~"),this.draft.note("home-translated",{field:i,from:o.from})):u(this.field(e,"home","userHome",o.from,"text"));break;case"workspace":"url"===e[0]||"oauth"===e[0]?u(this.field(e,"variable","workspaceFolder",o.from,"text")):(d("."),this.draft.note("workspace-folder-relative",{field:i,from:o.from}));break;case"workspace-basename":u(this.field(e,"workspace-basename","workspaceFolderBasename",o.from,"text"));break;case"unsupported":u(this.field(e,"unsupported-variable",o.from,o.from)),this.draft.note("unsupported-variable",{field:i,variable:o.from});break;case"prompt":"url"===e[0]&&d9(s,p)&&(n="uri-component"),u(this.promptField(e,o))}p+=("text"in o?o.text:o.from).length}),a&&this.draft.note("escaped-value",{field:i}),this.target(e,o,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=>dX(t.path)===dX(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 o=d6.has(t)?`${t}.${n}`:dQ(e);if(d6.has(t)){if(this.fields.has(o))return o}else for(let t=2;this.fields.has(o);t++)o=`${dQ(e)}#${t}`;let a=this.isSecretContext(e,r)||dd(n),l="headers"===e[0]&&"authorization"===e[1].toLowerCase();return this.fields.set(o,{id:o,kind:i??(a?"password":"text"),reason:t,label:n,placeholder:r,...void 0!==s?{defaultValue:s}:{},..."placeholder"===t&&l?{optional:!0}:{},targets:[]}),o}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 dd(e[1]);case"oauth":return"clientSecret"===e[1];case"args":{if(dR([this.argTexts[e[1]]??""]).masked)return!0;let t=this.argTexts[e[1]-1];return void 0!==t&&dR([t,"x"]).args[1]===dt}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,dC(`https://host.invalid/?${n}=x`,dk).masked)}default:return!1}}}function d9(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 d7(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 ue=/^[A-Za-z0-9_-]+$/;function ut(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 un=new Set(["mcp","server","mcp-server","mcpserver","cli","index","main","app","src","dist","build","bin","lib"]);function ur(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=us(t);return s&&!un.has(s.toLowerCase())?s:us(r)||r||s||t}let ui=[/^mcp[-_]server[-_]/i,/^server[-_]/i,/^mcp[-_]/i,/[-_]mcp[-_]server$/i,/[-_]mcp$/i,/[-_]server$/i];function us(e){let t=e;for(let e=!0;e;)for(let n of(e=!1,ui)){let r=t.replace(n,"");r!==t&&r&&(t=r,e=!0)}return t}let uo=new Set(["mcp","www","api","app","server","servers","remote","gateway"]);function ua(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=>!uo.has(e.toLowerCase()));return r[r.length-1]??n[n.length-1]??""}let ul=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 uc(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 ud(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(!un.has(n.toLowerCase())&&"."!==n&&".."!==n)return us(n.replace(/_/g,"-"))||n}return""}function uu(e,t){up(e,t)&&uh(e,Math.ceil(t/1e3),t)}function up(e,t){return!!("number"==typeof t&&Number.isFinite(t))&&t>0||(void 0!==t&&e.note("timeout-dropped",{value:String(t)}),!1)}function uh(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 uf=["codemode","deferred","direct","hidden"],um={"codemode-deferred":"codemode"},ug=["localhost","127.0.0.1","[::1]"];function ux(e){return"string"==typeof e&&uf.includes(e)?e:"string"==typeof e&&Object.hasOwn(um,e)?um[e]:void 0}function uv(e){try{return new URL(e)}catch{return}}function ub(e){let t=uv(e);return void 0!==t&&"http:"===t.protocol&&ug.includes(t.hostname)&&""===t.search&&""===t.hash}function uy(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function uj(e){return uy(e)&&Object.values(e).every(e=>"string"==typeof e)}function uk(e,t){if(!ue.test(e))return{problem:"name",name:e};if(!uy(t))return{problem:"not-an-object"};let{type:n,exposure:r,enabled:i,timeout:s,toolExposure:o,description:a}=t;if(void 0!==r&&!ux(r))return{problem:"exposure",value:String(r)};if(void 0!==o){if(!uy(o))return{problem:"tool-exposure"};for(let[e,t]of Object.entries(o))if(!ux(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=uv(t.url);if(!e||!/^https?:$/.test(e.protocol))return{problem:"url",url:t.url};if(void 0!==t.headers&&!uj(t.headers))return{problem:"headers"};let n=function(e){var t;let n;if(void 0===e)return;if(!uy(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||!ub(e.callbackUrl))return{problem:"callback-url",value:String(e.callbackUrl)};let t=new URL(e.callbackUrl).port;if(t&&void 0!==r&&Number(t)!==r)return{problem:"callback-port-mismatch",value:t}}if(void 0!==e.scope&&"string"!=typeof e.scope)return{problem:"oauth-scope"};if(void 0!==e.clientName&&("string"!=typeof e.clientName||!e.clientName.trim()))return{problem:"oauth-client-name"};if(void 0!==e.clientRegistration&&"dcr"!==e.clientRegistration){if("cimd"!==e.clientRegistration)return{problem:"oauth-client-registration",value:String(e.clientRegistration)};if(void 0!==e.clientId||void 0!==e.clientName)return{problem:"oauth-client-registration-client"};let t="string"==typeof e.callbackUrl?uv(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)?uv(t):void 0)&&("https:"===n.protocol||"http:"===n.protocol&&ug.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(!uy(r)||"string"!=typeof r.provider||!r.provider)return{problem:"auth"};if("https:"!==e.protocol&&!ug.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||uj(t.env)?void 0!==t.cwd&&"string"!=typeof t.cwd?{problem:"cwd"}:void 0:{problem:"env"}:{problem:"args"}:{problem:"no-command-or-url"}}let uw=/[A-Za-z_]/,uS=/[A-Za-z0-9_]/,uC=/^[A-Za-z_][A-Za-z0-9_]*$/,uN=new Set([..." \n'\"\\$`|&;<>()#*?[]{}!~="]),uE=new Set([..."|&;<>()"]),uI=/[0-9@*#?$!-]/,uT={n:"\n",t:" ",r:"\r",a:"\x07",b:"\b",e:"\x1b",E:"\x1b",f:"\f",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function u$(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 uM(e,t){return/^(?:[A-Za-z]:\\|\\\\[A-Za-z0-9.$_-])/.test(e.slice(t,t+4))}class uR{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 uL)return{ok:!1,error:e.detail};throw e}return{ok:!0,words:this.words}}fail(e){throw new uL(e)}startWord(){return this.parts||(this.lineBreak&&this.fail({code:"multiple-commands"}),this.parts=[],this.windowsWord=uM(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)&&u$(e,this.index)>0)this.index+=u$(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:"`"}):uE.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||!uN.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=uM(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 uT?(t+=uT[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&&uw.test(n)){let n=this.index+1;for(;n<t.length&&uS.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&&uI.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}),uC.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 uL extends Error{constructor(e){super(e.code),this.detail=e}}function uA(e){return new uR(e).run()}function uP(e){return e.parts.every(e=>"text"===e.type)?e.text:void 0}function uz(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let uW=["httpUrl","trust","includeTools","excludeTools","authProviderType","targetAudience","targetServiceAccount","tcp"];function uO(e){if(uW.some(t=>t in e))return!0;let t=e.oauth;return uz(t)&&["redirectUri","authorizationUrl","tokenUrl","audiences","tokenParamName"].some(e=>e in t)}function uD(e){if(!uz(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]||uz(t)&&"string"==typeof t.path||"string"==typeof n||"string"==typeof r||"string"==typeof i}function uF(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 uB(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 uH(e,t){let n=t?uB(t):void 0;return{code:"sse-transport",params:{...e?{server:e}:{},...t?{url:t}:{},...n?{suggestedUrl:n}:{}}}}function uU(e){return e?{server:e}:{}}function u_(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?String(e):void 0}function uq(e,t,n){let r;if(!uz(t))return{note:{code:"no-command-or-url",params:uU(e)}};let i=new Set,s=e=>(i.add(e),t[e]),o=n.rawPi,a=function(e,t){switch(e.flavor){case"zed":return dW;case"opencode":return dF;case"vscode":return dO;default:return uO(t)?dD:dO}}(n,t),l=s("name"),c=e??("string"==typeof l?l:void 0),d=new d4(n.source,o),u=(e,t)=>{if(o)return e?[{kind:"pi",text:e}]:[];return t&&"mcp-servers"===n.flavor&&/^!|\$\$|\$!/.test(e)&&d.note("looks-like-pi-config"),d_(e,a,t)};d.name=c,d.inputs=n.inputs;let p=s("inputs");Array.isArray(p)&&(d.inputs=new Map([...n.inputs??[],...uZ(p)]));let h=s("type"),f=s("command"),m=[s("httpUrl"),s("url"),s("serverUrl")].find(e=>"string"==typeof e);if("tcp"in t)return{note:{code:"websocket-transport",params:uU(c)}};if(void 0!==h&&"unknown"===(r="string"==typeof h?uF(h):"unknown"))return{note:{code:"unsupported-transport",params:{...uU(c),type:String(h)}}};let g="string"==typeof f&&""!==f||Array.isArray(f)||uz(f),x=void 0!==m;if("sse"===r)return{note:uH(c,m)};if("ws"===r)return{note:{code:"websocket-transport",params:{...uU(c),...m?{url:m}:{}}}};if(void 0===r){if(g&&x)return{note:{code:"ambiguous-command-and-url",params:uU(c)}};if(x){if(void 0!==uB(m))return{note:uH(c,m)};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:uU(c)}};r="stdio"}}if("stdio"!==r&&"http"!==r)return{note:{code:"unsupported-transport",params:{...uU(c),type:String(h)}}};if("stdio"===r&&!g||"http"===r&&!x)return{note:{code:"no-command-or-url",params:uU(c)}};if(d.transport=r,"stdio"===r){let e=function(e,t,n,r,i,s){let o,a=r("args"),l=r("opencode"===s.flavor?"environment":"env");if("opencode"===s.flavor&&void 0===l&&(l=r("env")),Array.isArray(n)){if(!n.every(e=>"string"==typeof e)||0===n.length)return{code:"invalid-config",params:{...uU(e.name),problem:"args"}};o=n[0],a=[...n.slice(1),...Array.isArray(a)?a:[]]}else if(uz(n))for(let t of(o="string"==typeof n.path?n.path:void 0,void 0===a&&(a=n.args),void 0===l&&(l=n.env),Object.keys(n)))["path","args","env"].includes(t)||e.note("dropped-key",{key:`command.${t}`});else"string"==typeof n&&(o=n);if(!o)return{code:"no-command-or-url",params:uU(e.name)};let c=Array.isArray(a)?[...a]:[];if(void 0!==a&&!Array.isArray(a))return{code:"invalid-config",params:{...uU(e.name),problem:"args"}};if(0===c.length&&/\s/.test(o.trim())&&!/^(?:[A-Za-z]:[\\/]|[\\/]|~[\\/]|\.{1,2}[\\/])/.test(o.trim())){let t=uA(o.trim()),n=t.ok?t.words.map(uP):void 0;n&&n.length>1&&n.every(e=>void 0!==e)&&(e.note("command-split",{command:o}),o=n[0],c.push(...n.slice(1)))}for(let[t,n]of(e.command=i(o,!1),c.entries())){let r=u_(n);if(void 0===r)return{code:"invalid-config",params:{...uU(e.name),problem:"args",index:t}};e.args.push(i(r,!1))}if(void 0!==l){if(!uz(l))return{code:"invalid-config",params:{...uU(e.name),problem:"env"}};for(let[t,n]of Object.entries(l)){if(null===n){e.note("env-null-dropped",{name:t});continue}let r=u_(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&&dd(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,f,s,u,n);if(e)return{note:e}}else!function(e,t,n,r,i){let s=r("headers"),o=i(n,!1),a=uz(s)&&Object.keys(s).some(e=>"authorization"===e.toLowerCase());if(1===o.length&&"text"in o[0]?d7(e,n,a):e.url=o,uz(s))for(let[t,n]of Object.entries(s)){let r=u_(n);if(void 0===r){e.note("dropped-key",{key:`headers.${t}`});continue}if(""===r.trim()){"authorization"===t.toLowerCase()?e.note("empty-authorization-dropped"):dd(t)?e.headers.push([t,[{kind:"prompt",id:`headers.${t}`,reason:"empty",label:t,from:"",secret:!0,optional:!0}]]):e.headers.push([t,[]]);continue}e.headers.push([t,i(r,!0)])}else void 0!==s&&e.note("dropped-key",{key:"headers"});let l=r("oauth"),c=r("auth");if(!1===l?e.note("oauth-disable-unsupported"):uz(l)?uK(e,l,i):void 0!==l&&e.note("dropped-key",{key:"oauth"}),uz(c))for(let t of(uK(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,m,s,u);let v=s("timeout");if(void 0!==v)if(o)"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(uO(t))uu(d,v);else["autoApprove","alwaysAllow","transportType"].some(e=>e in t)||"streamableHttp"===t.type?up(d,v)&&uh(d,Math.ceil(v),void 0):!function(e,t){if(!up(e,t))return;let n=t>=1e3;e.note("timeout-unit-guessed",{value:t,unit:n?"milliseconds":"seconds"}),n?uh(e,Math.ceil(t/1e3),t):uh(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 j=s("exposure");if(void 0!==j){let e=ux(j);e?d.exposure=e:d.note("invalid-exposure-dropped",{value:String(j)})}let k=s("toolExposure");if(void 0!==k){let e=uz(k)?Object.entries(k).map(e=>{let[t,n]=e;return[t,ux(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(o||void 0===j&&void 0===k||d.note("looks-like-pi-config"),o){let e=s("description");"string"==typeof e?d.description=e:void 0!==e&&d.note("dropped-key",{key:"description"})}for(let e of(uV(d,s("includeTools"),s("excludeTools")),Object.keys(t)))i.has(e)||d.note("dropped-key",{key:e});return{draft:d}}function uK(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"oauth.";for(let[i,s]of Object.entries(t))switch(i){case"clientId":"string"==typeof s&&""!==s&&(e.oauth.clientId=n(s,!1));break;case"clientSecret":"string"==typeof s&&""!==s&&(e.oauth.clientSecret=n(s,!0));break;case"callbackPort":"number"==typeof s&&Number.isInteger(s)&&s>=1&&s<=65535?e.oauth.callbackPort=s:e.note("callback-port-dropped",{value:String(s)});break;case"clientName":"string"==typeof s&&s.trim()?e.oauth.clientName=n(s,!1):e.note("oauth-option-dropped",{key:`${r}${i}`});break;case"clientRegistration":"dcr"===s||"cimd"===s?e.oauth.clientRegistration=s:e.note("oauth-option-dropped",{key:`${r}${i}`});break;case"authServerMetadataUrl":"string"==typeof s&&""!==s?e.oauth.authServerMetadataUrl=n(s,!1):e.note("oauth-option-dropped",{key:`${r}${i}`});break;case"callbackUrl":case"redirectUri":"string"==typeof s&&ub(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 uV(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 o={...e.toolExposure??{}};if(i.length>0){let t=e.exposure??"codemode";for(let n of(e.exposure="hidden",i))o[n]=t;e.note("tool-filter-imported",{mode:"include",tools:i.join(", ")})}for(let e of s)o[e]="hidden";s.length>0&&e.note("tool-filter-imported",{mode:"exclude",tools:s.join(", ")}),e.toolExposure=o}function uZ(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e)uz(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=>uz(e)?e.value:e).filter(e=>"string"==typeof e)}:{}});return t}function uJ(e,t,n,r){let i=[],s=0;for(let o of e.matchAll(/\{([A-Za-z_][A-Za-z0-9_-]*)\}/g)){o.index>s&&i.push({kind:"text",text:e.slice(s,o.index)});let a=uz(t)&&uz(t[o[1]])?t[o[1]]:{};i.push(uG(`${n}${o[1]}`,o[1],o[0],a,r)),s=o.index+o[0].length}return s<e.length&&i.push({kind:"text",text:e.slice(s)}),i}function uG(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 uY(e,t,n){let r=[],i="",s=()=>{i&&("pi"===t?r.push({kind:"pi",text:i}):r.push(...d_(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 uX(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 o=i.value.slice(s+t.length);return[n,[...o?[{...i,value:o}]:[],...e.slice(r+1)]]}}let uQ=/^https?:\/\//i,u0=/^wss?:\/\//i,u1={"@earendil-works/pi-coding-agent":"pi","@anthropic-ai/claude-code":"claude","@openai/codex":"codex","@google/gemini-cli":"gemini"},u2=new Set(["pi","claude","codex","gemini"]),u4=new Set(["install","remove","uninstall","update","list","config"]);function u8(e){return"error"in e?{error:e.error}:{entries:[e],notes:[]}}let u5={local:"flag",url:"value",env:"list",cwd:"value",header:"list","bearer-token-env-var":"value","oauth-client-id":"value","oauth-client-secret":"value","oauth-callback-port":"value","oauth-client-name":"value",exposure:"value",description:"value"},u6=new Map([["-l","--local"]]),u3=["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name"],u9=["env","cwd"];function u7(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 o=t[s],a=o.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(o);continue}let l=a.startsWith("--")?a.indexOf("="):-1,c=l>0?a.slice(0,l):a,d=n[c];if(!d){if(i.positional.length>=r.asArgAfter){i.positional.push(o),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=l>0?pe(o,l+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 pe(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 pt=/^[A-Za-z_][A-Za-z0-9_]*=/,pn=/^[^\s:]+:/;function pr(e,t,n,r){for(let i of t??[]){let t=uX(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],uY(t[1],n,!0)])}}function pi(e,t,n,r){for(let i of t??[]){let t=uX(i.parts,":"),s=t?.[0].trim();if(!t||!s)return{code:"cli-invalid-pair",params:{cli:r,option:"--header",value:i.text}};let o=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()&&o.every(e=>"text"===e.type&&""===e.value)){e.note("empty-authorization-dropped");continue}e.headers.push([s,uY(o,n,!0)])}}function ps(e){if(void 0!==e&&!0!==e){if("user"===e.text)return"global";if("project"===e.text)return"project"}}function po(e,t,n,r,i){let s,[o,a,...l]=r;if(!o||!a)return{code:"cli-usage",params:{cli:t}};e.name=o.text;let c=void 0===n||!0===n?void 0:n.text.toLowerCase();if(void 0===c){if("http"==(s=uQ.test(a.text)?"http":u0.test(a.text)?"ws":"stdio")&&void 0!==uB(a.text))return uH(o.text,a.text);"http"===s&&"gemini"===t&&e.note("transport-assumed-http")}else s="streamable-http"===c?"http":c;return"sse"===s?uH(o.text,a.text):"ws"===s?{code:"websocket-transport",params:{server:o.text,url:a.text}}:"http"===s?(e.transport="http",e.url=uY(a.parts,i,!1),l.length>0&&e.note("cli-extra-arguments",{cli:t,arguments:l.map(e=>e.text).join(" ")}),"http"):"stdio"!==s?{code:"unsupported-transport",params:{server:o.text,type:s}}:(e.transport="stdio",e.command=uY(a.parts,i,!1),e.args=l.map(e=>uY(e.parts,i,!1)),"stdio")}let pa={"-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 pl(e,t){return"env"===e?pt.test(t.text):pn.test(t.text)&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(t.text)}function pc(e){e.oauth.clientSecret=[{kind:"prompt",id:"oauth.clientSecret",reason:"client-secret",label:"clientSecret",from:"",secret:!0}],e.note("client-secret-prompt")}let pd={"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"--client-secret":{name:"client-secret",kind:"flag"}};function pu(e){let t,n=uP(e)??e.text;try{t=dP(n)}catch(e){return{error:{code:"invalid-json",params:{detail:e instanceof Error?e.message:String(e)}}}}return uz(t)?{value:t}:{error:{code:"no-servers-found"}}}let pp={"--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"}},ph={"-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 pf(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(pm(r),pm(i))}return t}function pm(e){try{return decodeURIComponent(e)}catch{return e}}function pg(e){let t=e.trim();for(let e=0;e<4;e++)try{return dP(t)}catch{let e=pm(t);if(e===t)break;t=e.trim()}}function px(e){return{error:{code:"install-link-invalid",params:{detail:e}}}}function pv(e){let t=e.get("config");if(!t)return px("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:pg(n);return uz(r)?{entries:[uq(e.get("name")||void 0,r,{source:"cursor-install-link",flavor:"mcp-servers",rawPi:!1})],notes:[]}:px("config")}function pb(e,t,n,r){return uz(e)?{entries:[uq(n,e,{source:t,flavor:"vscode",rawPi:!1,inputs:uZ(r)})],notes:[]}:px("config")}function py(e){return{error:{code:"by-name-link",params:{name:e}}}}function pj(e){let t=e.indexOf("?");return t<0?"":e.slice(t+1)}function pk(e){let t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=e.replace(/&amp;/g,"&");try{t=new URL(r)}catch{if(/^https?:\/\/\S+$/i.test(r)&&0===n)return{entries:[pS(void 0,r)],notes:[]};return{error:{code:"unrecognized-input"}}}if(n>3)return px("nesting");let i=t.protocol.replace(/:$/,"").toLowerCase();switch(i){case"cursor":if(/\/mcp\/install\/?$/.test(t.pathname))return pv(pf(t.search));return px("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 py(pm(t[1]));if(/^mcp\/api\.mcp\.github\.com\//.test(e))return py(e.replace(/^mcp\//,""));if(/^mcp\/install\?/.test(e))return pb(pg(pj(r)),"vscode-install-link");return px(i)}case"vsweb+mcp":return pb(pg(pj(r)),"visual-studio-install-link");case"ghapp":if(/^\/\/mcp\/install/.test(r.slice(r.indexOf(":")+1)))return pb(pg(pj(r)),"copilot-app-install-link");return px(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 pv(pf(e.search));if("vscode.dev"===r||"insiders.vscode.dev"===r){let t=pf(e.search);if(/^\/redirect\/?$/.test(i)&&t.get("url"))return pk(t.get("url"),n+1);if(/^\/redirect\/mcp\/install\/?$/.test(i)){let e=t.get("config");return e?pb(pg(e),"vscode-install-link",t.get("name")||void 0,pg(t.get("inputs")??"[]")):px("config")}}if("aka.ms"===r&&/^\/vs\/mcp-install\/?$/i.test(i))return pb(pg(e.search.slice(1)),"visual-studio-install-link");if("github.com"===r&&/^\/copilot\/app\/launch\/?$/.test(i)){let t=pf(e.search).get("open");return t?pk(t,n+1):px("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:[pS(e,t)],notes:[]}}(t,r,n);default:return{error:{code:"unsupported-url-scheme",params:{scheme:i}}}}}let pw=new Set(["localhost","127.0.0.1","[::1]"]);function pS(e,t){let n=ua(t)||void 0;if(void 0!==uB(t))return{note:uH(n,t)};let r=new d4("url",!1);return r.transport="http",d7(r,t,!1),e?.protocol!=="http:"||pw.has(e.hostname)||r.note("insecure-http",{host:e.hostname}),{draft:r}}let pC=/[\u200B-\u200D\u2060\uFEFF]/g,pN=/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]\S*)?$/i,pE={"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 pI(e){return new Set(e.fields.flatMap(e=>e.targets.map(e=>dX(e.path))))}function pT(e){var t;let n,r,i,s,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=(n=e.replace(pC,"").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=dP(e)}catch(t){try{n=dP(`{${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 uq(n,r,t)});if(Array.isArray(e)){let r=e.filter(uD);return 0===r.length?{error:{code:"no-servers-found"}}:{entries:r.map(e=>uq(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})),notes:n}}if(!uz(e))return{error:{code:"no-servers-found"}};let i=uz(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?ur(t.split("/").pop()??t):void 0,r=Array.isArray(e.remotes)?e.remotes.filter(uz):[],i=r.filter(e=>"string"==typeof e.type&&"http"===uF(e.type)&&"string"==typeof e.url);if(0===i.length){let e=r.find(e=>"sse"===e.type);return e?[{note:uH(n,"string"==typeof e.url?e.url:void 0)}]:[{note:{code:"registry-packages-unsupported",params:uU(n)}}]}return i.map(e=>{let r=new d4("registry-server-json",!1);for(let i of(r.name=n,t&&n!==t&&(r.originalName=t),r.transport="http",r.url=uJ(e.url,e.variables,"url.","registry-variable"),Array.isArray(e.headers)?e.headers.filter(uz):[])){if("string"!=typeof i.name||""===i.name)continue;let e=i.name;"string"==typeof i.value&&""!==i.value?r.headers.push([e,uJ(i.value,i.variables,`headers.${e}.`,"registry-header")]):r.headers.push([e,[uG(`headers.${e}`,e,"",i,"registry-header")]])}return{draft:r}})}(i),notes:n};if(uz(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(uz(e.servers)){let t=uZ(e.inputs);return{entries:r(e.servers,{source:"vscode-json",flavor:"vscode",rawPi:!1,inputs:t}),notes:n}}if(uz(e.mcp)){let t=e.mcp;if(uz(t.servers)){let e=uZ(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(uz(e.context_servers))return{entries:Object.entries(e.context_servers).map(e=>{let t,[n,r]=e;return uz(r)&&("extension"===r.source||!uD(r))?{note:{code:"zed-extension-server",params:{server:n}}}:uq(n,uz(r)?(t={...r},delete t.source,t):r,{source:"zed-json",flavor:"zed",rawPi:!1})}),notes:n};if(uD(e))return{entries:[uq(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})],notes:n};let s=Object.values(e);return s.length>0&&s.every(uz)&&s.some(uD)?{entries:r(e,{source:"server-map",flavor:"mcp-servers",rawPi:t}),notes:n}:{error:{code:"no-servers-found"}}}(n,t)}(a,!0===o.rawPi);else if(pN.test(a)){if(!("error"in(s=pk(`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)?pk(a):(e=uA(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&&u1[i]&&e[t+1]?.text==="mcp"&&(n=t,r=u1[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 u8(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=u6.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 o=s.slice(2),a=u5[o];if(!a)return{error:{code:"cli-unknown-option",params:{cli:"pi",option:s}}};if("flag"===a){r.set(o,!0);continue}let l=e[++t];if(void 0===l)return{error:{code:"cli-option-needs-value",params:{cli:"pi",option:s}}};"list"===a?i.set(o,[...i.get(o)??[],l]):r.set(o,l)}let[s,...o]=n,a=r.get("url");if(!s||""===s.text||void 0===a==(0===o.length))return{error:{code:"cli-usage",params:{cli:"pi"}}};let l=e=>{let t=r.get(e);return!0===t?void 0:t},c=(void 0===a?u3:u9).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 d4("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=uX(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=uY(a.parts,"pi",!1);let e=u("header");if("error"in e)return e;for(let[t,n]of e)d.headers.push([t,uY(n,"pi",!0)]);let t=l("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=l("oauth-client-id"),r=l("oauth-client-secret"),i=l("oauth-callback-port"),s=l("oauth-client-name");n&&(d.oauth.clientId=uY(n.parts,"pi",!1)),r&&(d.oauth.clientSecret=uY(r.parts,"pi",!0)),i&&(d.oauth.callbackPort=Number(i.text)),s&&(d.oauth.clientName=uY(s.parts,"pi",!1)),p.url=a.parts.some(e=>"variable"===e.type)?"https://placeholder.invalid/":a.text,(i||s)&&(p.oauth={...i?{callbackPort:Number(i.text)}:{},...s?{clientName:s.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,uY(n,"pi",!0)]);let[t,...n]=o;d.command=uY(t.parts,"pi",!1),d.args=n.map(e=>uY(e.parts,"pi",!1));let r=l("cwd");r&&(d.cwd=uY(r.parts,"pi",!1)),p.command=t.text}let h=l("exposure");void 0!==h&&(p.exposure=h.text,d.exposure=ux(h.text)??h.text);let f=l("description");void 0!==f&&(p.description=f.text,d.description=f.text);let m=uk("server",p);return m?{note:{code:"invalid-config",params:{server:s.text,...m}}}:{draft:d}}(t,i.slice(1)));if("claude"===r&&"add"===e)return u8(function(e){let t=u7("claude",e,pa,{asArgAfter:2,variadic:pl});if("error"in t)return{error:t.error};let n=new d4("claude-mcp-add",!1),r=po(n,"claude",t.values.get("transport"),[...t.positional,...t.afterDashDash],dO);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=ps(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=pi(n,t.lists.get("header"),dO,"claude");if(r)return{error:r};let o=t.values.get("client-id");o&&!0!==o&&(n.oauth.clientId=uY(o.parts,dO,!1)),t.values.has("client-secret")&&pc(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=pr(n,t.lists.get("env"),dO,"claude");if(e)return{error:e}}return{draft:n}}(t));if("claude"===r&&"add-json"===e)return u8(function(e){let t=u7("claude",e,pd,{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=pu(r);if("error"in s)return s;let o=uq(n.text,s.value,{source:"claude-mcp-add-json",flavor:"mcp-servers",rawPi:!1});return"note"in o||(o.draft.scopeHint=ps(t.values.get("scope")),t.values.has("client-secret")&&"http"===o.draft.transport&&!o.draft.oauth.clientSecret&&pc(o.draft)),o}(t));if("claude"===r&&"add-from-claude-desktop"===e)return{error:{code:"claude-desktop-import"}};if("codex"===r&&"add"===e)return u8(function(e){let t=u7("codex",e,pp,{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,o=n.length>0?n:s,a=t.values.get("url");if(!i||void 0===a==(0===o.length)||n.length>0&&s.length>0)return{error:{code:"cli-usage",params:{cli:"codex"}}};let l=new d4("codex-mcp-add",!1);for(let e of(l.name=i.text,["config","enable","disable"]))t.values.has(e)&&l.note("cli-option-ignored",{cli:"codex",option:t.seen.get(e)});if(t.values.has("oauth-resource")&&l.note("oauth-option-dropped",{key:"--oauth-resource"}),void 0!==a&&!0!==a){if(r.length>0)return{error:{code:"cli-option-wrong-transport",params:{cli:"codex",option:"--env",transport:"http"}}};if(void 0!==uB(a.text))return{note:uH(i.text,a.text)};l.transport="http",l.url=uY(a.parts,dW,!1);let e=t.values.get("bearer-token-env-var");e&&!0!==e&&l.headers.push(["Authorization",[{kind:"text",text:"Bearer "},{kind:"env",name:e.text,from:`\${${e.text}}`}]]);let n=t.values.get("oauth-client-id");n&&!0!==n&&(l.oauth.clientId=uY(n.parts,dW,!1))}else{for(let e of["bearer-token-env-var","oauth-client-id","oauth-resource"])if(t.values.has(e))return{error:{code:"cli-option-wrong-transport",params:{cli:"codex",option:`--${e}`,transport:"stdio"}}};l.transport="stdio";let e=pr(l,r,dW,"codex");if(e)return{error:e};l.command=uY(o[0].parts,dW,!1),l.args=o.slice(1).map(e=>uY(e.parts,dW,!1))}return{draft:l}}(t));if("gemini"===r&&"add"===e)return u8(function(e){let t=u7("gemini",e,ph,{asArgAfter:2});if("error"in t)return{error:t.error};let n=new d4("gemini-mcp-add",!1),r=po(n,"gemini",t.values.get("transport"),[...t.positional,...t.afterDashDash],dD);if("string"!=typeof r)return"cli-usage"===r.code?{error:r}:{note:r};if(n.scopeHint=ps(t.values.get("scope")),"http"===r){t.lists.has("env")&&n.note("cli-option-wrong-transport",{cli:"gemini",option:"--env",transport:"http"});let e=pi(n,t.lists.get("header"),dD,"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=pr(n,t.lists.get("env"),dD,"gemini");if(e)return{error:e}}let i=t.values.get("timeout");for(let e of(i&&!0!==i&&uu(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 uV(n,s("include-tools"),s("exclude-tools")),{draft:n}}(t));if("add"===e||"install"===e)return{error:{code:"cli-unsupported",params:{cli:r}}};if(u2.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]&&u4.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=pe(e[n],10)}if(!r)return{error:{code:"cli-option-needs-value",params:{cli:"code",option:"--add-mcp"}}};let s=pu(r);if("error"in s)return s;t.push(uq(void 0,s.value,{source:"vscode-add-mcp",flavor:"vscode",rawPi:!1}))}return{entries:t,notes:[]}}(e.slice(1)):u8(function(e){let t=new d4("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,uY(r.value,dW,!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=uY(i.parts,dW,!1),t.args=e.slice(n+1).map(e=>uY(e.parts,dW,!1));let s=e.slice(n+1).map(e=>e.text),o=s.some(e=>/^mcp-remote(?:@|$)/.test(e))?s.find(e=>uQ.test(e)):void 0;return o&&t.note("mcp-remote-bridge",{url:o}),{draft:t}}(e))}(e.words):{error:function(e){let{code:t,...n}=e;return Object.keys(n).length>0?{code:pE[t],params:n}:{code:pE[t]}}(e.error)}}if("error"in s)return{ok:!1,notes:[s.error]};let l=[...s.notes],c=[],d=[...o.takenNames??[]],u=new Set;for(let e of s.entries){if("note"in e){l.push(e.note);continue}let n=function(e){let t,n=new d3(e);if("stdio"===e.transport&&e.command&&""!==d8(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||""===d8(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:o,clientSecret:a,callbackPort:l,clientName:c,clientRegistration:d,callbackUrl:u,scope:p,authServerMetadataUrl:h}=e.oauth;o&&(s.clientId=n.encode(["oauth","clientId"],o)),a&&(s.clientSecret=n.encode(["oauth","clientSecret"],a)),void 0!==l&&(s.callbackPort=l),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){l.push(n.note);continue}let r=n.server,i=r.name,s=!i;s&&(i=function(e){if("url"in e)return ua(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&&ua(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=uc(t,new Set(["-p","--package","-c","--call"]));return e?ur(e):""}case"pnpm":case"yarn":case"bun":case"npm":{let e=t.findIndex(e=>"dlx"===e||"exec"===e||"x"===e),n=e>=0?uc(t.slice(e+1),new Set(["-p","--package"])):void 0;return n?ur(n):""}case"uvx":case"pipx":{let e=uc("pipx"===n&&"run"===t[0]?t.slice(1):t,new Set(["--from","--with","--python","-p","--index-url","--spec"]));return e?ur(e):""}case"uv":{let e=t.indexOf("run"),n=e>=0?uc(t.slice(e+1),new Set(["--with","--directory","--python","-p","--from","--project"])):void 0;return n?ud(n):""}case"docker":case"podman":{let e=t.indexOf("run"),n=e>=0?uc(t.slice(e+1),ul):void 0;if(!n)return"";let r=n.split("/").pop().replace(/[:@].*$/,"");return us(r)||r}case"python":case"python3":case"py":{let e=t.indexOf("-m");if(e>=0&&t[e+1])return ur(t[e+1].replace(/_/g,"-"));let n=uc(t,new Set(["-X","-W"]));return n?ud(n):""}case"node":case"deno":case"tsx":case"ts-node":{let e=uc("deno"===n&&"run"===t[0]?t.slice(1):t,new Set(["-r","--require","--import","--loader"]));return e?ud(e):""}default:return us(n.replace(/_/g,"-"))||n}}(e.command,t)}(r.config))&&r.notes.push({code:"name-derived",params:{name:i}});let o=(t=i,ue.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";o!==i&&i&&(r.originalName=r.originalName??i,r.notes.push({code:"name-sanitized",params:{original:i,name:o}}));let a=ut(o,s?[...d,...u]:u);a!==o&&(r.notes.push({code:"name-deduplicated",params:{original:o,name:a}}),o=a),!s&&d.includes(o)&&r.notes.push({code:"name-taken",params:{name:o,suggestedName:ut(o,[...d,...u])}}),r.name=o;let p=uk(o,function(e){let t=pI(e),n=JSON.parse(JSON.stringify(e.config));t.has(dX(["url"]))&&(n.url="https://placeholder.invalid/");let r=n.oauth;return r&&t.has(dX(["oauth","callbackUrl"]))&&delete r.callbackUrl,n}(r));if(p){l.push({code:"invalid-config",params:{server:o,...p}});continue}!function(e){let t=pI(e);for(let n of pW(e.config))t.has(dX(n))||e.notes.push({code:"literal-secret",params:{field:dQ(n)}});let n=e.config;if("url"in n){for(let[t,r]of Object.entries(n.headers??{})){let n=dV(r);n.length>0&&e.notes.push({code:"header-env-reference",params:{header:t,names:n.join(", ")}})}let t=dV(n.oauth?.clientSecret??"");t.length>0&&e.notes.push({code:"client-secret-env-reference",params:{names:t.join(", ")}})}}(r),u.add(o),c.push(r)}return 0===c.length?{ok:!1,notes:l.length>0?l:[{code:"no-servers-found"}]}:{ok:!0,servers:c,notes:l}}let p$=/^[A-Za-z_][A-Za-z0-9_]*$/;function pM(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 pR(e){let t=pI(e);return pW(e.config).filter(e=>d0(e)&&!t.has(dX(e)))}function pL(e){return"string"==typeof e&&""===e.trim()?"missing":"name"}let pA=/^(?:bearer|basic|token)\s+/i;function pP(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.parse(JSON.stringify(e.config)),i=new Map,s=[],o=new Map(pR(e).map(e=>[dQ(e),e])),a=[];for(let[e,t]of Object.entries(n)){let n="string"==typeof t?t.trim():"",r=o.get(e);r?p$.test(n)?a.push([r,n]):s.push({code:"field-reference-invalid",params:{field:e,problem:pL(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():"";p$.test(r)?"select"!==n.kind&&n.targets.every(e=>d0(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:pL(t)}});continue}let r=("string"==typeof e?e:n.defaultValue??"").trim();""===r?n.optional?i.set(n.id,void 0):s.push({code:"field-required",params:{field:n.id}}):"select"===n.kind&&n.options&&!n.options.includes(r)?s.push({code:"field-invalid-option",params:{field:n.id}}):i.set(n.id,{text:r})}if(s.length>0)return{ok:!1,notes:s};let l=new Set,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&&l.add(dQ(e.path));let s=dX(e.path);if(c.has(s))continue;if(c.add(s),e.parts.some(e=>"string"!=typeof e&&void 0===i.get(e.field))){pM(r,e.path,void 0);continue}let o="";for(let t of e.parts){var d,u,p,h;o+="string"==typeof t?t:(d=i.get(t.field),u=e.path,p=""===o,h=e.encoding,"reference"in d?`\${${d.reference}}`:"uri-component"===h?encodeURIComponent(d.text):d0(u)?dq(d.text,{atStart:p}):d.text)}pM(r,e.path,o)}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(pA)?.[0]??"":"";pM(r,e,`${i}\${${t}}`)}for(let e of pW(r))l.add(dQ(e));return{ok:!0,config:r,secretPaths:[...l]}}let pz=["command","args","env","cwd","url","headers","oauth"];function pW(e){let t=[];for(let n of function(e){if(!dL(e))return[];let t=[];for(let n of["env","headers"]){let r=e[n];if(dL(r))for(let[e,i]of Object.entries(r))"string"==typeof i&&dA(i)&&""!==i&&(dd(e)||/^(?:bearer|basic|token)\s+\S/i.test(i)||dI(i,db).masked)&&t.push({kind:"env"===n?"env":"header",name:e})}let n=dL(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&""!==n&&dA(n)&&t.push({kind:"oauth-client-secret"}),"string"==typeof e.url&&dC(e.url,dk).masked&&t.push({kind:"url"}),"string"==typeof e.command&&dI(e.command,dk).masked&&t.push({kind:"command"}),Array.isArray(e.args)&&dR(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:""):[];dR(n).args.forEach((e,r)=>{e!==n[r]&&t.push(["args",r])})}}return t.sort((e,t)=>pz.indexOf(e[0])-pz.indexOf(t[0]))}let pO="PI_WEB_PASSWORD";function pD(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function pF(e){return pD(e)?Object.entries(e).filter(e=>"string"==typeof e[1]):[]}function pB(e){if(!pD(e))return[];if(!("url"in e))return pF(e.env).map(e=>{let[t,n]=e;return{kind:"env",name:t,value:n}});let t=pF(e.headers).map(e=>{let[t,n]=e;return{kind:"header",name:t,value:n}}),n=pD(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&t.push({kind:"oauth-client-secret",value:n}),t}let pH={text:"",rawPi:!1,server:0,values:{},references:{},secretReferences:{}};function pU(e,t,n){let r=pT(e,{rawPi:t});if(!r.ok)return;let i=r.servers[Math.min(n,r.servers.length-1)],{config:s}=i,o="url"in s?["url",s.url]:["command",s.command,s.args??[]];return JSON.stringify([i.source,i.originalName??i.name,o])}function p_(e,t){let n={...e,...t},r=pU(e.text,e.rawPi,e.server);if(void 0!==r&&r===pU(n.text,n.rawPi,e.server))return n;let i={...n,server:0,values:{},references:{},secretReferences:{}};return delete i.name,i}function pq(e){return dz[e.code]??"warning"}function pK(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?l5(t):t;if("string"==typeof i.field&&e.code.startsWith("field-")){let e=r.find(e=>e.id===i.field);e&&(s.field=l5(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 o=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:o}):o}let pV={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"},pZ={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"},pJ=JSON.stringify({command:"uvx",args:["mcp-server-fetch"]}),pG=JSON.stringify({name:"fetch",command:"uvx",args:["mcp-server-fetch"]}),pY=[{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 '${pG}'`},{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(pJ)}`},{source:"vscode-install-link",text:`vscode:mcp/install?${encodeURIComponent(pG)}`},{source:"visual-studio-install-link",text:`vsweb+mcp:/install?${encodeURIComponent(pG)}`},{source:"copilot-app-install-link",text:`ghapp://mcp/install?${encodeURIComponent(pG)}`}];function pX(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?l5(r):r.field===e.id?n:`‹${l5(t.find(e=>{let{id:t}=e;return t===r.field})?.label??r.field)}›`).join("")}))].join(", ")}function pQ(e){return"select"!==e.kind&&e.targets.every(e=>d0(e.path)&&void 0===e.encoding)}let p0=/^[A-Za-z_][A-Za-z0-9_]*$/;function p1(){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 p0.test(r)?r:void 0}let p2=/^(?:proxy-)?authorization$/i;function p4(e,t){let n=function(e,t){if(e.startsWith("env.")){let t=e.slice(4);return p0.test(t)?t:p1(t)}let n=function(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];return p1(t,...n)??p1(...n)};if(e.startsWith("headers.")){let t=e.slice(8);return n(p2.test(t)?"TOKEN":t.replace(/^x-/i,""))}if("oauth.clientSecret"===e)return n("CLIENT_SECRET")}(e,t);return n===pO?void 0:n}function p8(e){return e.startsWith("env.")||e.startsWith("headers.")||"oauth.clientSecret"===e}function p5(e,t){let n=e;for(let e of t)n=n.split(e).join(dt);return{text:n,masked:n!==e}}function p6(e){let{kind:t,name:n}=e;return void 0===n?{kind:t}:{kind:t,name:n}}function p3(e,t){let n=t.files.find(t=>t.scope===e),r=n?.problems.find(cC);return n&&r?{kind:"file-problem",path:n.path,reason:r.reason}:void 0}function p9(e,t){return e.servers.filter(e=>e.scope===t).map(e=>e.name)}function p7(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 he(e,t,n){switch(e.kind){case"trust-too-broad":return t(hn[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(ht[e.kind])}}let ht={"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"},hn={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 hr(e){return l5(lb(e))}function hi(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}let hs=[{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"}],ho=new Set(["name-derived","name-sanitized","name-deduplicated","name-taken"]);function ha(e){let{notes:t,fields:n=[]}=e,{t:i}=(0,eO.s)();if(0===t.length)return null;let s={error:0,warning:1,info:2},o=[...t].sort((e,t)=>s[pq(e)]-s[pq(t)]);return(0,r.jsx)("ul",{className:"mcp-add-notes",children:o.map((e,t)=>(0,r.jsx)("li",{className:`mcp-add-note is-${pq(e)}`,children:pK(e,i,n)},`${t}\0${e.code}`))})}let hl={"server-invalid":"mcp.add.refused.server-invalid","web-password":"mcp.add.blocked.web-password"};function hc(e){let{data:t,cwd:n,draft:s,busy:o,controlsBusy:a,failure:l,onDraftChange:c,onSubmit:d,onTrustProject:u}=e,{t:p}=(0,eO.s)(),h=(0,i.useId)(),f=(0,i.useId)(),m=(0,i.useMemo)(()=>(function e(t,n,r){let i,s=function(e,t){let n=e=>({kind:"blocked",block:e});if(!t)return n({kind:"no-project"});let r=e.project;if(!r)return n({kind:"project-not-listed"});let i=r.trust;if(!i||void 0!==i.decisionError)return n({kind:"trust-unreadable"});if(!0===i.decision)return{kind:"write"};if(!1===i.decision)return n({kind:"untrusted-decision"});if(i.requiresTrust)return n({kind:"project-untrusted",trustable:cT(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),o=e=>pT(t.text,{rawPi:t.rawPi,takenNames:p9(n,e)}),a=o(t.scope??"global"),l=a.ok?a.servers[Math.min(t.server,a.servers.length-1)]:void 0,c=t.scope??(l?.scopeHint==="project"&&"write"===s.kind?"project":"global");c!==(t.scope??"global")&&(l=(a=o(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=cJ(n.mcp);if(!l)return{...d,submitBlock:{kind:u?"mcp-off":"nothing"}};let p=t.name??l.name,h=function(e,t){let n={};for(let r of e.fields){let e=t.references[r.id];void 0!==e&&pQ(r)?n[r.id]={reference:e}:void 0!==t.values[r.id]&&(n[r.id]=t.values[r.id])}return n}(l,t),f=pR(l).map(dQ),m=Object.fromEntries(f.flatMap(e=>{let n=t.secretReferences[e];return void 0===n?[]:[[e,n]]})),g=pP(l,h,m),x={};if(!g.ok)for(let e of g.notes){let t=e.params?.field;"field-required"===e.code||"string"!=typeof t||t in x||(x[t]=e)}let v=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={};for(let n of e.fields){let e=t[n.id];"object"==typeof e?r[n.id]=p0.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=pP(e,r,Object.fromEntries(Object.entries(n).map(e=>{let[t,n]=e;return[t,p0.test(n.trim())?n:"VALUE"]})));return i.ok?i.secretPaths:[]}(l,h,m),b=function(e,t,n){let r=n?.ok?n.config:e.config,i=n?.ok?function(e,t){let n=new Set;for(let r of e.fields){let e=t[r.id];if("password"!==r.kind||"string"!=typeof e||""===e.trim())continue;let i=e.trim();n.add(i),n.add(i.replace(/\$/g,"$$$$")),n.add(encodeURIComponent(i))}return[...n].filter(e=>""!==e).sort((e,t)=>t.length-e.length)}(e,t):[],s=!1!==r.enabled,o={source:e.source,commandFields:pB(r).filter(e=>{let{value:t}=e;return dK(t)}).map(p6),variableReferences:pB(r).map(e=>({...p6(e),variables:dV(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=p5(r.url,i);return{...o,transport:"http",target:l5(e.text),envNames:[],headerNames:Object.keys(r.headers??{}),masked:e.masked}}let a=p5(l9(r.command,r.args??[]),i);return{...o,transport:"stdio",target:a.text,...void 0!==r.cwd?{cwd:l5(r.cwd)}:{},envNames:Object.keys(r.env??{}),headerNames:[],masked:a.masked}}(l,h,g),y=g.ok?uk(p,g.config):void 0,j="blocked"===s.kind?s.block:v.length>0?{kind:"secret",fields:v,fixed:!v.every(p8)}:p3("project",n),k=p9(n,c),w=n.files.find(e=>e.scope===c);if(u)i={kind:"mcp-off"};else if(ue.test(p))if(k.includes(p))i={kind:"name-taken",name:p,suggestedName:ut(p,k),...w?{path:w.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 pB(e))if(t.isCommandConfigValue(n)?n.toUpperCase().includes(pO):t.getConfigValueEnvVarNames(n).some(e=>e.toUpperCase()===pO))return r}(g.config,{isCommandConfigValue:dK,getConfigValueEnvVarNames:dV}))i={kind:"web-password"};else if("project"===c&&j)i={kind:"scope",block:j};else{let e=p3(c,n);e&&(i={kind:"scope",block:e})}else{let e=e=>{let t=String(e.params?.field??"");return l.fields.find(e=>e.id===t)?.label??t},t=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&&j?e({...t,scope:"global"},n,r):{parsed:a,server:l,name:p,scope:c,projectMode:s,...j?{projectBlock:j}:{},values:h,pasteSecrets:f,secretReferences:m,fill:g,fieldProblems:x,secretPaths:v,preview:b,...i?{submitBlock:i}:{},trustFolder:"project"===c&&"trust-and-write"===s.kind}})(s,t,n),[s,t,n]),g=(0,i.useMemo)(()=>(function(e){let t=pT(e,{rawPi:!0});if(!t.ok)return!1;let n=pT(e,{rawPi:!1});return t.servers.some((e,t)=>e.rawPi&&!(n.ok&&n.servers[t]?.rawPi))})(s.text),[s.text]),{parsed:x,server:v,preview:b,projectBlock:y,submitBlock:j}=m,k=v?[...v.notes,...x.notes].filter(e=>"literal-secret"!==e.code||!m.pasteSecrets.includes(String(e.params?.field))):[],w=void 0!==s.name&&s.name!==v?.name?[]:k.filter(e=>ho.has(e.code)),S=k.filter(e=>!ho.has(e.code)),C=!o&&!a&&void 0===j,N=()=>{C&&d(p7(s,m))},E=e=>c({...s,...e}),I=t.files.find(e=>e.scope===m.scope)?.path??("project"===m.scope&&n?`${n.replace(/[\\/]+$/,"")}/.pi/mcp.json`:"mcp.json"),T=j&&(""!==s.text.trim()||"mcp-off"===j.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:l5(e.name),path:e.path?hr(e.path):"mcp.json"});case"fields":return t("mcp.add.blocked.fields",{fields:e.fields.map(l5).join(", ")});case"field-invalid":return t("mcp.add.blocked.fieldsInvalid",{fields:e.fields.map(l5).join(", ")});case"config-invalid":return pK(e.note,t,n);case"web-password":return t("mcp.add.blocked.web-password");case"scope":return he(e.block,t,hr)}}(j,p,v?.fields):void 0,$=y?.kind==="project-untrusted"&&y.trustable&&u,M=b?"http"===b.transport?b.headerNames:b.envNames:[];return(0,r.jsxs)(aI,{title:p("mcp.add.title"),catalogs:hs,target:(0,r.jsxs)(aN,{value:m.scope,label:p("config.saveTo"),options:[{value:"global",label:hi("global",p)},{value:"project",label:hi("project",p),disabled:void 0!==y&&"project"!==m.scope}],path:hr(I),disabledReason:y?he(y,p,hr):null,onChange:e=>E({scope:e}),children:[$&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aP,{size:"small",onClick:u,children:p("mcp.trust.trustButton")})}),m.trustFolder&&"trust-and-write"===m.projectMode.kind&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:p("mcp.add.trustExplain",{path:hr(m.projectMode.folder)})})]}),inputLabel:p("mcp.add.inputLabel"),inputId:"mcp-add-source",placeholder:p("mcp.add.placeholder"),value:s.text,canSubmit:C,onValueChange:e=>c(p_(s,{text:e})),onSubmit:N,examplesLabel:p("mcp.add.examples"),examples:""===s.text.trim()?pY.map(e=>{let{source:t,text:n}=e;return{label:p(pZ[t]),value:n}}):[],multiline:!0,children:[g&&(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:s.rawPi,onChange:e=>c(p_(s,{rawPi:e.target.checked}))}),(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line",children:p("mcp.add.rawPi")}),s.rawPi&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.rawPiOn")})]})]}),!x.ok&&""!==s.text.trim()&&(0,r.jsx)(ha,{notes:x.notes}),x.ok&&x.servers.length>1&&(0,r.jsxs)(aj,{label:p("mcp.add.serverLabel"),children:[(0,r.jsx)("select",{className:"mcp-add-input","aria-label":p("mcp.add.serverLabel"),value:String(x.servers.indexOf(v??x.servers[0])),onChange:e=>E({server:Number(e.target.value),name:void 0,values:{},references:{},secretReferences:{}}),children:x.servers.map((e,t)=>(0,r.jsx)("option",{value:t,children:l5(e.name)},`${t}\0${e.name}`))}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.serverCount",{count:x.servers.length})})]}),v&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(aj,{label:p("config.name"),children:(0,r.jsx)("input",{id:f,className:"mcp-add-input","aria-label":p("config.name"),value:m.name,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>E({name:e.target.value})})}),(0,r.jsx)(ha,{notes:w,fields:v.fields}),j?.kind==="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aP,{size:"small",onClick:()=>E({name:j.suggestedName}),children:p("mcp.add.useName",{name:l5(j.suggestedName)})})})]}),v&&b&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ay,{children:p("mcp.add.preview")}),(0,r.jsxs)(ak,{children:[(0,r.jsx)(aw,{label:p("mcp.add.readAs"),children:p(pZ[b.source])}),(0,r.jsx)(aw,{label:p("mcp.detail.transport"),children:p(`mcp.transport.${b.transport}`)}),(0,r.jsx)(aw,{label:"http"===b.transport?p("mcp.detail.url"):p("mcp.detail.command"),tone:"plain",mono:!0,children:b.target}),"stdio"===b.transport&&void 0!==b.cwd&&(0,r.jsx)(aw,{label:p("mcp.detail.cwd"),mono:!0,children:b.cwd}),M.length>0&&(0,r.jsx)(aw,{label:"http"===b.transport?p("mcp.detail.headers"):p("mcp.detail.env"),children:(0,r.jsx)(hd,{names:M})}),b.commandFields.length>0&&(0,r.jsx)(aw,{label:p("mcp.detail.shellCommands"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.server.commandFields")}),(0,r.jsx)("span",{className:"mcp-config-chips",children:b.commandFields.map(e=>{let t=ct(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})]})}),b.variableReferences.length>0&&(0,r.jsx)(aw,{label:p("mcp.detail.variables"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("http"===b.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables")}),(0,r.jsx)("span",{className:"mcp-config-chips",children:ci(b.variableReferences).map(e=>{let{variable:t,field:n}=e,i=ct(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p("mcp.server.variableIn",{variable:l5(t),field:p(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[b.unfilled&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.previewUnfilled")}),b.masked&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.server.masked")})]}),(0,r.jsx)(ha,{notes:S,fields:v.fields}),v.fields.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ay,{children:p("mcp.add.fields")}),v.fields.map(e=>{var t;let n;return(0,r.jsx)(hu,{field:e,fields:v.fields,draft:s,suggestedName:(t=m.name,(n=e.targets[0])?p4(dQ(n.path),t):void 0),problem:m.fieldProblems[e.id],onDraftChange:c},e.id)})]}),m.pasteSecrets.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ay,{children:p("mcp.add.secrets")}),m.pasteSecrets.map(e=>{var t,n;let i;return(0,r.jsx)(hp,{label:e,draft:s,suggestedName:p4(e,m.name),stored:m.fill?.ok?(t=m.fill.config,void 0!==(i="oauth.clientSecret"===(n=e)?"url"in t?t.oauth?.clientSecret:void 0:n.startsWith("headers.")?"url"in t?t.headers?.[n.slice("headers.".length)]:void 0:n.startsWith("env.")&&"command"in t?t.env?.[n.slice("env.".length)]:void 0)&&db(i)?i:void 0):void 0,problem:m.fieldProblems[e],onDraftChange:c},e)})]})]}),(0,r.jsx)(aP,{variant:"primary",className:"is-pushed-right",disabled:!C,"aria-busy":o||void 0,"aria-describedby":T?h:void 0,onClick:N,children:o?p("mcp.add.adding"):m.trustFolder?p("mcp.add.buttonTrust"):p("mcp.add.button")}),T&&(0,r.jsx)("p",{id:h,className:`mcp-config-line ${j?.kind==="scope"?"is-warning":"is-dim"}`,children:T}),v&&!j&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:p("mcp.add.afterAdd")}),l&&(0,r.jsxs)("div",{role:"alert",className:"mcp-add-failure",children:[(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[p("mcp.add.failed")," ",function(e,t){if(e.timedOut)return t("mcp.actionTimedOut");if("trust-too-broad"===e.reason&&e.breadth)return t(hn[e.breadth.kind],{path:hr(e.breadth.path)});if("secret-global-only"===e.reason&&e.fields)return t(e.fields.every(p8)?"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:l5(e.name),path:e.path?hr(e.path):"mcp.json"});let n=e.reason?hl[e.reason]:void 0;return n?t(n,{error:l5(e.error)}):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):l5(e.error)}(l,p)]}),l.trustKept&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.trustKept",{folder:hr(l.trust?.decisionPath??n??"")})}),l.notes&&l.notes.length>0&&(0,r.jsx)(ha,{notes:l.notes,fields:v?.fields}),"name-taken"===l.reason&&l.suggestedName&&j?.kind!=="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aP,{size:"small",onClick:()=>E({name:l.suggestedName}),children:p("mcp.add.useName",{name:l5(l.suggestedName)})})}),"host-env-confirm"===l.reason&&l.names&&l.names.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.hostEnv.body",{names:l.names.map(l5).join(", ")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aP,{variant:"danger",size:"small",disabled:o||a||void 0!==j,onClick:()=>d(p7(s,m,l.names)),children:p("mcp.add.hostEnv.confirm")})})]})]})]})}function hd(e){let{names:t}=e,{t:n}=(0,eO.s)();return(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>(0,r.jsx)("code",{className:"mcp-config-chip",children:l5(e)},e))}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.detail.valuesHidden")})]})}function hu(e){let t,{field:n,fields:s,draft:o,suggestedName:a,problem:l,onDraftChange:c}=e,{t:d}=(0,eO.s)(),u=(0,i.useId)(),p=l?{"aria-invalid":!0,"aria-describedby":u}:{},h=pQ(n),f=h?o.references[n.id]:void 0,m=void 0!==f,g=l5(n.label),x=o.values[n.id]??n.defaultValue??"",v=pV[n.reason],b=n.optional&&1===(t=new Set(n.targets.map(e=>{let{path:t}=e;return"headers"===t[0]?t[1]:void 0}))).size?[...t][0]:void 0,y=m?f&&!l?pX(n,s,"${"+f+"}",!0):void 0:pX(n,s,`‹${d("mcp.add.field.slot")}›`),j=e=>c({...o,values:{...o.values,[n.id]:e}}),k=e=>{let t={...o.references};void 0===e?delete t[n.id]:t[n.id]=e,c({...o,references:t})};return(0,r.jsxs)("div",{className:"mcp-add-field",children:[(0,r.jsx)(aj,{label:g,children:m?(0,r.jsx)("input",{className:"mcp-add-input","aria-label":d("mcp.add.field.variableName",{field:g}),value:f,placeholder:a??"GITHUB_TOKEN",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...p,onChange:e=>k(e.target.value)}):"select"===n.kind?(0,r.jsxs)("select",{className:"mcp-add-input","aria-label":g,value:x,...p,onChange:e=>j(e.target.value),children:[!n.options?.includes(x)&&(0,r.jsx)("option",{value:"",children:d("mcp.add.field.choose")}),(n.options??[]).map(e=>(0,r.jsx)("option",{value:e,children:l5(e)},e))]}):(0,r.jsx)("input",{className:"mcp-add-input",type:"password"===n.kind?"password":"text","aria-label":g,value:x,autoComplete:"off",placeholder:n.placeholder?l5(n.placeholder):void 0,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...p,onChange:e=>j(e.target.value)})}),l&&(0,r.jsx)("span",{id:u,className:"mcp-config-line is-error",children:pK(l,d,[n])}),(0,r.jsxs)("span",{className:"mcp-config-lines",children:[n.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:l5(n.description)}),v&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:d(v)}),m?(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:y?d("mcp.add.field.storedAsVariable",{value:y}):d("mcp.add.field.variableHint")}):(0,r.jsxs)(r.Fragment,{children:[y&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:d("mcp.add.field.storedAs",{value:y})}),n.optional&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:b?d("mcp.add.field.optionalHeader",{name:l5(b)}):d("mcp.add.field.optional")})]})]}),h&&(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:m,onChange:e=>k(e.target.checked?a??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("mcp.add.field.useVariable")})]})]})}function hp(e){let{label:t,draft:n,suggestedName:s,stored:o,problem:a,onDraftChange:l}=e,{t:c}=(0,eO.s)(),d=(0,i.useId)(),u=n.secretReferences[t],p=void 0!==u,h=l5(t),f=e=>{let r={...n.secretReferences};void 0===e?delete r[t]:r[t]=e,l({...n,secretReferences:r})};return(0,r.jsxs)("div",{className:"mcp-add-field",children:[(0,r.jsx)("span",{className:"mcp-config-lines",children:(0,r.jsxs)("span",{className:"mcp-config-line",children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:h})," ",c("mcp.add.secret.holds")]})}),(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:p,onChange:e=>f(e.target.checked?s??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:c("mcp.add.field.useVariable")})]}),p&&(0,r.jsx)(aj,{label:c("mcp.add.field.variableName",{field:h}),children:(0,r.jsx)("input",{className:"mcp-add-input","aria-label":c("mcp.add.field.variableName",{field:h}),value:u,placeholder:s??"API_TOKEN",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...a?{"aria-invalid":!0,"aria-describedby":d}:{},onChange:e=>f(e.target.value)})}),a&&(0,r.jsx)("span",{id:d,className:"mcp-config-line is-error",children:pK(a,c)}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p?void 0!==o?c("mcp.add.secret.storedAs",{value:l5(o)}):c("mcp.add.field.variableHint"):c("mcp.add.secret.asPasted")})]})}let hh=new Set(["done","failed","cancelled","expired"]);function hf(e){var t;return e?.flow!==void 0&&!e.gone&&(t=e.flow.phase,!hh.has(t))}let hm={"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"},hg={"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"},hx={connecting:"mcp.signIn.phase.connecting",starting:"mcp.signIn.phase.starting",finishing:"mcp.signIn.phase.finishing"},hv={"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 hb(e,t,n){var r;let i={...e,flow:t,deadlineAt:n+t.expiresInMs,gone:!1};return r=t.phase,hh.has(r)&&(delete i.pasteError,delete i.cancelError,i.pasting&&(i.pasting=!1),i.cancelling&&(i.cancelling=!1)),i}function hy(e){return"sign-in-unknown"===e.reason}async function hj(e,t,n,r){var i;let s,o;try{s=await n(e,{...t,cache:"no-store",signal:r})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{o=await s.json()}catch{return{ok:!1,error:{error:`HTTP ${s.status}`}}}return s.ok&&null!==(i=o)&&"object"==typeof i&&"string"==typeof i.flowId&&"string"==typeof i.phase&&"string"==typeof i.name&&("global"===i.scope||"project"===i.scope)&&"number"==typeof i.expiresInMs?{ok:!0,data:o}:{ok:!1,error:cW(o,s.status)}}function hk(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},o=t.method??"GET";return cO(r=>hj(e,t,n,r),()=>({ok:!1,error:{error:`${o} ${e} did not answer within ${i} ms`,timedOut:!0}}),i,r,s)}function hw(e){return`/api/mcp/sign-in/${encodeURIComponent(e)}`}function hS(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?hg[e.reason]:void 0;return r?t(r):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function hC(e){let{server:t,run:n,block:s,signOutBlock:o,controlsBusy:a,signingOut:l,onSignIn:c,onSignOut:d,onPaste:u,onCancel:p}=e,{t:h}=(0,eO.s)(),f=(0,i.useId)(),m=(0,i.useId)(),g=(0,i.useId)(),x=(0,i.useRef)(null),v=(0,i.useRef)(null),b=hf(n),y=(0,i.useRef)(b);if((0,i.useEffect)(()=>{let e=y.current;y.current=b,!e&&b?eN(document,v.current):e&&!b&&eN(document,x.current)},[b]),!t.usesOAuth)return void 0===t.authProvider&&t.headerNames.some(e=>"authorization"===e.toLowerCase())?null:(0,r.jsx)(aw,{label:h("mcp.detail.signIn"),children:void 0!==t.authProvider?h("mcp.signIn.provider",{provider:l5(t.authProvider)}):h("mcp.signIn.header")});let j=n?.flow,k=n?.starting===!0,w=void 0!==j&&(j.scope!==t.scope||j.name!==t.name),S=(t.oauthStateStored??t.signedIn)!==!1,C=k||l||void 0!==s,N=a||k||void 0!==o,E=j?.phase==="finishing";return(0,r.jsx)(aw,{label:h("mcp.detail.signIn"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line",children:h(!0===t.signedIn?"mcp.signIn.signedIn":!1===t.signedIn?t.oauthStateStored?"mcp.signIn.registrationOnly":"mcp.signIn.notSignedIn":"mcp.signIn.unknown")}),j&&b&&w&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.shared",{name:l5(j.name)})}),j&&b&&("authorize"===j.phase?(0,r.jsx)(hN,{flow:j,pasting:n?.pasting===!0,pasteError:n?.pasteError,onPaste:e=>u(t,j.flowId,e)},j.flowId):(0,r.jsx)("span",{role:"status",className:"mcp-config-line",children:h(hx[j.phase]??"mcp.signIn.phase.connecting")})),j&&b&&E&&(0,r.jsx)("span",{id:g,className:"mcp-config-line is-dim",children:h("mcp.signIn.phase.noCancel")}),j&&!b&&!n?.gone&&(0,r.jsx)(hE,{flow:j,shared:w}),n?.gone&&(0,r.jsx)("span",{role:"alert",className:"mcp-config-line is-warning",children:h("mcp.signIn.gone")}),n?.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.requestFailed")," ",hS(n.error,h)]}),b&&n?.cancelError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.cancelFailed")," ",hS(n.cancelError,h,"mcp.signIn.cancelTimedOut")]}),n?.signOutError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.signOutFailed")," ",hS(n.signOutError,h,"mcp.actionTimedOut")]}),n?.signedOut&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line",children:h(n.signedOut.removed?"mcp.signIn.signedOutDone":"mcp.signIn.signedOutNothing")}),s&&(0,r.jsx)("span",{id:f,className:"mcp-config-line is-dim",children:h(hm[s])}),!s&&o&&S&&!b&&(0,r.jsx)("span",{id:m,className:"mcp-config-line is-dim",children:h(hm[o])}),(0,r.jsxs)("div",{className:"mcp-sign-in-actions",children:[b&&j?(0,r.jsx)(aP,{ref:v,size:"small",disabled:n?.cancelling===!0||E,"aria-busy":n?.cancelling===!0||void 0,"aria-describedby":E?g:void 0,onClick:()=>p(t,j.flowId),children:h(n?.cancelling?"mcp.signIn.cancelling":"mcp.signIn.cancel")}):(0,r.jsx)(aP,{ref:x,size:"small",variant:"primary",disabled:C,"aria-busy":k||void 0,"aria-describedby":s?f:void 0,onClick:()=>c(t),children:h(k?"mcp.signIn.starting":"mcp.signIn.button")}),S&&!b&&(0,r.jsx)(aP,{size:"small",disabled:N,"aria-busy":l||void 0,"aria-describedby":o?s?f:m:void 0,onClick:()=>d(t),children:h(l?"mcp.signIn.signingOut":"mcp.signIn.signOut")})]}),!s&&!b&&S&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.replaces")}),S&&!o&&!b&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.signOutExplain")})]})})}function hN(e){let{flow:t,pasting:n,pasteError:s,onPaste:o}=e,{t:a}=(0,eO.s)(),[l,c]=(0,i.useState)(""),d=(0,i.useRef)(null),u=(0,i.useRef)(n);(0,i.useEffect)(()=>{let e=u.current;u.current=n,e&&!n&&eN(document,d.current)},[n]);let p=function(e){if(void 0!==e)try{let t=new URL(e);return"https:"===t.protocol||"http:"===t.protocol?t.href:void 0}catch{return}}(t.authorizationUrl);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(aG,{message:a("mcp.signIn.authorize.message"),hint:p?(0,r.jsxs)(r.Fragment,{children:[a("mcp.signIn.authorize.link")," ",(0,r.jsx)("a",{href:p,target:"_blank",rel:"noopener noreferrer",children:l5(p)})]}):(0,r.jsxs)(r.Fragment,{children:[a("mcp.signIn.authorize.notALink")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:l5(t.authorizationUrl??"")})]}),value:l,placeholder:a("mcp.signIn.paste.placeholder"),inputLabel:a("mcp.signIn.paste.label"),submitLabel:a(n?"mcp.signIn.paste.checking":"mcp.signIn.paste.submit"),disabled:n,plainEnterSubmits:!1,inputRef:d,onValueChange:c,onSubmit:()=>o(l)}),s&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[a("mcp.signIn.paste.refused")," ",hS(s,a,"mcp.signIn.paste.timedOut"),"redirect-denied"===s.reason&&s.error&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:l5(s.error)})]})]}),t.redirectUrl&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:a("mcp.signIn.authorize.redirect",{url:l5(t.redirectUrl)})}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:a("mcp.signIn.authorize.wait")})]})}function hE(e){let{flow:t,shared:n}=e,{t:i}=(0,eO.s)(),s=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];switch(e.phase){case"done":{if(t)return e.alreadySignedIn?"mcp.signIn.shared.already":"mcp.signIn.shared.done";if(e.alreadySignedIn)return"mcp.signIn.done.already";let n=e.result;if(n&&"needs-auth"===n.state)return"mcp.signIn.done.needsAuthAfter";if(n&&"failed"===n.state)return"mcp.signIn.done.failedAfter";if(!n)return"mcp.signIn.done.notConnected";return e.refreshed?"mcp.signIn.done.refreshed":"mcp.signIn.done.signedIn"}case"failed":if(t&&"connect-failed"===e.failure)return"mcp.signIn.shared.connect-failed";return hv[e.failure??"internal"];case"cancelled":return"mcp.signIn.cancelled";case"expired":return"mcp.signIn.expired";default:return}}(t,n);if(!s)return null;let o=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return"done"===e.phase?!t&&e.result&&"connected"!==e.result.state?"warning":"on":"failed"===e.phase?"error":"expired"===e.phase?"warning":"off"}(t,n);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{role:"status",className:"error"===o?"mcp-config-line is-error":"warning"===o?"mcp-config-line is-warning":"mcp-config-line",children:i(s,{name:l5(t.name)})}),t.error&&(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[i("mcp.test.error")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:l5(t.error)})]})]})}function hI(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function hT(e){return l5(lb(e))}function h$(e,t){let{key:n,params:r}=e;return r?t(n,void 0===r.path?r:{...r,path:hT(r.path)}):t(n)}function hM(e,t){return e.timedOut?t("mcp.loadTimedOut"):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function hR(e,t){return e.timedOut?t("mcp.actionTimedOut"):hM(e,t)}function hL(){if("u"<typeof document)return null;let e=document.activeElement;return e instanceof HTMLButtonElement||e instanceof HTMLSelectElement?e:null}function hA(e){let{cwd:t,onClose:n,embedded:s=!1,trust:o,onTrustProject:a,onProjectTrustChanged:l}=e,[c,d]=(0,i.useState)({state:"loading"}),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(()=>o1("mcp",t)),[m,g]=(0,i.useState)({saving:!1,error:null}),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(null),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),[E,I]=(0,i.useState)({}),T=(0,i.useRef)(0),$=(0,i.useRef)(null),M=(0,i.useRef)(null),R=(0,i.useRef)(null),L=(0,i.useRef)(new Map),[A,P]=(0,i.useState)({}),z=(0,i.useRef)(A);z.current=A;let[W,O]=(0,i.useState)(0),[D,F]=(0,i.useState)(!1),[B,H]=(0,i.useState)(pH),U=(0,i.useRef)(B);U.current=B;let[_,q]=(0,i.useState)(null),[K,V]=(0,i.useState)(null),Z=(0,i.useRef)(!0),J=(0,i.useRef)(c);J.current=c;let G=(0,i.useCallback)(async()=>{let e=++T.current;$.current?.abort();let n=new AbortController;$.current=n,p(!0);let r=await cU(t,void 0,n.signal);if(e===T.current){if(p(!1),!r.ok)return void d({state:"failed",error:r.error});d({state:"loaded",data:r.data,...r.projectError?{projectError:r.projectError}:{}}),f(e=>cI(cN(r.data,!!t),e))}},[t]),Y=lk(o);(0,i.useEffect)(()=>(G(),()=>{T.current+=1,$.current?.abort()}),[G,Y]);let X=(0,i.useCallback)(async e=>{let t=new AbortController;M.current=t,g({saving:!0,error:null,target:"preference"});let n=await cK(e,void 0,t.signal);M.current===t&&(M.current=null,g({saving:!1,error:n.ok?null:n.error,target:"preference"}),n.ok&&d(e=>{var t,r;let i;return"loaded"===e.state?{...e,data:(t=e.data,r=n.preference,i={...t.codemode,preference:r},delete i.preferenceError,{...t,codemode:i})}:e}),G())},[G]),Q=(0,i.useCallback)(async e=>{let t=new AbortController;M.current=t,g({saving:!0,error:null,target:"mode"});let n=await cV(e,void 0,t.signal);M.current===t&&(M.current=null,g({saving:!1,error:n.ok?null:n.error,target:"mode"}),n.ok&&d(e=>"loaded"===e.state?{...e,data:function(e,t){let n=e.codemode.mode;if(!n)return e;let r={settingsPath:n.settingsPath,...n.projectOverride?{projectOverride:n.projectOverride}:{},...t};return{...e,codemode:{...e.codemode,mode:r}}}(e.data,n.mode)}:e),G())},[G]),ee=(0,i.useCallback)(async e=>{let t=new AbortController;M.current=t,g({saving:!0,error:null,target:"inlineBudget"});let n=await cZ(e,void 0,t.signal);M.current===t&&(M.current=null,g({saving:!1,error:n.ok?null:n.error,target:"inlineBudget"}),n.ok&&d(e=>"loaded"===e.state?{...e,data:function(e,t){let n=e.codemode.inlineBudget;if(!n)return e;let r={settingsPath:n.settingsPath,default:n.default,max:n.max,...n.projectOverride?{projectOverride:n.projectOverride}:{},...t};return{...e,codemode:{...e.codemode,inlineBudget:r}}}(e.data,n.inlineBudget)}:e),G())},[G]);(0,i.useEffect)(()=>{let e=L.current;return Z.current=!0,()=>{Z.current=!1,M.current?.abort(),M.current=null,R.current?.abort(),R.current=null,e.clear()}},[]);let et=(0,i.useCallback)(async e=>{let n=ca(e);if(L.current.has(n))return;let r={};L.current.set(n,r),I(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,o=await de({scope:e.scope,name:e.name},s);if(L.current.get(n)!==r)return;L.current.delete(n),I(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],o,e.configKey)}));let a=J.current,l="loaded"===a.state?a.data.servers.find(e=>ca(e)===n):void 0;(o.ok?l?.configKey===o.data.configKey:void 0===o.error.reason||o.error.timedOut)||G()},[t,G]),en=(0,i.useCallback)((e,n)=>{T.current+=1,$.current?.abort(),p(!1),d(t=>({state:"loaded",data:e,..."loaded"===t.state&&t.projectError?{projectError:t.projectError}:{}})),f(r=>cI(cN(e,!!t),n??r))},[t]),er=(0,i.useCallback)(async e=>{let n=ca(e),r=z.current[n];if(r?.starting||hf(r))return;P(e=>({...e,[n]:{starting:!0}}));let i=J.current,s="loaded"===i.state&&i.data.project?t:null,o=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 hk("/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?hb({},e.data,t):{error:e.error}}(o)})),o.ok||void 0===o.error.reason||o.error.timedOut||G())},[t,G]),ei=(0,i.useCallback)(async(e,t,n)=>{let r=ca(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 hk(hw(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?{...hb(i,n.data,r),pasteError:void 0}:hy(n.error)?{...i,gone:!0}:{...i,pasteError:n.error}}(e[r],t,i);return void 0===n||n===e[r]?e:{...e,[r]:n}})},[]),es=(0,i.useCallback)(async(e,t)=>{let n=ca(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 hk(hw(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?hb(i,n.data,r):hy(n.error)?{...i,gone:!0}:{...i,cancelError:n.error}}(e[n],t,r);return void 0===i||i===e[n]?e:{...e,[n]:i}})},[]),eo=Object.entries(A).flatMap(e=>{let[t,n]=e;return hf(n)&&n.flow?[`${t}\u0001${n.flow.flowId}`]:[]}).join("\x02");(0,i.useEffect)(()=>{if(!eo)return;let e=new AbortController,t=setTimeout(async()=>{for(let t of eo.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 hk(hw(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?hb(e,n.data,r):hy(n.error)||void 0!==e.deadlineAt&&r>e.deadlineAt+5e3?{...e,gone:!0}:e:e}(e[n],r,s,Date.now(),i);return void 0===t||t===e[n]?e:{...e,[n]:t}})}O(e=>e+1)},1e3);return()=>{clearTimeout(t),e.abort()}},[eo,W]);let ea=(0,i.useRef)(A);(0,i.useEffect)(()=>{let e=ea.current;ea.current=A,Object.keys(A).some(t=>{var n,r;return n=e[t],r=A[t],hf(n)&&!hf(r)})&&G()},[A,G]);let el=(0,i.useCallback)(async(e,n,r)=>{R.current?.abort();let i=new AbortController;R.current=i,v(n);let s=J.current,o="loaded"===s.state&&s.data.project?t:null,a=await c1(e,o,void 0,i.signal);if(R.current===i)return R.current=null,v(null),a.ok?en(a.data,r?.(a.data)):G(),a},[en,t,G]),ec=(0,i.useCallback)(async(e,t)=>{let n=ca(e),r=hL();y(null),k(null);let i=await el({action:t?"enable":"disable",scope:e.scope,name:e.name},`switch:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[el]),ed=(0,i.useCallback)(async(e,t)=>{let n=ca(e),r=hL();y(null),k(null);let i=await el({action:"set-in-project",name:e.name,enabled:t},`in-project:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[el]),eu=(0,i.useCallback)(async(e,t)=>{let n=ca(e),r=hL();y(null),k(null);let i=await el({action:"set-exposure",scope:e.scope,name:e.name,exposure:t},`exposure:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[el]),ep=(0,i.useCallback)(async e=>{let t=ca(e),n=hL();y(null),k(null);let r=await el({action:"remove",scope:e.scope,name:e.name},`remove:${t}`);if(!r)return;if(!r.ok){y({key:t,failure:r.error}),N({control:n});return}let i=r.data.undo;i&&S({...i,undoing:!1})},[el]),eh=(0,i.useCallback)(async()=>{if(!w)return;let e=hL();y(null),k(null),S({...w,undoing:!0,error:void 0});let t=await el({action:"undo",token:w.token},"undo",e=>e.restored?ca(e.restored):void 0);t&&(S(e=>e?.token!==w.token?e:t.ok?null:{...e,undoing:!1,error:t.error}),t.ok||N({control:e}))},[el,w]),ef=(0,i.useCallback)(async e=>{let t=ca(e),n=hL();y(null),k(null),P(e=>({...e,[t]:{...e[t],signOutError:void 0,signedOut:void 0}}));let r=await el({action:"sign-out",scope:e.scope,name:e.name},`sign-out:${t}`);if(r){if(P(e=>({...e,[t]:r.ok?{signedOut:{removed:r.data.signedOut?.removed===!0}}:{...e[t],signOutError:r.error}})),r.ok){let e=Date.now();I(n=>{let r=function(e,t){if(e)return{running:e.running,...void 0!==e.startedAt?{startedAt:e.startedAt}:{},signedOutAt:t}}(n[t],e);return r?{...n,[t]:r}:n})}N({control:n})}},[el]),em=(0,i.useCallback)(async e=>{let n=hL(),r=U.current;y(null),k(null),q(null);let i=await el(e,"add",e=>e.added?ca(e.added):void 0);if(!i)return;let s=U.current!==r;if(!i.ok){s||q(i.error),i.error.trust&&t&&l?.(t,i.error.trust),N({control:n});return}let{added:o,trust:a,trustedFolder:c}=i.data;if(F(!1),s||H(pH),N({control:null,toSelectedRow:!0}),!o)return;V({...o,key:ca(o),...c&&t?{trustedFolder:t}:{}}),a&&t&&l?.(t,a);let d=i.data.servers.find(e=>ca(e)===ca(o));d&&!c4(d,i.data)&&et(d)},[t,l,el,et]),eg=w?.token,ex=w?.expiresInMs;(0,i.useEffect)(()=>{if(void 0===eg||void 0===ex)return;let e=setTimeout(()=>S(e=>e?.token===eg?null:e),ex);return()=>clearTimeout(e)},[eg,ex]);let ev=(0,i.useCallback)(async(e,t,n)=>{let{targets:r,keptOff:i}={targets:lj(t,n,e=>e.enabled).filter(n?cQ:cX),keptOff:n?t.filter(e=>!e.enabled&&cX(e)&&!cQ(e)).length:0},s=hL();if(y(null),k(i>0?{scope:e,keptOff:i,failures:[],total:0}:null),0===r.length)return;let o=await el({action:"set-enabled",enabled:n,servers:r.map(e=>{let{scope:t,name:n}=e;return{scope:t,name:n}})},`group:${e}`);if(!o)return;if(N({control:s}),!o.ok)return void k({scope:e,keptOff:i,failures:[],total:r.length,error:o.error});let a=o.data.results??[],l=a.filter(e=>void 0!==e.reason).map(e=>({name:e.name,failure:{error:e.error??"",reason:e.reason}}));k(l.length>0||i>0?{scope:e,keptOff:i,failures:l,total:a.length}:null)},[el]);return(0,i.useEffect)(()=>{h&&o2("mcp",h,t)},[t,h]),(0,r.jsx)(hP,{cwd:t,load:c,selected:h,refreshing:u,embedded:s,codemodeSave:m,busy:x,actionError:b,groupStatus:j,undo:w,focusBack:C,tests:E,signIns:A,adding:D,addDraft:B,addFailure:_,added:K,onAddOpen:()=>{F(!0),V(null),y(null)},onAddDraftChange:e=>{U.current=e,H(e),q(null)},onAddSubmit:e=>void em(e),onTest:e=>void et(e),onSignIn:e=>void er(e),onSignOut:e=>void ef(e),onSignInPaste:(e,t,n)=>void ei(e,t,n),onSignInCancel:(e,t)=>void es(e,t),onSelect:e=>{f(e),y(null),F(!1),V(t=>t?.key===e?t:null)},onRefresh:()=>void G(),onCodemodeChange:e=>void X(e),onCodemodeModeChange:e=>void Q(e),onCodemodeInlineBudgetSave:e=>void ee(e),onServerSwitch:(e,t)=>void 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:a,onClose:n})}function hP(e){var t,n,s,o;let a,l,c,{cwd:d,load:u,selected:p,refreshing:h,embedded:f,codemodeSave:m={saving:!1,error:null},busy:g=null,actionError:x=null,groupStatus:v=null,undo:b=null,focusBack:y=null,tests:j={},signIns:k={},adding:w=!1,addDraft:S=pH,addFailure:C=null,added:N=null,onAddOpen:E=()=>{},onAddDraftChange:I=()=>{},onAddSubmit:T=()=>{},onSelect:$,onRefresh:M,onCodemodeChange:R,onCodemodeModeChange:L=()=>{},onCodemodeInlineBudgetSave:A=()=>{},onServerSwitch:P=()=>{},onServerSwitchInProject:z=()=>{},onExposureChange:W=()=>{},onGroupSwitch:O=()=>{},onRemove:D=()=>{},onUndo:F=()=>{},onTest:B=()=>{},onSignIn:H=()=>{},onSignOut:U=()=>{},onSignInPaste:_=()=>{},onSignInCancel:q=()=>{},onTrustProject:K,onClose:V}=e,{t:Z}=(0,eO.s)(),J=(0,i.useId)(),G=(0,i.useId)(),Y="loaded"===u.state?(t=u.data,a=!1,l=t.servers.map(e=>{var t;let n=j[ca(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;a=!0;let r={...n.result,origin:"test"};return{...e,status:r}}),a?{...t,servers:l}:t):void 0,X=Y?cN(Y,!!d):[],Q=Y?{mcpAvailable:Y.mcp.available,projectServersLoad:cl(Y.project)}:void 0,ee=X.flatMap(e=>e.servers),et=ee.find(e=>ca(e)===p),en=N?ee.find(e=>ca(e)===N.key):void 0,er=Y?function(e){if(!e.available)return"builtin-disabled"===e.reason?e.settingsPath?{key:"mcp.unavailable.builtin-disabled",params:{path:e.settingsPath}}:{key:"mcp.unavailable.builtin-disabled-unknown"}:{key:"operator-disabled"===e.reason?"mcp.unavailable.operator-disabled":"mcp.unavailable.internals-unavailable"}}(Y.mcp):void 0,ei=er?void 0:Y?.hostInactive,es=Y?.files.find(e=>"project"===e.scope),eo=Y?function(e,t){if(!e||!t||!t.exists&&0===t.problems.length)return;let{trust:n}=e;return n?n.requiresTrust||!1===n.decision?!0===n.decision?n.inherited&&n.decisionPath?{kind:"inherited",key:"mcp.trust.trustedThrough",params:{path:n.decisionPath}}:void 0:!1===n.decision&&n.inherited&&n.decisionPath?{kind:"untrusted",key:"mcp.trust.untrustedThrough",params:{path:n.decisionPath}}:{kind:"untrusted",key:"mcp.trust.untrusted"}:void 0:{kind:"untrusted",key:"mcp.trust.unreadable"}}(Y.project,es):void 0,ea=K&&cT(Y?.project)?K:void 0,el=eo?.kind==="untrusted"&&void 0!==ea,ec=(0,i.useRef)(null),ed=(0,i.useRef)(null),eu=(0,i.useRef)(el);(0,i.useEffect)(()=>{let e=eu.current;eu.current=el,e&&!el&&eN(document,ec.current??ed.current)},[el]);let ep=(0,i.useRef)(null),eh=b?.token,ef=(0,i.useRef)(eh);(0,i.useEffect)(()=>{let e=ef.current;ef.current=eh,void 0!==eh&&eh!==e?eN(document,ep.current):void 0!==e&&void 0===eh&&eN(document,ec.current??ed.current)},[eh]);let em=Y?[...Y.files].sort((e,t)=>e.scope===t.scope?0:"global"===e.scope?-1:1).flatMap(e=>e.problems.map(t=>({file:e,problem:t}))):[],eg=cE(ee),ex=Y?.files.find(e=>"global"===e.scope),ev=Y?function(e){let t=e.files.find(e=>"project"===e.scope);if(t?.autoEnableCodemode!==void 0&&cl(e.project))return t.autoEnableCodemode?{value:!0,path:t.path}:{value:!1,path:t.path};let n=e.files.find(e=>"global"===e.scope);return n?.autoEnableCodemode!==void 0?n.autoEnableCodemode?{value:!0,path:n.path}:{value:!1,path:n.path}:{value:!0}}(Y):void 0,eb=Y?(n=ee.length,s=Y.files,n>0?"mcp.selectItem":s.some(e=>e.problems.some(cC))?"mcp.emptyFileProblem":"mcp.empty"):void 0,ey=null!==g||h||m.saving,ej=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(y&&!ey&&ej.current!==y)if(ej.current=y,y.toSelectedRow)eN(document,ec.current??ed.current);else{var e,t,n;e=document,t=y.control,n=ec.current??ed.current,t&&eN(e,t.isConnected&&!t.disabled?t:n)}},[y,ey]);let ek=e=>Y?cG(e,Y):void 0,ew=!!Y&&cJ(Y.mcp),eS=X.find(e=>"project"===e.scope)?.servers??[],eC=ek("project"),eE=eo?.kind==="untrusted"?[h$(eo,Z),eC&&"mcp-off"!==eC&&eS.length>0?Z(cY[eC]):null].filter(Boolean).join(" "):"";return(0,r.jsxs)(ao,{embedded:f,title:Z("settings.mcp"),subtitle:d?lb(d):void 0,closeLabel:Z("i18n.close"),onClose:V,children:[(0,r.jsxs)("div",{className:"mcp-config-notices",children:[er&&(0,r.jsxs)(aT,{id:J,children:[h$(er,Z),ew&&(0,r.jsxs)(r.Fragment,{children:[" ",Z(cY["mcp-off"])]}),Y&&!Y.mcp.available&&Y.mcp.detail&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:l5(Y.mcp.detail)})]})]}),ei&&(0,r.jsx)(aT,{children:Z("mcp.hostInactive",{path:hT(ei.cwd),owner:hT(ei.owner)})}),"loaded"===u.state&&u.projectError&&(0,r.jsx)(aT,{children:Z("mcp.projectNotListed",{reason:hM(u.projectError,Z)})}),eo?.kind==="untrusted"&&(0,r.jsx)(a$,{id:G,message:eE,trustLabel:Z("mcp.trust.trustButton"),onTrust:ea}),eo?.kind==="inherited"&&(0,r.jsx)(aT,{children:h$(eo,Z)}),b&&(0,r.jsxs)(aT,{action:b.error?.reason==="undo-unavailable"?void 0:(0,r.jsx)(aP,{ref:ep,size:"small",onClick:F,disabled:b.undoing||ey,children:b.undoing?Z("mcp.undoing"):Z("mcp.undo")}),children:[Z("mcp.removed",{name:l5(b.name),path:hT(b.path)}),b.error&&(0,r.jsxs)(r.Fragment,{children:[" ",Z("mcp.undoFailed")," ",hR(b.error,Z)]})]}),N&&Y&&en&&(0,r.jsx)(hz,{added:N,cwd:d,server:en,testing:j[N.key]?.running===!0,signIn:k[N.key],signingOut:g===`sign-out:${N.key}`,signInBlock:en?c4(en,Y):void 0,onSignIn:H})]}),(0,r.jsxs)(aa,{children:[(0,r.jsxs)(al,{children:[(0,r.jsx)(ac,{children:"loading"===u.state?(0,r.jsx)("div",{className:"config-sidebar-message",children:Z("i18n.loading")}):"failed"===u.state?(0,r.jsxs)("div",{role:"alert",className:"config-sidebar-message is-error",children:[Z("mcp.loadFailed")," ",hM(u.error,Z)]}):Y&&Q?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-sidebar-group",children:(0,r.jsx)(hW,{codemode:Y.codemode,active:!w&&p===co,rowRef:ec,onSelect:$})}),X.map(e=>{let t=ek(e.scope);return(0,r.jsx)(hO,{group:e,context:Q,selected:w?null:p,selectedRowRef:ec,block:t,blockNoticeId:"mcp-off"===t?er?J:void 0:t&&eo?.kind==="untrusted"?G:void 0,busy:g,controlsBusy:ey,status:v?.scope===e.scope?v:null,onSelect:$,onGroupSwitch:O},e.scope)})]}):null}),Y&&(0,r.jsx)(aW,{ref:ed,active:w,onClick:E,children:Z("mcp.add.action")})]}),(0,r.jsx)(aR,{children:(0,r.jsx)(am,{className:"is-fill",children:Y&&Q&&ev&&eb?w?(0,r.jsx)(hc,{data:Y,cwd:d,draft:S,busy:"add"===g,controlsBusy:ey,failure:C,onDraftChange:I,onSubmit:T,onTrustProject:ea}):p===co?(0,r.jsx)(hG,{codemode:Y.codemode,autoEnable:ev,save:m,serverBusy:null!==g,onChange:R,onModeChange:L,onInlineBudgetSave:A}):et?(0,r.jsx)(hB,{server:et,context:Q,codemode:Y.codemode,toolSearchDisabled:Y.toolSearchDisabled,autoEnable:ev,block:ek(et.scope),inProject:function(e,t){if("global"!==e.scope||void 0!==e.invalidError||e.notAnObject||!cl(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:ca(r),keys:r.override.keys,applies:!0===e.overriddenByProject}:void 0:{kind:"switch"}}(et,Y),inProjectBlock:ek("project"),savedWhileOff:!Y.mcp.available&&!ew,busy:g,controlsBusy:ey,actionError:x?.key===ca(et)?x.failure:null,test:(o=j[ca(et)],o&&void 0!==o.configKey&&o.configKey!==et.configKey?{running:o.running,...o.response?{response:o.response}:{}}:o),testBlock:c4(et,Y),signIn:k[ca(et)],signInBlock:c4(et,Y),signOutBlock:(c=cG(et.scope,Y))||(void 0===et.invalidError&&et.validated?void 0:"invalid"),onSwitch:P,onSwitchInProject:z,onShowServer:e=>{$(e),requestAnimationFrame(()=>eN(document,ec.current??ed.current))},onExposureChange:W,onRemove:D,onTest:B,onSignIn:H,onSignOut:U,onSignInPaste:_,onSignInCancel:q},ca(et)):(0,r.jsx)(aM,{children:"mcp.empty"===eb?Z(eb,{globalPath:hT(ex?.path??"~/.pi/agent/mcp.json")}):Z(eb)}):null})})]}),(0,r.jsxs)(aL,{status:em.length>0?(0,r.jsx)(aA,{tone:em.some(e=>{let{problem:t}=e;return cC(t)})?"error":"warning",summary:1===em.length?Z("mcp.footer.fileProblem"):Z("mcp.footer.fileProblems",{count:em.length}),details:em.map(e=>{let{file:t,problem:n}=e,i=cs(n,t.realPath);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:hT(t.path)})," ",Z(`mcp.fileProblem.${n.reason}`),i&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:i})]})]})})}):(0,r.jsx)(aA,{summary:eg.total>0?Z("mcp.serverCount",{enabled:eg.enabled,total:eg.total}):""}),children:[!f&&(0,r.jsx)(aP,{onClick:V,children:Z("i18n.close")}),(0,r.jsx)(aP,{variant:"secondary",onClick:M,disabled:ey,children:Z("i18n.refresh")})]})]})}function hz(e){let{added:t,cwd:n,server:i,testing:s,signIn:o,signingOut:a,signInBlock:l,onSignIn:c}=e,{t:d}=(0,eO.s)(),u=l5(t.name),p="project"===t.scope&&n?l5(ly(t.path,n)):hT(t.path),h=i.status,f=!s&&h?.origin==="test"&&"needs-auth"===h.state&&i.usesOAuth,m=o?.starting===!0||hf(o);return(0,r.jsxs)(aT,{action:!f||m||a||l?void 0:(0,r.jsx)(aP,{size:"small",variant:"primary",onClick:()=>c(i),children:d("mcp.signIn.button")}),children:[void 0===t.trustedFolder?d("mcp.add.added",{name:u,path:p}):t.trustedFolder===n?d("mcp.add.addedTrustedHere",{name:u,path:p}):d("mcp.add.addedTrusted",{name:u,path:p,folder:hT(t.trustedFolder)}),s&&(0,r.jsxs)(r.Fragment,{children:[" ",d("mcp.add.testing")]}),f&&(0,r.jsxs)(r.Fragment,{children:[" ",d("mcp.add.needsSignIn")]})]})}function hW(e){let{codemode:t,active:n,rowRef:i,onSelect:s}=e,{t:o}=(0,eO.s)(),a=t.builtinDisabled||"unavailable"===t.sandbox.state?"unavailable":t.preference??"unknown",l=o(cA[a]);return(0,r.jsxs)(ah,{ref:n?i:void 0,active:n,"aria-label":o("mcp.codemode.rowLabel",{state:l}),onClick:()=>s(co),children:[(0,r.jsx)(aO,{...cx(cP(a))}),(0,r.jsx)(af,{className:"is-grow",children:o("mcp.codemode.title")}),(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${cP(a)}`,children:l})]})}function hO(e){var t;let n,i,{group:s,context:o,selected:a,selectedRowRef:l,block:c,blockNoticeId:d,busy:u,controlsBusy:p,status:h,onSelect:f,onGroupSwitch:m}=e,{t:g}=(0,eO.s)(),{enabled:x,total:v}=cE(s.servers),b=(t=s.servers).some(e=>e.enabled&&cX(e))&&t.every(e=>e.enabled||!cQ(e)),y=function(e){if(!(e.servers.length>0))return e.file?e.file.problems.some(cC)?"mcp.group.fileProblem":"mcp.group.empty":"mcp.group.notListed"}(s),j=h?(n=h.keptOff>0?g("mcp.groupKeptOff",{count:h.keptOff}):void 0,i=h.error?`${g("mcp.actionFailed")} ${hR(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`${l5(t)}: ${hR(n,g)}`})].join("\n"):void 0,{...n?{note:n}:{},...i?{error:i}:{}}):void 0;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(ad,{aside:v>0?(0,r.jsx)(au,{enabled:x,total:v,checked:b,disabled:p||void 0!==c,loading:u===`group:${s.scope}`,describedBy:c?d:void 0,label:g(b?"mcp.groupSwitchOn":"mcp.groupSwitchOff",{group:hI(s.scope,g)}),onChange:e=>m(s.scope,s.servers,e)}):void 0,children:hI(s.scope,g)}),j&&(0,r.jsx)(ap,{note:j.note,error:j.error}),y&&(0,r.jsx)("div",{className:"mcp-sidebar-group-empty",children:g(y)}),s.servers.map(e=>{let t=ca(e),n=cd(e,o),i=cg(n),s=cm[n],c=l5(e.name);return(0,r.jsxs)(ah,{ref:a===t?l:void 0,active:a===t,"aria-label":g("mcp.rowLabel",{name:c,state:g(ch(n,e.status))}),onClick:()=>f(t),children:[(0,r.jsx)(aO,{...cx(i)}),(0,r.jsx)(af,{className:`is-grow${"on"===i?"":" is-muted"}`,children:c}),s&&(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${i}`,children:g(s)})]},t)})]})}function hD(e){let{fields:t}=e,{t:n}=(0,eO.s)();return(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>{let t=ct(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function hF(e){let{names:t}=e;return(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>(0,r.jsx)("code",{className:"mcp-config-chip",children:l5(e)},e))})}function hB(e){let{server:t,context:n,codemode:s,toolSearchDisabled:o,autoEnable:a,block:l,inProject:c,inProjectBlock:d,savedWhileOff:u,busy:p,controlsBusy:h,actionError:f,test:m,testBlock:g,signIn:x,signInBlock:v,signOutBlock:b,onSwitch:y,onSwitchInProject:j,onShowServer:k,onExposureChange:w,onRemove:S,onTest:C,onSignIn:N,onSignOut:E,onSignInPaste:I,onSignInCancel:T}=e,{t:$}=(0,eO.s)(),M=(0,i.useId)(),R=(0,i.useId)(),L=cd(t,n),A=l7(t),P=t.status,z=P?.origin==="test"&&"connected"===P.state&&P.toolCount>0?P:void 0,W=void 0===t.invalidError,O="http"===t.transport||void 0===t.transport&&void 0!==t.url,D=!O&&("stdio"===t.transport||void 0!==t.command),F=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"===c$(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:o},a):void 0,B=(0,i.useId)(),H=(0,i.useId)(),U=ca(t),_=l5(t.name),q=!t.enabled&&void 0!==t.webPasswordField,K=!0===t.notAnObject,V=l?$(`mcp.reason.${l}`):K?$("mcp.reason.entry-not-object"):q?$("mcp.reason.web-password"):u?$("mcp.write.savedWhileOff"):void 0;return(0,r.jsxs)(am,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(ag,{children:[(0,r.jsxs)(ax,{children:[(0,r.jsx)(aS,{scope:t.scope,children:hI(t.scope,$)}),(0,r.jsx)(ab,{children:_})]}),(0,r.jsxs)(av,{children:[(0,r.jsx)(hZ,{server:t,test:m,testBlock:g,describedBy:R,onTest:C}),(0,r.jsx)(aP,{variant:"danger",size:"small",disabled:h||void 0!==l,"aria-describedby":l?M:void 0,onClick:()=>S(t),children:p===`remove:${U}`?$("i18n.removing"):$("i18n.remove")}),(0,r.jsx)(az,{checked:t.enabled,disabled:h||void 0!==l||K||q,loading:p===`switch:${U}`,describedBy:V?M:void 0,label:$(t.enabled?"mcp.server.switchOff":"mcp.server.switchOn",{name:_}),onChange:e=>y(t,e)})]})]}),V&&(0,r.jsx)("div",{id:M,className:"config-detail-heading-note",children:V})]}),f&&(0,r.jsxs)("p",{role:"alert",className:"mcp-config-line is-error",children:[$("mcp.actionFailed")," ",hR(f,$)]}),(0,r.jsxs)(ak,{children:[(0,r.jsx)(hJ,{server:t,state:L,test:m,testBlock:g,testBlockId:R}),void 0!==t.description&&(0,r.jsx)(aw,{label:$("mcp.detail.description"),tone:"plain",children:l5(t.description)}),void 0!==A?(0,r.jsx)(aw,{label:O?$("mcp.detail.url"):$("mcp.detail.command"),tone:"plain",mono:!0,className:"mcp-config-code",children:A}):t.transport&&(0,r.jsx)(aw,{label:$("mcp.detail.transport"),children:$(`mcp.transport.${t.transport}`)}),D&&void 0!==t.cwd&&(0,r.jsx)(aw,{label:$("mcp.detail.cwd"),mono:!0,className:"mcp-config-code",children:l5(t.cwd)}),D&&t.envNames.length>0&&(0,r.jsx)(aw,{label:$("mcp.detail.env"),children:(0,r.jsx)(hF,{names:t.envNames})}),O&&t.headerNames.length>0&&(0,r.jsx)(aw,{label:$("mcp.detail.headers"),children:(0,r.jsx)(hF,{names:t.headerNames})}),W&&t.commandFields.length>0&&(0,r.jsx)(aw,{label:$("mcp.detail.shellCommands"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:$("mcp.server.commandFields")}),(0,r.jsx)(hD,{fields:t.commandFields})]})}),W&&t.variableReferences.length>0&&(0,r.jsx)(aw,{label:$("mcp.detail.variables"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:$(cn(t))}),(0,r.jsx)("span",{className:"mcp-config-chips",children:ci(t.variableReferences).map(e=>{let{variable:t,field:n}=e,i=ct(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:$("mcp.server.variableIn",{variable:t,field:$(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})}),O&&W&&(0,r.jsx)(hC,{server:t,run:x,block:v,signOutBlock:b,controlsBusy:h,signingOut:p===`sign-out:${U}`,onSignIn:N,onSignOut:E,onPaste:I,onCancel:T}),(t.exposure||z)&&(0,r.jsx)(aw,{label:$("mcp.detail.exposure"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[t.exposure&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-exposure-choice",children:[(0,r.jsx)("select",{className:"mcp-add-input mcp-exposure-select","aria-label":$("mcp.exposure.label",{name:_}),"aria-describedby":[B,l?M:null].filter(Boolean).join(" "),value:t.exposure,disabled:h||void 0!==l,onChange:e=>{let n=e.target.value;n!==t.exposure&&w(t,n)},children:cw.map(e=>(0,r.jsx)("option",{value:e,children:"codemode"===e?$("mcp.exposure.optionDefault",{label:$(cS[e])}):$(cS[e])},e))}),p===`exposure:${U}`&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:$("i18n.saving")})]}),(0,r.jsx)("span",{id:B,className:"mcp-config-line",children:$(ck[t.exposure])}),void 0!==t.toolExposureCount&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:$("mcp.exposure.toolOverrides",{count:t.toolExposureCount})}),F&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:h$(F,$)})]}),z&&(0,r.jsx)(hV,{status:z,serverExposure:t.exposure})]})}),c&&(0,r.jsx)(aw,{label:$("mcp.detail.inProject"),tone:"plain",children:(0,r.jsx)("span",{className:"mcp-config-lines",children:"override"===c.kind?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"mcp-config-line",children:c.applies?$("mcp.inProject.overridden",{keys:c.keys.join(", ")}):$("mcp.inProject.refused")}),(0,r.jsx)("span",{children:(0,r.jsx)(aP,{size:"small",onClick:()=>k(c.key),children:$("mcp.inProject.show")})})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:(0,r.jsx)(aP,{size:"small",disabled:h||void 0!==d||q,"aria-describedby":[H,d||q?M:null].filter(Boolean).join(" "),onClick:()=>j(t,!t.enabled),children:p===`in-project:${U}`?$("i18n.saving"):$(t.enabled?"mcp.inProject.turnOff":"mcp.inProject.turnOn")})}),(0,r.jsx)("span",{id:H,className:"mcp-config-line is-dim",children:$("mcp.inProject.saved")})]})})}),(0,r.jsx)(aw,{label:$("mcp.detail.file"),tone:"dim",mono:!0,className:"mcp-config-code",children:hT(t.sourcePath)})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[ce(t)&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:$("mcp.server.hiddenCharacters")}),!t.validated&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:$("mcp.server.unchecked")}),t.replacesGlobal&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:$("mcp.server.replacesGlobal")}),t.override&&(0,r.jsx)("p",{className:"mcp-config-line",children:h$(cr(t.override.keys),$)}),t.shadowedByProject&&"replaced"!==L&&(0,r.jsx)("p",{className:"mcp-config-line",children:$("mcp.server.shadowedByProject")}),t.overriddenByProject&&"overridden"!==L&&(0,r.jsx)("p",{className:"mcp-config-line",children:$("mcp.server.overriddenByProject")}),t.masked&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:$("mcp.server.masked")})]})]})}function hH(e){let{error:t,stderr:n}=e,{t:i}=(0,eO.s)();return(0,r.jsxs)(r.Fragment,{children:[t&&(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[i("mcp.test.error")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:l5(t)})]}),n&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:i("mcp.test.stderr")}),(0,r.jsx)("pre",{className:"mcp-test-output",children:n.split(/\r?\n/).map(l5).join("\n")})]})]})}function hU(e){let{status:t,showState:n,entryCwd:i}=e;return"session"===t.origin?(0,r.jsx)(hK,{status:t,showState:n}):(0,r.jsx)(hq,{status:t,showState:n,entryCwd:i})}function h_(e){let{view:t}=e,{t:n}=(0,eO.s)();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:`mcp-config-state is-${t.tone}`,children:n(t.key)})," "]})}function hq(e){let{status:t,showState:n,entryCwd:i}=e,{t:s,locale:o}=(0,eO.s)(),a=cv(t.testedAt,o),l=t.serverInfo;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,r.jsx)(h_,{view:t.timedOut?{key:c5.timedOut,tone:"error"}:{key:c5[t.state],tone:cg(t.state)}}),s((t.afterSignIn?c3:c6)[t.timedOut?"timedOut":t.state],{count:t.toolCount,seconds:c9(t.durationMs),time:a})]}),(0,r.jsx)(hH,{error:t.error,stderr:t.stderr}),l&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.serverInfo",{name:l5(l.title??l.name),version:l5(l.version)})}),t.resources&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.resources")}),void 0!==t.cwd&&t.cwd!==i&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.ranIn",{path:hT(t.cwd)})}),void 0!==t.queuedMs&&t.queuedMs>=500&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.queued",{seconds:c9(t.queuedMs)})})]})}function hK(e){let{status:t,showState:n}=e,{t:i,locale:s}=(0,eO.s)(),o=cv(t.updatedAt,s),a=void 0===t.closedAt?void 0:cv(t.closedAt,s);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,r.jsx)(h_,{view:void 0!==t.closedAt?{key:"mcp.session.state.closed",tone:"off"}:{key:cb[t.state],tone:cj[t.state]}}),i(void 0!==t.closedAt?"mcp.session.summary.closed":cy[t.state],{path:hT(t.cwd),time:o,...void 0===a?{}:{closedTime:a}})]}),void 0!==t.conflict&&(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[i("mcp.session.conflictOwner")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:hT(t.conflict)})]}),(0,r.jsx)(hH,{error:t.error,stderr:t.stderr})]})}function hV(e){let{status:t,serverExposure:n}=e,{t:i}=(0,eO.s)(),s=t.toolCount-t.tools.length;return(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("ul",{className:"mcp-test-tools",children:t.tools.map((e,t)=>(0,r.jsxs)("li",{className:"mcp-test-tool",children:[(0,r.jsxs)("span",{className:"mcp-config-chips",children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:l5(e.name)}),e.readOnly&&(0,r.jsx)("span",{className:"mcp-test-tool-tag",children:i("mcp.test.readOnly")}),e.exposure!==(n??"codemode")&&(0,r.jsx)("span",{className:"mcp-test-tool-tag",children:i(cS[e.exposure])})]}),e.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:l5(e.description)})]},`${t}\0${e.name}`))}),s>0&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:i("mcp.test.moreTools",{count:s})})]})}function hZ(e){let{server:t,test:n,testBlock:s,describedBy:o,onTest:a}=e,{t:l}=(0,eO.s)(),c=(0,i.useRef)(null),d=n?.running===!0,u=(0,i.useRef)(d);return(0,i.useEffect)(()=>{let e=u.current;u.current=d,e&&!d&&eN(document,c.current)},[d]),(0,r.jsx)(aP,{ref:c,size:"small",disabled:d||void 0!==s,"aria-busy":d||void 0,"aria-describedby":s?o:void 0,onClick:()=>a(t),children:l(d?"mcp.test.testing":"mcp.test.button")})}function hJ(e){let{server:t,state:n,test:i,testBlock:s,testBlockId:o}=e,{t:a}=(0,eO.s)(),l=t.status,c=cf[n],d="invalid"===s&&"invalid"===n?"state":"web-password"===s&&void 0!==t.webPasswordField?"password":void 0;return(0,r.jsx)(aw,{label:a("i18n.status"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:`mcp-config-state is-${cg(n)}`,children:a(ch(n,l))}),"invalid"===n&&(0,r.jsxs)("span",{id:"state"===d?o:void 0,className:"mcp-config-line is-warning",children:[a("mcp.server.invalid")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:l5(t.invalidError??"")})]}),t.webPasswordField&&(0,r.jsxs)("span",{id:"password"===d?o:void 0,className:"mcp-config-line is-warning",children:[a("mcp.server.webPassword")," ",(0,r.jsx)(hD,{fields:[t.webPasswordField]})]}),l?(0,r.jsx)(hU,{status:l,showState:cc(l)!==n,entryCwd:t.cwd}):!s&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:a("mcp.test.never")}),c&&(0,r.jsx)("span",{className:"mcp-config-line",children:a(c)}),i?.queueTimedOut&&(0,r.jsx)("span",{role:"alert",className:"mcp-config-line is-error",children:a("mcp.test.queueTimedOut")}),i?.error&&(0,r.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?c8[e.reason]:void 0;return n?t(n):hM(e,t)}(i.error,a)]}),s&&!d&&(0,r.jsx)("span",{id:o,className:"mcp-config-line is-dim",children:a(c2[s])}),!s&&t.commandFields.length>0&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:a("mcp.test.serial")})]})})}function hG(e){let{codemode:t,autoEnable:n,save:i,serverBusy:s,onChange:o,onModeChange:a,onInlineBudgetSave:l}=e,{t:c}=(0,eO.s)(),d=t.sandbox,u=t.preference,p=i.saving||s,h=void 0===i.target||"preference"===i.target?i:{saving:!1,error:null},f=function(e,t){if("automatic"===c$(e)&&!t.value)return{key:"mcp.codemode.autoEnableOff",params:{path:t.path}}}(t,n),m="unavailable"===t.sandbox.state?{key:"mcp.codemode.alwaysUnavailable.sandbox"}:t.globalBuiltinSettingsPath?{key:"mcp.codemode.alwaysUnavailable.builtin",params:{path:t.globalBuiltinSettingsPath}}:void 0,g=function(e){if(!e.builtinDisabled)return;let t=e.builtinSettingsPath;return t?e.globalBuiltinSettingsPath?{key:"mcp.codemode.builtinDisabled",params:{path:t}}:{key:"mcp.codemode.builtinDisabledProject",params:{path:t}}:{key:"mcp.codemode.builtinDisabledUnknown"}}(t),x=function(e){let t=e.projectOverride;if(t)return{key:cM[t.preference],params:{path:t.settingsPath}}}(t);return(0,r.jsxs)(am,{children:[(0,r.jsx)(ag,{children:(0,r.jsx)(ax,{children:(0,r.jsx)(ab,{children:c("mcp.codemode.title")})})}),(0,r.jsx)("p",{className:"mcp-config-line",children:c("mcp.codemode.intro")}),(0,r.jsxs)(ak,{children:[(0,r.jsx)(aw,{label:c("mcp.codemode.mode"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[u?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(aC,{value:u,label:c("mcp.codemode.title"),options:[{value:"automatic",label:c(cA.automatic),disabled:p},{value:"always",label:c(cA.always),disabled:p||void 0!==m}],disabledReason:m?h$(m,c):null,onChange:e=>{e!==u&&o(e)},children:h.saving&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:c("i18n.saving")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:c("always"===u?"mcp.codemode.alwaysDescription":"mcp.codemode.automaticDescription")})]}):(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[c("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:l5(t.preferenceError??"")})]}),h.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[c("mcp.codemode.saveFailed")," ",(0,r.jsx)(hY,{error:h.error})]}),x&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:h$(x,c)}),f&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:h$(f,c)})]})}),t.mode?(0,r.jsx)(hX,{mode:t.mode,codemode:t,save:i,waiting:p,onChange:a}):void 0!==t.modeError&&(0,r.jsx)(aw,{label:c("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[c("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:l5(t.modeError)})]})}),t.inlineBudget?(0,r.jsx)(hQ,{budget:t.inlineBudget,save:i,waiting:p,onSave:l}):void 0!==t.inlineBudgetError&&(0,r.jsx)(aw,{label:c("mcp.codemode.inlineBudget"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[c("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:l5(t.inlineBudgetError)})]})}),(0,r.jsx)(aw,{label:c("mcp.codemode.sandbox"),tone:"plain",children:"unavailable"===d.state?(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[c("mcp.codemode.sandbox.unavailable")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:l5(d.error)})]}):(0,r.jsx)("span",{className:"mcp-config-line",children:c("available"===d.state?"mcp.codemode.sandbox.available":"mcp.codemode.sandbox.not-checked")})}),g&&(0,r.jsx)(aw,{label:c("mcp.codemode.builtin"),tone:"error",children:h$(g,c)})]})]})}function hY(e){let{error:t}=e,{t:n}=(0,eO.s)();return t.timedOut?(0,r.jsx)(r.Fragment,{children:n("mcp.codemode.saveTimedOut")}):t.reason&&"internal"!==t.reason?(0,r.jsx)(r.Fragment,{children:n(`mcp.reason.${t.reason}`)}):(0,r.jsx)("code",{className:"mcp-config-chip",children:l5(t.error)})}function hX(e){let{mode:t,codemode:n,save:i,waiting:s,onChange:o}=e,{t:a}=(0,eO.s)(),l="mode"===i.target,c=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:cL[r.value],params:{path:r.settingsPath}}),"only"===(r??t).value&&"automatic"===c$(e)&&n.push({key:"mcp.codemode.toolMode.automaticNote"}),n}(n);return(0,r.jsx)(aw,{label:a("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)(aC,{value:t.value,label:a("mcp.codemode.toolMode"),options:[{value:"on",label:a("mcp.codemode.toolMode.on"),disabled:s},{value:"only",label:a("mcp.codemode.toolMode.only"),disabled:s}],onChange:e=>{(e!==t.value||void 0!==t.invalid)&&o(e)},children:l&&i.saving&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:a("i18n.saving")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:a(cR[t.value])}),c.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:h$(e,a)},e.key)),l&&i.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[a("mcp.codemode.toolMode.saveFailed")," ",(0,r.jsx)(hY,{error:i.error})]})]})})}function hQ(e){let t,n,{budget:s,save:o,waiting:a,onSave:l}=e,{t:c}=(0,eO.s)(),d=(0,i.useRef)(null),u=(0,i.useId)(),p=void 0===s.value?"":String(s.value),[h,f]=(0,i.useState)(p);(0,i.useEffect)(()=>{f(p)},[p]);let m=function(e,t){let n=e.trim();if(""===n)return{ok:!0,value:null};if(!/^\d+$/.test(n))return{ok:!1};let r=Number(n);return r<=t?{ok:!0,value:r}:{ok:!1}}(h,s.max),g=!!m.ok&&(null===m.value?void 0!==s.value||void 0!==s.invalid:m.value!==s.value),x="inlineBudget"===o.target,v=x&&o.saving,b=(0,i.useRef)(v);(0,i.useEffect)(()=>{let e=b.current;b.current=v,e&&!v&&eN(document,d.current)},[v]);let y=(t=[],void 0!==s.invalid&&t.push({key:"mcp.codemode.inlineBudget.invalid",params:{path:s.settingsPath,value:s.invalid,default:String(s.default)}}),(n=s.projectOverride)&&t.push(void 0!==n.value?{key:"mcp.codemode.inlineBudget.projectOverride",params:{path:n.settingsPath,value:String(n.value)}}:{key:"mcp.codemode.inlineBudget.projectOverrideDefault",params:{path:n.settingsPath,default:String(s.default)}}),t);return(0,r.jsx)(aw,{label:c("mcp.codemode.inlineBudget"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsxs)("form",{className:"mcp-codemode-budget",onSubmit:e=>{e.preventDefault(),m.ok&&g&&!a&&l(m.value)},children:[(0,r.jsx)("input",{ref:d,className:"mcp-add-input mcp-codemode-budget-input",inputMode:"numeric","aria-label":c("mcp.codemode.inlineBudget"),"aria-describedby":u,"aria-invalid":!m.ok||void 0,value:h,placeholder:String(s.default),readOnly:a,autoComplete:"off",spellCheck:!1,onChange:e=>f(e.target.value)}),(0,r.jsx)("span",{className:"mcp-config-line",children:c("mcp.codemode.inlineBudget.unit")}),(0,r.jsx)(aP,{type:"submit",size:"small",disabled:!g||a,children:c("mcp.codemode.inlineBudget.save")}),v&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:c("i18n.saving")})]}),!m.ok&&(0,r.jsx)("span",{className:"mcp-config-line is-error",children:c("mcp.codemode.inlineBudget.invalidDraft",{max:String(s.max)})}),(0,r.jsx)("span",{id:u,className:"mcp-config-line",children:c("mcp.codemode.inlineBudget.description",{default:String(s.default)})}),y.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:h$(e,c)},e.key)),x&&o.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[c("mcp.codemode.inlineBudget.saveFailed")," ",(0,r.jsx)(hY,{error:o.error})]})]})})}async function h0(e){let t=await fetch("/api/channels",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json().catch(()=>({}));return{ok:t.ok,error:n.error}}function h1(e){var t;let n,{embedded:s=!0,onClose:o}=e,{t:a}=(0,eO.s)(),[l,c]=(0,i.useState)(null),[d,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(""),[f,m]=(0,i.useState)(""),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(null),y=(0,i.useRef)(!1),j=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/channels",{cache:"no-store"}),t=await e.json();if(!e.ok||t.error)return void u(t.error??`HTTP ${e.status}`);c(t),u(null),y.current||m(t.config.defaultCwd??"")}catch(e){u(e instanceof Error?e.message:String(e))}},[]);(0,i.useEffect)(()=>{j();let e=setInterval(()=>void j(),5e3);return()=>clearInterval(e)},[j]);let k=(0,i.useCallback)(async(e,t,n)=>{x(e),b(null);let r=await h0(t);if(x(null),!r.ok)return void b({kind:"error",message:r.error??a("telegram.actionFailed")});let i=n();i&&b(i),await j()},[j,a]),{config:w}=l??{};return(0,r.jsxs)(ao,{embedded:s,title:a("settings.channels"),closeLabel:a("i18n.close"),onClose:()=>o?.(),children:[(0,r.jsxs)(aa,{children:[(0,r.jsx)(al,{children:(0,r.jsx)(ac,{children:d&&!l?(0,r.jsx)("div",{role:"alert",className:"config-sidebar-message is-error",children:a("channels.loadFailed",{error:d})}):l?(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(ad,{children:a("channels.group")}),(n=l.config.tokenSet?l.config.enabled?l.lastError?{tone:"error",badge:"channels.badge.error"}:{tone:"on",badge:"channels.badge.on"}:{tone:"off",badge:"channels.badge.off"}:{tone:"off",badge:"channels.badge.unconfigured"},(0,r.jsxs)(ah,{active:!0,"aria-label":`Telegram — ${a(n.badge)}`,children:[(0,r.jsx)(aO,{..."on"===(t=n.tone)?{active:!0}:"off"===t?{active:!1}:{color:"#ef4444"}}),(0,r.jsx)(af,{className:"is-grow",children:"Telegram"}),(0,r.jsx)("span",{className:`mcp-sidebar-badge${"error"===n.tone?" is-error":""}`,children:a(n.badge)})]}))]}):(0,r.jsx)("div",{className:"config-sidebar-message",children:a("i18n.loading")})})}),(0,r.jsx)(aR,{children:(0,r.jsx)(am,{className:"is-fill",children:l&&w?(0,r.jsxs)(r.Fragment,{children:[v&&(0,r.jsx)(aT,{children:v.message}),l.lastError&&(0,r.jsx)(aT,{children:a("telegram.loopError",{error:l.lastError})}),(0,r.jsxs)(ag,{children:[(0,r.jsx)(ax,{children:(0,r.jsx)(ab,{children:"Telegram"})}),(0,r.jsx)(av,{children:(0,r.jsx)(az,{checked:w.enabled,disabled:!w.tokenSet||null!==g,label:a("telegram.enabledLabel"),onChange:e=>void k("enabled",{action:"set-enabled",enabled:e},()=>null)})})]}),!w.tokenSet&&(0,r.jsx)(aT,{children:a("telegram.setupHint")}),(0,r.jsxs)(ak,{children:[(0,r.jsx)(aw,{label:a("telegram.botStatus"),children:l.running?a("telegram.connected",{bot:l.botUsername??""}):a("telegram.notConnected")}),(0,r.jsx)(aw,{label:a("telegram.tokenLabel"),children:(0,r.jsx)("input",{type:"password",autoComplete:"off",spellCheck:!1,className:"mcp-add-input",placeholder:w.tokenSet?a("telegram.tokenPlaceholder",{hint:w.tokenHint??""}):"1234567890:AA…","aria-label":a("telegram.tokenLabel"),value:p,onChange:e=>h(e.target.value)})})]}),(0,r.jsxs)(av,{children:[(0,r.jsx)(aP,{size:"small",disabled:""===p.trim()||null!==g,onClick:()=>void k("token",{action:"set-token",token:p.trim()},()=>(h(""),{kind:"ok",message:a("telegram.tokenSaved")})),children:a("telegram.tokenSave")}),w.tokenSet&&(0,r.jsx)(aP,{size:"small",variant:"secondary",disabled:null!==g,onClick:()=>void k("remove-token",{action:"remove-token"},()=>({kind:"info",message:a("telegram.tokenRemoved")})),children:a("telegram.tokenRemove")})]}),(0,r.jsx)(ay,{children:a("telegram.chatsHeading")}),(0,r.jsx)(ax,{children:a("telegram.chatsDescription")}),l.lastUnknownChat&&(0,r.jsx)(aT,{action:(0,r.jsx)(aP,{size:"small",disabled:null!==g||w.allowedChats.some(e=>e.id===l.lastUnknownChat?.id),onClick:()=>void k("allow",{action:"allow-chat",chatId:l.lastUnknownChat?.id,title:l.lastUnknownChat?.title},()=>({kind:"ok",message:a("telegram.chatAllowed")})),children:a("telegram.allowChat")}),children:a("telegram.unknownChatPrompt",{title:l.lastUnknownChat.title??a("telegram.unnamedChat"),id:String(l.lastUnknownChat.id)})}),0===w.allowedChats.length?(0,r.jsx)(aM,{children:a("telegram.noChats")}):(0,r.jsx)(r.Fragment,{children:w.allowedChats.map(e=>(0,r.jsx)("div",{className:"channels-chat",children:(0,r.jsxs)(ak,{children:[(0,r.jsxs)(aw,{label:e.title??a("telegram.unnamedChat"),mono:!0,children:[e.id,(0,r.jsxs)(av,{children:[(0,r.jsx)(aP,{size:"small",variant:"secondary",disabled:null!==g,onClick:()=>void k(`test-${e.id}`,{action:"test-send",chatId:e.id},()=>({kind:"ok",message:a("telegram.testSent")})),children:a("telegram.testSend")}),(0,r.jsx)(aP,{size:"small",variant:"secondary",disabled:null!==g,onClick:()=>void k(`remove-${e.id}`,{action:"remove-chat",chatId:e.id},()=>({kind:"info",message:a("telegram.chatRemoved")})),children:a("telegram.chatRemove")})]})]}),(0,r.jsx)(aw,{label:a("telegram.chatCwdLabel"),children:(0,r.jsx)("input",{type:"text",spellCheck:!1,className:"mcp-add-input",placeholder:a("telegram.defaultCwdPlaceholder"),"aria-label":a("telegram.chatCwdLabel"),defaultValue:e.cwd??"",onBlur:t=>{let n=t.target.value.trim();n!==(e.cwd??"")&&k(`cwd-${e.id}`,{action:"set-chat-cwd",chatId:e.id,cwd:n},()=>({kind:"ok",message:a("telegram.chatCwdSaved")}))}},`${e.id}:${e.cwd??""}`)})]})},e.id))}),(0,r.jsx)(ay,{children:a("telegram.defaultCwdLabel")}),(0,r.jsx)(ak,{children:(0,r.jsx)(aw,{label:a("telegram.defaultCwdLabel"),children:(0,r.jsx)("input",{type:"text",spellCheck:!1,className:"mcp-add-input",placeholder:a("telegram.defaultCwdPlaceholder"),"aria-label":a("telegram.defaultCwdLabel"),value:f,onChange:e=>{y.current=!0,m(e.target.value)}})})}),(0,r.jsx)(av,{children:(0,r.jsx)(aP,{size:"small",disabled:null!==g,onClick:()=>void k("cwd",{action:"set-default-cwd",cwd:f.trim()},()=>({kind:"ok",message:a("telegram.defaultCwdSaved")})),children:a("telegram.defaultCwdSave")})})]}):null})})]}),(0,r.jsx)(aL,{status:l?(0,r.jsx)(aA,{tone:l.lastError?"warning":void 0,summary:l.running?a("telegram.connected",{bot:l.botUsername??""}):a("telegram.notConnected")}):void 0,children:!s&&o&&(0,r.jsx)(aP,{onClick:o,children:a("i18n.close")})})]})}let h2={minutes:6e4,hours:36e5,days:864e5};function h4(e){return String(e).padStart(2,"0")}function h8(e){let t=new Date(e);return`${t.getFullYear()}-${h4(t.getMonth()+1)}-${h4(t.getDate())}T${h4(t.getHours())}:${h4(t.getMinutes())}`}function h5(e){if("cron"===e.kind)return{kind:"cron",expr:e.cronExpr.trim(),...""!==e.cronTz.trim()?{tz:e.cronTz.trim()}:{}};if("at"===e.kind){let t=Date.parse(e.atLocal);return Number.isFinite(t)?{kind:"at",atMs:t}:null}let t=Math.round(e.everyValue)*h2[e.everyUnit];return Number.isFinite(t)&&e.everyValue>0?{kind:"every",everyMs:t}:null}function h6(e){if(!e)return{name:"",kind:"every",cronExpr:"0 9 * * *",cronTz:Intl.DateTimeFormat().resolvedOptions().timeZone,atLocal:h8(Date.now()+36e5),everyValue:1,everyUnit:"hours",cwd:"",prompt:"",notify:!0,notifyChannels:[],silentWhen:""};let t=e.schedule;return{name:e.name,kind:t.kind,cronExpr:"cron"===t.kind?t.expr:"0 9 * * *",cronTz:"cron"===t.kind?t.tz??"":"",atLocal:"at"===t.kind?h8(t.atMs):h8(Date.now()+36e5),everyValue:"every"===t.kind?t.everyMs/h2.hours>=1&&t.everyMs%h2.hours==0?t.everyMs/h2.hours:Math.max(1,Math.round(t.everyMs/h2.minutes)):1,everyUnit:"every"===t.kind&&(t.everyMs%h2.hours!=0||t.everyMs<h2.hours)?"minutes":"hours",cwd:e.cwd,prompt:e.prompt,notify:e.notify,notifyChannels:e.notifyChannels.flatMap(e=>"telegram"===e.type&&Number.isInteger(e.chatId)?[{type:"telegram",chatId:e.chatId}]:[]),silentWhen:e.silentWhen}}function h3(e,t){if(null===e)return t("automations.neverAgain");let n=new Date(e),r=new Date().toDateString()===n.toDateString(),i=`${h4(n.getHours())}:${h4(n.getMinutes())}`;return r?i:`${h4(n.getMonth()+1)}-${h4(n.getDate())} ${i}`}async function h9(e){let t=await fetch("/api/automations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json().catch(()=>({}));return{ok:t.ok,error:"string"==typeof n.error?n.error:void 0,payload:n}}function h7(e){let{embedded:t=!0,onClose:n}=e,{t:s}=(0,eO.s)(),[o,a]=(0,i.useState)(null),[l,d]=(0,i.useState)([]),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(()=>h6(null)),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(null),w=(0,i.useRef)("ok"),S=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/automations",{cache:"no-store"}),t=await e.json();if(!e.ok||t.error)return;a(t.automations??[]),d(t.runs??[]),t.telegram&&p(t.telegram)}catch{}},[]);(0,i.useEffect)(()=>{S();let e=setInterval(()=>void S(),5e3);return()=>clearInterval(e)},[S]);let C=(0,i.useMemo)(()=>o?.find(e=>e.id===h)??null,[o,h]),N=(0,i.useCallback)(e=>{f(e),v(null),k(null),g(h6(o?.find(t=>t.id===e)??null))},[o]),E=(0,i.useCallback)(()=>{f("new"),v(null),k(null),g(h6(null))},[]);(0,i.useEffect)(()=>{let e=h5(m);if(!e)return;let t=setTimeout(()=>{h9({action:"preview",schedule:e}).then(e=>{e.ok?v({dueAt:"number"==typeof e.payload?.dueAt?e.payload.dueAt:null,problem:"string"==typeof e.payload?.problem?e.payload.problem:null}):v({dueAt:null,problem:e.error??s("automations.actionFailed")})})},400);return()=>clearTimeout(t)},[m,s]);let I=(0,i.useCallback)(async(e,t,n)=>{y(e),k(null);let r=await h9(t);return(y(null),r.ok)?(null!==n&&(w.current="ok",k(n)),await S(),!0):(w.current="error",k(r.error??s("automations.actionFailed")),!1)},[S,s]),T=()=>n?.(),$=null!==C,M=h5(m),R=""!==m.name.trim()&&""!==m.cwd.trim()&&""!==m.prompt.trim()&&null!==M&&x?.problem==null;return(0,r.jsxs)(ao,{embedded:t,title:s("settings.automations"),closeLabel:s("i18n.close"),onClose:T,children:[(0,r.jsxs)(aa,{children:[(0,r.jsxs)(al,{children:[(0,r.jsx)(ac,{children:null===o?(0,r.jsx)("div",{className:"config-sidebar-message",children:s("i18n.loading")}):0===o.length&&null===h?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:s("automations.noneYet")}):(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(ad,{children:s("automations.group")}),o.map(e=>(0,r.jsxs)(ah,{active:h===e.id,onClick:()=>N(e.id),children:[(0,r.jsx)(aO,{active:e.enabled&&null!==e.nextDueAt}),(0,r.jsx)(af,{className:"is-grow",children:e.name}),(0,r.jsx)("span",{className:"mcp-sidebar-badge",children:e.enabled?null!==e.nextDueAt?h3(e.nextDueAt,s):"…":s("channels.badge.off")})]},e.id))]})}),(0,r.jsx)(aW,{active:"new"===h,onClick:E,children:s("automations.newAction")})]}),(0,r.jsx)(aR,{children:(0,r.jsxs)(am,{className:"is-fill",children:[(null===h||"new"===h||$)&&(0,r.jsxs)(r.Fragment,{children:[j&&(0,r.jsx)(aT,{children:j}),null!==h&&"new"!==h&&$&&(0,r.jsxs)(ag,{children:[(0,r.jsx)(ax,{children:(0,r.jsx)(ab,{children:C.name})}),(0,r.jsxs)(av,{children:[(0,r.jsx)(az,{checked:C.enabled,disabled:null!==b,label:s("automations.enabledLabel"),onChange:e=>void I(`enabled-${C.id}`,{action:"set-enabled",id:C.id,enabled:e},null)}),(0,r.jsx)(aP,{size:"small",variant:"secondary",disabled:null!==b,onClick:()=>void I(`run-${C.id}`,{action:"run-now",id:C.id},s("automations.runStarted")),children:s("automations.runNow")}),(0,r.jsx)(aP,{size:"small",variant:"danger",disabled:null!==b,onClick:()=>{I(`delete-${C.id}`,{action:"delete",id:C.id},s("automations.deleted")).then(e=>{e&&N(null)})},children:s("automations.delete")})]})]}),(0,r.jsxs)(ak,{children:[(0,r.jsx)(aw,{label:s("automations.nameLabel"),children:(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,"aria-label":s("automations.nameLabel"),value:m.name,onChange:e=>g(t=>({...t,name:e.target.value}))})}),(0,r.jsx)(aw,{label:s("automations.scheduleLabel"),children:(0,r.jsxs)("div",{className:"automations-schedule",children:[(0,r.jsxs)("select",{"aria-label":s("automations.scheduleLabel"),value:m.kind,onChange:e=>g(t=>({...t,kind:e.target.value})),children:[(0,r.jsx)("option",{value:"cron",children:s("automations.kind.cron")}),(0,r.jsx)("option",{value:"every",children:s("automations.kind.every")}),(0,r.jsx)("option",{value:"at",children:s("automations.kind.at")})]}),"cron"===m.kind&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,placeholder:"0 9 * * 1-5","aria-label":s("automations.cronExpr"),value:m.cronExpr,onChange:e=>g(t=>({...t,cronExpr:e.target.value}))}),(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,placeholder:"Asia/Shanghai","aria-label":s("automations.cronTz"),value:m.cronTz,onChange:e=>g(t=>({...t,cronTz:e.target.value}))})]}),"every"===m.kind&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{className:"automations-number-input",type:"number",min:1,"aria-label":s("automations.everyValue"),value:m.everyValue,onChange:e=>g(t=>({...t,everyValue:Number(e.target.value)}))}),(0,r.jsxs)("select",{"aria-label":s("automations.everyUnit"),value:m.everyUnit,onChange:e=>g(t=>({...t,everyUnit:e.target.value})),children:[(0,r.jsx)("option",{value:"minutes",children:s("automations.unit.minutes")}),(0,r.jsx)("option",{value:"hours",children:s("automations.unit.hours")}),(0,r.jsx)("option",{value:"days",children:s("automations.unit.days")})]})]}),"at"===m.kind&&(0,r.jsx)("input",{className:"automations-datetime-input",type:"datetime-local","aria-label":s("automations.atTime"),value:m.atLocal,onChange:e=>g(t=>({...t,atLocal:e.target.value}))})]})}),(0,r.jsx)(aw,{label:s("automations.nextRun"),children:null===x?"…":null!==x.problem?`⚠️ ${x.problem}`:`${h3(x.dueAt,s)}`}),(0,r.jsx)(aw,{label:s("automations.cwdLabel"),children:(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,placeholder:"/Volumes/…","aria-label":s("automations.cwdLabel"),value:m.cwd,onChange:e=>g(t=>({...t,cwd:e.target.value}))})}),(0,r.jsx)(aw,{label:s("automations.notifyLabel"),children:(0,r.jsxs)("div",{className:"automations-notify",children:[(0,r.jsxs)("div",{className:"automations-notify-row",children:[(0,r.jsx)(az,{checked:m.notify,label:s("automations.notifyBrowser"),onChange:e=>g(t=>({...t,notify:e}))}),(0,r.jsx)("span",{children:s("automations.notifyBrowser")})]}),null!==u&&u.chats.map(e=>{let t=m.notifyChannels.some(t=>t.chatId===e.id);return(0,r.jsxs)("label",{className:"automations-notify-row",children:[(0,r.jsx)("input",{type:"checkbox",checked:t,onChange:t=>g(n=>({...n,notifyChannels:t.target.checked?[...n.notifyChannels,{type:"telegram",chatId:e.id}]:n.notifyChannels.filter(t=>t.chatId!==e.id)}))}),(0,r.jsx)("span",{children:null!==e.title&&""!==e.title.trim()?e.title:`Telegram \xb7 ${e.id}`})]},e.id)}),null!==u&&0===u.chats.length&&(0,r.jsx)("div",{className:"automations-notify-hint",children:s("automations.notifyTelegramHint")}),(0,r.jsxs)("div",{className:"automations-notify-row is-wide",children:[(0,r.jsx)("span",{className:"automations-notify-silent-label",children:s("automations.notifySilentLabel")}),(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,placeholder:"NO_REPLY","aria-label":s("automations.notifySilentLabel"),value:m.silentWhen,onChange:e=>g(t=>({...t,silentWhen:e.target.value}))})]}),(0,r.jsx)("div",{className:"automations-notify-hint",children:s("automations.notifySilentHint")})]})})]}),(0,r.jsx)(aj,{label:s("automations.promptLabel"),children:(0,r.jsx)("textarea",{className:"automations-prompt",rows:5,spellCheck:!1,"aria-label":s("automations.promptLabel"),value:m.prompt,onChange:e=>g(t=>({...t,prompt:e.target.value}))})}),"new"===h&&(0,r.jsx)(aT,{children:s("automations.disclosure")}),(0,r.jsx)(av,{children:(0,r.jsx)(aP,{disabled:!R||null!==b,onClick:()=>{I("save",{action:$?"update":"create",...$?{id:C.id}:{},name:m.name.trim(),schedule:h5(m),cwd:m.cwd.trim(),prompt:m.prompt,notify:m.notify,notifyChannels:m.notifyChannels,silentWhen:m.silentWhen.trim()},$?s("automations.saved"):s("automations.created")).then(e=>{e&&($||f(null))})},children:$?s("automations.save"):s("automations.create")})})]}),(0,r.jsx)(ay,{children:s("automations.historyTitle")}),0===l.length?(0,r.jsx)(aM,{children:s("automations.noRuns")}):(0,r.jsx)(ak,{children:l.slice(0,12).map(e=>{let t=o?.find(t=>t.id===e.automationId),n=null!==e.finishedAt?Math.max(1,Math.round((e.finishedAt-e.startedAt)/1e3)):null;return(0,r.jsxs)(aw,{label:t?.name??s("automations.deletedAutomation"),mono:!0,children:[(0,r.jsx)(aO,{..."failed"===e.status?{color:"#ef4444"}:{active:"done"===e.status}}),s(`automations.run.${e.status}`)," \xb7 ",new Date(e.startedAt).toLocaleString(),null!==n?` \xb7 ${n}s`:"",null!==e.sessionId&&(0,r.jsx)(aP,{size:"small",variant:"secondary",onClick:()=>window.open(c(e.sessionId),"_blank"),children:s("automations.openSession")})]},e.id)})})]})})]}),(0,r.jsx)(aL,{status:null!==o?(0,r.jsx)(aA,{summary:s("automations.footerCount",{count:o.length})}):void 0,children:!t&&T&&(0,r.jsx)(aP,{onClick:T,children:s("i18n.close")})})]})}let fe=[{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 ft(){let{t:e}=(0,eO.s)(),t=id();return(0,r.jsx)("div",{className:"settings-font-rows",children:fe.map(n=>{let{kind:i,label:s,placeholder:o,reset:a,weightLabel:l}=n,c=t[`${i}Weight`],d=rQ.findIndex(e=>e.value===c);return(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option settings-font-row",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header settings-font-header",children:[(0,r.jsx)("label",{htmlFor:`settings-font-${i}`,children:e(s)}),(0,r.jsx)("input",{id:`settings-font-${i}`,className:`settings-font-input${"mono"===i?" is-mono":""}`,type:"text",value:t[i],placeholder:e(o),maxLength:500,"aria-describedby":"settings-typography-description",autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,onChange:e=>t.setFontPreference(i,e.target.value)}),(0,r.jsx)("output",{htmlFor:`settings-font-${i}-weight`,title:`${e(l)}: ${c}`,children:e(rQ[d].label)}),(0,r.jsx)(aP,{variant:"ghost",size:"small",className:"settings-chat-reset",title:e(a),"aria-label":e(a),disabled:!t[i]&&400===c,onClick:()=>t.resetFontPreference(i),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:`settings-font-${i}-weight`,type:"range",min:rQ[0].value,max:rQ[rQ.length-1].value,step:100,value:c,"aria-label":e(l),"aria-valuetext":`${c} ${e(rQ[d].label)}`,onChange:e=>t.setFontWeight(i,Number(e.target.value))})]},i)})})}function fn(e){let{section:t,size:n=16,strokeWidth:i=1.8}=e,s={width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:"settings-section-icon"};return"general"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("path",{d:"M20 7h-9M14 17H5"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"3"}),(0,r.jsx)("circle",{cx:"17",cy:"17",r:"3"})]}):"models"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("path",{d:"M9 1v3M15 1v3M9 20v3M15 20v3M20 9h3M20 15h3M1 9h3M1 15h3"})]}):"skills"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("path",{d:"m12 2-10 5 10 5 10-5-10-5Z"}),(0,r.jsx)("path",{d:"m2 12 10 5 10-5M2 17l10 5 10-5"})]}):"agents"===t?(0,r.jsxs)("svg",{...s,className:"settings-section-icon is-agent",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]}):"mcp"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"7",rx:"2"}),(0,r.jsx)("rect",{x:"3",y:"14",width:"18",height:"7",rx:"2"}),(0,r.jsx)("path",{d:"M7 6.5h.01M7 17.5h.01M11 6.5h6M11 17.5h6"})]}):"channels"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("path",{d:"m21.5 4.5-2.9 13.2a1.6 1.6 0 0 1-2.5.9L12 15.6l-2.3 2.3a1 1 0 0 1-1.7-.5L7 13.6 3.4 12.2a.8.8 0 0 1-.1-1.5L20.2 3.2a.9.9 0 0 1 1.3 1.3Z"}),(0,r.jsx)("path",{d:"m7 13.6 11.7-8.4L9.4 14.8"})]}):"automations"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 7v5l3.5 2"})]}):(0,r.jsx)("svg",{...s,children:(0,r.jsx)("path",{d:"M9 7V2M15 7V2M6 13V8a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v5a6 6 0 0 1-12 0ZM12 19v3"})})}function fr(e){let{sessionId:t,onSessionReloaded:n,quoteSelectionEnabled:s,onQuoteSelectionChange:o}=e,{locale:a,setLocale:l,supportedLocales:c,t:d}=(0,eO.s)(),{preference:u,setThemePreference:p}=(0,or.D)(),{width:h,setWidth:f,fontSize:m,setFontSize:g}=rX(),x=rW(),v=eW(),[b,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(!1),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(!1),[E,I]=(0,i.useState)(null),[T,$]=(0,i.useState)(!1),[M,R]=(0,i.useState)(null),[L,A]=(0,i.useState)(!1),[P,z]=(0,i.useState)(null),[W,O]=(0,i.useState)(!1),[D,F]=(0,i.useState)(!1),[B,H]=(0,i.useState)("");(0,i.useEffect)(()=>{N((0,o4.ql)()),fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>O(e?.enabled===!0)).catch(()=>{})},[]);let U=async()=>{F(!0),H("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.replace("/login")}catch{H(d("auth.logoutFailed"))}finally{F(!1)}};(0,i.useEffect)(()=>{let e=!1;return fetch("/api/tools/settings").then(async t=>{let n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);e||y(n)}).catch(t=>{e||S(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/cache-miss-notices").then(async t=>{let n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);e||I(!0===n.enabled)}).catch(t=>{e||R(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]);let _=async e=>{$(!0),R(null);try{let r=await fetch("/api/cache-miss-notices",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);I(!0===i.enabled),t&&n()}catch(e){R(e instanceof Error?e.message:String(e))}finally{$(!1)}},q=async e=>{k(!0),S(null);try{let r=await fetch("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);y(i),t&&(await sa(t,{type:"reload"}),n())}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(!1)}},K=async()=>{if(!L){A(!0),z(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 lv(a))throw Error("unsupported or not permitted");z({kind:"ok",message:d("settings.pushRegistered")})}catch(e){z({kind:"error",message:`${d("settings.pushRegisterFailed")} ${e instanceof Error?e.message:String(e)}`})}finally{A(!1)}}};return(0,r.jsxs)("div",{className:"settings-general",children:[(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.appearance")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":d("settings.appearance"),className:"settings-theme-options",children:oK.F$.map(e=>{let t=u===e.id;return(0,r.jsxs)("label",{className:"settings-theme-option","data-system":"auto"===e.id||void 0,"data-wide":"contrast-light"===e.id||"contrast-dark"===e.id||"zenburn"===e.id||void 0,children:[(0,r.jsx)("input",{type:"radio",name:"theme",value:e.id,checked:t,onChange:()=>p(e.id),className:"sr-only"}),"auto"===e.id?(0,r.jsxs)("span",{className:"settings-theme-swatch settings-theme-system","aria-hidden":"true",children:[(0,r.jsx)("span",{"data-theme":"light",className:"settings-theme-chip"}),(0,r.jsx)("span",{"data-theme":"dark",className:"settings-theme-chip"}),(0,r.jsx)("span",{className:"settings-theme-system-name",children:d(e.label)})]}):(0,r.jsx)("span",{className:"settings-theme-swatch","aria-hidden":"true",children:(0,r.jsx)("span",{"data-theme":e.id,className:"settings-theme-fill",children:(0,r.jsx)("span",{className:"settings-theme-name",children:d(e.label)})})}),(0,r.jsx)("span",{className:"sr-only",children:d(e.label)})]},e.id)})})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.typography")}),(0,r.jsx)("p",{id:"settings-typography-description",className:"settings-general-description",children:d("settings.fontDescription")}),(0,r.jsxs)("div",{className:"settings-chat-options",children:[(0,r.jsx)(ft,{}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-font-size",children:d("settings.chatContentFontSize")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-font-size",children:[m,"px"]}),(0,r.jsx)(aP,{variant:"ghost",size:"small",className:"settings-chat-reset",title:d("settings.resetChatContentFontSize"),"aria-label":d("settings.resetChatContentFontSize"),disabled:14===m,onClick:()=>g(14),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:"settings-chat-content-font-size",type:"range",min:12,max:24,step:1,value:m,onChange:e=>g(Number(e.target.value))})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-width",children:d("settings.chatContentWidth")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-width",children:[h,"px"]}),(0,r.jsx)(aP,{variant:"ghost",size:"small",className:"settings-chat-reset",title:d("settings.resetChatContentWidth"),"aria-label":d("settings.resetChatContentWidth"),disabled:820===h,onClick:()=>f(820),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:"settings-chat-content-width",type:"range",min:820,max:2e3,step:10,value:h,onChange:e=>f(Number(e.target.value))})]})]})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.chat")}),(0,r.jsxs)("div",{className:"settings-chat-options",children:[(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:d("settings.thinkingExpandedDefault")}),(0,r.jsx)(az,{checked:C,label:d("settings.thinkingExpandedDefault"),onChange:e=>{(0,o4.kF)(e),N(e)}})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:d("settings.quoteSelection")}),(0,r.jsx)(az,{checked:s,label:d("settings.quoteSelection"),onChange:o})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",role:"radiogroup","aria-label":d("settings.enterSendMode"),children:[(0,r.jsx)("span",{children:d("settings.enterSendMode")}),(0,r.jsxs)("div",{className:"settings-send-mode-options",children:[(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"enter-send-mode",value:"enter",checked:"enter"===x,onChange:()=>rz("enter"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:d("settings.enterSendModeEnter")})]}),(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"enter-send-mode",value:"ctrlEnter",checked:"ctrlEnter"===x,onChange:()=>rz("ctrlEnter"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:d("settings.enterSendModeCtrlEnter")})]})]})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:d("settings.cacheMissNotices")}),(0,r.jsx)(az,{checked:!0===E,loading:null===E&&!M||T,label:d("settings.cacheMissNotices"),describedBy:"settings-cache-miss-notices-description",onChange:e=>void _(e)})]})]}),(0,r.jsx)("p",{id:"settings-cache-miss-notices-description",className:"settings-general-description",children:d("settings.cacheMissNoticesDescription")}),M&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:M})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.sidebar")}),(0,r.jsx)("div",{className:"settings-chat-options",children:(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",role:"radiogroup","aria-label":d("settings.filesPlacement"),"aria-describedby":"settings-files-placement-description",children:[(0,r.jsx)("span",{children:d("settings.filesPlacement")}),(0,r.jsxs)("div",{className:"settings-send-mode-options",children:[(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"files-placement",value:"below",checked:"below"===v,onChange:()=>ez("below"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:d("settings.filesPlacementBelow")})]}),(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"files-placement",value:"tab",checked:"tab"===v,onChange:()=>ez("tab"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:d("settings.filesPlacementTab")})]})]})]})}),(0,r.jsx)("p",{id:"settings-files-placement-description",className:"settings-general-description",children:d("settings.filesPlacementDescription")})]}),b?.isWindows&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.shellTool")}),(0,r.jsx)("p",{className:"settings-general-description",children:d("settings.shellToolDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:d("settings.usePowerShell")}),(0,r.jsx)(az,{checked:b.powerShellEnabled,loading:j,label:d("settings.usePowerShell"),onChange:e=>void q(e)})]}),w&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:w})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.pushPermission")}),(0,r.jsx)("p",{className:"settings-general-description",children:d("settings.pushPermissionDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:d("settings.pushPermission")}),(0,r.jsx)("button",{type:"button",className:"config-button config-button-small config-button-secondary",disabled:L,onClick:()=>void K(),children:L?d("settings.pushRegisterLoading"):d("settings.pushRegister")})]}),P&&(0,r.jsx)("p",{role:"status",className:"settings-general-error",style:"ok"===P.kind?{color:"var(--accent)"}:void 0,children:P.message})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("common.language")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":d("common.language"),className:"settings-language-options",children:c.map(e=>{let t=a===e.id;return(0,r.jsxs)("button",{type:"button",role:"radio","aria-checked":t,onClick:()=>l(e.id),className:"settings-language-option",children:[(0,r.jsx)("span",{className:"settings-language-radio",children:t&&(0,r.jsx)("span",{className:"settings-language-radio-dot"})}),(0,r.jsx)("span",{className:"settings-language-label",children:e.label}),(0,r.jsx)("span",{className:"settings-language-code",children:e.id})]},e.id)})})]}),W&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsxs)(aP,{variant:"secondary",disabled:D,onClick:()=>void U(),children:[(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M10 17l5-5-5-5M15 12H3M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"})}),D?d("auth.loggingOut"):d("auth.logOut")]}),B&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:B})]})]})}function fi(e){let{cwd:t,sessionId:n,initialSection:s,onClose:o,onSessionReloaded:a,quoteSelectionEnabled:l,onQuoteSelectionChange:c,projectTrust:d,onOpenTrustDialog:u,onProjectTrustChanged:p}=e,{t:h}=(0,eO.s)(),[f,m]=(0,i.useState)(s),[g,x]=(0,i.useState)(()=>new Set([f])),v=[{id:"general",label:h("settings.general")},{id:"models",label:h("common.models")},{id:"skills",label:h("common.skills")},{id:"agents",label:h("common.agents")},{id:"plugins",label:h("common.plugins")},{id:"mcp",label:h("settings.mcp")},{id:"channels",label:h("settings.channels")},{id:"automations",label:h("settings.automations")}].map(e=>({...e,requiresProject:oG(e.id)})),b=oG(f);(0,i.useEffect)(()=>o0(s),[s]),(0,i.useEffect)(()=>{var e;let t;return e=document,t=e=>{"Escape"!==e.key||e.defaultPrevented||eC(e)||(e.preventDefault(),o())},e.addEventListener("keydown",t,!1),()=>e.removeEventListener("keydown",t,!1)},[o]);let y=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>(function(e,t){let{restoreTextEntry:n=!0}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=e.activeElement,i=!!(r&&t&&t.contains(r)),s=r&&r!==e.body&&!i?r:null;return t&&!i&&t.focus({preventScroll:!0}),()=>{if(!s||!s.isConnected||!n&&function(e){if(e.isContentEditable)return!0;let t=e.tagName?.toUpperCase();return"TEXTAREA"===t||"INPUT"===t&&!["button","checkbox","color","file","hidden","image","radio","range","reset","submit"].includes((e.type??"text").toLowerCase())}(s))return;let r=e.activeElement;r&&r!==e.body&&!(t&&t.contains(r))||"function"==typeof s.focus&&s.focus({preventScroll:!0})}})(document,y.current,{restoreTextEntry:!window.matchMedia?.("(pointer: coarse)").matches}),[]),(0,i.useEffect)(()=>{!t&&b&&(m("general"),x(e=>new Set(e).add("general")),o0("general"))},[t,b]);let j=e=>{x(t=>new Set(t).add(e)),m(e),o0(e)},k=(e,t)=>g.has(e)?(0,r.jsx)("div",{hidden:f!==e,className:"settings-section-host",children:t},e):null;return(0,r.jsx)("div",{ref:y,role:"dialog","aria-modal":"true","aria-label":h("settings.title"),tabIndex:-1,onClick:e=>{e.target===e.currentTarget&&o()},className:"settings-dialog-backdrop",children:(0,r.jsxs)("div",{className:"settings-dialog-surface",children:[(0,r.jsxs)("div",{className:"settings-dialog-header",children:[(0,r.jsx)("strong",{className:"settings-dialog-title",children:h("settings.title")}),(0,r.jsx)("select",{"aria-label":h("settings.title"),value:f,onChange:e=>j(e.target.value),className:"settings-mobile-section-picker",children:v.map(e=>(0,r.jsx)("option",{value:e.id,disabled:e.requiresProject&&!t,children:e.label},e.id))}),(0,r.jsx)("nav",{"aria-label":h("settings.title"),className:"settings-section-tabs",children:v.map(e=>{let n=f===e.id,i=e.requiresProject&&!t;return(0,r.jsxs)("button",{type:"button",className:"settings-section-tab",disabled:i,title:i?h("settings.projectRequired"):e.label,"aria-current":n?"page":void 0,onClick:()=>j(e.id),children:[(0,r.jsx)(fn,{section:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id)})}),(0,r.jsx)("button",{type:"button",onClick:o,title:h("i18n.close"),"aria-label":h("i18n.close"),className:"config-close-button settings-dialog-close",children:"\xd7"})]}),(0,r.jsxs)("main",{className:"settings-dialog-main",children:[k("general",(0,r.jsx)(fr,{sessionId:n,onSessionReloaded:a,quoteSelectionEnabled:l,onQuoteSelectionChange:c})),k("models",(0,r.jsx)(lg,{embedded:!0,cwd:t,onClose:o})),t&&k("skills",(0,r.jsx)(lT,{embedded:!0,cwd:t,trust:d,onClose:o},t)),t&&k("agents",(0,r.jsx)(lH,{embedded:!0,cwd:t,sessionId:n,trust:d,onClose:o,onReloaded:a},t)),t&&k("plugins",(0,r.jsx)(l1,{embedded:!0,cwd:t,sessionId:n,trust:d,onClose:o,onReloaded:a},t)),k("mcp",(0,r.jsx)(hA,{embedded:!0,cwd:t,trust:d,onTrustProject:u,onProjectTrustChanged:p,onClose:o},t??"")),k("channels",(0,r.jsx)(h1,{})),k("automations",(0,r.jsx)(h7,{}))]})]})})}let fs="project-trust-mcp-status";function fo(e){let{cwd:t,busy:n,error:s,onCancel:o,onConfirm:a,onStatus:l}=e,[c,d]=(0,i.useState)({state:"loading"}),u=(0,i.useRef)(l);return(0,i.useEffect)(()=>{u.current=l},[l]),(0,i.useEffect)(()=>{let e=!0,n=!1;d({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);d(r),"loaded"===r.state&&r.status&&u.current?.(r.status)}).catch(t=>{e&&d(n?{state:"failed",timedOut:!0}:{state:"failed",error:t instanceof Error?t.message:String(t)})}).finally(()=>window.clearTimeout(i)),()=>{e=!1,window.clearTimeout(i),r.abort()}},[t]),(0,r.jsx)(fa,{cwd:t,busy:n,error:s,listing:c,onCancel:o,onConfirm:a})}function fa(e){let{cwd:t,busy:n,error:s,listing:o,onCancel:a,onConfirm:l}=e,{t:c}=(0,eO.s)(),d="loading"===o.state,u="loaded"===o.state?function(e){if(e){if(!e.requiresTrust)return"mcp.reason.trust-not-required";if(e.trusted)return"trust.alreadyTrusted"}}(o.status):void 0,p=(0,i.useRef)(null),h=(0,i.useRef)(n),f=(0,i.useRef)(a);return(0,i.useEffect)(()=>{h.current=n,f.current=a},[n,a]),(0,i.useEffect)(()=>{var e,t,n;let r,i,s;return e=document,t=p.current,n=()=>{h.current||f.current()},r=e.activeElement,t?.focus({preventScroll:!0}),i=e=>{"Escape"!==e.key||(e.stopPropagation(),eC(e)||(e.preventDefault(),n()))},e.addEventListener("keydown",i,!0),s=()=>e.removeEventListener("keydown",i,!0),()=>{s(),r&&r.isConnected&&"function"==typeof r.focus&&r.focus({preventScroll:!0})}},[]),(0,r.jsx)("div",{role:"presentation",className:"project-trust-backdrop",onClick:e=>{n||e.target!==e.currentTarget||a()},children:(0,r.jsxs)("div",{ref:p,role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title","aria-describedby":"project-trust-description",tabIndex:-1,className:"project-trust-dialog",children:[(0,r.jsxs)("div",{className:"project-trust-body",children:[(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"project-trust-icon",children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,r.jsxs)("div",{className:"project-trust-content",children:[(0,r.jsx)("div",{id:"project-trust-title",className:"project-trust-title",children:c("trust.dialogTitle")}),(0,r.jsx)("div",{id:"project-trust-description",className:"project-trust-text",children:c("trust.dialogBody")}),(0,r.jsx)("code",{className:"project-trust-path",children:l5(t)}),u&&(0,r.jsx)("p",{id:"project-trust-notice",role:"status",className:"project-trust-notice",children:c(u)}),"loaded"===o.state&&void 0!==o.statusError&&(0,r.jsxs)("div",{className:"project-trust-mcp-failed",children:[(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:c("mcp.reason.trust-unreadable")}),(0,r.jsx)("code",{className:"project-trust-mcp-detail",children:l5(o.statusError)})]}),(0,r.jsx)(fc,{listing:o})]})]}),s&&(0,r.jsx)(fl,{error:s}),(0,r.jsxs)("div",{className:"project-trust-footer",children:[(0,r.jsx)("button",{type:"button",className:"project-trust-button",onClick:a,disabled:n,children:c(u?"trust.close":"trust.cancel")}),!u&&(0,r.jsx)("button",{type:"button",className:"project-trust-button is-primary",onClick:l,disabled:n||d,"aria-busy":n||void 0,"aria-describedby":d?fs:void 0,children:c(n?"trust.trusting":"trust.trustProject")})]})]})})}function fl(e){let{error:t}=e,{t:n}=(0,eO.s)(),i=void 0!==t.reason&&"internal"!==t.reason;return(0,r.jsxs)("div",{role:"alert",className:"project-trust-error",children:[n(i?`mcp.reason.${t.reason}`:"trust.trustFailed"),!i&&(0,r.jsx)("code",{className:"project-trust-error-detail",children:l5(t.error)})]})}function fc(e){let{listing:t}=e,{t:n}=(0,eO.s)();if("loading"===t.state)return(0,r.jsx)("p",{id:fs,role:"status",className:"project-trust-mcp-status",children:n("trust.mcp.loading")});if("failed"===t.state||void 0!==t.listing.mcpError||!t.listing.mcpFile){let e;e="failed"===t.state?t.reason&&"internal"!==t.reason?n(`mcp.reason.${t.reason}`):t.error:t.listing.mcpError;let i="failed"===t.state&&t.timedOut;return(0,r.jsxs)("div",{className:"project-trust-mcp-failed",children:[(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:n(i?"trust.mcp.timedOut":"trust.mcp.loadFailed")}),e&&(0,r.jsx)("code",{className:"project-trust-mcp-detail",children:l5(e)})]})}let{mcpFile:i,mcpServers:s}=t.listing;return i.exists||0!==i.problems.length?(0,r.jsxs)("section",{className:"project-trust-mcp","aria-labelledby":"project-trust-mcp-title",children:[(0,r.jsx)("div",{id:"project-trust-mcp-title",className:"project-trust-mcp-title",children:n("trust.mcp.title")}),s.length>0&&(0,r.jsx)("p",{className:"project-trust-mcp-intro",children:n("trust.mcp.intro")}),(0,r.jsx)(fd,{file:i}),0===s.length&&0===i.problems.length&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:n("trust.mcp.none")}),s.some(e=>!e.validated)&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:n("trust.mcp.unchecked")}),s.length>0&&(0,r.jsx)("ul",{className:"project-trust-mcp-list",children:s.map(e=>(0,r.jsx)(fh,{server:e},e.name))})]}):null}function fd(e){let{file:t}=e,{t:n}=(0,eO.s)();return(0,r.jsx)(r.Fragment,{children:t.problems.map(e=>{let i=cs(e,t.realPath);return(0,r.jsxs)("div",{className:"project-trust-mcp-problem",children:[(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:n(`mcp.fileProblem.${e.reason}`)}),i&&(0,r.jsx)("code",{className:"project-trust-mcp-detail",children:i})]},e.reason)})})}function fu(e){let{fields:t}=e,{t:n}=(0,eO.s)();return(0,r.jsx)(r.Fragment,{children:t.map(e=>{let t=ct(e);return(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function fp(e){let{server:t}=e,{t:n}=(0,eO.s)();return(0,r.jsx)(r.Fragment,{children:ci(t.variableReferences).map(e=>{let{variable:t,field:i}=e,s=ct(i);return(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:n("mcp.server.variableIn",{variable:t,field:n(s.key,s.params)})},`${t}\0${i.kind}\0${i.name??""}`)})})}function fh(e){let t,{server:n}=e,{t:i}=(0,eO.s)(),s=l7(n),o=void 0===n.invalidError;return(0,r.jsxs)("li",{className:"project-trust-mcp-server",children:[(0,r.jsxs)("div",{className:"project-trust-mcp-server-head",children:[(0,r.jsx)("span",{className:"project-trust-mcp-server-name",children:l5(n.name)}),n.transport&&(0,r.jsx)("span",{className:"project-trust-mcp-tag",children:i(`mcp.transport.${n.transport}`)})]}),void 0!==s&&(0,r.jsx)("code",{className:"project-trust-mcp-target",children:s}),void 0!==n.cwd&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:i("trust.mcp.cwd",{path:l5(n.cwd)})}),ce(n)&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:i("mcp.server.hiddenCharacters")}),void 0!==n.invalidError&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.invalid")," ",(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:l5(n.invalidError)})]}),n.webPasswordField&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.webPassword")," ",(0,r.jsx)(fu,{fields:[n.webPasswordField]})]}),!n.enabled&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:i("mcp.server.disabled")}),o&&n.commandFields.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.commandFields")," ",(0,r.jsx)(fu,{fields:n.commandFields})]}),o&&n.variableReferences.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i(cn(n))," ",(0,r.jsx)(fp,{server:n})]}),n.replacesGlobal&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:i("mcp.server.replacesGlobal")}),n.override&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:i((t=cr(n.override.keys)).key,t.params)}),n.masked&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-dim",children:i("mcp.server.masked")})]})}function ff(e){return"message"===e.type&&"message"in e&&"system"!==e.message.role}function fm(e){let t=e,n=t.branchPreview,r=ff(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&ff(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function fg(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 fx(e){let{node:t,activePathIds:n,depth:i,isLast:s,parentLines:o,onSelect:a}=e,{node:l,skipped:c,branchPreview:d,labelEntry:u}=fm(t),p=n.has(l.entry.id),h=n.has(t.entry.id)||n.has(l.entry.id),f=d?.text??function(e){if("message"===e.type&&ff(e)){let t=e.message,n=t.content,r="";if("string"==typeof n?r=n:Array.isArray(n)&&(r=n.filter(e=>"text"===e.type).map(e=>e.text).join(" ")),r.length>40&&(r=r.slice(0,40)+"…"),r)return r;if("assistant"===t.role)return"[assistant]"}return e.type}(u),m=d?d.role??null:ff(u)?u.message.role:null;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:a?"pointer":"default"},onClick:a?()=>a(l.entry.id):void 0,children:[o.map((e,t)=>(0,r.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,r.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:s?"50%":0,width:1,background:"var(--border)"}}),(0,r.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,r.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:p?"var(--accent)":h?"var(--text-muted)":"var(--border)",border:p?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),m&&(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===m?"var(--accent)":"var(--text-dim)",background:"user"===m?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===m?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===m?"U":"A"}),c>0&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",c]}),(0,r.jsx)("span",{style:{fontSize:11,color:p?"var(--text)":h?"var(--text-muted)":"var(--text-dim)",fontWeight:p?500:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:f})]}),l.children.map((e,t)=>(0,r.jsx)(fx,{node:e,activePathIds:n,depth:i+1,isLast:t===l.children.length-1,parentLines:[...o,!s],onSelect:a},e.entry.id))]})}function fv(e){let{tree:t,activeLeafId:n,onLeafChange:s,inline:o,containerRef:a,open:l,onToggle:c,hasSession:d,compact:u,hideInlineButton:p,locked:h=!1}=e,{t:f}=(0,eO.s)(),[m,g]=(0,i.useState)(!1),x=void 0!==l?l:m,v=(0,i.useRef)(null),[b,y]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!x||!o)return;let e=a?.current??v.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();y({top:t.bottom,left:t.left,width:t.width})};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[x,o,a]);let j=(0,i.useMemo)(()=>(function(e,t){if(!t)return new Set;let n=e.map(e=>({node:e,path:[e.entry.id]}));for(;n.length>0;){let{node:e,path:r}=n.pop();if(e.entry.id===t||e.compressedEntryIds?.includes(t))return new Set(r);for(let t of e.children)n.push({node:t,path:[...r,t.entry.id]})}return new Set})(t,n),[t,n]),k=(0,i.useCallback)(e=>{s(e)},[s]),w=h?void 0:k,S=h&&(0,r.jsx)("div",{style:{padding:"2px 0 4px",fontSize:11,color:"var(--text-dim)",fontStyle:"italic"},children:f("i18n.branchesLockedWhileRunning")}),C=d?fg(t)?null:f("i18n.noBranches"):f("i18n.noActiveSession"),N=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=fm(e[0]).node;return t.children.length>1?t.children:[]}(t),E=!C&&N.length>0,I=(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:E?"var(--accent)":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),T=(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{marginLeft:2,transform:x?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})});return o?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"stretch"},children:[(0,r.jsxs)("button",{ref:v,onClick:()=>c?c():g(e=>!e),style:{display:p?"none":"flex",alignItems:"center",gap:6,height:"100%",padding:"0 12px",background:x?"var(--bg-selected)":"none",border:"none",borderTop:x?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:"pointer",color:x?"var(--text)":"var(--text-muted)",fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color=x?"var(--text)":"var(--text-muted)"},title:f("i18n.branches"),"aria-label":f("i18n.branches"),"aria-pressed":x,children:[I,!u&&(0,r.jsx)("span",{children:f("i18n.branches")})]}),x&&b&&(0,r.jsx)("div",{style:{position:"fixed",top:b.top,left:b.left,width:b.width,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",zIndex:500},children:E?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(fx,{node:e,activePathIds:j,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:w},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C})})]}):(0,r.jsxs)("div",{style:{borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>g(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"5px 12px",background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",fontSize:11,textAlign:"left"},children:[I,(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:f("i18n.branches")}),T]}),x&&(0,r.jsx)("div",{style:{position:"absolute",top:"100%",left:0,right:0,background:"var(--bg)",borderBottom:"1px solid var(--border)",boxShadow:"0 4px 12px rgba(0,0,0,0.1)",zIndex:100},children:E?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(fx,{node:e,activePathIds:j,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:w},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C??f("i18n.noBranches")})})]})}function fb(e){let{loading:t,prompt:n,translate:i}=e;return(0,r.jsxs)("section",{className:"system-prompt-panel","aria-label":i("system.prompt"),children:[(0,r.jsx)("div",{className:"system-prompt-scroll",children:n?(0,r.jsx)("div",{className:"system-prompt-text",children:n}):(0,r.jsx)("div",{className:"system-prompt-empty",children:i(""===n?"system.empty":t?"system.loading":"system.load")})}),(0,r.jsx)("style",{children:`
11
- .system-prompt-panel {
12
- display: flex;
13
- height: min(600px, 75dvh);
14
- min-height: 220px;
15
- flex-direction: column;
16
- background: var(--bg-panel);
17
- border-bottom: 1px solid var(--border);
18
- }
19
- .system-prompt-scroll {
20
- min-height: 0;
21
- flex: 1;
22
- overflow: auto;
23
- padding: 12px 16px;
24
- }
25
- .system-prompt-text {
26
- color: var(--text-muted);
27
- font-family: var(--font-mono);
28
- font-size: 12px;
29
- line-height: 1.6;
30
- overflow-wrap: anywhere;
31
- white-space: pre-wrap;
32
- }
33
- .system-prompt-empty {
34
- padding: 10px 0;
35
- color: var(--text-muted);
36
- font-size: 12px;
37
- font-style: italic;
38
- }
39
- `})]})}function fy(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e)}catch{return String(e)}}function fj(e){let{children:t}=e;return(0,r.jsx)("div",{className:"tool-definitions-empty",children:t})}function fk(e){let{loading:t,tools:n,translate:s}=e,o=(0,i.useMemo)(()=>n?.filter(e=>e.active&&!e.declarationHidden)??null,[n]),[a,l]=(0,i.useState)(null);(0,i.useEffect)(()=>{l(e=>o?.some(t=>t.name===e)?e:o?.[0]?.name??null)},[o]);let c=o?.find(e=>e.name===a)??o?.[0]??null,d=c?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 fy(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(fy).join(", "):void 0,defaultValue:void 0===i.default?void 0:fy(i.default)}})}(c.parameters):[];return(0,r.jsxs)("div",{className:"tool-definitions-panel",children:[(0,r.jsx)("nav",{className:"tool-definitions-sidebar","aria-label":s("tools.title"),children:(0,r.jsx)("div",{className:"tool-definitions-list",children:o&&o.length>0?o.map(e=>{let t=e.name===c?.name;return(0,r.jsx)("button",{type:"button",className:`tool-definitions-item${t?" selected":""}`,"aria-pressed":t,onClick:()=>l(e.name),children:(0,r.jsx)("code",{children:e.name})},e.name)}):o?(0,r.jsx)(fj,{children:s("tools.noTools")}):(0,r.jsx)(fj,{children:t?s("tools.loading"):s("tools.load")})})}),(0,r.jsx)("section",{className:"tool-definition-detail","aria-label":s("tools.details"),children:c?(0,r.jsxs)("div",{className:"tool-definition-scroll",children:[c.description&&(0,r.jsxs)("section",{className:"tool-definition-section",children:[(0,r.jsx)("div",{className:"tool-definition-section-label",children:s("tools.description")}),(0,r.jsx)("div",{className:"tool-definition-description",children:c.description})]}),(0,r.jsxs)("section",{className:"tool-definition-section",children:[(0,r.jsxs)("div",{className:"tool-definition-section-label",children:[(0,r.jsx)("span",{children:s("tools.parameters")}),(0,r.jsx)("span",{children:s("tools.parameterCount",{count:d.length})})]}),d.length>0?(0,r.jsx)("div",{className:"tool-definition-fields",children:d.map(e=>(0,r.jsxs)("div",{className:"tool-definition-field",children:[(0,r.jsxs)("div",{className:"tool-definition-field-name",children:[(0,r.jsx)("code",{children:e.name}),(0,r.jsx)("span",{className:e.required?"required":void 0,children:s(e.required?"tools.required":"tools.optional")})]}),(0,r.jsxs)("div",{className:"tool-definition-field-value",children:[(0,r.jsx)("code",{className:"tool-definition-type",children:e.type}),e.description&&(0,r.jsx)("div",{children:e.description}),e.allowedValues&&(0,r.jsxs)("div",{className:"tool-definition-meta",children:[s("tools.allowedValues"),": ",(0,r.jsx)("code",{children:e.allowedValues})]}),void 0!==e.defaultValue&&(0,r.jsxs)("div",{className:"tool-definition-meta",children:[s("tools.defaultValue"),": ",(0,r.jsx)("code",{children:e.defaultValue})]})]})]},e.name))}):(0,r.jsx)("div",{className:"tool-definition-no-parameters",children:s("tools.noParameters")})]}),c.promptGuidelines&&c.promptGuidelines.length>0&&(0,r.jsxs)("section",{className:"tool-definition-section",children:[(0,r.jsx)("div",{className:"tool-definition-section-label",children:s("tools.guidelines")}),(0,r.jsx)("ul",{className:"tool-definition-guidelines",children:c.promptGuidelines.map((e,t)=>(0,r.jsx)("li",{children:e},`${c.name}:${t}`))})]})]}):(0,r.jsx)(fj,{children:o?s("tools.noTools"):t?s("tools.loading"):s("tools.load")})}),(0,r.jsx)("style",{children:`
40
- .tool-definitions-panel {
41
- display: grid;
42
- grid-template-columns: clamp(112px, 26%, 220px) minmax(0, 1fr);
43
- height: min(600px, 75dvh);
44
- min-height: 240px;
45
- overflow: hidden;
46
- background: var(--bg-panel);
47
- border-bottom: 1px solid var(--border);
48
- }
49
- .tool-definitions-sidebar,
50
- .tool-definition-detail {
51
- display: flex;
52
- min-width: 0;
53
- min-height: 0;
54
- flex-direction: column;
55
- }
56
- .tool-definitions-sidebar {
57
- border-right: 1px solid var(--border);
58
- background: color-mix(in srgb, var(--bg-panel) 94%, var(--bg));
59
- }
60
- .tool-definitions-list,
61
- .tool-definition-scroll {
62
- min-height: 0;
63
- flex: 1;
64
- overflow: auto;
65
- }
66
- .tool-definitions-item {
67
- display: flex;
68
- width: 100%;
69
- min-height: 38px;
70
- align-items: center;
71
- padding: 8px 12px;
72
- border: none;
73
- border-bottom: 1px solid var(--border);
74
- background: transparent;
75
- color: var(--text-muted);
76
- cursor: pointer;
77
- text-align: left;
78
- }
79
- .tool-definitions-item:hover {
80
- background: var(--bg-hover);
81
- color: var(--text);
82
- }
83
- .tool-definitions-item.selected {
84
- background: var(--bg-selected);
85
- box-shadow: inset 2px 0 0 var(--accent);
86
- color: var(--text);
87
- }
88
- .tool-definitions-item code {
89
- max-width: 100%;
90
- color: inherit;
91
- font-size: 11px;
92
- font-weight: 600;
93
- overflow-wrap: anywhere;
94
- }
95
- .tool-definition-scroll {
96
- padding: 14px 16px 20px;
97
- }
98
- .tool-definition-section + .tool-definition-section {
99
- margin-top: 18px;
100
- }
101
- .tool-definition-section-label {
102
- display: flex;
103
- align-items: center;
104
- justify-content: space-between;
105
- gap: 8px;
106
- margin-bottom: 7px;
107
- color: var(--text-dim);
108
- font-size: 11px;
109
- font-weight: 600;
110
- }
111
- .tool-definition-section-label > span:last-child {
112
- font-weight: 400;
113
- white-space: nowrap;
114
- }
115
- .tool-definition-description {
116
- color: var(--text-muted);
117
- font-size: 12px;
118
- line-height: 1.55;
119
- overflow-wrap: anywhere;
120
- white-space: pre-wrap;
121
- }
122
- .tool-definition-fields {
123
- border-top: 1px solid var(--border);
124
- }
125
- .tool-definition-field {
126
- display: grid;
127
- grid-template-columns: minmax(88px, 0.75fr) minmax(0, 1.5fr);
128
- gap: 12px;
129
- padding: 9px 0;
130
- border-bottom: 1px solid var(--border);
131
- font-size: 11px;
132
- line-height: 1.45;
133
- }
134
- .tool-definition-field-name {
135
- display: flex;
136
- min-width: 0;
137
- flex-direction: column;
138
- gap: 3px;
139
- color: var(--text);
140
- }
141
- .tool-definition-field-name code {
142
- overflow-wrap: anywhere;
143
- }
144
- .tool-definition-field-name span {
145
- color: var(--text-dim);
146
- font-size: 10px;
147
- }
148
- .tool-definition-field-name span.required {
149
- color: var(--accent);
150
- }
151
- .tool-definition-field-value {
152
- min-width: 0;
153
- color: var(--text-muted);
154
- overflow-wrap: anywhere;
155
- }
156
- .tool-definition-type {
157
- display: block;
158
- margin-bottom: 3px;
159
- color: var(--text);
160
- }
161
- .tool-definition-meta {
162
- margin-top: 4px;
163
- color: var(--text-dim);
164
- }
165
- .tool-definition-meta code {
166
- color: var(--text-muted);
167
- }
168
- .tool-definition-no-parameters {
169
- padding: 2px 0 10px;
170
- color: var(--text-dim);
171
- font-size: 11px;
172
- }
173
- .tool-definition-guidelines {
174
- margin: 0;
175
- padding-left: 18px;
176
- color: var(--text-muted);
177
- font-size: 11px;
178
- line-height: 1.5;
179
- }
180
- .tool-definitions-empty {
181
- padding: 14px 12px;
182
- color: var(--text-muted);
183
- font-size: 12px;
184
- font-style: italic;
185
- overflow-wrap: anywhere;
186
- }
187
- @media (max-width: 640px) {
188
- .tool-definitions-panel {
189
- grid-template-columns: 112px minmax(0, 1fr);
190
- }
191
- .tool-definitions-item {
192
- padding: 8px 10px;
193
- }
194
- .tool-definition-scroll {
195
- padding: 12px;
196
- }
197
- .tool-definition-field {
198
- grid-template-columns: minmax(74px, 0.7fr) minmax(0, 1.3fr);
199
- gap: 9px;
200
- }
201
- }
202
- `})]})}function fw(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e)}function fS(e){return e>0?e>=.01?`$${e.toFixed(2)}`:"<$0.01":null}function fC(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 fN(e){let{usage:t,style:n}=e,{locale:i,t:s}=(0,eO.s)(),o=fS(t.cost);return(0,r.jsxs)("span",{title:function(e,t,n){let{tokens:r}=e;return[`${t("session.totalActive")}: ${fC(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")}(t,s,i),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,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:3},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]}),fC(t.totalActiveMs)]}),t.tokens.total>0&&(0,r.jsx)("span",{children:s("agentSwitcher.tokens",{count:fw(t.tokens.total)})}),o&&(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:o})]})}function fE(e){return!!(e&&(e.tokens.total>0||e.totalActiveMs>0))}function fI(e){return e.name||e.firstMessage||e.id.slice(0,12)}function fT(e){return"running"===e||"starting"===e?"var(--accent)":"completed"===e?"#16a34a":"failed"===e?"#dc2626":"aborted"===e?"#d97706":"var(--text-dim)"}function f$(e){let{status:t}=e;return"running"===t||"starting"===t?(0,r.jsxs)("svg",{className:"animate-spin",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2",opacity:"0.25"}),(0,r.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):"failed"===t?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"m9 9 6 6M15 9l-6 6"})]}):"aborted"===t||"interrupted"===t?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M9 9h6v6H9z"})]}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"m8 12 3 3 5-6"})]})}function fM(e){let{session:t,main:n,selected:i,running:s,usage:o,onSelect:a,tabShown:l,onToggleTab:c}=e,{locale:d,t:u}=(0,eO.s)(),p=t.relation?.kind==="subagent"?t.relation:null,h=s?"running":p?.status??"completed",f=n?u("agentSwitcher.main"):p?.description||fI(t),m=n?fI(t):`${p?.profile??u("agentSwitcher.subagent")} \xb7 ${function(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 o=Math.round(s/60);return 24>Math.abs(o)?i.format(o,"hour"):i.format(Math.round(o/24),"day")}(t.modified,d)}`;return(0,r.jsxs)("div",{style:{display:"flex",borderBottom:"1px solid var(--border)",borderLeft:i?"2px solid var(--accent)":"2px solid transparent",background:i?"var(--bg-selected)":"transparent"},children:[(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":i,onClick:a,style:{flex:1,minWidth:0,minHeight:56,display:"grid",gridTemplateColumns:"28px minmax(0, 1fr) auto",alignItems:"center",gap:9,padding:"7px 12px",border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="transparent")},children:[(0,r.jsx)("span",{style:{width:28,height:28,display:"grid",placeItems:"center",color:n?"var(--text-muted)":"var(--accent)"},children:n?(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"8",r:"4"}),(0,r.jsx)("path",{d:"M4 21a8 8 0 0 1 16 0"})]}):(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]})}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12,fontWeight:i?600:500},title:f,children:f}),(0,r.jsx)("span",{style:{display:"block",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11},title:m,children:m}),fE(o)&&(0,r.jsx)(fN,{usage:o,style:{marginTop:3}})]}),(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",gap:6,color:n&&!s?"var(--text-dim)":fT(h),fontSize:11,whiteSpace:"nowrap"},children:n&&!s?i?u("agentSwitcher.current"):null:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(f$,{status:h}),(0,r.jsx)("span",{children:u(`agentSwitcher.status.${h}`)})]})})]}),c&&(0,r.jsx)("button",{type:"button",onClick:c,title:u(l?"subagent.closeTab":"subagent.openTab"),"aria-label":u(l?"subagent.closeTab":"subagent.openTab"),"aria-pressed":l,style:{width:36,display:"grid",placeItems:"center",border:"none",borderLeft:"1px solid var(--border)",background:"none",color:l?"var(--accent)":"var(--text-muted)",cursor:"pointer",flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",l||(e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background="none",l||(e.currentTarget.style.color="var(--text-muted)")},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),(0,r.jsx)("path",{d:"M15 4v16"}),l&&(0,r.jsx)("path",{d:"M15 4h4a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-4z",fill:"currentColor"})]})})]})}function fR(e){let{rootSession:t,subagents:n,selectedSessionId:s,runningSessionIds:o,onSelectSession:a,openSubagentTabIds:c,onToggleSubagentTab:d}=e,{t:u}=(0,eO.s)(),[p,h]=(0,i.useState)(""),f=(0,i.useMemo)(()=>[...n].sort((e,t)=>{let n=o.has(e.id);return n!==o.has(t.id)?n?-1:1:t.modified.localeCompare(e.modified)}),[o,n]),m=p.trim().toLowerCase(),g=m?f.filter(e=>{let t=e.relation?.kind==="subagent"?e.relation:null;return[t?.description,t?.profile,e.name,e.firstMessage].some(e=>e?.toLowerCase().includes(m))}):f,x=l(n,o),v=(0,i.useMemo)(()=>[t.id,...n.map(e=>e.id)],[t.id,n]),b=v.filter(e=>o.has(e)).join(","),y=function(e,t){let[n,r]=(0,i.useState)({}),s=e.join(",");return(0,i.useEffect)(()=>{let e=s?s.split(","):[];if(0===e.length)return;let n=new AbortController,i=!1,o=async()=>{if(!i){i=!0;try{let t=await fetch("/api/sessions/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:e}),signal:n.signal,cache:"no-store"});if(!t.ok)return;let i=await t.json();!n.signal.aborted&&i.stats&&r(i.stats)}catch{}finally{i=!1}}};if(o(),!t)return()=>n.abort();let a=setInterval(()=>{"visible"===document.visibilityState&&o()},3e3);return()=>{clearInterval(a),n.abort()}},[s,t]),n}(v,b),j=(0,i.useMemo)(()=>{let e=v.map(e=>y[e]).filter(fE);if(0===e.length)return null;let t={tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,toolCalls:0,totalActiveMs:0};for(let n of e)t.tokens.input+=n.tokens.input,t.tokens.output+=n.tokens.output,t.tokens.cacheRead+=n.tokens.cacheRead,t.tokens.cacheWrite+=n.tokens.cacheWrite,t.tokens.total+=n.tokens.total,t.cost+=n.cost,t.toolCalls+=n.toolCalls,t.totalActiveMs+=n.totalActiveMs;return t},[v,y]);return(0,r.jsx)("div",{role:"listbox","aria-label":u("agentSwitcher.title"),style:{background:"var(--bg-panel)",borderLeft:"1px solid var(--border)",borderRight:"1px solid var(--border)",borderBottom:"1px solid var(--border)",borderRadius:"0 0 6px 6px",boxShadow:"0 10px 28px rgba(0,0,0,0.10)",overflow:"hidden"},children:(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{minHeight:44,display:"flex",alignItems:"center",gap:8,padding:"7px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("strong",{style:{fontSize:12,fontWeight:600},children:u("agentSwitcher.title")}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:u("agentSwitcher.count",{count:n.length})}),(0,r.jsxs)("span",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:10,minWidth:0},children:[j&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0,overflow:"hidden"},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,whiteSpace:"nowrap"},title:u("agentSwitcher.totalUsageHint"),children:u("agentSwitcher.totalUsage")}),(0,r.jsx)(fN,{usage:j})]}),x>0&&(0,r.jsx)("span",{style:{color:"var(--accent)",fontSize:11,whiteSpace:"nowrap"},children:u("agentSwitcher.runningCount",{count:x})})]})]}),n.length>8&&(0,r.jsx)("div",{style:{padding:8,borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{type:"search",value:p,onChange:e=>h(e.target.value),placeholder:u("agentSwitcher.search"),"aria-label":u("agentSwitcher.search"),style:{width:"100%",height:32,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text)",fontSize:12,outline:"none"}})}),(0,r.jsxs)("div",{style:{maxHeight:"min(58dvh, 480px)",overflowY:"auto"},children:[(0,r.jsx)(fM,{session:t,main:!0,selected:t.id===s,running:o.has(t.id),usage:y[t.id],onSelect:()=>a(t)}),g.map(e=>(0,r.jsx)(fM,{session:e,selected:e.id===s,running:o.has(e.id),usage:y[e.id],onSelect:()=>a(e),tabShown:c.has(e.id),onToggleTab:()=>{let t=e.relation?.kind==="subagent"?e.relation:null;d(e.id,t?.description||t?.profile||fI(e))}},e.id)),0===g.length&&(0,r.jsx)("div",{style:{padding:"22px 12px",color:"var(--text-dim)",fontSize:12,textAlign:"center"},children:u("agentSwitcher.noMatches")})]})]})})}let fL={messages:[],entryIds:[],oldestEntryId:null,hasMore:!1};function fA(e,t){let n=new URLSearchParams({deferThinking:"1",deferMedia:"1",tail:String(100)});return t&&n.set("before",t),`/api/sessions/${encodeURIComponent(e)}/context?${n}`}function fP(e){return{messages:e.messages??[],entryIds:e.entryIds??[],oldestEntryId:e.oldestEntryId??null,hasMore:!!e.hasMore}}function fz(e){let{sessionId:t,fallbackLabel:n,running:s,onOpenFile:o}=e,{t:a,locale:l}=(0,eO.s)(),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(n),[h,f]=(0,i.useState)(fL),{messages:m,entryIds:g,oldestEntryId:x,hasMore:v}=h,b=(0,i.useRef)(h);b.current=h;let[y,j]=(0,i.useState)(!1),[k,w]=(0,i.useState)(!1),[S,C]=(0,i.useState)(null),[N,E]=(0,i.useState)(0);(0,i.useEffect)(()=>{let e=new AbortController;return(async()=>{try{let r=await fetch(`/api/sessions/${encodeURIComponent(t)}`,{signal:e.signal,cache:"no-store"});if(404===r.status)return;if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(!i.info)throw Error(i.error??`HTTP ${r.status}`);d(i.info),p(i.info.name||i.info.firstMessage||n)}catch{}})(),()=>e.abort()},[t,s,N,n]),(0,i.useEffect)(()=>{let e=new AbortController,n=!1,r=!1,i=async()=>{if(!r){r=!0;try{let r=await fetch(fA(t),{signal:e.signal,cache:"no-store"});if(404===r.status){n||w(!0);return}if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(n)return;w(!1),C(null),f(e=>{var t;let n,r,s;return t=fP(i.context),n=new Map,e.entryIds.forEach((t,r)=>n.set(t,e.messages[r])),r=t.messages.map((e,r)=>n.get(t.entryIds[r])??e),(s=t.hasMore&&t.entryIds.length?e.entryIds.indexOf(t.entryIds[0]):-1)<0?{...t,messages:r}:{messages:[...e.messages.slice(0,s),...r],entryIds:[...e.entryIds.slice(0,s),...t.entryIds],oldestEntryId:e.oldestEntryId,hasMore:e.hasMore}})}catch(e){n||e instanceof Error&&"AbortError"===e.name||C(e instanceof Error?e.message:String(e))}finally{r=!1}}};if(i(),!s)return()=>{n=!0,e.abort()};let o=setInterval(()=>{"visible"===document.visibilityState&&i()},2e3);return()=>{n=!0,clearInterval(o),e.abort()}},[t,s,N]);let I=(0,i.useRef)(null),T=(0,i.useRef)(!0),$=(0,i.useRef)(null),M=(0,i.useRef)(!1),R=(0,i.useRef)(null);(0,i.useEffect)(()=>()=>R.current?.abort(),[]);let L=(0,i.useCallback)(async()=>{if(!x||M.current)return;M.current=!0;let e=new AbortController;R.current=e,j(!0);try{let n=await fetch(fA(t,x),{signal:e.signal,cache:"no-store"});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(b.current.oldestEntryId!==x)return;let i=I.current;$.current=i?i.scrollHeight-i.scrollTop:null,f(e=>{var t;return t=fP(r.context),e.oldestEntryId!==x?e:{messages:[...t.messages,...e.messages],entryIds:[...t.entryIds,...e.entryIds],oldestEntryId:t.oldestEntryId,hasMore:t.hasMore}})}catch{}finally{M.current=!1,R.current===e&&(R.current=null),e.signal.aborted||j(!1)}},[x,t]),A=(0,i.useCallback)(()=>{let e=I.current;e&&(T.current=e.scrollHeight-e.scrollTop-e.clientHeight<60)},[]);(0,i.useLayoutEffect)(()=>{let e=I.current,t=$.current;$.current=null,e&&(null!==t?e.scrollTop=e.scrollHeight-t:T.current&&(e.scrollTop=e.scrollHeight))},[m]);let P=(0,i.useMemo)(()=>(function(e){let t=new Map;for(let n of e)"toolResult"===n.role&&t.set(n.toolCallId,n);return t})(m),[m]),z=c?.relation?.kind==="subagent"?c.relation:null,W=s?"running":z?.status??"completed";return(0,r.jsxs)("div",{style:{height:"100%",display:"flex",flexDirection:"column",minWidth:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",flexShrink:0,minHeight:36},children:[(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",color:"var(--accent)",flexShrink:0},"aria-hidden":"true",children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]})}),(0,r.jsx)("strong",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12,fontWeight:600},title:z?`${z.profile??a("agentSwitcher.subagent")} \xb7 ${u}`:u,children:u}),(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:5,color:fT(W),fontSize:11,whiteSpace:"nowrap",flexShrink:0},title:z?.description,children:[(0,r.jsx)(f$,{status:W}),(0,r.jsx)("span",{children:a(`agentSwitcher.status.${W}`)})]}),(0,r.jsx)("button",{type:"button",onClick:()=>E(e=>e+1),title:a("subagent.refresh"),"aria-label":a("subagent.refresh"),style:{display:"grid",placeItems:"center",width:24,height:24,flexShrink:0,background:"none",border:"none",borderRadius:4,color:"var(--text-dim)",cursor:"pointer",padding:0},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"}),(0,r.jsx)("path",{d:"M21 3v6h-6"})]})})]}),(0,r.jsx)("div",{ref:I,onScroll:A,style:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden",padding:"10px 0"},lang:l,children:k?(0,r.jsx)("div",{style:{padding:"24px 16px",color:"var(--text-muted)",fontSize:12,textAlign:"center"},children:a(s?"subagent.viewer.starting":"subagent.viewer.error")}):S&&0===m.length?(0,r.jsxs)("div",{role:"alert",style:{padding:"24px 16px",color:"#dc2626",fontSize:12,textAlign:"center"},children:[a("subagent.viewer.error"),(0,r.jsx)("div",{style:{marginTop:6,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:S})]}):(0,r.jsxs)(r.Fragment,{children:[v&&(0,r.jsx)("div",{style:{display:"flex",justifyContent:"center",padding:"4px 0 10px"},children:(0,r.jsx)("button",{type:"button",onClick:L,disabled:y,style:{fontSize:11,padding:"4px 12px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:y?"default":"pointer"},children:a("i18n.loadMore")})}),m.map((e,n)=>(0,r.jsx)("div",{style:{padding:"2px 12px"},children:(0,r.jsx)(rd.Dx,{message:e,toolResults:P,cwd:c?.cwd,onOpenFile:o,sessionId:t,entryId:g[n]})},g[n]??n)),0===m.length&&!S&&(0,r.jsx)("div",{style:{padding:"24px 16px",color:"var(--text-dim)",fontSize:12,textAlign:"center"},children:a("subagent.viewer.empty")})]})})]})}var fW=n(39641),fO=n(52281);let fD="pi-web:terminal-theme",fF="dark",fB={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"}};function fH(){try{var e;return e=window.localStorage.getItem(fD),"light"===e?"light":fF}catch{return fF}}let fU=null,f_=new Set;function fq(){return null===fU&&(fU=fH()),fU}function fK(){f_.forEach(e=>e())}function fV(e){if(null!==e.key&&e.key!==fD)return;let t=fH();t!==fU&&(fU=t,fK())}function fZ(e){return 0===f_.size&&(window.addEventListener("storage",fV),fU=fH()),f_.add(e),()=>{f_.delete(e),0===f_.size&&window.removeEventListener("storage",fV)}}async function fJ(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 fG={ctrl:!1,alt:!1},fY=[["Escape","/","-","Home","ArrowUp","End","PageUp"],["Tab","ctrl","alt","ArrowLeft","ArrowDown","ArrowRight","PageDown"]],fX=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","PageUp","PageDown"]),fQ={ArrowUp:"A",ArrowDown:"B",ArrowRight:"C",ArrowLeft:"D",Home:"H",End:"F"},f0={PageUp:5,PageDown:6};function f1(e){let{ctrl:t,alt:n}=e;return 1+2*!!n+4*!!t}function f2(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 f4={Escape:"ESC","/":"/","-":"-",Home:"HOME",ArrowUp:"↑",End:"END",PageUp:"PGUP",Tab:"TAB",ctrl:"CTRL",alt:"ALT",ArrowLeft:"↓",ArrowDown:"↓",ArrowRight:"↑",PageDown:"PGDN"},f8={ArrowUp:"Up",ArrowDown:"Down",ArrowLeft:"Left",ArrowRight:"Right",PageUp:"Page Up",PageDown:"Page Down"};function f5(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 f6=()=>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 f3(e){let{modifiers:t,onKey:n,onToggleModifier:s}=e,{t:o}=(0,eO.s)(),a=(0,i.useRef)(null),l=()=>{null!==a.current&&window.clearTimeout(a.current),a.current=null};return(0,i.useEffect)(()=>l,[]),(0,r.jsx)("div",{className:"terminal-extra-keys",role:"toolbar","aria-label":o("terminal.extraKeys"),children:fY.flat().map(e=>{let i="ctrl"===e||"alt"===e;return(0,r.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:f8[e],onPointerDown:t=>((e,t)=>{if(e.preventDefault(),0!==e.button)return;if(l(),"ctrl"===t||"alt"===t)return void s(t);if(n(t),!fX.has(t))return;let r=()=>{n(t),a.current=window.setTimeout(r,50)};a.current=window.setTimeout(r,400)})(t,e),onPointerUp:l,onPointerCancel:l,onPointerLeave:l,onMouseDown:e=>e.preventDefault(),onContextMenu:e=>e.preventDefault(),children:"ArrowLeft"===e||"ArrowRight"===e?(0,r.jsx)("span",{className:"is-rotated",children:f4[e]}):f4[e]},e)})})}function f9(e){let{tab:t,active:n,onRestart:s,onClosed:o,onCloseError:a}=e,{t:l}=(0,eO.s)(),{id:c,cwd:d,restored:u}=t,p=(0,i.useRef)(null),h=(0,i.useRef)(null),f=(0,i.useRef)(Promise.resolve()),m=(0,i.useRef)(null),g=(0,i.useRef)({onClosed:o,onCloseError:a});g.current={onClosed:o,onCloseError:a};let[x,v]=(0,i.useState)("connecting"),[b,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(null),[w,S]=(0,i.useState)(0),[C,N]=(0,i.useState)(fG),E=(0,i.useRef)(C),I=(0,i.useSyncExternalStore)(f5,f6,()=>!1),T=(0,i.useSyncExternalStore)(fZ,fq,()=>fF),$=(0,i.useRef)(T);$.current=T;let M=r_(rX().fontSize)-14+13,R=(0,i.useRef)(M);R.current=M;let L=(0,i.useRef)(()=>{}),A=(0,i.useCallback)(()=>{let e=E.current;return(e.ctrl||e.alt)&&(E.current=fG,N(fG)),e},[]);(0,i.useEffect)(()=>{var e;let t,n,r,i,s,o=p.current;if(!o)return;let a=!1,l=null,g=!1,x=!1,b=!1;v("connecting"),y(null),k(null);let j=()=>{let e=getComputedStyle(o);return{fontFamily:e.getPropertyValue("--font-mono").trim()||"monospace",fontWeight:r2(e.getPropertyValue("--font-mono-weight"))}},S=new fO.B({cursorBlink:!0,...j(),fontSize:R.current,lineHeight:1.25,scrollback:8e3,screenReaderMode:!0,disableStdin:!0,theme:fB[$.current]});h.current=S;let C=new fW.Y;S.loadAddon(C),S.open(o),S.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&&S.hasSelection())});let N=(e=e=>{a||(b=!0,S.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 fJ(`/api/terminal/${encodeURIComponent(c)}`,{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)});m.current=N;let E=S.onData(e=>{!g||x||b||N.write(f2(e,A()))}),I=()=>{o.offsetWidth&&o.offsetHeight&&C.fit()},T=S.onResize(e=>{let{cols:t,rows:n}=e;!g||x||b||N.resize(Math.max(2,t),Math.max(2,n))});L.current=I;let M=new ResizeObserver(I);M.observe(o);let P=is(()=>{if(a)return;let e=j();S.options.fontFamily=e.fontFamily,S.options.fontWeight=e.fontWeight,I()}),z=()=>{a||x||!navigator.onLine||(l?.close(),(l=new EventSource(`/api/terminal/${encodeURIComponent(c)}/events${void 0===t?"":`?after=${t}`}`)).onmessage=e=>{let n=JSON.parse(e.data);if("output"===n.type){if(n.reset)S.reset();else if(void 0!==t&&n.offset<=t)return;S.write(n.data),t=n.offset}else x=!0,g=!1,S.options.disableStdin=!0,l?.close(),k("exit"===n.type?n.exitCode:null),v("exited")},l.onopen=()=>{g=!0,!b&&(S.options.disableStdin=!1,v("ready"),I(),N.resize(Math.max(2,S.cols),Math.max(2,S.rows)),o.offsetWidth&&o.offsetHeight&&S.focus())},l.onerror=()=>{a||x||(g=!1,S.options.disableStdin=!0,v(l?.readyState===EventSource.CLOSED?"error":"connecting"))})};f.current=(async()=>{I(),u||w>0?await fJ(`/api/terminal/${encodeURIComponent(c)}`):await fJ("/api/terminal",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:c,cwd:d,cols:S.cols,rows:S.rows})}),z()})().catch(e=>{a||(y(e.message),v("error"))});let W=()=>{g=!1,S.options.disableStdin=!0,l?.close(),x||b||v("connecting")},O=e=>{e.persisted&&z()};return window.addEventListener("pagehide",W),window.addEventListener("pageshow",O),window.addEventListener("offline",W),window.addEventListener("online",z),()=>{a=!0,l?.close(),N.stop(),M.disconnect(),P(),E.dispose(),T.dispose(),window.removeEventListener("pagehide",W),window.removeEventListener("pageshow",O),window.removeEventListener("offline",W),window.removeEventListener("online",z),S.dispose(),h.current=null,L.current=()=>{}}},[c,d,u,w,A]),(0,i.useEffect)(()=>{h.current&&(h.current.options.theme=fB[T])},[T]),(0,i.useEffect)(()=>{let e=h.current;e&&e.options.fontSize!==M&&(e.options.fontSize=M,L.current())},[M]),(0,i.useEffect)(()=>{n&&h.current?.focus()},[n]),(0,i.useEffect)(()=>{if(!t.closing)return;let e=!1;return h.current&&(h.current.options.disableStdin=!0),(async()=>{await f.current,await m.current?.stop(),await fJ(`/api/terminal/${encodeURIComponent(c)}`,{method:"DELETE",keepalive:!0}),e||g.current.onClosed()})().catch(t=>{e||(y(t.message),v("error"),g.current.onCloseError())}),()=>{e=!0}},[c,t.closing]);let P="dark"===T?"light":"dark",z="light"===P?"terminal.lightTheme":"terminal.darkTheme";return(0,r.jsxs)("section",{className:"terminal-panel","data-terminal-theme":T,"aria-label":l("terminal.title"),children:[(0,r.jsxs)("header",{className:"terminal-panel-header",children:[(0,r.jsxs)("div",{className:"terminal-panel-path",children:[(0,r.jsx)("span",{className:`terminal-status-dot is-${x}`,title:l(`terminal.${x}`)}),(0,r.jsx)("span",{title:d,children:d})]}),(0,r.jsxs)("div",{className:"terminal-panel-actions",children:["error"===x&&(0,r.jsx)("button",{type:"button",onClick:()=>S(e=>e+1),disabled:!!t.closing,title:l("terminal.reconnect"),"aria-label":l("terminal.reconnect"),children:(0,r.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,r.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,r.jsx)("button",{type:"button",onClick:()=>(function(e){if(e!==fq()){fU=e;try{window.localStorage.setItem(fD,e)}catch{}fK()}})(P),title:l(z),"aria-label":l(z),children:"light"===P?(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.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,r.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,r.jsx)("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}),(0,r.jsx)("button",{type:"button",onClick:s,disabled:!!t.closing,title:l("terminal.restart"),"aria-label":l("terminal.restart"),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M20 11a8 8 0 1 0-2.34 5.66"}),(0,r.jsx)("polyline",{points:"20 4 20 11 13 11"})]})})]})]}),(0,r.jsxs)("div",{children:[b&&(0,r.jsx)("div",{className:"terminal-panel-error",role:"alert",children:b}),"exited"===x&&(0,r.jsx)("div",{className:"terminal-panel-exit",role:"status",children:null===j?l("terminal.exited"):l("terminal.exitCode",{code:j})})]}),(0,r.jsx)("div",{className:"terminal-xterm",children:(0,r.jsx)("div",{ref:p,className:"terminal-xterm-host"})}),I&&(0,r.jsx)(f3,{modifiers:C,onKey:e=>{let t=h.current;if(!t)return;let n=function(e,t,n){let r=t.ctrl||t.alt,i=fQ[e];if(i)return r?`\x1b[1;${f1(t)}${i}`:n?`\x1bO${i}`:`\x1b[${i}`;let s=f0[e];return s?r?`\x1b[${s};${f1(t)}~`:`\x1b[${s}~`:"Escape"===e?t.alt?"\x1b\x1b":"\x1b":"Tab"===e?t.alt?"\x1b ":" ":f2(e,t)}(e,A(),t.modes.applicationCursorKeysMode);t.input(n,!0)},onToggleModifier:e=>{let t={...E.current,[e]:!E.current[e]};E.current=t,N(t)}})]})}class f7{constructor(e,t){this.parents=[],this.nextParentIndex=0,this.laneIndex=null,this.branch=null,this.nextLaneIndex=0,this.connections=[],this.rowIndex=e,this.hash=t}nextParent(){return this.nextParentIndex<this.parents.length?this.parents[this.nextParentIndex]:null}markParentProcessed(){this.nextParentIndex++}isMerge(){return this.parents.length>1}isOnBranch(){return null!==this.branch&&null!==this.laneIndex}getBranch(){return this.branch}joinBranch(e,t){null===this.branch&&(this.branch=e,this.laneIndex=t)}getLaneIndex(){return this.laneIndex??0}point(){return{laneIndex:this.getLaneIndex(),rowIndex:this.rowIndex}}nextPoint(){return{laneIndex:this.nextLaneIndex,rowIndex:this.rowIndex}}connectionTo(e,t){let n=this.connections.findIndex(n=>n?.target===e&&n.branch===t);return n>=0?{laneIndex:n,rowIndex:this.rowIndex}:null}reservePoint(e,t,n){e===this.nextLaneIndex&&(this.connections[e]={target:t,branch:n},this.nextLaneIndex=e+1)}widestLaneIndex(){return this.nextLaneIndex-1}}class me{constructor(e){this.endRowIndex=0,this.lines=[],this.colorIndex=e}addLine(e,t,n,r,i){this.lines.push({from:e,to:t,sourceHash:n,targetHash:r,lockedFirst:i})}}let mt=new f7(-1,"__missing_parent__"),mn=["#4f8cff","#f59e0b","#10b981","#ef4444","#a855f7","#d9a814"];function mr(e){return e.slice(0,7)}function mi(e){let{cwd:t,refreshKey:n=0}=e,{t:s,locale:o}=(0,eO.s)(),[a,l]=(0,i.useState)({commits:[],hasMore:!1}),[c,d]=(0,i.useState)(!0),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(null),j=(0,i.useRef)(!1),k=(0,i.useRef)(0),w=(0,i.useCallback)(async e=>{let n=new URLSearchParams({cwd:t,skip:String(e),maxCount:String(50)}),r=++k.current,i=await fetch(`/api/git/graph?${n.toString()}`);if(!i.ok){let e=await i.json().catch(()=>null);throw Error(e?.error??`HTTP ${i.status}`)}let s=await i.json();return r===k.current?s:null},[t]);(0,i.useEffect)(()=>{let e=!1;return(async()=>{d(!0),g(null);try{let t=await w(0);!e&&t&&(l(t),v(t.commits[0]?.hash??null))}catch(t){e||g(t instanceof Error?t.message:String(t))}finally{e||d(!1)}})(),()=>{e=!0}},[w,n]);let S=(0,i.useCallback)(async()=>{f(!0),g(null);try{let e=await w(0);e&&(l(e),v(e.commits[0]?.hash??null))}catch(e){g(e instanceof Error?e.message:String(e))}finally{f(!1)}},[w]),C=(0,i.useCallback)(async()=>{if(!j.current&&a.hasMore){j.current=!0,p(!0),g(null);try{let e=await w(a.commits.length);e&&l(t=>({commits:[...t.commits,...e.commits],hasMore:e.hasMore}))}catch(e){g(e instanceof Error?e.message:String(e))}finally{j.current=!1,p(!1)}}},[w,a.commits.length,a.hasMore]),N=(0,i.useMemo)(()=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.rowHeight??42,r=t.laneGap??18,i=t.lanePadding??16,s=t.topPadding??20,o=t.bottomPadding??18,a=function(e){let t=e.map((e,t)=>new f7(t,e.hash)),n=new Map(t.map(e=>[e.hash,e]));for(let r=0;r<e.length;r++)for(let i of e[r].parents)t[r].parents.push(n.get(i)??mt);return t}(e),l=[],c=[];for(let e=0;e<a.length;){let t=a[e],n=t.nextParent();if(null===n&&t.isOnBranch()){e++;continue}if(n===mt){t.markParentProcessed();continue}null!==n&&t.isMerge()&&t.isOnBranch()&&n.isOnBranch()?function(e,t,n){let r=t.getBranch();if(!r)return e.markParentProcessed();let i=e.point();for(let s=e.rowIndex+1;s<n.length;s++){let o=n[s],a=o.connectionTo(t,r),l=null!==a,c=a??o.nextPoint();if(r.addLine(i,c,e.hash,t.hash,l||i.laneIndex<c.laneIndex),o.reservePoint(c.laneIndex,t,r),i=c,l){e.markParentProcessed();break}}}(t,n,a):function(e,t,n,r){let i,s=t[e],o=s.nextParent(),a=s.isOnBranch()?s.point():s.nextPoint(),l=new me((i=r.findIndex(t=>t<e))>=0?i:(r.push(0),r.length-1));s.joinBranch(l,a.laneIndex),s.reservePoint(a.laneIndex,s,l);let c=e+1;for(;c<t.length&&null!==o&&o!==mt;c++){let e=t[c],n=o===e&&e.isOnBranch()?e.point():e.nextPoint();if(l.addLine(a,n,s.hash,o.hash,a.laneIndex<n.laneIndex),e.reservePoint(n.laneIndex,o,l),a=n,o===e){s.markParentProcessed();let t=e.isOnBranch();if(e.joinBranch(l,n.laneIndex),(o=(s=e).nextParent())===mt){s.markParentProcessed();break}if(null===o||t)break}}l.endRowIndex=Math.min(c,t.length),n.push(l),r[l.colorIndex]=l.endRowIndex}(e,a,l,c)}let d=e=>i+e*r,u=e=>s+e*n,p=a.map((t,n)=>({commit:e[n],rowIndex:n,laneIndex:t.getLaneIndex(),x:d(t.getLaneIndex()),y:u(n)})),h=[],f=-1;for(let e of p)f=Math.max(f,e.laneIndex);for(let e of a)f=Math.max(f,e.widestLaneIndex());for(let e of l)for(let t of e.lines)f=Math.max(f,t.from.laneIndex,t.to.laneIndex),h.push({id:`${t.sourceHash}:${t.targetHash}:${t.from.rowIndex}:${t.to.rowIndex}:${h.length}`,d:function(e,t,n,r,i){if(e===n)return`M ${e} ${t} L ${n} ${r}`;let s=Math.max(14,.38*Math.abs(r-t));return i?`M ${e} ${t} C ${e} ${t+s}, ${n} ${t+s}, ${n} ${r}`:`M ${e} ${t} C ${e} ${r-s}, ${n} ${r-s}, ${n} ${r}`}(d(t.from.laneIndex),u(t.from.rowIndex),d(t.to.laneIndex),u(t.to.rowIndex),t.lockedFirst),colorIndex:e.colorIndex,relatedHashes:t.sourceHash===t.targetHash?[t.sourceHash]:[t.sourceHash,t.targetHash]});let m=Math.max(1,f+1);return{rows:p,paths:h,laneCount:m,width:2*i+(m-1)*r,height:s+Math.max(0,e.length-1)*n+o,rowHeight:n,laneGap:r,lanePadding:i}})(a.commits),[a.commits]),E=(0,i.useMemo)(()=>new Intl.DateTimeFormat(o,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}),[o]),I=(0,i.useMemo)(()=>a.commits.find(e=>e.hash===x)??null,[a.commits,x]),T=Math.max(N.width+12,56),$=`${T}px minmax(160px, 1fr) 110px 100px 78px`,M=(0,i.useCallback)(e=>{let t=e.currentTarget;t.scrollHeight-t.scrollTop-t.clientHeight<=96&&C()},[C]);return c?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12},children:s("gitGraph.loading")}):(0,r.jsxs)("section",{style:{height:"100%",display:"flex",flexDirection:"column",background:"var(--bg)",minWidth:0},children:[(0,r.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontSize:12,fontWeight:500,color:"var(--text)"},children:s("gitGraph.title")}),a.commits.length>0&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s(a.hasMore?"gitGraph.subtitlePartial":"gitGraph.subtitle",{count:a.commits.length,lanes:N.laneCount})}),(0,r.jsx)("span",{style:{flex:1}}),(0,r.jsx)("button",{type:"button",onClick:()=>{S()},disabled:h,title:s("gitGraph.refresh"),"aria-label":s("gitGraph.refresh"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,border:"none",borderRadius:4,background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"}),(0,r.jsx)("polyline",{points:"21 3 21 9 15 9"})]})})]}),m&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 10px",fontSize:11,color:"var(--text)",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:s("gitGraph.errorLoad",{error:m})}),0===a.commits.length?(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:4,color:"var(--text-dim)",padding:16},children:[(0,r.jsx)("span",{style:{fontSize:13},children:s("gitGraph.emptyTitle")}),(0,r.jsx)("span",{style:{fontSize:11},children:s("gitGraph.emptyDescription")})]}):(0,r.jsxs)("div",{className:"scrollbar-subtle",onScroll:M,style:{flex:1,minHeight:0,overflowY:"auto",position:"relative"},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:0,zIndex:2,display:"grid",gridTemplateColumns:$,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",fontSize:10,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},"aria-hidden":"true",children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{style:{padding:"4px 8px",overflow:"hidden",textOverflow:"ellipsis"},children:s("gitGraph.columnDescription")}),(0,r.jsx)("span",{style:{padding:"4px 8px"},children:s("gitGraph.columnDate")}),(0,r.jsx)("span",{style:{padding:"4px 8px"},children:s("gitGraph.columnAuthor")}),(0,r.jsx)("span",{style:{padding:"4px 8px"},children:s("gitGraph.columnCommit")})]}),(0,r.jsxs)("div",{style:{position:"relative"},children:[(0,r.jsxs)("svg",{width:T,height:N.height+N.rowHeight,viewBox:`0 0 ${T} ${N.height+N.rowHeight}`,"aria-label":s("gitGraph.graphAriaLabel"),role:"img",style:{position:"absolute",left:0,top:0,overflow:"visible",pointerEvents:"none"},children:[N.paths.map(e=>{let t=null!==b&&e.relatedHashes.includes(b),n=null!==b&&!t;return(0,r.jsx)("path",{d:e.d,fill:"none",stroke:mn[e.colorIndex%mn.length],strokeWidth:2,opacity:n?.25:t?1:.6},e.id)}),N.rows.map(e=>{let t=e.commit.hash===x,n=mn[e.laneIndex%mn.length];return(0,r.jsxs)("g",{children:[(0,r.jsx)("circle",{cx:e.x,cy:e.y,r:t?5:4,fill:n,stroke:"var(--bg)",strokeWidth:2}),t&&(0,r.jsx)("circle",{cx:e.x,cy:e.y,r:7.5,fill:"none",stroke:n,strokeWidth:1,opacity:.85})]},e.commit.hash)})]}),N.rows.map(e=>{let t=e.commit,n=t.hash===x;return(0,r.jsxs)("button",{type:"button",onClick:()=>{v(e=>e===t.hash?null:t.hash)},onMouseEnter:()=>y(t.hash),onMouseLeave:()=>y(null),"aria-label":`${mr(t.hash)} ${t.subject}`,style:{display:"grid",gridTemplateColumns:$,alignItems:"center",width:"100%",height:N.rowHeight,textAlign:"left",fontSize:12,background:n?"var(--bg-selected)":"transparent",border:"none",borderTop:n?"1px solid var(--border)":"none",borderBottom:n?"1px solid var(--border)":"none",cursor:"pointer",padding:0,color:"var(--text)"},children:[(0,r.jsx)("span",{"aria-hidden":"true"}),(0,r.jsxs)("span",{style:{minWidth:0,display:"flex",alignItems:"center",gap:6,padding:"0 8px"},children:[t.refs.length>0&&(0,r.jsx)("span",{style:{display:"inline-flex",gap:3,flexShrink:0,maxWidth:180,overflow:"hidden"},children:t.refs.slice(0,3).map(e=>(0,r.jsx)(ms,{gitRef:e},`${t.hash}:${e.kind}:${e.name}`))}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:t.subject||mr(t.hash)}),t.parents.length>1&&(0,r.jsx)(mo,{})]}),(0,r.jsx)("span",{style:{padding:"0 8px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-muted)",fontSize:11},children:t.authoredAtMs?E.format(new Date(t.authoredAtMs)):""}),(0,r.jsx)("span",{style:{padding:"0 8px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-muted)"},children:t.authorName??""}),(0,r.jsx)("span",{style:{padding:"0 8px",fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-muted)"},children:mr(t.hash)})]},t.hash)})]}),a.hasMore&&(0,r.jsx)("div",{style:{display:"flex",justifyContent:"center",padding:10},children:(0,r.jsx)("button",{type:"button",onClick:()=>{C()},disabled:u,style:{fontSize:12,padding:"5px 14px",borderRadius:6,cursor:"pointer",border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)"},children:s(u?"gitGraph.loadingMore":"gitGraph.loadMore")})})]}),I&&(0,r.jsxs)("footer",{style:{flexShrink:0,borderTop:"1px solid var(--border)",background:"var(--bg-panel)",padding:"8px 10px",display:"grid",gap:4,fontSize:11,color:"var(--text-muted)",gridTemplateColumns:"minmax(0, 1.4fr) minmax(0, 1fr)"},children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{marginBottom:2,fontSize:10,textTransform:"uppercase",letterSpacing:.4,color:"var(--text-dim)"},children:s("gitGraph.detailSubject")}),(0,r.jsx)("div",{style:{color:"var(--text)",overflowWrap:"anywhere"},children:I.subject||mr(I.hash)}),I.refs.length>0&&(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:3,marginTop:4},children:I.refs.map(e=>(0,r.jsx)(ms,{gitRef:e},`${I.hash}:detail:${e.kind}:${e.name}`))})]}),(0,r.jsxs)("div",{style:{display:"grid",gap:2,minWidth:0},children:[(0,r.jsxs)("span",{children:[s("gitGraph.detailCommit"),": ",(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",color:"var(--text)"},children:mr(I.hash)})]}),(0,r.jsxs)("span",{children:[s("gitGraph.detailAuthor"),": ",(0,r.jsx)("span",{style:{color:"var(--text)"},children:I.authorName??"—"})]}),(0,r.jsxs)("span",{children:[s("gitGraph.detailDate"),":"," ",(0,r.jsx)("span",{style:{color:"var(--text)"},children:I.authoredAtMs?new Intl.DateTimeFormat(o,{dateStyle:"medium",timeStyle:"short"}).format(new Date(I.authoredAtMs)):"—"})]}),(0,r.jsxs)("span",{style:{overflowWrap:"anywhere"},children:[s("gitGraph.detailParents"),":"," ",(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",color:"var(--text)"},children:I.parents.length>0?I.parents.map(mr).join(", "):"—"})]})]})]})]})}function ms(e){let{gitRef:t}=e,n="head"===t.kind,i="tag"===t.kind;return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",height:16,padding:"0 5px",borderRadius:4,border:`1px solid ${n?"var(--accent)":"var(--border)"}`,background:n?"var(--bg-selected)":i?"var(--bg-hover)":"transparent",color:n?"var(--text)":"var(--text-muted)",fontSize:10,maxWidth:130,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:0},children:[n?"● ":"",t.name]})}function mo(){return(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,color:"var(--text-dim)"},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"18",cy:"18",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"6",r:"3"}),(0,r.jsx)("path",{d:"M6 9v2a4 4 0 0 0 4 4h5"})]})}let ma="pi-web:terminal-tabs";function ml(e){return{id:Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join(""),cwd:e}}function mc(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let md=[48,120,240,420,720];function mu(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document;return"visible"!==e.visibilityState||!e.hasFocus()}async function mp(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}}),"service-worker"}catch{}try{let r=t.createWindowNotification(e.title,n);return r.onclick=()=>{r.close(),e.onClick()},"window"}catch{return null}}let mh="pi-web:tab-open-session";function mf(){try{return window.sessionStorage}catch{return null}}function mm(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 mg(e,t){t.setItem(mh,JSON.stringify(e))}let mx=new Set(sf.kU);function mv(e){return`parked-new:${e}`}function mb(e){let t=e.at(-1);return t?`agent:${t.sessionId}`:null}function my(){var e;let t,n,c,m,g,x,v,b,y,j,k,w,S,C=(0,s.useRouter)(),N=(0,s.useSearchParams)(),[E,I]=(0,i.useState)(()=>{let e;return{requestedCwd:e=N.get("cwd")?.trim()||null,sessionId:e?null:N.get("session")||null,sidebarCollapsed:"collapsed"===N.get("sidebar")}});(0,or.D)(),id();let{locale:T,t:$}=(0,eO.s)(),M=(0,eD.a)(),R=(0,eD.n)();(0,i.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:mc(),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)},o=()=>{null!==n&&window.cancelAnimationFrame(n),n=window.requestAnimationFrame(s),(()=>{if(i)return;i=!0;let e=0,t=()=>{if(e>=md.length){i=!1;return}let n=md[e++],o=window.setTimeout(()=>{r.delete(o),s(),t()},n);r.add(o)};t()})()},a=()=>{mc()&&o()};return o(),e.addEventListener("resize",o),e.addEventListener("scroll",o),window.addEventListener("resize",o),window.addEventListener("focusin",o),window.addEventListener("focusout",o),window.addEventListener("pageshow",o),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",o),e.removeEventListener("scroll",o),window.removeEventListener("resize",o),window.removeEventListener("focusin",o),window.removeEventListener("focusout",o),window.removeEventListener("pageshow",o),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,i.useEffect)(()=>{"Notification"in window&&"granted"===Notification.permission&&lv(T)},[T]);let{soundEnabled:L,onSoundToggle:A,playDoneSound:P,unlockAudio:z,holdAudio:W,soundEnabledRef:O}=function(){let[e,t]=(0,i.useState)(()=>{try{let e=localStorage.getItem("pi-sound-enabled");return null===e||"true"===e}catch{return!0}}),n=(0,i.useRef)(e);(0,i.useEffect)(()=>{n.current=e},[e]);let r=(0,i.useRef)(null),s=(0,i.useCallback)(()=>{if(r.current&&"closed"!==r.current.state)return r.current;try{r.current=new AudioContext}catch{return null}return r.current},[]),o=(0,i.useRef)(0),a=(0,i.useRef)(0),l=(0,i.useRef)(void 0),c=(0,i.useCallback)(e=>{clearTimeout(l.current),l.current=setTimeout(()=>{0===o.current&&0===a.current&&e.suspend().catch(()=>{})},1e3)},[]),d=(0,i.useCallback)((e,t)=>{o.current++,e.resume().then(t).catch(()=>{}).then(()=>{o.current--,c(e)})},[c]),u=(0,i.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!e&&!n.current)return;let t=s();t&&"running"!==t.state&&d(t,()=>{})},[s,d]),p=(0,i.useCallback)(()=>{let e=!n.current;e?u(!0):r.current?.suspend().catch(()=>{}),n.current=e;try{localStorage.setItem("pi-sound-enabled",String(e))}catch{}t(e)},[u]),h=(0,i.useCallback)(()=>{if(a.current++,clearTimeout(l.current),n.current){let e=s();e&&"running"!==e.state&&d(e,()=>{})}let e=!1;return()=>{!e&&(e=!0,a.current--,r.current&&c(r.current))}},[s,d,c]);return{soundEnabled:e,onSoundToggle:p,playDoneSound:(0,i.useCallback)(()=>{if(!n.current)return;let e=s();if(!e)return;let t=Date.now();d(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 o=t+.18*r;s.gain.setValueAtTime(0,o),s.gain.linearRampToValueAtTime(.18,o+.02),s.gain.exponentialRampToValueAtTime(.001,o+.45),i.start(o),i.stop(o+.45)})}catch{}})},[s,d]),unlockAudio:u,holdAudio:h,soundEnabledRef:n}}(),[D,F]=(0,i.useState)(!1);(0,i.useEffect)(()=>{try{F("true"===localStorage.getItem("pi-quote-selection-enabled"))}catch{}},[]);let B=(0,i.useCallback)(e=>{F(e);try{localStorage.setItem("pi-quote-selection-enabled",String(e))}catch{}},[]),H=(0,i.useRef)(new Set),U=(0,i.useCallback)(()=>{O.current&&P()},[P,O]),[_,q]=(0,i.useState)(null),K=(0,i.useRef)(_);K.current=_;let[V,Z]=(0,i.useState)([]),J=(0,i.useCallback)(e=>{Z(e),q(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})},[]),G=(0,i.useMemo)(()=>_?[...V.filter(e=>e.id!==_.id),_]:V,[_,V]),Y=(0,i.useMemo)(()=>{var e;return(e=_?.id)?a(G).find(t=>t.root.id===e||t.subagents.some(t=>t.id===e))??null:null},[_?.id,G]),X=!!Y?.subagents.length,[Q,ee]=(0,i.useState)(()=>new Set),et=(0,i.useCallback)(e=>{ee(t=>t.size===e.size&&[...e].every(e=>t.has(e))?t:e)},[]),en=Y?(t=l(e=Y.subagents,Q))>0?{count:t,running:!0}:{count:e.length,running:!1}:null,er=en?.running?$("agentSwitcher.titleRunning",{count:en.count}):$("agentSwitcher.title"),[ei,es]=(0,i.useState)(null),[eo,ea]=(0,i.useState)("initial"),el=(0,i.useRef)(null),ec=(0,i.useRef)(null),[ed,eu]=(0,i.useState)(null),ep=(0,i.useRef)(null),eh=(0,i.useCallback)(e=>{e&&e.cwd===ep.current?.cwd&&(ep.current=null),eu(e)},[]),ef=(0,i.useRef)(null),em=(0,i.useRef)(null),[eg,ex]=(0,i.useState)(null),ev=(0,i.useCallback)(e=>{em.current=e,ex(null)},[]),[eb,ey]=(0,i.useState)(()=>E.requestedCwd?"validating":"idle"),[ej,ek]=(0,i.useState)(null),[ew,eS]=(0,i.useState)(0),[eC,eN]=(0,i.useState)(0),eE=(0,i.useRef)(new Map),eI=(0,i.useCallback)((e,t)=>{eE.current.set(e,t)},[]),[eT,e$]=(0,i.useState)(null),eM=(0,i.useCallback)(e=>{e$(t=>t===e?null:t)},[]),[eR,eL]=(0,i.useState)(0),[eA,eP]=(0,i.useState)(null),[ez,eW]=(0,i.useState)(0),[eB,eU]=(0,i.useState)(null),[e_,eq]=(0,i.useState)(!1),[eK,eV]=(0,i.useState)(!1),[eZ,eJ]=(0,i.useState)(null),[eG,eY]=(0,i.useState)(()=>!E.sidebarCollapsed),eX=(0,i.useRef)(!E.sidebarCollapsed),[eQ,e0]=(0,i.useState)(!1),[e1,e2]=(0,i.useState)(!1),e4=eQ&&e1&&!M;(0,i.useEffect)(()=>{(!eQ||M)&&e2(!1)},[eQ,M]);let[e8,e5]=(0,i.useState)(!1),[e6,e3]=(0,i.useState)(!1),e7=(0,i.useRef)(260),te=(0,i.useRef)(560),tt=(0,i.useCallback)(()=>eF(.42*window.innerWidth,360,640),[]),tr=(0,i.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,rightPanelOpen:eQ,rightPanelWidth:te.current}),[eQ]),ti=(0,i.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,sidebarOpen:eG,sidebarWidth:e7.current}),[eG]),ts=eH({ariaLabel:$("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:tr,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"pi-sidebar-width",widthRef:e7}),to=eH({ariaLabel:$("layout.resizeFilePanel"),cssVariable:"--right-panel-width",defaultWidth:560,getDefaultWidth:tt,getMaxWidth:ti,growthDirection:"left",maxWidth:1200,minWidth:300,storageKey:"pi-right-panel-width",widthRef:te}),ta=ts.reclampWidth,tl=to.reclampWidth;(0,i.useEffect)(()=>{eY(!M&&eX.current)},[M]),(0,i.useEffect)(()=>{e3(!0)},[]),(0,i.useEffect)(()=>{eQ&&(ta(),tl())},[tl,ta,eQ]);let tc=(0,i.useRef)(null),[td,tu]=(0,i.useState)(null),tp=(0,i.useRef)(null),th=(0,i.useRef)(null),[tf,tm]=(0,i.useState)([]),[tg,tx]=(0,i.useState)(null),[tv,tb]=(0,i.useState)(!1),tj=(0,i.useRef)(null),tk=fg(tf),tw=(0,i.useCallback)((e,t,n,r)=>{tm(e),tx(t),tb(r),tj.current=n},[]),tS=(0,i.useCallback)(e=>{tj.current?.(e)},[]),[tC,tN]=(0,i.useState)(null),[tE,tI]=(0,i.useState)(null),[tT,t$]=(0,i.useState)(!1),tM=(0,i.useRef)(null),tR=(0,i.useRef)(0),tL=(0,i.useRef)(null),tA=(0,i.useCallback)(e=>{tN(e),t$(!1)},[]),tP=(0,i.useCallback)(e=>{tI(e)},[]),tz=(0,i.useCallback)(e=>{tR.current+=1,tM.current=e,t$(!1)},[]),[tW,tO]=(0,i.useState)(null),[tD,tF]=(0,i.useState)({kind:"idle"}),tB=(0,i.useRef)(null),tH=(0,i.useRef)(_?.id??null);tH.current=_?.id??null;let tU=(0,i.useCallback)(e=>{tO(e)},[]),[t_,tq]=(0,i.useState)(null),tK=(0,i.useRef)(null),tV=(0,i.useCallback)((e,t)=>{(0,ty.D)(t).then(()=>{tK.current&&clearTimeout(tK.current),tq(e),tK.current=setTimeout(()=>tq(null),1400)})},[]);(0,i.useEffect)(()=>()=>{tK.current&&clearTimeout(tK.current),tB.current&&clearTimeout(tB.current)},[]);let[tZ,tJ]=(0,i.useState)(null),tG=(0,i.useCallback)(e=>{tJ(e)},[]),[tY,tX]=(0,i.useState)(null),[tQ,t0]=(0,i.useState)(null);(0,i.useEffect)(()=>{tk||tX(e=>"branches"===e?null:e)},[tk]),(0,i.useEffect)(()=>{X||tX(e=>"agents"===e?null:e)},[X]),(0,i.useEffect)(()=>{e4&&tX(null)},[e4]);let t1=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];M&&eY(!1),tX(t=>t===e?null:e),M&&R&&t&&e5(!0)},[M,R]),t2=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=tY!==e;if(t1(e,t),!n||tT)return;let r=tM.current;if(!r)return;let i=++tR.current;t$(!0),r().catch(e=>{console.error("Failed to load system information:",e)}).finally(()=>{tR.current===i&&t$(!1)})},[tY,tT,t1]),t4=(0,i.useCallback)(()=>{M&&eY(!1),e5(!1),tX("session")},[M]),t8=(0,i.useCallback)(e=>{eP(e)},[]),t5=(0,i.useCallback)(()=>{M&&(tX(null),e5(!1)),eY(e=>{let t=!e;return M||(eX.current=t),t})},[M]),t6=(0,i.useCallback)(()=>{eY(!1),tX(null),e5(e=>!e)},[]),t3=(0,i.useCallback)(()=>{M&&(eY(!1),tX(null),e5(!1)),e0(e=>!e)},[M]),t9=(0,i.useCallback)(()=>{tX(null),e2(e=>!e)},[]);(0,i.useEffect)(()=>{if(!e8)return;let e=e=>{let t=th.current;t&&e.composedPath().includes(t)||e5(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),e5(!1))};return document.addEventListener("pointerdown",e,!0),document.addEventListener("keydown",t,!0),()=>{document.removeEventListener("pointerdown",e,!0),document.removeEventListener("keydown",t,!0)}},[e8]),(0,i.useEffect)(()=>{e5(!1)},[M,R,_?.id,eo]),(0,i.useEffect)(()=>{if(!tY||!tp.current)return;let e=()=>{let e=tp.current.getBoundingClientRect();"agents"===tY?t0({top:e.bottom,left:e.left,width:Math.min(420,e.width)}):t0({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(tp.current),()=>t.disconnect()},[tY,M]);let[t7,ne]=(0,i.useState)([]),[nt,nn]=(0,i.useState)(null),nr=(0,i.useRef)(new Map),[ni,ns]=(0,i.useState)(0),no=(0,i.useRef)(0),[na,nl]=(0,i.useState)([]),[nc,nd]=(0,i.useState)([]),[nu,np]=(0,i.useState)(!1),[nh,nf]=(0,i.useState)([]),nm=[...t7,...na.map(e=>({id:e.id,label:(0,e9.WP)(e.cwd)||e.cwd,filePath:e.cwd,kind:"terminal",closing:!!e.closing})),...nc.map(e=>({id:`git-graph:${e}`,label:(0,e9.WP)(e)||e,filePath:e,kind:"git-graph"})),...nh.map(e=>({id:`agent:${e.sessionId}`,label:e.label,filePath:e.label,kind:"agent"}))];(0,i.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(ma));nl(e.tabs),e.activeId&&(nn(e.activeId),e0(e.open))}catch{}np(!0)},[]),(0,i.useEffect)(()=>{if(nu)try{window.sessionStorage.setItem(ma,JSON.stringify({tabs:na.map(e=>{let{id:t,cwd:n}=e;return{id:t,cwd:n}}),activeId:nt,open:eQ}))}catch{}},[na,nt,eQ,nu]);let ng=(0,i.useCallback)((e,t,n,r)=>{e!==no.current?function(e,t,n,r,i){for(let[s,o]of e)if(o.generation===t)return void e.set(s,{...o,tabs:oq(o.tabs,n,r,i)})}(nr.current,e,t,n,r):ne(e=>oq(e,t,n,r))},[]),nx=(0,i.useCallback)((e,t)=>{if(e===t)return;let n=nt?.startsWith("file:")?nt: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}}(nr.current,e,t,{tabs:t7,activeTabId:n,open:eQ&&!!n},no.current);no.current+=1,ns(no.current),ne(r.tabs),nf([]),nd([]),(!nt||n||nt.startsWith("agent:")||nt.startsWith("git-graph:"))&&(nn(r.activeTabId),e0(r.open))},[nt,t7,eQ]),nv=(0,i.useCallback)((e,t)=>{tc.current?.insertText(tn(e,t)),M&&(e0(!1),eY(!1))},[M]),nb=(0,i.useCallback)(e=>{let t=e.map(e=>tn(e,!1)).join("");t&&tc.current?.insertText(t),M&&(e0(!1),eY(!1))},[M]),ny=(0,i.useCallback)((e,t,n)=>{let r,i,s,o;tc.current?.insertText((r=Math.max(1,Math.min(t,n)),i=Math.max(1,Math.max(t,n)),s=e.includes(" ")?`@"${e}"`:`@${e}`,o=r===i?`:${r}`:`:${r}-${i}`,`${s}${o} `)),M&&(e0(!1),eY(!1))},[M]),nj=E.sessionId,nk=E.sessionFromTab?null:E.sessionId,[nw,nS]=(0,i.useState)(null),nC=(0,i.useRef)(null),[nN,nE]=(0,i.useState)(()=>!nj);(0,i.useLayoutEffect)(()=>{var e;let t=(e=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:mf();if(!e)return null;try{return mm(e.getItem(mh))}catch{return null}}(),E.requestedCwd||E.sessionId||!e?E:"session"===e.kind?{...E,sessionId:e.sessionId,sessionFromTab:!0}:{...E,requestedCwd:e.cwd});t!==E&&(I(t),t.sessionId&&nE(!1))},[E]);let nI=(0,i.useRef)(!1),nT=(0,i.useRef)(!1),n$=(0,i.useRef)(0),nM=(0,i.useCallback)(()=>{n$.current+=1},[]);(0,i.useEffect)(()=>{if(_){!function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:u();if(n)try{let r=p(n);r[e]=t,n.setItem(d,JSON.stringify(r))}catch{}}(_.projectKey??nC.current??f(_),_.id),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mf();if(t&&e)try{mg({kind:"session",sessionId:e},t)}catch{}}(_.id);return}ei&&function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mf(),n=e.trim();if(t&&n)try{mg({kind:"new",cwd:n},t)}catch{}}(ei)},[ei,_]),(0,i.useEffect)(()=>{let e=E.requestedCwd;if(!e)return;let t=new AbortController;return ey("validating"),ek(null),fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e}),signal:t.signal}).then(async t=>{let n=await t.json().catch(()=>({}));if(!t.ok||!n.cwd)throw Error(n.error??`HTTP ${t.status}`);nI.current=!0;let r=`initial:${e}`;ea(r),el.current=`new:${r}:${n.cwd}`,es(n.cwd),ey("ready"),new URLSearchParams(window.location.search).get("cwd")||C.replace(`?cwd=${encodeURIComponent(n.cwd)}`,{scroll:!1})}).catch(e=>{t.signal.aborted||(ek(e instanceof Error?e.message:String(e)),ey("error"))}),()=>t.abort()},[E,C]);let nR=(0,i.useCallback)((e,t)=>{let n=++n$.current,r=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:u();if(!t)return null;try{let n=p(t)[e];return"string"==typeof n&&n.length>0?n:null}catch{return null}}(e);if(!r)return;let i=i=>{if(n!==n$.current)return;let s=i?.sessions.find(e=>e.id===r);if(!s){i&&h(e);return}if(f(s)!==e)return void h(e);let o=el.current;o&&rj(o,mv(t)),el.current=null,q(s),eN(e=>e+1),new URLSearchParams(window.location.search).get("session")!==s.id&&C.replace(`?session=${encodeURIComponent(s.id)}`,{scroll:!1})};V.length>0?i({sessions:V}):fetch("/api/sessions").then(e=>e.ok?e.json():null).then(i).catch(()=>{})},[C,V]),nL=(0,i.useCallback)((e,t,n)=>{nM();let r=ei??nw;if(nS(e),!e)return;let i=nT.current;nT.current=!1;let s=n??t??e,o=nC.current??(_?f(_):null);if(nC.current=s,nI.current){nI.current=!1;return}if(r===e&&o!==s||o===s&&(null!==_||r===e))return;let a=el.current;a&&r&&rj(a,mv(r));let l="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,c=`new:${l}:${e}`;rj(mv(e),c),ea(l),el.current=c,q(null),es(t=>t&&t!==e?null:t),eN(e=>e+1),tm([]),tx(null),tb(!1),tN(null),tI(null),t$(!1),tX(null),o!==s&&(nx(o,s),i||nR(s,e)),C.replace(window.location.pathname,{scroll:!1})},[nw,nx,nM,ei,C,_,nR]),nA=(0,i.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;e$(n?{sessionId:e.id,entryId:n,blockIndex:r}:null),nM();let s=el.current,o=ei??(null===_?nw:null);s&&o&&rj(s,mv(o)),el.current=null;let a=f(e);if(nC.current!==a&&(nx(nC.current,a),tX(null)),nC.current=a,!t&&_){let t=f(_)===f(e);if(_.id===e.id&&t){M&&eY(!1);return}}es(null),q(e),eN(e=>e+1),tm([]),tx(null),tb(!1),tj.current=null,tN(null),tI(null),t$(!1),nE(!0),!M||t||i?.keepSidebarOpen||eY(!1),t&&(nI.current=!0),t&&new URLSearchParams(window.location.search).get("session")===e.id||C.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[nw,nx,nM,C,M,ei,_]),nP=(0,i.useCallback)((e,t,n,r)=>{nM();let i=`new:${e}:${t}`,s=el.current,o=ei??(null===_?nw:null);if(r?.carryComposer&&null===_&&s){let e=tc.current;e?e.rekeyDraft(s,i):rj(s,i),ex(em.current)}else s&&o&&o!==t&&rj(s,mv(o));let a=n??(t===nw?nC.current:null)??t;nC.current!==a&&nx(nC.current,a),nC.current=a,rg(i)||rj(mv(t),i),el.current=i,ea(e),q(null),es(t),eN(e=>e+1),tm([]),tx(null),tb(!1),tN(null),tI(null),t$(!1),tX(null),M&&eY(!1),C.replace(`?cwd=${encodeURIComponent(t)}`,{scroll:!1}),M||ef.current||requestAnimationFrame(()=>{document.activeElement?.closest("[aria-modal='true']")||tc.current?.focus()})},[nw,nx,nM,M,ei,C,_]);!function(e){let{onNewSession:t,activeCwd:n}=e;(0,i.useEffect)(()=>{let e=e=>{if("Escape"===e.key)return void function(e){if("Escape"!==e.key||e.defaultPrevented||!o)return;let t=e.target?.tagName;"TEXTAREA"!==t&&"INPUT"!==t&&(e.preventDefault(),o())}(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=>nP(`kb-${Date.now()}`,e),activeCwd:nw});let nz=(0,i.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&&q(t=>t?.id===e?{...t,...n,transient:n.transient??!1}:t)}).catch(()=>{})},[]),nW=(0,i.useCallback)((e,t)=>{eS(e=>e+1),el.current===t&&(nM(),el.current=null,es(null),q(e),nz(e.id),C.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1}))},[nM,C,nz]),nO=(0,i.useCallback)(e=>{let{targetSession:t,title:n,body:r,tag:i}=e;if(!("Notification"in window))return;let s=()=>{mp({title:n,body:r,sessionUrl:t?`/?session=${encodeURIComponent(t.id)}`:"/",tag:i,onClick:()=>{window.focus(),t&&nA(t)}})};"granted"===Notification.permission?(s(),lv(T)):"default"===Notification.permission&&Notification.requestPermission().then(e=>{"granted"===e&&(s(),lv(T))})},[nA,T]),nD=(0,i.useCallback)(e=>{eS(e=>e+1),eL(e=>e+1),e.aborted||_?.relation?.kind==="subagent"||!mu()||nO({targetSession:_,title:_?.name??$("i18n.sessionComplete"),body:$("i18n.taskFinished"),tag:_?`pi-session-complete:${_.id}`:"pi-session-complete"})},[nO,_,$]),nF=(0,i.useCallback)(e=>{var t;_?.relation?.kind!=="subagent"&&mu()&&(t=H.current,!(!i7(e)||t.has(e.id))&&(t.add(e.id),1)&&nO({targetSession:_,title:$("i18n.attentionNeeded"),body:"custom"===e.method?$("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[nO,_,$]),nB=(0,i.useCallback)(async()=>{let e=_?.id;if(e&&"naming"!==tD.kind){tB.current&&clearTimeout(tB.current),tX(null),tF({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(eS(e=>e+1),tH.current!==e)return;q(t=>t?.id===e?{...t,name:r}:t),tO(t=>t?.sessionId===e?{...t,sessionName:r}:t),tF({kind:"success"}),tB.current=setTimeout(()=>tF({kind:"idle"}),1800)}catch(t){if(tH.current!==e)return;tF({kind:"error",message:t instanceof Error?t.message:String(t)}),tB.current=setTimeout(()=>tF({kind:"idle"}),5e3)}}},[tD.kind,_?.id]);(0,i.useEffect)(()=>{tB.current&&clearTimeout(tB.current),tF({kind:"idle"})},[_?.id]);let nH=(0,i.useCallback)(()=>{eL(e=>e+1)},[]),nU=(0,i.useRef)(null),n_=(0,i.useCallback)(e=>{mx.has(e)||nU.current||(nU.current=setTimeout(()=>{nU.current=null,eL(e=>e+1)},1e3))},[]);(0,i.useEffect)(()=>()=>{nU.current&&clearTimeout(nU.current)},[]);let nK=(0,i.useCallback)(e=>{nM(),el.current=null,eS(e=>e+1),eN(e=>e+1),es(null),q(t=>({...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1})),nz(e),C.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1})},[nM,C,nz]),nV=(0,i.useCallback)(async(e,t,n)=>{let r=await sa(t,{type:"fork_branch",entryId:n});if(!r?.newSessionId)throw Error($("chat.quoteForkFailed"));tu({sessionId:r.newSessionId,text:e}),nK(r.newSessionId)},[nK,$]),nZ=(0,i.useCallback)(()=>{nE(!0),nk&&(nT.current=!0)},[nk]),nJ=(0,i.useCallback)(e=>{nM(),eS(e=>e+1);let t=K.current;if(t?.id===e){!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mf();if(t&&e)try{let n=mm(t.getItem(mh));if(n?.kind!=="session"||n.sessionId!==e)return;t.removeItem(mh)}catch{}}(e);let n=t.cwd,r="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;ea(r),el.current=n?`new:${r}:${n}`:null,q(null),es(n??null),eN(e=>e+1),tm([]),tx(null),tb(!1),tN(null),tI(null),t$(!1),tX(null),C.replace(n?`?cwd=${encodeURIComponent(n)}`:window.location.pathname,{scroll:!1})}},[nM,C]),nG=(0,i.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,i=n?.modeHint,s=n?.page,o=`file:${e}`;ne(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,wrapLines:!1,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??!1,scrollTop:0,scrollLeft:0},s=!0),s&&(n.viewerRevision=(e.viewerRevision??0)+1),n}):e})(n,{fileName:t,filePath:e,modeHint:i,page:s,sourceSessionId:r,tabId:o})),nn(o),e0(!0),M&&eY(!1)},[M]),nY=(0,i.useCallback)((e,t)=>{nG(e,(0,e9.WP)(e),{sourceSessionId:_?.id??null,page:t})},[nG,_?.id]),nX=(0,i.useCallback)(e=>{let t=na.find(t=>t.cwd===e),n=t??ml(e);t||nl(e=>[...e,n]),nn(n.id),e0(!0),M&&eY(!1)},[na,M]),nQ=(0,i.useCallback)(e=>{nd(t=>t.includes(e)?t:[...t,e]),nn(`git-graph:${e}`),e0(!0),M&&eY(!1)},[M]),n0=(0,i.useCallback)((e,t)=>{nf(n=>n.some(t=>t.sessionId===e)?n:[...n,{sessionId:e,label:t}]),nn(`agent:${e}`),e0(!0),M&&eY(!1)},[M]),n1=(0,i.useCallback)((e,t)=>{let n=Y?Y.subagents.find(t=>t.id===e)??(Y.root.id===e?Y.root:void 0):void 0;n?nA(n):(async()=>{try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}`,{cache:"no-store"});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();if(!n.info)throw Error(n.error??`HTTP ${t.status}`);nA(n.info)}catch{n0(e,t)}})()},[Y,nA,n0]),n2=(0,i.useMemo)(()=>new Set(eQ?nh.map(e=>e.sessionId):[]),[nh,eQ]),n4=(0,i.useCallback)(e=>{if(na.some(t=>t.id===e))return void nl(t=>t.map(t=>t.id!==e||t.closing?t:{...t,closing:"close"}));if(e.startsWith("git-graph:")){let t=nc.filter(t=>`git-graph:${t}`!==e);nd(t),nn(n=>{if(n!==e)return n;let r=t.at(-1);return t7.at(-1)?.id??na.at(-1)?.id??(void 0!==r?`git-graph:${r}`:null)??mb(nh)}),0===t7.length&&0===na.length&&0===t.length&&0===nh.length&&e0(!1);return}if(e.startsWith("agent:")){let t=nh.filter(t=>`agent:${t.sessionId}`!==e);nf(t),nn(n=>{if(n!==e)return n;let r=nc.at(-1);return t7.at(-1)?.id??na.at(-1)?.id??(void 0!==r?`git-graph:${r}`:null)??mb(t)}),0===t7.length&&0===na.length&&0===nc.length&&0===t.length&&e0(!1);return}ne(t=>{let n=t.filter(t=>t.id!==e);return 0===n.length&&0===na.length&&0===nc.length&&0===nh.length&&e0(!1),n}),nn(t=>{if(t!==e)return t;let n=t7.filter(t=>t.id!==e),r=nc.at(-1);return n.at(-1)?.id??na.at(-1)?.id??(void 0!==r?`git-graph:${r}`:null)??mb(nh)})},[t7,na,nc,nh]),n8=(0,i.useCallback)(()=>{_&&window.open(`/api/sessions/${encodeURIComponent(_.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[_]),n5=ei??(null===_&&nw?nw:null),n6=null===_&&n5?`new:${eo}:${n5}`:null;(0,i.useLayoutEffect)(()=>{el.current=n6},[n6]);let n3=(0,i.useCallback)((e,t)=>{null===_&&n5&&e.cwd!==n5&&(ef.current=t,e.projectKey&&e.projectRoot&&ep.current?.cwd!==e.cwd&&(ep.current={cwd:e.cwd,project:{key:e.projectKey,root:e.projectRoot},branch:null}),ec.current?.startNewSessionIn({...e,carryComposer:!0}))},[n5,_]),n9=(0,i.useRef)(n3);n9.current=n3;let n7=(0,i.useCallback)(e=>{ec.current?.openFolderForNewSession(e=>n9.current(e,"project"),e)},[]),re=(0,i.useCallback)(()=>{ec.current?.openDefaultDirectoryForNewSession(e=>n9.current(e,"project"))},[]),rt=(0,i.useCallback)(()=>{ec.current?.refreshWorktrees()},[]),rn=(0,i.useCallback)(async(e,t)=>{let n=ec.current;if(!n)throw Error("The session sidebar is not mounted");let r=await n.createWorktree(e,t);return"path"in r&&(ep.current={cwd:r.path,project:e,branch:t}),r},[]),rr=(0,i.useCallback)(()=>{ef.current=null},[]),ri=null===_&&n5?(0,r.jsx)(s7,{context: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},o=s.alias??i.find(e=>e.key===s.key)?.alias;return{cwd:t,project:void 0===o?s:{...s,alias:o},worktrees:null,currentWorktreePath:null,projects:i}}(ed,n5,ep.current),mobile:M,initialFocus:ef.current,onInitialFocusDone:rr,onPick:n3,onUseDefaultDirectory:re,onOpenFolder:n7,onRefreshWorktrees:rt,onCreateWorktree:rn}):null,rs=null!==_||null!==n5,ro=_?.cwd??n5,ra=nN&&!rs;(0,i.useEffect)(()=>{if(eU(null),eq(!1),eJ(null),!ro)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(ro)}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);eU(t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[ro]);let rl=(0,i.useCallback)(async()=>{if(ro&&!eK){eV(!0),eJ(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:ro})}),t=await e.json();if(!e.ok||t.error)return void eJ({error:t.error??`HTTP ${e.status}`,...t.reason?{reason:t.reason}:{}});eU(t),eq(!1),eW(e=>e+1),eN(e=>e+1)}catch(e){eJ({error:e instanceof Error?e.message:String(e)})}finally{eV(!1)}}},[eK,ro]),rc=(0,i.useCallback)(()=>{eJ(null),eq(!0)},[]),rd=(0,i.useCallback)((e,t)=>{e===ro&&eU(t)},[ro]),ru=t7.find(e=>e.id===nt)??null,rp=nh.find(e=>`agent:${e.sessionId}`===nt)??null,rh=nt?.startsWith("git-graph:")?nc.find(e=>`git-graph:${e}`===nt)??null:null,rf=nw?(0,e9.WP)(nw)||nw:null,rm=rf?`${rf} - Pi Web`:"Pi Web";(0,i.useEffect)(()=>{let e=()=>{document.title!==rm&&(document.title=rm)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[rm]);let rx=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(nq,{selectedSessionId:_?.id??null,onSelectSession:nA,onNewSession:nP,controlRef:ec,onNewSessionContextChange:eh,initialSessionId:nj,initialSessionLinked:null!==nk,skipInitialProjectSelection:null!==E.requestedCwd,onInitialRestoreDone:nZ,refreshKey:ew,onSessionDeleted:nJ,selectedCwd:_?.cwd??ei??null,onCwdChange:nL,onOpenFile:nG,onOpenTerminal:nX,onOpenGitGraph:nQ,explorerRefreshKey:eR,onExplorerRefresh:nH,onAtMention:nv,onAtMentions:nb,onBackgroundTaskDone:U,onRunningSessionIdsChange:et,onSessionsChange:J}),(0,r.jsxs)("div",{style:{padding:"8px",flexShrink:0,display:"flex",justifyContent:"space-between",gap:4},children:[[["models",$("common.models")],["skills",$("common.skills")],["automations",$("common.automations")]].map(e=>{let[t,n]=e,i=oG(t)&&!ro;return(0,r.jsxs)("button",{type:"button",onClick:()=>eP(t),disabled:i,title:i?$("settings.projectRequired"):n,"aria-label":n,style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",gap:6,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:i?"default":"pointer",fontSize:12,opacity:i?.35:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{i||(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-muted)"},children:[(0,r.jsx)(fn,{section:t,size:14,strokeWidth:2}),(0,r.jsx)("span",{children:n})]},t)}),(0,r.jsxs)("button",{type:"button",onClick:()=>eP(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:oY();if(!t)return"general";try{let n=oX(t).section;if(!("string"==typeof n&&oV.includes(n)))return"general";return oG(n)&&!e?"general":n}catch{return"general"}}(ro)),title:$("common.settings"),"aria-label":$("common.settings"),style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",gap:6,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)(fn,{section:"general",size:14,strokeWidth:2}),(0,r.jsx)("span",{children:$("common.settings")})]})]})]}),rv=e=>rs&&eB?.requiresTrust&&!eB.trusted?(0,r.jsxs)("button",{type:"button",onClick:rc,title:$("trust.resourcesNotLoaded"),"aria-label":$("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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"M12 8v4"}),(0,r.jsx)("path",{d:"M12 16h.01"})]}),(0,r.jsx)("span",{children:$("trust.resourcesNotLoaded")})]}):null,rb=e=>{let t,n,i,s,o,a;return e||rs?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",height:"100%"},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>{n8(),e&&R&&e5(!0)},disabled:!_,title:_?$("history.full"):$("history.unsaved"),"aria-label":$("history.full"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"none",border:"none",borderTop:"2px solid transparent",borderRight:"1px solid var(--border)",color:_?"var(--text-muted)":"var(--text-dim)",cursor:_?"pointer":"not-allowed",opacity:_?1:.45,flexShrink:0,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s, opacity 0.1s"},onMouseEnter:e=>{_&&(e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{e.currentTarget.style.color=_?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.background="none"},"data-mobile-toolbar-action":e?"history":void 0,children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:_?"var(--text-muted)":"var(--text-dim)",flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]}),!e&&(0,r.jsx)("span",{children:$("history.label")})]}),(t=!!(_&&((tW?.userMessages??0)>0||_.messageCount>0)),n=!_||_.transient||!t||"naming"===tD.kind,i="success"===tD.kind,s="error"===tD.kind,o="naming"===tD.kind?$("title.generating"):i?$("title.updated"):s?$("title.failed"):$("title.generate"),a=!_||_.transient?$("title.unsaved"):t?s?tD.message:$("title.generateSession"):$("title.noMessages"),(0,r.jsxs)("button",{type:"button",onClick:()=>{nB(),e&&R&&e5(!0)},disabled:n,title:a,"aria-label":o,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"none",border:"none",borderTop:"2px solid transparent",borderRight:"1px solid var(--border)",color:s?"#dc2626":i?"var(--accent)":n?"var(--text-dim)":"var(--text-muted)",cursor:n?"not-allowed":"pointer",opacity:n&&"naming"!==tD.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=s?"#dc2626":"var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{e.currentTarget.style.color=s?"#dc2626":i?"var(--accent)":n?"var(--text-dim)":"var(--text-muted)",e.currentTarget.style.background="none"},"data-mobile-toolbar-action":e?"name":void 0,children:["naming"===tD.kind?(0,r.jsxs)("svg",{className:"animate-spin",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2",opacity:"0.25"}),(0,r.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):i?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m15 4 5 5L7 22l-5-5Z"}),(0,r.jsx)("path",{d:"m14 5 5 5"}),(0,r.jsx)("path",{d:"M6 4V2M5 3H3M19 19v3M17.5 20.5h3"})]}),!e&&(0,r.jsx)("span",{children:o})]})),X&&en&&(0,r.jsxs)("button",{type:"button",onClick:()=>t1("agents",e),title:er,"aria-label":er,"aria-pressed":"agents"===tY,style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"agents"===tY?"var(--bg-selected)":"none",border:"none",borderTop:"agents"===tY?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"agents"===tY?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},"data-mobile-toolbar-action":e?"agents":void 0,children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]}),!e&&(0,r.jsx)("span",{children:$("agentSwitcher.title")}),(0,r.jsxs)("span",{"aria-hidden":"true",style:{position:"relative",minWidth:15,height:15,padding:"0 4px",display:"grid",placeItems:"center",borderRadius:7,background:en.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:en.running?600:void 0,...e?{position:"absolute",top:3,right:3,minWidth:13,height:13,padding:"0 3px",fontSize:9}:{}},children:[en.running&&(0,r.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,r.jsx)("circle",{cx:"12",cy:"12",r:"11",stroke:"currentColor",strokeWidth:"2",opacity:"0.2"}),(0,r.jsx)("path",{d:"M23 12a11 11 0 0 0-11-11",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),en.count]})]}),tk&&(e?(0,r.jsx)("button",{type:"button",onClick:()=>t1("branches",!0),title:$("i18n.branches"),"aria-label":$("i18n.branches"),"aria-pressed":"branches"===tY,style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:"100%",padding:0,background:"branches"===tY?"var(--bg-selected)":"none",border:"none",borderTop:"branches"===tY?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"branches"===tY?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0},"data-mobile-toolbar-action":"branches",children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:tf.length>0?"var(--accent)":"var(--text-dim)"},"aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}):(0,r.jsx)(fv,{tree:tf,activeLeafId:tg,onLeafChange:tS,locked:tv,inline:!0,containerRef:tp,open:"branches"===tY,onToggle:()=>t1("branches"),hasSession:!0})),(0,r.jsxs)("button",{ref:tL,type:"button",onClick:()=>t2("system",e),disabled:e&&!rs,title:$("system.prompt"),"aria-label":$("system.prompt"),"aria-pressed":"system"===tY,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"system"===tY?"var(--bg-selected)":"none",border:"none",borderTop:"system"===tY?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:e&&!rs?"not-allowed":"pointer",color:"system"===tY?"var(--text)":"var(--text-muted)",opacity:e&&!rs?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||rs)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="system"===tY?"var(--text)":"var(--text-muted)"},"data-mobile-toolbar-action":e?"system":void 0,children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:tC?"var(--accent)":"var(--text-dim)",flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),(0,r.jsx)("polyline",{points:"14 2 14 8 20 8"}),(0,r.jsx)("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),(0,r.jsx)("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]}),!e&&(0,r.jsx)("span",{children:$("system.label")})]}),(0,r.jsxs)("button",{type:"button",onClick:()=>t2("tools",e),disabled:e&&!rs,title:$("tools.title"),"aria-label":$("tools.title"),"aria-pressed":"tools"===tY,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"tools"===tY?"var(--bg-selected)":"none",border:"none",borderTop:"tools"===tY?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:e&&!rs?"not-allowed":"pointer",color:"tools"===tY?"var(--text)":"var(--text-muted)",opacity:e&&!rs?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||rs)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="tools"===tY?"var(--text)":"var(--text-muted)"},"data-mobile-toolbar-action":e?"tools":void 0,children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:tE?.some(e=>e.active)?"var(--accent)":"var(--text-dim)",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.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"})}),!e&&(0,r.jsx)("span",{children:$("tools.label")})]})]}):null},ry=e=>{if(!e&&(!rs||!tW&&!tZ))return null;let t=tW?.tokens,n=tW?.cost??0,i=fS(n),s="var(--text-muted)",o=null,a=null;if(tZ?.contextWindow){let e=tZ.percent;null!==e&&e>90?s="#ef4444":null!==e&&e>70&&(s="rgba(234,179,8,0.95)"),o=null!==e?`${e.toFixed(0)}% / ${fw(tZ.contextWindow)}`:`? / ${fw(tZ.contextWindow)}`,a=null!==e?`${e.toFixed(0)}%`:null}let l=[];if(t&&(l.push(`in: ${t.input.toLocaleString(T)}`),l.push(`out: ${t.output.toLocaleString(T)}`),l.push(`cache read: ${t.cacheRead.toLocaleString(T)}`),l.push(`cache write: ${t.cacheWrite.toLocaleString(T)}`),n>0&&l.push(`cost: $${n.toFixed(4)}`)),tZ?.contextWindow){let e=tZ.percent;l.push(`context: ${null!==e?e.toFixed(1)+"%":"unknown"} of ${tZ.contextWindow.toLocaleString()} tokens`)}let c=l.join(" | "),d=e&&R&&e8,u=!!(t&&(t.input>0||t.output>0)||i||a);return(0,r.jsx)("button",{type:"button",onClick:()=>t1("session"),disabled:!rs||d,tabIndex:d?-1:void 0,title:c||$("session.title"),"aria-label":$("session.title"),"aria-pressed":"session"===tY,"aria-hidden":!!d||void 0,className:e?"mobile-session-stats":void 0,"data-mobile-toolbar-stats":e?"true":void 0,style:{marginLeft:e?0:"auto",display:"flex",alignItems:"center",justifyContent:"flex-end",flex:e?1:void 0,minWidth:0,gap:e?7:10,paddingLeft:e?6:12,paddingRight:e?6:12,height:"100%",overflow:"hidden",visibility:d?"hidden":"visible",pointerEvents:d?"none":"auto",background:"session"===tY?"var(--bg-selected)":"none",border:"none",borderTop:"session"===tY?"2px solid var(--accent)":"2px solid transparent",fontSize:11,color:"var(--text-muted)",whiteSpace:"nowrap",cursor:rs?"pointer":"default",fontVariantNumeric:"tabular-nums",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{rs&&!d&&(e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="session"===tY?"var(--text)":"var(--text-muted)"},children:e?(0,r.jsxs)(r.Fragment,{children:[t&&t.input>0&&(0,r.jsxs)("span",{className:"mobile-session-stat-io",style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"8.5",x2:"5",y2:"1.5"}),(0,r.jsx)("polyline",{points:"2 4 5 1.5 8 4"})]}),fw(t.input)]}),t&&t.output>0&&(0,r.jsxs)("span",{className:"mobile-session-stat-io",style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"1.5",x2:"5",y2:"8.5"}),(0,r.jsx)("polyline",{points:"2 6 5 8.5 8 6"})]}),fw(t.output)]}),i&&(0,r.jsx)("span",{className:"mobile-session-stat-cost",style:{color:"var(--text)",fontWeight:500,flexShrink:0},children:i}),a&&(0,r.jsx)("span",{style:{color:s,flexShrink:0},children:a}),!u&&rs&&(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",color:"var(--text-dim)"},children:$("session.title")})]}):(0,r.jsxs)(r.Fragment,{children:[t&&t.input>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"8.5",x2:"5",y2:"1.5"}),(0,r.jsx)("polyline",{points:"2 4 5 1.5 8 4"})]}),fw(t.input)]}),t&&t.output>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"1.5",x2:"5",y2:"8.5"}),(0,r.jsx)("polyline",{points:"2 6 5 8.5 8 6"})]}),fw(t.output)]}),t&&t.cacheRead>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M8.5 5a3.5 3.5 0 1 1-1-2.45"}),(0,r.jsx)("polyline",{points:"6.5 1.5 8.5 2.5 7.5 4.5"})]}),fw(t.cacheRead)]}),i&&(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",color:"var(--text)",fontWeight:500},children:i}),o&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4,color:s},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M1 9 L1 5 Q1 1 5 1 Q9 1 9 5 L9 9"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"9",y2:"9"})]}),o]})]})})},rk=e=>{let t=e&&R&&e8;return(0,r.jsx)("button",{type:"button",onClick:t3,disabled:t,tabIndex:t?-1:void 0,"aria-controls":"file-panel","aria-expanded":eQ,"aria-hidden":!!t||void 0,title:eQ?$("files.hidePanel"):$("files.showPanel"),"aria-label":eQ?$("files.hidePanel"):$("files.showPanel"),"data-mobile-toolbar-file":e?"true":void 0,style:{marginLeft:e||tW||tZ?0:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,visibility:t?"hidden":"visible",pointerEvents:t?"none":"auto",background:eQ?"var(--bg-selected)":"none",border:"none",borderLeft:"1px solid var(--border)",color:eQ?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{t||(e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color=eQ?"var(--text)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"15",y1:"3",x2:"15",y2:"21"})]})})};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("style",{children:`
203
- @keyframes session-info-pop {
204
- 0% {
205
- opacity: 0;
206
- transform: translateY(-24px);
207
- filter: blur(6px);
208
- box-shadow: 0 2px 8px rgba(0,0,0,0);
209
- }
210
- 55% {
211
- opacity: 1;
212
- transform: translateY(0);
213
- filter: blur(0);
214
- background: color-mix(in srgb, var(--accent) 8%, var(--bg-panel));
215
- box-shadow: 0 18px 44px rgba(37,99,235,0.16);
216
- }
217
- 100% {
218
- opacity: 1;
219
- transform: translateY(0);
220
- filter: blur(0);
221
- background: var(--bg-panel);
222
- box-shadow: 0 10px 28px rgba(0,0,0,0.10);
223
- }
224
- }
225
- @keyframes session-info-light-wash {
226
- 0% {
227
- opacity: 0;
228
- transform: translateX(-110%) skewX(-16deg);
229
- }
230
- 24% {
231
- opacity: 0.42;
232
- }
233
- 100% {
234
- opacity: 0;
235
- transform: translateX(115%) skewX(-16deg);
236
- }
237
- }
238
- .session-info-popover {
239
- position: relative;
240
- overflow: hidden;
241
- transform-origin: top right;
242
- animation: session-info-pop 360ms ease-out both;
243
- will-change: transform, opacity, filter, background, box-shadow;
244
- }
245
- .session-info-popover::after {
246
- content: "";
247
- position: absolute;
248
- top: 0;
249
- bottom: 0;
250
- left: 0;
251
- width: 44%;
252
- pointer-events: none;
253
- background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--accent) 24%, transparent), transparent);
254
- animation: session-info-light-wash 620ms ease-out both;
255
- }
256
- @media (prefers-reduced-motion: reduce) {
257
- .session-info-popover,
258
- .session-info-popover::after {
259
- animation: none;
260
- }
261
- }
262
- .mobile-session-stats {
263
- container-type: inline-size;
264
- }
265
- @container (max-width: 158px) {
266
- .mobile-session-stat-io {
267
- display: none !important;
268
- }
269
- }
270
- @container (max-width: 88px) {
271
- .mobile-session-stat-cost {
272
- display: none !important;
273
- }
274
- }
275
- @media (max-width: 640px) {
276
- .sidebar-overlay-backdrop.sidebar-mobile-pending {
277
- opacity: 0 !important;
278
- pointer-events: none !important;
279
- }
280
- .sidebar-container.sidebar-mobile-pending.sidebar-open {
281
- transform: translateX(calc(-100% - env(safe-area-inset-left)));
282
- box-shadow: none;
283
- }
284
- }
285
- `}),(0,r.jsxs)("div",{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:[(0,r.jsx)("div",{className:`sidebar-overlay-backdrop${e6?"":" sidebar-mobile-pending"}`,onClick:()=>eY(!1),style:{position:"fixed",inset:0,zIndex:199,background:"rgba(0,0,0,0.4)",opacity:+!!eG,pointerEvents:eG?"auto":"none",transition:"opacity 0.25s ease"}}),(0,r.jsx)("div",{ref:ts.panelRef,id:"session-sidebar",inert:e4,className:`sidebar-container${eG?" sidebar-open":" sidebar-closed"}${e6?"":" sidebar-mobile-pending"}${ts.isResizing?" sidebar-resizing":""}`,style:{"--sidebar-width":`${ts.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:200},children:rx}),eG&&(0,r.jsx)("div",{...ts.separatorProps,inert:e4,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${ts.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${$("layout.resizeSidebar")}: ${$("layout.resizeHint")}`}),(0,r.jsxs)("div",{inert:e4,style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:[(0,r.jsxs)("div",{ref:tp,style:{flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",position:"relative",borderBottom:"1px solid var(--border)",height:"calc(36px + env(safe-area-inset-top))",paddingTop:"env(safe-area-inset-top)"},children:[(0,r.jsx)("button",{onClick:t5,title:eG?$("sidebar.hide"):$("sidebar.show"),"aria-label":eG?$("sidebar.hide"):$("sidebar.show"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,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:eG?(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]}):(0,r.jsxs)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),(0,r.jsx)("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),(0,r.jsx)("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})}),M&&(0,r.jsxs)("div",{ref:th,"data-mobile-toolbar":"true",style:{position:"relative",display:"flex",alignItems:"stretch",flex:1,minWidth:0,height:"100%"},children:[R&&(0,r.jsx)("button",{type:"button",onClick:t6,title:e8?$("chat.close"):$("chat.moreControls"),"aria-label":e8?$("chat.close"):$("chat.moreControls"),"aria-controls":"mobile-toolbar-actions","aria-expanded":e8,"data-mobile-toolbar-more":"true",style:{position:"relative",zIndex:e8?21:void 0,display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:e8?"var(--bg-selected)":"none",border:"none",borderRight:"1px solid var(--border)",color:e8?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s, background 0.12s"},children:e8?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"5",x2:"19",y2:"19"}),(0,r.jsx)("line",{x1:"19",y1:"5",x2:"5",y2:"19"})]}):(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"5",cy:"12",r:"1.5"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1.5"}),(0,r.jsx)("circle",{cx:"19",cy:"12",r:"1.5"})]})}),!R&&rb(!0),ry(!0),rk(!0),R&&e8&&(0,r.jsx)("div",{id:"mobile-toolbar-actions",role:"toolbar","aria-label":$("chat.moreControls"),"data-mobile-toolbar-actions":"true",style:{position:"absolute",top:0,right:0,bottom:0,left:36,zIndex:20,display:"flex",alignItems:"stretch",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:rb(!0)})]}),!M&&(0,r.jsxs)(r.Fragment,{children:[rv(!1),rb(!1),ry(!1)]}),!M&&rk(!1),M&&tk&&(0,r.jsx)(fv,{tree:tf,activeLeafId:tg,onLeafChange:tS,locked:tv,inline:!0,compact:!0,containerRef:tp,open:"branches"===tY,onToggle:()=>t1("branches"),hasSession:rs,hideInlineButton:!0}),tY&&tQ&&(0,r.jsxs)("div",{style:{position:"fixed",top:tQ.top,left:tQ.left,width:tQ.width,maxHeight:`calc(100dvh - ${tQ.top}px)`,overflowY:"auto",zIndex:500},children:["agents"===tY&&Y&&_&&(0,r.jsx)(fR,{rootSession:Y.root,subagents:Y.subagents,selectedSessionId:_.id,runningSessionIds:Q,onSelectSession:nA,openSubagentTabIds:n2,onToggleSubagentTab:(e,t)=>{n2.has(e)?n4(`agent:${e}`):(M&&tX(null),n0(e,t))}}),"system"===tY&&(0,r.jsx)(fb,{loading:tT,prompt:tC,translate:$}),"tools"===tY&&(0,r.jsx)(fk,{loading:tT,tools:tE,translate:$}),"session"===tY&&(0,r.jsx)("div",{className:"session-info-popover",style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",boxShadow:"0 10px 28px rgba(0,0,0,0.10)",padding:"12px 16px"},children:tW?(n=tW.totalActiveMs??0,c=[...tW.sessionName?[{label:$("session.name"),value:tW.sessionName,copyField:null}]:[],{label:$("session.file"),value:tW.sessionFile??$("session.inMemory"),copyField:"file"},{label:$("session.id"),value:tW.sessionId,copyField:"id"},...n>0?[{label:$("session.totalActive"),value:fC(n),copyField:null}]:[]],m=[..._?[{label:$("session.projectDir"),value:_.projectRoot??_.cwd,copyField:"projectDir"}]:[],..._?.branch?[{label:$("session.gitBranch"),value:_.branch,copyField:"gitBranch"}]:[],..._?.isWorktree?[{label:$("session.gitWorktree"),value:_.cwd,copyField:"gitWorktree"}]:[]],g=[[$("session.user"),tW.userMessages.toLocaleString(T)],[$("session.assistant"),tW.assistantMessages.toLocaleString(T)],[$("session.toolCalls"),tW.toolCalls.toLocaleString(T)],[$("session.toolResults"),tW.toolResults.toLocaleString(T)],[$("session.total"),tW.totalMessages.toLocaleString(T)]],x=[[$("session.input"),tW.tokens.input.toLocaleString(T)],[$("session.output"),tW.tokens.output.toLocaleString(T)],...tW.tokens.cacheRead>0?[[$("session.cacheRead"),tW.tokens.cacheRead.toLocaleString(T)]]:[],...tW.tokens.cacheWrite>0?[[$("session.cacheWrite"),tW.tokens.cacheWrite.toLocaleString(T)]]:[],[$("session.total"),tW.tokens.total.toLocaleString(T)]],v=tZ??tW.contextUsage,b=[...tW.cost>0?[[$("session.cost"),`$${tW.cost.toFixed(4)}`]]:[],...v?.contextWindow?[[$("session.context"),`${null!==v.percent?`${v.percent.toFixed(1)}%`:"?"} / ${fw(v.contextWindow)}`]]:[],...tW.tokens.cacheRead+tW.tokens.cacheWrite>0&&tW.tokens.cacheRead+tW.tokens.cacheWrite+tW.tokens.input>0?[[$("session.cacheHitRate"),`${(tW.tokens.cacheRead/(tW.tokens.cacheRead+tW.tokens.cacheWrite+tW.tokens.input)*100).toFixed(1)}%`]]:[]],y=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"left",i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:e}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:i?"max-content max-content":"auto minmax(0, 1fr)",columnGap:i?14:12,rowGap:4,justifyContent:i?"start":void 0},children:t.map(t=>{let[s,o]=t;return(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:s}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:i?"normal":"anywhere",textAlign:n,whiteSpace:"right"===n?"nowrap":"normal"},children:o})]},`${e}:${s}`)})})]})},j={file:"session.copyFile",id:"session.copyId",projectDir:"session.copyProjectDir",gitBranch:"session.copyGitBranch",gitWorktree:"session.copyGitWorktree"},k=(e,t)=>{let n=t_===e;return(0,r.jsx)("button",{type:"button",title:n?$("session.copied"):$(j[e]),onClick:()=>tV(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,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})},w=(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:$("session.infoSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:c.map(e=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,r.jsx)("div",{children:e.copyField?k(e.copyField,e.value):null})]},`session-info:${e.label}`))})]}),S=m.length>0?(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:$("session.projectSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:m.map(e=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,r.jsx)("div",{children:e.copyField?k(e.copyField,e.value):null})]},`project-info:${e.label}`))})]}):null,(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:M?"1fr":"minmax(360px, 1.7fr) minmax(140px, 0.55fr) minmax(190px, 0.75fr)",gap:M?16:24,fontSize:12,lineHeight:1.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:M?16:20},children:[w,S]}),y($("session.messages"),g),y($("session.tokens"),[...x,...b],"right",!0)]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:$("session.load")})})]})]}),M&&rv(!0)]}),(0,r.jsx)("div",{style:{flex:1,overflow:"hidden",position:"relative"},children:rs?(0,r.jsx)(s0,{session:_,searchTarget:eT?.sessionId===_?.id?eT:null,onSearchTargetHandled:eM,initialScrollPosition:_?eE.current.get(_.id)??null:null,onScrollPositionChange:eI,sessionRunning:!!(_&&Q.has(_.id)),newSessionCwd:n5,newSessionDraftKey:n6,newSessionContextBar:ri,initialNewSessionChoices:null===_?eg:null,onNewSessionChoicesChange:ev,onAgentEnd:nD,onToolEnd:n_,onAttentionNeeded:nF,onSessionCreated:nW,onSessionForked:nK,modelsRefreshKey:ez,chatInputRef:tc,onBranchDataChange:tw,onSystemPromptChange:tA,onSystemToolsChange:tP,onSystemInfoLoaderChange:tz,onSessionStatsChange:tU,onSessionStatsPanelOpen:t4,onOpenSettings:t8,onContextUsageChange:tG,onOpenFile:nY,onFilesUploaded:nH,onOpenSubagent:n0,onEnterSubagent:n1,onAskInNewChat:nV,quoteSelectionEnabled:D,initialPrompt:td?.sessionId===_?.id?td?.text:void 0,onInitialPromptConsumed:()=>tu(null),soundEnabled:L,onSoundToggle:A,playDoneSound:P,unlockAudio:z,holdAudio:W},eC):"validating"===eb?(0,r.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,r.jsx)("div",{style:{fontSize:14,color:"var(--text)"},children:$("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:E.requestedCwd})]}):"error"===eb?(0,r.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,r.jsx)("div",{style:{fontSize:14,color:"#dc2626"},children:$("workspace.unable")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:E.requestedCwd}),(0,r.jsx)("div",{style:{maxWidth:720,fontSize:12},children:ej})]}):ra?nw?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:$("workspace.selectSession")}):(0,r.jsxs)("div",{style:{position:"absolute",top:12,left:12,display:"flex",alignItems:"flex-start",gap:8,userSelect:"none",pointerEvents:"none"},children:[(0,r.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,r.jsx)("line",{x1:"20",y1:"12",x2:"4",y2:"12"}),(0,r.jsx)("polyline",{points:"10 6 4 12 10 18"})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:18,fontWeight:600,color:"var(--text)",marginBottom:8},children:$("workspace.getStarted")}),(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.8},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"1."}),$("workspace.selectProject"),(0,r.jsx)("br",{}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),$("workspace.addModels")]})]})]}):null})]}),(0,r.jsx)("div",{"aria-hidden":"true",className:`right-panel-overlay-backdrop${eQ?" is-open":""}`,onClick:()=>e0(!1)}),eQ&&(0,r.jsx)("div",{...to.separatorProps,inert:e4,"aria-controls":"file-panel",className:`panel-resize-handle right-panel-resize-handle${to.isResizing?" is-resizing":""}`,"data-resize-handle":"right-panel",title:`${$("layout.resizeFilePanel")}: ${$("layout.resizeHint")}`}),(0,r.jsxs)("div",{ref:to.panelRef,id:"file-panel",className:`right-panel-container${eQ?" right-panel-open":" right-panel-closed"}${e4?" right-panel-full-width":""}${to.isResizing?" right-panel-resizing":""}`,style:{"--right-panel-width":`${to.width}px`,display:"flex",flexDirection:"column",borderLeft:"1px solid var(--border)",background:"var(--bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexShrink:0,height:"calc(36px + env(safe-area-inset-top))",paddingTop:"env(safe-area-inset-top)",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{flex:1,overflow:"hidden"},children:(0,r.jsx)(o_,{tabs:nm,activeTabId:nt??"",onSelectTab:nn,onCloseTab:n4})}),(0,r.jsx)("button",{type:"button",className:"file-panel-expand-button",onClick:t9,"aria-controls":"file-panel","aria-pressed":e4,title:$(e4?"files.restorePanelWidth":"files.expandPanel"),"aria-label":$(e4?"files.restorePanelWidth":"files.expandPanel"),children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:e4?"M9 3v6H3m12-6v6h6M9 21v-6H3m12 6v-6h6M3 3l6 6m12-6-6 6M3 21l6-6m12 6-6-6":"M8 3H3v5m13-5h5v5M3 16v5h5m13-5v5h-5M3 3l6 6m12-6-6 6M3 21l6-6m12 6-6-6"})})}),(0,r.jsx)("button",{type:"button",onClick:()=>e0(!1),"aria-controls":"file-panel","aria-expanded":eQ,title:$("files.hidePanel"),"aria-label":$("files.hidePanel"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:"var(--bg-selected)",border:"none",borderLeft:"1px solid var(--border)",color:"var(--text)",cursor:"pointer",flexShrink:0,transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text)"},children:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"15",y1:"3",x2:"15",y2:"21"})]})})]}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflow:"hidden",paddingBottom:"env(safe-area-inset-bottom)"},children:[ru?.filePath?(0,r.jsx)(oH,{filePath:ru.filePath,cwd:nw??void 0,sourceSessionId:ru.sourceSessionId,gitRefreshKey:eR,initialDisplayMode:ru.initialDisplayMode,initialPage:ru.page,initialState:ru.viewerState,watchEnabled:eQ,onStateChange:e=>ng(ni,ru.id,ru.viewerRevision??0,e),onMentionLines:eQ?ny:void 0,onAtMention:nv,onOpenFile:(e,t)=>nG(e,(0,e9.WP)(e),{sourceSessionId:ru.sourceSessionId,page:t})},`${ni}:${ru.id}:${ru.viewerRevision??0}`):na.some(e=>e.id===nt)||rp||rh?null:(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12},children:$("files.noneOpen")}),null!==rh&&(0,r.jsx)(mi,{cwd:rh,refreshKey:eR},`git-graph:${rh}`),na.map(e=>(0,r.jsx)("div",{hidden:e.id!==nt,style:{width:"100%",height:"100%"},children:(0,r.jsx)(f9,{tab:e,active:eQ&&e.id===nt,onRestart:()=>nl(t=>t.map(t=>t.id===e.id?{...t,closing:"restart"}:t)),onClosed:()=>{let t,n;return t="restart"===e.closing?ml(e.cwd):null,n=na.filter(t=>t.id!==e.id),void(nl(n=>n.flatMap(n=>n.id!==e.id?[n]:t?[t]:[])),nn(r=>r!==e.id?r:t?.id??n.at(-1)?.id??t7.at(-1)?.id??mb(nh)),!t&&!n.length&&!t7.length&&!nc.length&&!nh.length&&e0(!1))},onCloseError:()=>nl(t=>t.map(t=>t.id===e.id?{...t,closing:void 0}:t))})},e.id)),rp&&(0,r.jsx)(fz,{sessionId:rp.sessionId,fallbackLabel:rp.label,running:Q.has(rp.sessionId),onOpenFile:nY},rp.sessionId)]})]})]}),eA&&(0,r.jsx)(fi,{cwd:ro,sessionId:_?.id??null,initialSection:eA,quoteSelectionEnabled:D,onQuoteSelectionChange:B,onClose:()=>{eP(null),eW(e=>e+1)},onSessionReloaded:()=>eN(e=>e+1),projectTrust:eB,onOpenTrustDialog:rc,onProjectTrustChanged:rd}),e_&&ro&&(0,r.jsx)(fo,{cwd:ro,busy:eK,error:eZ,onCancel:()=>{eK||eq(!1)},onConfirm:()=>void rl(),onStatus:eU})]})}},82725:(e,t,n)=>{"use strict";n.d(t,{Q8:()=>r,YO:()=>p,getPresetFromTools:()=>u,kU:()=>o,sn:()=>d,xG:()=>h});let r="configured",i=["configured","none","read-only","default","full"],s=[],o=["read","grep","find","ls"],a=["read","bash","edit","write"],l=["bash","read","edit","write","grep","find","ls"],c=new Set([...l,"powershell"]);function d(e){return"string"==typeof e&&i.includes(e)}function u(e){return p(e.filter(e=>e.active).map(e=>e.name))}function p(e){if(0===e.length)return"none";let t=e.map(e=>"powershell"===e?"bash":e).filter(e=>c.has(e)).sort().join(",");return t===[...o].sort().join(",")?"read-only":t===[...a].sort().join(",")?"default":t===[...l].sort().join(",")?"full":"default"}function h(e){if(e!==r)return"none"===e?[...s]:"read-only"===e?[...o]:"full"===e?[...l]:[...a]}}},e=>{e.O(0,[9969,5500,4712,8555,6011,462,4251,1798,7441,3316,7358],()=>e(e.s=11340)),_N_E=e.O()}]);