@mcy2015/pi-web 0.17.2 → 0.17.3

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 (70) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +15 -15
  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/agent/new/route.js +1 -1
  19. package/.next/server/app/api/app-update/route.js +1 -1
  20. package/.next/server/app/api/sessions/[id]/auto-name/route.js +1 -1
  21. package/.next/server/app/api/sessions/[id]/entries/[entryId]/thinking/route.js +1 -1
  22. package/.next/server/app/api/sessions/[id]/entries/[entryId]/thinking/route.js.nft.json +1 -1
  23. package/.next/server/app/api/sessions/[id]/entries/[entryId]/tool-result-image/route.js +1 -1
  24. package/.next/server/app/api/sessions/[id]/entries/[entryId]/tool-result-image/route.js.nft.json +1 -1
  25. package/.next/server/app/api/sessions/[id]/export/route.js +1 -1
  26. package/.next/server/app/api/sessions/[id]/export/route.js.nft.json +1 -1
  27. package/.next/server/app/api/sessions/[id]/fork/route.js +1 -1
  28. package/.next/server/app/api/sessions/[id]/share/route.js +1 -1
  29. package/.next/server/app/api/sessions/ui-state/route.js +1 -1
  30. package/.next/server/app/api/sessions/ui-state/route.js.nft.json +1 -1
  31. package/.next/server/app/api/shares/route.js +1 -1
  32. package/.next/server/app/files/page_client-reference-manifest.js +1 -1
  33. package/.next/server/app/files.html +1 -1
  34. package/.next/server/app/files.rsc +3 -3
  35. package/.next/server/app/files.segments/_full.segment.rsc +3 -3
  36. package/.next/server/app/files.segments/_tree.segment.rsc +1 -1
  37. package/.next/server/app/files.segments/files/__PAGE__.segment.rsc +3 -3
  38. package/.next/server/app/index.html +1 -1
  39. package/.next/server/app/index.rsc +4 -4
  40. package/.next/server/app/index.segments/__PAGE__.segment.rsc +4 -4
  41. package/.next/server/app/index.segments/_full.segment.rsc +4 -4
  42. package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  43. package/.next/server/app/login/page_client-reference-manifest.js +1 -1
  44. package/.next/server/app/login.html +1 -1
  45. package/.next/server/app/login.rsc +3 -3
  46. package/.next/server/app/login.segments/_full.segment.rsc +3 -3
  47. package/.next/server/app/login.segments/_tree.segment.rsc +1 -1
  48. package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +3 -3
  49. package/.next/server/app/page.js +6 -6
  50. package/.next/server/app/page_client-reference-manifest.js +1 -1
  51. package/.next/server/app/share/[code]/page_client-reference-manifest.js +1 -1
  52. package/.next/server/app-paths-manifest.json +15 -15
  53. package/.next/server/chunks/1795.js +1 -1
  54. package/.next/server/chunks/1906.js +1 -1
  55. package/.next/server/chunks/210.js +3 -3
  56. package/.next/server/chunks/2243.js +1 -1
  57. package/.next/server/chunks/6429.js +1 -1
  58. package/.next/server/middleware-build-manifest.js +1 -1
  59. package/.next/server/pages/404.html +1 -1
  60. package/.next/server/pages/500.html +1 -1
  61. package/.next/static/chunks/1278-62c1807415068bca.js +1 -0
  62. package/.next/static/chunks/app/{layout-4ca77cad75a0bfc8.js → layout-940cd6ecf374f9ad.js} +1 -1
  63. package/.next/static/chunks/app/page-0df1a6d33c89872a.js +1457 -0
  64. package/.next/trace +41 -38
  65. package/.next/trace-build +1 -1
  66. package/package.json +1 -1
  67. package/.next/static/chunks/1278-876b99533141f279.js +0 -1
  68. package/.next/static/chunks/app/page-ebc3272cf64b5bd8.js +0 -1457
  69. /package/.next/static/{xtVraug33Zuh6-oCFF6TA → BwFpia-Mahfafr8weQmhE}/_buildManifest.js +0 -0
  70. /package/.next/static/{xtVraug33Zuh6-oCFF6TA → BwFpia-Mahfafr8weQmhE}/_ssgManifest.js +0 -0
@@ -0,0 +1,1457 @@
1
+ (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{5284:e=>{e.exports={lock:"LockToggle_lock__hI4qs"}},14755:(e,t,n)=>{"use strict";n.d(t,{Q8:()=>r,YO:()=>h,getPresetFromTools:()=>p,kU:()=>a,kt:()=>d,sn:()=>u,xG:()=>m});let r="configured",i=["configured","none","read-only","default","full"],s=[],a=["read","grep","find","ls"],l=["read","bash","edit","write"],o=["bash","read","edit","write","grep","find","ls"],d=["read","grep","find","ls","edit","write","bash"],c=new Set([...o,"powershell"]);function u(e){return"string"==typeof e&&i.includes(e)}function p(e){return h(e.filter(e=>e.active).map(e=>e.name))}function h(e){if(0===e.length)return"none";let t=e.map(e=>"powershell"===e?"bash":e).filter(e=>c.has(e)).sort().join(",");return t===[...a].sort().join(",")?"read-only":t===[...l].sort().join(",")?"default":t===[...o].sort().join(",")?"full":"default"}function m(e){if(e!==r)return"none"===e?[...s]:"read-only"===e?[...a]:"full"===e?[...o]:[...l]}},18967:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>gZ});var r=n(95155),i=n(12115),s=n(73321);let a=null;function l(e,t,n){if(e.name&&"Side chat"!==e.name)return e.name;let r=n.filter(e=>e.relation?.kind==="side").sort((e,t)=>e.created.localeCompare(t.created)||e.id.localeCompare(t.id)).findIndex(t=>t.id===e.id);return r<0?t:`${t} ${r+1}`}function o(e){return e?.kind==="subagent"||e?.kind==="side"}function d(e){let t=function(e){let t=new Map(e.map(e=>[e.id,e])),n=new Map;for(let r of e){if(n.has(r.id))continue;let e=[],i=new Set,s=r.id,a=null;for(;;){if(n.has(s)){a=n.get(s)??null;break}if(i.has(s))break;i.add(s),e.push(s);let r=t.get(s);if(!r)break;if(!o(r.relation)){a=r.id;break}s=r.relation.parentSessionId}for(let t of e)n.set(t,a)}return n}(e),n=new Map;for(let t of e)o(t.relation)||n.set(t.id,{root:t,subagents:[],latestModified:t.modified});for(let r of e){if(!o(r.relation))continue;let e=t.get(r.id),i=e?n.get(e):void 0;i&&(i.subagents.push(r),r.modified>i.latestModified&&(i.latestModified=r.modified))}return[...n.values()].sort((e,t)=>t.latestModified.localeCompare(e.latestModified))}function c(e,t){return t?d(e).find(e=>e.root.id===t||e.subagents.some(e=>e.id===t))??null:null}function u(e,t){return e.filter(e=>t.has(e.id)).length}function p(e){return`?session=${encodeURIComponent(e)}`}let h="pi-web:last-open-by-workspace";function m(){try{return window.localStorage}catch{return null}}function g(e){let t=e.getItem(h);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function f(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:m();if(t)try{let n=g(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(h):t.setItem(h,JSON.stringify(n))}catch{}}function x(e){return e.projectKey??e.projectRoot??e.cwd}function b(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=x(n),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{root:e,modified:n.modified})}return[...t.entries()].sort((e,t)=>t[1].modified.localeCompare(e[1].modified)).map(e=>{let[t,{root:n}]=e;return{key:t,root:n}})}let v=/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/,y=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function k(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function j(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function w(e){return"string"==typeof e&&v.test(e)}function S(e){return"string"==typeof e&&e.length>0&&e.length<=4096&&"__proto__"!==e}let C=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;function N(e){if(null===e)return null;if("string"!=typeof e)return;let t=e.trim();return t?C.test(t)||[...t].length>80?void 0:t:null}let I=new TextEncoder;function E(e){return I.encode(JSON.stringify(e)).length+1}function $(e){let t=1;for(let n of e)t+=E(n);return t}function T(e,t){return e<=1e3&&t<=262144}function M(e){let t=[],n=1;for(let r of e){if(t.length>=1e3)break;let e=E(r);n+e>262144||(t.push(r),n+=e)}return t}function R(e,t){return I.encode(JSON.stringify(e)).length+I.encode(JSON.stringify(t)).length+2}function A(e,t){return e<=1e3&&t<=262144}function L(){return{version:1,revision:0,sessions:{},projects:{}}}function P(e){let t=Object.entries(e);return t.length<=2e3?e:(t.sort((e,t)=>t[1]-e[1]),Object.fromEntries(t.slice(0,2e3)))}function z(e,t,n){let r=y(e,t)?e[t]:void 0;return void 0===n.pinnedAt&&void 0===n.archivedAt?!!r&&(delete e[t],!0):(r?.pinnedAt!==n.pinnedAt||r?.archivedAt!==n.archivedAt)&&(e[t]=n,!0)}function O(e,t){var n;return n=e.projectOrder??[],!(n.length===t.length&&n.every((e,n)=>e===t[n]))&&(0===t.length?delete e.projectOrder:e.projectOrder=t,!0)}function W(e,t){let n=new Set(e),r=[];for(let e of t)n.has(e)||(n.add(e),r.push(e));return r}function F(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:500,n=Math.max(1,Math.floor(t)),r=[];for(let t=0;t<e.length;t+=n)r.push(e.slice(t,t+n));return r}let D={desktop:{"pinned-header":28,session:28,"pinned-more":26,group:28,"group-more":26,"group-empty":28,spacer:8,"footer-open":28,"footer-archived":28,"archive-group":28},mobile:{"pinned-header":44,session:44,"pinned-more":36,group:44,"group-more":36,"group-empty":44,spacer:8,"footer-open":44,"footer-archived":44,"archive-group":44}},B="pinned";function H(e,t){return Object.hasOwn(e.sessions,t)?e.sessions[t]:void 0}function _(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function U(e,t){return e===t?0:e>t?-1:1}function K(e){return[e.root.id,...e.subagents.map(e=>e.id)]}function q(e,t){return 0!==t.size&&(t.has(e.root.id)||e.subagents.some(e=>t.has(e.id)))}function Z(e,t,n){let r=_(H(t,e.root.id)?.archivedAt);if(null===r||q(e,n))return!1;if(e.root.detailsPending)return!0;let i=Date.parse(e.root.modified);return Number.isNaN(i)||r>=i}function V(e,t,n){return null!==_(H(t,e.root.id)?.pinnedAt)&&!Z(e,t,n)}function J(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e.charAt(0);let n=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return t.slice(n+1)}function G(e,t){if(Object.hasOwn(t,e.key)){let n=t[e.key];if("boolean"==typeof n)return n}return e.current||e.pinned}function Y(e,t){var n;return{running:q(e,t.runningIds),awaiting:!!t.awaitingIds&&q(e,t.awaitingIds),unread:q(e,t.unreadIds),selected:!!(n=t.selectedSessionId)&&(e.root.id===n||e.subagents.some(e=>e.id===n)),transient:!0===e.root.transient}}function X(e,t){let n=0,r=0,i=0;for(let s of e)t.awaitingIds&&q(s,t.awaitingIds)?r++:q(s,t.runningIds)&&n++,q(s,t.unreadIds)&&i++;return{running:n,awaiting:r,unread:i}}function Q(e){return x(e.root)}function ee(e,t){let n=new Map,r=new Map;return{noteFamily(e){let t=Q(e);n.has(t)||n.set(t,e.root.projectRoot??e.root.cwd)},get(i){let s,a=r.get(i);if(a)return a;let l=Object.hasOwn(e.projects,i)?e.projects[i]:void 0,o=null!==t&&t.key===i,d=n.get(i)??(o?t.root:void 0)??l?.root??i,c=((s=e.projectNames)&&y(s,i)?s[i]:void 0)??null,u={key:i,root:d,name:c??J(d),customName:c,pinned:void 0!==l,current:o};return r.set(i,u),u}}}function et(e,t,n,r){return{kind:"session",key:`session:${t}:${e.root.id}`,family:e,context:t,project:n,status:Y(e,r)}}function en(e,t,n,r){let i=e.map((e,n)=>{if(n<t)return!1;let i=Y(e,r);return i.running||i.unread||i.selected}),s=t+n,a=0,l=e.filter((e,n)=>n<t||!!i[n]||n<s&&(a++,!0)),o=Math.max(t,Math.min(s,e.length));for(let t=0;o<e.length&&t<20;o++)!i[o]&&t++;return{visible:l,revealed:a,nextShown:o-t}}function er(e,t){if(!Object.hasOwn(e,t))return 0;let n=e[t];return"number"==typeof n&&Number.isFinite(n)&&n>0?Math.floor(n):0}function ei(e,t){if(!Object.hasOwn(e,t))return e;let n={...e};return delete n[t],n}function es(e,t,n){let r=e-t,i=n>0;return r>0||i?{hidden:r,canShowLess:i}:null}function ea(e,t,n,r){let i=r-n,s=[];for(let n of d(e.sessions)){if(Q(n)!==t||Z(n,e.uiState,e.runningIds)||V(n,e.uiState,e.runningIds))continue;let r=Y(n,e);if(r.running||r.unread||r.selected||r.transient)continue;let a=Date.parse(n.latestModified);Number.isNaN(a)||a>=i||s.push(n.root.id)}return s}function el(e,t){let n=[],r=0;for(let i of d(e.sessions))if(Q(i)===t&&!i.root.transient){if(q(i,e.runningIds)||e.awaitingIds&&q(i,e.awaitingIds)){r++;continue}n.push(i.root.id)}return{ids:n,running:r}}function eo(e,t,n){let r=e.find(e=>e.key===t);if(!r)return null;let i=e.filter(e=>e.pinned===r.pinned),s=i.indexOf(r),a=i["up"===n?s-1:s+1];return a?{anchorKey:a.key,position:"up"===n?"before":"after"}:null}function ed(e,t,n,r,i){if(!Number.isInteger(t)||t<0||t>=e.length-1)return null;let s=e[t],a=e[t+1];return"start"===i?s===n?null:s:s>=n&&a<=n+r?null:"nearest"===i&&a>n&&s<n+r?s<n||a-s>r?s:a-r:Math.max(0,s-Math.max(0,(r-(a-s))/2))}var ec=n(23579);async function eu(e,t){let n={deletedRoots:[],deleted:[],running:[],error:null};for(let r=0;r<e.length;r+=500){let i=e.slice(r,r+500);try{let e=await t("/api/sessions/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:i})}),r=await e.json().catch(()=>({}));if(!e.ok||!Array.isArray(r.deleted)){n.error=r.error??`HTTP ${e.status}`;break}let s=new Set(r.deleted);n.deleted.push(...r.deleted),n.deletedRoots.push(...i.filter(e=>s.has(e))),n.running.push(...r.running??[])}catch(e){n.error=e instanceof Error?e.message:String(e);break}}return n}function ep(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function eh(e,t){let n=t.replace(/[/\\]+$/,"");return n&&(e===n||e.startsWith(`${n}/`)||e.startsWith(`${n}\\`))?`./${e.slice(n.length).replace(/^[/\\]/,"")}`:ep(e)}let em=/ · [0-9a-f]{4}$/;function eg(e){let t=em.exec(e);return t&&0!==t.index?{base:e.slice(0,t.index),suffix:t[0]}:null}function ef(e,t){return{cwd:e.current&&t?t:e.root,projectKey:e.key,projectRoot:e.root}}function ex(e){let t=e.project;return!t||e.projects.some(e=>e.key===t.key)?[...e.projects]:[t,...e.projects]}function eb(e,t){let{key:n,root:r}=e,i=t&&Object.hasOwn(t,n)?t[n]:void 0;return void 0===i?{key:n,root:r}:{key:n,root:r,alias:i}}function ev(e){let t=e.map(e=>({choice:e,name:e.alias??J(e.root)})),n=new Map;for(let{name:e}of t)n.set(e,(n.get(e)??0)+1);return t.map(e=>{let t,r,{choice:i,name:s}=e;return{choice:i,name:s,note:void 0===i.alias&&(n.get(s)??0)>1&&(r=Math.max((t=i.root.replace(/[\\/]+$/,"")).lastIndexOf("/"),t.lastIndexOf("\\")))>0?J(t.slice(0,r)):null}})}let ey={awaiting:"#d97706",unread:"#0891b2"};function ek(e){return Number.isFinite(e)?Math.max(0,Math.floor(e)):0}let ej=null,ew=null,eS=new Map;function eC(){return[...document.querySelectorAll('link[rel="icon"]')]}async function eN(e,t){let n=await (!ew&&(ew=new Promise(e=>{let t=new Image;t.onload=()=>e(t),t.onerror=()=>e(null),t.src="/icons/icon-192.png"})),ew);if(!n||ej!==t)return;let r=document.createElement("canvas");r.width=192,r.height=192;let i=r.getContext("2d");if(!i)return;i.clearRect(0,0,192,192),i.drawImage(n,0,0,192,192);let s=e.count>1,a=s?56:42,l=192-a-10,o=a+10;if(i.beginPath(),i.arc(l,o,a,0,2*Math.PI),i.fillStyle=ey[e.kind],i.fill(),i.lineWidth=10,i.strokeStyle="#ffffff",i.stroke(),s&&(i.fillStyle="#ffffff",i.font=`bold ${e.count>9?56:68}px system-ui, sans-serif`,i.textAlign="center",i.textBaseline="middle",i.fillText(String(e.count),l,o+4)),ej!==t)return;let d=r.toDataURL("image/png");for(let e of eC())e.href=d}function eI(e){return e.isComposing||229===e.keyCode}function eE(e,t){let n=e.activeElement;return!!t&&(!n||n===e.body)&&(t.focus({preventScroll:!0}),!0)}var e$=n(16913);let eT="pi-web:unread-session-ids";function eM(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function eR(e){let t,n=new Map;if(!e)return n;try{t=JSON.parse(e)}catch{return n}if(Array.isArray(t))for(let e of t)"string"==typeof e&&n.set(e,0);else if("object"==typeof t&&null!==t)for(let[e,r]of Object.entries(t))eM(r)&&n.set(e,r);return n}function eA(e,t){if(!t||0===e.size)return e;let n=null;for(let[i,s]of e){var r;void 0!==(r=Object.prototype.hasOwnProperty.call(t,i)?t[i]:void 0)&&r>=s&&(n??=new Map(e)).delete(i)}return n??e}let eL=["pointerdown","keydown","wheel","touchstart"],eP=null,ez=0,eO=null;function eW(){return"u">typeof document&&"visible"===document.visibilityState&&document.hasFocus()}function eF(){return eP??=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:12e4,r=null,i=!1,s=new Set,a=e=>null!==r&&e-r<n,l=t=>{let n=e()&&a(t),r=n&&!i;if(i=n,r)for(let e of[...s])try{e()}catch(e){console.error(e)}};return{noteInput(){let e=t();a(e)||(i=!1),r=e,l(e)},notePageChange(){let e=t();a(e)||(i=!1),l(e)},isAttended:()=>e()&&a(t()),onAttended:e=>(s.add(e),()=>s.delete(e))}}(eW,()=>performance.now())}function eD(){return 0!==ez&&eF().isAttended()}let eB="pi-web:sidebar-files-placement",eH="below";function e_(){try{var e;return e=window.localStorage.getItem(eB),"tab"===e?"tab":eH}catch{return eH}}let eU=null,eK=new Set;function eq(){return null===eU&&(eU=e_()),eU}function eZ(){eK.forEach(e=>e())}function eV(e){if(null!==e.key&&e.key!==eB)return;let t=e_();t!==eU&&(eU=t,eZ())}function eJ(e){return 0===eK.size&&(window.addEventListener("storage",eV),eU=e_()),eK.add(e),()=>{eK.delete(e),0===eK.size&&window.removeEventListener("storage",eV)}}function eG(e){if(e!==eq()){eU=e;try{window.localStorage.setItem(eB,e)}catch{}eZ()}}function eY(){return(0,i.useSyncExternalStore)(eJ,eq,()=>eH)}var eX=n(21278),eQ=n(31590),e0=n(12545);function e1(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];(0,i.useEffect)(()=>{if(!t)return;let n=null,r=null,i=!1,s=null,a=()=>{null!==s&&(clearTimeout(s),s=null)},l=()=>{n&&(a(),n.classList.add("scrollbar-visible"))},o=()=>{n&&(a(),s=setTimeout(()=>{s=null,n?.classList.remove("scrollbar-visible")},500))},d=()=>{l(),o()},c=()=>{if(!i){if(!(n=e.current)){r=requestAnimationFrame(c);return}n.addEventListener("pointerenter",l),n.addEventListener("pointerleave",o),n.addEventListener("scroll",d)}};return c(),()=>{i=!0,null!==r&&cancelAnimationFrame(r),n?.removeEventListener("pointerenter",l),n?.removeEventListener("pointerleave",o),n?.removeEventListener("scroll",d),a(),n?.classList.remove("scrollbar-visible")}},[t,e])}let e2="/api/sessions/ui-state";async function e4(e){try{let t=await e.json();if(t&&"object"==typeof t&&"string"==typeof t.error)return t.error}catch{}return`HTTP ${e.status}`}function e8(e){return e instanceof Error?e.message:String(e)}async function e6(e){if(!e.ok)throw Error(await e4(e));let t=await e.json(),n=t&&"object"==typeof t?function(e){if(!k(e)||void 0!==e.version&&1!==e.version||void 0!==e.sessions&&!k(e.sessions)||void 0!==e.projects&&!k(e.projects))return null;let t=L(),n=e.revision;for(let[r,i]of("number"==typeof n&&Number.isSafeInteger(n)&&n>=0&&(t.revision=n),Object.entries(e.sessions??{}))){if(!w(r))continue;let e=function(e){if(!k(e))return null;let t={};return j(e.pinnedAt)&&(t.pinnedAt=e.pinnedAt),j(e.archivedAt)&&(t.archivedAt=e.archivedAt),void 0===t.pinnedAt&&void 0===t.archivedAt?null:t}(i);e&&(t.sessions[r]=e)}for(let[n,r]of Object.entries(e.projects??{})){if(!S(n))continue;let e=k(r)&&j(r.pinnedAt)&&S(r.root)?{pinnedAt:r.pinnedAt,root:r.root}:null;e&&(t.projects[n]=e)}if(Array.isArray(e.projectOrder)){let n=new Set,r=M(e.projectOrder.filter(e=>!(!S(e)||n.has(e))&&(n.add(e),!0)));r.length>0&&(t.projectOrder=r)}if(k(e.projectNames)){let n={},r=0,i=1;for(let[t,s]of Object.entries(e.projectNames)){let e=N(s);if(!S(t)||"string"!=typeof e)continue;let a=R(t,e);A(r+1,i+a)&&(n[t]=e,r++,i+=a)}r>0&&(t.projectNames=n)}if(k(e.readAt)){let n={};for(let[t,r]of Object.entries(e.readAt))w(t)&&j(r)&&(n[t]=r);let r=P(n);Object.keys(r).length>0&&(t.readAt=r)}return t}(t.state):null;if(!n)throw Error("Invalid session UI state response");return n}function e3(){let[e,t]=(0,i.useState)(null),n=(0,i.useRef)(null),r=(0,i.useCallback)(()=>{null!==n.current&&(clearTimeout(n.current),n.current=null)},[]),s=(0,i.useCallback)(()=>{r(),t(null)},[r]),a=(0,i.useCallback)(e=>{(r(),function(){try{return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}catch{return!1}}())?t(null):(t(e),n.current=setTimeout(()=>{n.current=null,t(null)},300))},[r]);return(0,i.useEffect)(()=>r,[r]),{phase:e,start:a,end:s}}var e5=n(47650);let e9={overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},e7={height:36,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12},te={padding:"6px 16px",borderRadius:6,fontSize:13},tt={...te,border:0,background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600},tn={...te,border:"1px solid var(--border)",background:"none",color:"var(--text-muted)"};async function tr(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);return r}async function ti(e,t){let n=await fetch("/api/cwd/browse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e,name:t})}),r=await n.json();if(!n.ok||r.error||!r.path)throw Error(r.error??`HTTP ${n.status}`);return r.path}function ts(){return(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function ta(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,r.jsx)("path",{d:"M2 9h12"}),(0,r.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function tl(e){let{onCancel:t,onSelect:n,initialPath:s,busy:a=!1,error:l}=e,{t:o}=(0,eX.s)(),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(""),[h,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(s??""),[x,b]=(0,i.useState)([]),[v,y]=(0,i.useState)(null),[k,j]=(0,i.useState)(null),[w,S]=(0,i.useState)(!0),[C,N]=(0,i.useState)(!1),[I,E]=(0,i.useState)(""),[$,T]=(0,i.useState)(null),[M,R]=(0,i.useState)(!1),A=(0,i.useRef)(!1),L=(0,i.useRef)(!1),P=(0,i.useRef)(null),z=(0,i.useRef)(!1),O=(0,i.useCallback)(async e=>{S(!0),j(null);try{let t=await tr(e),n=t.path??e??"/";return p(n),m(t.parentPath??null),f(n),b(t.directories??[]),y(t.drives??null),n}catch(e){return j(e instanceof Error?e.message:String(e)),null}finally{S(!1)}},[]);(0,i.useEffect)(()=>{c(document.body),O(s||void 0)},[s,O]),(0,i.useEffect)(()=>(z.current=!0,()=>{z.current=!1}),[]),(0,i.useEffect)(()=>{(k||l)&&P.current?.focus()},[k,l]);let W=()=>{M||(N(!1),E(""),T(null))},F=async()=>{let e=I.trim();if(u&&e&&!M){R(!0),T(null);try{let t=await ti(u,e);N(!1),E(""),await O(t)}catch(e){T(e instanceof Error?e.message:String(e))}finally{R(!1)}}},D=g.trim(),B=D!==u,H=!!D&&!a&&!w,_=!!u&&!B&&!a&&!w,U=!!h||/^[a-zA-Z]:[\\/]?$/.test(u),K=async()=>{let e=B?await O(D):u;e&&z.current&&n(e)};return d?(0,e5.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":o("directoryPicker.selectDirectory"),onPointerDown:e=>{A.current=e.target===e.currentTarget},onClick:e=>{let n=A.current;A.current=!1,n&&e.target===e.currentTarget&&!a&&t()},onPointerCancel:()=>{A.current=!1},onKeyDown:e=>{!e.nativeEvent.isComposing&&229!==e.keyCode&&("Escape"!==e.key||a||t())},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{...e9,position:"relative",width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:o("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:t,disabled:a,title:o("i18n.close"),"aria-label":o("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:a?"default":"pointer",opacity:a?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=g.trim();t&&O(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void O(h??void 0),disabled:w||!U,title:o("directoryPicker.goToParent"),"aria-label":o("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:U?"pointer":"default",opacity:U?1:.45},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:o("directoryPicker.directoryPath")}),(0,r.jsx)("input",{ref:P,className:"directory-picker-path",id:"directory-path",type:"text",value:g,placeholder:o("directoryPicker.pathPlaceholder"),autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{f(e.target.value),j(null)},style:{...e7,minWidth:0,flex:1}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:w||!g.trim(),title:o("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:w||!g.trim()?"default":"pointer",opacity:w||!g.trim()?.6:1},children:o("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:o("directoryPicker.loadingDirectories")}):null!==v?(0,r.jsx)(r.Fragment,{children:v.length>0?v.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void O(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(ta,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:o("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void O(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(ts,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:o("directoryPicker.noSubdirectories")}),(k||l)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:k??l})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>{N(!0),T(null)},disabled:!_,style:{...tn,marginRight:"auto",opacity:_?1:.6,cursor:_?"pointer":"default"},children:o("directoryPicker.newDirectory")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:t,disabled:a,style:{...tn,cursor:a?"default":"pointer"},children:o("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>void K(),disabled:!H,title:B&&D?o("directoryPicker.selectTypedPath",{path:D}):o("directoryPicker.selectCurrentDirectory"),style:{...tt,opacity:H?1:.6,cursor:H?"pointer":"default"},children:o(a?"i18n.checking":"directoryPicker.selectThisFolder")})]}),C&&(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:12,background:"rgba(0,0,0,0.35)"},onPointerDown:e=>{L.current=e.target===e.currentTarget},onClick:e=>{let t=L.current;L.current=!1,t&&e.target===e.currentTarget&&W()},onPointerCancel:()=>{L.current=!1},onKeyDown:e=>{e.stopPropagation(),e.nativeEvent.isComposing||229===e.keyCode||"Escape"===e.key&&W()},children:(0,r.jsxs)("form",{role:"dialog","aria-modal":"true","aria-label":o("directoryPicker.createDirectory"),onSubmit:e=>{e.preventDefault(),F()},style:{...e9,width:400,maxWidth:"100%"},children:[(0,r.jsx)("div",{style:{padding:"12px 18px",borderBottom:"1px solid var(--border)",color:"var(--text)",fontSize:15,fontWeight:700},children:o("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:o("directoryPicker.directoryName")}),(0,r.jsx)("input",{id:"new-directory-name",value:I,autoFocus:!0,autoComplete:"off",spellCheck:!1,placeholder:o("directoryPicker.directoryNamePlaceholder"),onChange:e=>{E(e.target.value),T(null)},disabled:M,className:"directory-picker-path",style:{...e7,width:"100%",boxSizing:"border-box"}}),$&&(0,r.jsx)("div",{style:{marginTop:7,color:"#dc2626",fontSize:11,lineHeight:1.35},children:$}),(0,r.jsxs)("div",{style:{display:"flex",gap:6,marginTop:10},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:M||!I.trim(),style:{...tt,flex:1,opacity:M?.65:1,cursor:M||!I.trim()?"default":"pointer"},children:o(M?"directoryPicker.creating":"directoryPicker.create")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:W,disabled:M,style:{...tn,flex:1,cursor:M?"default":"pointer"},children:o("i18n.cancel")})]})]})]})})]})}),d):null}var to=n(46599),td=n(65748),tc=n(7834);let tu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function tp(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Math.random,r=4*e.length;if(t>=r)return e;let i=Math.floor(t/r*e.length),s="";for(let t=0;t<e.length;t++){let r=e[t];s+=" "===r||t<i?r:tu[Math.floor(n()*tu.length)]}return s}function th(e){let{onWidthChange:t}=e,{t:n}=(0,eX.s)(),[s,a]=(0,i.useState)(!1),l=(0,i.useRef)(null),o="0.17.3",d="1.5.2",c=function(e){let[t,n]=(0,i.useState)(e),r=(0,i.useRef)(e);return(0,i.useEffect)(()=>{if(r.current===e)return;if(r.current=e,window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return void n(e);let t=4*e.length,i=0,s=0,a=()=>{n(tp(e,i+=1)),i<t&&(s=requestAnimationFrame(a))};return n(tp(e,0)),s=requestAnimationFrame(a),()=>cancelAnimationFrame(s)},[e]),t}(s?`${o??"0.0.0"}p${d??"0.0.0"}`:"Pi Web");return(0,i.useLayoutEffect)(()=>{t?.()},[c.length,t]),(0,i.useEffect)(()=>()=>{l.current&&clearTimeout(l.current)},[]),(0,r.jsx)("button",{type:"button",className:`sidebar-brand${s?" is-version":""}`,"aria-label":n("sidebar.brandLabel",{app:o??"0.0.0",pi:d??"0.0.0"}),onClick:()=>{(l.current&&clearTimeout(l.current),l.current=null,s)?a(!1):(a(!0),l.current=setTimeout(()=>{l.current=null,a(!1)},3e3))},children:c})}var tm=n(2730),tg=n(1518);let tf={desktop:32,mobile:48};function tx(e,t,n,r){return Math.hypot(n-e,r-t)}function tb(e){return e.getClientRects().length>0}var tv=n(72451);function ty(e){let t=(0,tg.d)(e.firstMessage)??e.firstMessage;return e.name||t.slice(0,50)||e.id.slice(0,12)}function tk(e){return e.nativeEvent.isComposing||229===e.keyCode}function tj(e){let{rows:t,layout:n,emptyLabel:s,loading:a,error:l,renamingRootId:o,renamingProjectKey:d,confirmDeleteRootId:c,activeMenuRowKey:u,reveal:p}=e,{t:h}=(0,eX.s)(),m=(0,i.useRef)(e);m.current=e;let g=(0,i.useRef)(null),f=(0,i.useRef)(null),x=(0,i.useRef)(null),b=(0,i.useRef)(null);e1(f);let[v,y]=(0,i.useState)(0),[k,j]=(0,i.useState)(0),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(()=>Date.now()),I=(0,i.useRef)(null),E=(0,i.useCallback)(()=>{null===I.current&&(I.current=requestAnimationFrame(()=>{I.current=null;let e=f.current;e&&y(e.scrollTop)}))},[]);(0,i.useLayoutEffect)(()=>{let e=f.current;if(!e)return;let t=()=>{let t=`${Math.max(0,e.offsetWidth-e.clientWidth)}px`;e.style.setProperty("--session-tree-scrollbar",t),e.offsetWidth>0&&e.closest(".session-sidebar")?.style.setProperty("--session-tree-scrollbar",t)};if(t(),j(e.clientHeight),y(e.scrollTop),"u"<typeof ResizeObserver)return;let n=new ResizeObserver(()=>{t(),j(e.clientHeight),y(e.scrollTop)});return n.observe(e),()=>n.disconnect()},[]),(0,i.useEffect)(()=>()=>{null!==I.current&&cancelAnimationFrame(I.current)},[]),(0,i.useEffect)(()=>{let e=window.setInterval(()=>N(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let $=(0,i.useCallback)(e=>{let t=e.target instanceof Element?e.target.closest("[data-row-key]"):null;S(t?.getAttribute("data-row-key")??null)},[]),T=(0,i.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||S(null)},[]),M=(0,i.useMemo)(()=>(function(e,t){let n=D[t],r=Array(e.length+1);r[0]=0;for(let t=0;t<e.length;t++)r[t+1]=r[t]+n[e[t].kind];return r})(t,n),[t,n]),R=!!e.onMoveGroup,A=(0,i.useMemo)(()=>{let e={pinned:0,other:0};for(let n of t)"group"===n.kind&&e[n.project.pinned?"pinned":"other"]++;return e},[t]),L=function(e){let{rows:t,offsets:n,enabled:r}=e,s=(0,i.useRef)(e);s.current=e;let a=(0,i.useMemo)(()=>(function(e,t){let n=[],r=0;for(;r<e.length;){var i;let s=e[r];if("group"!==s.kind){r++;continue}let a=r;for(;a>0&&"spacer"===e[a-1].kind;)a--;let l=r+1;for(;l<e.length&&("group-more"===(i=e[l]).kind||"group-empty"===i.kind||"session"===i.kind&&"group"===i.context);)l++;let o=l;for(;o<e.length&&"spacer"===e[o].kind;)o++;n.push({key:s.project.key,pinned:s.project.pinned,top:t[r],bottom:t[l],gapAbove:t[r]-t[a],gapBelow:t[o]-t[l]}),r=l}return n})(t,n),[t,n]),l=(0,i.useRef)(a);l.current=a;let o=(0,i.useRef)(null),d=(0,i.useRef)(0),[c,u]=(0,i.useState)(null),p=(0,i.useMemo)(()=>{let e=e=>{u("armed"===e.phase||"dragging"===e.phase?{projectKey:e.projectKey,phase:e.phase,drop:e.drop}:null)},t=e=>{let t=s.current.innerRef.current;return t?function(e,t,n){let r=e.find(e=>e.key===t);if(!r)return null;let i=e.filter(e=>e.pinned===r.pinned),s=i.indexOf(r),a=i.filter(e=>e!==r);if(0===a.length)return null;let l=a.filter(e=>(e.top+e.bottom)/2<n).length;if(l===s)return null;let o=a[a.length-1],d=Math.max(3,l<a.length?a[l].top-a[l].gapAbove/2:o.bottom+o.gapBelow/2);return l>0?{anchorKey:a[l-1].key,position:"after",lineY:d}:{anchorKey:a[0].key,position:"before",lineY:d}}(l.current,e.projectKey,e.clientY-t.getBoundingClientRect().top):null},n=()=>{let e=o.current,t=s.current.ghostRef.current,n=s.current.treeRef.current,r=s.current.innerRef.current,i=s.current.scrollRef.current;if(!e?.ghost||!t||!n||!i)return;let a=n.getBoundingClientRect().top,l=i.getBoundingClientRect(),d=t.offsetHeight,c=function(e){let{pointerY:t,lineY:n,ghostHeight:r,pointerGap:i,lineGap:s,minTop:a,maxTop:l}=e,o=Math.max(a,l),d=t-i-r,c=null!==n&&n>=a&&n<=o+r?n:null,u=e=>e>=a&&e<=o,p=e=>null!==c&&e>c-s-r&&e<c+s,h=null===c?[d,a,t+i,o]:[d,c-s-r,a,t+i,c+s,o],m=e=>{let t=null;for(let n of h)e(n)&&(null===t||Math.abs(n-d)<Math.abs(t-d))&&(t=n);return t};return m(e=>u(e)&&!(e>d&&e<t+i)&&!p(e))??m(e=>u(e)&&!p(e))??Math.min(o,Math.max(a,d))}({pointerY:e.clientY,lineY:e.drop&&r?r.getBoundingClientRect().top+e.drop.lineY:null,ghostHeight:d,pointerGap:"mouse"===e.pointerType?8:28,lineGap:8,minTop:l.top,maxTop:l.bottom-d});t.style.top=`${c-a}px`,t.style.left=`${e.ghost.left}px`},r=e=>{null!==e.timer&&window.clearTimeout(e.timer),null!==e.frame&&cancelAnimationFrame(e.frame),e.timer=null,e.frame=null,s.current.scrollRef.current?.removeEventListener("scroll",p);try{e.element.hasPointerCapture(e.pointerId)&&e.element.releasePointerCapture(e.pointerId)}catch{}},i=()=>{let e=o.current;e&&(o.current=null,r(e),window.removeEventListener("pointermove",f,!0),window.removeEventListener("pointerup",x,!0),window.removeEventListener("pointercancel",b,!0),window.removeEventListener("pointerdown",v,!0),window.removeEventListener("keydown",y,!0),window.removeEventListener("contextmenu",k,!0),window.removeEventListener("blur",j),document.removeEventListener("visibilitychange",w),u(null))},a=()=>{let e=o.current;if(e){if("armed"!==e.phase&&"dragging"!==e.phase){"pending"===e.phase&&i();return}e.phase="cancelled",e.drop=null,r(e),u(null)}},c=function(){var r;let i=arguments.length>0&&void 0!==arguments[0]&&arguments[0],l=o.current;if(!l||"dragging"!==l.phase)return;let d=s.current.scrollRef.current;if(!d||!tb(d))return void a();let c=t(l),u=i||c!==(r=l.drop)&&(null===c||null===r||c.anchorKey!==r.anchorKey||c.position!==r.position||c.lineY!==r.lineY);l.drop=c,n(),u&&e(l)};function p(){c()}let h=()=>{let e=o.current;if(!e||"dragging"!==e.phase)return;e.frame=null;let t=s.current.scrollRef.current;if(!t||!tb(t))return void a();let n=t.getBoundingClientRect(),r=function(e,t,n,r){let i=Math.min(r,(n-t)/2);if(!(i>0)||!Number.isFinite(e))return 0;let s=e=>Math.ceil(14*Math.min(1,e/i));return e<t+i?-s(t+i-e):e>n-i?s(e-(n-i)):0}(e.clientY,n.top,n.bottom,tf[s.current.layout]);if(0!==r){let n=Math.min(Math.max(0,(s.current.offsets[s.current.offsets.length-1]??0)-t.clientHeight),Math.max(0,t.scrollTop+r));n!==t.scrollTop&&(t.scrollTop=n,e.expectedScrollTop=t.scrollTop,c())}o.current===e&&"dragging"===e.phase&&(e.frame=requestAnimationFrame(h))},m=e=>{let t=s.current.scrollRef.current,n=s.current.treeRef.current;if(!t||!n||!tb(t)||!e.element.isConnected)return void a();if(e.phase="dragging","touch"!==e.pointerType)try{e.element.setPointerCapture(e.pointerId)}catch{}e.ghost={left:e.element.getBoundingClientRect().left-n.getBoundingClientRect().left+4},e.expectedScrollTop=t.scrollTop,t.addEventListener("scroll",p,{passive:!0}),e.frame=requestAnimationFrame(h),c(!0)},g=()=>{let t=o.current;t&&"pending"===t.phase&&(t.timer=null,t.phase="armed",t.armX=t.clientX,t.armY=t.clientY,t.expectedScrollTop=s.current.scrollRef.current?.scrollTop??0,e(t))};function f(e){let t=o.current;if(!t||e.pointerId!==t.pointerId)return;if("mouse"===t.pointerType&&0===e.buttons)return void i();t.clientX=e.clientX,t.clientY=e.clientY;let n=tx(t.startX,t.startY,e.clientX,e.clientY);switch(t.phase){case"pending":"mouse"===t.pointerType?n>=4&&m(t):n>8&&i();break;case"armed":tx(t.armX,t.armY,e.clientX,e.clientY)>=4&&m(t);break;case"dragging":c()}}function x(e){let n=o.current;if(n&&e.pointerId===n.pointerId){if("dragging"===n.phase){n.clientX=e.clientX,n.clientY=e.clientY;let r=t(n);r&&s.current.onMove(n.projectKey,r.anchorKey,r.position)}"pending"!==n.phase&&(d.current=e.timeStamp+600),i()}}function b(e){o.current&&e.pointerId===o.current.pointerId&&i()}function v(e){o.current&&e.pointerId!==o.current.pointerId&&a()}function y(e){let t=o.current;t&&"Escape"===e.key&&("armed"===t.phase||"dragging"===t.phase)&&(e.preventDefault(),e.stopPropagation(),a())}function k(e){let t=o.current;if(t){if("pending"===t.phase)return void i();e.preventDefault(),e.stopPropagation()}}function j(){i()}function w(){"hidden"===document.visibilityState&&i()}return{handlers:{onPointerDown(e,t){if(!s.current.enabled||o.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};o.current=r,window.addEventListener("pointermove",f,!0),window.addEventListener("pointerup",x,!0),window.addEventListener("pointercancel",b,!0),window.addEventListener("pointerdown",v,!0),window.addEventListener("keydown",y,!0),window.addEventListener("contextmenu",k,!0),window.addEventListener("blur",j),document.addEventListener("visibilitychange",w),"mouse"!==e.pointerType&&(r.timer=window.setTimeout(g,350))},onTouchMove(e){let t=o.current;if(!t||"armed"!==t.phase&&"dragging"!==t.phase)return;if(e.cancelable)return void e.preventDefault();let n=s.current.scrollRef.current;n&&n.scrollTop!==t.expectedScrollTop&&i()}},cancel:a,teardown:i,updateDrag:c,placeGhost:n}},[]);(0,i.useLayoutEffect)(()=>{let e=o.current;e&&("armed"===e.phase||"dragging"===e.phase)&&(t.some(t=>"group"===t.kind&&t.project.key===e.projectKey)?p.updateDrag():p.cancel())},[t,n,p]),(0,i.useEffect)(()=>{r||p.cancel()},[r,p]);let h=c?.phase==="dragging";(0,i.useLayoutEffect)(()=>{h&&p.placeGhost()},[h,p]),(0,i.useEffect)(()=>()=>p.teardown(),[p]);let m=(0,i.useCallback)(e=>{let t=d.current;0===t||(d.current=0,e.timeStamp>t||(e.preventDefault(),e.stopPropagation()))},[]),g=(0,i.useCallback)(()=>{d.current=0},[]);return{view:(0,i.useMemo)(()=>{if(!c)return null;let e="dragging"===c.phase?a.find(e=>e.key===c.projectKey)??null:null;return{...c,source:e}},[c,a]),handlers:p.handlers,onClickCapture:m,onPointerDownCapture:g}}({rows:t,offsets:M,layout:n,enabled:R&&!a,scrollRef:f,innerRef:x,treeRef:g,ghostRef:b,onMove:(e,t,n)=>m.current.onMoveGroup?.(e,t,n)}),P=L.view,z=P?`group:${P.projectKey}`:null,[O,W]=(0,i.useState)(null),F=p&&p.id!==O?p:null,H=F?.rowKey??null,_=(0,i.useMemo)(()=>{let e=[];return t.forEach((t,n)=>{t.key===w||t.key===u||t.key===H||t.key===z||"session"===t.kind&&(t.family.root.id===o||t.family.root.id===c)?e.push(n):"group"===t.kind&&t.project.key===d&&e.push(n)}),e},[t,w,u,H,z,o,d,c]),U=(0,i.useMemo)(()=>a?[]:function(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],s=Math.max(0,e.length-1),a=Number.isFinite(t)?Math.max(0,t):0,l=Number.isFinite(n)&&n>0?n:600,o=Number.isFinite(r)&&r>0?r:0,d=a-o,c=a+l+o,u=0,p=s;for(;u<p;){let t=u+p>>>1;e[t+1]>d?p=t:u=t+1}let h=u;for(u=h,p=s;u<p;){let t=u+p>>>1;e[t]>=c?p=t:u=t+1}let m=u,g=[];for(let e=h;e<m;e++)g.push(e);if(0===i.length)return g;let f=i.filter(e=>Number.isInteger(e)&&e>=0&&e<s&&(e<h||e>=m));return 0===f.length?g:[...new Set([...g,...f])].sort((e,t)=>e-t)}(M,v,k,240,_),[a,M,v,k,_]),K=(0,i.useRef)(null),q=(0,i.useRef)(null),Z=(0,i.useCallback)((e,t,n,r)=>{let i=document.activeElement===r,s=i&&r.matches(":focus-visible");K.current={rowKey:e,fallbackKey:t===B?"pinned-header":`group:${t}`,focus:i,scroll:"less"===n||s},"more"===n?m.current.onShowMore(t):m.current.onShowLess(t)},[]);(0,i.useLayoutEffect)(()=>{let e=K.current;if(!e)return;K.current=null;let n=f.current,r=t.findIndex(t=>t.key===e.rowKey);if(r<0&&(r=t.findIndex(t=>t.key===e.fallbackKey)),e.scroll&&n&&r>=0){let e=ed(M,r,n.scrollTop,n.clientHeight);null!==e&&(n.scrollTop=e),y(n.scrollTop)}e.focus&&(q.current={rowKey:e.rowKey,fallbackKey:e.fallbackKey,tries:0})},[t,M]);let V=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{if(!F)return;let e=t.findIndex(e=>e.key===F.rowKey),n=function(e,t,n,r){let i=e?.id===t.id?e:{id:t.id,misses:0};if(!(r-t.at<=3e3))return{misses:i,action:"drop"};if(n)return{misses:i,action:"reveal"};let s={id:t.id,misses:i.misses+1};return{misses:s,action:s.misses>=3?"drop":"wait"}}(V.current,F,e>=0,Date.now());if(V.current=n.misses,"wait"!==n.action){if("reveal"===n.action){let t=f.current;if(t&&t.getClientRects().length>0){let n=ed(M,e,t.scrollTop,t.clientHeight,F.block);null!==n&&(t.scrollTop=n),y(t.scrollTop)}F.takeFocusFrom&&(q.current={rowKey:F.rowKey,fallbackKey:F.rowKey,tries:0,takeFocusFrom:F.takeFocusFrom})}W(F.id),m.current.onRevealHandled?.(F.id)}},[F,t,M]),(0,i.useLayoutEffect)(()=>{let e=q.current;if(!e)return;let t=document.activeElement;if(t&&t!==document.body&&document.contains(t)&&!e.takeFocusFrom?.(t)){q.current=null;return}let n=f.current,r=e=>n?.querySelector(`[data-row-key="${CSS.escape(e)}"]`)??null,i=r(e.rowKey),s=i?.querySelector('[data-more-action="more"]')??i?.querySelector("a[href], button")??r(e.fallbackKey)?.querySelector("a[href], button");s?(s.focus({preventScroll:!0}),q.current=null):++e.tries>2&&(q.current=null)},[U]);let J=t.some(e=>"session"===e.kind||"group"===e.kind||"archive-group"===e.kind),G=!a&&!l&&null!==s&&!J,Y=P?.source??null,X=P?.drop?.lineY??null,Q=P?.phase==="dragging"?t.find(e=>"group"===e.kind&&e.project.key===P.projectKey)?.project??null:null;return(0,r.jsxs)("div",{ref:g,className:`session-tree${"mobile"===n?" is-mobile":""}${Q?" is-group-dragging":""}`,children:[a&&(0,r.jsx)("div",{className:"session-tree-message",children:h("sidebar.loading")}),l&&(0,r.jsx)("div",{className:"session-tree-message is-error",children:l}),G&&(0,r.jsx)("div",{className:"session-tree-message",children:s}),(0,r.jsx)("div",{ref:f,className:"session-tree-scroll scrollbar-subtle",onScroll:E,onFocus:$,onBlur:T,onPointerDownCapture:L.onPointerDownCapture,onClickCapture:L.onClickCapture,children:!a&&(0,r.jsxs)("div",{ref:x,className:"session-tree-inner",style:{height:M[t.length]},children:[U.map(e=>{let i=t[e];if("spacer"===i.kind)return null;let s=M[e],a=M[e+1]-s,l=i.key===u;if("session"===i.kind)return(0,r.jsx)(tS,{row:i,layout:n,top:s,height:a,now:C,renaming:i.family.root.id===o,confirming:i.family.root.id===c,menuOpen:l,handlers:m},i.key);if("archive-group"===i.kind)return(0,r.jsx)(tT,{row:i,top:s,height:a,menuOpen:l,handlers:m},i.key);if("group"===i.kind){let e=i.project.key===d;return(0,r.jsx)(tE,{row:i,top:s,height:a,menuOpen:l,renaming:e,canDrag:R&&!e&&A[i.project.pinned?"pinned":"other"]>1,dragPhase:P?.projectKey===i.project.key?P.phase:null,drag:L.handlers,handlers:m},i.key)}return(0,r.jsx)(t$,{row:i,top:s,height:a,handlers:m,onMoreAction:Z},i.key)}),Y&&(0,r.jsx)("div",{className:"session-tree-drag-source","aria-hidden":"true",style:{top:Y.top,height:Y.bottom-Y.top}}),null!==X&&(0,r.jsx)("div",{className:"session-tree-drop-line","aria-hidden":"true",style:{top:X}})]})}),Q&&(0,r.jsx)("div",{ref:b,className:"session-tree-drag-ghost","aria-hidden":"true",children:(0,r.jsx)("span",{className:"session-tree-group-name",children:Q.name})})]})}function tw(e,t){return{top:e,height:t}}let tS=(0,i.memo)(function(e){let t,n,{row:i,layout:s,top:a,height:l,now:o,renaming:d,confirming:c,menuOpen:u,handlers:h}=e,{locale:m,t:g}=(0,eX.s)(),{family:f,context:x,status:b}=i,v=f.root,y=ty(v),k=new Date(o),j=["session-tree-row session-tree-session",b.selected?"is-selected":"",b.running?"is-running":"","archive"===x?"is-archived":"",u?"is-menu-open":"",c?"is-confirming":"",d?"is-renaming":""].filter(Boolean).join(" ");if(c){let e=y.slice(0,22)+(y.length>22?"…":"");return(0,r.jsx)("div",{className:j,style:tw(a,l),"data-row-key":i.key,onKeyDown:e=>{"Escape"!==e.key||tk(e)||(e.preventDefault(),e.stopPropagation(),h.current.onDeleteCancel())},children:(0,r.jsx)(tN,{label:g("sidebar.deleteSession",{title:e}),deleteLabel:g("sidebar.delete"),cancelLabel:g("sidebar.cancel"),onConfirm:e=>{e.stopPropagation(),h.current.onDeleteConfirm(f,e)},onCancel:e=>{e.stopPropagation(),h.current.onDeleteCancel()}})})}if(d)return(0,r.jsx)("div",{className:j,style:tw(a,l),"data-row-key":i.key,children:(0,r.jsx)(tC,{initialValue:y,label:g("sidebar.rename"),onCommit:e=>h.current.onRenameCommit(f,e),onCancel:()=>h.current.onRenameCancel()})});let w=v.isWorktree&&v.branch?v.branch:null,S=v.name&&v.relation?.kind==="fork"?eg(v.name):null,C=v.detailsPending?"…":g("sidebar.messagesCount",{count:v.messageCount}),N=`${y}
2
+ ${C} \xb7 ${(0,tm.fw)(v.modified,m,k)}${w?` \xb7 ⑂ ${w}`:""}`,I="";b.awaiting?(t=(0,r.jsx)("span",{className:"session-tree-awaiting",role:"img","aria-label":g("sidebar.agentAwaitingInput")}),I=" is-awaiting",n=g("sidebar.agentAwaitingInput")):b.running?(t=(0,r.jsx)(tv.Nl,{size:12,label:g("sidebar.agentRunning")}),I=" is-running",n=g("sidebar.agentRunning")):b.unread?(t=(0,r.jsx)("span",{className:"session-tree-unread",role:"img","aria-label":g("sidebar.newSessionActivity")}),I=" is-unread",n=g("sidebar.newActivity")):t="pinned"===x?(0,r.jsx)("span",{className:"session-tree-project",children:i.project.name}):(0,tm.Rg)(f.latestModified,m,k);let E="desktop"===s&&("archive"===x||!b.running),$=(0,r.jsxs)(r.Fragment,{children:[S?(0,r.jsxs)("span",{className:"session-tree-title has-fork-suffix",children:[(0,r.jsx)("span",{className:"session-tree-title-base",children:S.base}),(0,r.jsx)("span",{className:"session-tree-title-suffix",children:S.suffix})]}):(0,r.jsx)("span",{className:"session-tree-title",children:y}),w&&(0,r.jsxs)("span",{className:"session-tree-branch",children:[(0,r.jsx)(tv.OK,{size:10,className:"session-tree-branch-icon"}),w]}),!0===v.ephemeral&&(0,r.jsx)("span",{className:"session-tree-branch",title:g("ephemeral.badge"),"aria-label":g("ephemeral.badge"),style:{color:"var(--text-dim)"},children:"◌"}),(0,r.jsx)("span",{className:`session-tree-meta${I}`,title:n,children:t})]});return(0,r.jsxs)("div",{className:j,style:tw(a,l),"data-row-key":i.key,onClick:()=>h.current.onSelectFamily(f),onContextMenu:e=>h.current.onRowContextMenu(i,e),children:[b.transient?(0,r.jsx)("button",{type:"button",className:"session-tree-main",title:N,"aria-current":b.selected?"true":void 0,children:$}):(0,r.jsx)("a",{className:"session-tree-main",href:p(v.id),title:N,"aria-current":b.selected?"true":void 0,onClick:e=>{e.stopPropagation(),e.defaultPrevented||0!==e.button||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||(e.preventDefault(),h.current.onSelectFamily(f))},children:$}),!b.transient&&(0,r.jsxs)("span",{className:"session-tree-actions",children:[E&&("archive"===x?(0,r.jsx)("button",{type:"button",className:"session-tree-action session-tree-quick-action","aria-label":g("sidebar.restore"),title:g("sidebar.restore"),onClick:e=>{e.stopPropagation(),h.current.onRestoreFamily(f)},children:(0,r.jsx)(tv.G2,{size:13})}):(0,r.jsx)("button",{type:"button",className:"session-tree-action session-tree-quick-action","aria-label":g("sidebar.archive"),title:g("sidebar.archive"),onClick:e=>{e.stopPropagation(),h.current.onArchiveFamily(f)},children:(0,r.jsx)(tv.kb,{size:13})})),(0,r.jsx)("button",{type:"button",className:`session-tree-action session-tree-more-action${u?" is-active":""}`,"aria-label":g("sidebar.moreActions"),title:g("sidebar.moreActions"),"aria-haspopup":"menu","aria-expanded":u,onClick:e=>{let t;e.stopPropagation();let n=e.currentTarget;h.current.onOpenRowMenu(i,{kind:"rect",rect:{left:(t=n.getBoundingClientRect()).left,top:t.top,right:t.right,bottom:t.bottom},align:"end"},n)},children:(0,r.jsx)(tv.Z4,{size:14})})]})]})});function tC(e){let{initialValue:t,label:n,maxLength:s,onCommit:a,onCancel:l}=e,[o,d]=(0,i.useState)(t),c=(0,i.useRef)(null),u=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=c.current;e&&(e.focus(),e.select())},[]);let p=e=>{u.current||(u.current=!0,a(e))};return(0,r.jsx)("input",{ref:c,className:"session-tree-rename",value:o,"aria-label":n,maxLength:s,onChange:e=>d(e.target.value),onBlur:e=>p(e.currentTarget.value),onKeyDown:e=>{if(!tk(e)){if("Enter"===e.key)e.preventDefault(),p(e.currentTarget.value);else if("Escape"===e.key){if(e.preventDefault(),e.stopPropagation(),u.current)return;u.current=!0,l()}}}})}function tN(e){let{label:t,deleteLabel:n,cancelLabel:s,onConfirm:a,onCancel:l}=e,o=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=document.activeElement;e&&e!==document.body||o.current?.focus()},[]),(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"session-tree-confirm-text",children:t}),(0,r.jsxs)("button",{type:"button",className:"session-tree-confirm-delete",onClick:a,children:[(0,r.jsx)(tv.uc,{size:12}),n]}),(0,r.jsx)("button",{ref:o,type:"button",className:"session-tree-confirm-cancel",onClick:l,children:s})]})}function tI(e){let{running:t,awaiting:n=0,unread:i,t:s}=e;return 0===t&&0===n&&0===i?null:(0,r.jsxs)("span",{className:"session-tree-summary",children:[t>0&&(0,r.jsxs)("span",{className:"session-tree-summary-running",role:"img",title:s("sidebar.agentRunning"),"aria-label":`${s("sidebar.agentRunning")} (${t})`,children:[(0,r.jsx)(tv.Nl,{size:10}),t]}),n>0&&(0,r.jsxs)("span",{className:"session-tree-summary-awaiting",role:"img",title:s("sidebar.agentAwaitingInput"),"aria-label":`${s("sidebar.agentAwaitingInput")} (${n})`,children:[(0,r.jsx)("span",{className:"session-tree-summary-dot is-awaiting"}),n]}),i>0&&(0,r.jsxs)("span",{className:"session-tree-summary-unread",role:"img",title:s("sidebar.newSessionActivity"),"aria-label":`${s("sidebar.newSessionActivity")} (${i})`,children:[(0,r.jsx)("span",{className:"session-tree-summary-dot"}),i]})]})}let tE=(0,i.memo)(function(e){let{row:t,top:n,height:s,menuOpen:a,renaming:l,canDrag:o,dragPhase:d,drag:c,handlers:u}=e,{t:p}=(0,eX.s)(),{project:h,expanded:m}=t,g=(0,i.useRef)(null),f=["session-tree-row session-tree-group",h.current?"is-current":"",a?"is-active":"","armed"===d?"is-drag-armed":""].filter(Boolean).join(" ");return((0,i.useEffect)(()=>{let e=g.current;if(!o||!e)return;let t=e=>c.onTouchMove(e);return e.addEventListener("touchmove",t,{passive:!1}),()=>e.removeEventListener("touchmove",t)},[o,c]),l)?(0,r.jsx)("div",{ref:g,className:`${f} is-renaming`,style:tw(n,s),"data-row-key":t.key,children:(0,r.jsx)(tC,{initialValue:h.name,label:p("sidebar.projectName"),maxLength:80,onCommit:e=>u.current.onRenameProjectCommit(h,e),onCancel:()=>u.current.onRenameProjectCancel()})}):(0,r.jsxs)("div",{ref:g,className:f,style:tw(n,s),"data-row-key":t.key,onPointerDown:o?e=>c.onPointerDown(e,h.key):void 0,children:[(0,r.jsxs)("button",{type:"button",className:"session-tree-group-toggle","aria-expanded":m,title:h.root,onClick:e=>u.current.onToggleGroup(h.key,e.altKey),children:[(0,r.jsx)(tv.zp,{size:12,strokeWidth:3,className:`session-tree-chevron${m?" is-open":""}`}),(0,r.jsx)("span",{className:"session-tree-group-name",children:h.name}),h.pinned&&(0,r.jsx)(tv.ts,{size:10,className:"session-tree-group-pin",label:p("sidebar.pinnedProject")}),!m&&(0,r.jsx)(tI,{running:t.running,awaiting:t.awaiting,unread:t.unread,t:p})]}),(0,r.jsxs)("span",{className:"session-tree-group-actions",children:[(0,r.jsx)("button",{type:"button",className:"session-tree-group-action","aria-label":p("sidebar.newSessionInProject",{name:h.name}),title:p("sidebar.newSessionInProject",{name:h.name}),onClick:e=>{e.stopPropagation(),u.current.onGroupNew(h)},children:(0,r.jsx)(tv.c1,{size:13})}),(0,r.jsx)("button",{type:"button",className:`session-tree-group-action${a?" is-active":""}`,"aria-label":p("sidebar.projectActions",{name:h.name}),title:p("sidebar.projectActions",{name:h.name}),"aria-haspopup":"menu","aria-expanded":a,onClick:e=>{e.stopPropagation(),u.current.onGroupMenu(h,e.currentTarget)},children:(0,r.jsx)(tv.Z4,{size:13})})]})]})}),t$=(0,i.memo)(function(e){let{row:t,top:n,height:i,handlers:s,onMoreAction:a}=e,{t:l}=(0,eX.s)(),o=tw(n,i);switch(t.kind){case"pinned-header":return(0,r.jsx)("div",{className:"session-tree-row session-tree-pinned-header",style:o,"data-row-key":t.key,children:(0,r.jsxs)("button",{type:"button",className:"session-tree-pinned-toggle","aria-expanded":!t.collapsed,onClick:()=>s.current.onTogglePinned(),children:[(0,r.jsx)(tv.zp,{size:12,strokeWidth:3,className:`session-tree-chevron${t.collapsed?"":" is-open"}`}),(0,r.jsx)("span",{className:"session-tree-pinned-label",children:l("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:l("sidebar.agentRunning"),"aria-label":`${l("sidebar.agentRunning")} (${t.running})`}),t.collapsed&&t.awaiting>0&&(0,r.jsx)("span",{className:"session-tree-pinned-dot is-awaiting",role:"img",title:l("sidebar.agentAwaitingInput"),"aria-label":`${l("sidebar.agentAwaitingInput")} (${t.awaiting})`}),t.collapsed&&t.unread>0&&(0,r.jsx)("span",{className:"session-tree-pinned-dot is-unread",role:"img",title:l("sidebar.newSessionActivity"),"aria-label":`${l("sidebar.newSessionActivity")} (${t.unread})`})]})});case"pinned-more":case"group-more":{let e="pinned-more"===t.kind?B:t.projectKey;return(0,r.jsxs)("div",{className:"session-tree-row session-tree-more",style:o,"data-row-key":t.key,children:[t.hidden>0&&(0,r.jsx)("button",{type:"button",className:"session-tree-more-toggle","data-more-action":"more",onClick:n=>a(t.key,e,"more",n.currentTarget),children:l("sidebar.showMore",{count:t.hidden})}),t.canShowLess&&(0,r.jsx)("button",{type:"button",className:"session-tree-more-toggle","data-more-action":"less",onClick:n=>a(t.key,e,"less",n.currentTarget),children:l("sidebar.showLess")})]})}case"group-empty":return(0,r.jsxs)("div",{className:"session-tree-row session-tree-group-empty",style:o,"data-row-key":t.key,children:[(0,r.jsx)("span",{className:"session-tree-group-empty-label",children:l("sidebar.noLiveSessions")}),!t.project.pinned&&(0,r.jsx)("button",{type:"button",className:"session-tree-more-toggle",onClick:()=>s.current.onPinEmptyGroup(t.project),children:l("sidebar.pinToKeep")})]});case"footer-open":return(0,r.jsx)("div",{className:"session-tree-row session-tree-footer",style:o,"data-row-key":t.key,children:(0,r.jsxs)("button",{type:"button",className:"session-tree-footer-button",onClick:e=>s.current.onOpenOtherProject(e.currentTarget),children:[(0,r.jsx)(tv.YP,{size:12}),(0,r.jsx)("span",{className:"session-tree-footer-label",children:l("sidebar.openOtherProject")})]})});case"footer-archived":return(0,r.jsx)("div",{className:"session-tree-row session-tree-footer",style:o,"data-row-key":t.key,children:(0,r.jsxs)("button",{type:"button",className:"session-tree-footer-button",onClick:()=>s.current.onOpenArchive(),children:[(0,r.jsx)(tv.kb,{size:12}),(0,r.jsx)("span",{className:"session-tree-footer-label",children:l("sidebar.archivedCount",{count:t.count})}),(0,r.jsx)(tv.zp,{size:10,className:"session-tree-footer-chevron"})]})})}}),tT=(0,i.memo)(function(e){let{row:t,top:n,height:i,menuOpen:s,handlers:a}=e,{t:l}=(0,eX.s)(),{project:o,expanded:d}=t,c=["session-tree-row session-tree-group session-tree-archive-group",o.current?"is-current":"",s?"is-active":""].filter(Boolean).join(" ");return(0,r.jsxs)("div",{className:c,style:tw(n,i),"data-row-key":t.key,children:[(0,r.jsxs)("button",{type:"button",className:"session-tree-group-toggle","aria-expanded":d,title:o.root,onClick:e=>a.current.onToggleArchiveGroup?.(o.key,e.altKey),children:[(0,r.jsx)(tv.zp,{size:12,strokeWidth:3,className:`session-tree-chevron${d?" is-open":""}`}),(0,r.jsx)("span",{className:"session-tree-group-name",children:o.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":l("sidebar.archivedProjectActions",{name:o.name}),title:l("sidebar.archivedProjectActions",{name:o.name}),"aria-haspopup":"menu","aria-expanded":s,onClick:e=>{e.stopPropagation(),a.current.onArchiveGroupMenu?.(o,e.currentTarget)},children:(0,r.jsx)(tv.Z4,{size:13})})})]})}),tM="[data-sidebar-menu-filter]",tR="[data-sidebar-menu-autofocus]",tA="button, input, textarea, select, a[href], [tabindex]";function tL(e){return i.Children.toArray(e).length>0}function tP(e){return"item"===e.type&&void 0!==e.checked}function tz(e){return e.getClientRects().length>0}function tO(e){return!e.disabled&&"true"!==e.getAttribute("aria-disabled")&&tz(e)}function tW(e){return Array.from(e.querySelectorAll("[data-sidebar-menu-item]")).filter(tO)}function tF(e){let t=Array.from(e.querySelectorAll(tR)).find(tO);if(t)return t;let n=tW(e);return n.length>0?n[0]:Array.from(e.querySelectorAll(tA)).filter(e=>e.tabIndex>=0&&tO(e))[0]??null}function tD(e){e.stopPropagation()}let tB={onClick:tD,onDoubleClick:tD,onMouseDown:tD,onMouseUp:tD,onPointerDown:tD,onPointerUp:tD,onKeyDown:tD,onKeyUp:tD,onFocus:tD,onBlur:tD,onContextMenu:function(e){e.preventDefault(),e.stopPropagation()}};function tH(e,t){return n=>{"Enter"!==n.key||n.nativeEvent.isComposing||229===n.keyCode||(n.preventDefault(),t(e,n.shiftKey))}}function t_(e){let{item:t,onActivate:n}=e,i=void 0!==t.checked,s=["sidebar-menu-item",i?"is-choice":"",t.danger?"is-danger":"",t.checked?"is-checked":""].filter(Boolean).join(" "),a=["sidebar-menu-label",t.mono?"is-mono":"",t.path?"is-path":""].filter(Boolean).join(" "),l=null;t.disabled&&t.disabledReason?l=(0,r.jsx)("span",{className:"sidebar-menu-note",children:t.disabledReason}):t.note?l=(0,r.jsx)("span",{className:"sidebar-menu-note",children:t.note}):t.shortcut&&(l=(0,r.jsx)("kbd",{className:"sidebar-menu-shortcut",children:t.shortcut}));let o=(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:tH(t,n),children:[(0,r.jsx)("span",{className:"sidebar-menu-icon",children:i?t.checked?(0,r.jsx)(tv.Sr,{size:13}):null:t.icon}),(0,r.jsx)("span",{className:a,children:t.path?(0,r.jsx)("span",{children:t.label}):t.label}),t.badge,l]}),d=t.secondary;return d?(0,r.jsxs)("div",{className:i?"sidebar-menu-row is-choice":"sidebar-menu-row",role:"none",children:[o,(0,r.jsx)("button",{type:"button",role:"menuitem","aria-label":d.label,"aria-disabled":!!d.disabled||void 0,tabIndex:-1,title:d.label,"data-sidebar-menu-item":"",className:d.danger?"sidebar-menu-secondary is-danger":"sidebar-menu-secondary",onClick:e=>n(d,e.shiftKey),onKeyDown:tH(d,n),children:d.icon})]}):o}function tU(e){var t;let n,{sheet:i,ariaLabel:s,title:a,items:l,filter:o,filterQuery:d="",onFilterQueryChange:c,children:u,cancelLabel:p,focusCancel:h=!1,width:m=208,classic:g=!1,footer:f,surfaceRef:x,onActivate:b,onClose:v}=e,y=tL(u),k=!y&&tL(f),j=void 0!==o&&!y&&function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;return(e??[]).filter(tP).length>=t}(l,o.minChoices),w=j?(t=l??[],(n=d.trim().toLowerCase())?t.filter(e=>"item"!==e.type||void 0===e.checked||[e.label,e.note,e.title].some(e=>e?.toLowerCase().includes(n))):[...t]):l??[],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)(t_,{item:e,onActivate:b},e.id)),C=y?u:j||k?(0,r.jsxs)(r.Fragment,{children:[j&&(0,r.jsx)("div",{className:"sidebar-menu-filter",children:(0,r.jsx)("input",{className:"sidebar-menu-filter-input",value:d,placeholder:o.placeholder,"aria-label":o.placeholder,autoComplete:"off",spellCheck:!1,"data-sidebar-menu-filter":"","data-sidebar-menu-autofocus":i?void 0:"",onChange:e=>c?.(e.target.value)})}),j&&(0,r.jsx)("div",{role:"status",children:d.trim()&&!w.some(tP)&&(0,r.jsx)("div",{className:"sidebar-menu-empty",children:o.emptyLabel})}),(0,r.jsx)("div",{role:"menu","aria-label":s,children:S}),k&&f]}):S,N=y||j||k?void 0:"menu";return i?(0,r.jsxs)("div",{className:"sidebar-sheet-layer",...tB,children:[(0,r.jsx)("div",{className:"sidebar-sheet-backdrop","aria-hidden":"true",onClick:()=>v("outside")}),(0,r.jsxs)("div",{ref:x,className:"sidebar-sheet",role:"dialog","aria-modal":"true","aria-label":s,children:[a?(0,r.jsx)("div",{className:"sidebar-sheet-title",children:a}):null,(0,r.jsx)("div",{className:"sidebar-sheet-body",role:N,"aria-label":N?s:void 0,children:C}),(0,r.jsx)("button",{type:"button",className:"sidebar-sheet-cancel","data-sidebar-menu-autofocus":h?"":void 0,onClick:()=>v("cancel"),children:p})]})]}):(0,r.jsx)("div",{ref:x,className:g?"sidebar-menu is-classic":"sidebar-menu",role:N??"dialog","aria-label":s,style:{width:m},...tB,children:C})}function tK(e){let{open:t,anchor:n,sheet:s,ariaLabel:a,title:l,items:o,filter:d,children:c,cancelLabel:u,focusCancel:p,onClose:h,returnFocusTo:m,width:g,classic:f=!1,footer:x,focusKey:b=""}=e,[v,y]=(0,i.useState)(null),[k,j]=(0,i.useState)(""),w=(0,i.useRef)(k);w.current=k;let S=(0,i.useRef)(null),C=(0,i.useRef)(h);C.current=h;let N=(0,i.useRef)(o);N.current=o;let I=(0,i.useRef)(m??null);I.current=m??null;let E=(0,i.useRef)(n);E.current=n,(0,i.useEffect)(()=>{y(document.body)},[]);let $=t&&null!==v&&(s||null!==n),T=tL(c),M=n?JSON.stringify(n):"",R=(e,t)=>{if(e.disabled)return;let n=!1;e.onSelect({shiftKey:t,keepOpen:()=>{n=!0}}),n||C.current("select")},A=(0,i.useRef)(R);A.current=R,(0,i.useLayoutEffect)(()=>{let e=S.current;if(!$||s||!e)return;let t=window.visualViewport,n=()=>{let n=E.current;if(!n)return;let r=e.getBoundingClientRect(),{left:i,top:s}=function(e,t,n){let r,i,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8,a=n.left+s,l=n.top+s,o=n.left+n.width-s,d=n.top+n.height-s;if("point"===e.kind)r=e.x+t.width>o&&e.x-t.width>=a?e.x-t.width:e.x,i=e.y+t.height>d&&e.y-t.height>=l?e.y-t.height:e.y;else{let{rect:n}=e;r="end"===e.align?n.right-t.width:n.left;let s=n.bottom+4,a=n.top-4-t.height;i=s+t.height>d&&a>=l?a:s}return{left:Math.max(a,Math.min(r,o-t.width)),top:Math.max(l,Math.min(i,d-t.height))}}(n,{width:r.width,height:r.height},{left:t?.offsetLeft??0,top:t?.offsetTop??0,width:t?.width??window.innerWidth,height:t?.height??window.innerHeight});e.style.left=`${i}px`,e.style.top=`${s}px`};n();let r="u"<typeof ResizeObserver?null:new ResizeObserver(n);return r?.observe(e),window.addEventListener("resize",n),t?.addEventListener("resize",n),t?.addEventListener("scroll",n),()=>{r?.disconnect(),window.removeEventListener("resize",n),t?.removeEventListener("resize",n),t?.removeEventListener("scroll",n)}},[$,s,M,T]),(0,i.useEffect)(()=>{j("")},[$,T]);let L=(0,i.useRef)(!1);return((0,i.useLayoutEffect)(()=>{let e=S.current;if(!$||!e){L.current=!1;return}let t=!L.current;L.current=!0,(t?tF(e):Array.from(e.querySelectorAll(tR)).filter(e=>!e.matches(tM)&&tO(e))[0]??tF(e))?.focus({preventScroll:!0})},[$,s,T,b]),(0,i.useLayoutEffect)(()=>{let e=S.current;if(!$||!e)return;let t=I.current;return()=>{let n=document.activeElement;if(n&&n!==document.body&&!e.contains(n))return;let r=function(e){if(!e||!e.isConnected)return null;if(tz(e))return e;let t=e.closest("[data-row-key]");if(!t)return null;for(let e of Array.from(t.querySelectorAll(tA)))if(e.tabIndex>=0&&tO(e))return e;return null}(t);r&&(r.focus({preventScroll:!0}),t&&r!==t&&tz(t)&&t.focus({preventScroll:!0}))}},[$,s]),(0,i.useEffect)(()=>{if(!$)return;let e=e=>{let t=S.current;if(!t||e.isComposing||229===e.keyCode)return;if("Escape"===e.key){e.preventDefault(),e.stopPropagation();let n=t.querySelector(tM);if(n&&w.current){j(""),n.focus({preventScroll:!0});return}C.current("escape");return}let n=e.target instanceof Element?e.target:null,r=null!==n&&t.contains(n),i=null===n||n===document.body||n===document.documentElement;if(!r&&!i)return;if("Tab"===e.key){var s;let i,a;r&&(s=e.shiftKey,i=Array.from(t.querySelectorAll(tA)).filter(e=>e!==n&&e.tabIndex>=0&&tO(e)),a=s?Node.DOCUMENT_POSITION_PRECEDING:Node.DOCUMENT_POSITION_FOLLOWING,i.some(e=>(n.compareDocumentPosition(e)&a)!=0))||C.current("outside");return}let a=("ArrowDown"===e.key||"ArrowUp"===e.key)&&n?.matches(tM);if(r&&function(e){if(!e)return!1;if(e.isContentEditable)return!0;let t=e.tagName;return"TEXTAREA"===t||"SELECT"===t||"INPUT"===t&&!["button","checkbox","radio","range","reset","submit","image","color","file"].includes((e.type||"text").toLowerCase())}(n)&&!a)return;if("ArrowDown"===e.key||"ArrowUp"===e.key||"Home"===e.key||"End"===e.key){let r,i=tW(t);if(0===i.length)return;e.preventDefault(),e.stopPropagation();let s=n?i.indexOf(n):-1;r="Home"===e.key?0:"End"===e.key?i.length-1:"ArrowDown"===e.key?s<0?0:(s+1)%i.length:s<0?i.length-1:(s-1+i.length)%i.length,i[r].focus({preventScroll:!1});return}if(1!==e.key.length||e.ctrlKey||e.metaKey||e.altKey)return;let l=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);l&&!T&&(e.preventDefault(),e.stopPropagation(),A.current(l,e.shiftKey))};return document.addEventListener("keydown",e,!0),()=>document.removeEventListener("keydown",e,!0)},[$,T]),(0,i.useEffect)(()=>{if(!$||s)return;let e=e=>{let t=S.current,n=e.target instanceof Node?e.target:null;if(!t||n&&t.contains(n))return;let r=I.current;r&&n&&0===e.button&&r.contains(n)&&function(e){let t=e.ownerDocument,n=t.defaultView;if(!n)return;let r=0,i=()=>{t.removeEventListener("click",s,!0),n.clearTimeout(r)};function s(t){i(),t.target instanceof Node&&e.contains(t.target)&&(t.preventDefault(),t.stopPropagation())}t.addEventListener("click",s,!0),r=n.setTimeout(i,1e3)}(r),C.current("outside")};return document.addEventListener("pointerdown",e,!0),()=>document.removeEventListener("pointerdown",e,!0)},[$,s]),$&&v)?(0,e5.createPortal)((0,r.jsx)(tU,{sheet:s,ariaLabel:a,title:l,items:o,filter:d,filterQuery:k,onFilterQueryChange:j,cancelLabel:u,focusCancel:p,width:g,classic:f,footer:x,surfaceRef:S,onActivate:(e,t)=>A.current(e,t),onClose:e=>C.current(e),children:c}),v):null}function tq(e){let{heading:t,busy:n,error:s,showCancel:a,onCreate:l,onCancel:o}=e,{t:d}=(0,eX.s)(),[c,u]=(0,i.useState)(""),p=c.trim(),h=()=>{p&&!n&&l(p)};return(0,r.jsxs)("div",{className:"sidebar-worktree-form",children:[t&&(0,r.jsx)("div",{className:"sidebar-menu-header",children:t}),(0,r.jsx)("input",{className:"sidebar-worktree-input","data-sidebar-menu-autofocus":"",value:c,readOnly:n,placeholder:d("sidebar.branchName"),"aria-label":d("sidebar.branchName"),onChange:e=>u(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.preventDefault(),h())}}),(0,r.jsxs)("div",{className:"sidebar-worktree-form-buttons",children:[(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-create",disabled:n||!p,onClick:h,children:d(n?"sidebar.creating":"sidebar.create")}),a&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-cancel",onClick:o,children:d("sidebar.cancel")})]}),s&&(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:s})]})}function tZ(e,t){return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function tV(e){return e.branch??J(e.path)}function tJ(e){let{heading:t,dirty:n,busy:i,error:s,showCancel:a,onForce:l,onCancel:o}=e,{t:d}=(0,eX.s)();return(0,r.jsxs)("div",{className:"sidebar-worktree-form",children:[t&&(0,r.jsx)("div",{className:"sidebar-menu-header",children:t}),n&&(0,r.jsx)("div",{className:"sidebar-worktree-message",children:d("sidebar.forceRemoveCheckout")}),(n||a)&&(0,r.jsxs)("div",{className:"sidebar-worktree-form-buttons",children:[n&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-force",disabled:i,onClick:l,children:d("sidebar.force")}),a&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-cancel","data-sidebar-menu-autofocus":"",onClick:o,children:d("sidebar.cancel")})]}),s&&(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:s})]})}function tG(e){let{busy:t,onForce:n,onCancel:s}=e,{t:a}=(0,eX.s)(),l=(0,i.useId)();return(0,r.jsxs)("div",{className:"sidebar-worktree-confirm",children:[(0,r.jsx)("span",{id:l,className:"sidebar-worktree-confirm-text",title:a("sidebar.forceRemoveCheckout"),children:a("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{type:"button",role:"menuitem",tabIndex:-1,"data-sidebar-menu-item":"","aria-describedby":l,"aria-disabled":!!t||void 0,className:"sidebar-worktree-force",onClick:()=>{t||n()},children:a("sidebar.force")}),(0,r.jsx)("button",{type:"button",role:"menuitem",tabIndex:-1,"data-sidebar-menu-item":"","data-sidebar-menu-autofocus":"",className:"sidebar-worktree-cancel",onClick:s,children:a("sidebar.cancel")})]})}function tY(e){let t,n,{layout:s,context:a,mobile:l,label:o,placeholder:d="",homeDir:c,projectActivity:u,worktreeHint:p=null,newWorktreeTitle:h,handleRef:m,onPick:g,onUseDefaultDirectory:f,onOpenFolder:x,onRefreshWorktrees:b,onCreateWorktree:v,onRemoveWorktree:y}=e,{t:k}=(0,eX.s)(),[j,w]=(0,i.useState)(null),S=(0,i.useRef)(j);S.current=j;let C=(0,i.useRef)(0),N=(0,i.useRef)(null),I=(0,i.useRef)(null),E=(0,i.useRef)(!1),$=(0,i.useRef)(g);$.current=g;let T="inline"!==s,M=!T,R=!l,{project:A,worktrees:L}=a,P=(t=a.worktrees??[]).find(e=>e.path===a.currentWorktreePath)??t.find(e=>e.isMain)??null,z=M&&A?ev(ex(a)).find(e=>{let{choice:t}=e;return t.key===A.key}):void 0;(0,i.useEffect)(()=>(E.current=!0,()=>{E.current=!1}),[]);let O=()=>(C.current+=1,C.current),W=()=>w(null),F=(e,t)=>{let n=t.getBoundingClientRect(),r=Math.max(T?220:"project"===e?260:240,Math.round(n.width));w({id:O(),kind:e,anchor:{kind:"rect",rect:{left:n.left,top:n.top,right:n.right,bottom:n.bottom},align:"row"===s&&"worktree"===e?"end":"start"},opener:t,width:r,body:null,removing:!1}),"worktree"===e&&b()},D=(0,i.useRef)(F);D.current=F,(0,i.useImperativeHandle)(m,()=>({button:e=>("worktree"===e?I:N).current,openMenu:e=>{let t=("worktree"===e?I:N).current;t&&D.current(e,t)}}),[]);let B=(e,t)=>{w(n=>n?.id===e?t(n):n)},H=e=>{let t=O();w(n=>n?.kind==="worktree"?{...n,id:t,body:e,removing:!1}:n)},_=async e=>{let t,n=S.current;if(!n||n.body?.kind!=="create"||!A)return;let{id:r}=n,i=(e,t)=>{B(r,n=>({...n,body:{kind:"create",busy:e,error:t}}))};i(!0,null);try{t=await v(A,e)}catch(e){t={error:e instanceof Error?e.message:String(e)}}E.current&&("error"in t?i(!1,t.error):S.current?.id===r&&(w(null),$.current({cwd:t.path,projectKey:A.key,projectRoot:A.root},"worktree")))},U=async(e,t)=>{let n,r=S.current;if(!r||!A||!y)return;let{id:i}=r;B(i,e=>({...e,removing:!0,body:e.body?.kind==="remove"?{...e.body,busy:!0,error:null}:e.body}));try{n=await y(A,e.path,t)}catch(e){n={error:e instanceof Error?e.message:String(e)}}E.current&&B(i,t=>{if("removed"===n)return{...t,removing:!1,body:null};let r="dirty"===n||t.body?.kind==="remove"&&t.body.dirty;return{...t,removing:!1,body:{kind:"remove",worktree:e,dirty:r,busy:!1,error:"dirty"===n?null:n.error}}})},K=()=>[...(L??[]).map(e=>R&&q?.kind==="remove"&&q.dirty&&q.worktree.path===e.path?{type:"custom",id:`worktree:${e.path}`,content:(0,r.jsx)(tG,{busy:q.busy,onForce:()=>{U(e,!0)},onCancel:()=>H(null)})}:{type:"item",id:`worktree:${e.path}`,label:R?e.branch??tZ(e.path,c):tV(e),mono:R,path:R,note:e.isMain?k("sidebar.main"):void 0,title:e.path,checked:e.path===P?.path,secondary:y&&!e.isMain?{label:k("sidebar.removeWorktreeTitle",{path:e.path}),icon:(0,r.jsx)(tv.uc,{size:12}),danger:!0,disabled:j?.removing,onSelect:t=>{let{keepOpen:n}=t;n(),U(e,!1)}}:void 0,onSelect:()=>{A&&e.path!==P?.path&&g({cwd:e.path,projectKey:A.key,projectRoot:A.root},"worktree")}}),...R?[]:[{type:"separator",id:"separator"}],...R&&q?.kind==="create"?[]:[{type:"item",id:"new-worktree",label:k("sidebar.newWorktree"),icon:(0,r.jsx)(tv.c1,{size:13}),onSelect:e=>{let{keepOpen:t}=e;t(),H({kind:"create",busy:!1,error:null})}}]],q=j?.kind==="worktree"?j.body:null,Z="",V=null,G=null;if(R&&j?.kind==="worktree")Z=k("sidebar.switchWorktree"),n=K(),q?.kind==="create"?G=(0,r.jsx)(tq,{heading:null,busy:q.busy,error:q.error,showCancel:!0,onCreate:e=>{_(e)},onCancel:()=>H(null)}):q?.kind==="remove"&&q.error&&(G=(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:q.error}));else if(q?.kind==="create")Z=h,V=(0,r.jsx)(tq,{heading:l?null:Z,busy:q.busy,error:q.error,showCancel:!l,onCreate:e=>{_(e)},onCancel:W});else if(q?.kind==="remove")Z=k("sidebar.removeWorktreeHeading",{name:tV(q.worktree)}),V=(0,r.jsx)(tJ,{heading:l?null:Z,dirty:q.dirty,busy:q.busy,error:q.error,showCancel:!l,onForce:()=>{U(q.worktree,!0)},onCancel:W});else if(j?.kind==="project"){let e,t;Z=k("workspace.project"),t=(e=ev(ex(a)).map(e=>{let{choice:t,name:n,note:i}=e,s=u?.get(t.key),a=R&&void 0===t.alias;return{type:"item",id:`project:${t.key}`,label:a?tZ(t.root,c):n,note:a?void 0:i??void 0,mono:R,path:a,title:t.root,checked:t.key===A?.key,badge:s?(0,r.jsx)(tI,{running:s.running,unread:s.unread,t:k}):void 0,onSelect:()=>{t.key===A?.key&&L||g({cwd:t.root,projectKey:t.key,projectRoot:t.root},"project")}}})).length>0?[{type:"separator",id:"separator"}]:[],n=[...e,...t,{type:"item",id:"default-directory",label:k("sidebar.useDefaultDirectory"),icon:(0,r.jsx)(tv.sj,{size:13}),onSelect:()=>f()},{type:"item",id:"open-folder",label:k(R?"sidebar.customPath":"sidebar.openOtherProject"),icon:R?(0,r.jsx)(tv.c1,{size:13}):(0,r.jsx)(tv.YP,{size:13}),onSelect:()=>x(j?.opener??null)}]}else j?.kind==="worktree"&&(Z=k("sidebar.switchWorktree"),n=K());let Y=j?.kind==="project"?{placeholder:k("sidebar.filterProjects"),emptyLabel:k("sidebar.noMatchingProjects"),minChoices:R?9:void 0}:{placeholder:k("sidebar.filterWorktrees"),emptyLabel:k("sidebar.noMatchingWorktrees")},X=T&&void 0!==u&&[...u].some(e=>{let[t,{running:n,unread:r}]=e;return t!==A?.key&&(n>0||r>0)});return(0,r.jsxs)("div",{className:`project-picker is-${s}`,role:"group","aria-label":o,children:[(0,r.jsxs)("button",{ref:N,type:"button",className:A?"project-picker-button is-project":"project-picker-button is-project is-empty",title:A?.root??"","aria-haspopup":"menu","aria-expanded":j?.kind==="project",onClick:e=>F("project",e.currentTarget),children:[M&&(0,r.jsx)(tv.sj,{size:12,className:"project-picker-icon"}),M&&A?(0,r.jsxs)("span",{className:"project-picker-name",children:[void 0===A.alias&&z?.note&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"project-picker-parent",children:z.note}),"/"]}),(0,r.jsx)("span",{className:"project-picker-leaf",children:A.alias??z?.name??J(A.root)})]}):A?.alias!==void 0?(0,r.jsx)("span",{className:"project-picker-label is-alias",children:A.alias}):A?(0,r.jsx)("span",{className:"project-picker-path",children:(0,r.jsx)("span",{children:tZ(A.root,c)})}):(0,r.jsx)("span",{className:"project-picker-label",children:d}),X&&(0,r.jsx)("span",{className:"project-picker-activity",role:"img",title:k("sidebar.newActivity"),"aria-label":k("sidebar.newActivity")}),M&&(0,r.jsx)(tv.zp,{size:9,className:"project-picker-chevron sidebar-icon-down"})]}),L&&(0,r.jsxs)("button",{ref:I,type:"button",className:"project-picker-button",title:P?k("sidebar.worktreePath",{path:P.path}):k("sidebar.switchWorktree"),"aria-haspopup":"menu","aria-expanded":j?.kind==="worktree",onClick:e=>F("worktree",e.currentTarget),children:[(0,r.jsx)(tv.OK,{size:11,className:P&&!P.isMain?"project-picker-icon is-linked":"project-picker-icon"}),(0,r.jsx)("span",{className:"project-picker-path",children:(0,r.jsx)("span",{children:P?P.branch??tZ(P.path,c):"…"})}),P?.isMain&&"stacked"===s&&(0,r.jsx)("span",{className:"project-picker-note",children:k("sidebar.main")}),T&&L.length>1&&(0,r.jsx)("span",{className:"project-picker-note",children:L.length}),(0,r.jsx)(tv.zp,{size:9,className:"project-picker-chevron sidebar-icon-down"})]}),!L&&T&&p&&(0,r.jsxs)("button",{type:"button","aria-disabled":"true",tabIndex:-1,title:p.title,className:"project-picker-button is-inactive",children:[(0,r.jsx)(tv.OK,{size:11,className:"project-picker-icon"}),(0,r.jsx)("span",{className:"project-picker-label",children:p.label})]}),(0,r.jsx)(tK,{open:null!==j,anchor:j?.anchor??null,sheet:l,ariaLabel:Z,title:Z,items:n,filter:Y,cancelLabel:k("sidebar.cancel"),focusCancel:q?.kind==="remove",onClose:W,returnFocusTo:j?.opener??null,width:j?.width,classic:R,footer:G,focusKey:q?`${q.kind}:${"remove"===q.kind&&q.dirty}`:"list",children:V})]})}function tX(e,t,n){if(e.relation?.kind!=="side")return null;let r=e.relation.parentSessionId,i=t.find(e=>e.id===r),s=i?.name||i?.firstMessage||void 0,a=t.filter(e=>e.relation?.kind==="side"&&e.relation.parentSessionId===r),o=a.some(t=>t.id===e.id)?a:[...a,e];return{parentSessionId:r,...s?{parentTitle:s}:{},label:l(e,n,o)}}function tQ(e){let{open:t,query:n,children:s,selectedSessionId:a,onSelectSession:l,onSelectSideChat:o,sessions:d,archivedSessionIds:c,projectNames:u}=e,{t:p,locale:h}=(0,eX.s)(),[m,g]=(0,i.useState)({query:""}),f=n.trim(),b=m.query===f?m.response:void 0,v=m.query===f&&m.failed;return(0,i.useEffect)(()=>{if(!t||!f)return;let e=new AbortController;g({query:f});let n=setTimeout(async()=>{try{let t=await fetch(`/api/sessions/search?${new URLSearchParams({q:f})}`,{signal:e.signal});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();e.signal.aborted||g({query:f,response:n})}catch{e.signal.aborted||g({query:f,failed:!0})}},300);return()=>{clearTimeout(n),e.abort()}},[t,f]),t&&f?(0,r.jsxs)("div",{className:"min-h-20 flex-1 overflow-y-auto","aria-busy":!b&&!v,children:[(0,r.jsx)("div",{role:"status",className:"px-3 py-2 text-xs text-text-muted",children:v?p("sidebar.sessionSearchFailed"):b?0===b.results.length?p("sidebar.sessionSearchEmpty"):p("sidebar.sessionSearchCount",{count:b.results.length}):p("sidebar.sessionSearching")}),b?.truncated&&(0,r.jsx)("div",{role:"status",className:"px-3 pb-2 text-xs text-text-muted",children:p("sidebar.sessionSearchPartial")}),b?.results.map(e=>{let t,n,{session:i,entryId:s,blockIndex:m,titleMatch:g,before:f,match:b,after:v}=e,y=i.relation?.kind==="side"?i.relation:null,k=y?tX(i,d,p("agentSwitcher.sideChat")):null,j=k?k.label:i.name||i.firstMessage;return(0,r.jsxs)("button",{type:"button",onClick:()=>{y&&i.id!==a?o(i):l(i,s,m)},"aria-current":i.id===a?"true":void 0,className:`block w-full cursor-pointer border-b border-border px-3 py-2 text-left hover:bg-bg-hover focus-visible:outline-2 focus-visible:outline-accent ${i.id===a?"bg-bg-selected":""}`,children:[(0,r.jsxs)("span",{className:"flex min-w-0 items-center gap-1.5",children:[(0,r.jsx)("span",{className:"min-w-0 truncate text-xs font-medium text-text",children:g?(0,r.jsxs)(r.Fragment,{children:[f,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:b}),v]}):j}),c?.has(i.id)&&(0,r.jsx)("span",{className:"shrink-0 rounded-[4px] border border-border px-1 text-[10px] leading-[14px] text-text-dim",children:p("sidebar.archived")})]}),k&&(0,r.jsx)("span",{className:"mt-1 block truncate text-[10px] text-text-dim",title:k.parentTitle,children:k.parentTitle?p("sidebar.sideChatOf",{name:k.parentTitle}):p("agentSwitcher.sideChat")}),(0,r.jsxs)("span",{className:"mt-1 flex min-w-0 gap-2 text-[10px] text-text-dim",children:[(0,r.jsxs)("span",{className:"min-w-0 flex-1 truncate",title:i.cwd,children:[(0,r.jsx)("span",{className:"font-medium text-text-muted",children:(t=x(i),n=i.projectRoot??i.cwd,u&&Object.hasOwn(u,t)?u[t]:J(n))}),i.cwd!==(i.projectRoot??i.cwd)&&` \xb7 ${i.cwd}`]}),(0,r.jsx)("span",{className:"shrink-0",children:(0,tm.fw)(i.modified,h)})]}),!g&&(0,r.jsxs)("span",{className:"mt-1 block text-xs leading-relaxed wrap-anywhere text-text-muted",children:[f,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:b}),v]})]},i.id)})]}):s}let t0=[1,7,30];function t1(e){return null===e||"number"==typeof e&&t0.includes(e)}let t2=[{value:1,labelKey:"share.duration1Day"},{value:7,labelKey:"share.duration7Days"},{value:30,labelKey:"share.duration30Days"},{value:null,labelKey:"share.durationForever"}];function t4(e){return null===e?"":String(e)}function t8(e){let t=""===e?null:Number(e);return t1(t)?t:7}function t6(e,t){return`${e}/share/${t}`}function t3(e){return e instanceof Error?e.message:String(e)}function t5(e){let{sessionId:t,origin:n,fetchImpl:s,onCopied:a,onStopped:l}=e,{t:o}=(0,eX.s)(),[d,c]=(0,i.useState)({status:"loading"}),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(!1),[x,b]=(0,i.useState)(7),[v,y]=(0,i.useState)(null),k=s??fetch,j=n??window.location.origin,w=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!0;return c({status:"loading"}),m(null),f(!1),k(`/api/sessions/${encodeURIComponent(t)}/share`,{cache:"no-store"}).then(async t=>{let n=await t.json().catch(()=>({}));if(e){if(!t.ok)return void c({status:"load-failed",error:n.error??`HTTP ${t.status}`});c(n.share?{status:"shared",share:n.share}:{status:"unshared"}),n.share&&b(n.share.durationDays)}}).catch(t=>{e&&c({status:"load-failed",error:t3(t)})}),()=>{e=!1}},[k,t]),(0,i.useEffect)(()=>{let e=!0;return k(`/api/sessions/${encodeURIComponent(t)}`,{cache:"no-store"}).then(async t=>{let n=await t.json().catch(()=>({}));e&&t.ok&&"number"==typeof n.info?.messageCount&&y(n.info.messageCount)}).catch(()=>{}),()=>{e=!1}},[k,t]);let S=(0,i.useCallback)(()=>{w.current||(w.current=!0,p("create"),m(null),k(`/api/sessions/${encodeURIComponent(t)}/share`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({durationDays:x})}).then(async e=>{var t,n;let r=await e.json().catch(()=>({}));if(!("string"==typeof(t=r).code&&"string"==typeof t.createdAt&&(null===t.expiresAt||"string"==typeof t.expiresAt)&&t1(t.durationDays)&&"string"==typeof t.title)){let{key:t,params:i}=(n=e.status,"too_large"===r.code||"too_large"===r.error?{key:"share.tooLarge"}:{key:"share.createError",params:{error:r.error??`HTTP ${n}`}});m(o(t,i));return}c({status:"shared",share:{code:r.code,createdAt:r.createdAt,expiresAt:r.expiresAt,durationDays:r.durationDays,title:r.title}}),f(!1)}).catch(e=>{m(o("share.createError",{error:t3(e)}))}).finally(()=>{w.current=!1,p(null)}))},[x,k,t,o]),C=(0,i.useCallback)(()=>{if(!w.current){if(!g)return void f(!0);w.current=!0,p("stop"),m(null),k(`/api/sessions/${encodeURIComponent(t)}/share`,{method:"DELETE"}).then(async e=>{let t=await e.json().catch(()=>({}));e.ok&&!0===t.ok?(c({status:"unshared"}),f(!1),y(null),l()):m(o("share.stopError",{error:t.error??`HTTP ${e.status}`}))}).catch(e=>{m(o("share.stopError",{error:t3(e)}))}).finally(()=>{w.current=!1,p(null)})}},[l,k,t,g,o]),N=(0,i.useCallback)(()=>{c(e=>("shared"===e.status&&(0,tc.D)(t6(j,e.share.code)).then(()=>a(),()=>{}),e))},[a,j]);return(0,r.jsx)(t9,{state:d,messageCount:v,busy:u,error:h,stopArmed:g,duration:x,origin:j,onCopy:N,onCreate:S,onRefresh:S,onStop:C,onDurationChange:b})}function t9(e){let{state:t,messageCount:n,busy:i,error:s,stopArmed:a,duration:l,origin:o,onCopy:d,onCreate:c,onRefresh:u,onStop:p,onDurationChange:h}=e,{t:m}=(0,eX.s)();return(0,r.jsxs)("div",{className:"sidebar-share-panel",children:[(0,r.jsx)("div",{className:"sidebar-menu-header",children:m("share.title")}),"loading"===t.status&&(0,r.jsx)("p",{role:"status",className:"sidebar-share-status",children:m("sidebar.loading")}),"load-failed"===t.status&&(0,r.jsx)("div",{role:"alert",className:"sidebar-share-error",children:m("share.loadError",{error:t.error})}),"unshared"===t.status&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"sidebar-share-text",children:m("share.description")}),null!==n&&(0,r.jsx)("p",{className:"sidebar-share-note",children:m("share.summary",{count:n})}),(0,r.jsx)(t7,{duration:l,onDurationChange:h,label:m("share.durationLabel")}),(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:m("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:m("share.linkLabel")}),(0,r.jsx)("code",{className:"sidebar-share-link",children:t6(o,t.share.code)}),(0,r.jsx)(ne,{expiresAt:t.share.expiresAt}),(0,r.jsx)(t7,{duration:l,onDurationChange:h,label:m("share.durationLabel")}),(0,r.jsxs)("div",{className:"sidebar-share-buttons",children:[(0,r.jsx)("button",{type:"button",className:"sidebar-share-copy","data-sidebar-menu-autofocus":"",onClick:d,children:m("share.copy")}),(0,r.jsx)("button",{type:"button",className:"sidebar-share-refresh",disabled:null!==i,onClick:u,children:m("create"===i?"share.creating":"share.refresh")})]}),(0,r.jsx)("div",{className:"sidebar-share-buttons",children:(0,r.jsx)("button",{type:"button",className:`sidebar-share-stop${a?" is-armed":""}`,disabled:null!==i,onClick:p,children:m(a?"share.confirmStop":"share.stop")})})]}),s&&(0,r.jsx)("div",{role:"alert",className:"sidebar-share-error",children:s})]})}function t7(e){let{duration:t,onDurationChange:n,label:i}=e,{t:s}=(0,eX.s)();return(0,r.jsxs)("div",{className:"sidebar-share-duration",children:[(0,r.jsx)("span",{className:"sidebar-share-duration-label",children:i}),(0,r.jsx)("select",{className:"sidebar-share-duration-select","aria-label":i,value:t4(t),onChange:e=>n(t8(e.target.value)),children:t2.map(e=>(0,r.jsx)("option",{value:t4(e.value),children:s(e.labelKey)},e.labelKey))})]})}function ne(e){let{expiresAt:t}=e,{t:n,locale:i}=(0,eX.s)();if(null===t)return(0,r.jsx)("p",{className:"sidebar-share-note",children:n("share.permanent")});let s=Date.parse(t);return Number.isFinite(s)?!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();return t>=e}(s)?(0,r.jsx)("p",{className:"sidebar-share-note",children:n("share.expiresIn",{time:(0,tm.fw)(new Date(s),i)})}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"sidebar-share-note",children:n("share.expired")}),(0,r.jsx)("p",{className:"sidebar-share-note",children:n("share.expiredHint")})]}):null}function nt(e){let{toast:t,dismissLabel:n,durationMs:s,onDismissRef:a}=e,l=(0,i.useRef)(null),[o,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(!1),p=o||c;return(0,i.useLayoutEffect)(()=>{let e=l.current;e&&window.matchMedia?.("(hover: hover)").matches&&e.matches(":hover")&&d(!0)},[]),(0,i.useEffect)(()=>{if(p)return;let e=window.setTimeout(()=>a.current(),s);return()=>window.clearTimeout(e)},[p,s,a]),(0,r.jsxs)("div",{ref:l,className:"sidebar-toast",onPointerEnter:e=>{"mouse"===e.pointerType&&d(!0)},onPointerLeave:()=>d(!1),onFocus:()=>u(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||u(!1)},children:[t.tail?(0,r.jsxs)("span",{className:"sidebar-toast-message has-tail",title:t.message+t.tail,children:[(0,r.jsx)("span",{className:"sidebar-toast-message-head",children:t.message}),(0,r.jsx)("span",{className:"sidebar-toast-message-tail",children:t.tail})]}):(0,r.jsx)("span",{className:"sidebar-toast-message",title:t.message,children:t.message}),t.actions.map(e=>(0,r.jsx)("button",{type:"button",className:"sidebar-toast-action",onClick:()=>{a.current(),e.onClick()},children:e.label},e.id)),(0,r.jsx)("button",{type:"button",className:"sidebar-toast-dismiss","aria-label":n,title:n,onClick:()=>a.current(),children:(0,r.jsx)(tv.US,{size:12})})]})}function nn(e){let{toast:t,onDismiss:n,dismissLabel:s,durationMs:a=1e4}=e,l=(0,i.useRef)(n);return l.current=n,(0,r.jsx)("div",{className:"sidebar-toast-region",role:"status","aria-live":"polite",children:t?(0,r.jsx)(nt,{toast:t,dismissLabel:s,durationMs:a,onDismissRef:l},t.id):null})}let nr={remote:"sidebar.openInExplorerRemoteOnly","unsupported-platform":"sidebar.openInExplorerUnsupported"};function ni(e){let{ref:t,onClick:n,title:i,disabled:s,pressed:a,expanded:l,controls:o,done:d,className:c,children:u}=e;return(0,r.jsx)("button",{ref:t,type:"button",onClick:n,disabled:s,title:i,"aria-label":i,"aria-pressed":a,"aria-expanded":l,"aria-controls":o,className:`sidebar-tool-button${a||l?" is-active":""}${d?" is-done":""}${c?` ${c}`:""}`,children:u})}let ns="pi-web:last-custom-cwd",na={"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 nl(){try{return window.localStorage.getItem(ns)??""}catch{return""}}function no(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 nd(e,t){return e.length>t?`${e.slice(0,t)}…`:e}function nc(e){let t=document.activeElement;e&&t instanceof HTMLElement&&t!==document.body&&(0===t.getClientRects().length||null!==t.closest("[inert]"))?e.focus({preventScroll:!0}):eE(document,e)}function nu(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 np(e){var t,n,s;let a,l,u,h,m,g,f,v,{selectedSessionId:k,onSelectSession:j,onSelectSideChat:w,onNewSession:S,controlRef:C,onNewSessionContextChange:I,initialSessionId:D,initialSessionLinked:q,skipInitialProjectSelection:Y,onInitialRestoreDone:ed,refreshKey:eh,onSessionDeleted:em,selectedCwd:ex,onCwdChange:ev,onOpenFile:ey,onOpenTerminal:ew,onOpenGitGraph:eI,explorerRefreshKey:eP,onExplorerRefresh:eW,onAtMention:eB,onAtMentions:eH,onBackgroundTaskDone:e_,hiddenFinishedSessionIds:eU,onRunningSessionIdsChange:eK,onSessionsChange:eq}=e,{t:eZ}=(0,eX.s)(),eV=(0,eQ.a)(),[eJ,eG]=(0,i.useState)([]),e4=(0,i.useRef)(null),e5=(0,i.useRef)(0),[e9,e7]=(0,i.useState)(!0),[te,tt]=(0,i.useState)(!1),[tn,tr]=(0,i.useState)(null),[ti,ts]=(0,i.useState)(null),[ta,tu]=(0,i.useState)(""),[tp,tm]=(0,i.useState)(!1),[tg,tf]=(0,i.useState)(nl),[tx,tb]=(0,i.useState)(null),[tk,tw]=(0,i.useState)(!1),[tS,tC]=(0,i.useState)(null),tN=(0,i.useRef)(null),[tI,tE]=(0,i.useState)(null),[t$,tT]=(0,i.useState)(null),tM=(0,i.useRef)(null);tM.current??=new Set((0,ec.PS)());let[tR,tA]=(0,i.useState)(0),[tL,tP]=(0,i.useState)(!1),[tz,tO]=(0,i.useState)(!1),[tW,tF]=(0,i.useState)(!1),[tD,tB]=(0,i.useState)(""),[tH,t_]=(0,i.useState)(0),[tU,tq]=(0,i.useState)(!0),[tZ,tV]=(0,i.useState)(!1),[tJ,tG]=(0,i.useState)(!1),[tX,t0]=(0,i.useState)(null),[t1,t2]=(0,i.useState)(null),[t4,t8]=(0,i.useState)(()=>new Set),[t6,t3]=(0,i.useState)(()=>new Set),[t9,t7]=(0,i.useState)(()=>new Set),[ne,nt]=(0,i.useState)(()=>(function(){try{return eR(window.localStorage.getItem(eT))}catch{return new Map}})()),np=(0,i.useRef)(new Set),nh=(0,i.useRef)(new Set),nm=(0,i.useRef)({latest:null,before:null}),ng=(0,i.useRef)(null);ng.current??=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Date.now,t=0;return{note(e,n,r){eM(e)&&Number.isFinite(n)&&Number.isFinite(r)&&(t=e-(n+r)/2)},toServer(){let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:e();return n+t}}}();let nf=(0,i.useRef)(new Set),nx=(0,i.useRef)(new Set),nb=(0,i.useRef)(new Set),nv=(0,i.useRef)(new Set),ny=(0,i.useRef)(!1),nk=(0,i.useRef)(null),nj=(0,i.useRef)(null),nw=(0,i.useRef)(null),nS=eY(),nC=!eV&&"below"===nS,[nN,nI]=(0,i.useState)("sessions"),[nE,n$]=(0,i.useState)(!1),nT=(0,i.useRef)(null),nM=(0,i.useRef)(null),nR=(0,i.useRef)(null),nA=(0,i.useRef)(null),nL=(0,i.useRef)(new WeakMap),[nP,nz]=(0,i.useState)({}),[nO,nW]=(0,i.useState)(()=>new Set),[nF,nD]=(0,i.useState)({}),[nB,nH]=(0,i.useState)(!1),[n_,nU]=(0,i.useState)(!1),[nK,nq]=(0,i.useState)([]),[nZ,nV]=(0,i.useState)(!1),{phase:nJ,start:nG,end:nY}=e3(),{phase:nX,start:nQ,end:n0}=e3(),n1=(0,i.useRef)(nE);n1.current=nE;let n2=(0,i.useRef)(nZ);n2.current=nZ;let n4=(0,i.useCallback)(e=>{e!==n2.current&&nQ(e?"in":"out"),nV(e)},[nQ]),n8=(a=nE&&"out"===nJ,l=!nE&&"in"===nJ,{bodyHidden:nE&&!a,bodyInert:a,moving:a||l,open:!nE&&!l}),n6=(u=nZ&&"in"===nX,h=!nZ&&"out"===nX,{mainHidden:nZ&&!u,mainInert:u,archiveMounted:nZ||h,archiveInert:h,archiveClass:u?"is-entering":h?"is-leaving":null}),[n3,n5]=(0,i.useState)(null),[n9,n7]=(0,i.useState)(null),[re,rt]=(0,i.useState)(null),[rn,rr]=(0,i.useState)(null),[ri,rs]=(0,i.useState)(null),ra=(0,i.useRef)(0),rl=(0,i.useCallback)(e=>{rs(t=>t?.id===e?null:t)},[]),[ro,rd]=(0,i.useState)(null),rc=(0,i.useCallback)(e=>{rd(t=>t?.id===e?null:t)},[]),ru=(0,i.useRef)(k);ru.current=k;let[rp,rh]=(0,i.useState)(null),rm=(0,i.useRef)(0),rg=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2?arguments[2]:void 0;rm.current+=1,rh({id:rm.current,message:e,...n?{tail:n}:{},actions:t})},[]),[rf,rx]=(0,i.useState)(0),rb=(0,i.useRef)(0),rv=(0,i.useRef)(null),[ry,rk]=(0,i.useState)(0),rj=(0,i.useRef)(null),rw=(0,i.useRef)(null),rS=(0,i.useRef)(null),rC=(0,i.useRef)(null),[rN,rI]=(0,i.useState)(0),rE=(0,i.useCallback)(e=>{rC.current=e,rI(e=>e+1)},[]);(0,i.useEffect)(()=>{let e=rC.current;rC.current=null,e&&eE(document,e())},[rN]);let{state:r$,loaded:rT,synced:rM,error:rR,apply:rA,snapshot:rL,noteRevision:rP}=function(){let[e,t]=(0,i.useState)(L),[n,r]=(0,i.useState)(!1),[s,a]=(0,i.useState)(!1),[l,o]=(0,i.useState)(null),d=(0,i.useRef)(e),c=(0,i.useRef)(e),u=(0,i.useRef)([]),p=(0,i.useRef)(Promise.resolve()),h=(0,i.useRef)(0),m=(0,i.useRef)(null),g=(0,i.useCallback)(()=>{let e=d.current;for(let{request:t,now:n}of u.current)e=function(e,t,n){var r,i,s,a;let l=function(e){let t={};for(let[n,r]of Object.entries(e.sessions))t[n]={...r};let n={};for(let[t,r]of Object.entries(e.projects))n[t]={...r};let r={...e,sessions:t,projects:n};return e.projectOrder&&(r.projectOrder=[...e.projectOrder]),e.projectNames&&(r.projectNames={...e.projectNames}),e.readAt&&(r.readAt={...e.readAt}),r}(e),o=!1;switch(t.action){case"set":for(let e of t.ids){let r=y(l.sessions,e)?l.sessions[e]:void 0;z(l.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))&&(o=!0)}break;case"restore":for(let e of t.entries){let t={};null!==e.pinnedAt&&(t.pinnedAt=e.pinnedAt),null!==e.archivedAt&&(t.archivedAt=e.archivedAt),z(l.sessions,e.id,t)&&(o=!0)}break;case"pin-project":{let{projectKey:e,root:a}=t,d=y(l.projects,e)?l.projects[e]:void 0;if(t.pinned?d?.root!==a&&(l.projects[e]={pinnedAt:n,root:a},o=!0):d&&(delete l.projects[e],o=!0),(t.pinned?void 0===d:void 0!==d)&&l.projectOrder){let n,a,d=(r=l.projectOrder,i=l.projects,s=t.pinned,a=r.filter(t=>t!==e),s?(n=0,a.forEach((e,t)=>{y(i,e)&&(n=t+1)})):(n=a.findIndex(e=>!y(i,e)))<0&&(n=a.length),a.splice(n,0,e),a);T(d.length,$(d))&&O(l,d)&&(o=!0)}break}case"add-projects":O(l,function(e,t){let n=W(e,t),r=e.length,i=$(e),s=n.length;for(;s>0;){let e=E(n[s-1]);if(!T(r+1,i+e))break;r++,i+=e,s--}return[...n.slice(s),...e]}(l.projectOrder??[],t.keys))&&(o=!0);break;case"move-project":{let e,n,{projectKey:r,anchorKey:i,position:s,add:d}=t,c=l.projectOrder??[];O(l,function(e,t){let n=e.length,r=$(e);if(T(n,r))return e;let i=new Set;for(let s=e.length-1;s>=0&&!T(n,r);s--)t.has(e[s])||(i.add(s),n--,r-=E(e[s]));let s=e.filter((e,t)=>!i.has(t));return T(n,r)?s:M(s)}((a=[...W(c,d),...c],(e=a.filter(e=>e!==r)).includes(i)||e.unshift(i),n=e.indexOf(i),e.splice("before"===s?n:n+1,0,r),e),new Set([r,i,...d])))&&(o=!0);break}case"rename-project":{let e=N(t.name);void 0!==e&&function(e,t,n){let r={...e.projectNames};if((y(r,t)?r[t]:void 0)===(n??void 0))return!1;if(null===n)delete r[t];else if(r[t]=n,!A(Object.keys(r).length,function(e){let t=1;for(let[n,r]of Object.entries(e))t+=R(n,r);return t}(r)))return!1;return 0===Object.keys(r).length?delete e.projectNames:e.projectNames=r,!0}(l,t.projectKey,e)&&(o=!0);break}case"read":{let e={...l.readAt};for(let r of t.ids){let t=y(e,r)?e[r]:void 0;void 0!==t&&t>=n||(e[r]=n,o=!0)}o&&(l.readAt=P(e))}}return{state:l,changed:o}}(e,t,n).state;c.current=e,t(e)},[]),f=(0,i.useCallback)(async e=>{let t=++h.current;m.current=t;try{let n=await fetch(e2,{cache:"no-store"}),i=await e6(n);if(t!==h.current)return;d.current=i,g(),e||o(null),r(!0),a(!0)}catch(e){if(t!==h.current)return;o(e8(e)),r(!0)}finally{m.current===t&&(m.current=null)}},[g]),x=(0,i.useCallback)(()=>f(!1),[f]),b=(0,i.useCallback)(e=>{"number"!=typeof e||!Number.isFinite(e)||u.current.length>0||e===d.current.revision||(null===m.current||m.current!==h.current)&&x()},[x]),v=(0,i.useCallback)(e=>{let t={request:e,now:Date.now()};u.current=[...u.current,t],g();let n=async()=>{let n=!1;try{let t=await fetch(e2,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store"}),i=await e6(t);h.current++,d.current=i,o(null),r(!0),a(!0),n=!0}catch(e){o(e8(e))}return u.current=u.current.filter(e=>e!==t),g(),n||await f(!0),n},i=p.current.then(n,n);return p.current=i,i},[f,g]),k=(0,i.useCallback)(e=>(function(e,t){let n=new Set,r=[];for(let i of t){if(n.has(i))continue;n.add(i);let t=y(e.sessions,i)?e.sessions[i]:void 0;r.push({id:i,pinnedAt:t?.pinnedAt??null,archivedAt:t?.archivedAt??null})}return r})(c.current,e),[]);return(0,i.useEffect)(()=>{x()},[x]),(0,i.useMemo)(()=>({state:e,loaded:n,synced:s,error:l,refresh:x,noteRevision:b,apply:v,snapshot:k}),[e,n,s,l,x,b,v,k])}(),rz=r$.readAt,rO=(0,i.useMemo)(()=>new Set(eA(ne,rz).keys()),[ne,rz]);(0,i.useEffect)(()=>{nt(e=>eA(e,rz))},[rz,ne]);let rW=(0,i.useRef)({allSessions:eJ,readAt:rz,unreadMarks:ne,runningSessionIds:t4,subagentsActiveSessionIds:t9});rW.current={allSessions:eJ,readAt:rz,unreadMarks:ne,runningSessionIds:t4,subagentsActiveSessionIds:t9};let rF=(0,i.useCallback)(e=>{let t=nx.current,n=[...new Set(e)].filter(e=>!t.has(e));if(0!==n.length){for(let e of n)t.add(e);rA({action:"read",ids:n}).then(e=>{for(let r of n)t.delete(r),e&&nf.current.delete(r)})}},[rA]),rD=(0,i.useCallback)((e,t)=>{var n;let r=rW.current;if(r.runningSessionIds.has(e)||r.subagentsActiveSessionIds.has(e))return;if(!eD()){t&&nf.current.add(e);return}let i=r.allSessions.find(t=>t.id===e),s=i?Date.parse(i.modified):0/0;((n={readAt:r.readAt&&Object.prototype.hasOwnProperty.call(r.readAt,e)?r.readAt[e]:void 0,modifiedMs:Number.isFinite(s)?s:void 0,marked:t,pending:nf.current.has(e)}).marked||n.pending||void 0===n.readAt||void 0!==n.modifiedMs&&n.modifiedMs>n.readAt)&&rF([e])},[rF]);(0,i.useEffect)(()=>{var e;let t,n;return e=()=>{let e=ru.current;e&&rD(e,!1)},t=eF().onAttended(e),0==ez++&&(eO=function(){let e=eF(),t=()=>e.noteInput(),n=()=>e.notePageChange(),r={capture:!0,passive:!0};for(let e of eL)window.addEventListener(e,t,r);return window.addEventListener("focus",n),window.addEventListener("blur",n),document.addEventListener("visibilitychange",n),()=>{for(let e of eL)window.removeEventListener(e,t,r);window.removeEventListener("focus",n),window.removeEventListener("blur",n),document.removeEventListener("visibilitychange",n)}}()),n=!1,()=>{n||(n=!0,t(),0==--ez&&(eO?.(),eO=null))}},[rD]);let rB=(0,i.useRef)(null),rH=(0,i.useRef)(null);e1(rH);let r_=(0,i.useRef)(null),rU=(0,i.useRef)(null),rK=(0,i.useRef)(320),rq=(0,i.useCallback)(()=>{let e=rU.current,t=rB.current;return e&&t&&0!==e.clientHeight?e.clientHeight-t.offsetHeight:window.innerHeight-36},[]),rZ=(0,i.useCallback)(()=>Math.round(.45*rq()),[rq]),rV=(0,i.useCallback)(()=>rq()-120,[rq]),rJ=(0,e0.T)({ariaLabel:eZ("sidebar.resizeFiles"),axis:"vertical",cssVariable:"--sidebar-files-height",defaultWidth:320,getDefaultWidth:rZ,getMaxWidth:rV,growthDirection:"up",maxWidth:2e3,minWidth:220,persistClamp:!1,storageKey:"pi-web:sidebar-files-height",widthRef:rK}),rG=rJ.panelRef,rY=(0,i.useCallback)(e=>{rU.current=e,rG.current=e},[rG]),rX=rJ.reclampWidth;(0,i.useEffect)(()=>{let e=rU.current;if(!nC||!e||"u"<typeof ResizeObserver)return;let t=new ResizeObserver(()=>rX());return t.observe(e),()=>t.disconnect()},[rX,nC]),(0,i.useEffect)(()=>{let e=(0,ec.K$)();"sessions"!==e&&nI(e);let t=(0,ec.$$)();Object.keys(t).length>0&&nz(t),(0,ec.iw)()&&nH(!0);let n=(0,ec.cA)();n.length>0&&nq(n),(0,ec.bj)()&&n$(!0),(0,ec.hS)()&&tV(!0),nU(!0),(0,ec.vK)()},[]);let rQ=(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=++e5.current;try{e&&e7(!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!==e5.current)return;e4.current=s.sessionListVersion,eG(s.sessions),n||tt(!0),ny.current||(nb.current=new Set(s.completionNotificationSuppressedSessionIds??[]),nm.current={latest:Date.now(),before:nm.current.latest},t8(e=>no(e,s.runningSessionIds??[])),t3(e=>no(e,s.awaitingInputSessionIds??[])));let a=new Set(s.sessions.filter(e=>!o(e.relation)).map(e=>e.id));nt(e=>{if(0===e.size)return e;let t=new Map([...e].filter(e=>{let[t]=e;return a.has(t)}));return t.size===e.size?e:t}),tr(null)}catch(e){r===e5.current&&tr(String(e))}finally{r===e5.current&&e7(!1)}},[]),r0=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!r0.current;r0.current=!0;let t=!0;return e?rQ(!0,!1,!0).then(()=>{t&&(nk.current=setTimeout(()=>{nk.current=null,t&&rQ(!1,!0)},750))}):rQ(),()=>{t=!1,nk.current&&(clearTimeout(nk.current),nk.current=null)}},[rQ,eh]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/open-in-explorer").then(e=>e.ok?e.json():null).then(t=>{!e&&t&&t0(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{t2(null)},[ti,ex]);let r1=(0,i.useCallback)(async()=>{let e=ti??ex;if(!e)return!1;try{let t=await fetch("/api/open-in-explorer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e})});if(t.ok)return t2(null),!1;let n=await t.json().catch(()=>({}));t2(n.error??`HTTP ${t.status}`)}catch(e){t2(e instanceof Error?e.message:String(e))}return!0},[ti,ex]),r2=eZ(tX?.platform==="darwin"?"sidebar.openInFinder":tX?.platform==="win32"?"sidebar.openInExplorer":"sidebar.openInFileManager"),r4=tX?.supported===!1,r8=t1?eZ(nr[t1]??t1):null;(0,i.useEffect)(()=>{try{let e=0===ne.size?null:JSON.stringify(Object.fromEntries(ne));null===e?window.localStorage.removeItem(eT):window.localStorage.setItem(eT,e)}catch{}},[ne]),(0,i.useEffect)(()=>{let e=e=>{(null===e.key||e.key===eT)&&nt(t=>(function(e,t){if(e.size!==t.size)return t;for(let[n,r]of t)if(e.get(n)!==r)return t;return e})(t,eR(e.newValue)))};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[]),(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let s=new AbortController;n?.abort(),n=s;let a=Date.now(),l=null,o="error",d=null;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:s.signal});if(d=t.status,!t.ok)return;o="ok";let r=await t.json();if(l=Date.now(),e||n!==s)return;ny.current=!0,"number"==typeof r.serverNow&&ng.current?.note(r.serverNow,a,l),nm.current={latest:a,before:nm.current.latest},nb.current=new Set(r.completionNotificationSuppressedSessionIds??[]),t8(e=>no(e,r.runningSessionIds??[])),t3(e=>no(e,r.awaitingInputSessionIds??[])),t7(e=>no(e,r.subagentsActiveSessionIds??[])),rP(r.sessionUiStateRevision),r.sessionListVersion!==e4.current&&await rQ()}catch{o=s.signal.aborted?"aborted":"error"}finally{n===s&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500)),(0,e$.tK)(a,o,d,l)}},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)}},[rQ,rP]),(0,i.useEffect)(()=>{eK?.(t4)},[eK,t4]),(0,i.useEffect)(()=>{eq?.(eJ)},[eJ,eq]),(0,i.useEffect)(()=>{!function(e){let t,n;if("u"<typeof document)return;let r=(n=(t=ek(e.awaiting))+ek(e.unread))<=0?null:{kind:t>0?"awaiting":"unread",count:Math.min(n,99)},i=r?`${r.kind}:${r.count}`:"none";if(i!==ej){if(ej=i,!r){for(let[e,t]of eS)e.href=t;return}for(let e of eC())eS.has(e)||eS.set(e,e.href);eN(r,i)}}({awaiting:t6.size,unread:function(e,t){if(!t||0===t.size)return e.size;let n=0;for(let r of t)e.has(r)||(n+=1);return e.size+n}(rO,eU)})},[t6,rO,eU]),(0,i.useEffect)(()=>{let e=np.current,t=[...e].filter(e=>!t4.has(e)&&e!==k),n=new Set([...t4,...t9]),r=[...nh.current].filter(e=>!n.has(e)&&e!==k),i=new Set(eJ.filter(e=>o(e.relation)).map(e=>e.id)),s=r.filter(e=>!nv.current.has(e)&&!i.has(e)),a=[...t4].filter(t=>!e.has(t));if(s.length>0||a.length>0){let e=nm.current.before,t=ng.current.toServer(e??void 0);nt(e=>{let n=new Map(e);return t4.forEach(e=>n.delete(e)),s.forEach(e=>n.set(e,t)),n})}k&&nh.current.has(k)&&!n.has(k)&&(eD()?rF([k]):nf.current.add(k));let l=a.some(e=>!eJ.some(t=>t.id===e));if((t.length>0||l)&&rQ(),s.length>0){let e=nm.current.before??Date.now()-5e3;e_?.(s,e)}np.current=t4,nh.current=n;let d=nv.current;nv.current=new Set([...n].filter(e=>nb.current.has(e)||i.has(e)||d.has(e)&&!t4.has(e)))},[t4,t9,k,eJ,rQ,e_,rF]),(0,i.useEffect)(()=>{if(!k)return;let e=rW.current.unreadMarks.has(k);rD(k,e),e&&nt(e=>{if(!e.has(k))return e;let t=new Map(e);return t.delete(k),t})},[k,rD]),(0,i.useEffect)(()=>{void 0!==eP&&tA(e=>e+1)},[eP]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&tu(e.home)}).catch(()=>{})},[]);let r6=(0,i.useRef)(!1),r3=(0,i.useCallback)(e=>e?function(e,t){let{validated:n,listing:r,sessions:i}=t;if(n?.cwd===e)return{root:n.root,key:n.key};if(r?.forCwd===e||r?.isTopLevel&&r.worktrees.some(t=>t.path===e))return{root:r.projectRoot,key:r.projectKey};let s=i.find(t=>t.cwd===e||(t.projectRoot??t.cwd)===e);return s?{root:s.projectRoot??s.cwd,key:x(s)}:{root:e,key:e}}(e,{validated:tS,listing:tI,sessions:eJ}):null,[tS,tI,eJ]),r5=(0,i.useMemo)(()=>r3(ti),[r3,ti]),r9=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=r3(ti),t=r9.current;(t?.cwd!==ti||t.key!==(e?.key??null))&&(r9.current={cwd:ti,key:e?.key??null},ev?.(ti,e?.root??null,e?.key??null))},[ti,ev,r3]);let r7=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!ex){r7.current=null;return}ex!==r7.current&&(r7.current=ex,ts(ex))},[ex]);let[ie,it]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!ti){tE(null),tT(null);return}let e=!1;return tT(ti),fetch(`/api/worktrees?cwd=${encodeURIComponent(ti)}`).then(e=>e.json()).then(t=>{if(!e){if(tT(null),t.error||!t.projectRoot)return void tE(null);t.isGit?tM.current?.delete(ti):tM.current?.add(ti),(0,ec._N)(ti,!!t.isGit),tE({forCwd:ti,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||(tT(null),tE(null))}),()=>{e=!0}},[ti,ie,eh]),(0,i.useEffect)(()=>{if(0!==eJ.length&&!Y&&null===ti){if(D&&!r6.current){r6.current=!0;let e=eJ.find(e=>e.id===D);if(e){ts(e.cwd),j(e,!0);return}ed?.(),q&&rg(eZ("sidebar.sessionNotFound"))}let e=b(eJ);e.length>0&&ts(e[0].root)}},[eJ,ti,D,q,Y,j,ed,rg,eZ]);let ir=tI?tI.worktrees.find(e=>e.path===ti)??(tI.forCwd===ti&&tI.currentWorktreePath?tI.worktrees.find(e=>e.path===tI.currentWorktreePath):void 0)??tI.worktrees.find(e=>e.isMain):void 0,ii=ir?.path??null,is=(0,i.useCallback)(async function(e){let{remember:t=!0,purpose:n=tp}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=(e??tg).trim();if(r&&!tk){tw(!0),tb(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 tb(s.error??`HTTP ${e.status}`);if(t){var i=s.cwd;try{window.localStorage.setItem(ns,i)}catch{}tf(s.cwd)}if(tm(!1),"new-session"===n){let e=rw.current,t=rS.current;rw.current=null,rS.current=null,e?.({cwd:s.cwd,projectKey:s.projectKey,projectRoot:s.projectRoot}),rE(()=>t?.isConnected?t:null);return}tC({cwd:s.cwd,root:s.projectRoot,key:s.projectKey}),ts(s.cwd)}catch(e){tb(e instanceof Error?e.message:String(e))}finally{tw(!1)}}},[tp,tg,tk,rE]),ia=(0,i.useCallback)(()=>{tm("files"),tb(null)},[]),il=(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 is(n.cwd,{remember:!1,purpose:e})}catch{}},[is]),io=(0,i.useRef)(il);io.current=il;let id=(0,i.useCallback)(async(e,t)=>{try{let r=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e.root,branch:t})}),i=await r.json().catch(()=>({}));if(!r.ok||i.error||!i.path){var n;let e,t=(n=r.status,(e="branch_in_use"===i.code?"sidebar.worktreeBranchInUse":"branch_worktree_missing"===i.code?"sidebar.worktreeBranchMissing":null)&&i.branch&&i.worktreePath?{key:e,params:{branch:i.branch,path:i.worktreePath}}:{error:i.error??`HTTP ${n}`});return"key"in t?{error:eZ(t.key,{...t.params,path:ep(t.params.path)})}:t}let s=i.path;return tE(n=>n&&n.projectKey===e.key&&!n.worktrees.some(e=>e.path===s)?{...n,worktrees:[...n.worktrees,{path:s,branch:t,isMain:!1}]}:n),it(e=>e+1),{path:s}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},[eZ]),ic=(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 ii===t&&ts(e.root),it(e=>e+1),"removed"}catch(e){return{error:e instanceof Error?e.message:String(e)}}},[ii]),iu=(0,i.useCallback)(()=>it(e=>e+1),[]),ip=(0,i.useCallback)(e=>{let{cwd:t,projectKey:n,projectRoot:r}=e;n&&r&&tC({cwd:t,root:r,key:n}),ts(t)},[]),ih=(0,i.useCallback)((e,t,n,r)=>{eG(t=>t.some(t=>t.id===e.id)?t:[e,...t]),e.cwd&&ts(e.cwd),j(e,!1,t,n,r)},[j]),im=(0,i.useCallback)(e=>{let{cwd:t,projectKey:n,projectRoot:r,carryComposer:i}=e;n&&r&&tC({cwd:t,root:r,key:n}),ts(t),S?.("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)},[S]),ig=(0,i.useRef)(im);ig.current=im,(0,i.useImperativeHandle)(C,()=>({startNewSessionIn:e=>ig.current(e),openFolderForNewSession:(e,t)=>{rw.current=e,rS.current=t,tb(null),tm("new-session")},openDefaultDirectoryForNewSession:e=>{rw.current=e,rS.current=null,io.current("new-session")},refreshWorktrees:iu,createWorktree:id}),[id,iu]);let ix=(0,i.useCallback)(()=>{ti&&im({cwd:ti})},[ti,im]),ib=(0,i.useMemo)(()=>b(eJ),[eJ]),iv=(0,i.useMemo)(()=>d(eJ),[eJ]),iy=(0,i.useMemo)(()=>new Map(iv.map(e=>[e.root.id,e])),[iv]),ik=(0,i.useMemo)(()=>{let e=new Set,t=new Map;for(let n of iv){if(!Z(n,r$,t4))continue;for(let t of K(n))e.add(t);let r=x(n.root);t.set(r,(t.get(r)??0)+1)}return{ids:e,countByProject:t}},[iv,r$,t4]),ij=(0,i.useMemo)(()=>(function(e,t,n){let r=new Map;for(let i of e){let e=x(i);if(!e)continue;let s=r.get(e);s||(s={running:0,unread:0},r.set(e,s)),t.has(i.id)&&s.running++,n.has(i.id)&&s.unread++}return r})(0===ik.ids.size?eJ:eJ.filter(e=>!ik.ids.has(e.id)),t4,rO),[eJ,ik,t4,rO]),iw=!!(tI?.isGit&&tI.isTopLevel&&ti&&r5?.key===tI.projectKey),iS=ti&&tI?.isGit&&r5?.key===tI.projectKey&&!iw?{label:eZ("sidebar.openRepoRoot"),title:eZ("sidebar.openRepoRootTitle")}:null,iC=!!(ti&&t$===ti),iN=iS??(!iC||iw||ti&&tM.current?.has(ti)?null:{label:eZ("sidebar.worktrees"),title:eZ("sidebar.checkingWorktrees")}),iI=r5?.key??null,iE=r5?.root??null,i$=(0,i.useMemo)(()=>iI&&iE?{key:iI,root:iE}:null,[iI,iE]),iT=(0,i.useMemo)(()=>0===nO.size?nP:Object.fromEntries([...[...nO].filter(e=>!Object.hasOwn(nP,e)).map(e=>[e,!0]),...Object.entries(nP)]),[nP,nO]),iM=(0,i.useMemo)(()=>(function(e){let{uiState:t,runningIds:n,currentProject:r}=e,i=d(e.sessions),s=ee(t,r),a=0,l=[],o=new Map,c=new Map,u=new Set;for(let e of i){if(Z(e,t,n)){a++;continue}s.noteFamily(e);let r=Q(e),i=function(e){let t=Date.parse(e);return Number.isNaN(t)?-1/0:t}(e.latestModified);if(c.set(r,Math.max(c.get(r)??-1/0,i)),e.root.transient||u.add(r),V(e,t,n)){l.push(e);continue}let d=o.get(r);d?d.push(e):o.set(r,[e])}let p=[{kind:"spacer",key:"top-spacer"}];if(l.length>0){let n=e=>_(H(t,e.root.id)?.pinnedAt)??0,r=l.map((e,t)=>({family:e,index:t})).sort((e,t)=>U(n(e.family),n(t.family))||e.index-t.index).map(e=>{let{family:t}=e;return t}),{running:i,awaiting:a,unread:o}=X(r,e);if(p.push({kind:"pinned-header",key:"pinned-header",count:r.length,collapsed:e.pinnedCollapsed,running:i,awaiting:a,unread:o}),!e.pinnedCollapsed){let{visible:t,revealed:n,nextShown:i}=en(r,8,er(e.moreShown,B),e);for(let n of t)p.push(et(n,"pinned",s.get(Q(n)),e));let a=es(r.length,t.length,n);a&&p.push({kind:"pinned-more",key:"pinned-more",...a,nextShown:i})}p.push({kind:"spacer",key:"pinned-spacer"})}let h=[...o.keys()],m=new Set(h),g=e=>{m.has(e)||(m.add(e),h.push(e))};for(let e of(r&&g(r.key),Object.keys(t.projects)))g(e);let f=h.map(e=>s.get(e)),x=new Map;(t.projectOrder??[]).forEach((e,t)=>{x.has(e)||x.set(e,t)});let b=e=>e.pinned||u.has(e.key),v=(e,t)=>[...e.filter(e=>{let{project:t}=e;return!x.has(t.key)}).sort((e,n)=>Number(b(e.project))-Number(b(n.project))||t(e,n)),...e.filter(e=>{let{project:t}=e;return x.has(t.key)}).sort((e,t)=>(x.get(e.project.key)??0)-(x.get(t.project.key)??0))].map(e=>{let{project:t}=e;return t}),y=e=>c.get(e.key)??(e.current?1/0:-1/0),k=e=>_(t.projects[e.key]?.pinnedAt)??0,j=f.map((e,t)=>({project:e,index:t})),w=v(j.filter(e=>{let{project:t}=e;return t.pinned}),(e,t)=>U(k(t.project),k(e.project))||e.index-t.index),S=v(j.filter(e=>{let{project:t}=e;return!t.pinned}),(e,t)=>U(y(e.project),y(t.project))||e.index-t.index),C=[...w,...S],N=e=>e.filter(e=>!x.has(e.key)).map(e=>e.key),I={pinned:N(w),other:N(S)},E=C.filter(e=>!x.has(e.key)&&b(e)).map(e=>e.key);for(let[t,n]of C.entries()){t>0&&p.push({kind:"spacer",key:`group-spacer:${n.key}`});let r=o.get(n.key)??[],i=G(n,e.groupExpansion),{running:s,awaiting:a,unread:l}=X(r,e);if(p.push({kind:"group",key:`group:${n.key}`,project:n,expanded:i,running:s,awaiting:a,unread:l}),i)if(0===r.length)p.push({kind:"group-empty",key:`empty:${n.key}`,project:n});else{let{visible:t,revealed:i,nextShown:s}=en(r,6,er(e.moreShown,n.key),e);for(let r of t)p.push(et(r,"group",n,e));let a=es(r.length,t.length,i);a&&p.push({kind:"group-more",key:`more:${n.key}`,projectKey:n.key,...a,nextShown:s})}}return C.length>0&&p.push({kind:"spacer",key:"footer-spacer"}),p.push({kind:"footer-open",key:"footer-open"}),a>0&&p.push({kind:"footer-archived",key:"footer-archived",count:a}),{rows:p,projects:C,archivedCount:a,unorderedKeysByBand:I,projectKeysToRecord:E}})({sessions:eJ,uiState:r$,runningIds:t4,awaitingIds:t6,unreadIds:rO,selectedSessionId:k,currentProject:i$,groupExpansion:iT,moreShown:nF,pinnedCollapsed:nB}),[eJ,r$,t4,t6,rO,k,i$,iT,nF,nB]),iR=n6.archiveMounted,iA=(0,i.useMemo)(()=>new Set(nK),[nK]),iL=(0,i.useMemo)(()=>iR?function(e){let{uiState:t,runningIds:n}=e,r=ee(t,e.currentProject),i=new Map;for(let s of d(e.sessions)){if(!Z(s,t,n))continue;r.noteFamily(s);let e=_(H(t,s.root.id)?.archivedAt)??0,a=Q(s),l=i.get(a);l?(l.families.push({family:s,archivedAt:e}),l.newest=Math.max(l.newest,e)):i.set(a,{newest:e,families:[{family:s,archivedAt:e}]})}let s=[];for(let{key:t,group:n}of[...i.entries()].map((e,t)=>{let[n,r]=e;return{key:n,group:r,index:t}}).sort((e,t)=>U(e.group.newest,t.group.newest)||e.index-t.index)){let i=r.get(t),a=!e.collapsed?.has(t);if(s.push({kind:"archive-group",key:`archive:${t}`,project:i,count:n.families.length,expanded:a}),a)for(let{family:t}of n.families.map((e,t)=>({...e,index:t})).sort((e,t)=>U(e.archivedAt,t.archivedAt)||e.index-t.index))s.push(et(t,"archive",i,e))}return s}({sessions:eJ,uiState:r$,runningIds:t4,awaitingIds:t6,unreadIds:rO,selectedSessionId:k,currentProject:i$,collapsed:iA}):[],[iR,eJ,r$,t4,t6,rO,k,i$,iA]),iP=(0,i.useMemo)(()=>iL.flatMap(e=>"archive-group"===e.kind?[e]:[]),[iL]),iz=(0,i.useMemo)(()=>new Map(iM.projects.map(e=>[e.key,e])),[iM.projects]),iO=(0,i.useRef)(new Set),iW=iM.projectKeysToRecord,iF=r$.projectOrder?.length??0;(0,i.useEffect)(()=>{if(e9||!rM||!te||iF>=1e3)return;let e=iO.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)}(iW,e);if(0!==t.length){for(let n of t)e.add(n);rA({action:"add-projects",keys:t})}},[rA,e9,iW,te,iF,rM]);let iD=r$.projectNames,iB=(0,i.useMemo)(()=>(function(e,t,n){let r=new Set,i=[];for(let s of[...e,...t])r.has(s.key)||(r.add(s.key),i.push(eb(s,n)));return i})(iM.projects,ib,iD),[iM.projects,ib,iD]),iH=(0,i.useMemo)(()=>{if(!ti||!r5)return null;let e=iw&&null!==tI;return{cwd:ti,project:eb(r5,iD),worktrees:e?tI.worktrees.map(e=>{let{path:t,branch:n,isMain:r}=e;return{path:t,branch:n,isMain:r}}):null,currentWorktreePath:e?ii:null,projects:iB}},[ti,r5,iw,tI,ii,iB,iD]),i_=(0,i.useRef)(iH);i_.current=iH;let iU=iH?JSON.stringify([iH.cwd,iH.project.key,iH.project.root,iH.project.alias??null,iH.currentWorktreePath,iH.worktrees?.map(e=>[e.path,e.branch,e.isMain])??null,iH.projects.map(e=>[e.key,e.root,e.alias??null])]):"";(0,i.useEffect)(()=>{I?.(i_.current)},[iU,I]);let iK=(0,i.useRef)(iI);(0,i.useLayoutEffect)(()=>{let e=iK.current;if(iK.current=iI,null===e||e===iI)return;let t=iz.get(e);nW(e=>!t||t.current||t.pinned||e.has(t.key)||Object.hasOwn(nP,t.key)?e:new Set(e).add(t.key))},[iI,nP,iz]);let iq=(0,i.useCallback)((e,t)=>{nz(e),(0,ec.wL)(e),nW(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)),nD(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))},[]),iZ=(0,i.useCallback)(()=>(nR.current?.hidden?nM:nT).current??r_.current,[]),iV=(0,i.useCallback)(e=>{let t=nR.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 iZ()},[iZ]),iJ=(0,i.useCallback)(e=>{let t=CSS.escape(`group:${e}`),n=nR.current?.querySelector(`[data-row-key="${t}"] .session-tree-group-toggle`);return n&&n.getClientRects().length>0?n:iZ()},[iZ]),iG=(0,i.useCallback)(async e=>{let t=await rA(e);return t||rx(e=>e+1),t},[rA]);(0,i.useEffect)(()=>{rf!==rb.current&&(rb.current=rf,rg(eZ("sidebar.uiStateFailed",{error:rR??""})))},[rf,rR,rg,eZ]);let iY=(0,i.useCallback)((e,t,n)=>{let r=iz.get(e),i=iz.get(t);r&&i&&r!==i&&r.pinned===i.pinned&&(iG({action:"move-project",projectKey:e,anchorKey:t,position:n,add:iM.unorderedKeysByBand[r.pinned?"pinned":"other"].slice(-500)}),ra.current+=1,rs({id:ra.current,at:Date.now(),rowKey:`group:${e}`}))},[iG,iM.unorderedKeysByBand,iz]),iX=(0,i.useCallback)(e=>{nC||(nI(e),(0,ec.d9)(e))},[nC]),iQ=(0,i.useCallback)(e=>{e!==n1.current&&nG(e?"out":"in"),n$(e),(0,ec.oh)(e)},[nG]),i0=(0,i.useCallback)(e=>{let t=e.target;t instanceof Element&&nL.current.set(t,t.scrollTop)},[]);(0,i.useLayoutEffect)(()=>{for(let e of[nR.current,nA.current])if(e&&!e.hidden)for(let t of e.querySelectorAll(".session-tree-scroll, .sidebar-files-scroll")){let e=nL.current.get(t);void 0!==e&&t.scrollTop!==e&&(t.scrollTop=e)}},[nN,nZ,nC,nE]);let i1=(0,i.useCallback)(e=>{if(rr(null),n4(!0),tF(!1),iX("sessions"),void 0!==e){if(nK.includes(e)){let t=nK.filter(t=>t!==e);nq(t),(0,ec.zY)(t)}ra.current+=1,rd({id:ra.current,at:Date.now(),rowKey:`archive:${e}`,block:"start"})}},[nK,n4,iX]),i2=(0,i.useRef)(null),i4=(0,i.useRef)(nZ),i8=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(i4.current===nZ)return;if(i4.current=nZ,nZ)return void nc(i2.current);let e=nR.current?.querySelector('[data-row-key="footer-archived"] button'),t=e&&e.getClientRects().length>0?e:iZ();nc(t),t&&document.activeElement===t&&(i8.current=t)},[nZ,iZ]);let i6=(0,i.useRef)(null),i3=(0,i.useRef)(nC);(0,i.useLayoutEffect)(()=>{if(i3.current===nC)return;i3.current=nC;let e=i6.current;e&&(!e.isConnected||0===e.getClientRects().length)&&nc(iZ())},[nC,iZ]);let i5=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"===nN?"files":"sessions";iX(t),("sessions"===t?nT:nM).current?.focus()},i9=(0,i.useCallback)((e,t)=>{iG({action:"set",ids:[e.root.id],pinned:t})},[iG]),i7=(0,i.useCallback)((e,t)=>{var n;if(t){let t=rW.current.unreadMarks;rF([e.root.id,...K(e).filter(e=>t.has(e))])}let r=rW.current.readAt,i=r&&Object.prototype.hasOwnProperty.call(r,e.root.id)?r[e.root.id]:void 0,s=(n=ng.current.toServer(),void 0===i?n:Math.max(n,i+1));nt(n=>{let r=new Map(n);if(t)for(let t of K(e))r.delete(t);else r.set(e.root.id,s);return r})},[rF]),se=(0,i.useCallback)(e=>{0!==e.length&&nt(t=>{let n=new Map(t);for(let[t,r]of e)t===ru.current||n.has(t)||n.set(t,r);return n.size===t.size?t:n})},[]),st=(0,i.useCallback)(e=>{let t=e.filter(e=>!e.root.transient);if(0===t.length)return;let n=rL(t.map(e=>e.root.id)),r=t.flatMap(e=>K(e)),i=r.flatMap(e=>{let t=ne.get(e);return void 0!==t&&rO.has(e)?[[e,t]]:[]});for(let e of F(t))iG({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=>K(e)));se(i.filter(e=>{let[t]=e;return n.has(t)}))});i.length>0&&nt(e=>{let t=new Map(e);for(let e of r)t.delete(e);return t}),rg(1===t.length?eZ("sidebar.archivedToast",{title:nd(ty(t[0].root),28)}):eZ("sidebar.archivedManyToast",{count:t.length}),[{id:"undo",label:eZ("sidebar.undo"),onClick:()=>{for(let e of F(n))iG({action:"restore",entries:e});se(i),rE(()=>iV(t[0].root.id))}},{id:"view",label:eZ("sidebar.viewArchive"),onClick:()=>i1()}])},[iG,rE,iV,i1,se,rg,rL,eZ,ne,rO]),sn=(0,i.useCallback)(e=>{K(e).some(e=>t4.has(e))||st([e])},[st,t4]),sr=(0,i.useCallback)(e=>{if(0===e.length)return;let t=e.map(e=>e.root.id),n=rL(t);for(let e of F(t))iG({action:"set",ids:e,archived:!1});rg(1===e.length?eZ("sidebar.restoredToast",{title:nd(ty(e[0].root),28)}):eZ("sidebar.restoredManyToast",{count:e.length}),[{id:"undo",label:eZ("sidebar.undo"),onClick:()=>{for(let e of F(n))iG({action:"restore",entries:e});rE(()=>iV(e[0].root.id))}}])},[iG,iV,rE,rg,rL,eZ]),si=(0,i.useCallback)(e=>sr([e]),[sr]),ss=(0,i.useCallback)(e=>{e.root.transient||(rt(null),n5(e.root.id))},[]),sa=(0,i.useCallback)(async(e,t)=>{let n=e.root,r=ty(n),i=t.trim();if(n5(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})}),rQ()}catch{}},[rQ]),sl=(0,i.useCallback)(e=>{n7(e.key)},[]),so=(0,i.useCallback)(e=>{n7(t=>t===e?null:t),rE(()=>iJ(e))},[rE,iJ]),sd=(0,i.useCallback)((e,t)=>{so(e.key);let n=function(e,t){let n=t.trim();if(n===e.name)return null;let r=""===n||n===J(e.root);return r&&null===e.customName?null:{action:"rename-project",projectKey:e.key,name:r?null:n}}(e,t);n&&iG(n)},[iG,so]),sc=(0,i.useCallback)(async e=>{let t=e.root;if(!t.transient){rt(e=>e===t.id?null:e);try{await fetch(`/api/sessions/${encodeURIComponent(t.id)}`,{method:"DELETE"}),em?.(t.id),rQ()}catch{}}},[rQ,em]),su=(0,i.useCallback)((e,t)=>{t?sc(e):(n5(null),rt(e.root.id))},[sc]),sp=(nC||"sessions"===nN)&&!nZ&&!(tW&&""!==tD.trim()),sh=(0,i.useRef)(null),sm=(0,i.useRef)(null),sg=(0,i.useRef)(null);(0,i.useEffect)(()=>{k!==sm.current&&(sm.current=k,sh.current=k);let e=sh.current;if(!e||e9||!rT||!n_||!sp)return;sh.current=null;let t=sg.current;sg.current=null;let n=function(e,t){let n=c(e.sessions,t);if(!n||Z(n,e.uiState,e.runningIds))return null;let r=Q(n);if(V(n,e.uiState,e.runningIds))return{rowKey:`session:pinned:${n.root.id}`,projectKey:r,unfoldPinned:e.pinnedCollapsed,unfoldGroup:!1};let i=Object.hasOwn(e.groupExpansion,r)&&!1===e.groupExpansion[r];return{rowKey:`session:group:${n.root.id}`,projectKey:r,unfoldPinned:!1,unfoldGroup:i}}({sessions:eJ,uiState:r$,runningIds:t4,groupExpansion:iT,pinnedCollapsed:nB},e);if(n){if(n.unfoldPinned&&(nH(!1),(0,ec.Lc)(!1)),n.unfoldGroup){let e={...nP};delete e[n.projectKey],e[n.projectKey]=!0,iq(e,[n.projectKey])}ra.current+=1,rs({id:ra.current,at:Date.now(),rowKey:n.rowKey,block:"nearest",...t?.sessionId===e?{takeFocusFrom:t.takeFocusFrom}:{}})}},[k,eJ,r$,t4,iT,nP,nB,e9,rT,n_,sp,iq]);let sf=(e,t)=>{if(i8.current=null,nZ){let e=nR.current?.querySelector(".sidebar-sessions-view .session-tree-scroll");e&&nL.current.delete(e),n4(!1)}let n=t?`[data-row-key="${CSS.escape(t)}"]`:null;sg.current={sessionId:e.id,takeFocusFrom:e=>null!==n&&null!==e.closest(n)||e===i8.current},ih(e,void 0,void 0,{keepSidebarOpen:null!==t}),rQ()},sx=(0,i.useRef)(sf);sx.current=sf;let sb=(0,i.useRef)(new Set),sv=(0,i.useCallback)(async e=>{let t=e.family.root;if(t.transient||sb.current.has(t.id))return;sb.current.add(t.id);let n=ru.current;try{var r;let i,s,a=await fetch(`/api/sessions/${encodeURIComponent(t.id)}/fork`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),l=await a.json().catch(()=>({}));if(!a.ok||!l.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}}}}(l.code,l.error??`HTTP ${a.status}`);rg(eZ(e,t)),"not_found"===l.code&&rQ();return}let o=l.session,d=ty(o),{head:c,tail:u}=(r=eZ("sidebar.forkedToast",{title:d}),((s=(i=eg(d)?.suffix)?r.lastIndexOf(i):-1)>0?{head:r.slice(0,s),tail:r.slice(s)}:null)??{head:eZ("sidebar.forkedToast",{title:nd(d,28)}),tail:void 0});if(ru.current!==n){eG(e=>e.some(e=>e.id===o.id)?e:[o,...e]);let e=ng.current.toServer();nt(t=>new Map(t).set(o.id,e)),rQ(),rg(c,[{id:"open",label:eZ("sidebar.open"),onClick:()=>sx.current(o,null)}],u);return}sx.current(o,e.key),rg(c,[],u)}catch(e){rg(eZ("sidebar.forkFailed",{error:e instanceof Error?e.message:String(e)}))}finally{sb.current.delete(t.id)}},[rQ,rg,eZ]),sy=(0,i.useCallback)(e=>{e.root.transient||window.open(p(e.root.id),"_blank","noopener,noreferrer")},[]),sk=(0,i.useCallback)((e,t,n)=>{e.status.transient||rr({kind:"row",row:e,anchor:t,opener:n})},[]),sj=(0,i.useCallback)((e,t)=>{let n=e.family.root;if(n.id===n3||n.id===re)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:()=>{rQ()}})){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?nu(r,"start"):{kind:"point",x:t.clientX,y:t.clientY},s=document.activeElement,a=s instanceof HTMLElement&&null!==r&&r.contains(s);rj.current=!a&&s instanceof HTMLElement&&s!==document.body?s:null,sk(e,i,a?s:null)},[re,rQ,sk,n3]),sw=(0,i.useMemo)(()=>({sessions:eJ,uiState:r$,runningIds:t4,awaitingIds:t6,unreadIds:rO,selectedSessionId:k}),[eJ,r$,t4,t6,rO,k]),sS=(0,i.useCallback)((e,t)=>{let n=ea(sw,e.key,6048e5,Date.now()).length;rr({kind:"group",project:e,olderCount:n,anchor:nu(t,"end"),opener:t})},[sw]),sC=(0,i.useCallback)(e=>{st(ea(sw,e.key,6048e5,Date.now()).flatMap(e=>{let t=iy.get(e);return t?[t]:[]}))},[st,iy,sw]),sN=(0,i.useCallback)((e,t)=>{rr(n=>n?.kind==="group"&&n.project.key===e?{...n,askDelete:t}:n)},[]),sI=(0,i.useRef)(new Set),sE=(0,i.useCallback)(async(e,t,n)=>{if(rr(null),!(0===t.length||sI.current.has(e))){sI.current.add(e),rg(eZ("sidebar.deletingSessions"));try{let e=await eu(t,fetch);for(let t of e.deleted)em?.(t);if(rQ().then(()=>rE(n)),null!==e.error)return void rg(eZ("sidebar.deleteFailed",{error:e.error}));let r=e.deletedRoots.length,i=[1===r?eZ("sidebar.deletedOneToast"):eZ("sidebar.deletedManyToast",{count:r})];e.running.length>0&&i.push(eZ("sidebar.keptRunningToast",{count:e.running.length})),rg(i.join(" \xb7 "))}finally{sI.current.delete(e)}}},[rE,rQ,em,rg,eZ]),s$=(0,i.useCallback)(e=>{let{ids:t}=el(sw,e.key);sE(`project:${e.key}`,t,()=>iJ(e.key))},[sE,iJ,sw]),sT=(0,i.useCallback)(e=>{let t=null===e?null:CSS.escape(`archive:${e}`),n=null===t?null:nR.current?.querySelector(`[data-row-key="${t}"] .session-tree-group-toggle`);if(n&&n.getClientRects().length>0)return n;let r=i2.current;return r&&r.getClientRects().length>0?r:iZ()},[iZ]),sM=(0,i.useCallback)(e=>e.flatMap(e=>{let t=iy.get(e);return t?[t]:[]}),[iy]),sR=(0,i.useCallback)((e,t)=>{rr({kind:"archive-group",project:e,anchor:nu(t,"end"),opener:t})},[]),sA=(0,i.useCallback)(e=>{rr(t=>t?.kind==="archive"?null:{kind:"archive",anchor:nu(e,"end"),opener:e})},[]),sL=(0,i.useCallback)(e=>{rr(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 d(e.sessions))if((void 0===t.projectKey||Q(r)===t.projectKey)&&Z(r,e.uiState,e.runningIds)){if(void 0!==t.archivedBefore){let n=_(H(e.uiState,r.root.id)?.archivedAt);if(null===n||n>=t.archivedBefore)continue}n.push(r.root.id)}return n})(sw,"all"===e?{}:"old"===e?{archivedBefore:Date.now()-2592e6}:e),[sw]),sz=(0,i.useCallback)(e=>{let t=sP(e);sE("string"==typeof e?`archive:${e}`:`archive-project:${e.projectKey}`,t,()=>"string"==typeof e?sT(null):sT(e.projectKey))},[sP,sT,sE]),sO=(0,i.useCallback)(e=>{nq(e),(0,ec.zY)(e)},[]),sW=(0,i.useCallback)(e=>{let t=iP.map(e=>e.project.key),n=nK.filter(e=>!t.includes(e));sO(e?n:[...n,...t])},[nK,iP,sO]),sF=(0,i.useCallback)((e,t)=>{let n=nK.includes(e);if(t)return void sW(n);let r=nK.filter(t=>t!==e);sO(n?r:[...r,e])},[nK,sO,sW]),sD=(0,i.useCallback)(e=>{rr(null),im(ef(e,ti))},[ti,im]),sB=(0,i.useCallback)(()=>rr(null),[]);(0,i.useEffect)(()=>{if(null!==rn)return;let e=rj.current;if(rj.current=null,!e?.isConnected)return;let t=document.activeElement;t&&t!==document.body||e.focus({preventScroll:!0})},[rn]);let sH=nZ?iL:iM.rows;(0,i.useEffect)(()=>{rn?.kind!=="row"||sH.some(e=>e.key===rn.row.key)||rr(null),rn?.kind!=="archive-group"||sH.some(e=>e.key===`archive:${rn.project.key}`)||rr(null)},[rn,sH]);let s_=rn?.kind==="row"?sH.find(e=>"session"===e.kind&&e.key===rn.row.key)??rn.row:null,sU=(0,i.useCallback)(e=>{ih(e.root)},[ih]),sK=(0,i.useCallback)(e=>{let t={...nP};for(let n of iM.projects)delete t[n.key],t[n.key]=e(n);iq(t,null)},[nP,iM.projects,iq]),sq=(0,i.useCallback)((e,t)=>{let n=iz.get(e);if(!n)return;let r=!G(n,iT);if(t)return void sK(()=>r);let i={...nP};delete i[e],i[e]=r,iq(i,[e])},[nP,iz,iq,sK,iT]),sZ=(0,i.useCallback)(e=>{let t=iM.rows.find(t=>"group-more"===t.kind&&t.projectKey===e||"pinned-more"===t.kind&&e===B);(t?.kind==="group-more"||t?.kind==="pinned-more")&&nD(n=>{var r;return r=t.nextShown,{...n,[e]:Math.max(er(n,e),Math.floor(r))}})},[iM.rows]),sV=(0,i.useCallback)(e=>{nD(t=>ei(t,e))},[]),sJ=(0,i.useCallback)(e=>{rv.current=e,rk(e=>e+1),nC?iQ(!1):iX("files")},[iQ,nC,iX]),sG=nC?n8.open:"files"===nN;(0,i.useEffect)(()=>{let e=rv.current;e&&sG&&(rv.current=null,"project-list"===e?tN.current?.openMenu("project"):"file-search"===e?document.getElementById("file-search-input")?.focus({preventScroll:!0}):tN.current?.button("project")?.focus({preventScroll:!0}))},[sG,ry]);let sY=e=>{let{heading:t,headingTitle:n,notes:i,count:s,onConfirm:a,onCancel:l}=e;return(0,r.jsxs)("div",{className:"sidebar-menu-question",children:[(0,r.jsx)("div",{className:"sidebar-menu-header",title:n,children:t}),i.map(e=>(0,r.jsx)("p",{className:"sidebar-menu-question-text",children:e},e)),(0,r.jsxs)("div",{className:"sidebar-menu-question-buttons",children:[(0,r.jsx)("button",{type:"button",className:"sidebar-menu-question-confirm",disabled:0===s,onClick:a,children:eZ("sidebar.deleteCount",{count:s})}),!eV&&(0,r.jsx)("button",{type:"button",className:"sidebar-menu-question-cancel","data-sidebar-menu-autofocus":"",onClick:l,children:eZ("sidebar.cancel")})]})]})},sX=(e,t)=>sY({heading:t?eZ("sidebar.deleteArchivedInProjectHeading",{name:t.name}):eZ("old"===e?"sidebar.deleteOldArchivedHeading":"sidebar.deleteAllArchivedHeading"),headingTitle:t?.root,notes:[eZ("sidebar.deleteArchivedMessage")],count:sP(e).length,onConfirm:()=>sz(e),onCancel:()=>sL(void 0)}),sQ="",s0=null;if(rn?.kind==="row"&&s_)g=ty(s_.family.root),sQ=eZ("sidebar.sessionActions"),v=(function(e,t){if(t.transient)return[];let n={kind:"action",id:"open-new-tab",shortcut:"T"};return"archive"===e?[{kind:"action",id:"unarchive",shortcut:"A"},{kind:"action",id:"pin",shortcut:"P"},{kind:"action",id:"rename",shortcut:"R"},{kind:"action",id:"fork",shortcut:"F"},{kind:"action",id:"share",shortcut:"S"},{kind:"action",id:"copy-session-id",shortcut:"I"},n,{kind:"separator"},{kind:"action",id:"delete",shortcut:"D"}]:[{kind:"action",id:"pinned"===e?"unpin":"pin",shortcut:"P"},{kind:"action",id:"rename",shortcut:"R"},{kind:"action",id:"fork",shortcut:"F"},{kind:"action",id:"share",shortcut:"S"},{kind:"action",id:"copy-session-id",shortcut:"I"},{kind:"action",id:t.unread?"mark-read":"mark-unread",shortcut:"U"},t.running?{kind:"action",id:"archive",shortcut:"A",disabledReason:"running"}:{kind:"action",id:"archive",shortcut:"A"},n,{kind:"separator"},{kind:"action",id:"delete",shortcut:"D"}]})(s_.context,s_.status).map((e,t)=>{if("separator"===e.kind)return{type:"separator",id:`separator-${t}`};let n=eZ(na[e.id]);return{type:"item",id:e.id,label:"delete"===e.id||"share"===e.id?`${n}…`:n,icon:function(e){switch(e){case"open-new-tab":return(0,r.jsx)(tv.Gb,{});case"pin":return(0,r.jsx)(tv.ts,{});case"unpin":return(0,r.jsx)(tv.UT,{});case"rename":return(0,r.jsx)(tv.R2,{});case"fork":return(0,r.jsx)(tv.o5,{});case"share":return(0,r.jsx)(tv.li,{});case"copy-session-id":return(0,r.jsx)(tv.Td,{});case"mark-read":return(0,r.jsx)(tv.TA,{});case"mark-unread":return(0,r.jsx)(tv.Zy,{});case"archive":return(0,r.jsx)(tv.kb,{});case"unarchive":return(0,r.jsx)(tv.G2,{});case"delete":return(0,r.jsx)(tv.uc,{})}}(e.id),shortcut:e.shortcut,danger:"delete"===e.id,disabled:void 0!==e.disabledReason,disabledReason:"running"===e.disabledReason?eZ("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":i9(i,!0);break;case"unpin":i9(i,!1);break;case"rename":ss(i);break;case"fork":sv(t);break;case"share":r?.(),rr(e=>e?.kind==="row"&&e.row.key===t.key?{...e,share:!0}:e);break;case"copy-session-id":(0,tc.D)(i.root.id).then(()=>rg(eZ("sidebar.sessionIdCopied")),()=>{});break;case"mark-read":i7(i,!0);break;case"mark-unread":i7(i,!1);break;case"archive":sn(i);break;case"unarchive":si(i);break;case"delete":su(i,n)}})(e.id,s_,n,r)}}}),rn.share&&(v=void 0,s0=(0,r.jsx)(t5,{sessionId:s_.family.root.id,onCopied:()=>rg(eZ("share.copiedToast")),onStopped:()=>rg(eZ("share.stoppedToast"))}),f=320);else if(rn?.kind==="group"){let e,t,i,a,l,o=iz.get(rn.project.key)??rn.project;g=o.name,sQ=eZ("sidebar.projectActions",{name:o.name}),n=o,s=rn.olderCount,e=ik.countByProject.get(n.key)??0,t=el(sw,n.key),i=eo(iM.projects,n.key,"up"),a=eo(iM.projects,n.key,"down"),l=(null===n.customName?["rename-project"]:["rename-project","reset-project-name"]).map(e=>"rename-project"===e?{type:"item",id:e,label:eZ("sidebar.renameProject"),icon:(0,r.jsx)(tv.R2,{}),onSelect:()=>sl(n)}:{type:"item",id:e,label:eZ("sidebar.resetProjectName"),icon:(0,r.jsx)(tv.G2,{}),onSelect:()=>{iG({action:"rename-project",projectKey:n.key,name:null})}}),v=[{type:"item",id:"pin-project",label:eZ(n.pinned?"sidebar.unpinProject":"sidebar.pinProject"),icon:n.pinned?(0,r.jsx)(tv.UT,{}):(0,r.jsx)(tv.ts,{}),onSelect:()=>{iG({action:"pin-project",projectKey:n.key,root:n.root,pinned:!n.pinned})}},...l,{type:"item",id:"open-in-files",label:eZ("sidebar.openInFilesTab"),icon:(0,r.jsx)(tv.sj,{}),onSelect:()=>{n.current||ts(n.root),sJ("project-button")}},{type:"item",id:"open-new-tab",label:eZ("sidebar.openInNewTab"),icon:(0,r.jsx)(tv.Gb,{}),shortcut:"T",onSelect:()=>(e=>{let{cwd:t}=ef(e,ti);window.open(`?cwd=${encodeURIComponent(t)}`,"_blank","noopener,noreferrer")})(n)},{type:"separator",id:"separator-layout"},{type:"item",id:"move-up",label:eZ("sidebar.moveProjectUp"),icon:(0,r.jsx)(tv.zp,{className:"sidebar-icon-up"}),disabled:null===i,onSelect:()=>{i&&iY(n.key,i.anchorKey,i.position)}},{type:"item",id:"move-down",label:eZ("sidebar.moveProjectDown"),icon:(0,r.jsx)(tv.zp,{className:"sidebar-icon-down"}),disabled:null===a,onSelect:()=>{a&&iY(n.key,a.anchorKey,a.position)}},{type:"item",id:"collapse-others",label:eZ("sidebar.collapseOtherGroups"),icon:(0,r.jsx)(tv.zp,{}),disabled:iM.projects.every(e=>G(e,iT)===(e.key===n.key)),onSelect:()=>sK(e=>e.key===n.key)},{type:"item",id:"expand-all",label:eZ("sidebar.expandAllGroups"),icon:(0,r.jsx)(tv.zp,{className:"sidebar-icon-down"}),disabled:iM.projects.every(e=>G(e,iT)),onSelect:()=>sK(()=>!0)},{type:"separator",id:"separator-sessions"},{type:"item",id:"archive-older",label:eZ("sidebar.archiveOlderThanWeek",{count:s}),icon:(0,r.jsx)(tv.kb,{}),disabled:0===s,onSelect:()=>sC(n)},{type:"item",id:"view-archived",label:eZ("sidebar.viewArchived",{count:e}),icon:(0,r.jsx)(tv.kb,{}),disabled:0===e,onSelect:()=>i1(n.key)},{type:"item",id:"delete-all",label:eZ("sidebar.deleteProjectSessions",{count:t.ids.length}),icon:(0,r.jsx)(tv.uc,{}),danger:!0,disabled:0===t.ids.length,onSelect:e=>{let{keepOpen:t}=e;t(),sN(n.key,!0)}}],rn.askDelete&&(s0=(e=>{let{ids:t,running:n}=el(sw,e.key);return sY({heading:eZ("sidebar.deleteProjectSessionsHeading",{name:e.name}),headingTitle:e.root,notes:[eZ("sidebar.deleteProjectSessionsMessage"),...n>0?[eZ("sidebar.deleteProjectSessionsRunning",{count:n})]:[]],count:t.length,onConfirm:()=>s$(e),onCancel:()=>sN(e.key,!1)})})(o)),f=264}else if(rn?.kind==="archive-group"){let e,t=iP.find(e=>e.project.key===rn.project.key)?.project??rn.project;g=t.name,sQ=eZ("sidebar.archivedProjectActions",{name:t.name}),v=[{type:"item",id:"restore-all",label:eZ("sidebar.restoreAllArchived",{count:(e=sP({projectKey:t.key})).length}),icon:(0,r.jsx)(tv.G2,{}),disabled:0===e.length,onSelect:()=>sr(sM(e))},{type:"separator",id:"separator-delete"},{type:"item",id:"delete-all",label:eZ("sidebar.deleteAllArchived",{count:e.length}),icon:(0,r.jsx)(tv.uc,{}),danger:!0,disabled:0===e.length,onSelect:e=>{let{keepOpen:t}=e;t(),sL("all")}}],rn.askDelete&&(s0=sX({projectKey:t.key},t)),f=248}else if(rn?.kind==="archive"){let e,t,n;g=eZ("sidebar.archived"),sQ=eZ("sidebar.archiveActions"),e=sP("all"),t=sP("old"),n=iP.filter(e=>!e.expanded).length,v=[{type:"item",id:"collapse-all",label:eZ("sidebar.collapseAllGroups"),icon:(0,r.jsx)(tv.zp,{}),disabled:n===iP.length,onSelect:()=>sW(!1)},{type:"item",id:"expand-all",label:eZ("sidebar.expandAllGroups"),icon:(0,r.jsx)(tv.zp,{className:"sidebar-icon-down"}),disabled:0===n,onSelect:()=>sW(!0)},{type:"separator",id:"separator-sessions"},{type:"item",id:"restore-all",label:eZ("sidebar.restoreAllArchived",{count:e.length}),icon:(0,r.jsx)(tv.G2,{}),disabled:0===e.length,onSelect:()=>sr(sM(e))},{type:"item",id:"delete-old",label:eZ("sidebar.deleteOldArchived",{count:t.length}),icon:(0,r.jsx)(tv.uc,{}),danger:!0,disabled:0===t.length,onSelect:e=>{let{keepOpen:t}=e;t(),sL("old")}},{type:"item",id:"delete-all",label:eZ("sidebar.deleteAllArchived",{count:e.length}),icon:(0,r.jsx)(tv.uc,{}),danger:!0,disabled:0===e.length,onSelect:e=>{let{keepOpen:t}=e;t(),sL("all")}}],rn.askDelete&&(s0=sX(rn.askDelete,null)),f=280}let s1={layout:eV?"mobile":"desktop",loading:e9||!rT,error:tn,renamingRootId:n3,renamingProjectKey:n9,confirmDeleteRootId:re,activeMenuRowKey:rn?.kind==="row"?rn.row.key:rn?.kind==="group"?`group:${rn.project.key}`:rn?.kind==="archive-group"?`archive:${rn.project.key}`:null,onSelectFamily:sU,onToggleGroup:sq,onShowMore:sZ,onShowLess:sV,onTogglePinned:()=>{let e=!nB;nH(e),(0,ec.Lc)(e),e&&nD(e=>ei(e,B))},onArchiveFamily:sn,onRestoreFamily:si,onOpenRowMenu:sk,onRowContextMenu:sj,onRenameCommit:(e,t)=>{sa(e,t)},onRenameCancel:()=>n5(null),onRenameProjectCommit:sd,onRenameProjectCancel:()=>{n9&&so(n9)},onDeleteConfirm:e=>{sc(e)},onDeleteCancel:()=>{rt(null),re&&rE(()=>iV(re))},onGroupNew:sD,onGroupMenu:sS,onPinEmptyGroup:e=>{iG({action:"pin-project",projectKey:e.key,root:e.root,pinned:!0}),rE(()=>iJ(e.key))},onToggleArchiveGroup:sF,onArchiveGroupMenu:sR,onOpenOtherProject:()=>{sJ("project-list")},onOpenArchive:()=>i1(),onMoveGroup:iY},s2=ti??ex??null,s4=s2&&tH>0?eZ("sidebar.changedFiles",{count:tH}):void 0,s8=(0,i.useRef)(null),s6=!s2||0===tH;(0,i.useLayoutEffect)(()=>{let e=s8.current;if(s6&&e&&i6.current===e){var t,n;let r;t=document,n=iZ(),(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}):eE(t,r)}},[s6,iZ]);let s3=nC||"sessions"===nN,s5=!nC&&"files"===nN&&null!==s2,s9=(t=(nC?["below",eZ("sidebar.new")]:["tabs",eZ("sidebar.tabSessions"),eZ("sidebar.tabFiles"),eZ("sidebar.new"),s2&&tH>0?tH:"",nN]).join("\n"),m=(0,i.useCallback)(()=>{let e=rB.current;if(e){for(let t of["0","1","2"])if(e.dataset.fit=t,e.scrollWidth<=e.clientWidth)return}},[rB]),(0,i.useLayoutEffect)(()=>{let e=rB.current;if(!e)return;m();let t=new ResizeObserver(m);return t.observe(e),()=>t.disconnect()},[rB,m,t]),m),s7=iM.archivedCount,ae=nC?13:14,at=(0,r.jsx)(ni,{onClick:()=>{s2&&ew?.(s2)},disabled:!s2||!ew,title:eZ("terminal.open"),children:(0,r.jsx)(tv.k3,{size:ae})}),an=(0,r.jsx)(ni,{onClick:()=>{r1().then(e=>{e&&nC&&iQ(!1)})},disabled:!s2||r4,title:r4?eZ(tX?.reason==="remote"?"sidebar.openInExplorerRemoteOnly":"sidebar.openInExplorerUnsupported"):r2,children:(0,r.jsx)(tv.sj,{size:ae})}),ar=(0,r.jsx)(ni,{onClick:()=>{nC&&nE&&iQ(!1),nw.current?.openUploadPicker()},disabled:!s2||tL,title:eZ("sidebar.uploadFilesTitle"),children:(0,r.jsx)(tv.JM,{size:ae})}),ai=(0,r.jsx)(ni,{onClick:()=>{eW?eW():tA(e=>e+1),tG(!0),nj.current&&clearTimeout(nj.current),nj.current=setTimeout(()=>tG(!1),2e3)},disabled:!s2,title:eZ("sidebar.refreshExplorer"),done:tJ,children:tJ?(0,r.jsx)(tv.Sr,{size:ae}):(0,r.jsx)(tv.fN,{size:ae})}),as=e=>(0,r.jsx)(ni,{onClick:()=>{let e=!tZ;tV(e),(0,ec.qM)(e)},disabled:!s2,title:eZ("sidebar.showIgnoredFiles"),pressed:tZ,className:e,children:(0,r.jsx)(tv.bM,{size:ae})}),aa=(0,r.jsx)(ni,{ref:s8,onClick:()=>{if(nC&&nE){iQ(!1),tq(!1);return}tq(e=>!e)},disabled:s6,title:eZ("sidebar.changedFiles",{count:tH}),pressed:!s6&&!tU,children:(0,r.jsx)(tv.Vz,{size:ae})}),al=(0,r.jsx)(ni,{onClick:()=>{s2&&eI?.(s2)},disabled:!s2||!eI,title:eZ("sidebar.openGitGraph"),children:(0,r.jsx)(tv.WQ,{size:ae})});return(0,r.jsxs)("div",{ref:rY,className:`session-sidebar${nC?" is-files-below":""}${nC&&nE?" is-files-collapsed":""}${nC&&n8.moving?" is-files-folding":""}${rp?" has-toast":""}`,style:{"--sidebar-files-height":`${rJ.width}px`},onFocus:e=>{i6.current=e.target},onBlur:e=>{(null!==e.relatedTarget||document.hasFocus())&&(e.currentTarget.contains(e.relatedTarget)||(i6.current=null))},children:[tp&&(0,r.jsx)(tl,{initialPath:tg,busy:tk,error:tx,onCancel:()=>{let e="new-session"===tp?rS.current:null;rw.current=null,rS.current=null,tm(!1),tb(null),e&&rE(()=>e.isConnected?e:null)},onSelect:e=>void is(e)}),(0,r.jsxs)("div",{ref:rB,className:"sidebar-header",children:[nC&&(0,r.jsx)(th,{onWidthChange:s9}),!nC&&(0,r.jsxs)("div",{className:"sidebar-tabs-list",role:"tablist","aria-label":eZ("sidebar.tabsLabel"),children:[(0,r.jsxs)("button",{ref:nT,type:"button",role:"tab",id:"session-sidebar-tab-sessions","aria-selected":"sessions"===nN,"aria-controls":"session-sidebar-panel-sessions",tabIndex:"sessions"===nN?0:-1,className:`sidebar-tab${"sessions"===nN?" is-selected":""}`,onClick:()=>iX("sessions"),onKeyDown:i5,children:[(0,r.jsx)(tv.b1,{size:13,className:"sidebar-tab-icon"}),(0,r.jsx)("span",{className:"sidebar-tab-label",children:eZ("sidebar.tabSessions")})]}),(0,r.jsxs)("button",{ref:nM,type:"button",role:"tab",id:"session-sidebar-tab-files","aria-selected":"files"===nN,"aria-controls":"session-sidebar-panel-files",tabIndex:"files"===nN?0:-1,title:s4,className:`sidebar-tab${"files"===nN?" is-selected":""}`,onClick:()=>iX("files"),onKeyDown:i5,children:[(0,r.jsx)(tv.sj,{size:13,className:"sidebar-tab-icon"}),(0,r.jsx)("span",{className:"sidebar-tab-label",children:eZ("sidebar.tabFiles")}),s2&&tH>0&&(0,r.jsx)("span",{className:"sidebar-tab-count","aria-hidden":"true",children:tH})]})]}),(0,r.jsx)("span",{className:"sidebar-header-spacer"}),(0,r.jsxs)("button",{type:"button",className:"sidebar-new-button",onClick:ix,disabled:!ti,title:ti?eZ("sidebar.newSessionTitle",{path:ti}):eZ("sidebar.selectProject"),children:[(0,r.jsx)(tv.c1,{size:12}),(0,r.jsx)("span",{className:"sidebar-new-label",children:eZ("sidebar.new")})]}),(0,r.jsx)("button",{ref:r_,type:"button",onClick:()=>{if(s5)return void tO(e=>!e);if(!s3){iX("sessions"),tF(!0);return}tF(e=>!e)},title:s5?eZ("sidebar.searchFiles"):eZ("sidebar.toggleSessionSearch"),"aria-label":s5?eZ("sidebar.searchFiles"):eZ("sidebar.toggleSessionSearch"),"aria-expanded":s5?tz:tW,"aria-controls":s5?"file-search-input":"session-search-input",className:`sidebar-search-toggle${(s5?tz:tW)?" is-active":""}`,children:(0,r.jsx)(tv.WI,{size:16})})]}),(0,r.jsxs)("div",{ref:nR,id:"session-sidebar-panel-sessions",role:nC?"region":"tabpanel","aria-label":nC?eZ("sidebar.tabSessions"):void 0,"aria-labelledby":nC?void 0:"session-sidebar-tab-sessions",hidden:!nC&&"sessions"!==nN,className:"sidebar-panel sidebar-sessions-panel",onScrollCapture:i0,children:[tW&&(0,r.jsx)("div",{className:"sidebar-search",children:(0,r.jsx)("input",{id:"session-search-input",type:"search",autoFocus:!0,value:tD,maxLength:200,"aria-label":eZ("sidebar.searchSessions"),placeholder:eZ("sidebar.searchSessions"),onChange:e=>tB(e.target.value),onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.stopPropagation(),tB(""))},className:"sidebar-search-input"})}),(0,r.jsx)(tQ,{open:tW,query:tD,selectedSessionId:k,onSelectSession:ih,onSelectSideChat:w,sessions:eJ,archivedSessionIds:ik.ids,projectNames:iD,children:(0,r.jsxs)("div",{className:"sidebar-sessions-views",children:[(0,r.jsx)("div",{className:"sidebar-sessions-view",hidden:n6.mainHidden,inert:n6.mainInert,children:(0,r.jsx)(tj,{...s1,rows:iM.rows,emptyLabel:eZ("sidebar.noSessions"),reveal:ri,onRevealHandled:rl})}),n6.archiveMounted&&(0,r.jsxs)("div",{className:`sidebar-sessions-view sidebar-archive-view${n6.archiveClass?` ${n6.archiveClass}`:""}`,inert:n6.archiveInert,onAnimationEnd:e=>{e.target===e.currentTarget&&n0()},children:[(0,r.jsxs)("div",{className:"sidebar-archive-bar",children:[(0,r.jsxs)("button",{ref:i2,type:"button",className:"sidebar-archive-back",title:eZ("sidebar.backToSessions"),"aria-label":`${eZ("sidebar.backToSessions")}: ${eZ("sidebar.archivedCount",{count:s7})}`,onClick:()=>n4(!1),children:[(0,r.jsx)(tv.zp,{size:13,className:"sidebar-icon-back"}),(0,r.jsx)("span",{children:eZ("sidebar.archived")}),(0,r.jsxs)("span",{className:"sidebar-archive-count",children:["\xb7 ",s7]})]}),(0,r.jsx)("button",{type:"button",className:`sidebar-archive-menu-button${rn?.kind==="archive"?" is-active":""}`,title:eZ("sidebar.archiveActions"),"aria-label":eZ("sidebar.archiveActions"),"aria-haspopup":"menu","aria-expanded":rn?.kind==="archive",disabled:0===iP.length,onClick:e=>sA(e.currentTarget),children:(0,r.jsx)(tv.Z4,{size:13})})]}),(0,r.jsx)(tj,{...s1,rows:iL,emptyLabel:eZ("sidebar.noArchived"),reveal:ro,onRevealHandled:rc})]})]})})]}),nC&&n8.open&&(0,r.jsx)("div",{...rJ.separatorProps,"aria-controls":"session-sidebar-panel-files",className:`panel-resize-handle sidebar-files-resize-handle${rJ.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar-files",title:`${eZ("sidebar.resizeFiles")}: ${eZ("sidebar.resizeFilesHint")}`}),(0,r.jsxs)("div",{ref:nA,id:"session-sidebar-panel-files",role:nC?"region":"tabpanel","aria-label":nC?eZ("sidebar.tabFiles"):void 0,"aria-labelledby":nC?void 0:"session-sidebar-tab-files",hidden:!nC&&"files"!==nN,className:"sidebar-panel sidebar-files-panel",onScrollCapture:i0,onTransitionEnd:e=>{e.target===e.currentTarget&&"height"===e.propertyName&&nY()},children:[nC&&(0,r.jsxs)("div",{className:"sidebar-files-section",children:[(0,r.jsxs)("button",{type:"button",className:"sidebar-files-section-toggle","aria-expanded":!nE,"aria-controls":"session-sidebar-files-body",title:s4,onClick:()=>iQ(!nE),children:[(0,r.jsx)(tv.zp,{size:12,strokeWidth:3,className:`session-tree-chevron${nE?"":" is-open"}`}),(0,r.jsx)("span",{className:"sidebar-files-section-label",children:eZ("sidebar.tabFiles")}),s4&&(0,r.jsxs)("span",{className:"sidebar-files-section-count","aria-hidden":"true",children:["\xb7 ",tH]})]}),(0,r.jsxs)("div",{className:"sidebar-files-keys",role:"group","aria-label":eZ("sidebar.fileActions"),children:[at,an,ar,ai,as(),aa,al,(0,r.jsx)(ni,{onClick:()=>{if(nE){tO(!0),sJ("file-search");return}tO(e=>!e)},disabled:!s2,title:eZ("sidebar.searchFiles"),expanded:tz,controls:"file-search-input",children:(0,r.jsx)(tv.WI,{size:13})})]})]}),(0,r.jsxs)("div",{id:"session-sidebar-files-body",className:"sidebar-files-body",hidden:nC&&n8.bodyHidden,inert:nC&&n8.bodyInert,children:[(0,r.jsxs)("div",{className:"sidebar-files-head",children:[(0,r.jsx)(tY,{handleRef:tN,layout:nC?"row":"stacked",context:iH??{project:null,worktrees:null,currentWorktreePath:null,projects:iB},mobile:eV,label:eZ("sidebar.projectAndWorktree"),placeholder:D&&!r6.current?"":eZ("sidebar.selectProject"),homeDir:ta,projectActivity:ij,worktreeHint:iN,newWorktreeTitle:eZ("sidebar.createWorktreeTitle"),onPick:ip,onUseDefaultDirectory:()=>{il()},onOpenFolder:ia,onRefreshWorktrees:iu,onCreateWorktree:id,onRemoveWorktree:ic}),!nC&&s2&&(0,r.jsxs)("div",{className:"sidebar-files-actions",role:"group","aria-label":eZ("sidebar.fileActions"),children:[ew&&at,an,ar,ai,as("sidebar-files-views-start"),aa,al]})]}),s2&&r8&&(0,r.jsxs)("div",{role:"alert",className:"sidebar-files-error",children:[(0,r.jsx)("span",{className:"sidebar-files-error-text",children:r8}),(0,r.jsx)(to.R,{onClick:()=>t2(null),title:eZ("files.dismissError")})]}),(0,r.jsx)("div",{ref:rH,className:"sidebar-files-scroll scrollbar-subtle",children:s2&&(0,r.jsx)(td.I,{ref:nw,cwd:s2,onOpenFile:ey??(()=>{}),refreshKey:tR,onAtMention:eB,onAtMentions:eH,onUploadBusyChange:tP,changesCollapsed:tU,onChangesCountChange:t_,fileSearchOpen:tz,onFileSearchOpenChange:tO,showHidden:tZ})})]})]}),(0,r.jsx)(tK,{open:null!==rn,anchor:rn?.anchor??null,sheet:eV,ariaLabel:sQ,title:g,items:v,cancelLabel:eZ("sidebar.cancel"),focusCancel:null!==s0,onClose:sB,returnFocusTo:rn?.opener??null,width:f,children:s0}),(0,r.jsx)(nn,{toast:rp,onDismiss:()=>rh(null),dismissLabel:eZ("sidebar.dismiss")})]})}var nh=n(5772);let nm=/\x1B(?:\][^\x07\x1B]*(?:\x07|\x1B\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g,ng=/^\x1B(?:\][^\x07\x1B]*(?:\x07|\x1B\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/,nf=/\x1B_pi:[^\x07\x1B\n]*(?:\x07|\x1B\\)/g;function nx(e){return e.replace(nf,"").replace(nm,"")}function nb(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(ng);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 nv(e,t){let n=nb(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function ny(e){return nb(e)[0]?.char}let nk=/[▀-▟]/,nj=/https?:\/\/(?:\[[0-9A-Fa-f:.]+\])?[^\s<>"'`\]}。,、;:!?)」』】]*/gi,nw=/^[.,;:!?]$/,nS={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:""},nC={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"};var nN=n(48656),nI=n(19870),nE=n(14667);function n$(e,t){let n,r=t.shortWithArg??new Set,i=t.longWithArg??new Set,s=t.inPlace??new Set,a=[],l=!1,o=!1,d=e=>{t.targetDir&&(n=e)};for(let c=1;c<e.length;c++){let u=e[c],p=u.text;if(!u.quoted&&"--"===p){for(let t=c+1;t<e.length;t++)a.push(e[t].text);break}if(!u.quoted&&p.startsWith("--")){let r=p.indexOf("=");if(-1!==r){let e=p.slice(0,r);s.has(e)?l=!0:t.expression&&("--expression"===e||"--file"===e)?o=!0:"--target-directory"===e&&t.targetDir&&(n=p.slice(r+1));continue}if(s.has(p)){l=!0;continue}t.expression&&("--expression"===p||"--file"===p)&&(o=!0),i.has(p)&&c+1<e.length&&("--target-directory"===p&&d(e[c+1].text),c+=1);continue}if(!u.quoted&&p.startsWith("-")&&p.length>1&&!/^\d/.test(p.slice(1))){let n=p.slice(1);for(let i=0;i<n.length;i++){let a=`-${n[i]}`;if(s.has(a)&&(l=!0),t.expression&&("-e"===a||"-f"===a)&&(o=!0),r.has(a)){let t=n.slice(i+1);t.length>0?"-t"===a&&d(t):c+1<e.length&&("-t"===a&&d(e[c+1].text),c+=1);break}}continue}a.push(p)}return{operands:a,targetDirectory:n,inPlace:l,expressionSeen:o}}var nT=n(83236),nM=n(67803);function nR(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}function nA(e){return e?e.map(e=>e.newPath).filter(e=>"string"==typeof e&&e.length>0):[]}function nL(e,t,n){let r=new Set,i=[],s=e=>{let t=(0,nI.XK)(e,n);!t||r.has(t)||(r.add(t),i.push({filePath:t}))};for(let n of e){var a;let e;if("toolCall"!==n.type||(a=n.toolName,!((0,nE.V4)(a)||(0,nE.iG)(a))&&!(0,nE.aP)(n.toolName)&&!(0,nE.Y2)(n.toolName)&&n.toolName!==nT.sp))continue;let r=t?.get(n.toolCallId);if(r&&!r.isError){if((0,nE.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,nM.IN)(e).matchAll(/^\*\*\* Delete File: (.+)$/gm)){let e=(t[1]??"").trim();e&&n.add(e)}return n}(e,n),i=(0,nM.dc)(n);if(i)return i.filter(e=>!r.has(e));if((0,nM.FK)(n))return[];if(n&&"object"==typeof n&&!Array.isArray(n)){let e=nA((0,nM.ND)(n.preview));if(e.length>0)return e}return nA((0,nM.oC)((0,nM.IN)(e)))}(n.input,r);else if((0,nE.Y2)(n.toolName)){let t=function(e){if(!e)return null;let t=e.command??e.cmd??e.script;return"string"==typeof t&&t.length>0?t:null}(n.input);e=t?function(e){if("string"!=typeof e||0===e.length||e.length>2e5)return[];let t=new Set,n=[];for(let r of function(e){let t=[],n=[],r="",i=!1,s="",a=()=>{(r.length>0||i)&&n.push({text:r,quoted:i}),r="",i=!1},l=()=>{a(),n.length>0&&t.push(n),n=[]};for(let t=0;t<e.length;t++){let n=e[t];if(s){if("\\"===n&&'"'===s&&e[t+1]){r+=e[t+1],t+=1;continue}if(n===s){s="";continue}r+=n;continue}if("'"===n||'"'===n){s=n,i=!0;continue}if("\\"===n){e[t+1]&&(r+=e[t+1],i=i||/[^\w./-]/.test(e[t+1]),t+=1);continue}if(";"===n||"|"===n||"&"===n||"\n"===n){("|"===e[t+1]||"&"===e[t+1])&&(t+=1),l();continue}if("#"===n&&0===r.length){let n=e.indexOf("\n",t);t=-1===n?e.length-1:n-1,l();continue}if(/\s/.test(n)){a();continue}r+=n}return l(),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=n$(t,{}).operands;break;case"touch":s=n$(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]}(n$(t,{shortWithArg:new Set(["-t","-S","-Z"]),longWithArg:new Set(["--target-directory","--suffix","--context"]),targetDir:!0}));break;case"sed":{let e=n$(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=n$(t,{shortWithArg:new Set(["-s","-r"]),longWithArg:new Set(["--size","--reference"])}).operands;break;case"dd":s=t.slice(1).flatMap(e=>{let t=e.text.match(/^of=(.+)$/);return t?[t[1]]:[]})}let a=[...i,...s].filter(e=>!(0===e.length||/[\$`]/.test(e)||/[*?\[]/.test(e)||e.startsWith("-")||e.startsWith("~")||e.startsWith("/dev/")));return a.length>0?a:null}(r);if(e){for(let r of e)if(!t.has(r)&&(t.add(r),n.push(r),n.length>=100))return n}}return n}(t):[]}else e=n.toolName===nT.sp?function(e){let{calls:t}=(0,nT.or)(e?.details),n=[];for(let e of t){if("ok"!==e.status||!(0,nE.V4)(e.name)&&!(0,nE.iG)(e.name))continue;let t=function(e){try{let t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return nR(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):[nR(n.input)];for(let t of e)t&&s(t)}}return i}var nP=n(11316),nz=n(6483);function nO(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,nz.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 nW(e,t){let n,r=[],i=null;for(let s=0;s<t;s++){let t=new URLSearchParams({tail:"1000",deferThinking:"",deferMedia:""});n&&t.set("before",n);let s=await fetch(`/api/sessions/${encodeURIComponent(e)}/context?${t}`,{cache:"no-store"});if(!s.ok)throw Error(`context ${s.status}`);let a=await s.json();i??=a.cwd??null;let l=a.context??{},o=Array.isArray(l.messages)?l.messages:[];if(r.unshift(...o),!l.hasMore||!l.oldestEntryId)break;n=l.oldestEntryId}return{messages:r,cwd:i}}let nF=new Map,nD=new Map;function nB(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={...e,content:t};return n.omitUsage&&(r.usage=void 0),n.omitStop&&(r.stopReason=void 0,r.errorMessage=void 0),r}var nH=n(56038);function n_(e){let t=e.trim().split("\n").map(e=>`> ${e}`).join("\n");return`${t}
3
+
4
+ `}function nU(e){return!e.trim()||e.endsWith("\n\n")?"":e.endsWith("\n")?"\n":"\n\n"}var nK=n(2836),nq=n(21813),nZ=n(2849);function nV(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 nJ=new Map;function nG(e){return`parked-new:${e}`}function nY(e){return{value:e.value,images:e.images.map(e=>({...e}))}}function nX(e){return!e.value&&0===e.images.length}function nQ(e){let t=nJ.get(e);return t?nY(t):null}function n0(e,t){nX(t)?nJ.delete(e):nJ.set(e,nY(t))}function n1(e){nJ.delete(e)}function n2(e,t){return e.trim()?t.trim()?`${e}
5
+
6
+ ${t}`:e:t}function n4(e,t,n,r){let i=[...t??[],...r].filter(nV).slice(0,10).map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});return{value:n2(e,n),images:i}}function n8(e,t,n){let r=nQ(e)??{value:"",images:[]},i=n4(t,n,r.value,r.images);return n0(e,i),i}function n6(e,t,n){if(e===t)return n?nY(n):nQ(t);let r=nQ(e),i=n&&!nX(n)?nY(n):r??(n?nY(n):null),s=nQ(t);if(n1(e),!i)return s;let a=s?n4(s.value,s.images,i.value,i.images):i;return n0(t,a),nY(a)}var n3=n(3099);let n5=/^([ \t]*)([-*+])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,n9=/^([ \t]*)(\d{1,9})([.)])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,n7=/^([ \t]*)(\d{1,3})(、)([ \t]*)/,re=/^[ \t]*([-*_])(?:[ \t]*\1){2,}[ \t]*$/,rt=/^[ \t]{0,3}(`{3,}|~{3,})/;function rn(e){return"mcp"===e.name&&e.sourceInfo?.path==="builtin:mcp"}function rr(e){return"/mcp"===e.trim()}var ri=n(30527),rs=n(8436);let ra="pi-enter-send-mode",rl="enter",ro=null,rd=new Set;function rc(){return null===ro&&(ro=function(){try{let e=window.localStorage.getItem(ra);return"ctrlEnter"===e?"ctrlEnter":"enter"}catch{return rl}}()),ro}function ru(e){return rd.add(e),()=>{rd.delete(e)}}function rp(e){ro=e;try{window.localStorage.setItem(ra,e)}catch{}rd.forEach(e=>e())}function rh(){return(0,i.useSyncExternalStore)(ru,rc,()=>rl)}function rm(){let e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}let rg={en:"en-US","zh-CN":"zh-CN","zh-TW":"zh-TW"};var rf=n(23584),rx=n(74761);function rb(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 rv(e){let{active:t,onSelect:n,star:s,gutter:a=!!s,children:l}=e,o=(0,eQ.a)(),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=!!(s&&!s.isDefault),m=h&&(d||u||o);return(0,r.jsxs)("div",{onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),onFocus:()=>p(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||p(!1)},style:{position:"relative",background:t?"var(--bg-selected)":d?"var(--bg-hover)":"transparent",transition:"background 0.1s"},children:[(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":t,onClick:n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minWidth:0,padding:a?"7px 36px 7px 12px":"7px 12px",border:"none",background:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:t?600:400,textAlign:"left",whiteSpace:"nowrap"},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),l]}),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)(rb,{filled:!0,size:10})}),s&&h&&(0,r.jsx)("button",{type:"button",title:s.saveLabel,"aria-label":s.saveLabel,tabIndex:m?0:-1,onClick:e=>{e.stopPropagation(),s.onSave()},style:{position:"absolute",top:"50%",right:6,transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,padding:0,background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",opacity:+!!m,pointerEvents:m?"auto":"none",transition:"opacity 0.1s, background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="rgba(37,99,235,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},children:(0,r.jsx)(rb,{filled:!1,size:12})})]})}function ry(e){var t;let n,s,a,l,o,d,c,u,p,h,m,{options:g,value:f,onChange:x,onReselect:b,onClear:v,emptyLabel:y,selectedLabel:k,disabled:j=!1,busy:w=!1,isAutoSelection:S=!1,ariaLabel:C,variant:N="toolbar",placement:I="up",defaultValue:E,onSetDefault:$,allOptions:T,onShowAll:M}=e,{t:R}=(0,eX.s)(),A=(0,eQ.a)(),L=(0,i.useRef)(null),P=(0,i.useRef)(null),[z,O]=(0,i.useState)(!1),[W,F]=(0,i.useState)(null),[D,B]=(0,i.useState)(""),[H,_]=(0,i.useState)(!1),U=j||w,K=H?T:g,q=(t=K??[],(n=D.trim().toLocaleLowerCase())?t.filter(e=>`${e.name} ${e.providerName??""} ${e.modelId} ${e.provider}/${e.modelId}`.toLocaleLowerCase().includes(n)):t),Z=!!M||g.length>8,V=(e,t)=>e?.find(e=>e.modelId===t.modelId&&e.provider===t.provider),J=()=>{H||M?.(),_(!H)},G=function(e){let t=[];for(let n of e){let e=t.find(e=>e.provider===n.provider);e?(e.options.push(n),e.providerName===e.provider&&n.providerName?.trim()&&(e.providerName=n.providerName.trim())):t.push({provider:n.provider,providerName:n.providerName?.trim()||n.provider,options:[n]})}return t}(q),Y=k??(f?(V(g,f)??V(T,f))?.name??f.modelId:y??(g.length>0?R("chat.selectModel"):R("chat.noModels")));(0,i.useEffect)(()=>{let e=e=>{L.current&&!L.current.contains(e.target)&&P.current&&!P.current.contains(e.target)&&(O(!1),B(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{if(!z)return;let e=()=>{let e=L.current?.querySelector("button")?.getBoundingClientRect();e?.height&&F({top:e.top,right:e.right,bottom:e.bottom,left:e.left,width:e.width})},t=window.visualViewport,n=new MutationObserver(e);return n.observe(document.documentElement,{attributes:!0,attributeFilter:["style","data-keyboard-open"]}),window.addEventListener("resize",e),t?.addEventListener("resize",e),t?.addEventListener("scroll",e),()=>{n.disconnect(),window.removeEventListener("resize",e),t?.removeEventListener("resize",e),t?.removeEventListener("scroll",e)}},[z]),(0,i.useEffect)(()=>{U&&(O(!1),B(""))},[U]);let X="field"===N?{display:"flex",alignItems:"center",gap:7,width:"100%",minWidth:0,height:34,padding:"0 9px",overflow:"hidden",border:"1px solid var(--border)",borderRadius:5,background:U?"var(--bg-panel)":"var(--bg)",color:U?"var(--text-dim)":"var(--text)",cursor:U?"default":"pointer",fontSize:12,textAlign:"left"}:{display:"flex",alignItems:"center",justifyContent:A?"flex-start":void 0,gap:6,width:A?"100%":void 0,maxWidth:A?"100%":220,height:A?44:32,padding:A?"8px 10px":"8px 12px",overflow:"hidden",border:"none",borderRadius:9,background:z?"var(--bg-hover)":"none",color:"var(--text-muted)",cursor:U?"not-allowed":"pointer",fontSize:12,opacity:U?.5:1,transition:"background 0.12s, color 0.12s"};return(0,r.jsxs)("div",{ref:L,className:`model-selector is-${N}${U?" is-disabled":""}`,style:{position:"relative",width:"field"===N||A?"100%":void 0,minWidth:0,flex:"toolbar"===N&&A?"1 1 auto":void 0},onKeyDown:e=>{"Escape"===e.key&&z&&(e.preventDefault(),e.stopPropagation(),B(""),O(!1))},children:[(0,r.jsxs)("button",{type:"button","aria-label":C,"aria-haspopup":"listbox","aria-expanded":z,"aria-busy":w||void 0,disabled:U,title:w?R("chat.switchingModel"):U?Y:g.length>0||v?R("chat.changeModel"):R("chat.noAvailableModels"),style:X,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();F({top:t.top,right:t.right,bottom:t.bottom,left:t.left,width:t.width}),O(e=>(e?B(""):_(!1),!e))},onMouseEnter:e=>{U||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{if(U){e.currentTarget.style.background="field"===N?"var(--bg-panel)":"none",e.currentTarget.style.color="field"===N?"var(--text-dim)":"var(--text-muted)";return}e.currentTarget.style.background=z?"var(--bg-hover)":"field"===N?"var(--bg)":"none",e.currentTarget.style.color="field"===N?"var(--text)":"var(--text-muted)"},children:[w?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Y}),"field"===N&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--text-dim)"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),z&&W&&(s=window.visualViewport?.offsetTop??0,a=window.visualViewport?.height??window.innerHeight,l=window.visualViewport?.width??window.innerWidth,d=(o=Math.min(W.top-6,s+a-8))-s-8,c=s+a-W.bottom-6-8,p=Math.max(120,Math.min((u="up"===I||d>c)?d:c,.6*a)),h=u?{top:o,transform:"translateY(-100%)"}:{top:W.bottom+6},m=A?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:W.left,width:"max-content",minWidth:W.width,maxWidth:Math.max(W.width,l-W.left-8)},(0,r.jsxs)("div",{ref:P,role:"listbox","aria-label":C,style:{position:"fixed",...h,...m,zIndex:500,display:"flex",flexDirection:"column",maxHeight:p,overflow:"hidden",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:u?"0 -4px 16px rgba(0,0,0,0.10)":"0 4px 16px rgba(0,0,0,0.10)"},children:[M&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px 0",fontSize:11},children:[[!1,!0].map(e=>(0,r.jsx)("button",{type:"button","aria-pressed":H===e,onClick:()=>{H!==e&&J()},style:{padding:"2px 7px",border:"1px solid",borderColor:H===e?"var(--border)":"transparent",borderRadius:4,background:H===e?"var(--bg-hover)":"none",color:H===e?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11},children:R(e?"chat.modelScopeAll":"chat.modelScopeScoped")},String(e))),!A&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:"Tab"})]}),Z&&(0,r.jsx)("div",{style:{flexShrink:0,padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:D,onChange:e=>B(e.target.value),onKeyDown:e=>{M&&"Tab"===e.key&&(e.preventDefault(),J())},placeholder:R("chat.filterModels"),"aria-label":R("chat.filterModels"),autoFocus:!A,autoComplete:"off",spellCheck:!1,style:{boxSizing:"border-box",width:"100%",minWidth:220*!A,padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})}),(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[v&&!D.trim()&&(0,r.jsx)(rv,{active:!f,gutter:!!$,onSelect:()=>{O(!1),B(""),v()},children:(0,r.jsx)(rk,{label:y??R("i18n.default")})}),0===G.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:K?D.trim()?R("chat.noMatchingModels"):R("chat.noAvailableModels"):R("agents.modelsLoading")}):G.map((e,t)=>(0,r.jsxs)("div",{children:[G.length>1&&(0,r.jsx)("div",{title:e.providerName===e.provider?void 0:e.provider,style:{padding:"6px 12px 4px",borderTop:t>0||v?"1px solid var(--border)":"none",color:"var(--text-dim)",fontSize:10,fontWeight:600,letterSpacing:0,textTransform:e.providerName===e.provider?"uppercase":"none"},children:e.providerName}),e.options.map(e=>(0,r.jsx)(rv,{active:e.modelId===f?.modelId&&e.provider===f?.provider,onSelect:()=>{let t;return t=e.modelId===f?.modelId&&e.provider===f?.provider,void(O(!1),B(""),!t||S?x(e.provider,e.modelId):b?.(e.provider,e.modelId))},star:$&&(!H||V(g,e))?{isDefault:e.modelId===E?.modelId&&e.provider===E?.provider,saveLabel:R("chat.saveDefaultModel"),defaultLabel:R("chat.defaultModel"),onSave:()=>{O(!1),B(""),$?.(e.provider,e.modelId)}}:void 0,children:(0,r.jsx)(rk,{label:e.name})},`${e.provider}:${e.modelId}`))]},e.provider))]})]}))]})}function rk(e){let{label:t}=e;return(0,r.jsx)("span",{title:t,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})}let rj=["configured","chat-only","read-only","default","full"],rw={configured:"configured","chat-only":"none","read-only":"read-only",default:"default",full:"full"},rS=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function rC(e,t,n){return t<=0?0:((e+n)%t+t)%t}function rN(e,t,n,r){e.setRangeText(r,t,n,"end"),e.dispatchEvent(new Event("input",{bubbles:!0}))}function rI(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:r.length,s=e.selectionStart,a=e.selectionEnd;if(e.focus(),s===a&&t<=s&&n>=a){let i=e.value.length-(n-t)+r.length;for(let n=s-t;n>0&&e.selectionStart>t&&document.execCommand("delete");n--);if(document.execCommand("insertText",!1,r))for(let t=n-a;t>0&&e.value.length>i&&document.execCommand("forwardDelete");t--);else rN(e,t,e.selectionStart+(n-a),r)}else e.setSelectionRange(t,n),document.execCommand("insertText",!1,r)||rN(e,t,n,r);i!==r.length&&e.setSelectionRange(t+i,t+i)}function rE(e){let t=e.scrollTop;e.style.height="auto",e.style.height=`${e.value?Math.min(e.scrollHeight,200):e.clientHeight}px`,e.style.overflowY=e.value&&e.scrollHeight>e.clientHeight?"auto":"hidden",e.scrollTop=t}function r$(e){e.selectionEnd===e.value.length&&(e.scrollTop=e.scrollHeight)}function rT(e,t){let n=null,r=()=>{n=null,t(function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8;return Math.max(0,Math.floor(e-t-n))}(e.getBoundingClientRect().bottom,function(e){let t=window.visualViewport?.offsetTop??0;for(let n=e.parentElement;n;n=n.parentElement){let e=window.getComputedStyle(n).overflowY;("auto"===e||"scroll"===e||"hidden"===e||"clip"===e)&&(t=Math.max(t,n.getBoundingClientRect().top+n.clientTop))}return t}(e)))},i=()=>{null!==n&&cancelAnimationFrame(n),n=requestAnimationFrame(r)};r();let s=e.parentElement,a=s?.parentElement,l="u">typeof ResizeObserver&&s?new ResizeObserver(i):null;s&&l?.observe(s),a&&l?.observe(a);let o=window.visualViewport;return o?.addEventListener("resize",i),o?.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("scroll",i,!0),()=>{l?.disconnect(),o?.removeEventListener("resize",i),o?.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("scroll",i,!0),null!==n&&cancelAnimationFrame(n)}}let rM=["auto","off","minimal","low","medium","high","xhigh","max"],rR={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 rA(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let rL=[{name:"compact",description:"chat.commandCompact",source:"builtin"},{name:"auto-compact",description:"chat.commandAutoCompact",source:"builtin"},{name:"reload",description:"chat.commandReload",source:"builtin"},{name:"name",description:"chat.commandName",source:"builtin"},{name:"session",description:"chat.commandSession",source:"builtin",availableWhileStreaming:!0},{name:"copy",description:"chat.commandCopy",source:"builtin",availableWhileStreaming:!0},{name:"clone",description:"chat.commandClone",source:"builtin"},{name:"side",description:"chat.commandSide",source:"builtin",availableWhileStreaming:!0}];function rP(e){return function(e){let t=e.trim().match(/^\/([^\s]+)(?:\s|$)/);if(t)return rL.find(e=>e.name===t[1])}(e)?.availableWhileStreaming===!0}let rz=["builtin","extension","prompt","skill"],rO={builtin:"chat.builtIn",extension:"chat.extensions",prompt:"chat.prompts",skill:"chat.skills"},rW={builtin:0,extension:1,prompt:2,skill:3};function rF(e,t){return"builtin"===e.source?t(e.description):e.description??""}function rD(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function rB(e){return{data:e.data,mimeType:e.mimeType}}function rH(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function r_(e){return(e??[]).filter(nV).slice(0,10).map(rH)}function rU(e){return"string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function rK(e){return"string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,n=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof n)return[];let r={data:t,mimeType:n};return nV(r)?[r]:[]})}function rq(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function rZ(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 rV(e){let{tone:t,title:n,body:i,onClose:s}=e,{t:a}=(0,eX.s)(),l="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(${l},0.3)`,borderRadius:6,background:`rgba(${l},0.07)`,color:`rgb(${l})`,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:n}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:i})]}),s&&(0,r.jsx)("button",{type:"button",onClick:s,"aria-label":a("sidebar.dismiss"),style:{flexShrink:0,background:"none",border:"none",padding:"0 2px",cursor:"pointer",color:"inherit",opacity:.7,fontSize:13,lineHeight:1},children:"\xd7"})]})}function rJ(e){let{cwd:t}=e,{t:n}=(0,eX.s)();return t?(0,r.jsx)(rV,{tone:"error",title:n("chat.cwdMissingTitle"),body:n("chat.cwdMissingBody",{cwd:t})}):null}function rG(e){let{error:t}=e,{t:n}=(0,eX.s)();return t?(0,r.jsx)(rV,{tone:"error",title:n("chat.modelError"),body:t}):null}function rY(e){let{warnings:t}=e,{t:n}=(0,eX.s)();return t&&0!==t.length?(0,r.jsx)(rV,{tone:"warning",title:n(t.length>1?"chat.modelScopeWarnings":"chat.modelScopeWarning"),body:t.join("\n")}):null}function rX(e){let{listening:t,title:n,ariaLabel:i,isMobile:s,onClick:a}=e;return(0,r.jsx)("button",{type:"button",onClick:a,title:n,"aria-label":i,"aria-pressed":t,style:{flexShrink:0,alignSelf:"flex-end",display:"grid",placeItems:"center",...s?{width:36,height:36}:{width:34,height:34},background:"transparent",border:"1px solid var(--border)",borderRadius:8,color:t?"var(--accent)":"var(--text-muted)",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:t?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"2",width:"6",height:"12",rx:"3"}),(0,r.jsx)("path",{d:"M5 10a7 7 0 0 0 14 0"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})})}function rQ(e){let{status:t,errorKind:n,interim:i,onRetry:s,t:a}=e;if("idle"===t)return null;if("listening"===t)return(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{marginTop:4,display:"flex",gap:8,alignItems:"baseline"},children:[(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--accent)"},children:a("chat.speechListening")}),i?(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-muted)"},children:i}):null]});let l=!1===window.isSecureContext,o=(()=>{switch(n){case"mic":return{title:a("chat.speechNoMic")};case"network":return{title:a("chat.speechNetwork")};case"permission":return l?{title:a("chat.speechInsecure")}:{title:a("chat.speechPermissionDenied"),hint:a("chat.speechPermissionHint")};default:return{title:a("chat.speechUnavailable")}}})();return(0,r.jsxs)("div",{className:"text-xs px-2 py-1",role:"status",style:{marginTop:4,display:"flex",gap:8,alignItems:"baseline",color:"rgba(239,68,68)"},children:[(0,r.jsx)("span",{style:{flexShrink:0},children:o.title}),o.hint?(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-muted)"},children:o.hint}):null,(0,r.jsx)("button",{type:"button",onClick:s,style:{flexShrink:0,background:"none",border:"none",padding:0,cursor:"pointer",color:"inherit",textDecoration:"underline",font:"inherit"},children:a("chat.speechRetry")})]})}let r0=(0,i.memo)((0,i.forwardRef)(function(e,t){let n,s,a,l,o,{onSend:d,onAbort:c,onSteer:u,onSideChat:p,onFollowUp:h,isStreaming:m,model:g,isAutoModelSelection:f,modelNames:x,modelList:b,modelError:v,missingCwd:y,modelScopeWarnings:k,allModelList:j,onLoadAllModels:w,onModelChange:S,modelSwitching:C,defaultModel:N,onSetDefaultModel:I,onCompact:E,onAbortCompaction:$,isCompacting:T,compactError:M,onDismissCompactError:R,compactResult:A,toolPreset:L,onToolPresetChange:P,newSessionEphemeral:z,onNewSessionEphemeralChange:O,thinkingLevel:W,isAutoThinkingSelection:F=!1,onThinkingLevelChange:D,availableThinkingLevels:B,thinkingLevelMap:H,savedDefaultThinkingLevel:_,onSetDefaultThinkingLevel:U,retryInfo:K,queuedMessages:q,inputHistory:Z=[],onRecallQueue:V,slashCommands:J,slashCommandsLoading:G,onLoadSlashCommands:Y,extensionUiOpen:X=!1,onBuiltinCommand:Q,soundEnabled:ee,onSoundToggle:et,onAudioUnlock:en,onPromptWithStreamingBehavior:er,draftKey:ei,cwd:es,onAttachFiles:ea,compact:el=!1}=e,{t:eo,locale:ed}=(0,eX.s)(),{fontSize:ec}=(0,rf.Uh)(),{ui:eu,uiWeight:ep}=(0,rx.VE)(),eh=(0,eQ.a)(),em=eh?44:32,eg=rh(),[ef,ex]=(0,i.useState)(()=>ei?nQ(ei)?.value??"":""),[eb,ev]=(0,i.useState)(!1),[ey,ek]=(0,i.useState)(!1),[ej,ew]=(0,i.useState)(!1),[eS,eC]=(0,i.useState)(()=>ei?r_(nQ(ei)?.images):[]),eN=ef.trimStart(),eI=0===eS.length&&eN.startsWith("!"),eE=eI&&eN.startsWith("!!"),[e$,eT]=(0,i.useState)(!1),[eM,eR]=(0,i.useState)(0),[eA,eL]=(0,i.useState)(null),[eP,ez]=(0,i.useState)(null),[eO,eW]=(0,i.useState)(!1),[eF,eD]=(0,i.useState)(null),[eB,eH]=(0,i.useState)(0),[e_,eU]=(0,i.useState)(!1),[eK,eq]=(0,i.useState)(!1),[eZ,eV]=(0,i.useState)(0),[eJ,eG]=(0,i.useState)(!1),eY=(0,i.useRef)(!1),e0=(0,i.useRef)(null),[e1,e2]=(0,i.useState)(null),[e4,e8]=(0,i.useState)(!1),[e6,e3]=(0,i.useState)(null),[e5,e9]=(0,i.useState)(null),e7=es&&e5?.cwd===es?e5.values:{},te=(0,i.useRef)(null),tt=(0,i.useRef)(null),tn=(0,i.useRef)(null),tr=(0,i.useRef)(null),ti=(0,i.useRef)(null),ts=(0,i.useRef)(null),ta=(0,i.useRef)(!1),tl=(0,i.useRef)(""),td=(0,i.useRef)(0),tc=(0,i.useRef)(null),tu=(0,i.useRef)(!1),tp=(0,i.useRef)(null),th=(0,i.useRef)([]),tm=(0,i.useRef)(null),tg=(0,i.useRef)([]),tf=(0,i.useRef)([]),tx=(0,i.useRef)(null),tb=(0,i.useRef)(null),tv=(0,i.useRef)(ei),ty=(0,i.useRef)(ef),tk=(0,i.useRef)(eS),tj=(0,i.useRef)(0);ty.current=ef,tk.current=eS;let tw=e=>{let t=te.current;if(!t)return void ex(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.value.slice(0,n),i=r&&!/\s$/.test(r)?" ":"";rI(t,n,t.selectionEnd??n,i+e),ez(null),requestAnimationFrame(()=>{rE(t),r$(t)})},tS=function(e){let{lang:t,onFinal:n}=e,[r,s]=(0,i.useState)(!1),[a,l]=(0,i.useState)("idle"),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(""),p=(0,i.useRef)(!1),h=(0,i.useRef)(null),m=(0,i.useRef)(n);(0,i.useEffect)(()=>{m.current=n});let g=(0,i.useRef)(t);(0,i.useEffect)(()=>{g.current=t},[t]);let f=(0,i.useRef)(250),x=(0,i.useRef)(0),b=(0,i.useRef)(0),v=(0,i.useRef)(void 0),y=(0,i.useRef)(void 0),k=(0,i.useCallback)(()=>{clearTimeout(v.current),v.current=void 0,clearTimeout(y.current),y.current=void 0},[]),j=(0,i.useCallback)(()=>{let e=h.current;if(e){e.onresult=null,e.onerror=null,e.onend=null,e.onspeechstart=null;try{e.abort()}catch{}h.current=null}},[]),w=(0,i.useCallback)(()=>{p.current=!1,k(),j(),l("idle"),u("")},[k,j]),S=(0,i.useCallback)(e=>{p.current=!1,k(),j(),d(e),l("error"),u("")},[k,j]),C=(0,i.useRef)(()=>{}),N=(0,i.useRef)(()=>{}),I=(0,i.useCallback)(()=>{clearTimeout(y.current),y.current=setTimeout(()=>{y.current=void 0,C.current()},1e4)},[]),E=(0,i.useCallback)(()=>{let e=rm();if(!e||!p.current)return;let t=new e;h.current=t,t.lang=g.current,t.continuous=!1,t.interimResults=!0,t.maxAlternatives=1,t.onresult=e=>{x.current=0,b.current=0,f.current=250;let t="";for(let n=e.resultIndex;n<e.results.length;n++){let r=e.results[n],i=r?.[0];if(!i)continue;let s=i.transcript??"";if(r.isFinal){let e=s.trim();e&&m.current?.(e)}else t+=s}u(t),I()},t.onspeechstart=()=>{I()},t.onerror=e=>{let t=e.error;"not-allowed"===t||"service-not-allowed"===t?S("permission"):"audio-capture"===t?S("mic"):"network"===t?b.current++:"no-speech"===t&&C.current()},t.onend=()=>{if(!p.current)return void u("");if(u(""),x.current++,x.current>6)return void S("unavailable");if(b.current>=2)return void S("network");k();let e=f.current;f.current=Math.min(2*f.current,5e3),v.current=setTimeout(()=>{v.current=void 0,p.current&&(j(),N.current())},e)};try{t.start(),I()}catch{S("unavailable")}},[I,k,S,j]);C.current=w,N.current=E;let $=(0,i.useCallback)(()=>{if(rm()&&!p.current){if(!1===window.isSecureContext)return void S("permission");p.current=!0,x.current=0,b.current=0,f.current=250,d(null),u(""),l("listening"),E()}},[S,E]),T=(0,i.useCallback)(()=>{w()},[w]),M=(0,i.useCallback)(()=>{p.current?w():$()},[$,w]);return(0,i.useEffect)(()=>{s(null!==rm())},[]),(0,i.useEffect)(()=>{p.current&&(k(),j(),E())},[t,k,j,E]),(0,i.useEffect)(()=>()=>{p.current=!1,k(),j()},[k,j]),{supported:r,status:a,errorKind:o,interim:c,start:$,stop:T,toggle:M}}({lang:rg[ed]??"en-US",onFinal:e=>{if(ta.current){tl.current+=(tl.current?" ":"")+e;return}tw(e)}}),{stop:tC}=tS;(0,i.useImperativeHandle)(t,()=>({setText(e){let t=te.current;if(!t){ty.current=e,ex(e);return}t.setSelectionRange(0,t.value.length),rI(t,0,t.value.length,e),ez(null),requestAnimationFrame(()=>rE(t))},pasteText(e){if(!e)return;let t=te.current;t?(rI(t,t.selectionStart??t.value.length,t.selectionEnd??t.value.length,e),ez(null),requestAnimationFrame(()=>rE(t))):ex(t=>t+e)},insertIfEmpty(e){let t=te.current;(t?t.value:ef).trim()||(ty.current=e,ex(e),ez(null),requestAnimationFrame(()=>{t&&(t.focus(),rE(t),r$(t))}))},replaceMessage(e){var t,n,r;let i=te.current;if(t=i?i.value:ef,n=tk.current.length,r=tj.current,t.trim()||0!==n||0!==r)return;let s=rU(e),a=r_(rK(e));ty.current=s,tk.current=a,ex(s),ez(null),eq(!1),eC(e=>(e.forEach(rq),a)),requestAnimationFrame(()=>{i&&(i.focus(),rE(i),r$(i))})},prependText(e){if(!e.trim())return;let t=te.current,n=[e,t?t.value:ef].filter(e=>e.trim()).join("\n\n");ty.current=n,ex(n),ez(null),requestAnimationFrame(()=>{t&&(t.focus(),t.setSelectionRange(n.length,n.length),rE(t),r$(t))})},rekeyDraft(e,t){if(e===t)return;if(tv.current!==e)return void n6(e,t);let n={value:ty.current,images:tk.current.map(rB)},r=n6(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(tv.current=t,i)return;let s=r_(r.images);ty.current=r.value,tk.current=s,ex(r.value),eC(e=>(e.forEach(rq),s)),ez(null),eq(!1)},restoreSubmission(e,t,n){if(!e.trim()&&!t?.length)return;let r=tv.current,i=n??r,s=i===r,a=!s&&i?nQ(i):null,l=n4(e,t,s?ty.current:a?.value??"",s?tk.current.map(rB):a?.images??[]);if(i&&n0(i,l),!s)return;let o=t?.length?[...r_(t).slice(0,Math.max(0,10-tk.current.length)),...tk.current].slice(0,10):tk.current;ty.current=l.value,tk.current=o,ex(t=>{let n=n2(e,t);return ty.current=n,n}),ez(null),eq(!1),t?.length&&eC(e=>{let n=Math.max(0,10-e.length),r=r_(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tk.current=i,i}),requestAnimationFrame(()=>{let e=te.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),rE(e),r$(e))})},focus(){let e=te.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length))},insertText(e){let t=te.current;if(!t)return void ex(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n);rI(t,n,r,(i.length>0&&!i.endsWith(" ")?" ":"")+e),ez(null)},insertQuote(e){let t=te.current;if(!t)return void ex(t=>t+nU(t)+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length;rI(t,n,r,nU(t.value.slice(0,n))+e),ez(null)},addImages(e){tN(e)}}));let tN=(0,i.useCallback)(async e=>{if(el)return;let t=Math.max(0,10-tk.current.length-tj.current),n=e.filter(e=>e.type.startsWith("image/")&&e.size<=0xa00000).slice(0,t);if(n.length){tj.current+=n.length;try{let e=await Promise.all(n.map(async e=>{var t;return{...await (t=e.type,new Promise((n,r)=>{let i=new FileReader;i.onload=()=>{let e="string"==typeof i.result?i.result.split(",")[1]:void 0;e?n({data:e,mimeType:t}):r(Error("Failed to read image"))},i.onerror=r,i.readAsDataURL(e)})),previewUrl:URL.createObjectURL(e)}}));eC(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(rq);let r=[...t,...n];return tk.current=r,r})}finally{tj.current-=n.length}}},[el]),tI=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",ea?ea(t):tN(t)},[ea,tN]),tE=(0,i.useCallback)(e=>{eC(t=>{let n=[...t],[r]=n.splice(e,1);return r&&rq(r),tk.current=n,n})},[]),t$=(0,i.useCallback)(()=>{tk.current=[],eC(e=>(e.forEach(rq),[]))},[]),tT=(0,i.useCallback)(()=>{ty.current="",ex(""),ez(null),eq(!1),ei&&n1(ei),tv.current&&tv.current!==ei&&n1(tv.current),t$(),te.current&&(te.current.style.height="auto"),tC()},[t$,ei,tC]);(0,i.useEffect)(()=>{ei&&tv.current===ei&&n0(ei,{value:ef,images:eS.map(rB)})},[eS,ei,ef]),(0,i.useEffect)(()=>{let e=tv.current;if(e===ei)return;e&&n0(e,{value:ty.current,images:tk.current.map(rB)});let t=ei?nQ(ei):null;tv.current=ei;let n=t?.value??"",r=r_(t?.images);ty.current=n,tk.current=r,ex(n),ez(null),eq(!1),eC(e=>(e.forEach(rq),r))},[ei]);let tM=(0,i.useCallback)(()=>{let e=te.current;e&&(e.value?rE(e):(e.style.height="auto",e.style.overflowY="hidden"))},[]);(0,i.useLayoutEffect)(tM,[ef,ec,eu,ep,tM]),(0,i.useEffect)(()=>{let e=te.current;if(!e)return;let t=-1,n=new ResizeObserver(e=>{let[n]=e;n.contentRect.width!==t&&(t=n.contentRect.width,tM())});return n.observe(e),()=>n.disconnect()},[tM]),(0,i.useEffect)(()=>{let e=te.current;if(!e)return;let t=t=>{if("insertLineBreak"!==t.inputType||t.isComposing)return;let n=function(e,t,n){let r;if(t!==n)return null;let i=e.lastIndexOf("\n",t-1)+1,s=e.indexOf("\n",t),a=-1===s?e.length:s,l=e.slice(i,a),o=function(e){if(re.test(e))return null;let t=n5.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=n9.exec(e)??n7.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}(l);return!o||t-i<o.length||function(e){let t=null;for(let n of e.split("\n")){let e=rt.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:""===l.slice(o.length).trim()?{start:i,end:a,text:""}:{start:t,end:t,text:`
7
+ ${r=null===o.number?o.marker:`${String(Number(o.number)+1).padStart(o.number.length,"0")}${o.delimiter}`,`${o.indent}${r}${o.spacing}${o.task?"[ ] ":""}`}`}}(e.value,e.selectionStart,e.selectionEnd);n&&(t.preventDefault(),e.setSelectionRange(n.start,n.end),document.execCommand(n.text?"insertText":"delete",!1,n.text))};return e.addEventListener("beforeinput",t),()=>e.removeEventListener("beforeinput",t)},[]),(0,i.useEffect)(()=>()=>{tk.current.forEach(rq)},[]),(0,i.useLayoutEffect)(()=>{if(eJ){let e=e=>{e.target!==e0.current&&(e0.current=null)};return document.addEventListener("pointerdown",e,!0),()=>document.removeEventListener("pointerdown",e,!0)}let e=e0.current;e0.current=null,e?.isConnected&&document.activeElement===document.body&&!document.querySelector('[aria-modal="true"]')&&e.focus({preventScroll:!0})},[eJ]);let tR=(0,i.useCallback)(async e=>{if(eS.length||!e.startsWith("/")||!Q)return!1;if(eY.current)return!0;e0.current=document.activeElement===te.current?te.current:null,eY.current=!0,eG(!0);try{var t,n;let r=await Q(e);if(!r.handled)return!1;return r.error||(t=ty.current,n=tk.current.length,0!==n||t.trim()!==e)||tT(),!0}finally{eY.current=!1,eG(!1)}},[eS.length,tT,Q]),tA=(0,i.useCallback)(async()=>{var e;let t=ef.trim();(t||eS.length)&&(en?.(),(!m||rP(e=t)||rr(e))&&await tR(t)||(!m||t.startsWith("!")&&!eS.length)&&(tT(),d(t,eS.length?eS:void 0)))},[ef,eS,m,tR,d,tT,en]),tL=!el&&ef.startsWith("/")&&!/\s/.test(ef.slice(1))?ef.slice(1).toLowerCase():null,tP=(()=>{var e;let t,n;return null===tL?[]:(e=[...m?rL.filter(e=>e.availableWhileStreaming):rL,...J??[]],((n=(t=e.map(e=>{let t,n;return{command:e,rank:(t=e.name.toLowerCase(),(n="skill"===e.source&&t.startsWith("skill:")?t.slice(6):t)===tL||t===tL?0:n.startsWith(tL)||t.startsWith(tL)?1:t.includes(tL)?2:3)}})).filter(e=>{let{rank:t}=e;return t<3})).length>0?n:t.filter(e=>{let{command:t}=e;return rF(t,eo).toLowerCase().includes(tL)})).sort((e,t)=>e.rank-t.rank||rW[e.command.source]-rW[t.command.source]||rS.compare(e.command.name,t.command.name)).map(e=>{let{command:t}=e;return t}))})(),{commands:tz,groups:tO}=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",r=0,i=rz.map(i=>{let s=e.filter(e=>e.source===i),a="skill"!==i||n?s:[...s.filter(e=>!rD(e,t)),...s.filter(e=>rD(e,t))];return{source:i,items:a.map(e=>({command:e,index:r++}))}}).filter(e=>e.items.length>0);return{commands:i.flatMap(e=>e.items.map(e=>{let{command:t}=e;return t})),groups:i}}(tP,e7,tL??""),tW=1===tP.length?eo(tL?"chat.match":"chat.command"):eo(tL?"chat.matches":"chat.commands",{count:tP.length}),tF=!!ef.trim()||eS.length>0,tD=el||eh&&m,tB=eS.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)&&!e_;(0,i.useEffect)(()=>{0===eS.length&&eU(!1)},[eS.length]);let tH=(0,i.useCallback)((e,t)=>{if(!es)return void ez(null);let n=t??e.length;ez((0,n3.RO)(e.slice(0,n)))},[es]),t_=eP?.query??null,tU=i.useMemo(()=>null!==t_&&e1&&e1.cwd===es?(0,n3.R7)(e1.entries,t_):[],[t_,e1,es]),tK=!!(t_&&e1?.truncated&&e1.cwd===es);(0,i.useEffect)(()=>{if(!tK||!es||!t_)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(es)}&q=${encodeURIComponent(t_)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>e3({cwd:es,query:t_,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tK,t_,es]);let tq=tK&&null!==e6&&e6.cwd===es&&e6.query===t_,tZ=tq?e6.matches:tU,tV=null===eP?null:`${eP.start}:${+!!eP.quoted}:${eP.query}`;(0,i.useEffect)(()=>{if(null===tV){eW(!1),eH(0);return}eW(!0),eH(0)},[tV]);let tJ=null!==eP;(0,i.useEffect)(()=>{if(!tJ||!es)return;let e=tx.current;e&&e.cwd===es&&Date.now()-e.fetchedAt<1e4||tb.current===es||(tb.current=es,e8(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(es)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{e2({cwd:es,entries:(0,n3.Yh)(e.files??[]),truncated:!!e.truncated}),tx.current={cwd:es,fetchedAt:Date.now()}}).catch(()=>{tx.current=null}).finally(()=>{tb.current=null,e8(!1)}))},[tJ,es]);let tG=(0,i.useCallback)(e=>{if(!eP)return;let t=te.current;if(!t)return;let n=t.selectionStart??t.value.length,r=n+(eP.quoted&&'"'===t.value[n]?1:0),i=(0,n3.W)(e.path,e.isDir,eP.quoted),s=eP.start+i.cursorOffset;rI(t,eP.start,r,i.text,i.cursorOffset),ez((0,n3.RO)(t.value.slice(0,s)))},[eP]);(0,i.useEffect)(()=>{eB>=tZ.length&&eH(Math.max(0,tZ.length-1))},[tZ.length,eB]),(0,i.useEffect)(()=>{tg.current.length=tZ.length},[tZ.length]),(0,i.useEffect)(()=>{eO&&tg.current[eB]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eB,eO]),(0,i.useEffect)(()=>{eZ>=Z.length&&eV(Math.max(0,Z.length-1))},[Z.length,eZ]),(0,i.useEffect)(()=>{tf.current.length=Z.length},[Z.length]),(0,i.useEffect)(()=>{eK&&!X&&tf.current[eZ]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eZ,eK,X]);let tY=(0,i.useCallback)(e=>{ex(e),eq(!1),eV(0),ez(null),requestAnimationFrame(()=>{let t=te.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),rE(t),r$(t))})},[]),tX=(0,i.useCallback)(e=>{let t=`/${e.name} `;ex(t),eT(!1),eR(0),requestAnimationFrame(()=>{let e=te.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),rE(e))})},[]),tQ=(0,i.useCallback)(()=>{let e=ef.trim();e&&!eS.length&&p&&(tT(),p(e))},[ef,eS,p,tT]),t0=(0,i.useCallback)(e=>{let t=ef.trim();if(!t&&!eS.length)return;if(t.startsWith("!")&&!eS.length)return void tA();en?.();let n=eS.length?eS:void 0,r=()=>{if(t.startsWith("/")&&er){tT(),er(t,"steer"===e?"steer":"followUp",n);return}tT(),"steer"===e&&u?u(t,n):"followup"===e&&h&&h(t,n)};!eS.length&&Q&&rP(t)?tR(t):!eS.length&&Q&&rr(t)?tR(t).then(e=>{e||r()},()=>r()):r()},[ef,eS,Q,er,u,h,tT,en,tR,tA]),t1=(0,i.useCallback)(e=>{let t=tz.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eM-1);if("right"===e)return Math.min(t,eM+1);let n=th.current[eM];if(!n)return"down"===e?Math.min(t,eM+1):Math.max(0,eM-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,s=r.top+r.height/2,a=-1,l=1/0;for(let n=0;n<=t;n+=1){if(n===eM)continue;let t=th.current[n];if(!t)continue;let r=t.getBoundingClientRect(),o=r.top+r.height/2-s;if("down"===e?o<=4:o>=-4)continue;let d=1e3*Math.abs(o)+Math.abs(r.left+r.width/2-i);d<l&&(a=n,l=d)}return a>=0?a:"down"===e?Math.min(t,eM+1):Math.max(0,eM-1)},[tz.length,eM]),t2=(0,i.useCallback)(e=>{let t=e.nativeEvent,n="Enter"===e.key&&!e.shiftKey,r=eh||"ctrlEnter"===eg?n&&(e.ctrlKey||e.metaKey):n,i=eh?r:n,s=Date.now()-td.current<100,a=ta.current||t.isComposing||229===t.keyCode;if(i&&(a||s)){s&&e.preventDefault();return}if(eK&&!X&&!a){if("ArrowDown"===e.key){e.preventDefault(),eV(e=>Math.min(Math.max(0,Z.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eV(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),eq(!1);return}if(("Tab"===e.key||i)&&Z[eZ]){e.preventDefault(),tY(Z[eZ]);return}}if(e$&&null!==tL&&!X){if("ArrowDown"===e.key){e.preventDefault(),eR(t1("down"));return}if("ArrowUp"===e.key){e.preventDefault(),eR(t1("up"));return}if("ArrowRight"===e.key){e.preventDefault(),eR(t1("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),eR(t1("left"));return}if("Escape"===e.key){e.preventDefault(),eT(!1);return}let t=tz[eM];if("Tab"===e.key&&t){e.preventDefault(),tX(t);return}if(i&&t){e.preventDefault(),r&&function(e,t,n){if("builtin"===t.source)return"builtin"===t.source&&e.trim()===`/${t.name}`&&(!n||!0===t.availableWhileStreaming);return rn(t)&&rr(e)}(ef,t,m)?(eT(!1),tA()):tX(t);return}}if(eO&&null!==eP&&!X&&!a){if("ArrowDown"===e.key){e.preventDefault(),eH(e=>rC(e,tZ.length,1));return}if("ArrowUp"===e.key){e.preventDefault(),eH(e=>rC(e,tZ.length,-1));return}if("Escape"===e.key){e.preventDefault(),eW(!1);return}if(("Tab"===e.key||i)&&tZ[eB]){e.preventDefault(),tG(tZ[eB]);return}}if("ArrowUp"===e.key&&!a&&!m&&Z.length>0&&0===ef.trim().length){e.preventDefault(),eT(!1),eW(!1),eV(Z.length-1),eq(!0);return}if("Escape"===e.key&&!a&&m&&c){e.preventDefault(),c();return}r&&(e.preventDefault(),m&&(u||h)?t0(e.altKey&&h||!u?"followup":"steer"):tA())},[eh,eg,m,u,h,c,X,e$,tL,tz,eM,tX,t0,tA,t1,eO,eP,tZ,eB,tG,eK,Z,eZ,tY,ef]),t4=(0,i.useCallback)(()=>{tc.current=null;let e=te.current;e&&rE(e)},[]),t8=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!el&&t.length){e.preventDefault(),tN(t.map(e=>e.getAsFile()).filter(e=>null!==e));return}let n=e.clipboardData.getData("text/html"),r=e.clipboardData.getData("text/plain");if(r){let t=e.currentTarget,n=e.nativeEvent,i=t.selectionStart,s=t.selectionEnd,a={};tc.current=a,setTimeout(()=>{tc.current===a&&(tc.current=null,!n.defaultPrevented&&t.isConnected&&rI(t,i,s,r))},0)}if(!n||!r)return;let i=new DOMParser().parseFromString(n,"text/html"),s=function(e,t){let n="",r=0,i=!1;for(let{label:s,href:a,occurrence:l}of t){if(!s||!a)continue;let t=0;for(let n=0;n<=l&&!((t=e.indexOf(s,n?t+s.length:0))<0);n++);if(t<r)continue;let o=s.replace(/([\\[\]])/g,"\\$1"),d=a.replace(/([\\()])/g,"\\$1");n+=`${e.slice(r,t)}[${o}](${d})`,r=t+s.length,i=!0}return i?n+e.slice(r):null}(r,Array.from(i.querySelectorAll("a[href]"),e=>{let t=e.textContent??"",n=i.createRange();return n.setStart(i.body,0),n.setEndBefore(e),{label:t,href:e.getAttribute("href")?.trim()??"",occurrence:t?n.toString().split(t).length-1:0}}));if(null===s)return;let a=e.currentTarget,l=a.selectionStart,o=a.value.slice(0,l)+s+a.value.slice(a.selectionEnd);e.preventDefault(),ty.current=o,ex(o),eq(!1),tH(o,l+s.length),requestAnimationFrame(()=>{a.focus(),a.setSelectionRange(l+s.length,l+s.length),r$(a)})},[el,tN,tH]);(0,i.useEffect)(()=>{if(null===tL){eT(!1),eR(0),tu.current=!1;return}eT(!0),eR(0),!tu.current&&Y&&(tu.current=!0,Promise.resolve(Y()).catch(()=>{tu.current=!1}))},[tL,Y]),(0,i.useEffect)(()=>{if(!e$||!es)return;let e=!1;return e9({cwd:es,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(es)}`).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;e9({cwd:es,values:n})}).catch(()=>{e||e9({cwd:es,values:{}})}),()=>{e=!0}},[e$,es]),(0,i.useEffect)(()=>{eM>=tz.length&&eR(Math.max(0,tz.length-1))},[tz.length,eM]),(0,i.useEffect)(()=>{th.current.length=tz.length},[tz.length]),(0,i.useEffect)(()=>{e$&&!X&&th.current[eM]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eM,e$,X]),(0,i.useLayoutEffect)(()=>{if(!e$||null===tL||X)return void eL(null);let e=tp.current;if(e)return rT(e,e=>{eL(t=>t===e?t:e)})},[e$,tL,X]),(0,i.useLayoutEffect)(()=>{if(!eO||null===eP||X)return void eD(null);let e=tm.current;if(e)return rT(e,e=>{eD(t=>t===e?t:e)})},[eO,eP,X]);let t6=b&&b.length>0?b.map(e=>({provider:e.provider,providerName:e.providerName,modelId:e.id,name:e.name})):Object.entries(x??{}).map(e=>{let[t,n]=e;return{provider:g?.provider??"unknown",modelId:t,name:n}}),t3=A?Math.max(0,A.tokensBefore-A.estimatedTokensAfter):0,t5=A?`${A.reason&&"manual"!==A.reason?`${A.reason[0].toUpperCase()}${A.reason.slice(1)} `:eo("chat.compacted")} ${rA(A.tokensBefore)} -> ${rA(A.estimatedTokensAfter)} tokens (${eo("chat.tokensSaved",{saved:rA(t3)})})`:null,t9=W&&"auto"!==W?W:null,t7="auto"!==(n=t9??"auto")&&H?H[n]??n:n,ne=Object.entries(rw).find(e=>{let[,t]=e;return t===(L??"configured")})?.[0]??"configured",nt="chat-only"===ne?eo("chat.chatOnly"):ne;(0,i.useEffect)(()=>{let e=e=>{tt.current&&!tt.current.contains(e.target)&&ev(!1),tn.current&&!tn.current.contains(e.target)&&ek(!1),tr.current&&!tr.current.contains(e.target)&&ew(!1),!ti.current||ti.current.contains(e.target)||te.current?.contains(e.target)||eq(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{m&&ev(!1)},[m]);let nn=(0,i.useRef)(-1/0);(0,i.useLayoutEffect)(()=>{if(m)return()=>{nn.current=performance.now()}},[m]);let nr=e=>{var t,n;return t=e.detail,n=performance.now()-nn.current,t>0&&n<600};return(0,i.useEffect)(()=>{eh||ew(!1)},[eh]),(0,r.jsxs)("fieldset",{disabled:eJ,"aria-busy":eJ,className:el?void 0:"chat-input-shell",style:{...el?{flexShrink:0}:{display:"flex",flexDirection:"column",minHeight:0},minWidth:0,margin:0,border:0,background:"transparent",padding:el?0:"0 16px 8px",paddingRight:el?0:eh?16:52,opacity:eJ?.5:1,transition:"opacity 0.15s"},children:[!el&&(0,r.jsx)("input",{ref:ts,type:"file",accept:ea?void 0:"image/*",multiple:!0,style:{display:"none"},onChange:tI}),(0,r.jsxs)("div",{style:{...el?void 0:{display:"flex",flexDirection:"column",minHeight:0,width:"100%"},maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(0,r.jsx)(rJ,{cwd:y}),(0,r.jsx)(rG,{error:v}),(0,r.jsx)(rY,{warnings:k}),tB&&(s=b?.find(e=>e.provider===g?.provider&&e.id===g?.modelId),(0,r.jsx)(rV,{tone:"warning",title:eo("chat.imageNotSupportedTitle"),body:eo("chat.imageNotSupportedBody",{model:s?.name||g?.modelId||""}),onClose:()=>eU(!0)})),(q?.steering.length??0)+(q?.followUp.length??0)>0&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:72,marginBottom:8,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:eo("chat.queued",{count:(q?.steering.length??0)+(q?.followUp.length??0)})}),V&&(0,r.jsxs)("button",{onClick:V,title:eo("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"})]}),eo("chat.recall")]})]}),(0,r.jsxs)("div",{style:{maxHeight:"min(180px, calc(var(--app-viewport-height, 100dvh) * 0.25))",overflowY:"auto",overscrollBehavior:"contain"},children:[q?.steering.map((e,t)=>(0,r.jsx)(rZ,{kind:"steer",text:e},`steer-${t}`)),q?.followUp.map((e,t)=>(0,r.jsx)(rZ,{kind:"follow-up",text:e},`followup-${t}`))]})]}),K&&(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"})]}),eo("chat.retrying",{attempt:K.attempt,max:K.maxAttempts}),K.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",K.errorMessage]})]}),t5&&(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"})}),t5]}),M&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,marginBottom:8,padding:R?"3px 3px 3px 10px":"7px 10px",background:"rgba(239,68,68,0.07)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:6,color:"#ef4444",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,padding:R?"4px 0":0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:M}),R&&(0,r.jsx)(to.R,{onClick:R,title:eo("chat.dismissCompactError")})]}),eS.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:eS.map((e,t)=>(0,r.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,r.jsx)(rs.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:()=>tE(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:[eK&&!X&&Z.length>0&&(0,r.jsxs)("div",{ref:ti,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",maxHeight:"min(44vh, 360px)"},children:[(0,r.jsx)("div",{title:eo("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:Z.map((e,t)=>{let n=t===eZ;return(0,r.jsxs)("button",{ref:e=>{tf.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tY(e)},onMouseEnter:()=>eV(t),style:{width:"100%",display:"flex",alignItems:"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}`)})})]}),e$&&null!==tL&&!X&&(0,r.jsxs)("div",{ref:tp,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eA?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${eA}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:G?eo("chat.loadingCommands"):eo("chat.slashCommands",{label:tW})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eo("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:10},children:G||0!==tP.length?tO.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:eo(rO[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===eM,s=rD(t,e7);return(0,r.jsxs)("button",{ref:e=>{th.current[n]=e},type:"button",onMouseDown:e=>{e.preventDefault(),tX(t)},onMouseEnter:()=>eR(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:eo("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:rF(t,eo)})]},`${t.source}:${t.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eo("chat.noCommands")})})]}),eO&&null!==eP&&!X&&(a=e4&&(!e1||e1.cwd!==es),l=1===tZ.length?eo("chat.match"):eo("chat.matches",{count:tZ.length}),o=e1?.truncated&&!tq?eP.query?eo("chat.searchingAll"):eo("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:tm,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eF?"min(48vh, 400px)":`min(48vh, 400px, ${eF}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:a?eo("chat.loadingFiles"):eo("chat.files",{label:l,hint:o})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eo("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:a||0!==tZ.length?tZ.map((e,t)=>{let n=t===eB,i=e.path.split("/").pop()??e.path,s=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tg.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tG(e)},onMouseEnter:()=>eH(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)(ri.sj,{size:14}):(0,ri.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:tK&&!tq?eo("chat.searching"):eo("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:tD?void 0:"chat-composer-row",style:{minWidth:0,display:"flex",flexDirection:tD?"column":"row",gap:8,alignItems:tD?"stretch":"center",background:"var(--bg)",border:el?"none":`1px solid ${eI?"var(--tool-bg)":m&&(u||h)?"rgba(234,179,8,0.4)":"color-mix(in srgb, var(--border) 70%, transparent)"}`,borderRadius:14*!el,padding:el?0:eh?"6px 6px 6px 12px":"10px 10px 10px 14px",boxShadow:el?"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:te,className:"chat-input-textarea","aria-label":el?eo("chat.askInSideChat"):void 0,value:ef,onChange:e=>{ty.current=e.target.value,ex(e.target.value),eq(!1),tH(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;tH(t.value,t.selectionStart)},onKeyDown:t2,onCompositionStart:()=>{ta.current=!0},onCompositionEnd:e=>{ta.current=!1,td.current=Date.now();let t=e.currentTarget;if(tH(t.value,t.selectionStart),tl.current){let e=tl.current;tl.current="",tw(e)}},onInput:t4,onPaste:t8,placeholder:T?eo("chat.compactingPlaceholder"):m&&(u||h)?eo("chat.steerPlaceholder"):m?eo("chat.agentPlaceholder"):eo("chat.messagePlaceholder"),rows:1,style:{flex:tD?"none":1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:"var(--chat-content-font-size, 14px)",lineHeight:1.6,fontFamily:"inherit",minHeight:el?96:24,maxHeight:200,overflow:"auto"}}),tS.supported&&(0,r.jsx)(rX,{listening:"listening"===tS.status,title:"listening"===tS.status?eo("chat.speechStop"):eo("chat.speechDictate"),ariaLabel:"listening"===tS.status?eo("chat.speechStop"):eo("chat.speechDictate"),isMobile:eh,onClick:tS.toggle}),m&&!eI?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[p&&(0,r.jsx)("button",{type:"button",onClick:tQ,disabled:!ef.trim()||eS.length>0,title:eo("chat.sideChatHint"),"aria-label":eo("chat.sideChat"),className:`bg-transparent ${ef.trim()&&!eS.length?"cursor-pointer text-text-muted hover:bg-bg-hover hover:text-text":"cursor-not-allowed text-text-dim"}`,style:{width:38,display:"grid",placeItems:"center",padding:0,border:"1px solid var(--border)",borderRadius:8,transition:"background 0.12s"},children:(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"}),(0,r.jsx)("path",{d:"M13 8.5v7M9.5 12h7"})]})}),u&&(0,r.jsxs)("button",{onClick:()=>t0("steer"),disabled:!tF,title:eo("chat.steerHint"),"aria-label":eo("chat.steer"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tF?"rgba(234,179,8,0.12)":"none",border:"1px solid rgba(234,179,8,0.35)",borderRadius:8,color:tF?"rgba(180,130,0,1)":"var(--text-dim)",cursor:tF?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{className:"chat-composer-run-label",children:eo("chat.steer")})]}),h&&(0,r.jsxs)("button",{onClick:()=>t0("followup"),disabled:!tF,title:`${eo("chat.followUpHint")} (${eh?"Ctrl/Cmd+":""}Alt/Option+Enter)`,"aria-label":eo("chat.followUp"),"aria-keyshortcuts":eh?"Control+Alt+Enter Meta+Alt+Enter":"Alt+Enter",style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tF?"rgba(129,140,248,0.12)":"none",border:"1px solid rgba(129,140,248,0.35)",borderRadius:8,color:tF?"rgba(99,102,241,1)":"var(--text-dim)",cursor:tF?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),(0,r.jsx)("span",{className:"chat-composer-run-label",children:eo("chat.followUp")})]})]}):(0,r.jsxs)("button",{onClick:tA,disabled:!ef.trim()&&!eS.length,title:eo("chat.send"),"aria-label":eo("chat.send"),style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,...eh?{width:36,height:36,padding:0}:{padding:"7px 14px"},background:ef.trim()||eS.length?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:ef.trim()||eS.length?"var(--accent-contrast)":"var(--text-dim)",cursor:ef.trim()||eS.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:ef.trim()||eS.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"})]}),!eh&&eo("chat.send")]})]})]}),eI&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eE?"var(--text-muted)":"var(--accent)",marginTop:4},children:[eo("chat.shell")," \xb7 ",eE?eo("chat.outputLocal"):eo("chat.outputModel")]}),(0,r.jsx)(rQ,{status:tS.status,errorKind:tS.errorKind,interim:tS.interim,onRetry:tS.start,t:eo}),!el&&(0,r.jsxs)("div",{className:"chat-input-controls",style:{marginTop:eh?4:8,display:eh?"grid":"flex",gridTemplateColumns:eh?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:eh?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2},children:[(0,r.jsx)("button",{onClick:()=>ts.current?.click(),title:eo("chat.attachFiles"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:em,height:em,padding:0,background:"none",border:"none",borderRadius:9,color:eS.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=eS.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=eS.length?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:eh?18:15,height:eh?18:15,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),(t6.length>0||g||v)&&S&&(0,r.jsx)(ry,{options:t6,value:g,onChange:S,onReselect:S,busy:C,isAutoSelection:f,defaultValue:N,onSetDefault:I,allOptions:j?.map(e=>({provider:e.provider,providerName:e.providerName,modelId:e.id,name:e.name})),onShowAll:w}),O&&(0,r.jsx)("button",{type:"button",onClick:()=>O(!z),title:eo("ephemeral.toggleHint"),"aria-label":eo("ephemeral.toggle"),"aria-pressed":!0===z,style:{display:"flex",alignItems:"center",justifyContent:"center",width:eh?30:26,height:eh?30:26,border:"none",borderRadius:6,background:"none",color:z?"var(--accent)":"var(--text-muted)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=z?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=z?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:eh?18:15,height:eh?18:15,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:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"}),(0,r.jsx)("path",{d:"M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,r.jsx)("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),(0,r.jsx)("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})})]}),!eh&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsxs)("div",{ref:tr,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:eh?0:"auto"},children:[eh&&(0,r.jsx)("button",{type:"button",title:ej?void 0:eo("chat.moreControls"),"aria-label":eo("chat.moreControls"),"aria-expanded":ej,"aria-hidden":ej||void 0,tabIndex:ej?-1:void 0,onClick:()=>{ew(!0)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:em,padding:"8px 10px",background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:ej?"default":"pointer",fontSize:12,fontWeight:500,visibility:ej?"hidden":"visible",pointerEvents:ej?"none":"auto",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{ej||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{ej||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:eo("chat.moreControls")}),(0,r.jsxs)("div",{style:{display:eh?ej?"flex":"none":"flex",alignItems:"center",gap:eh?1:2,...eh?{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:[D&&(0,r.jsxs)("div",{ref:tn,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>ek(e=>!e),title:m?eo("chat.currentReasoning",{level:t7}):eo("chat.changeReasoning",{level:t7}),"aria-label":eo("chat.changeReasoningLabel"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eh?"0 10px":"8px 12px",width:eh?"auto":void 0,height:em,background:ey?"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=ey?"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"})]}),(!eh||ej)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t7})]}),ey&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",...eh?{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:rM.filter(e=>!B||"auto"===e||B.includes(e)).map(e=>{let t="auto"===e?F:!F&&t9===e,n=eo(rR[e]),i="auto"!==e&&H?H[e]:void 0,s=null!=i&&i!==e?i:e,a=null!=i&&i!==e;return(0,r.jsxs)(rv,{active:t,onSelect:()=>{if(ek(!1),"auto"===e){F||D("auto");return}(!t||F)&&D(e)},gutter:!!U,star:U&&"auto"!==e?{isDefault:_===e,saveLabel:eo("chat.saveDefaultThinking"),defaultLabel:eo("chat.defaultThinking"),onSave:()=>{ek(!1),U(e)}}:void 0,children:[(0,r.jsxs)("span",{style:{flex:1},children:[s,a&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",e,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:n})]},e)})})]}),!m&&P&&(0,r.jsxs)("div",{ref:tt,style:{position:eh?"static":"relative"},children:[(0,r.jsxs)("button",{onClick:e=>{m||nr(e)||ev(e=>!e)},disabled:m,title:eo("chat.changeToolPreset")+`: ${nt}`,"aria-label":eo("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eh?"0 10px":"8px 12px",width:eh?"auto":void 0,height:em,background:eb?"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=eb?"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"})}),(!eh||ej)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nt})]}),eb&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,maxWidth:eh?"calc(100vw - 16px)":void 0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:120},children:rj.map(e=>{let t,n=rw[e],i=(L??"configured")===n;return t="configured"===e?eo("chat.configuredTools"):"chat-only"===e?eo("chat.chatOnly"):"read-only"===e?eo("chat.readOnlyTools",{count:4}):"default"===e?eo("chat.builtInTools",{count:4}):eo("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{ev(!1),i||P(n)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:t})]},e)})})]}),(!m||T)&&E&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{onClick:T?$:e=>{nr(e)||E()},style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eh?"0 10px":"8px 12px",width:eh?"auto":void 0,height:em,background:T?"rgba(239,68,68,0.08)":"none",border:"none",borderRadius:9,color:T?"#ef4444":"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=T?"rgba(239,68,68,0.16)":"var(--bg-hover)",e.currentTarget.style.color=T?"#ef4444":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=T?"rgba(239,68,68,0.08)":"none",e.currentTarget.style.color=T?"#ef4444":"var(--text-muted)"},title:T?eo("chat.stopCompaction"):eo("chat.compactContext"),"aria-label":T?eo("chat.stopCompaction"):eo("chat.compactContext"),children:T?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(!eh||ej)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eo("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"})]}),(!eh||ej)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eo("chat.compact")})]})})}),m&&(0,r.jsxs)("button",{onClick:c,title:eo("chat.stopAgent"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:em,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"})}),eo("chat.stop")]}),void 0!==et&&(0,r.jsx)("button",{onClick:et,title:ee?eo("chat.disableSound"):eo("chat.enableSound"),"aria-label":ee?eo("chat.disableSound"):eo("chat.enableSound"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:em,height:em,padding:0,background:"none",border:"none",borderRadius:9,color:ee?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",opacity:ee?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=ee?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.opacity=ee?"1":"0.55"},children:ee?(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"})]})}),eh&&ej&&(0,r.jsx)("button",{type:"button",title:eo("chat.collapseControls"),"aria-label":eo("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{ev(!1),ek(!1),ew(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:eh?em:36,height:em,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 r1=n(19109),r2=n(32316),r4=n(88374),r8=n(68925);function r6(){try{return window.localStorage}catch{return null}}function r3(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:r6();if(!t)return!1;try{return"true"===t.getItem(e)}catch{return!1}}function r5(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:r6();if(n)try{n.setItem(e,String(t))}catch{}}let r9="pi-web:minimap-preview-locked";function r7(e){return r3(r9,e)}var ie=n(88576),it=n.n(ie),ir=n(5284),ii=n.n(ir);function is(e){let{locked:t,iconSize:n=16,className:i,...s}=e;return(0,r.jsx)("button",{...s,type:"button","aria-pressed":t,className:i?`${ii().lock} ${i}`:ii().lock,children:(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"4",y:"11",width:"16",height:"10",rx:"2"}),t?(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"})]})})}function ia(e){let{level:t,children:n,headingIndex:i,onClick:s}=e;return(0,r.jsx)("button",{type:"button",className:it().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 il=[...r8.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]:[]}}],io=[[r4.A,{throwOnError:!1,strict:!1}]];function id(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 ic=(0,i.memo)(function(e){let{markdown:t,onHeadingClick:n,onAnswerClick:s}=e,a=(0,i.useMemo)(()=>(0,r8.Ep)(t),[t]);return t?(0,r.jsx)("div",{className:it().outline,children:(0,r.jsx)(r2.oz,{remarkPlugins:il,rehypePlugins:io,components:{h1:e=>{let{children:t,node:i}=e;return(0,r.jsx)(ia,{level:1,headingIndex:id(i),onClick:n,children:t})},h2:e=>{let{children:t,node:i}=e;return(0,r.jsx)(ia,{level:2,headingIndex:id(i),onClick:n,children:t})},h3:e=>{let{children:t,node:i}=e;return(0,r.jsx)(ia,{level:3,headingIndex:id(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:it().paragraph,onClick:s,children:t})},blockquote:()=>null,ul:()=>null,ol:()=>null,pre:()=>null,table:()=>null,hr:()=>null,a:e=>{let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})},code:e=>{let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})}},children:a})}):null}),iu=(0,i.memo)(function(e){let{messages:t,getStreamingMessage:n,scrollContainer:s,messageRefs:a,onRevealHistory:l,turnsBefore:o,turnAnchors:d}=e,{t:c}=(0,eX.s)(),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)([]),[g,f]=(0,i.useState)(null),[x,b]=(0,i.useState)(600),[v,y]=(0,i.useState)(!1),[k,j]=(0,i.useState)(r7),[w,S]=(0,i.useState)(null),C=(0,i.useRef)(!1),N=(0,i.useRef)(null),I=(0,i.useRef)([]),E=(0,i.useRef)({nodes:[],gap:50,fillsHeight:!1}),$=(0,i.useRef)(null),T=(0,i.useRef)(new Map),M=(0,i.useRef)(null),R=(0,i.useRef)(null),A=(0,i.useRef)(null),L=(0,i.useRef)(t);L.current=t;let P=(0,i.useRef)(d);P.current=d;let z=(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}})(h,x),[h,x]),{nodes:O,gap:W}=z;E.current=z;let F=(0,i.useCallback)(e=>{R.current={index:e,until:Date.now()+1600},f(e)},[]),D=(0,i.useCallback)((e,t)=>{let n=R.current;if(n&&Date.now()<n.until)return void f(n.index);R.current=null;let r=t.filter(e=>null!==e.targetTurn.scrollTop);if(0===r.length)return void f(null);let i=e.scrollTop+.3*e.clientHeight;f(r.reduce((e,t)=>Math.abs((t.targetTurn.scrollTop??0)-i)<Math.abs((e.targetTurn.scrollTop??0)-i)?t:e,r[0]).index)},[]),B=(0,i.useCallback)(()=>{let e=s.current;if(!e)return;let t=e.scrollHeight-e.clientHeight,n=I.current;p(t>20),D(e,n)},[s,D]),H=(0,i.useRef)(null),_=(0,i.useCallback)(()=>{H.current||(H.current=setTimeout(()=>{H.current=null;let e=s.current,t=N.current;if(!e||!t)return;let r=a.current,i=e.getBoundingClientRect(),l=[],o=0,d=null,c=n();for(let[t,n]of(c?[...L.current,c]:L.current).entries()){let s=!0===P.current[t];if(!s&&"assistant"!==n.role)continue;let a=null;if((0,nN.nR)(n,s)&&(a=r?.[o]??null,o++),s){d=null;let t=a?.getBoundingClientRect();d={userMessage:n,assistantPreviews:[],scrollTop:t?t.top-i.top+e.scrollTop:null,toolCount:0},l.push(d);continue}if(!d)continue;null===d.scrollTop&&a&&(0,nN.zZ)(d.userMessage)&&(d.scrollTop=a.getBoundingClientRect().top-i.top+e.scrollTop),d.toolCount+="assistant"===n.role&&Array.isArray(n.content)?n.content.reduce((e,t)=>e+ +("toolCall"===t.type),0):0;let c=function(e){if("assistant"!==e.role)return"";let{answerBlocks:t}=(0,nN.dQ)(e);return t.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n").trim()}(n);c&&d.assistantPreviews.push({markdown:c,element:a})}let u=l.map((e,t)=>({topRatio:0,targetTurn:e,index:t}));b(t.clientHeight),I.current=u,m(u),p(e.scrollHeight-e.clientHeight>20),D(e,u);let h=A.current,g=h?u[h.nodeIndex]:null;if(h&&g){let t=void 0===h.assistantIndex?null:g.targetTurn.assistantPreviews[h.assistantIndex],n=g.targetTurn.scrollTop;if("assistant"===h.target){let r=t?.element?.getBoundingClientRect();n=r?r.top-i.top+e.scrollTop:null}else if("heading"===h.target){let r=void 0===h.headingIndex?null:t?.element?.querySelectorAll("h1, h2, h3").item(h.headingIndex),s=r?.getBoundingClientRect();n=s?s.top-i.top+e.scrollTop:null}if(null===n)return;A.current=null,F(g.index);let r=.3*e.clientHeight;e.scrollTo({top:Math.max(0,n-r),behavior:"smooth"})}},150))},[n,F,a,s,D]);(0,i.useEffect)(()=>{let e=s.current;if(e)return e.addEventListener("scroll",B,{passive:!0}),()=>e.removeEventListener("scroll",B)},[s,B]),(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=()=>{_(),B()},n=new ResizeObserver(t);return n.observe(e),e.firstElementChild&&n.observe(e.firstElementChild),t(),()=>{n.disconnect(),H.current&&(clearTimeout(H.current),H.current=null)}},[_,s,B]),(0,i.useEffect)(()=>{let e=setTimeout(()=>{_(),B()},50);return()=>clearTimeout(e)},[t.length,d,_,B]);let U=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;if(F(e.index),null===e.targetTurn.scrollTop){A.current={nodeIndex:e.index,target:"user"},l();return}let r=Math.max(0,e.targetTurn.scrollTop-.3*n.clientHeight);n.scrollTo({top:r,behavior:t})},[F,l,s]),K=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;let r=e.targetTurn.assistantPreviews[t]?.element;if(!r){A.current={nodeIndex:e.index,target:"assistant",assistantIndex:t},l();return}let i=n.getBoundingClientRect(),a=r.getBoundingClientRect().top-i.top+n.scrollTop-.3*n.clientHeight;F(e.index),n.scrollTo({top:Math.max(0,a),behavior:"smooth"})},[F,l,s]),q=(0,i.useCallback)(e=>{let{nodes:t,gap:n,fillsHeight:r}=E.current,i=N.current?.clientHeight??0;if(0===t.length||i<=0)return null;let s=Math.max(0,Math.min(i,e*i)),a=t[0].topRatio*i,l=n>0?Math.round((s-a)/n):0,o=Math.max(0,Math.min(t.length-1,l)),d=t[o];if(!r&&Math.abs(s-d.topRatio*i)>Math.max(10,n/2))return null;return d},[]),Z=(0,i.useCallback)((e,t,n)=>{let r=s.current;if(!r)return;let i=e.targetTurn.assistantPreviews[t]?.element;if(!i){A.current={nodeIndex:e.index,target:"heading",assistantIndex:t,headingIndex:n},l();return}let a=i.querySelectorAll("h1, h2, h3").item(n);if(!a)return;let o=r.getBoundingClientRect(),d=a.getBoundingClientRect().top-o.top+r.scrollTop-.3*r.clientHeight;F(e.index),r.scrollTo({top:Math.max(0,d),behavior:"smooth"})},[F,l,s]),V=(0,i.useCallback)(()=>{M.current&&(clearTimeout(M.current),M.current=null)},[]),J=(0,i.useCallback)(()=>{k||(V(),y(!0))},[V,k]),G=(0,i.useCallback)(()=>{let e=!k;j(e),r5(r9,e,void 0),e&&(V(),y(!1),S(null))},[V,k]),Y=(0,i.useCallback)(()=>{V(),M.current=setTimeout(()=>{M.current=null,y(!1),S(null)},250)},[V]);(0,i.useEffect)(()=>()=>V(),[V]);let X=(0,i.useCallback)(e=>{if(!u)return;C.current=!0,J();let t=e.currentTarget.getBoundingClientRect();S(Math.max(0,Math.min(1,(e.clientY-t.top)/t.height)));let n=(e,n)=>{let r=q(Math.max(0,Math.min(1,(e-t.top)/t.height)));r&&U(r,n)};n(e.clientY,"smooth");let r=e=>{C.current&&n(e.clientY,"auto")},i=()=>{C.current=!1,window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",i)};window.addEventListener("mousemove",r),window.addEventListener("mouseup",i)},[q,U,J,u]),Q=null===w?null:q(w),ee=Q?.index??null;if((0,i.useEffect)(()=>{if(!v||null===ee)return;let e=$.current,t=T.current.get(ee);if(!e||!t)return;let n=t.offsetTop-(e.clientHeight-t.offsetHeight)/2;e.scrollTop=Math.max(0,n)},[h,v,ee]),!u)return null;let et=Math.max(1,(O.length>0?O[O.length-1].topRatio*x:12)-12);return(0,r.jsxs)("div",{ref:N,onMouseDown:X,onMouseEnter:J,onMouseLeave:Y,onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();S((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:[o>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:et,width:1,background:"var(--border)",transform:"translateX(-50%)",zIndex:0}}),O.map(e=>{let t=v&&Q?.index===e.index,n=g===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,W),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)(is,{locked:k,className:it().lock,"data-minimap-lock":k?"on":"off",title:c(k?"chatMinimap.unlockPreview":"chatMinimap.lockPreview"),"aria-label":c("chatMinimap.lockPreview"),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),G()}}),v&&h.length>0&&(0,r.jsxs)("div",{ref:$,className:it().preview,"data-minimap-preview-box":"",onMouseEnter:J,onMouseDown:e=>e.stopPropagation(),onMouseMove:e=>e.stopPropagation(),children:[o>0&&(0,r.jsx)("button",{type:"button",className:it().earlier,"data-minimap-preview-earlier":"",onClick:()=>s.current?.scrollTo({top:0,behavior:"smooth"}),children:c("chatMinimap.earlierTurns",{count:o})}),h.map(e=>{var t;let n=ee===e.index;return(0,r.jsxs)("div",{ref:t=>{t?T.current.set(e.index,t):T.current.delete(e.index)},className:it().turn,"data-minimap-preview-index":e.index,"data-located":n?"true":void 0,children:[(0,r.jsxs)("span",{className:it().number,children:[(0,r.jsx)("span",{"aria-hidden":"true",children:String(o+e.index+1).padStart(2,"0")}),e.targetTurn.toolCount>0&&(0,r.jsx)("span",{className:it().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:it().content,children:[(0,r.jsx)("button",{type:"button",className:it().user,"data-minimap-preview-user":e.index,onClick:()=>{U(e,"smooth")},children:(0,r.jsx)("span",{className:it().userText,children:(0,nN.zZ)(e.targetTurn.userMessage)?c("chatMinimap.extensionTurn",{type:e.targetTurn.userMessage.customType}):"string"==typeof(t=e.targetTurn.userMessage).content?t.content.trim():t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim()})}),e.targetTurn.assistantPreviews.map((t,n)=>(0,r.jsxs)("div",{className:it().assistant,children:[(0,r.jsx)("button",{type:"button",className:it().assistantJump,"data-minimap-preview-assistant":`${e.index}-${n}`,onClick:()=>K(e,n),"aria-label":c("chatMinimap.locateAssistant"),title:c("chatMinimap.locateAssistant"),children:"A"}),(0,r.jsx)(ic,{markdown:t.markdown,onAnswerClick:()=>K(e,n),onHeadingClick:t=>Z(e,n,t)})]},n))]})]},e.index)})]})]})});var ip=n(42790);function ih(e){let{text:t}=e,n=(0,i.useMemo)(()=>{let e=new ip.v;e.use_classes=!0;let n=t.replace(nf,"");return e.ansi_to_html(n).replaceAll('<a href="','<a target="_blank" rel="noopener noreferrer" href="')},[t]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:n}})}function im(e){let t,n,s,{widgets:a,children:l}=e,{t:o}=(0,eX.s)(),d=(0,i.useId)(),c=(0,i.useRef)(null),u=(0,i.useRef)(new Map),[p,h]=(0,i.useState)(()=>a.find(e=>{let t=e.lines.length;return t>1&&t<=3})?.key??null),[m,g]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{var e;let t=new Map(a.map(e=>[e.key,[...e.lines]])),n=(e=c.current,e?Array.from(t,t=>{let[n,r]=t,i=e.get(n);return i&&i.length===r.length?r.some((e,t)=>e!==i[t])?n:null:i?n:null}).filter(e=>null!==e):[]);for(let[e,n]of(c.current=t,u.current))t.has(e)||(clearTimeout(n),u.current.delete(e));for(let e of(g(e=>{let r=new Set(Array.from(e).filter(e=>t.has(e)));for(let e of n)r.add(e);return r.size===e.size&&Array.from(r).every(t=>e.has(t))?e:r}),n)){let t=u.current.get(e);t&&clearTimeout(t),u.current.set(e,setTimeout(()=>{u.current.delete(e),g(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},1100))}},[a]),(0,i.useEffect)(()=>()=>{for(let e of u.current.values())clearTimeout(e);u.current.clear()},[]),0===a.length)return null;let f=a.find(e=>e.key===p&&e.lines.length>0);return(0,r.jsxs)(r.Fragment,{children:[f&&(0,r.jsx)("div",{className:"extension-widget-panels",children:(t=a.indexOf(f),n=`${d}-trigger-${t}`,s=`${d}-panel-${t}`,(0,r.jsxs)("section",{id:s,className:"extension-widget-panel","aria-labelledby":n,children:[(0,r.jsx)("div",{className:"extension-widget-panel-heading",children:f.key}),(0,r.jsx)("pre",{className:"extension-widget-content",children:(0,r.jsx)(ih,{text:f.lines.join("\n")})})]},f.key))}),(0,r.jsxs)("div",{className:"extension-status-row",children:[(0,r.jsx)("div",{className:"extension-widget-triggers","aria-label":o("chat.extensionWidgets"),children:a.map((e,t)=>{let n=e.lines.length>0,i=n&&e.key===f?.key,s=m.has(e.key),a=o(1===e.lines.length?"chat.extensionWidgetLine":"chat.extensionWidgetLines",{count:e.lines.length}),l=o("belowEditor"===e.placement?"chat.extensionWidgetBelow":"chat.extensionWidgetAbove"),c=`${d}-trigger-${t}`,u=`${d}-panel-${t}`,p=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"extension-widget-update-pulse","aria-hidden":"true"}),(0,r.jsx)("span",{className:"extension-widget-placement","aria-hidden":"true",children:(0,r.jsx)("svg",{className:"extension-widget-placement-icon",viewBox:"0 0 8 6",width:"8",height:"6","data-direction":"belowEditor"===e.placement?"down":"up",focusable:"false",children:(0,r.jsx)("path",{d:"belowEditor"===e.placement?"M0 0h8L4 6z":"M4 0l4 6H0z"})})}),(0,r.jsx)("span",{className:"extension-widget-key",children:e.key})]});return n?(0,r.jsx)("button",{id:c,type:"button",className:`extension-widget-trigger${i?" is-expanded":""}${s?" is-updating":""}`,"aria-controls":u,"aria-expanded":i,"aria-label":`${l}: ${e.key}, ${a}`,title:`${e.key} - ${l} - ${i?o("i18n.collapse"):o("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":`${l}: ${e.key}, ${a}`,title:`${e.key} - ${l}`,children:p},e.key)})}),l]})]})}let ig="command:";function ix(e){let{statuses:t,widgets:n=[],onCommand:i,commandsDisabled:s=!1}=e,a=function(e){let t=[];for(let n of[...e].sort((e,t)=>e.key.localeCompare(t.key))){let e=n.text.replace(/\r\n?/g,"\n").split("\n").map(e=>e.replace(/\t/g," ").replace(/ +/g," ").trim()).join("\n").trim(),r=function(e){if(!e.startsWith(ig))return null;let t=e.slice(ig.length).trim();return t.length>1&&t.startsWith("/")?t:null}(n.key);if(r){let n=nx(e).replace(/\s+/g," ").trim();t.push({kind:"command",command:r,label:n||r})}else nx(e).trim()&&t.push({kind:"text",text:e})}return t}(t);if(0===a.length&&0===n.length)return null;let l=a.some(e=>"command"===e.kind),o=a.map(e=>"text"===e.kind?nx(e.text):e.label).join(" "),d=a.length>0?(0,r.jsx)("div",{role:"status",className:"extension-status-line","aria-label":o,title:o,children:(0,r.jsx)("span",{className:"extension-status-text",children:a.map((e,t)=>"text"===e.kind?(0,r.jsx)("span",{className:"extension-status-item",children:(0,r.jsx)(ih,{text:e.text})},t):(0,r.jsx)("button",{type:"button",className:"extension-status-item extension-status-command",disabled:!i||s,title:`${e.label} \xb7 ${e.command}`,"aria-label":`${e.label} (${e.command})`,onClick:()=>i?.(e.command),children:e.label},t))})}):null;return(0,r.jsx)("div",{className:`extension-status-shelf${n.length>0?" has-widgets":""}${a.length>0?" has-status":""}${l?" has-commands":""}`,children:n.length>0?(0,r.jsx)(im,{widgets:n,children:d}):d})}function ib(e,t){return e?.kind==="running_tools"&&e.tools.length>0?e:t?{kind:"waiting_model"}:{kind:"running_command"}}function iv(e){switch(e.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==e.closed;default:return!1}}function iy(e,t){return e.every(e=>t.has(e.id))?e:e.filter(e=>t.has(e.id))}function ik(e,t){return e.some(e=>e.id===t)?e.filter(e=>e.id!==t):e}function ij(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function iw(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(!ij(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=ij(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=ij(e.arguments)?e.arguments:null;return n&&r&&"string"==typeof r[n]?r[n]:void 0}(e):void 0;return void 0===r?n:{...n,rawInput:r}})(e,t)??e);return{...e,content:r}}function iS(e){if(!e||"object"!=typeof e)return null;let{reason:t,cwd:n}=e;return"cwd-missing"===t&&"string"==typeof n&&n?n:null}class iC extends Error{constructor(e,t,n,r,i){super(e),this.status=t,this.code=n,this.accepted=r,this.missingCwd=i,this.name="AgentCommandError"}}function iN(e){return e instanceof iC&&"prompt_rejected"===e.code&&!1===e.accepted}function iI(e){return`/api/agent/${encodeURIComponent(e)}?systemPrompt=0`}async function iE(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 iC(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted,iS(r)??void 0);return r.data}let i$={not_found:"sideChat.error.notFound",unsaved:"sideChat.error.unsaved",empty:"sideChat.error.empty",subagent:"sideChat.error.subagent",side:"sideChat.error.side"};async function iT(e,t,n){let r=await fetch(`/api/sessions/${encodeURIComponent(e)}/fork`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({side:!0,...n?{name:n}:{}}),cache:"no-store"}),i=await r.json().catch(()=>null);return r.ok&&i?.sessionId&&i.session?{session:i.session}:{error:i?.code&&i.code in i$?t(i$[i.code]):i?.error??`HTTP ${r.status}`}}async function iM(e){let t=await fetch(`/api/sessions/${encodeURIComponent(e)}`,{method:"DELETE",cache:"no-store"});if(t.ok)return null;let n=await t.json().catch(()=>null);return{error:n?.error??`HTTP ${t.status}`}}function iR(){return globalThis.__piSessionViewCache||(globalThis.__piSessionViewCache=new Map),globalThis.__piSessionViewCache}let iA=new WeakMap;function iL(e){let t,n=iA.get(e);if(void 0!==n)return n;try{t=JSON.stringify(e).length}catch{t=Number.MAX_SAFE_INTEGER}return iA.set(e,t),t}function iP(e){let t=iR().get(e);return t?Date.now()-t.savedAt>6e5?(iR().delete(e),null):(iR().delete(e),iR().set(e,t),t):null}function iz(e){if(!e.sessionId||!e.revision)return!1;let t=iR();t.delete(e.sessionId);let n={...e,savedAt:Date.now()};return!(iL(n)>0x2000000)&&(t.set(n.sessionId,n),!function(){let e=iR();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+=iL(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-=iL(r))}}(),iR().has(n.sessionId))}function iO(e){iR().delete(e)}var iW=n(14755);let iF="pi-tool-preset";function iD(){try{return window.localStorage}catch{return null}}function iB(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 iH(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,iB(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),iB(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}var i_=n(64738);function iU(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 iK(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(iU).filter(Boolean)}):JSON.stringify({text:"",images:[]})}let iq=(e,t)=>`live:${e??""}:${t}`;class iZ 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 iV{constructor(e){this.options=e,this.current=null,this.retry=null,this.retryGeneration=0,this.endedSessionId=null,this.opens=0,this.retries=0,this.lastError=null,this.lastClose=null}close(e){let t=null!==this.lastError&&!(this.lastClose&&this.lastClose.at>=this.lastError.at);(this.current||this.retry||t)&&(this.lastClose={reason:e??null,at:Date.now()}),this.stopRetrying(),this.current&&this.discard(this.current,new iZ("closed"))}snapshot(){let e=this.current,t=this.retry;return{sessionId:e?.sessionId??t?.sessionId??null,state:e?e.attempt.ready?"connected":"connecting":t?"retrying":"idle",readyState:e?e.source.readyState:null,openedAt:e?.openedAt??null,connectedAt:e?.connectedAt??null,lastSeenAt:e?.lastSeenAt??null,lastHeartbeatAt:e?.lastHeartbeatAt??null,events:e?.events??0,opens:this.opens,retries:this.retries,retryDueAt:t?.dueAt??null,watchdogArmed:!!(e&&null!==e.watchdog),staleAfterMs:this.options.staleAfterMs??null,lastError:this.lastError?{...this.lastError}:null,lastClose:this.lastClose?{...this.lastClose}:null}}maintain(e){if(this.endedSessionId===e||!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof iZ?"startup_error"===n.status?this.stopRetrying():this.scheduleRetry(e):this.options.onUnexpectedError?.(n))})}async ensureConnected(e){if(this.endedSessionId===e)throw new iZ("closed");for(;;){let t=this.current;if(t&&t.sessionId===e){if(t.attempt.ready&&1===t.source.readyState)return}else t=this.open(e);if(await t.attempt.promise,this.current!==t){if(this.current?.sessionId===e)continue;throw new iZ("closed")}if(1===t.source.readyState)return;this.lastClose={reason:"stuck",at:Date.now()},this.discard(t,new iZ("closed"))}}open(e){let t,n,r;this.current&&(this.lastClose={reason:"replaced",at:Date.now()},this.discard(this.current,new iZ("closed")));try{t=this.options.createSource(e)}catch(t){let e=t instanceof Error?t.message:String(t);throw this.lastError={reason:"error",message:e,at:Date.now()},new iZ("closed",e)}this.opens+=1;let i=!1,s=new Promise((e,t)=>{n=e,r=t}),a=setTimeout(()=>{this.fail(d,new iZ("ready_timeout"),"ready_timeout")},this.options.readinessTimeoutMs),l={promise:s,ready:!1,succeed(){i||(i=!0,clearTimeout(a),n())},fail(e){i||(i=!0,clearTimeout(a),r(e))}},o=Date.now(),d={sessionId:e,source:t,attempt:l,watchdog:null,openedAt:o,connectedAt:null,lastSeenAt:null,lastHeartbeatAt:null,events:0};return this.current=d,t.onmessage=t=>{let n;if(this.current===d){d.lastSeenAt=Date.now();try{n=JSON.parse(t.data)}catch{return}if("session_ended"===n.type&&n.sessionId===e){this.endedSessionId=e,this.close(),this.options.onEvent(n);return}if("heartbeat"===n.type){d.lastHeartbeatAt=d.lastSeenAt;return}if("connected"===n.type){d.connectedAt??=d.lastSeenAt,l.ready=!0,l.succeed(),this.stopRetrying();let e=this.options.staleAfterMs;e&&null===d.watchdog&&(d.watchdog=setInterval(()=>{Date.now()-(d.lastSeenAt??o)>e&&this.fail(d,new iZ("closed"),"stale")},Math.max(1e3,Math.floor(e/3))))}else if("startup_error"===n.type){let e="string"==typeof n.errorMessage?n.errorMessage:void 0;this.fail(d,new iZ("startup_error",e),"startup_error");return}d.events+=1,this.options.onEvent(n)}},t.onerror=()=>{this.fail(d,new iZ("closed"),"error")},d}fail(e,t,n){this.current===e&&(this.lastError={reason:n,message:"startup_error"===n?t.message:null,at:Date.now()},this.discard(e,t),"startup_error"===t.status?this.stopRetrying():this.scheduleRetry(e.sessionId))}discard(e,t){null!==e.watchdog&&clearInterval(e.watchdog),e.watchdog=null,e.attempt.fail(t),e.source.close(),this.current===e&&(this.current=null)}scheduleRetry(e){if(!this.options.shouldMaintain(e)||this.retry?.sessionId===e)return;this.clearRetry();let t=setTimeout(()=>{this.retry?.timer===t&&(this.retry=null,this.retries+=1,this.maintain(e))},this.options.reconnectDelayMs);this.retry={sessionId:e,timer:t,dueAt:Date.now()+this.options.reconnectDelayMs}}stopRetrying(){this.retryGeneration+=1,this.clearRetry()}clearRetry(){this.retry&&clearTimeout(this.retry.timer),this.retry=null}}function iJ(e){return!!e&&"unanswered"!==e&&!!(e.running||e.awaitingInput||e.subagentsActive)}var iG=n(48495);function iY(e){return("tool_execution_start"===e.type||"tool_execution_update"===e.type||"tool_execution_end"===e.type)&&"string"==typeof e.parentToolCallId&&""!==e.parentToolCallId}function iX(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 iQ(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let i0=/^(?:custom-ui|extension-widget):/;var i1=n(89594),i2=n(40505);function i4(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return e+t>=n-r}let i8={isStreaming:!1,streamingMessage:null};function i6(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 i3(){let e=i8,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=iw(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 i6(e,n.contentIndex,()=>({type:"text",text:""}));case"text_delta":return i6(e,n.contentIndex,e=>e?.type==="text"?{...e,text:e.text+n.delta}:null);case"text_end":return i6(e,n.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:n.content}));case"thinking_start":return i6(e,n.contentIndex,()=>({type:"thinking",thinking:""}));case"thinking_delta":return i6(e,n.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+n.delta}:null);case"thinking_end":return i6(e,n.contentIndex,e=>({...e?.type==="thinking"?e:{},type:"thinking",thinking:n.content}));case"toolcall_start":return i6(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 i6(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 i6(e,n.contentIndex,()=>({type:"toolCall",toolCallId:n.toolCall.id,toolName:n.toolCall.name,input:n.toolCall.arguments}));default:return e}case"end":return i8;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 i5(e,t){let n=e.lastIndexOf(t);return -1===n?e:[...e.slice(0,n),...e.slice(n+1)]}function i9(e,t){return e.reduce((e,n)=>"user"===n.role&&iK(n)===t?e+1:e,0)}function i7(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function se(e){return e&&"auto"!==e?e:null}let st=new Map,sn=[2e3,5e3,1e4],sr=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:200,t=new Set;return n=>!t.has(n)&&(t.add(n),t.size>e&&t.delete(t.values().next().value),!0)}();function si(e){return new Promise(t=>setTimeout(t,e))}function ss(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function sa(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:ss(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:ss(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=ss(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function sl(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 so(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 sd=e=>e.isStreaming,sc=e=>!!e.streamingMessage?.content.length,su=e=>e.streamingMessage;var sp=n(70843),sh=n(36690);let sm="pi-web:done-chimes";function sg(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Date.now(),r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:function(){try{return window.localStorage}catch{return null}}();if(0===e.length)return!1;if(!r)return!0;try{let i=function(e){let t=e.getItem(sm);if(!t)return{};try{let e=JSON.parse(t);if(!e||"object"!=typeof e||Array.isArray(e))return{};let n={};for(let[t,r]of Object.entries(e))"number"==typeof r&&Number.isFinite(r)&&(n[t]=r);return n}catch{return{}}}(r),s=e.filter(e=>!("number"==typeof i[e]&&i[e]>=t));if(0===s.length)return!1;for(let e of s)i[e]=n;let a=Object.entries(i).filter(e=>{let[,t]=e;return n-t<=864e5}).sort((e,t)=>t[1]-e[1]).slice(0,200);return r.setItem(sm,JSON.stringify(Object.fromEntries(a))),!0}catch{return!0}}let sf=null,sx=null;function sb(e){let{label:t}=e,[n,s]=(0,i.useState)(()=>sx);if((0,i.useEffect)(()=>{if(sx)return;let e=!1;return(sf??=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=>(sx=e,e)).catch(()=>(sf=null,null))).then(t=>{!e&&t&&s(t)}),()=>{e=!0}},[]),!n)return null;let a=t(n.latestVersion);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"new-session-meta-arrow","aria-hidden":"true",children:"→"}),(0,r.jsxs)("a",{className:"new-session-update",href:n.releaseUrl,target:"_blank",rel:"noopener noreferrer",title:a,"aria-label":a,children:["v",n.latestVersion,(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M7 17 17 7"}),(0,r.jsx)("path",{d:"M7 7h10v10"})]})]})]})}function sv(e){let{messageCount:t,toolCallCount:n,durationMs:s,cacheMisses:a,defaultExpanded:l=!1,reveal:o=!1,children:d,t:c}=e,[u,p]=(0,i.useState)(l);(0,i.useLayoutEffect)(()=>{o&&p(!0)},[o]);let h=[`${t} ${c(1===t?"chat.message":"chat.messages")}`];n>0&&h.push(`${n} ${c(1===n?"chat.toolCall":"chat.toolCalls")}`),void 0!==s&&h.push(c("chat.turnDuration",{time:(0,nH.J)(s)}));let m=a&&!(u||o)?(0,sh.YL)(c,a):void 0;return(0,r.jsxs)("div",{style:{marginBottom:14},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":u||o,"aria-label":[c("chat.processDetails"),...h,...m?[m]:[]].join(" \xb7 "),onClick:()=>p(e=>!e),style:{display:"flex",alignItems:"center",gap:8,width:"auto",maxWidth:"100%",minHeight:24,padding:"2px 0",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},title:c(u?"chat.collapseProcess":"chat.expandProcess"),children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:u?"rotate(90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"4 2.5 7.5 6 4 9.5"})}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[h.join(" \xb7 "),m&&(0,r.jsx)("span",{style:{color:sh.lV},children:` \xb7 ${m}`})]})]}),(u||o)&&(0,r.jsx)("div",{style:{marginTop:8},children:d})]})}function sy(e){let t,{session:s,searchTarget:l,onSearchTargetHandled:d,initialScrollPosition:c,onScrollPositionChange:u,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:m,newSessionContextBar:g,initialNewSessionChoices:f,onNewSessionChoicesChange:x,onAgentEnd:b,onSessionEnded:v,onToolEnd:y,onAttentionNeeded:k,onSessionCreated:j,onSessionForked:w,panel:S=!1,onSideSession:C,modelsRefreshKey:N,chatInputRef:I,onBranchDataChange:E,onSystemPromptChange:$,onSystemToolsChange:T,onSystemInfoLoaderChange:M,onDebugSnapshotReaderChange:R,onSessionStatsChange:A,onSessionStatsPanelOpen:L,onOpenSettings:P,onContextUsageChange:z,onOpenFile:O,onFilesUploaded:W,onOpenSubagent:F,onEnterSubagent:D,quoteSelectionEnabled:B=!1,initialPrompt:H,onInitialPromptConsumed:_,soundEnabled:U=!0,onSoundToggle:K,playDoneSound:q=()=>{},unlockAudio:Z,holdAudio:V}=e,{t:J}=(0,eX.s)(),G=(0,eQ.a)(),Y=!o(s?.relation),X=(0,i.useRef)(q);X.current=q;let Q=(0,i.useRef)(U);Q.current=U;let ee=(0,i.useRef)(!1),et=(0,i.useCallback)(e=>{if(Y&&Q.current&&!e.aborted&&!e.subagentsActive){let e=ti.current??s?.id;(!e||sg([e],Date.now()-3e3))&&X.current()}b?.(e)},[Y,b,s?.id]),en=(0,i.useRef)(l?null:c??null),[er,ei]=(0,i.useState)(()=>{let e=en.current;return e&&!e.atBottom?e:null}),[es,ea]=(0,i.useState)(!1),{loading:el,error:eo,messages:ed,activeToolResults:ec,toolClocks:eu,entryIds:ep,messageKeys:eh,historyCursor:em,hasEarlierMessages:eg,earlierTurnCount:ef,streamingStore:ex,agentRunning:eb,bashRunning:ev,pendingBash:ey,modelNames:ek,modelList:ej,modelError:ew,missingCwd:eS,modelScopeWarnings:eC,isModelScopeActive:eN,allModelList:eI,modelThinkingLevels:eE,modelThinkingLevelMaps:eT,toolPreset:eM,thinkingLevel:eR,retryInfo:eA,contextUsage:eL,forkingEntryId:eP,isCompacting:ez,compactError:eO,compactResult:eW,displayModel:eF,modelSwitching:eD,sessionStats:eB,slashCommands:eH,slashCommandsLoading:e_,queuedMessages:eU,notices:eK,extensionDialog:eq,waitingExtensionDialogCount:eZ,extensionCustomUi:eV,waitingExtensionCustomUiCount:eJ,extensionStatuses:eG,extensionWidgets:eY,respondToExtensionUi:e0,sendExtensionCustomInput:e2,setNoticePaused:e4,addNotice:e8,isAutoModelSelection:e6,isAutoThinkingSelection:e3,defaultModel:e9,savedDefaultThinkingLevel:e7,agentPhase:te,isNew:tt,editEntryId:tn,showScrollToBottom:tr,sessionIdRef:ti,scrollContainerRef:ts,lastUserMsgRef:ta,promptAnchorActive:tl,handleSend:to,handleAbort:td,startSideChat:tu,handleFork:tp,handleEditContent:th,cancelEdit:tm,handleModelChange:tg,handleCompact:tf,handleSteer:tx,handleFollowUp:tb,handlePromptWithStreamingBehavior:tv,handleAbortCompaction:ty,dismissCompactError:tk,handleRecallQueue:tj,handleBuiltinSlashCommand:tw,handleToolPresetChange:tS,handleThinkingLevelChange:tC,handleSetDefaultModel:tN,handleSetDefaultThinkingLevel:tI,loadSlashCommands:tE,loadAllModels:t$,scrollUserMsgToTop:tT,loadContext:tM,activeLeafId:tR,scrollToBottom:tA,scrollToMessage:tL,sessionEphemeral:tP,newSessionEphemeral:tz,handleNewSessionEphemeralChange:tO}=function(e){var t;let r,s,{session:a,newSessionCwd:l,newSessionDraftKey:o,onAgentEnd:d,onSessionEnded:c,onToolEnd:u,onAttentionNeeded:p,onSessionCreated:h,onSessionForked:m,onSideSession:g,modelsRefreshKey:f,onBranchDataChange:x,onSystemPromptChange:b,onSystemToolsChange:v,onSystemInfoLoaderChange:y,onSessionStatsPanelOpen:k,onOpenSettings:j,onDebugSnapshotReaderChange:w}=e,S=null===a&&null!==l,C=S?e.initialNewSessionChoices??null:null,[N,I]=(0,i.useState)(null),[E,$]=(0,i.useState)(!S),[T,M]=(0,i.useState)(null),[R,A]=(0,i.useState)(null),[L,P]=(0,i.useState)([]),[z,O]=(0,i.useState)(new Map),[W,F]=(0,i.useState)(i2.HP),[D,B]=(0,i.useState)([]),[H,_]=(0,i.useState)(()=>new Map),[U,K]=(0,i.useState)(null),[q,Z]=(0,i.useState)(!1),[V,J]=(0,i.useState)(0),[G]=(0,i.useState)(i3),Y=G.dispatch,[X,Q]=(0,i.useState)(!1),[ee,et]=(0,i.useState)(!1),[en,er]=(0,i.useState)(null),[ei,es]=(0,i.useState)({}),[ea,el]=(0,i.useState)([]),[eo,ed]=(0,i.useState)(null),[ec,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(null),[em,eg]=(0,i.useState)([]),[ef,ex]=(0,i.useState)(!1),[eb,ev]=(0,i.useState)(null),ey=(0,i.useRef)(null),[ek,ej]=(0,i.useState)({}),[ew,eS]=(0,i.useState)({}),[eC,eN]=(0,i.useState)(()=>C?.model??null),[eI,eE]=(0,i.useState)(null),[eT,eM]=(0,i.useState)(iW.Q8),[eR,eA]=(0,i.useState)(()=>C?.thinkingLevel??null),[eL,eP]=(0,i.useState)(null),[ez,eO]=(0,i.useState)(null),[eW,eF]=(0,i.useState)(null),[eD,eB]=(0,i.useState)(null),[eH,e_]=(0,i.useState)(null),[eU,eK]=(0,i.useState)(null),[eq,eZ]=(0,i.useState)(null),eV=(0,i.useRef)(0),eJ=(0,i.useRef)(0),[eG,eY]=(0,i.useState)(null),[eX,eQ]=(0,i.useState)(null),[e0,e1]=(0,i.useState)(null),[e2,e4]=(0,i.useState)(null),[e8,e6]=(0,i.useState)(null),[e3,e5]=(0,i.useState)(!1),e9=(0,i.useRef)(!1),e7=(0,i.useRef)(!1),[te,tt]=(0,i.useState)(!1),[tn,tr]=(0,i.useState)(!1),[ti,ts]=(0,i.useState)(!1),[ta,tl]=(0,i.useState)(!0),[to,td]=(0,i.useState)(null),[tu,tp]=(0,i.useState)(null),[th,tm]=(0,i.useState)(null),[tg,tf]=(0,i.useState)(!1),[tx,tb]=(0,i.useState)(!1),[tv,ty]=(0,i.useState)([]),[tk,tj]=(0,i.useState)(!1),[tw,tS]=(0,i.useReducer)(sa,{visible:[],pending:[]}),[tC,tN]=(0,i.useState)(null),[tI,tE]=(0,i.useState)([]),[t$,tT]=(0,i.useState)([]),[tM,tR]=(0,i.useState)([]),[tA,tL]=(0,i.useState)([]),[tP,tz]=(0,i.useState)({steering:[],followUp:[]}),tO=(0,i.useRef)(null),tW=(0,i.useRef)(null),tF=(0,i.useRef)(0),tD=(0,i.useRef)(!1),tB=(0,i.useRef)(!1),[tH,t_]=(0,i.useState)(0),tU=(0,i.useRef)(null),tK=(0,i.useRef)(()=>{}),tq=(0,i.useRef)({renewStartedAt:null,inFlightSince:null,requests:0,unanswered:0,errors:0,last:null}),tZ=(0,i.useRef)({count:0,lastAt:null}),tV=(0,i.useRef)({count:0,lastAt:null,lastReason:null}),tJ=(0,i.useRef)(null),tG=(0,i.useRef)(null),tY=(0,i.useRef)(!1),tX=(0,i.useRef)(0),tQ=(0,i.useRef)(a?.id??null),t0=(0,i.useRef)(null),t1=(0,i.useRef)(a?.id??null),t2=(0,i.useRef)(!1),t4=(0,i.useRef)(!1),t8=(0,i.useRef)(!1),t6=(0,i.useRef)(!1),t3=(0,i.useRef)(-1),t5=(0,i.useRef)(!1),t9=(0,i.useRef)(0),t7=(0,i.useRef)(0),ne=(0,i.useRef)(null),nt=(0,i.useRef)(!!e.deferInitialScroll),nn=(0,i.useRef)(null),nr=(0,i.useRef)(!1),ni=(0,i.useRef)(!0),ns=(0,i.useRef)(0),na=(0,i.useRef)(null),nl=(0,i.useRef)(void 0),no=(0,i.useRef)(void 0),nd=(0,i.useRef)(null),nc=(0,i.useRef)(null),nu=(0,i.useRef)([]),np=(0,i.useRef)(null),nh=(0,i.useRef)(0),nm=(0,i.useRef)(!1),ng=(0,i.useRef)(C?.model??null),nf=(0,i.useRef)(C?.thinkingLevel??null),nb=(0,i.useRef)({}),nv=(0,i.useRef)(null),ny=(0,i.useRef)(0),nk=(0,i.useRef)(null),nj=(0,i.useRef)(null),nw=(0,i.useRef)(null),nS=(0,i.useRef)(0),nC=(0,i.useRef)(null),nI=(0,i.useCallback)(()=>{nj.current=ny.current,nw.current?.runId===ny.current&&(nw.current=null)},[]),nE=(0,i.useRef)(!1),n$=(0,i.useRef)(new Map),nM=(0,i.useRef)(!0),nR=(0,i.useRef)(new Map),nA=(0,i.useRef)(null),nL=(0,i.useRef)([]),nP=(0,i.useRef)([]),nO=(0,i.useRef)(null),nW=(0,i.useRef)(null),nF=(0,i.useRef)(!1),nD=(0,i.useRef)(0);t1.current=a?.id??null,nA.current=N,nL.current=L,nP.current=D,nO.current=R,nW.current=U,nF.current=q,nD.current=V,tY.current=ti,tX.current=tI.length+t$.length;let nB=(0,i.useCallback)(e=>nM.current&&t0.current!==e&&tQ.current===e&&(t4.current||tD.current||t1.current===e&&!tB.current),[]);tO.current||(tO.current=new iV({createSource:e=>(0,e$.Lf)("agent",new EventSource(`/api/agent/${encodeURIComponent(e)}/events?holder=${encodeURIComponent((0,e$.nU)())}`),e),onEvent:e=>ne.current?.(e),shouldMaintain:nB,readinessTimeoutMs:6e4,reconnectDelayMs:1e3,staleAfterMs:75e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let nH=e.setToolPreset??eM,n_=a?.id;(0,i.useLayoutEffect)(()=>{(n_||S&&!tQ.current)&&nH(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:iD();if(!e)return iW.Q8;try{let t=e.getItem(iF);return(0,iW.sn)(t)?t:iW.Q8}catch{return iW.Q8}}())},[n_,S,nH]);let nU=e.onNewSessionChoicesChange;(0,i.useEffect)(()=>{S&&nU?.({model:eC,thinkingLevel:eR})},[S,eC,eR,nU]);let nK=(0,i.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"smooth",t=nd.current;t&&(t.scrollTo({top:t.scrollHeight,behavior:e}),ns.current=t.scrollTop)},[]),nq=e0??e2??N?.context.model??e8??null,nZ=S?eC??eI:nq??(N?.context.messages.length===0?eI:null),nV=se(N?.context.thinkingLevel&&"off"!==N.context.thinkingLevel?N.context.thinkingLevel:null),nJ=S?eR??eL:eW??eD??nV??(N?.context.messages.length===0?eL:null),nY=a?.id??o??void 0,nX=(0,i.useCallback)(e=>{e4(e?.model?{provider:e.model.provider,modelId:e.model.id}:null),e?.thinkingLevel!==void 0&&eB(se(e.thinkingLevel))},[]),n2=(0,i.useCallback)(e=>{tQ.current||(e9.current=e,e5(e))},[]),n4=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=n$.current.get(t);if(!e)break;t=e}return t},[]),n3=(0,i.useCallback)((t,n,r)=>{let i=n?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}}),s=n4(r);if(!nM.current&&!nm.current&&r===o)return;let a=e.chatInputRef?.current;a?a.restoreSubmission(t,i,s):s&&n8(s,t,i)},[o,e.chatInputRef,n4]),[n5,n9]=(0,i.useState)(()=>{let e=a?.id;return e&&!nQ(e)&&st.delete(e),e&&st.get(e)||null}),n7=(0,i.useCallback)(e=>{a?.id&&(e?st.set(a.id,e):st.delete(a.id),n9(e))},[a?.id]),re=(0,i.useCallback)((t,n)=>{a?.id&&(e.chatInputRef?.current?.replaceMessage(t),n7(n))},[e.chatInputRef,a?.id,n7]),rt=(0,i.useCallback)(()=>n7(null),[n7]),rr=(0,i.useMemo)(()=>{let e=N?.totalActiveMs,t=eq&&eq.sessionId===N?.sessionId?eq.value:void 0,n=void 0===e&&void 0===t?void 0:Math.max(e??0,t??0);if(tC)return{...tC,totalActiveMs:n,...eU?{contextUsage:eU}:{}};let r=N?.stats,i=function(e,t,n){let r=iH(n);if(!e)return r;let i=iH(t),s=(e,t)=>Math.max(0,e-t),a={input:e.tokens.input+s(r.tokens.input,i.tokens.input),output:e.tokens.output+s(r.tokens.output,i.tokens.output),cacheRead:e.tokens.cacheRead+s(r.tokens.cacheRead,i.tokens.cacheRead),cacheWrite:e.tokens.cacheWrite+s(r.tokens.cacheWrite,i.tokens.cacheWrite),total:0};return a.total=a.input+a.output+a.cacheRead+a.cacheWrite,{userMessages:e.userMessages+s(r.userMessages,i.userMessages),assistantMessages:e.assistantMessages+s(r.assistantMessages,i.assistantMessages),toolCalls:e.toolCalls+s(r.toolCalls,i.toolCalls),toolResults:e.toolResults+s(r.toolResults,i.toolResults),totalMessages:e.totalMessages+s(r.totalMessages,i.totalMessages),tokens:a,cost:e.cost+s(r.cost,i.cost)}}(r,N?.context.messages??[],L);return 0!==i.tokens.total||0!==L.length||r?{sessionFile:N?.filePath||void 0,sessionId:tQ.current??a?.id??"",sessionName:a?.name,...i,totalActiveMs:n,...eU?{contextUsage:eU}:{}}:null},[L,tC,eU,eq,N?.sessionId,N?.context.messages,N?.filePath,N?.totalActiveMs,N?.stats,a?.id,a?.name]),ri=(0,i.useCallback)((e,t,n,r)=>{nM.current&&tQ.current===t&&ny.current===n&&!(r<=eJ.current)&&(eJ.current=r,e?.contextUsage!==void 0&&eK(e.contextUsage??null),"number"==typeof e?.totalActiveMs&&eZ({sessionId:t,value:e.totalActiveMs}))},[]),rs=(0,i.useCallback)(async e=>{let t=ny.current,n=++eV.current;try{let r=await fetch(iI(e));if(!r.ok)return;let i=await r.json();ri(i.state,e,t,n)}catch{}},[ri]),ra=(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:nR.current.get(i);if(s)return await s;let a=(async()=>{let i=!1,s=++nS.current,a=!t4.current;try{t&&$(!0);let l=new URLSearchParams({deferThinking:"1",deferMedia:"1",tree:"summary"});r?.force&&l.set("force","1");let o=await fetch(`/api/sessions/${encodeURIComponent(e)}?${l}`);if(404===o.status)return t&&(I(null),A(null),P([]),B([]),K(null),Z(!1),J(0),M(null)),iO(e),null;if(!o.ok)throw Error(`HTTP ${o.status}`);let d=await o.json();if(tQ.current!==e)return null;(nC.current?.seq??0)<s&&(nC.current={sid:e,seq:s,messages:d.context.messages,entryIds:d.context.entryIds??[]});let c=iP(e),u=!!(d.snapshotRevision&&c?.revision===d.snapshotRevision&&c.entryIds.length>=(d.context.entryIds??[]).length),p=u?nL.current:d.context.messages;if(I(u?{...d,context:{...d.context,messages:nL.current,entryIds:nP.current,oldestEntryId:nW.current,hasMore:nF.current,turnsBefore:nD.current}}:d),A(d.leafId),u)iz({sessionId:e,revision:d.snapshotRevision,messages:nL.current,entryIds:nP.current,leafId:d.leafId,oldestEntryId:nW.current,hasMore:nF.current,turnsBefore:nD.current,summaryTree:d.tree,thinkingLevel:d.context.thinkingLevel,model:d.context.model,stats:d.stats,totalActiveMs:d.totalActiveMs,loadedEntryIds:nP.current});else{let e={messages:nL.current,entryIds:nP.current},t={messages:p,entryIds:d.context.entryIds??[]};_(n=>(function(e,t){let n=new Set(t.entryIds),r=new Map([...e.aliases].filter(e=>{let[t]=e;return n.has(t)})),i=e.entryIds.length,s=e.entryIds[i-1],a=void 0===s?0:t.entryIds.indexOf(s)+1;if(0===a&&void 0!==s)return r;for(let n=0;i+n<e.messages.length;n++){var l,o;let d=t.entryIds[a+n];if(void 0===d||(l=e.messages[i+n],o=t.messages[a+n],l.role!==o.role||("user"===l.role?iK(l)!==iK(o):"custom"===l.role?l.customType!==o.customType:l.timestamp!==o.timestamp)))break;r.set(d,iq(s,n))}return r})({...e,aliases:n},t)),P(t.messages),B(t.entryIds),K(d.context.oldestEntryId),Z(d.context.hasMore),J(d.context.turnsBefore??0)}if(t2.current=void 0!==d.toolNames,nH(void 0!==d.toolNames?(0,iW.YO)(d.toolNames):iW.Q8),e1(e=>nE.current?e:null),eF(null),M(null),"summary"===d.treeFormat&&d.snapshotRevision&&iz({sessionId:e,revision:d.snapshotRevision,messages:p,entryIds:d.context.entryIds??[],leafId:d.leafId,oldestEntryId:d.context.oldestEntryId,hasMore:d.context.hasMore,turnsBefore:d.context.turnsBefore??0,summaryTree:d.tree,thinkingLevel:d.context.thinkingLevel,model:d.context.model,stats:d.stats,totalActiveMs:d.totalActiveMs,loadedEntryIds:d.context.entryIds??[]}),d.wrapperRebuilt&&(tO.current?.close("rebuilt"),tO.current?.maintain(e)),!n&&d.context.thinkingLevel&&"off"!==d.context.thinkingLevel&&eB(se(d.context.thinkingLevel)),i=!0,a&&s>t9.current&&er(e=>e?.result?null:e),t&&$(!1),!n)return null;try{let t=ny.current,n=++eV.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(tQ.current!==e)return null;let s=i.state;return nX(s),s?(ri(s,e,t,n),tt(!0===s.ephemeral),void 0!==s.systemPrompt&&eY(s.systemPrompt??null),void 0!==s.extensionStatuses&&tR(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tL(s.extensionWidgets??[]),void 0!==s.queuedMessages&&tz(i7(s.queuedMessages)),void 0!==s.autoCompactionEnabled&&tl(s.autoCompactionEnabled??!0)):i.running||tz({steering:[],followUp:[]}),i}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return M(String(e)),"error"}finally{t&&!i&&$(!1)}})();return nR.current.set(i,a),a.finally(()=>{nR.current.get(i)===a&&nR.current.delete(i)}),await a},[ri,nH,nX]),rl=(0,i.useCallback)(async(e,t,n,r)=>{try{let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&i.set("leafId",t),n&&i.set("before",n),r?.tail&&i.set("tail",String(r.tail));let s=`/api/sessions/${encodeURIComponent(e)}/context?${i}`,a=await fetch(s,{signal:r?.signal});if(!a.ok)throw Error(`HTTP ${a.status}`);let l=await a.json();if(tQ.current!==e||r?.signal?.aborted||!nM.current)return;return K(l.context.oldestEntryId),Z(l.context.hasMore),J(l.context.turnsBefore??0),I(t=>{if(!t||t.sessionId!==e)return t;let r=n?{...t.context,messages:[...l.context.messages,...t.context.messages],entryIds:[...l.context.entryIds,...t.context.entryIds],oldestEntryId:l.context.oldestEntryId,hasMore:l.context.hasMore,turnsBefore:l.context.turnsBefore}:l.context;return{...t,context:r}}),n?(P(e=>[...l.context.messages,...e]),B(e=>[...l.context.entryIds,...e])):(P(l.context.messages),B(l.context.entryIds??[])),l.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),ro=(0,i.useCallback)(async e=>{try{let t=await iE(e,{type:"get_tools"});if(!t||!nM.current||tQ.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return nH(t2.current?r(t):iW.Q8),v?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[v,nH]),rd=(0,i.useCallback)(function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"(no messages)",r=tQ.current;if(S&&l&&r&&!nm.current&&(nm.current=!0,o)){if(o!==r){n$.current.set(o,r);let t=e.chatInputRef?.current;t?t.rekeyDraft(o,r):n6(o,r)}h?.({id:r,path:"",cwd:l,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0,...e7.current?{ephemeral:!0}:{}},o)}},[S,l,o,h,e.chatInputRef]),rc=(0,i.useCallback)((e,t,n)=>{e.model&&ng.current===t&&(e6(e.model),t||eE(e.model)),e.thinkingLevel&&nf.current===n&&(eB(se(e.thinkingLevel)),n||eP(se(e.thinkingLevel)))},[]),ru=(0,i.useCallback)(async()=>{if(tQ.current||!S||!l)return tQ.current;if(nc.current)return nc.current;let e=(async()=>{let e=ng.current,t=nf.current;e&&e6(e);let n=(0,iW.xG)(eT);t2.current=void 0!==n;let r=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:l,type:"ensure_session",...void 0!==n?{toolNames:n}:{},...e?{provider:e.provider,modelId:e.modelId}:{},...t?{thinkingLevel:t}:{},...e9.current?{ephemeral:!0}:{}})});if(!r.ok){let e=await r.json().catch(()=>null),t="string"==typeof e?.error?e.error:`HTTP ${r.status}`,n=iS(e);throw n?new iC(t,r.status,void 0,void 0,n):Error(t)}let i=await r.json(),s=i.sessionId;return tQ.current=s,e7.current=e9.current,e7.current&&tt(!0),rc(i,e,t),s})();nc.current=e;try{return await e}finally{nc.current=null}},[rc,S,l,eT]),rp=(0,i.useCallback)(async()=>{let e=tQ.current??await ru();if(!e)return;let[t]=await Promise.all([iE(e,{type:"get_state"}),ro(e)]);nM.current&&tQ.current===e&&(nX(t),eY(t.systemPrompt??""))},[ru,ro,nX]),rh=(0,i.useCallback)(e=>{nu.current=e,ty(e)},[]),rm=(0,i.useCallback)(()=>{nh.current+=1,np.current=null,rh([])},[rh]),rg=(0,i.useCallback)(async(e,t)=>{let n=null===t1.current&&nM.current;n&&tO.current?.ensureConnected(e).catch(()=>{});try{return await t()}finally{!n||null!==t1.current||tQ.current!==e||0!==tX.current||t4.current||t5.current||tO.current?.close("grace_end")}},[]),rf=(0,i.useCallback)(()=>{let e=++nh.current,t=(async()=>{let t=tQ.current??await ru();if(!t)return nh.current===e&&rh([]),[];tj(!0);try{let n=await rg(t,()=>iE(t,{type:"get_commands"})),r=n?.commands??[];return nh.current===e&&rh(r),r}catch(t){return console.error("Failed to load slash commands:",t),nh.current===e&&rh([]),null}finally{nh.current!==e&&np.current||tj(!1)}})();np.current=t;let n=()=>{np.current===t&&(np.current=null)};return t.then(n,n),t},[ru,rh,rg]),rx=(0,i.useCallback)(async()=>await rf()??[],[rf]),rb=(0,i.useCallback)(async()=>{let e=np.current,t=nu.current;return!e&&t.length>0?t:await (e??rf()).catch(()=>null)??(t.length>0?t:null)},[rf]),rv=(0,i.useCallback)(()=>{tF.current+=1,tD.current=!1,tG.current=null,tW.current&&(clearTimeout(tW.current),tW.current=null)},[]),ry=(0,i.useCallback)(e=>{tO.current?.close(e)},[]),rk=(0,i.useCallback)(e=>tO.current.ensureConnected(e),[]),rj=(0,i.useCallback)(e=>{tO.current.maintain(e)},[]);(0,i.useEffect)(()=>{let e=a?.id;if(e)return nM.current=!0,tB.current=!1,rj(e),()=>{tQ.current===e&&tO.current?.close("deselected")}},[rj,a?.id]);let rw=(0,i.useCallback)(e=>{let t=tU.current;if(t?.sid===e)return t.promise;let n=new AbortController,r=setTimeout(()=>n.abort(),5e3),i={sid:e,promise:Promise.resolve(null)};return i.promise=(async()=>{let t=null,s=null,a=Date.now();tq.current.inFlightSince=a,tq.current.requests+=1;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}/lease`,{method:"POST",cache:"no-store",signal:n.signal});return t=r.status,s=r.ok?await r.json():null}catch(e){return s=n.signal.aborted||e instanceof TypeError?"unanswered":null}finally{clearTimeout(r),tU.current===i&&(tU.current=null);try{let e=tq.current,n=Date.now(),r="unanswered"===s?"unanswered":null===s?"error":"reply";"unanswered"===r&&(e.unanswered+=1),"error"===r&&(e.errors+=1);let i="object"==typeof s&&null!==s?s:null;e.inFlightSince=null,e.last={at:n,durationMs:Math.max(0,n-a),outcome:r,httpStatus:t,reply:i&&{running:!0===i.running,awaitingInput:!0===i.awaitingInput,subagentsActive:!0===i.subagentsActive}}}catch{}}})(),tU.current=i,i.promise},[]),rS=!X&&!ee&&!ti&&0===tI.length&&0===t$.length;(0,i.useEffect)(()=>{let e=a?.id;if(!e||!rS)return;let t=!1,n=null,r=()=>!t&&"hidden"===document.visibilityState&&!tB.current&&tQ.current===e&&t1.current===e&&!t4.current&&!t5.current,i=async()=>{if(n=null,tJ.current=null,!r())return;let t=await rw(e);if(r()){if(!("unanswered"===t||t&&!iJ(t)))return void s();tB.current=!0,tZ.current={count:tZ.current.count+1,lastAt:Date.now()},ry("released")}},s=()=>{null===n&&(n=setTimeout(()=>void i(),iG.P),tJ.current=Date.now()+iG.P)},l=()=>{"hidden"===document.visibilityState?s():n&&(clearTimeout(n),n=null,tJ.current=null)};return"hidden"===document.visibilityState&&s(),document.addEventListener("visibilitychange",l),()=>{t=!0,n&&clearTimeout(n),tJ.current=null,document.removeEventListener("visibilitychange",l)}},[ry,rS,tH,rw,a?.id]);let rC=(0,i.useCallback)(async(e,t)=>{let n=tQ.current;if(tE(t=>ik(t,e.id)),!n)return;try{await iE(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e);return}if(null!==t1.current)return;let r=ng.current,i=nf.current;try{let e=await iE(n,{type:"get_state"});if(!nM.current||tQ.current!==n||null!==t1.current)return;rc({model:e.model?{provider:e.model.provider,modelId:e.model.id}:null,thinkingLevel:e.thinkingLevel},r,i),void 0!==e.systemPrompt&&eY(e.systemPrompt)}catch{}},[rc]),rN=(0,i.useCallback)(async(e,t)=>{let n=tQ.current;if(n)try{await iE(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),rI=(0,i.useCallback)(e=>{let t=e.message.trim();t&&tS({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"}})},[]),rE=(0,i.useRef)(e.t);rE.current=e.t;let r$=(0,i.useCallback)((e,t)=>rE.current(e,t),[]),rT=(0,i.useCallback)(()=>{rI({type:"warning",message:r$("chat.sendUnconfirmed")})},[rI,r$]),rM=(0,i.useCallback)(e=>{nM.current&&P(t=>i5(t,e.bubble));let t=iP(e.sid);t?.messages.includes(e.bubble)&&iz({...t,messages:i5(t.messages,e.bubble)})},[]),rR=(0,i.useCallback)((e,t,n)=>{let r=nw.current;if(!r||r.runId!==t||r.sid!==e)return;nw.current=null;let i=nC.current,s=i?.sid===e&&i.seq>n?i:null,a=s?null===r.lastEntryIdAtSend?0:s.entryIds.indexOf(r.lastEntryIdAtSend)+1||-1:-1;s&&a>=0&&i9(s.messages.slice(a),r.key)>r.sameTextAfterSend||(n3(r.message,r.images,r.draftKey),s&&rM(r),rI(s&&!r.command&&a===s.entryIds.length?{type:"error",message:r$("chat.sendNotReceived")}:{type:"warning",message:r$("chat.sendUnconfirmed")}))},[rI,rM,n3,r$]),rA=(0,i.useCallback)(()=>{let e=nw.current;if(nw.current=null,e){if(e.parkedDraftKey){let t=e.images?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});n8(e.parkedDraftKey,e.message,t)}else n3(e.message,e.images,e.draftKey);rM(e)}},[rM,n3]),rL=(0,i.useRef)(rA);rL.current=rA;let rP=(0,i.useCallback)(t=>{switch(iv(t)&&p?.(t),t.method){case"select":case"confirm":case"input":case"editor":tE(e=>e.some(e=>e.id===t.id)?e:[...e,t]);break;case"notify":if(t.id&&!sr(t.id))break;rI({id:t.id,message:nx(t.message),type:t.notifyType??"info"});break;case"setStatus":tR(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":tL(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=nx(t.title));break;case"set_editor_text":e.chatInputRef?.current?.setText(nx(t.text));break;case"custom":tT(e=>{let n;return t.closed?ik(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)})}},[rI,p,e.chatInputRef]),rz=(0,i.useCallback)(()=>{let e=t4.current;return t4.current=!1,Q(!1),tm(null),e_(null),O(new Map),F(i2.HP),Y({type:"end"}),e},[Y]),rO=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t3.current!==e&&(t3.current=e,d?.({aborted:t,...n?{subagentsActive:n}:{}}),!0)},[d]),rW=(0,i.useCallback)(e=>{if(t1.current===e)return void rv();rv(),tD.current=!0;let t=tF.current,n=async()=>{if(t===tF.current&&tQ.current===e&&tD.current)try{let r=await fetch(iI(e));if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(t!==tF.current||tQ.current!==e||!tD.current)return;let s=i.state;if(nX(s),i.running&&s&&(s.isStreaming||s.isPromptRunning)){tD.current=!1,tW.current=null,tG.current=null,t8.current=!!s?.isStreaming,t6.current=!!s?.isPromptRunning,t4.current=!0,Q(!0),tm(e=>ib(e,!!s?.isStreaming));return}if(i.running&&s?.isCompacting){ts(!0),tW.current=setTimeout(()=>void n(),600),tG.current=Date.now()+600;return}tD.current=!1,tW.current=null,tG.current=null,ry("grace_end")}catch{if(t!==tF.current||tQ.current!==e||!tD.current)return;tW.current=setTimeout(()=>void n(),600),tG.current=Date.now()+600}};tW.current=setTimeout(()=>void n(),3e4),tG.current=Date.now()+3e4},[rv,ry,nX]),rF=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tQ.current,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ny.current;if(ny.current!==t)return;let n=nS.current;try{e&&await ra(e)}finally{if(ny.current!==t)return;e&&rR(e,t,n);let r=t6.current,i=t8.current;t6.current=!1,t8.current=!1,nk.current=null;let s=rz();r?rO(t):i&&s&&d?.({aborted:!1}),e&&rW(e)}},[ra,rO,d,rW,rz,rR]),rD=(0,i.useCallback)(async(e,t)=>{await si(800);let n=Date.now();for(;t4.current&&Date.now()-n<2e4;){if(void 0!==t&&ny.current!==t)return;try{let n=await fetch(iI(e));if(n.ok){let r=await n.json(),i=r.state;if(nX(i),!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await rF(e,t)}}catch{}await si(600)}},[rF,nX]),rB=(0,i.useCallback)(async e=>{let t=t7.current+1;for(t7.current=t;t5.current&&t7.current===t&&tQ.current===e;){await si(1e3);try{let n=await fetch(iI(e));if(!n.ok)continue;let r=await n.json();if(nX(r.state),r.state?.isBashRunning)continue;if(await ra(e),t7.current!==t||tQ.current!==e)return;t5.current=!1,et(!1),er(null);return}catch{}}},[ra,nX]),rH=(0,i.useCallback)(async e=>{if(!t4.current||tQ.current!==e)return;let t=ny.current,n=++eV.current;try{let r=await fetch(iI(e));if(!r.ok)return;let i=await r.json();if(tQ.current!==e||ny.current!==t)return;let s=i.state;if(ri(s,e,t,n),nX(s),ts(s?.isCompacting??!1),tl(s?.autoCompactionEnabled??!0),tz(i7(s?.queuedMessages)),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isCompacting)){t8.current=!!s.isStreaming,t6.current=!!s.isPromptRunning;return}if(!t4.current)return;s&&(void 0!==s.extensionStatuses&&tR(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tL(s.extensionWidgets??[]),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(t=>{t&&nM.current&&tQ.current===e&&t.state?.systemPrompt!==void 0&&eY(t.state.systemPrompt??null)}).catch(()=>{})),await rF(e,t)}catch{}},[ri,rF,nX]);(0,i.useEffect)(()=>{if(!X)return;let e=()=>{let e=tQ.current;e&&rH(e)},t=()=>{"visible"===document.visibilityState&&e()},n=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[X,rH]),(0,i.useEffect)(()=>{t4.current=X},[X]);let r_=(0,i.useCallback)(e=>nM.current&&tQ.current===e&&!t4.current,[]),rU=(0,i.useRef)(null),rK=(0,i.useRef)(null),rq=(0,i.useCallback)(async e=>{var t;let n,r=new URLSearchParams({deferThinking:"1",deferMedia:"1",tail:"1"}),i=await fetch(`/api/sessions/${encodeURIComponent(e)}/context?${r}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let{context:s,leafId:a}=await i.json();if(!r_(e))return;let l=nP.current.at(-1),o=nL.current.at(-1),d=void 0!==l&&nL.current.length===nP.current.length?(n=(t={messages:s.messages,entryIds:s.entryIds??[]}).entryIds.lastIndexOf(l))<0?null:{messages:t.messages.slice(n+1),entryIds:t.entryIds.slice(n+1)}:null;if(!d)return void await ra(e);if(0===d.entryIds.length)return;if(t5.current&&d.messages.some(e=>"bashExecution"===e.role)){rK.current=e;return}nP.current=[...nP.current,...d.entryIds],nL.current=[...nL.current,...d.messages],B(e=>e.at(-1)===l?[...e,...d.entryIds]:e),P(e=>e.at(-1)===o?[...e,...d.messages]:e),a&&(rU.current={base:nO.current,lastEntryId:d.entryIds.at(-1),leafId:a});let c=iP(e);c&&iz({...c,loadedEntryIds:[...c.loadedEntryIds,...d.entryIds]})},[r_,ra]),rZ=(0,i.useRef)(rq);rZ.current=rq;let rV=(0,i.useRef)(null);rV.current??=(t={pendingReads:e=>[nR.current.get(e),nR.current.get(`force:${e}`)],read:e=>rZ.current(e),wanted:r_,onError:e=>console.error("Failed to read a message sent while idle:",e)},r=!1,s=null,e=>{s=e,r||(r=!0,(async()=>{try{for(;null!==s;){let e=s;if(s=null,t.wanted(e))try{await Promise.allSettled(t.pendingReads(e)),t.wanted(e)&&await t.read(e)}catch(e){t.onError?.(e)}}}finally{r=!1}})())}),ne.current=(0,i.useCallback)(t=>{if(!t0.current)switch(t.type){case"session_ended":{let e=tQ.current;if(!e||t.sessionId!==e)return;t0.current=e,rv(),tO.current?.close(),iO(e),c?.(e);return}case"connected":if(Y({type:"end"}),Array.isArray(t.pendingExtensionUiIds)){let e=new Set(t.pendingExtensionUiIds);tE(t=>iy(t,e)),tT(t=>iy(t,e))}F(i2.E),!0===t.isStreaming&&(rv(),t8.current=!0,t4.current=!0,Q(!0),tm({kind:"waiting_model"})),tQ.current&&rs(tQ.current);break;case"agent_start":nI(),rv(),t8.current=!0,t4.current=!0,Q(!0),tm({kind:"waiting_model"}),e_(null),Y({type:"start"});break;case"agent_end":if(!t4.current)break;if(tm(null),e_(null),Y({type:"end"}),tQ.current){let e=tQ.current,t=ny.current,n=++eV.current;ra(e),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(r=>{r&&nM.current&&tQ.current===e&&ny.current===t&&(nX(r.state),ri(r.state,e,t,n),r.state?.systemPrompt!==void 0&&eY(r.state.systemPrompt??null),r.state?.extensionStatuses!==void 0&&tR(r.state.extensionStatuses??[]),r.state?.extensionWidgets!==void 0&&tL(r.state.extensionWidgets??[]),tz(i7(r.state?.queuedMessages)))}).catch(()=>{})}break;case"agent_settled":{let e=t8.current;if(t8.current=!1,!e||t6.current)break;let n=tQ.current,r=rz();ts(!1),n&&(ra(n),rW(n)),r&&d?.({aborted:!0===t.aborted,...!0===t.subagentsActive?{subagentsActive:!0}:{}});break}case"prompt_done":{nI();let e=ny.current,n=t6.current;t6.current=!1,nk.current=null;let r=rO(e,!0===t.aborted,!0===t.subagentsActive);if(!n&&!r)break;let i=tQ.current;i&&ra(i),!t8.current&&(rz(),i&&rW(i))}break;case"prompt_error":rI({type:"error",message:t.errorMessage??"Command failed"});break;case"extension_error":var n,r;rI({type:"error",message:(n=t.extensionPath,r=t.error??"Extension command failed","string"==typeof n&&n&&!i0.test(n)?`Extension "${n}" error: ${r}`:r)});break;case"message_start":case"message_update":if(!t4.current||iX(t))break;if("message_start"===t.type){let e=t.message;if(e?.role==="user")break;e?.role==="assistant"?(Y({type:"snapshot",message:e}),e.content.length>0&&tm(null)):e&&tm(null)}else{let e=t.assistantMessageEvent;e&&(Y({type:"delta",event:e}),"toolcall_start"!==e.type&&"toolcall_delta"!==e.type&&tm(null))}!nr.current&&ni.current&&null===na.current&&(na.current=requestAnimationFrame(()=>{na.current=null,ni.current&&nK("auto")}));break;case"message_end":{if(!t4.current){let e=t.message;e?.role==="custom"&&!(0,nN.zZ)(e)&&tQ.current&&rV.current?.(tQ.current);break}if(iX(t))break;let e=t.message;if(e&&"user"===e.role){let t=iw(e),n=iK(t),r=nk.current;nk.current=null,r&&nI(),P(e=>{let i=e[e.length-1];return r&&i?.role==="user"&&iK(i)===r?r===n?e:[...e.slice(0,-1),t]:[...e,t]})}else if(e){let n=Array.isArray(t.transcriptNotices)?t.transcriptNotices:void 0;if(P(t=>[...t,(0,i1.mO)(iw(e),n)]),"toolResult"===e.role){let t=e.toolCallId;F(e=>(0,i2.vx)(e,t))}if("assistant"===e.role){let e=tQ.current;e&&rs(e)}}Y({type:"end"}),tm({kind:"waiting_model"});break}case"tool_execution_start":{if(iY(t))break;let e=t.toolCallId,n=t.toolName,r=performance.now();F(e=>(0,i2.Ho)(e,t,r)),tm(t=>{let r=t?.kind==="running_tools"?[...t.tools]:[];return r.some(t=>t.id===e)||r.push({id:e,name:n}),{kind:"running_tools",tools:r}});break}case"tool_execution_update":{if(iY(t))break;let e=t.toolCallId,n=t.toolName,r=t.partialResult,i=r?.content;Array.isArray(i)&&("bash"===n||"powershell"===n||n===nT.sp||(0,nz.G)(r?.details))&&O(t=>{let s=new Map(t);return s.set(e,{role:"toolResult",toolCallId:e,toolName:n,content:i,isError:r?.isError,details:r?.details}),s});let s=n===nT.sp?(0,nT.ky)(t.partialResult):function(e){if(!iQ(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>iQ(e)&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n").split(/\r?\n/),r="";for(let e=n.length-1;e>=0&&!(r=n[e].trim());e-=1);if(!r)return null;let i=r.replace(/\s+/g," ");return i.length<=500?i:`...${i.slice(-497)}`}(t.partialResult);tm(t=>{let r=t?.kind==="running_tools"?[...t.tools]:[],i=r.find(t=>t.id===e),a={id:e,name:n||i?.name||"tool",progress:s??i?.progress};return{kind:"running_tools",tools:[...r.filter(t=>t.id!==e),a]}});break}case"tool_execution_end":{if(iY(t))break;let e=t.toolCallId;u?.(t.toolName);let n=performance.now();F(e=>(0,i2.Ho)(e,t,n)),O(t=>{if(!t.has(e))return t;let n=new Map(t);return n.delete(e),n}),tm(t=>{if(t?.kind!=="running_tools")return t;let n=t.tools.filter(t=>t.id!==e);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"queue_update":nI(),tz({steering:[...t.steering??[]],followUp:[...t.followUp??[]]});break;case"auto_retry_start":case"summarization_retry_scheduled":e_({attempt:t.attempt,maxAttempts:t.maxAttempts,errorMessage:t.errorMessage});break;case"auto_retry_end":case"summarization_retry_attempt_start":case"summarization_retry_finished":e_(null);break;case"auto_compaction_start":case"compaction_start":ts(!0),td(null),tp(null);break;case"auto_compaction_end":case"compaction_end":ts(!1),e_(null),t.errorMessage?(td(t.errorMessage),tp(null)):!t.aborted&&(tp(sl(t.result,t.reason??"auto")),tQ.current&&ra(tQ.current));break;case"bash_output":{let e=t.output;if(!t5.current||"string"!=typeof e)break;er(n=>n&&!n.result&&n.command===t.command?{...n,liveOutput:e}:n);break}case"editor_paste":"string"==typeof t.text&&e.chatInputRef?.current?.pasteText(nx(t.text));break;case"extension_ui_request":rP(t);break;case"extension_ui_closed":tE(e=>ik(e,t.id))}},[rI,ri,e.chatInputRef,rv,Y,rP,ra,nI,rO,d,c,u,rs,rW,nK,rz,nX]);let rJ=(0,i.useCallback)(async(e,t)=>{let n=e.trim();if(!n&&!t?.length)return;let r=!t?.length&&n.startsWith("!");if(t5.current||t4.current&&!r){t5.current&&r&&rI({type:"warning",message:r$("chat.bashAlreadyRunning")}),n3(e,t,nY);return}if(n5&&(n7(null),!await no.current?.(n5))){n7(n5),n3(e,t,nY);return}let i=!t?.length&&n.startsWith("/");if(r){let r=n.startsWith("!!"),i=(r?n.slice(2):n.slice(1)).trim();return i?void await nl.current?.(i,r):void n3(e,t,nY)}let s=ny.current+1;rv(),t6.current=!0;let o=t?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),d={role:"user",content:o?.length?[...e.trim()?[{type:"text",text:e}]:[],...o]:e,timestamp:Date.now()},c=iK(d),u=nP.current,p=u.at(-1)??null,h=i9(nL.current.slice(u.length),c);P(e=>[...e,d]),nk.current=c,ny.current=s,t4.current=!0,Q(!0),tm(i?{kind:"running_command"}:{kind:"waiting_model"}),Y({type:"start"}),nr.current=!0,tf(!0);let m=()=>{P(e=>{let t=e.lastIndexOf(d);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),nk.current=null},g=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),f=null,x=!1;try{if(S&&l){let t=tQ.current??await nc.current,n=t??await ru();if(!n)throw Error("Unable to create a session for the prompt");f=n,eC&&(e6(eC),t&&await iE(n,{type:"set_model",provider:eC.provider,modelId:eC.modelId})),nM.current&&await rk(n).catch(e=>{if(nM.current)throw e}),x=!0;let r=await iE(n,{type:"prompt",message:e,...g?.length?{images:g}:{}});r?.queued&&m(),rd(1,e)}else if(a){f=a.id,await rk(a.id),x=!0;let t=await iE(a.id,{type:"prompt",message:e,...g?.length?{images:g}:{}});t?.queued&&m()}else throw Error("No active session for the prompt");eh(null),i&&f&&rD(f,s)}catch(n){if(console.error("Failed to send message:",n),!(!x||iN(n))&&f){nj.current!==s&&(nw.current={runId:s,sid:f,message:e,images:t,draftKey:nY,parkedDraftKey:S&&l?nG(l):null,lastEntryIdAtSend:p,sameTextAfterSend:h,bubble:d,key:c,command:i},nM.current||rA()),rD(f,s);return}if(t6.current=!1,P(e=>i5(e,d)),n instanceof iC&&n.missingCwd?eh(n.missingCwd):rI({type:"error",message:n instanceof Error?n.message:String(n)}),n3(e,t,nY),nk.current=null,f)return void rH(f);t4.current=!1,ry("send_failed"),Q(!1),tm(null),Y({type:"end"})}},[S,l,eC,a,ru,rk,rd,rD,rI,rA,rv,ry,nY,Y,rH,n3,n5,n7,r$]);nl.current=(0,i.useCallback)(async(e,t)=>{if(t5.current)return;let n=`${t?"!!":"!"}${e}`;t5.current=!0;let r=Date.now();er({command:e,excludeFromContext:t,startedAt:r}),et(!0);let i=null;try{let s=tQ.current??a?.id??await ru();if(!s)throw Error("Unable to create a session for the shell command");await rk(s).catch(()=>{});let l=await iE(s,{type:"bash",command:e,excludeFromContext:t});t4.current&&l?(i={command:e,excludeFromContext:t,startedAt:r,result:l},t9.current=nS.current):(await ra(s),rd(1,n))}catch(e){console.error("Failed to execute shell command:",e),e instanceof iC&&"extension_reported"===e.code||rI({type:"error",message:e instanceof Error?e.message:String(e)}),n3(n,void 0,nY)}finally{t5.current=!1,er(i),et(!1);let e=rK.current;rK.current=null,e&&rV.current?.(e)}},[rI,nY,rk,ru,ra,rd,n3,a]);let rG=en?.result;(0,i.useEffect)(()=>{if(X||!rG)return;let e=tQ.current;e&&ra(e,!1,!1,{force:!0})},[X,rG,ra]);let rY=(0,i.useCallback)(t=>{let n=[...t?.steering??[],...t?.followUp??[]].join("\n\n");t?.images?.length?n3(n,t.images,nY):n&&e.chatInputRef?.current?.prependText(n)},[nY,e.chatInputRef,n3]),rX=(0,i.useCallback)(async()=>{let e=tQ.current;if(e){if(t5.current&&!t4.current){try{await iE(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{let t=await iE(e,{type:"abort"});t&&tz({steering:[],followUp:[]}),rY(t)}catch(e){console.error("Failed to abort:",e)}}},[rY]),rQ=(0,i.useCallback)(async(e,t)=>{if(t5.current)return;let n=tQ.current;if(n){eQ(e);try{let{cancelled:r,newSessionId:i}=await iE(n,{type:"fork",entryId:e})??{};!r&&i&&(t&&n0(i,t),m?.(i))}catch(e){console.error("Fork failed:",e),rI({type:"error",message:e instanceof Error?e.message:String(e)})}finally{eQ(null)}}},[rI,m]),r0=(0,i.useCallback)(async e=>{if(t5.current)return!1;let t=tQ.current;if(!t)return!1;try{let n=await iE(t,{type:"navigate_tree",targetId:e});if(n?.cancelled||tQ.current!==t)return!1;return await ra(t),tQ.current===t}catch(e){return console.error("Failed to navigate:",e),!1}},[ra]);no.current=r0;let r1=(0,i.useCallback)(async e=>{if(t5.current||t4.current||ti)return;A(e);let t=tQ.current;t&&(await rl(t,e),e&&iE(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[ti,rl]),r2=(0,i.useCallback)(async(e,t)=>{if(S){let n={provider:e,modelId:t};ng.current=n,eN(n),e6(n),null===nf.current&&eP(se(nb.current[`${e}/${t}`])??nv.current);let r=tQ.current??await nc.current;if(!r)return;try{await iE(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tQ.current;if(!n||nE.current)return;nE.current=!0,e1({provider:e,modelId:t}),tr(!0);let r=t4.current||t5.current,i=async()=>{let e=await fetch(iI(n)).catch(()=>null),t=e?.ok?await e.json().catch(()=>null):null;t?.state&&nM.current&&tQ.current===n&&nX(t.state)};try{let s=await iE(n,{type:"set_model",provider:e,modelId:t});e4({provider:s.provider,modelId:s.id}),nE.current=!1,r?(e1(null),await i()):await ra(n)}catch(e){console.error("Failed to set model:",e),nE.current=!1,e1(e0),rI({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),r?await i():await ra(n,!1,!0)}finally{nE.current=!1,tr(!1)}},[rI,e0,S,ra,eN,nX]),r4=(0,i.useCallback)(async e=>{let t=tQ.current;if(!t||ti)return!0;ts(!0),td(null),tp(null);try{let n=await iE(t,{type:"compact",...e?{customInstructions:e}:{}});return tp(sl(n,"manual")),await ra(t)&&rd(),!0}catch(e){return td(e instanceof Error?e.message:String(e)),tp(null),!1}finally{ts(!1)}},[ti,ra,rd]),r8=(0,i.useCallback)(()=>td(null),[]),r6=(0,i.useCallback)(async e=>{let t,n=l??a?.cwd??"",r=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",i=null;try{let n=await fetch(r,e?{signal:e}:void 0);if(!n.ok){let e="";try{let t=await n.json();t&&"object"==typeof t&&"error"in t&&"string"==typeof t.error&&(e=t.error),i=iS(t)}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw e}throw Error(e||`Failed to load models (HTTP ${n.status})`)}t=await n.json(),e?.throwIfAborted()}catch(t){throw e?.aborted||t instanceof DOMException&&"AbortError"===t.name||(eu(i),ed(i?null:t instanceof Error?t.message:String(t))),t}eu(null),es(t.models),ed(t.modelError??null),eg(t.modelScopeWarnings??[]),ex(!!t.isScoped),ev(null),ey.current=null,ej(t.thinkingLevels??{}),eS(t.thinkingLevelMaps??{});let s=t.modelList??[];el(s);let o=t.defaultModel?s.find(e=>e.id===t.defaultModel?.modelId&&e.provider===t.defaultModel?.provider):void 0;if(eE(o?{provider:o.provider,modelId:o.id}:null),nb.current=t.thinkingLevelPins??{},nv.current=se(t.defaultThinkingLevel),eO(se(t.savedDefaultThinkingLevel)),S&&!tQ.current){let e=ng.current,n=e&&(0===s.length||!!t.isScoped||s.some(t=>t.provider===e.provider&&t.id===e.modelId));e&&!n&&(ng.current=null,eN(null));let r=n?e:o&&{provider:o.provider,modelId:o.id},i=r&&t.thinkingLevelPins?.[`${r.provider}/${r.modelId}`];null===nf.current&&eP(se(i)??nv.current)}},[S,l,a?.cwd]),r3=(0,i.useCallback)(()=>{if(ey.current)return;let e={};ey.current=e;let t=l??a?.cwd??"";fetch(`/api/models?scope=all${t?`&cwd=${encodeURIComponent(t)}`:""}`).then(async t=>{if(!t.ok)throw Error(`Failed to load models (HTTP ${t.status})`);let n=await t.json();ey.current===e&&(es(e=>({...n.models,...e})),ej(e=>({...n.thinkingLevels,...e})),eS(e=>({...n.thinkingLevelMaps,...e})),ev(n.modelList??[]))}).catch(t=>{ey.current===e&&(ey.current=null,rI({type:"error",message:t instanceof Error?t.message:String(t)}))})},[rI,l,a?.cwd]);(0,i.useEffect)(()=>{!ef||!nZ||eb||ea.some(e=>e.provider===nZ.provider&&e.id===nZ.modelId)||r3()},[eb,nZ,ef,r3,ea]);let r5=(0,i.useCallback)(async e=>{let t=l??a?.cwd,n=await fetch("/api/models/default",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t?{cwd:t}:{},...e})});if(n.ok)return;let r="";try{let e=await n.json();e&&"object"==typeof e&&"error"in e&&"string"==typeof e.error&&(r=e.error)}catch{}throw Error(r||`HTTP ${n.status}`)},[l,a?.cwd]),r9=(0,i.useCallback)(()=>{r6().catch(()=>{})},[r6]),r7=(0,i.useCallback)(async(e,t)=>{try{await r5({provider:e,modelId:t})}catch(e){rI({type:"error",message:`Failed to save default model: ${e instanceof Error?e.message:String(e)}`});return}rI({type:"success",message:`Default model: ${e}/${t}`}),eE({provider:e,modelId:t}),(nZ?.provider!==e||nZ?.modelId!==t)&&await r2(e,t),r9()},[rI,nZ,r2,r9,r5]),ie=(0,i.useCallback)(async(t,n)=>{let r=e.session?.relation?.kind;if("side"===r||"subagent"===r)return r$(i$[r]);let i=tQ.current;if(!i)return r$("sideChat.error.noSession");let s=await iT(i,r$,n);return"error"in s?s.error:(g?.(s.session,t),null)},[g,e.session?.relation?.kind,r$]),it=(0,i.useCallback)(async t=>{if(!t.startsWith("/"))return{handled:!1};let n=t.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!n)return{handled:!1};let[,r,i=""]=n,s=i.trim(),a=tQ.current??await ru(),l=e=>(e.handled&&(e.error?rI({type:"error",message:e.error}):e.action||rI({type:"success",message:e.message??"Command completed"})),e);try{switch(r){case"compact":if(!a||ti)return l({handled:!0,error:"No active session to compact"});return r4(s||void 0).then(t=>{!t&&s&&e.chatInputRef?.current?.prependText(`/compact ${s}`)}),l({handled:!0,action:"compact"});case"auto-compact":{if(!a)return l({handled:!0,error:"No active session"});let e=await iE(a,{type:"get_state"}),t=!(e?.autoCompactionEnabled??!0);return await iE(a,{type:"set_auto_compaction",enabled:t}),tl(t),l({handled:!0,message:t?"Auto-compaction enabled":"Auto-compaction disabled"})}case"reload":if(!a)return l({handled:!0,error:"No active session to reload"});return await iE(a,{type:"reload"}),await Promise.all([ra(a,!1,!0),ro(a),rx(),r6()]),l({handled:!0,message:"Reloaded session resources"});case"name":if(!a)return l({handled:!0,error:"No active session to name"});if(!s)return l({handled:!0,error:"Usage: /name <name>"});return await iE(a,{type:"set_session_name",name:s}),await ra(a)&&rd(),l({handled:!0,message:`Session renamed to ${s}`});case"session":{if(!a)return l({handled:!0,error:"No active session"});if(!k)return l({handled:!0,message:(0,i_.C$)(rr,r$)});let e=await iE(a,{type:"get_session_stats"});return e&&tN(e),k(),l({handled:!0,action:"openSessionStats"})}case"mcp":{if(s||!j)return{handled:!1};let e=await rb();if(!e||!(e.some(rn)||!e.some(e=>"mcp"===e.name)))return{handled:!1};return j("mcp"),l({handled:!0,action:"openSettings"})}case"copy":{if(!a)return l({handled:!0,error:"No active session"});let e=await iE(a,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return l({handled:!0,error:"No assistant message to copy"});return await (0,tc.D)(t),l({handled:!0,message:"Copied last assistant message"})}case"clone":{if(!a)return l({handled:!0,error:"No active session to clone"});if(t4.current||t5.current)return l({handled:!0,error:"Cannot clone while the session is running"});let e=rU.current,t=await iE(a,{type:"clone",leafId:e?.base===R&&e.lastEntryId===nP.current.at(-1)?e.leafId:R});if(t?.cancelled&&t.byExtension)return{handled:!0};if(t?.cancelled||!t?.newSessionId)return l({handled:!0,error:"Cannot clone an empty or unsaved session"});let n=l({handled:!0,message:"Cloned current session branch"});return m?.(t.newSessionId),n}case"side":{let e=await ie(s||null);return l(e?{handled:!0,error:e}:{handled:!0,action:"openSideChat"})}default:return{handled:!1}}}catch(e){return l({handled:!0,error:e instanceof Error?e.message:String(e)})}},[R,rI,ru,r4,ti,r6,ra,rx,ro,rd,j,m,k,e.chatInputRef,rr,rb,ie,r$]),ir=(0,i.useCallback)(async(e,t,n)=>{let r=tQ.current;if(n5)return void n3(e,n,nY);if(!r){n3(e,n,nY),rI({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 iE(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){if(console.error("Failed to submit streaming prompt:",t),n3(e,n,nY),t instanceof iC&&t.missingCwd)return void eh(t.missingCwd);iN(t)?rI({type:"error",message:t.message}):rT()}},[rI,rT,nY,n5,n3]),ii=(0,i.useCallback)(async(e,t)=>{await ir(e,"steer",t)},[ir]),is=(0,i.useCallback)(async(e,t,n)=>{await ir(e,t,n)},[ir]),ia=(0,i.useCallback)(async(e,t)=>{await ir(e,"followUp",t)},[ir]),il=(0,i.useCallback)(async()=>{let e=tQ.current;if(e)try{await iE(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),io=(0,i.useCallback)(async()=>{let e=tQ.current;if(e)try{let t=await iE(e,{type:"clear_queue"});tz({steering:[],followUp:[]}),rY(t)}catch(e){console.error("Failed to recall queued messages:",e),rI({type:"error",message:"Failed to recall queued messages"})}},[rI,rY]),id=(0,i.useCallback)(async e=>{if("auto"===e){nf.current=null,eA(null),eF(null);return}S?(nf.current=e,eA(e)):eF(e);let t=tQ.current??await nc.current;if(t)try{await iE(t,{type:"set_thinking_level",level:e}),nM.current&&tQ.current===t&&(eB(e),eF(null))}catch(e){console.error("Failed to set thinking level:",e),eF(null)}},[S]),ic=(0,i.useCallback)(async e=>{try{await r5({thinkingLevel:e})}catch(e){rI({type:"error",message:`Failed to save default reasoning level: ${e instanceof Error?e.message:String(e)}`});return}rI({type:"success",message:`Default reasoning level: ${e}`}),eO(e),nJ!==e&&await id(e),r9()},[rI,nJ,id,r9,r5]),iu=(0,i.useCallback)(async e=>{let t=(0,iW.xG)(e);!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:iD();if(t)try{t.setItem(iF,e)}catch{}}(e),nH(e);let n=tQ.current??await nc.current;if(!n){t2.current=void 0!==t;return}try{let e=await iE(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});t2.current=void 0!==t;let r=e?.sessionId??n;(r!==n||e?.recreated)&&(rv(),ry("set_tools"),tE([]),tT([]),tQ.current=r,e?.recreated&&t1.current===r&&rj(r)),rm(),tR([]),tL([]);let[i]=await Promise.all([iE(r,{type:"get_state"}),ro(r)]);nM.current&&tQ.current===r&&(eY(i.systemPrompt??""),nX(i))}catch(e){console.error("Failed to set tools:",e)}},[rv,rm,ry,ro,rj,nH,nX]),ip=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=nd.current;n&&(null!==na.current&&(cancelAnimationFrame(na.current),na.current=null),nt.current=!0,nr.current=!1,ni.current=!1,tf(!1),n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),ns.current=n.scrollTop)},[]),ih=(0,i.useCallback)(()=>{let e=nd.current,t=nn.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!==na.current&&(cancelAnimationFrame(na.current),na.current=null),ni.current=!0,ns.current=n,e.scrollTo({top:n,behavior:"auto"})},[]),im=(0,i.useCallback)(()=>{let e=nd.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=t4.current,s=ni.current,a=function(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:96;return!!i4(n,r,i)||!(n<t)&&(!!(!e&&n>t&&i4(n,r,i,s))||e)}(s,ns.current,t,n,r,i?96:8);ni.current=a,ns.current=t;let l=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return!(n<=t)&&!i4(e,t,n,r)}(t,n,r);tb(e=>e===l?e:l),!s&&a&&i?nK("auto"):a||null===na.current||(cancelAnimationFrame(na.current),na.current=null)}},[nK]),ig=(0,i.useCallback)((e,t)=>{t?.running&&(ro(e),(t.state?.isStreaming||t.state?.isPromptRunning)&&(t8.current=!!t.state.isStreaming,t6.current=!!t.state.isPromptRunning,t4.current=!0,Q(!0),tm(e=>ib(e,t.state?.isStreaming===!0)),Y({type:"resume"}),!t.state.isStreaming&&t.state.isPromptRunning&&rD(e)),t.state?.isBashRunning&&(t5.current=!0,et(!0),rB(e))),t?.state&&(tt(!0===t.state.ephemeral),void 0!==t.state.isCompacting&&ts(t.state.isCompacting),void 0!==t.state.systemPrompt&&eY(t.state.systemPrompt??null),void 0!==t.state.extensionStatuses&&tR(t.state.extensionStatuses??[]),void 0!==t.state.extensionWidgets&&tL(t.state.extensionWidgets??[]),void 0!==t.state.queuedMessages&&tz(i7(t.state.queuedMessages)))},[Y,ro,rB,rD]);tK.current=(e,t)=>{!tB.current||t0.current===e||(tB.current=!1,tV.current={count:tV.current.count+1,lastAt:Date.now(),lastReason:t},t_(e=>e+1),nM.current&&tQ.current===e&&t1.current===e&&(rj(e),ra(e,!1,!0).then(t=>{nM.current&&tQ.current===e&&ig(e,t)})))},(0,i.useEffect)(()=>{let e=a?.id;if(!e)return;let t=!1,n=tq.current,r=async()=>{let n=await rw(e);!t&&"hidden"===document.visibilityState&&iJ(n)&&tK.current(e,"activity")};r();let i=setInterval(()=>void r(),3e4);n.renewStartedAt=Date.now();let s=()=>{"visible"===document.visibilityState&&(tK.current(e,"visible"),r())};return document.addEventListener("visibilitychange",s),()=>{t=!0,clearInterval(i),n.renewStartedAt=null,document.removeEventListener("visibilitychange",s)}},[rw,a?.id]),(0,i.useEffect)(()=>{if(nM.current=!0,eJ.current=eV.current,a){tQ.current=a.id;let e=iP(a.id);e&&(I({sessionId:a.id,filePath:"",totalActiveMs:e.totalActiveMs??0,tree:e.summaryTree,leafId:e.leafId,context:{messages:e.messages,entryIds:e.entryIds,oldestEntryId:e.oldestEntryId,hasMore:e.hasMore,turnsBefore:e.turnsBefore,thinkingLevel:e.thinkingLevel,model:e.model},stats:e.stats}),A(e.leafId),P(e.messages),B(e.entryIds),K(e.oldestEntryId),Z(e.hasMore),J(e.turnsBefore),M(null),$(!1)),ra(a.id,!e,!0,{force:!0}).then(e=>{ig(a.id,e)})}return()=>{nM.current=!1;let e=S?o:null;e&&queueMicrotask(()=>{nM.current||nm.current||n1(e)});let t=tQ.current,n=nA.current;if(t&&n&&n.sessionId===t&&n.snapshotRevision){let e=iP(t),r=nP.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)?iz({sessionId:t,revision:n.snapshotRevision,messages:nL.current,entryIds:nP.current,leafId:nO.current,oldestEntryId:nW.current,hasMore:nF.current,turnsBefore:nD.current,summaryTree:n.tree,thinkingLevel:n.context.thinkingLevel,model:n.context.model,stats:n.stats,totalActiveMs:n.totalActiveMs,loadedEntryIds:nP.current}):iO(t)}rL.current(),null!==na.current&&(cancelAnimationFrame(na.current),na.current=null),t7.current+=1,rv(),ry()}},[]),(0,i.useEffect)(()=>{b?.(eG)},[eG,b]),(0,i.useEffect)(()=>(y?.(rp),()=>y?.(null)),[rp,y]);let ix=(0,i.useCallback)(()=>{let e=null;try{e=tO.current?.snapshot?.()??null}catch{e=null}let t=tQ.current,n=tq.current,r=tV.current;return{pageId:(0,e$.kz)(),sessionId:t,selectedSessionId:t1.current,mounted:nM.current,wantsStream:null!==t&&nB(t),connection:e,released:{active:tB.current,...tZ.current},reattached:{...r},hiddenReleaseDueAt:tJ.current,hiddenGraceMs:iG.P,graceDueAt:tG.current,run:{agentRunning:t4.current,bashRunning:t5.current,compacting:tY.current,dialogs:tX.current},lease:{renewIntervalMs:3e4,renewStartedAt:n.renewStartedAt,inFlightSince:n.inFlightSince,requests:n.requests,unanswered:n.unanswered,errors:n.errors,last:n.last&&{...n.last,reply:n.last.reply&&{...n.last.reply}}}}},[nB]);(0,i.useEffect)(()=>(w?.(ix),()=>w?.(null)),[ix,w]);let ij=X||ee||ti;(0,i.useEffect)(()=>{x&&x(N?.tree??[],R,r1,ij)},[N?.tree,R,r1,ij,x]),(0,i.useEffect)(()=>{let e=nd.current;if(e)return ns.current=e.scrollTop,e.addEventListener("scroll",im,{passive:!0}),()=>{e.removeEventListener("scroll",im)}},[L.length,E,im]),(0,i.useEffect)(()=>{X||tf(!1)},[X]),(0,i.useLayoutEffect)(()=>{L.length>0&&(nr.current?(nr.current=!1,nt.current=!0,ih()):nt.current?!t4.current&&ni.current&&nK("auto"):(nt.current=!0,nK("instant")))},[L.length,X,nK,ih]),(0,i.useEffect)(()=>{let e=new AbortController;return(async()=>{for(let t=0;;t++)try{await r6(e.signal);return}catch(n){if(e.signal.aborted||n instanceof DOMException&&"AbortError"===n.name||t>=sn.length||(await si(sn[t]),e.signal.aborted))return}})(),()=>e.abort()},[r6,f]),(0,i.useEffect)(()=>{if(!tu)return;let e=setTimeout(()=>tp(null),6e3);return()=>clearTimeout(e)},[tu]);let[iM,iR]=(0,i.useState)(null),iA=(0,i.useRef)(5e3),iL=(0,i.useRef)(null),iB=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(0===tw.visible.length){iB.current=null;return}let e=tw.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{tS({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=tw.visible[0];if(!t||(iB.current!==t.id&&(iB.current=t.id,iA.current=5e3),tw.visible.some(e=>e.id===iM)))return;iL.current=Date.now();let n=setTimeout(()=>{tS({type:"mark_oldest_exiting"})},iA.current);return()=>{clearTimeout(n),null!==iL.current&&(iA.current=Math.max(0,iA.current-(Date.now()-iL.current)),iL.current=null)}},[tw.visible,iM]),(0,i.useEffect)(()=>{tN(null)},[L.length,eU?.tokens,eU?.percent,eU?.contextWindow]);let iU=nJ??"auto",iZ=tI[0]??null,i8=Math.max(0,tI.length-1),i6=t$[0]??null,ss=Math.max(0,t$.length-1),so=(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?iq(r,s-e.length):n.get(t)??t)}return i})(D,L.length,H),[D,L.length,H]);return{data:N,loading:E,error:T,activeLeafId:R,messages:L,activeToolResults:z,toolClocks:W,entryIds:D,messageKeys:so,historyCursor:U,hasEarlierMessages:q,earlierTurnCount:V,streamingStore:G,agentRunning:X,modelNames:ei,modelList:ea,modelError:eo,missingCwd:ep??ec,modelScopeWarnings:em,isModelScopeActive:ef,allModelList:eb,modelThinkingLevels:ek,modelThinkingLevelMaps:ew,newSessionModel:eC,toolPreset:eT,thinkingLevel:iU,retryInfo:eH,contextUsage:eU,systemPrompt:eG,forkingEntryId:eX,isCompacting:ti,compactError:to,compactResult:tu,currentModel:nq,displayModel:nZ,modelSwitching:tn,sessionStats:rr,autoCompactionEnabled:ta,slashCommands:tv,slashCommandsLoading:tk,queuedMessages:tP,notices:tw.visible,extensionDialog:iZ,waitingExtensionDialogCount:i8,extensionCustomUi:i6,waitingExtensionCustomUiCount:ss,extensionStatuses:tM,extensionWidgets:tA,respondToExtensionUi:rC,sendExtensionCustomInput:rN,isAutoModelSelection:S&&null===eC,isAutoThinkingSelection:S&&null===eR,defaultModel:eI,savedDefaultThinkingLevel:ez,agentPhase:th,isNew:S,sessionEphemeral:te||a?.ephemeral===!0,newSessionEphemeral:e3,handleNewSessionEphemeralChange:n2,editEntryId:n5,promptAnchorActive:tg,showScrollToBottom:tx,sessionIdRef:tQ,scrollContainerRef:nd,lastUserMsgRef:nn,pendingScrollToUserRef:nr,initialScrollDoneRef:nt,handleSend:rJ,handleAbort:rX,startSideChat:ie,handleFork:rQ,handleNavigate:r0,handleModelChange:r2,handleCompact:r4,handleSteer:ii,handleFollowUp:ia,handlePromptWithStreamingBehavior:is,handleAbortCompaction:il,dismissCompactError:r8,handleRecallQueue:io,handleBuiltinSlashCommand:it,handleEditContent:re,cancelEdit:n5?rt:void 0,addNotice:rI,setNoticePaused:iR,handleToolPresetChange:iu,handleThinkingLevelChange:id,handleSetDefaultModel:r7,handleSetDefaultThinkingLevel:ic,loadTools:ro,loadSlashCommands:rx,loadAllModels:r3,setActiveLeafId:A,setData:I,setMessages:P,loadContext:rl,scrollToBottom:nK,scrollUserMsgToTop:ih,scrollToMessage:ip,dispatch:Y,setAgentRunning:Q,setForkingEntryId:eQ,bashRunning:ee,pendingBash:en,handleAgentEventRef:ne}}({session:s,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:m,initialNewSessionChoices:f,onNewSessionChoicesChange:x,onAgentEnd:et,onSessionEnded:v,onToolEnd:y,onAttentionNeeded:k,onSessionCreated:j,onSessionForked:w,onSideSession:C,modelsRefreshKey:N,chatInputRef:I,onBranchDataChange:E,onSystemPromptChange:$,onSystemToolsChange:T,onSystemInfoLoaderChange:M,onSessionStatsPanelOpen:L,onOpenSettings:P,onDebugSnapshotReaderChange:R,t:J,deferInitialScroll:!!er}),tW=so(ex,sd),[tF,tD]=(0,i.useState)(!1),tB=(0,i.useCallback)(async()=>{if(s&&!tF){tD(!0);try{let e=await fetch(`/api/sessions/${encodeURIComponent(s.id)}`,{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);v?.(s.id)}catch(e){tD(!1),e8({type:"error",message:J("sidebar.deleteFailed",{error:e instanceof Error?e.message:String(e)})})}}},[s,tF,v,e8,J]),tH=so(ex,sc),t_=(0,i.useCallback)(()=>ex.getState().streamingMessage,[ex]),tU=eb||ev,tK=(0,i.useCallback)((e,t)=>{tp(e,{value:rU(t),images:rK(t)})},[tp]);(0,i.useEffect)(()=>{if(eb&&V)return V()},[eb,V]);let[tq,tZ]=(0,i.useState)(null),[tV,tJ]=(0,i.useState)(!1),[tG,tY]=(0,i.useState)(!1),[tX,tQ]=(0,i.useState)(null),t0=(0,i.useRef)(null),t1=(0,i.useRef)(null),t2=(0,i.useCallback)(()=>{tZ(null),tJ(!1),tQ(null)},[]);(0,i.useEffect)(()=>{B||t2()},[B,t2]);let t4=(0,i.useCallback)(()=>{if(!B||tV)return;let e=window.getSelection(),t=e?.rangeCount?e.getRangeAt(0):null,n=nn.current;if(!e||e.isCollapsed||!t||!n||!n.contains(t.commonAncestorContainer))return void tZ(null);let r=e.toString().trim();if(!r)return void tZ(null);let i=t.getBoundingClientRect();tZ({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))})},[B,tV]);(0,i.useEffect)(()=>{tV&&tq&&t1.current?.insertIfEmpty(n_(tq.text))},[tV,tq]),(0,i.useLayoutEffect)(()=>{let e=t0.current;if(!e||!tq)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(tq.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(tq.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)}},[tq,tV,tX]),(0,i.useEffect)(()=>{if(!tq)return;let e=e=>{tV||t0.current?.contains(e.target)||t2()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),tG||t2())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[tq,tV,tG,t2]);let t8=(0,i.useCallback)(()=>{tq&&(I?.current?.insertQuote(n_(tq.text)),t2())},[I,tq,t2]),t6=(0,i.useCallback)(async e=>{if(!tG&&e.trim()&&tq){tY(!0),tQ(null);try{let t=await tu(e,tq.text);if(!t)return void t2();t1.current?.restoreSubmission(e),tQ(t)}catch(t){t1.current?.restoreSubmission(e),tQ(t instanceof Error?t.message:String(t))}finally{tY(!1)}}},[tq,tG,t2,tu]),t3=(0,i.useCallback)(async e=>{let t;try{t=await tu(e)}catch(e){t=e instanceof Error?e.message:String(e)}t&&(I?.current?.restoreSubmission(e),e8({type:"error",message:t}))},[e8,I,tu]),t5=(0,i.useRef)(!1);(0,i.useEffect)(()=>{el||eo||!H||t5.current||(t5.current=!0,_?.(),to(H))},[H,el,eo,to,_]),(0,i.useEffect)(()=>{let e=!!eq&&!ee.current;ee.current=!!eq,Y&&e&&X.current()},[Y,eq]),(0,i.useEffect)(()=>{S||(a=tU?td:null)},[S,tU,td]);let[t9,t7]=(0,i.useState)(50),[ne,nt]=(0,i.useState)(null),nn=(0,i.useRef)(null),nr=(0,i.useRef)(null),ni=(0,i.useRef)(!1),ns=(0,i.useRef)(!1),na=(0,i.useRef)(er);na.current=er;let[nl,no]=(0,i.useState)(null),nd=ed[ep.indexOf(nl?.entryId??"")],nc=nd?.role==="assistant"?nl?.blockIndex===void 0?nd.content.find(e=>"text"===e.type):nd.content[nl.blockIndex]:void 0,nu=(0,i.useRef)({entryIds:ep,historyCursor:em,hasEarlierMessages:eg});nu.current={entryIds:ep,historyCursor:em,hasEarlierMessages:eg};let np=(0,i.useRef)(null),nm=(0,i.useCallback)(async(e,t,n)=>{np.current=t;let r=await tM(e,tR,t,n);return r||np.current!==t||(np.current=null),r},[tR,tM]);(0,i.useEffect)(()=>{em!==np.current&&(np.current=null)},[em]),(0,i.useLayoutEffect)(()=>{let e=s?.id,t=ts.current,n=nn.current;if(e&&u&&t&&n)return()=>{if(na.current)return;if(i4(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:nu.current.historyCursor})}},[el,u,ts,s?.id]),(0,i.useEffect)(()=>{l&&ei(null)},[l]),(0,i.useEffect)(()=>{let e=s?.id;if(!er||!e||el||l||ns.current)return;ns.current=!0;let t=new AbortController;return(async()=>{let n=nu.current;if(n.entryIds.includes(er.anchorEntryId)){t7(e=>Math.max(e,2*n.entryIds.length)),ea(!0);return}ni.current=!0;let r=n.historyCursor,i=n.hasEarlierMessages;try{for(;i&&r&&!t.signal.aborted;){let n=await nm(e,r,{signal:t.signal});if(t.signal.aborted)return;if(!n){tA("instant"),ei(null);return}if(t7(e=>e+Math.max(50,2*n.messages.length)),n.entryIds.includes(er.anchorEntryId))return void ea(!0);if(n.oldestEntryId===er.oldestEntryId)break;r=n.oldestEntryId,i=n.hasMore}t.signal.aborted||(tA("instant"),ei(null))}finally{ni.current=!1}})(),()=>{t.abort(),ei(null)}},[tR,nm,el,er,tA,l,s?.id]),(0,i.useLayoutEffect)(()=>{let e=nn.current;if(!er||!e||l)return;let t=Array.from(e.children).find(e=>e instanceof HTMLElement&&e.dataset.entryId===er.anchorEntryId);if(t instanceof HTMLElement){tL(t,er.anchorOffset),ei(null);return}es&&(tA("instant"),ei(null))},[ep,er,es,tA,tL,l,t9]),(0,i.useEffect)(()=>{if(!l||el)return;let e=new AbortController;return(async()=>{let t=nu.current,n=t.entryIds.includes(l.entryId);if(!n&&!tU&&t.hasEarlierMessages&&t.historyCursor&&!ni.current){ni.current=!0;let r=ts.current;r&&(nr.current=r.scrollHeight-r.scrollTop);let i=await nm(l.sessionId,t.historyCursor,{tail:200,signal:e.signal});ni.current=!1,n=!!i?.entryIds.includes(l.entryId)}e.signal.aborted||(n?(nr.current=null,t7(e=>Math.max(e,(nu.current.entryIds.length+200)*2)),no(l)):d?.(l))})(),()=>e.abort()},[l,el,tU,nm,d,ts]),(0,i.useLayoutEffect)(()=>{if(!nl||nl!==l)return;let e=`[data-entry-id="${CSS.escape(nl.entryId)}"]`,t=ts.current?.querySelector(nd?.role==="user"?e:`${e} [data-search-target]`);t&&(tL(t),t.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500})),no(null),d?.(nl)},[nl,l,nd,ts,tL,d]),(0,i.useEffect)(()=>{let e=ts.current;if(!ne||!e)return;let t=new IntersectionObserver(t=>{if(!t[0]?.isIntersecting||ni.current)return;if(!eg){nr.current=e.scrollHeight-e.scrollTop,t7(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50;return e+t})(e));return}if(!em||em===np.current)return;let n=s?.id??ti.current;n&&(ni.current=!0,nr.current=e.scrollHeight-e.scrollTop,nm(n,em).finally(()=>{ni.current=!1}))},{root:e,threshold:0});return t.observe(ne),()=>t.disconnect()},[ne,t9,em,eg,s,nm,ti,ts]),(0,i.useEffect)(()=>{t7(e=>Math.max(e,ed.length))},[ed.length]),(0,i.useEffect)(()=>{if(null==nr.current)return;let e=ts.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nr.current),nr.current=null}},[t9,ts]);let ng=eB?[eB.sessionId,eB.sessionFile??"",eB.sessionName??"",eB.userMessages,eB.assistantMessages,eB.toolCalls,eB.toolResults,eB.totalMessages,eB.tokens.input,eB.tokens.output,eB.tokens.cacheRead,eB.tokens.cacheWrite,eB.tokens.total,eB.cost??0,eB.totalActiveMs??0].join("|"):null,nf=(0,i.useRef)(eB);nf.current=eB,(0,i.useEffect)(()=>{A?.(nf.current)},[ng,A]),(0,i.useEffect)(()=>()=>{A?.(null)},[A]);let nb=eL?`${eL.percent??"null"}|${eL.contextWindow}|${eL.tokens??"null"}`:null,nv=(0,i.useRef)(eL);nv.current=eL,(0,i.useEffect)(()=>{z?.(nv.current)},[nb,z]),(0,i.useEffect)(()=>()=>{z?.(null)},[z]);let ny=(0,i.useCallback)(async e=>{let t=s?.cwd??h;if(!t)return void e8({type:"warning",message:J("chat.dropNeedsCwd")});try{let{status:n,data:r}=await (0,nK.Zn)(t,e,"skip");if(200!==n&&207!==n)throw Error(r.error??`HTTP ${n}`);let i=r.uploaded??[],s=r.skipped??[],a=(0,nK.JI)(e,[...i,...s]);for(let e of(a&&I?.current?.insertText(a),i.length>0&&(e8({type:"success",message:J("chat.dropUploaded",{count:i.length})}),W?.()),s.length>0&&e8({type:"warning",message:J("chat.dropAlreadyExists",{names:s.join(", ")})}),r.errors??[]))e8({type:"error",message:J("chat.dropFailed",{message:`${e.name}: ${e.error}`})})}catch(e){e8({type:"error",message:J("chat.dropFailed",{message:e instanceof Error?e.message:String(e)})})}},[e8,I,h,W,s?.cwd,J]),nk=(0,i.useCallback)(e=>{let{images:t,files:n,folders:r}=(0,nK.H7)(e);t.length>0&&I?.current?.addImages(t),r.length>0&&e8({type:"warning",message:J("chat.dropFoldersUnsupported",{names:r.join(", ")})}),n.length>0&&ny(n)},[e8,I,J,ny]),nj=(0,i.useCallback)(e=>{nk(e.map(e=>({kind:"file",file:e})))},[nk]),{isDragOver:nw,handleDragEnter:nS,handleDragOver:nC,handleDragLeave:nI,handleDrop:nE}=(0,sp.J)(nk),n$=eb||tW,nM=(0,i.useMemo)(()=>(0,nN.Io)(ed,{openTail:n$}),[ed,n$]),nR=ed.reduce((e,t,n)=>e+ +!!(0,nN.nR)(t,nM[n]),0),nA=(0,i.useMemo)(()=>{let e=new Map(ec);for(let t of ed)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[ec,ed]),nU=(0,i.useMemo)(()=>new WeakMap,[]),nZ=(0,i.useMemo)(()=>(0,nP.n_)(ed),[ed]),nV=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=ed.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}(ed[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[ed]),nJ=((t=(0,i.useRef)([])).current=Array(nR).fill(null).map((e,n)=>t.current[n]??null),t),nY=(0,i.useCallback)(()=>{t7(e=>Math.max(e,2*ed.length))},[ed.length]),nX=tt&&0===ed.length&&!tW&&!tU;e1(ts,!!s?.id||!nX);let n2=s?.cwd??h??void 0,n4=function(e,t,n){let[r,s]=(0,i.useState)(()=>new Map);return(0,i.useEffect)(()=>{let r=nO(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=nF.get(e);if(r)return r;let i=nD.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 nW(e,5),a=new Map;for(let e of i)"toolResult"===e.role&&a.set(e.toolCallId,e);return{files:(r=t??s??n,nL(i.flatMap(e=>"assistant"===e.role?e.content??[]:[]),a,r))}}catch{return nD.set(e,Date.now()),null}})();return nF.set(e,s),s.catch(()=>nD.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}(ed,nA,n2),n3=(0,i.useRef)(null),n5=(0,i.useRef)(0),n9=(0,i.useRef)(null),n7=(0,i.useRef)(!1),re=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=n3.current;if(!eb||!tl){re.current=null,n5.current=0,n7.current=!1,e&&(e.style.height="");return}let t=ts.current,n=nn.current,r=ta.current;if(!t||!n||!r||!e)return;let i=!1,s=()=>{var s;let a;if(i||ts.current!==t||nn.current!==n||ta.current!==r||n3.current!==e)return;let l=t.getBoundingClientRect().top,o=Math.max(0,r.getBoundingClientRect().top-l+t.scrollTop-16),d=e.getBoundingClientRect().top-l+t.scrollTop,c=(s=t.clientHeight,0===(a=Math.max(0,o))?0:Math.max(0,Math.ceil(a+s-Math.max(0,d)))),u=!n7.current;u&&(n7.current=!0),c!==n5.current&&(n5.current=c,e.style.height=c>0?`${c}px`:"",u&&c>0&&tT())};re.current=s,s();let a="u"<typeof ResizeObserver?null:new ResizeObserver(()=>{i||null!==n9.current||(n9.current=requestAnimationFrame(()=>{n9.current=null,s()}))});return a?.observe(t),a?.observe(n),a?.observe(r),()=>{i=!0,re.current===s&&(re.current=null),a?.disconnect(),null!==n9.current&&(cancelAnimationFrame(n9.current),n9.current=null)}},[eb,ta,ed.length,tl,ts,tT]);let rt=(0,i.useCallback)(()=>{re.current?.()},[]);(0,i.useLayoutEffect)(rt,[tW,tH,rt]);let rr=eF?eE[`${eF.provider}:${eF.modelId}`]??null:null,ri=eF?eT[`${eF.provider}:${eF.modelId}`]??null:null,rs=(0,r.jsx)(r0,{ref:I,onSend:to,onAbort:td,onSideChat:!C||o(s?.relation)||tP?void 0:t3,onSteer:eb?tx:void 0,onFollowUp:eb?tb:void 0,onPromptWithStreamingBehavior:eb?tv:void 0,isStreaming:tU,model:eF,isAutoModelSelection:e6,modelNames:ek,modelList:ej,modelError:ew,missingCwd:eS,modelScopeWarnings:eC,allModelList:eI,onLoadAllModels:eN?t$:void 0,onModelChange:tg,modelSwitching:eD,defaultModel:e9,onSetDefaultModel:tN,onCompact:s||tt?tf:void 0,onAbortCompaction:ty,isCompacting:ez,compactError:eO,onDismissCompactError:tk,compactResult:eW,toolPreset:eM,newSessionEphemeral:tt?tz:void 0,onNewSessionEphemeralChange:tt?tO:void 0,onToolPresetChange:s&&!o(s.relation)||tt?tS:void 0,thinkingLevel:eR,isAutoThinkingSelection:e3,onThinkingLevelChange:s||tt?tC:void 0,availableThinkingLevels:rr,thinkingLevelMap:ri,savedDefaultThinkingLevel:e7,onSetDefaultThinkingLevel:s||tt?tI:void 0,retryInfo:eA,queuedMessages:eU,inputHistory:nV,onRecallQueue:tj,slashCommands:eH,slashCommandsLoading:e_,onLoadSlashCommands:tE,extensionUiOpen:!!(eq||eV),onBuiltinCommand:tw,soundEnabled:U,onSoundToggle:K,onAudioUnlock:Z,draftKey:s?.id??m??void 0,cwd:s?.cwd??h,onAttachFiles:nj});return el?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:J("chat.loadingSession")}):eo?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:eo}):(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:nS,onDragOver:nC,onDragLeave:nI,onDrop:nE,children:[nw&&(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*!G,zIndex:40,display:"flex",justifyContent:"flex-end",padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)(sw,{notices:eK,floating:!0,onPauseChange:e4})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[eq&&(0,r.jsx)(sN,{request:eq,waitingCount:eZ,onRespond:e0},eq.id),eV&&(0,r.jsx)(sI,{request:eV,waitingCount:eJ,onInput:e2},eV.id),!nX&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:ts,className:"scrollbar-subtle min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-gutter:stable]",style:{visibility:er?"hidden":void 0},children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{ref:nn,onPointerUp:t4,style:{width:"100%",minWidth:0,maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(()=>{var e;let t,n,a=-1;for(let e=ed.length-1;e>=0;e--)if("user"===ed[e].role){a=e;break}let l=-1;for(let e=ed.length-1;e>=0;e--)if(nM[e]){l=e;break}let o=new Map,d=0;ed.forEach((e,t)=>{(0,nN.nR)(e,nM[t])&&o.set(t,d++)});let c=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.messageOverride??ed[e];if("custom"===n.role&&"pi-web:side-boundary"===n.customType)return(0,r.jsx)(sk,{},"side-chat-divider");if((0,nN.zZ)(n))return null;let l=!1===t.withNotices?[]:(0,i1.YQ)(ed[e]),d=(0,nN.nR)(n,nM[e]),c=o.get(e),u=t.keyPrefix??"message",p=eh[e],h=!1;if("assistant"===n.role){h=!0;for(let t=e+1;t<ed.length&&!nM[t];t++)if("assistant"===ed[t].role){h=!1;break}h&&tW&&e===ed.length-1&&(h=!1)}void 0!==t.showTimestamp&&(h=t.showTimestamp);let m=(0,r.jsx)(nq.Dx,{message:n,toolResults:nA,toolClocks:eu,modelNames:ek,cwd:n2,onOpenFile:O,onOpenSubagent:F,onEnterSubagent:D,entryId:ep[e],searchBlock:ep[e]===nl?.entryId?nc:void 0,onFork:ev||tt||tP?void 0:tK,forking:eP===ep[e],onEditContent:tU?void 0:th,onCancelEdit:tm,isEditing:tn===ep[e],showTimestamp:h,prevTimestamp:e>0?ed[e-1].timestamp:void 0,sessionId:s?.id??ti.current??void 0,writtenFiles:t.writtenFiles,turnDurationMs:t.turnDurationMs,onCompact:t.recoverTruncation?tf:void 0,isCompacting:t.recoverTruncation?ez:void 0,compactError:t.recoverTruncation?eO:void 0},`${u}-view-${p}`),g=l.length>0?(0,r.jsx)(sh.yt,{notices:l},`${u}-notices-${p}`):null;return d&&void 0!==c?(0,r.jsxs)("div",{"data-entry-id":ep[e],ref:!1===t.attachRef?void 0:t=>{nJ.current[c]=t,e===a&&(ta.current=t)},children:[m,g]},`${u}-${p}`):(0,r.jsxs)(i.Fragment,{children:[m,g]},`${u}-${p}`)},u=[];for(let e=0;e<ed.length;){let t,n=nM[e];if(!n&&0!==e){u.push(c(e)),e+=1;continue}let i=n?e:-1,s=n?e:0,a=e+1;for(;a<ed.length&&!nM[a];)a+=1;let d=function(e,t,n){for(let i=n-1;i>t;i--){var r;if("assistant"===(r=e[i]).role&&(0,nN.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}(ed,i,a);if(-1===d||(tU||tW)&&a===ed.length&&i===l){for(let e=s;e<a;e++)u.push(c(e));e=a;continue}n&&u.push(c(i));let p=n&&ep[i]?(0,nH.G)(ed,i,a):void 0,h=function(e,t){let n=e.get(t);if(n)return n;let{answerBlocks:r}=(0,nN.dQ)(t),i=r.length>0||(0,nN.mc)(t)||(0,nN.PC)(t)||(0,nN.oG)(t)?nB(t,r):null,s=t.content.indexOf(r[0]),a={answer:i,process:nB(t,t.content.slice(0,s<0?void 0:s),{omitUsage:!!i,omitStop:!!i})};return e.set(t,a),a}(nU,ed[d]),m=h.answer,g=[],f=0,x=0,b=!1;for(let e=i+1;e<=d;e++){let n=ed[e];if("custom"===n.role){if((0,nN.zZ)(n))continue;b||=!!(nl&&nl.entryId===ep[e]),f+=1,g.push(c(e,{attachRef:!1,keyPrefix:"process"}));continue}if("assistant"!==n.role)continue;let i=e===d?h.process:n,s=e!==d||!m,a=(0,nN.TC)(i);if(0===a.length){let t=s?(0,i1.YQ)(n):[];t.length>0&&g.push((0,r.jsx)(sh.yt,{notices:t},`process-notices-${eh[e]}`));continue}t??=o.get(e),x+=(0,nN._q)(a),f+=1,b||=!!(nl&&ep[e]===nl.entryId&&(!nc||a.includes(nc))),g.push(c(e,{attachRef:!1,keyPrefix:"process",messageOverride:i,showTimestamp:!1,withNotices:s}))}if(0===f)u.push(...g);else if(g.length>0){let e=(0,nN.sE)(m),n=(0,i1.Uv)(ed.slice(i+1,m?d:d+1));u.push((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{nJ.current[t]=e},children:(0,r.jsx)(sv,{messageCount:f,toolCallCount:x,durationMs:p,cacheMisses:n,defaultExpanded:!e,reveal:b,t:J,children:g},e?"answered":"unanswered")},`process-group-${eh[s]}`))}if(m){let e=[];for(let t=i+1;t<=d;t++){let n=ed[t];if(n?.role==="assistant")for(let t of n.content??[])e.push(t)}let t=nL(e,nA,n2);for(let e of nO(ed.slice(i+1,d+1),nA))for(let n of n4.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)}(h,t);u.push(c(d,{messageOverride:m,writtenFiles:n,turnDurationMs:0===g.length?p:void 0,recoverTruncation:a===ed.length&&!tW&&!(0,nN.D6)(m)}))}for(let e=d+1;e<a;e++)u.push(c(e));e=a}let{startIndex:p}=(t=Math.min(Math.max(t9,0),Math.max(e=u.length,0)),{startIndex:n=Math.max(0,e-t),hasMore:n>0}),h=p>0||eg;return(0,r.jsxs)(r.Fragment,{children:[h&&(0,r.jsx)("div",{ref:nt,className:"py-3 text-center text-xs text-text-muted",children:J("chat.loadEarlier")}),u.slice(p)]})})(),tW&&tH&&(0,r.jsx)(sj,{store:ex,onCommit:rt,toolResults:nA,modelNames:ek,cwd:n2,onOpenFile:O,onOpenSubagent:F,onEnterSubagent:D}),(eb||ez)&&!tH&&(te||ez)&&(0,r.jsx)("div",{className:"break-words py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(n)return r>0?t("chat.compactingQueued",{count:r}):t("chat.compacting");if(e?.kind==="running_tools"){let n=e.tools[e.tools.length-1];if(n?.progress)return`${t("chat.runningNamedTool",{name:n.name})} ${n.progress}`;let r=e.tools.map(e=>e.name);return 0===r.length?t("chat.runningTool"):1===r.length?t("chat.runningNamedTool",{name:r[0]}):r.length<=3?t("chat.runningTools",{names:r.join(", ")}):t("chat.runningToolsMore",{names:r.slice(0,2).join(", "),count:r.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(te,J,ez,(eU?.steering.length??0)+(eU?.followUp.length??0))})}),ev&&!ey&&(0,r.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:J("chat.runningCommand")})}),ey&&(0,r.jsx)(nq.Dx,{message:{role:"bashExecution",command:ey.command,output:"",...ey.result,excludeFromContext:ey.excludeFromContext,timestamp:ey.startedAt},sessionId:s?.id??ti.current??void 0,onOpenSubagent:F,onEnterSubagent:D}),ey?.liveOutput&&!ey.result&&(0,r.jsx)("div",{"aria-live":"off",className:"rounded-md border border-border px-2.5 py-1.5 font-mono text-[12px] leading-[1.45] text-text-muted",style:{marginTop:-2,background:"var(--tool-bg)"},children:(0,r.jsx)("pre",{className:"m-0 flex flex-col justify-end overflow-hidden whitespace-pre-wrap break-words",style:{maxHeight:`${1.45*nN.OP}em`},children:(0,r.jsx)("span",{children:(0,nN.Kj)(ey.liveOutput)})})}),(0,r.jsx)("div",{ref:n3,"aria-hidden":"true"})]})})}),G||er?null:(0,r.jsx)(iu,{messages:ed,getStreamingMessage:t_,scrollContainer:ts,messageRefs:nJ,onRevealHistory:nY,turnsBefore:ef,turnAnchors:nM})]})]}),B&&tq&&(0,e5.createPortal)((0,r.jsx)("div",{ref:t0,role:tV?"dialog":"toolbar","aria-label":J(tV?"chat.newQuoteChat":"chat.selectionActions"),style:{position:"fixed",top:tq.top,left:tq.left,zIndex:260,display:"flex",flexWrap:"wrap",gap:3,width:tV?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:tV?12:3,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",boxShadow:"0 2px 10px rgba(0,0,0,0.12)"},children:tV?(0,r.jsxs)("fieldset",{disabled:tG,"aria-busy":tG,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:J("chat.askInSideChat")}),(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button",title:J("i18n.close"),"aria-label":J("i18n.close"),disabled:tG,onClick:t2,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)(r0,{ref:t1,compact:!0,onSend:t6,onAbort:t2,isStreaming:!1}),tX&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:tX})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:J("chat.quoteSelection"),"aria-label":J("chat.quoteSelection"),onPointerDown:e=>e.preventDefault(),onClick:t8,style:{width:"auto",height:35,flex:"0 0 auto",gap:5,padding:"0 10px",border:"none",fontSize:12,fontWeight:500},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}),(0,r.jsx)("path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"})]}),(0,r.jsx)("span",{children:J("chat.quoteSelection")})]}),C&&!o(s?.relation)&&(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:J("chat.askInSideChat"),"aria-label":J("chat.askInSideChat"),onPointerDown:e=>e.preventDefault(),onClick:()=>{tJ(!0),window.getSelection()?.removeAllRanges()},style:{width:"auto",height:35,flex:"0 0 auto",gap:5,padding:"0 10px",border:"none",fontSize:12,fontWeight:500},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"})}),(0,r.jsx)("span",{children:J("chat.askInSideChat")})]})]})}),document.body),(0,r.jsxs)("div",{className:"relative flex min-h-0 flex-col",children:[!nX&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"100%",left:0,right:36*!G,display:"flex",justifyContent:"center",paddingBottom:10,pointerEvents:"none",zIndex:20},children:(0,r.jsx)("button",{type:"button",className:`chat-scroll-to-bottom${tr&&!er?" is-visible":""}`,title:J("chat.scrollToLatest"),"aria-label":J("chat.scrollToLatest"),onClick:()=>tA("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:G?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)(nh.A,{src:"/icons/apple-touch-icon.png",width:40,height:40,alt:"",priority:!0,className:"new-session-logo"}),(0,r.jsxs)("div",{className:"new-session-brand-text",children:[(0,r.jsx)("span",{className:"new-session-brand-name",children:"Pi Web"}),(0,r.jsxs)("span",{className:"new-session-meta",children:[(0,r.jsxs)("span",{children:["web v","0.17.3"]}),(0,r.jsx)(sb,{label:e=>J("appUpdate.releaseNotes",{version:e})}),(0,r.jsx)("span",{"aria-hidden":"true",children:"\xb7"}),(0,r.jsxs)("span",{className:"new-session-meta-pi",children:["pi v","1.5.2"]})]})]})]}),g]})}),tP&&s&&(0,r.jsxs)("div",{className:"ephemeral-banner",title:J("ephemeral.bannerHint"),style:{display:"flex",alignItems:"center",gap:8,padding:"4px 12px",borderTop:"1px solid var(--border)",color:"var(--text-muted)",fontSize:12},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",style:{flex:"0 0 auto"},children:[(0,r.jsx)("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"}),(0,r.jsx)("path",{d:"M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,r.jsx)("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),(0,r.jsx)("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]}),(0,r.jsx)("span",{style:{flex:1,minWidth:0},children:J("ephemeral.banner")}),(0,r.jsx)("button",{type:"button",disabled:tF,onClick:()=>{tB()},style:{border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text)",padding:"2px 10px",fontSize:12,cursor:tF?void 0:"pointer"},children:J("ephemeral.end")})]}),(0,r.jsx)(r1.Z,{snapshot:nZ}),rs,(0,r.jsx)(ix,{statuses:eG,widgets:eY,onCommand:to,commandsDisabled:tU})]}),nX&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}function sk(){let{t:e}=(0,eX.s)();return(0,r.jsxs)("div",{role:"separator",className:"my-4 flex items-center gap-3 text-xs",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("span",{className:"h-px flex-1",style:{background:"var(--border)"}}),(0,r.jsx)("span",{children:e("sideChat.divider")}),(0,r.jsx)("span",{className:"h-px flex-1",style:{background:"var(--border)"}})]})}let sj=(0,i.memo)(function(e){let{store:t,onCommit:n,toolResults:s,modelNames:a,cwd:l,onOpenFile:o,onOpenSubagent:d,onEnterSubagent:c}=e,u=so(t,su);return((0,i.useLayoutEffect)(n,[u,n]),u)?(0,r.jsx)(nq.Dx,{message:u,toolResults:s,isStreaming:!0,modelNames:a,cwd:l,onOpenFile:o,onOpenSubagent:d,onEnterSubagent:c}):null});function sw(e){let{notices:t,floating:n=!1,onPauseChange:s}=e;return 0===t.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",marginBottom:10*!n},children:t.map((e,a)=>{var l;let o,d,c,u="error"===e.type?"#ef4444":"warning"===e.type?"#d97706":"success"===e.type?"#10b981":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",onMouseEnter:()=>s?.(e.id),onMouseLeave:e=>{e.currentTarget.contains(document.activeElement)||s?.(null)},onFocus:()=>s?.(e.id),onBlur:e=>{e.currentTarget.matches(":hover")||s?.(null)},style:{display:"flex",alignItems:"flex-start",gap:10,minHeight:60,height:"auto",maxHeight:500,pointerEvents:"auto",marginBottom:6*(a!==t.length-1),overflow:"hidden",borderRadius:14,border:"1px solid color-mix(in srgb, var(--border) 70%, transparent)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:n?"0 1px 2px rgba(15,23,42,0.05), 0 10px 28px -14px rgba(15,23,42,0.24)":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",fontSize:14,lineHeight:1.5,transformOrigin:"top right",animation:e.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out backwards",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:u,flexShrink:0,marginTop:25.5}}),(0,r.jsx)("span",{tabIndex:0,style:{padding:"18.5px 0",minWidth:0,maxWidth:"100%",maxHeight:498,overflowY:"auto",scrollbarWidth:"thin",whiteSpace:"pre-line",wordBreak:"break-word"},children:(l=e.message,o=[],d=(e,t)=>{if(!t)return;let n=o[o.length-1];n?.kind===e?n.text+=t:o.push({kind:e,text:t})},c=!1,l.split("\n").forEach((e,t)=>{let n=nk.test(e);t>0&&d(n&&c?"art":"text","\n"),d(n?"art":"text",e),c=n}),o).map((e,t)=>"art"===e.kind?(0,r.jsx)("span",{style:{display:"inline-block",verticalAlign:"top",maxWidth:"100%",overflowX:"auto",whiteSpace:"pre",fontFamily:"Menlo, Consolas, 'DejaVu Sans Mono', monospace",lineHeight:1,color:"var(--text)"},children:e.text},t):(0,r.jsx)(i.Fragment,{children:(function(e){let t=[],n=0;for(let r of e.matchAll(nj)){let i=function(e){let t=0,n=0;for(let r of e)"("===r?t+=1:")"===r&&(n+=1);let r=e.length;for(;r>0;){let i=e[r-1];if(nw.test(i))r-=1;else if(")"===i&&n>t)r-=1,n-=1;else break}return e.slice(0,r)}(r[0]);if(!/^https?:\/\/[^/]/i.test(i))continue;let s=r.index??0;s>n&&t.push({kind:"text",text:e.slice(n,s)}),t.push({kind:"link",text:i}),n=s+i.length}return n<e.length&&t.push({kind:"text",text:e.slice(n)}),t})(e.text).map((e,n)=>"link"===e.kind?(0,r.jsx)("a",{href:e.text,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",textDecoration:"underline",textUnderlineOffset:2,wordBreak:"break-all"},children:e.text},`${t}-${n}`):e.text)},t))})]},e.id)})})}function sS(e){let{count:t}=e,{t:n}=(0,eX.s)();return t<=0?null:(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",whiteSpace:"nowrap",flexShrink:0},children:n("chat.extensionMoreWaiting",{count:t})})}function sC(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 sN(e){let{request:t,waitingCount:n,onRespond:s}=e,{t:a}=(0,eX.s)(),[l,o]=(0,i.useState)("editor"===t.method?t.prefill??"":""),[d,c]=(0,i.useState)(!1),u=(0,i.useRef)(null),p=(0,i.useRef)(null),[h,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(!1),x=(0,i.useCallback)(()=>f(e=>!e),[]),[b,v]=(0,i.useState)(()=>Date.now()),y=(0,i.useCallback)(e=>e?.focus(),[]),k=function(e){if("select"===e.method&&e.options.length>0)return nx(e.options[0]);if("confirm"===e.method){let t=nx(e.message).split("\n").find(e=>e.trim());return t?.trim()}}(t),j=void 0===t.expiresAt?null:Math.max(0,Math.ceil((t.expiresAt-b)/1e3));(0,i.useLayoutEffect)(()=>{if(d)return;let e=u.current,t=p.current;if(!e||!t)return;let n=!1,r=()=>{if(n)return;let r=t.querySelectorAll("pre, .markdown-table-wrap");if(0===r.length)return;t.classList.add("extension-dialog-measuring");let i=Array.from(r,e=>e.scrollWidth-e.clientWidth);t.classList.remove("extension-dialog-measuring");let s=function(e,t){let n=0;for(let e of t)e>1&&e>n&&(n=e);return 0===n?null:40*Math.ceil((e+n)/40)}(e.offsetWidth,i);null!==s&&m(e=>null!==e&&e>=s?e:s)};r();let i=new MutationObserver(r);return i.observe(t,{childList:!0,subtree:!0,characterData:!0}),document.fonts?.ready.then(r),()=>{n=!0,i.disconnect()}},[d]),(0,i.useEffect)(()=>{if(void 0===t.expiresAt)return;let e=setInterval(()=>v(Date.now()),1e3);return()=>clearInterval(e)},[t.expiresAt]);let w=null!==j&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:a("chat.extensionExpiresIn",{seconds:j})}),S=()=>{"confirm"===t.method?s(t,{confirmed:!0}):s(t,{value:l})};return(0,r.jsx)("div",{onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode||(e.preventDefault(),e.stopPropagation(),s(t,{cancelled:!0}))},style:{position:"absolute",inset:0,zIndex:90,display:"flex",alignItems:d?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:d?(0,r.jsxs)("button",{type:"button",onClick:()=>c(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(560px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:a("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:nx(t.title)}),k&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:k}),(0,r.jsx)(sS,{count:n}),w,(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:a("chat.extensionExpand")})]}):(0,r.jsxs)("div",{ref:u,role:"dialog","aria-label":nx(t.title),style:{pointerEvents:"auto",width:g?"100%":`min(${h??560}px, 100%)`,maxHeight:g?"100%":"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{flexShrink:1,minHeight:0,display:"flex",alignItems:"flex-start",gap:8,padding:"12px 14px",borderBottom:"1px solid var(--border)",maxHeight:"50vh",overflowY:"auto"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:650,lineHeight:1.45,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:nx(t.title)}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:8,marginTop:3,color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{children:a("chat.extensionRequest")}),(0,r.jsx)(sS,{count:n}),w]})]}),(0,r.jsx)("button",{type:"button",onClick:x,title:a(g?"chat.extensionRestoreSize":"chat.extensionMaximize"),"aria-label":a(g?"chat.extensionRestoreSize":"chat.extensionMaximize"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)(sC,{expanded:g})}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:a("chat.extensionCollapse"),"aria-label":a("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})})]}),(0,r.jsxs)("div",{ref:p,style:{padding:14,flex:"1 1 auto",minHeight:0,overflowY:"auto"},children:["confirm"===t.method&&(0,r.jsx)(nZ.m,{children:nx(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":nx(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)(nZ.m,{children:nx(e)})})},e))}),"input"===t.method&&(0,r.jsx)("input",{autoFocus:!0,value:l,placeholder:t.placeholder,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode||S()},style:{width:"100%",padding:"9px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",fontSize:13}}),"editor"===t.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:l,onChange:e=>o(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&!e.nativeEvent.isComposing&&229!==e.nativeEvent.keyCode&&S()},style:{width:"100%",minHeight:220,padding:10,borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:13,lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 14px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("button",{autoFocus:"confirm"===t.method||"select"===t.method&&0===t.options.length,onClick:()=>s(t,{cancelled:!0}),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"},children:a("chat.cancel")}),"confirm"===t.method?(0,r.jsx)("button",{onClick:S,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:a("chat.confirm")}):"select"!==t.method?(0,r.jsx)("button",{onClick:S,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:a("chat.submit")}):null]})]})})}function sI(e){let{request:t,waitingCount:n,onInput:s}=e,{t:a}=(0,eX.s)(),l=(0,i.useRef)(null),o=(0,i.useRef)(!1),[d,c]=(0,i.useState)(!1),u=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(nf,""),i=nx(e).trimEnd();if(t.test(i))continue;let s=e,a=ny(s);("│"===a||"┃"===a)&&" "===ny(s=nv(s,0))&&(s=nv(s,0));let l=function(e){let t=nb(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(s),o=l>=0?nb(s)[l]?.char:void 0;("│"===o||"┃"===o)&&(s=nv(s,l)),n.push(function(e){let t=e;for(;;){let e=nb(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&&""===nx(n[0]).trim();)n.shift();for(;n.length>0&&""===nx(n[n.length-1]).trim();)n.pop();return n.length?n:e.map(e=>e.replace(nf,""))}(t.lines),p=u.map(nx).find(e=>e.trim())?.trim();return(0,i.useEffect)(()=>{d||l.current?.focus()},[d]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:d?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:d?(0,r.jsxs)("button",{type:"button",onClick:()=>c(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(920px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:a("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:a("chat.extensionPanel")}),p&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:p}),(0,r.jsx)(sS,{count:n}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:a("chat.extensionExpand")})]}):(0,r.jsxs)("div",{role:"dialog",onClick:e=>{e.target.closest("button")||l.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:l,"aria-label":a("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:e=>{if(o.current||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode)return;let n=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;if(" "===e)return"\0";if("/"===e||"-"===e)return"\x1f";let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}let t=nS[e.key],n=1+ +!!e.shiftKey+2*!!e.altKey+4*!!e.ctrlKey;if(n>1&&!(e.altKey&&!e.ctrlKey&&!e.shiftKey&&nC[e.key])){if(/^\x1b\[[ABCDHF]$/.test(t??""))return`\x1b[1;${n}${t.at(-1)}`;if(/^\x1b\[\d+~$/.test(t??""))return`${t.slice(0,-1)};${n}~`}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=nC[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":" ":nS[e.key]??null}(e);n&&(e.preventDefault(),e.stopPropagation(),s(t,n))},onInput:e=>{if(o.current||e.nativeEvent.isComposing)return;let n=e.currentTarget.value;e.currentTarget.value="",n&&s(t,n)},onCompositionStart:()=>{o.current=!0},onCompositionEnd:e=>{o.current=!1;let n=e.currentTarget;queueMicrotask(()=>{let e=n.value;n.value="",e&&s(t,e)})},onPaste:e=>{e.preventDefault();let n=e.clipboardData.getData("text");n&&s(t,`\x1b[200~${n}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:a("chat.extensionPanel")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)(sS,{count:n}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:a("chat.extensionCollapse"),"aria-label":a("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),(0,r.jsx)("button",{onClick:()=>s(t,"\x03"),style:{padding:"5px 9px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:a("chat.close")})]})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,minHeight:0,overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(0,r.jsx)(ih,{text:u.join("\n")})})]})})}let sE=null,s$="";function sT(e){let{context:t,mobile:n,initialFocus:s,onInitialFocusDone:a,onPick:l,onUseDefaultDirectory:o,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u}=e,{t:p}=(0,eX.s)(),[h,m]=(0,i.useState)(()=>s$),g=(0,i.useRef)(null),f=(0,i.useRef)(s),x=(0,i.useRef)(a);return x.current=a,(0,i.useEffect)(()=>{if(s$)return;let e=!1;return(sE??=fetch("/api/home").then(e=>e.json()).then(e=>s$=e.home??"").catch(()=>(sE=null,""))).then(t=>{!e&&t&&m(t)}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=f.current;if(!e)return;f.current=null,x.current();let t=g.current;eE(document,("worktree"===e?t?.button("worktree"):null)??t?.button("project")??null)},[]),(0,r.jsx)("div",{className:"new-session-context",children:(0,r.jsx)(tY,{handleRef:g,layout:"inline",context:t,mobile:n,label:p("workspace.newSessionContext"),homeDir:h,newWorktreeTitle:p("sidebar.newWorktreeForSession"),onPick:l,onUseDefaultDirectory:o,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u})})}var sM=n(33520),sR=n(90137),sA=n(88545),sL=n(96793),sP=n(68929);let sz=["general","models","skills","agents","plugins","mcp","channels","automations","shares"],sO="pi-web:settings-navigation",sW=new Set(["skills","agents","plugins"]);function sF(e){return sW.has(e)}function sD(){try{return window.localStorage}catch{return null}}function sB(e){let t=e.getItem(sO);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 sH(e,t){return"models"===e?e:t?JSON.stringify([e,t]):"mcp"===e||"channels"===e||"automations"===e||"shares"===e?e:null}function s_(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sD();if(t)try{let n=sB(t);n.section=e,t.setItem(sO,JSON.stringify(n))}catch{}}function sU(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:sD();if(!n)return null;let r=sH(e,t);if(!r)return null;try{let e=sB(n).selections?.[r];return"string"==typeof e&&e.length>0?e:null}catch{return null}}function sK(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:sD();if(!r||!t)return;let i=sH(e,n);if(i)try{let e=sB(r);e.selections={...e.selections,[i]:t},r.setItem(sO,JSON.stringify(e))}catch{}}var sq=n(61958);let sZ="llama.cpp";function sV(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}class sJ extends Error{constructor(e){super(`Context window of ${e} must be a positive number of tokens`),this.name="ContextWindowError",this.model=e}}function sG(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 sY={empty:e=>`Provider ${e} needs a Base URL or at least one model`,baseUrl:e=>`Provider ${e} needs a Base URL`};class sX extends Error{constructor(e,t){super(sY[t](e)),this.name="ProviderEntryError",this.provider=e,this.problem=t}}function sQ(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function s0(e){return!sQ(e)||"string"!=typeof e.id||e.id.trim().length>0}function s1(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function s2(e){let t=s1(e.inputLimits)?e.inputLimits.images:void 0,n=s1(t)?t.resize:void 0;return s1(n)?n.maxBytes:void 0}function s4(e){let t="string"==typeof e?/^\d+$/.test(e.trim())?Number(e.trim()):0:e;return"number"==typeof t&&Number.isSafeInteger(t)&&t>=1?t:void 0}function s8(e){let t=["B","KiB","MiB","GiB"],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;let i=0===r?String(n):String(Math.round(10*n)/10);return`${i} ${t[r]}`}class s6 extends Error{constructor(e){super(`Image size limit of ${e} must be a positive whole number of bytes`),this.name="ImageMaxBytesError",this.model=e}}let s3=["input","output","cacheRead","cacheWrite"];function s5(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 s9(e){if(!s7(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 s7(e){return s3.some(t=>""!==e[t].trim())}function ae(e,t,n){return{...e,compat:{...e.compat??{},[t]:n}}}function at(e){return new Map(Object.entries(e.providers??{}).map(e=>{let[t,n]=e;return[t,(n.models??[]).map(e=>e.id)]}))}function an(e,t,n){if(n<=0)return;let r=e.get(t)??[];e.set(t,[...r,...Array.from({length:n},()=>null)])}function ar(e,t,n,r){let i=e.providers??{},s=i[n],a=s?.models;if(!a||r.every((e,t)=>e===t))return null;let l=t.get(n);return l&&t.set(n,r.map(e=>l[e]??null)),{config:{...e,providers:{...i,[n]:{...s,models:r.map(e=>a[e])}}},providerName:n,order:r}}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 aa(e){return e.name?.trim()||e.id}function al(e){let t=new Map;for(let[n,r]of Object.entries(e.providers??{}))"string"==typeof r.name&&t.set(n,r.name);return t}function ao(e){let{embedded:t,title:n,subtitle:i,closeLabel:s="Close",onClose:a,children:l,width:o=900,height:d="78vh"}=e,c=t?void 0:{"--config-panel-width":`${o}px`,"--config-panel-height":d};return(0,r.jsx)("div",{role:t?void 0:"dialog","aria-modal":t?void 0:"true","aria-label":n,className:`config-panel-root ${t?"is-embedded":"is-modal"}`,onClick:e=>{t||e.target!==e.currentTarget||a()},children:(0,r.jsxs)("div",{className:"config-panel-surface",style:c,children:[!t&&(0,r.jsxs)("div",{className:"config-panel-header",children:[(0,r.jsx)("strong",{className:"config-panel-title",children:n}),i&&(0,r.jsx)("code",{className:"config-panel-subtitle",title:i,children:i}),(0,r.jsx)("button",{type:"button",className:"config-close-button",onClick:a,title:s,"aria-label":s,children:"\xd7"})]}),l]})})}let ad=(0,i.createContext)(null);function ac(){return(0,i.useContext)(ad)??au}let au={detailOpen:!1,openDetail:()=>{},closeDetail:()=>{},reportDetailTitle:()=>{}};function ap(e,t){let{detailOpen:n,reportDetailTitle:r}=ac(),s=(0,i.useRef)(null);return(0,i.useLayoutEffect)(()=>{let t=s.current;if(!e||!n||!t||t.closest("[hidden]"))return;let i=(t.querySelector(".config-sidebar-text")??t).textContent?.trim();i&&r(i)}),e=>{s.current=e,"function"==typeof t?t(e):t&&(t.current=e)}}function ah(e){let{children:t}=e,n=(0,i.useContext)(ad);return(0,r.jsx)("div",{className:"config-split-view","data-pane":n?n.detailOpen?"detail":"list":void 0,children:t})}function am(e){let{children:t}=e;return(0,r.jsx)("aside",{className:"config-sidebar",children:t})}function ag(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-sidebar-list",children:t})}function af(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 ax(e){let{enabled:t,total:n,checked:i,label:s,disabled:a=!1,loading:l=!1,describedBy:o,onChange:d}=e;return(0,r.jsxs)("span",{className:"config-sidebar-group-switch",children:[(0,r.jsxs)("span",{className:"config-sidebar-group-count",children:[t,"/",n]}),(0,r.jsx)(aH,{checked:i??(n>0&&t===n),disabled:a,loading:l,label:s,describedBy:o,onChange:d})]})}function ab(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 av(e){let{active:t=!1,className:n,children:i,onClick:s,ref:a,...l}=e,{openDetail:o}=ac(),d=ap(t,a);return(0,r.jsx)("button",{type:"button",...l,ref:d,onClick:e=>{s?.(e),e.defaultPrevented||o()},"aria-current":t?"page":void 0,className:["config-sidebar-item",n].filter(Boolean).join(" "),children:i})}function ay(e){let{className:t,...n}=e;return(0,r.jsx)("span",{...n,className:["config-sidebar-text",t].filter(Boolean).join(" ")})}function ak(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-stack",t].filter(Boolean).join(" ")})}function aj(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header",t].filter(Boolean).join(" ")})}function aw(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header-info",t].filter(Boolean).join(" ")})}function aS(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-actions",t].filter(Boolean).join(" ")})}function aC(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-title",children:t})}function aN(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-section-title",children:t})}function aI(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 aE(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-grid",children:t})}function a$(e){let{label:t,tone:n="muted",mono:i=!1,className:s,style:a,children:l}=e;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-detail-grid-label",children:t}),(0,r.jsx)("div",{className:["config-detail-grid-value","plain"===n?null:`is-${n}`,i?"is-mono":null,s].filter(Boolean).join(" "),style:a,children:l})]})}function aT(e){let{scope:t,children:n}=e;return(0,r.jsx)("span",{className:`config-scope-tag${"project"===t?" is-project":""}`,children:n})}function aM(e){let{value:t,options:n,label:s,disabledReason:a,size:l="default",onChange:o,children:d}=e,c=(0,i.useId)(),u=a&&n.some(e=>e.disabled)?a:null;return(0,r.jsxs)("div",{className:"config-scope-switch-field",children:[(0,r.jsxs)("div",{className:"config-scope-switch-row",children:[(0,r.jsx)("div",{role:"group","aria-label":s,className:`config-scope-switch${"small"===l?" is-small":""}`,children:n.map(e=>(0,r.jsx)("button",{type:"button","aria-pressed":e.value===t,"aria-describedby":e.disabled&&u?c:void 0,disabled:e.disabled,className:"config-scope-switch-option",onClick:()=>{e.disabled||o(e.value)},children:e.label},e.value))}),d]}),u&&(0,r.jsx)("span",{id:c,className:"config-scope-switch-reason",children:u})]})}function aR(e){let{value:t,options:n,label:s,path:a,disabledReason:l,onChange:o,children:d}=e;return(0,r.jsxs)("div",{className:"config-save-target",children:[(0,r.jsx)(aM,{value:t,options:n,label:s,disabledReason:l,size:"small",onChange:o,children:(0,r.jsx)("span",{className:"config-save-target-path",children:"string"==typeof a?a.split(/([\\/])/).map((e,t)=>"/"===e||"\\"===e?(0,r.jsxs)(i.Fragment,{children:[e,(0,r.jsx)("wbr",{})]},t):e):a})}),d]})}function aA(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)(aC,{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 aL(e){let{title:t,catalogs:n,target:s,inputLabel:a,inputId:l,placeholder:o,value:d,canSubmit:c,normalizeValue:u,onValueChange:p,onSubmit:h,examplesLabel:m,examples:g,error:f,multiline:x=!1,children:b}=e,v=(0,i.useRef)(null),y=(0,i.useRef)(null);(0,i.useEffect)(()=>{x?window.matchMedia?.("(pointer: coarse)").matches||y.current?.focus():v.current?.focus()},[x]);let k=e=>{if(!u)return;let t=e.clipboardData.getData("text"),n=u(t);n!==t&&(e.preventDefault(),p(n))};return(0,r.jsxs)(ak,{className:"is-fill",children:[(0,r.jsx)(aA,{title:t,catalogs:n,target:s}),(0,r.jsx)(aI,{label:a,children:x?(0,r.jsx)("textarea",{id:l,ref:y,value:d,"aria-label":a,className:"config-add-source-input is-multiline",placeholder:o,rows:5,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>p(e.target.value),onPaste:k,onBlur:e=>{u&&p(u(e.currentTarget.value))},onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&e.nativeEvent?.isComposing!==!0&&229!==e.keyCode&&(e.preventDefault(),c&&h())}}):(0,r.jsx)("input",{id:l,ref:v,value:d,"aria-label":a,className:"config-add-source-input",placeholder:o,onChange:e=>p(e.target.value),onPaste:k,onBlur:e=>{u&&p(u(e.currentTarget.value))},onKeyDown:e=>{!e.nativeEvent.isComposing&&229!==e.keyCode&&"Enter"===e.key&&c&&h()}})}),b,g.length>0&&(0,r.jsxs)("div",{className:"config-add-source-examples",children:[(0,r.jsx)("div",{className:"config-add-source-examples-label",children:m}),(0,r.jsx)("div",{className:"config-add-source-example-list",children:g.map(e=>"string"==typeof e?(0,r.jsx)("button",{type:"button",className:"config-add-source-example",onClick:()=>p(e),children:e},e):(0,r.jsxs)("button",{type:"button",className:"config-add-source-example has-label",onClick:()=>p(e.value),children:[(0,r.jsx)("span",{className:"config-add-source-example-label",children:e.label}),(0,r.jsx)("span",{className:"config-add-source-example-value",children:e.value})]},e.value))})]}),f&&(0,r.jsx)("div",{role:"alert",className:"config-add-source-error",children:f})]})}function aP(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 az(e){let{id:t,message:n,trustLabel:i,trusting:s=!1,onTrust:a}=e;return(0,r.jsx)(aP,{id:t,action:a&&i?(0,r.jsx)(aB,{size:"small",onClick:a,disabled:s,children:i}):void 0,children:n})}function aO(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-empty-state",children:t})}function aW(e){let{children:t,style:n}=e;return(0,r.jsx)("div",{className:"config-detail",style:n,children:t})}function aF(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 aD(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 aB(e){let{variant:t="secondary",size:n="default",className:i,children:s,...a}=e;return(0,r.jsx)("button",{type:"button",...a,className:["config-button",`config-button-${t}`,`config-button-${n}`,i].filter(Boolean).join(" "),children:s})}function aH(e){let{checked:t,disabled:n=!1,loading:i=!1,size:s="default",label:a,describedBy:l,onChange:o}=e,d=n||i;return(0,r.jsx)("button",{type:"button",role:"switch","aria-checked":t,"aria-busy":i||void 0,"aria-label":a,"aria-describedby":l,title:a,disabled:d,className:`config-switch${"small"===s?" is-small":""}${i?" is-loading":""}`,onClick:()=>o(!t),children:(0,r.jsx)("span",{className:"config-switch-knob","aria-hidden":"true"})})}function a_(e){let{active:t=!1,children:n,className:i,onClick:s,ref:a,...l}=e,{openDetail:o}=ac(),d=ap(t,a);return(0,r.jsx)("div",{className:"config-list-action",children:(0,r.jsxs)("button",{type:"button",...l,ref:d,onClick:e=>{s?.(e),e.defaultPrevented||o()},"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 aU(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 aK(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 aq(e,t){let n=aK(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 aZ(e,t){return t.enabled&&(e?.enabledTotal??0)<=1}function aV(e,t){return e?.providers.find(e=>e.id===t)}function aJ(e){let{modelName:t,effective:n,value:i,onChange:s,disabled:a=!1,describedBy:l}=e,{t:o}=(0,eX.s)(),d=void 0!==i&&void 0===sG(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:o("models.contextWindow"),"aria-label":o("models.contextForModel",{model:t}),"aria-invalid":d||void 0,"aria-describedby":l,disabled:a,onChange:e=>s(""===e.target.value.trim()?void 0:e.target.value)})}let aG={"last-model":"models.enabledLastModel","project-scope":"models.enabledProjectScope"};function aY(e){let{controller:t}=e,{t:n}=(0,eX.s)(),{view:i,pending:s}=t;if(!i)return null;let a=!i.allEnabled,l=i.stalePatterns.length;return a||0!==l?(0,r.jsxs)("div",{className:"enabled-models-banner",children:[(0,r.jsxs)("span",{className:"enabled-models-banner-text",...l>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}`,l>0&&` \xb7 ${n("models.enabledStale",{count:l})}`]})]}),i.editable&&l>0&&(0,r.jsx)(aB,{size:"small",onClick:t.pruneStale,disabled:null!==s,title:n("models.enabledPruneHint"),children:n("models.enabledPrune")}),i.editable&&a&&(0,r.jsx)(aB,{size:"small",onClick:t.clearScope,disabled:null!==s,title:n("models.enabledClearHint"),children:n("models.enabledClear")})]}):null}function aX(e){let{providerId:t,controller:n,noteId:i}=e,{t:s}=(0,eX.s)(),{view:a,loading:l,pending:o,failure:d}=n,c=aV(a,t),u=d?d.messageKey?s(d.messageKey):d.message:null,p=aQ(n,t)?i:void 0;if(l&&!a)return null;if(!c)return(0,r.jsx)(aH,{checked:!1,disabled:!0,label:s("models.enabledProviderToggle",{provider:t}),describedBy:p,onChange:()=>{}});let h=aq(a,c);return(0,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("span",{className:"enabled-models-switch-error",children:u}),(0,r.jsx)(aH,{checked:h.checked,loading:o===`provider:${c.id}`,disabled:null!==o||h.blocked,label:s("models.enabledProviderToggle",{provider:c.name}),describedBy:p,onChange:e=>n.setProvider(c.id,e)})]})}function aQ(e,t){let{view:n,loading:r}=e;if(r&&!n)return null;let i=aV(n,t);if(!i)return"models.enabledCustomEmpty";let{reason:s}=aq(n,i);return s?aG[s]:null}function a0(e){let{providerId:t,controller:n,id:i}=e,{t:s}=(0,eX.s)(),a=aQ(n,t);return a?(0,r.jsx)("div",{id:i,className:"config-detail-heading-note",children:s(a)}):null}function a1(e){var t;let n,{providerId:s,controller:a,contextSettings:l,emptyCatalogHint:o}=e,{t:d}=(0,eX.s)(),[c,u]=(0,i.useState)(""),{view:p,loading:h,pending:m,failure:g}=a,f=aV(p,s)??(o&&!g?{id:s,models:[],enabledCount:0}:void 0),x=function(e,t){let[n,r]=(0,i.useState)(!1),[s,a]=(0,i.useState)(null);return(0,i.useEffect)(()=>a(null),[e]),{refreshing:n,note:s,refresh:(0,i.useCallback)(()=>{r(!0),a(null),(async()=>{try{let n=await fetch("/api/models/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);"offline"===r.reason?a("models.catalogOffline"):r.completed?a(r.changed?"models.catalogUpdated":"models.catalogUnchanged"):a("models.catalogUnreachable"),r.changed&&t()}catch{a("models.catalogUnreachable")}finally{r(!1)}})()},[e,t])}}(s,a.refresh),b=(0,i.useId)();if((0,i.useEffect)(()=>u(""),[s]),h&&!p)return(0,r.jsx)("div",{className:"enabled-models-empty",children:d("agents.modelsLoading")});if(!f)return g?.message?(0,r.jsx)("div",{className:"enabled-models-error",children:g.message}):(0,r.jsx)("div",{className:"enabled-models-empty",children:d("models.enabledUnavailable")});let v=(t=f.models,(n=c.trim().toLowerCase())?t.filter(e=>e.id.toLowerCase().includes(n)||e.name.toLowerCase().includes(n)):[...t]),y=aK(p,v),k=v.length!==f.models.length,j=null!==m,w=`provider:${f.id}`,S=p?.editable===!0,C=`${b}-scope`,N=`${b}-last`,I=`${b}-context`,E=S&&!y.canDisable&&y.disableRefs.length>0,$=E||S&&v.some(e=>aZ(p,e)),T=(e,t)=>{k?a.setModels(w,t,e):a.setProvider(f.id,e)};return(0,r.jsxs)("div",{className:"enabled-models-section",children:[(0,r.jsxs)("div",{className:"enabled-models-header",children:[(0,r.jsx)("span",{className:"enabled-models-title",children:d("models.enabledSection")}),(0,r.jsx)("span",{className:"enabled-models-count",children:d("models.enabledCount",{enabled:f.enabledCount,total:f.models.length})}),(0,r.jsx)(aB,{size:"small",disabled:j||!y.canEnable,"aria-describedby":S?void 0:C,onClick:()=>T(!0,y.enableRefs),children:k?d("models.enableShown"):d("models.enableAll")}),(0,r.jsx)(aB,{size:"small",disabled:j||!y.canDisable,"aria-describedby":S?E?N:void 0:C,onClick:()=>T(!1,y.disableRefs),children:k?d("models.disableShown"):d("models.disableAll")}),(0,r.jsx)(aB,{size:"small",disabled:j||x.refreshing,title:d("models.refreshCatalogHint"),onClick:x.refresh,children:x.refreshing?d("models.refreshingCatalog"):d("models.refreshCatalog")})]}),x.note&&(0,r.jsx)("div",{className:"enabled-models-note",children:d(x.note)}),!S&&(0,r.jsx)("div",{id:C,className:"enabled-models-note",children:d("models.enabledProjectScope")}),$&&(0,r.jsx)("div",{id:N,className:"enabled-models-note",children:d("models.enabledLastModel")}),g&&(0,r.jsx)("div",{className:"enabled-models-error",children:g.messageKey?d(g.messageKey):g.message}),f.models.length>8&&(0,r.jsx)("input",{value:c,onChange:e=>u(e.target.value),placeholder:d("models.enabledFilterPlaceholder",{count:f.models.length}),"aria-label":d("models.enabledFilter"),className:"enabled-models-filter"}),l&&f.models.length>0&&(0,r.jsx)("div",{id:I,className:"enabled-models-note",children:d("models.contextOverrideHelp")}),(0,r.jsx)("div",{className:"enabled-models-list",children:0===v.length?(0,r.jsx)("div",{className:"enabled-models-empty",children:0===f.models.length&&o||d("models.enabledNoMatches")}):v.map(e=>{let t=aZ(p,e),n=l?.overrides?.[e.id],i=n&&"object"==typeof n&&!Array.isArray(n)?n.contextWindow:void 0;return(0,r.jsxs)("div",{className:"enabled-models-row",children:[(0,r.jsxs)("span",{className:"enabled-models-row-text",children:[(0,r.jsx)("span",{className:"enabled-models-row-name",children:e.name}),(0,r.jsx)("code",{className:"enabled-models-row-id",children:e.id})]}),e.thinkingPin&&(0,r.jsx)("span",{className:"enabled-models-pin",title:d("models.enabledPinHint"),children:e.thinkingPin}),l&&(0,r.jsx)(aJ,{modelName:e.name,effective:e.contextWindow,value:i,disabled:l.disabled,describedBy:I,onChange:t=>l.onChange(e.id,t)}),(0,r.jsx)(aH,{checked:e.enabled,loading:m===e.ref,disabled:j||!p?.editable||t,label:d("models.enabledToggle",{model:e.name}),describedBy:S?t?N:void 0:C,onChange:t=>a.setModels(e.ref,[e.ref],t)})]},e.ref)})})]})}function a2(e){let{message:t,hint:n,value:i,placeholder:s,submitLabel:a,inputLabel:l,disabled:o=!1,plainEnterSubmits:d=!0,inputRef:c,onValueChange:u,onSubmit:p}=e,h=!o&&i.trim().length>0;return(0,r.jsxs)("div",{className:"oauth-paste-panel",children:[(0,r.jsx)("p",{className:"oauth-paste-message",children:t}),n&&(0,r.jsx)("p",{className:"oauth-paste-hint",children:n}),(0,r.jsxs)("div",{className:"oauth-paste-row",children:[(0,r.jsx)("input",{ref:c,value:i,className:"oauth-paste-input",placeholder:s,"aria-label":l,disabled:o||void 0,onChange:e=>u(e.target.value),onKeyDown:e=>{var t;t={key:e.key,metaKey:e.metaKey,ctrlKey:e.ctrlKey,isComposing:e.nativeEvent.isComposing,keyCode:e.keyCode},"Enter"===t.key&&!t.isComposing&&229!==t.keyCode&&(d||t.metaKey||t.ctrlKey)&&h&&p()}}),(0,r.jsx)("button",{type:"button",className:"oauth-paste-submit",onClick:p,disabled:!h,children:a})]})]})}let a4={anthropic:{symbol:"anthropic",color:!1},openai:{symbol:"openai",color:!1},"openai-codex":{symbol:"openai",color:!1},google:{symbol:"google",color:!0},"google-vertex":{symbol:"google",color:!0},"ant-ling":{symbol:"antgroup",color:!0},deepseek:{symbol:"deepseek",color:!0},groq:{symbol:"groq",color:!1},"llama.cpp":{symbol:"llama-cpp",color:!1},mistral:{symbol:"mistral",color:!0},moonshotai:{symbol:"moonshot",color:!1},"moonshotai-cn":{symbol:"moonshot",color:!1},moonshot:{symbol:"moonshot",color:!1},minimax:{symbol:"minimax",color:!0},"minimax-cn":{symbol:"minimax",color:!0},fireworks:{symbol:"fireworks",color:!0},huggingface:{symbol:"huggingface",color:!0},cerebras:{symbol:"cerebras",color:!0},openrouter:{symbol:"openrouter",color:!1},xai:{symbol:"xai",color:!1},"cloudflare-ai-gateway":{symbol:"cloudflare",color:!0},"cloudflare-workers-ai":{symbol:"cloudflare",color:!0},"vercel-ai-gateway":{symbol:"vercel",color:!1},"github-copilot":{symbol:"githubcopilot",color:!1},"amazon-bedrock":{symbol:"aws",color:!0},azure:{symbol:"azure",color:!0},"azure-openai-responses":{symbol:"azure",color:!0},"kimi-coding":{symbol:"kimi",color:!0},nvidia:{symbol:"nvidia",color:!0},opencode:{symbol:"opencode",color:!1},"opencode-go":{symbol:"opencode",color:!1},qwen:{symbol:"qwen",color:!0},xiaomi:{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-ams":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-cn":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-sgp":{symbol:"xiaomimimo",color:!1},zai:{symbol:"zai",color:!1},"zai-coding-cn":{symbol:"zai",color:!1},zhipu:{symbol:"zhipu",color:!0},cohere:{symbol:"cohere",color:!0},perplexity:{symbol:"perplexity",color:!0},together:{symbol:"together",color:!0},grok:{symbol:"grok",color:!1},Strata:{symbol:"strata",color:!1},strata:{symbol:"strata",color:!1}};function a8(e){let{id:t,size:n}=e,i=a4[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 a6=["openai-codex","deepseek","openrouter","moonshotai","moonshotai-cn","minimax","minimax-cn","vercel-ai-gateway","opencode-go","kimi-coding"],a3="pi-web:provider-usage:";function a5(e){let{providerId:t,enabled:n}=e;return a6.includes(t)?(0,r.jsx)(a9,{providerId:t,enabled:n}):null}function a9(e){let{providerId:t,enabled:n}=e,[s,a]=(0,i.useState)(null),[l,o]=(0,i.useState)(!1),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),h=(0,i.useRef)(null),{locale:m,t:g}=(0,eX.s)();(0,i.useEffect)(()=>{h.current&&clearTimeout(h.current),p(!1),a(null);try{let e=localStorage.getItem(`${a3}${t}`);if(e){let t=JSON.parse(e);t?.status==="ready"&&t.report&&Array.isArray(t.report.buckets)&&Array.isArray(t.report.metrics)&&a(t)}}catch{try{localStorage.removeItem(`${a3}${t}`)}catch{}}return c(null),()=>{h.current&&clearTimeout(h.current)}},[t]);let f=(0,i.useCallback)(async()=>{o(!0),c(null);try{let e=await fetch("/api/provider-usage/query",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:t})}),n=await e.json();if(!e.ok)throw Error(n.error??`HTTP ${e.status}`);if("ready"===n.status){a(n);try{localStorage.setItem(`${a3}${t}`,JSON.stringify(n))}catch{}p(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>p(!1),2e3)}else c(n.message??g("providerUsage.queryFailed"))}catch(e){c(e instanceof Error?e.message:g("providerUsage.queryFailed"))}finally{o(!1)}},[t,g]),x=s?.status==="ready"?s.report:void 0;return(0,r.jsxs)("section",{style:{paddingTop:10,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:13,color:"var(--text)",fontWeight:600,lineHeight:1.35},children:g("providerUsage.usage")}),(0,r.jsx)("button",{type:"button",onClick:f,disabled:!n||l,title:g(l?"providerUsage.refreshing":"providerUsage.refresh"),"aria-label":g(l?"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&&!l?"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:l?{animation:"spin 0.8s linear infinite"}:void 0,"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}),x&&(0,r.jsx)("span",{title:new Date(x.capturedAt).toLocaleString(m),style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap"},children:g("providerUsage.updated",{time:(0,tm.ob)(x.capturedAt,m)})})]}),!x&&!d&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)"},children:g("providerUsage.notQueried")}),d&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171"},children:d}),x&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"180px minmax(0, 1fr)",columnGap:14,rowGap:8,alignItems:"baseline",minWidth:0,width:"min(100%, 420px)",maxWidth:"100%",fontSize:12},children:[x.buckets.map(e=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.groupLabel?`${e.groupLabel} / ${e.label}`:e.label}),(0,r.jsx)("span",{style:{color:"var(--text)",fontFamily:"var(--font-mono)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:function(e,t){if("percent"===e.unit&&void 0!==e.remaining){let t=e.resetsAt?` / ${new Date(1e3*e.resetsAt).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:"";return`${Math.round(e.remaining)}%${t}`}return"currency"===e.unit?`${"CNY"===e.currency?"CNY ":"$"}${a7(e.remaining??e.limit)}`:void 0!==e.remaining&&void 0!==e.limit?`${a7(e.remaining)} / ${a7(e.limit)}`:e.period??t}(e,g("providerUsage.available"))})]},e.id)),x.metrics.map(e=>{var t;return(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("span",{style:{color:"var(--text)",fontFamily:"var(--font-mono)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:"currency"===(t=e).unit?`${"CNY"===t.currency?"CNY ":"$"}${t.value}`:String(t.value)})]},e.id)})]})]})}function a7(e){return void 0===e?"-":Number.isInteger(e)?String(e):e.toFixed(2)}function le(){let e=sU("models");if(!e)return null;try{let t=JSON.parse(e);if(null===t||"object"!=typeof t)return null;if("provider"===t.type&&"string"==typeof t.name)return{type:"provider",name:t.name};if("model"===t.type&&"string"==typeof t.providerName&&"number"==typeof t.index&&Number.isInteger(t.index)&&t.index>=0)return{type:"model",providerName:t.providerName,index:t.index};if(("oauth"===t.type||"apikey"===t.type)&&"string"==typeof t.providerId)return{type:t.type,providerId:t.providerId}}catch{}return null}function lt(e){return 1===Object.keys(e).length&&Object.keys(e.modelOverrides??{}).length>0}let ln=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],lr=["chat-template","qwen-chat-template","deepseek","openai"],li={empty:"models.providerIncomplete",baseUrl:"models.providerNeedsBaseUrl"};function ls(e){let{label:t,children:n}=e;return(0,r.jsx)(aI,{label:t,children:n})}let la={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 ll(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:{...la,fontFamily:s?"var(--font-mono)":"inherit"}})}function lo(e){let{value:t,onChange:n,placeholder:s,mono:a,onKeyDown:l,autoComplete:o="off",spellCheck:d=!1,style:c}=e,[u,p]=(0,i.useState)(!1),{t:h}=(0,eX.s)();return(0,i.useEffect)(()=>{t||p(!1)},[t]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...c},children:[(0,r.jsx)("input",{type:u?"text":"password",value:t,onChange:e=>n(e.target.value),onKeyDown:l,placeholder:s,style:{...la,paddingRight:34,fontFamily:a?"var(--font-mono)":"inherit"},autoComplete:o,spellCheck:d}),(0,r.jsx)("button",{type:"button",onClick:()=>p(e=>!e),"aria-label":h(u?"i18n.hideDetails":"i18n.showDetails"),title:h(u?"i18n.hideDetails":"i18n.showDetails"),style:{position:"absolute",right:5,top:"50%",transform:"translateY(-50%)",width:24,height:24,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:u?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C7 20 2.73 16.89 1 12a18.45 18.45 0 0 1 5.06-6.94"}),(0,r.jsx)("path",{d:"M9.9 4.24A10.94 10.94 0 0 1 12 4c5 0 9.27 3.11 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,r.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,r.jsx)("path",{d:"M1 1l22 22"})]}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function ld(e){let{value:t,onChange:n,placeholder:i,invalid:s}=e;return(0,r.jsx)("input",{type:"number",value:t,onChange:e=>n(e.target.value),placeholder:i,"aria-invalid":s||void 0,style:s?{...la,borderColor:"#ef4444"}:la})}function lc(e){let{value:t,onChange:n,options:i,required:s}=e,{t:a}=(0,eX.s)();return(0,r.jsxs)("select",{value:t,onChange:e=>n(e.target.value),style:{...la,color:t?"var(--text)":"var(--text-dim)"},children:[!s&&(0,r.jsxs)("option",{value:"",children:["— ",a("i18n.default")," / none —"]}),i.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]})}function lu(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 lp(e){let{children:t}=e;return(0,r.jsx)(aN,{children:t})}function lh(e){let{name:t,editingName:n,fallbackLabel:s,provider:a,onChange:l,onEditingNameChange:o,onRename:d,onDelete:c,onAddModels:u,enabledModels:p,managedCredential:h=!1}=e,{t:m}=(0,eX.s)(),[g,f]=(0,i.useState)({phase:"idle"}),[x,b]=(0,i.useState)(""),[v,y]=(0,i.useState)([]),k=(0,i.useRef)(0),j=(0,i.useRef)(null),w=(0,i.useId)(),S=(e,t)=>l({...a,[e]:t});(0,i.useEffect)(()=>{k.current+=1,f({phase:"idle"}),b(""),y([])},[t,a.baseUrl,a.api,a.apiKey]);let[C,N]=(0,i.useState)(null);(0,i.useEffect)(()=>{N(null)},[t]);let I="string"==typeof a.compat?.thinkingFormat?a.compat.thinkingFormat:"",E=a.compat?.chatTemplateKwargs,$=C??(null==E||"object"!=typeof E||Array.isArray(E)?"":JSON.stringify(E,null,2)),T=!1;if(null!==C&&C.trim())try{let e=JSON.parse(C);T=null===e||"object"!=typeof e||Array.isArray(e)}catch{T=!0}let M=(0,i.useCallback)(async()=>{if("loading"===g.phase)return;let e=++k.current;f({phase:"loading"}),y([]);try{let n=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:t,provider:{...a,models:void 0}})}),r=await n.json();if(e!==k.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??a.baseUrl??""})}catch(t){if(e!==k.current)return;f({phase:"error",message:t instanceof Error?t.message:String(t)})}},[g.phase,t,a]),R=new Set((a.models??[]).map(e=>e.id)),A="success"===g.phase?g.models:[],L=x.trim().toLocaleLowerCase(),P=A.filter(e=>!L||e.id.toLocaleLowerCase().includes(L)||e.name?.toLocaleLowerCase().includes(L)),z=P.slice(0,300),O=z.filter(e=>!R.has(e.id)).map(e=>e.id),W=v.filter(e=>!R.has(e)).length,F=O.length>0&&O.every(e=>v.includes(e)),D=!F&&O.some(e=>v.includes(e));return(0,i.useEffect)(()=>{j.current&&(j.current.indeterminate=D)},[D]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(aj,{children:[(0,r.jsx)(aw,{children:(0,r.jsx)(lp,{children:m("i18n.provider")})}),(0,r.jsxs)(aS,{children:[(0,r.jsx)(aX,{providerId:t,controller:p,noteId:w}),(0,r.jsx)(aB,{variant:"danger",size:"small",onClick:c,children:m("i18n.delete")})]})]}),(0,r.jsx)(a0,{providerId:t,controller:p,id:w})]}),h?(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[t," \xb7 ",m("models.definitionInModelsJson")]}):(0,r.jsxs)(ls,{label:m("i18n.providerId"),children:[(0,r.jsx)(ll,{value:n,onChange:o,placeholder:"provider-id",mono:!0}),n!==t&&n.trim()&&(0,r.jsx)("button",{onClick:()=>d(n.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--accent)",border:"none",borderRadius:4,color:"var(--accent-contrast)",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:m("i18n.rename")})]}),(0,r.jsx)(ls,{label:m("models.providerDisplayName"),children:(0,r.jsx)(ll,{value:a.name??"",onChange:e=>l(function(e,t){if(!t.trim()){let t={...e};return delete t.name,t}return"name"in e?{...e,name:t}:{name:t,...e}}(a,e)),placeholder:s})}),(0,r.jsx)(ls,{label:"Base URL",children:(0,r.jsx)(ll,{value:a.baseUrl??"",onChange:e=>S("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),!h&&(0,r.jsx)(ls,{label:"API Key",children:(0,r.jsx)(lo,{value:a.apiKey??"",onChange:e=>S("apiKey",e||void 0),placeholder:m("models.apiKeyPlaceholder"),mono:!0})}),(0,r.jsx)(ls,{label:"API",children:(0,r.jsx)(lc,{value:a.api??"",onChange:e=>S("api",e||void 0),options:ln})}),(0,r.jsx)(ls,{label:"Headers",children:(0,r.jsx)(lk,{headers:a.headers,onChange:e=>S("headers",e)})}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)(lp,{children:m("models.compatibility")}),(0,r.jsxs)(ls,{label:m("models.thinkingFormat"),children:[(0,r.jsx)(lc,{value:I,onChange:e=>{let t=lv(a,"thinkingFormat",e||void 0);"chat-template"!==e&&(t=lv(t,"chatTemplateKwargs",void 0)),l(t)},options:lr}),(0,r.jsx)("code",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:"compat.thinkingFormat"})]}),"chat-template"===I&&(0,r.jsxs)(ls,{label:m("models.chatTemplateKwargs"),children:[(0,r.jsx)("textarea",{value:$,onChange:e=>(e=>{if(N(e),!e.trim())return void l(lv(a,"chatTemplateKwargs",void 0));try{let t=JSON.parse(e);null===t||"object"!=typeof t||Array.isArray(t)||l(lv(a,"chatTemplateKwargs",t))}catch{}})(e.target.value),placeholder:'{"enable_thinking": {"$var": "thinking.enabled"}}',rows:4,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off","aria-invalid":T||void 0,style:{...la,fontFamily:"var(--font-mono)",resize:"vertical",minHeight:60,borderColor:T?"#ef4444":void 0}}),T&&(0,r.jsx)("span",{style:{fontSize:10,color:"#ef4444",marginTop:2},children:m("models.chatTemplateKwargsInvalid")}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:m("models.chatTemplateKwargsHelp")}),(0,r.jsx)("code",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:"compat.chatTemplateKwargs"})]})]}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==g.phase&&(0,r.jsx)("button",{onClick:M,disabled:"loading"===g.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:"loading"===g.phase?"var(--text-dim)":"var(--text-muted)",cursor:"loading"===g.phase?"not-allowed":"pointer",fontSize:11},children:"loading"===g.phase?m("models.discoveryFetching"):m("models.discoveryFetch")}),"error"===g.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:g.message}),"success"===g.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:x,onChange:e=>b(e.target.value),placeholder:m("models.discoveryFilterPlaceholder",{count:g.models.length}),"aria-label":m("models.discoveryFilter"),style:{...la,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:O.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:j,type:"checkbox",checked:F,disabled:0===O.length,onChange:()=>{let e=new Set(O);y(t=>F?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...O])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),m("models.discoverySelectShown")]}),0===z.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:m("models.discoveryNoMatches")}):z.map((e,t)=>{let n=R.has(e.id),i=v.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 y(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:m("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:g.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:P.length>z.length?m("models.discoveryShowing",{shown:z.length,total:P.length}):m("models.discoveryFetched",{count:g.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==g.phase)return;let e=new Set(v),t=g.models.filter(t=>e.has(t.id)&&!R.has(t.id));0!==t.length&&(u(t),y([]))},disabled:0===W,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:W?"var(--accent)":"var(--bg-panel)",color:W?"var(--accent-contrast)":"var(--text-dim)",cursor:W?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:W?m("models.discoveryAddSelectedCount",{count:W}):m("models.discoveryAddSelected")})]})]})]})]})}let lm=["off","minimal","low","medium","high","xhigh","max"],lg={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function lf(e){let{value:t,onChange:n}=e,{t:i}=(0,eX.s)(),s=t??{},a=(e,t)=>{let r={...s};"omit"===t?delete r[e]:r[e]=t,n(Object.keys(r).length?r:void 0)};return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:lm.map(e=>{let t=s[e],n=e in s?null===t?"null":"string":"omit",l="string"==typeof t?t:"",o=lg[e],d={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},c={background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600};return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:o,flexShrink:0,opacity:"null"===n?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===n?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===n?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>a(e,"omit"),style:{...d,..."omit"===n?c:{}},children:i("i18n.default")}),(0,r.jsx)("button",{onClick:()=>a(e,null),style:{...d,borderLeft:"1px solid var(--border)",..."null"===n?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:i("i18n.disabled")})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===n?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>a(e,l||e),style:{...d,..."string"===n?c:{},borderRight:"1px solid var(--border)",flexShrink:0},children:i("i18n.custom")}),(0,r.jsx)("input",{value:l,onChange:t=>a(e,t.target.value),onFocus:()=>{"string"!==n&&a(e,l||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===n?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===n?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let lx={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function lb(e){return e.compat?.thinkingFormat==="deepseek"}function lv(e,t,n){if(void 0===n){if(!e.compat?.[t])return e;let n={...e.compat};return delete n[t],{...e,compat:Object.keys(n).length?n:void 0}}return{...e,compat:{...e.compat??{},[t]:n}}}function ly(e,t){return{...e.compat??{},...t.compat??{}}}function lk(e){let{headers:t,onChange:n}=e,{t:s}=(0,eX.s)(),[a,l]=(0,i.useState)(()=>Object.entries(t??{}).map((e,t)=>{let[n,r]=e;return{id:t,name:n,value:r}})),o=(0,i.useRef)(a.length),d=e=>{l(e),n(function(e){let t={};for(let n of e){let e=n.name.trim();e&&(t[e]=n.value)}return Object.keys(t).length?t:void 0}(e))},c=(e,t)=>{d(a.map(n=>n.id===e?{...n,...t}:n))},u={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[a.map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{value:e.name,onChange:t=>c(e.id,{name:t.target.value}),"aria-label":s("models.headerName"),placeholder:"Header-Name",style:{...la,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>c(e.id,{value:t.target.value}),"aria-label":s("models.headerValue"),placeholder:"value",style:{...la,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{"aria-label":s("models.removeHeader"),onClick:()=>{var t;return t=e.id,void d(a.filter(e=>e.id!==t))},style:u,children:"✕"})]},e.id)),(0,r.jsxs)("button",{onClick:()=>l(e=>[...e,{id:o.current++,name:"",value:""}]),style:{padding:"5px 9px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,alignSelf:"flex-start"},children:["+ ",s("models.addHeader")]})]})}function lj(e){let{providerName:t,provider:n,model:s,onChange:a,onDelete:l}=e,[o,d]=(0,i.useState)({phase:"idle"}),{t:c}=(0,eX.s)(),[u,p]=(0,i.useState)({phase:"idle"}),[h,m]=(0,i.useState)(!1),[g,f]=(0,i.useState)(()=>s5(s.cost)),x=(0,i.useRef)(g),[b,v]=(0,i.useState)(!1),y=(0,i.useRef)(0),k=s.baseUrl??n.baseUrl,j=(0,i.useRef)(0),w=(0,i.useRef)(null),S=(0,i.useRef)(s.cost),C=(e,t)=>a({...s,[e]:t}),N=(()=>{if("idle"===o.phase)return null;if("testing"===o.phase)return c("i18n.testingModel");let e=[void 0!==o.latencyMs?`${o.latencyMs}ms`:null,void 0!==o.status?`HTTP ${o.status}`:null].filter(Boolean);return"success"===o.phase?[c("i18n.connected"),...e,o.responseText||null].filter(Boolean).join(" \xb7 "):[c("i18n.failed"),...e,o.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>(y.current+=1,d({phase:"idle"}),()=>{y.current+=1}),[t,n,s]),(0,i.useEffect)(()=>{j.current+=1,p({phase:"idle"}),w.current=null},[t,k,s.id]);let I=(0,i.useCallback)(async()=>{if(!s.id.trim()||"testing"===o.phase)return;let e=++y.current;d({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:t,provider:n,model:s})}),i=await r.json();if(e!==y.current)return;if(!r.ok||!i.ok)return void d({phase:"error",message:i.error??`HTTP ${r.status}`,latencyMs:i.latencyMs,status:i.status});d({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(t){if(e!==y.current)return;d({phase:"error",message:t instanceof Error?t.message:String(t)})}},[s,n,t,o.phase]),E=(0,i.useCallback)(async()=>{let e=s.id.trim();if(!e||"loading"===u.phase)return;let n=++j.current;p({phase:"loading"});try{let r=new URLSearchParams({q:e,provider:t,limit:"50"});k?.trim()&&r.set("baseUrl",k.trim());let i=await fetch(`/api/models-config/catalog?${r}`),l=await i.json();if(n!==j.current)return;if(!i.ok||l.error||!l.recommendation)return void p({phase:"error",message:l.error??`HTTP ${i.status}`});let o=function(e,t){let n={...e},r=0;if(!e.name?.trim()&&t.name&&(n.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(n.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(n.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(n.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(n.maxTokens=t.maxTokens,r+=1),t.cost){let i={...e.cost??{}},s=0;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],s+=1);let a=s9(s5(i));s>0&&a&&(n.cost={...i,...a},r+=s)}return{model:n,appliedCount:r}}(s,l.recommendation.preset);o.appliedCount>0&&(w.current=s,a(o.model)),m(!1),p({phase:"success",recommendation:l.recommendation,appliedCount:o.appliedCount})}catch(e){if(n!==j.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,s,a,k,t]),$=(()=>{if("success"!==u.phase)return null;let{recommendation:e,appliedCount:n}=u,r=n>0?c("models.catalogFilled",{count:n}):c("models.catalogNoEmptyFields");if("unreliable"===e.price.status){let t="no-exact-match"===e.price.reason?c("models.catalogNoExactMatch"):c("models.catalogPriceUnreliable");return`${r} \xb7 ${t}`}let i="provider"===e.price.method?c("models.catalogPriceProvider",{provider:e.price.providerName??e.price.providerId??t}):"base-url"===e.price.method?c("models.catalogPriceBaseUrl",{provider:e.price.providerName??e.price.providerId??t}):c("models.catalogPriceConsensus",{support:e.price.support,total:e.price.total});return`${r} \xb7 ${i}`})(),T="error"===u.phase?u.message:$,M="error"===u.phase?"#ef4444":"success"===u.phase&&"unreliable"===u.recommendation.price.status?"#d97706":"var(--text-dim)",R=[{key:"input",label:c("models.costInput")},{key:"output",label:c("models.costOutput")},{key:"cacheRead",label:c("models.costCacheRead")},{key:"cacheWrite",label:c("models.costCacheWrite")}],A=new Set(Object.keys(s.compat??{})),L=0;lb(s)&&(L+=1,A.delete("thinkingFormat"),A.delete("requiresReasoningContentOnAssistantMessages")),Object.prototype.hasOwnProperty.call(s.compat??{},"supportsDeveloperRole")&&(L+=1,A.delete("supportsDeveloperRole")),L+=A.size;let P=s2(s),z=s4(P),O=[s.baseUrl?c("models.baseUrlOverride"):null,s.api?`API: ${s.api}`:null,Object.keys(s.headers??{}).length?c("models.headersSummary",{count:Object.keys(s.headers??{}).length}):null,L?c("models.compatSummary",{count:L}):null,Object.keys(s.thinkingLevelMap??{}).length?c("models.thinkingSummary",{count:Object.keys(s.thinkingLevelMap??{}).length}):null,void 0!==z?c("models.imageMaxBytesSummary",{size:s8(z)}):null].filter(e=>!!e),W=O.length?O.join(" \xb7 "):c("models.providerDefaults");return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(aj,{children:[(0,r.jsx)(aw,{children:(0,r.jsx)(lp,{children:c("i18n.model")})}),(0,r.jsxs)(aS,{children:[N&&(0,r.jsx)("span",{title:N,style:{maxWidth:260,height:28,padding:"0 8px",border:`1px solid ${"error"===o.phase?"#fecaca":"success"===o.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===o.phase?"#fee2e2":"success"===o.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)(aB,{size:"small",variant:"success"===o.phase?"primary":"secondary",onClick:"success"===o.phase?()=>d({phase:"idle"}):I,disabled:!s.id.trim()||"testing"===o.phase,title:c("i18n.testConnection"),className:"success"===o.phase?"is-success":void 0,children:["success"===o.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"===o.phase?c("i18n.checking"):"success"===o.phase?c("common.ok"):c("i18n.test")]}),(0,r.jsx)(aB,{variant:"danger",size:"small",onClick:l,children:c("i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(ls,{label:"ID *",children:(0,r.jsx)(ll,{value:s.id,onChange:e=>C("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(ls,{label:"Name",children:(0,r.jsx)(ll,{value:s.name??"",onChange:e=>C("name",e||void 0),placeholder:c("models.displayNamePlaceholder")})})]}),(0,r.jsxs)("div",{style:{padding:"2px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>void E(),disabled:!s.id.trim()||"loading"===u.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:s.id.trim()&&"loading"!==u.phase?"var(--text-muted)":"var(--text-dim)",cursor:s.id.trim()&&"loading"!==u.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===u.phase?c("models.catalogFilling"):c("models.catalogFill")}),(0,r.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:c("models.catalogSource")})]}),T&&(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:8,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:M,fontSize:10},children:[(0,r.jsx)("span",{title:T,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:T}),w.current&&(0,r.jsx)("button",{onClick:()=>{let e=w.current;e&&(w.current=null,a(e),p({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:c("models.catalogUndo")})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(lp,{children:c("models.capabilities")}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginTop:8},children:[(0,r.jsx)(lu,{label:c("models.reasoning"),checked:s.reasoning??!1,onChange:e=>C("reasoning",e||void 0)}),(0,r.jsx)(lu,{label:c("models.imageInput"),checked:s.input?.includes("image")??!1,onChange:e=>C("input",e?["text","image"]:void 0)})]})]}),(0,r.jsxs)("section",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[(0,r.jsx)(lp,{children:c("models.modelSpecs")}),(0,r.jsx)("button",{type:"button",onClick:()=>{if(h)return void m(!1);S.current=s.cost;let e=s5(s.cost);x.current=e,f(e),m(!0)},"aria-expanded":h,style:{padding:"2px 4px",border:"none",background:"transparent",color:"var(--accent)",cursor:"pointer",fontSize:10},children:h?c("models.finishEditingCosts"):c("models.editCosts")})]}),(0,r.jsxs)("div",{style:{marginTop:10,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:10},children:[(0,r.jsx)(ls,{label:c("models.contextWindow"),children:(0,r.jsx)(ld,{value:void 0!==s.contextWindow?String(s.contextWindow):"",onChange:e=>C("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(ls,{label:c("models.maxOutputTokens"),children:(0,r.jsx)(ld,{value:void 0!==s.maxTokens?String(s.maxTokens):"",onChange:e=>C("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{style:{marginTop:16},children:[(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontWeight:600,textTransform:"uppercase"},children:c("models.costPerMillion")}),h?(0,r.jsxs)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(110px, 1fr))",gap:8},children:[R.map(e=>{let{key:t,label:n}=e;return(0,r.jsx)(ls,{label:n,children:(0,r.jsx)(ld,{value:g[t],onChange:e=>{let n,r,i;return r=s9(n={...x.current,[t]:e}),i={...s},void(x.current=n,f(n),r?(i.cost={...S.current??{},...r},S.current=i.cost):delete i.cost,a(i))},placeholder:"0"})},t)}),s7(g)&&!s9(g)&&(0,r.jsx)("div",{"aria-live":"polite",style:{gridColumn:"1 / -1",color:"#d97706",fontSize:10},children:c("models.costAllRequired")})]}):(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(105px, 1fr))",gap:"8px 16px"},children:R.map(e=>{let t,{key:n,label:i}=e,a=s.cost?.[n]===void 0;return(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:i}),(0,r.jsx)("div",{style:{marginTop:3,color:a?"var(--text-dim)":"var(--text)",fontSize:12,fontFamily:"var(--font-mono)",fontVariantNumeric:"tabular-nums"},children:void 0===(t=s.cost?.[n])?c("models.notProvided"):`$${String(t)}`})]},n)})})]})]}),(0,r.jsxs)("section",{style:{borderTop:"1px solid var(--border)",paddingTop:4},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>v(e=>!e),"aria-expanded":b,"aria-controls":"model-advanced-settings",style:{width:"100%",minHeight:48,padding:"8px 0",border:"none",background:"transparent",display:"grid",gridTemplateColumns:"minmax(0, 1fr) 18px",alignItems:"center",gap:10,color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:11,fontWeight:600},children:c("models.advancedSettings")}),(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-dim)",fontSize:10,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:W})]}),(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{color:"var(--text-dim)",transform:b?"rotate(180deg)":"none",transition:"transform 0.15s ease"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),b&&(0,r.jsxs)("div",{id:"model-advanced-settings",style:{display:"flex",flexDirection:"column",gap:14,padding:"4px 0 16px"},children:[(0,r.jsx)(ls,{label:c("models.baseUrlOverride"),children:(0,r.jsx)(ll,{value:s.baseUrl??"",onChange:e=>C("baseUrl",e.trim()||void 0),placeholder:n.baseUrl??c("models.providerDefaults"),mono:!0})}),(0,r.jsx)(ls,{label:c("models.apiOverride"),children:(0,r.jsx)(lc,{value:s.api??"",onChange:e=>C("api",e||void 0),options:ln})}),(0,r.jsxs)(ls,{label:c("models.headers"),children:[(0,r.jsx)(lk,{headers:s.headers,onChange:e=>C("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:c("models.headersHelp")})]}),(s.input?.includes("image")||void 0!==P)&&(0,r.jsxs)(ls,{label:c("models.imageMaxBytes"),children:[(0,r.jsx)(ld,{value:void 0===P?"":String(P),onChange:e=>{var t;let n,r,i,l;return a((t=e.trim()||void 0,n={...s1(s.inputLimits)?s.inputLimits:{}},r={...s1(n.images)?n.images:{}},i={...s1(r.resize)?r.resize:{}},void 0===t?delete i.maxBytes:i.maxBytes=s4(t)??t,Object.keys(i).length?r.resize=i:delete r.resize,Object.keys(r).length?n.images=r:delete n.images,l={...s},Object.keys(n).length?l.inputLimits=n:delete l.inputLimits,l))},placeholder:String(4718592),invalid:void 0===z&&void 0!==P}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[void 0!==z&&`${s8(z)} \xb7 `,c("models.imageMaxBytesHelp",{size:s8(4718592)})]}),(0,r.jsx)("code",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:"inputLimits.images.resize.maxBytes"})]}),s.reasoning&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsx)(lp,{children:c("models.compatibility")}),(0,r.jsx)(lu,{label:c("models.deepSeekThinkingCompat"),checked:lb(s),onChange:e=>a(function(e,t){if(t)return{...e,compat:{...e.compat??{},...lx}};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)(lu,{label:c("models.developerRole"),checked:!1!==ly(n,s).supportsDeveloperRole,onChange:e=>a(ae(s,"supportsDeveloperRole",e))}),(s.api??n.api)==="anthropic-messages"&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[(0,r.jsx)(lu,{label:c("models.adaptiveThinking"),checked:!0===ly(n,s).forceAdaptiveThinking,onChange:e=>a(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(n!==r)return ae(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)(lp,{children:c("models.thinkingLevelMap")}),s.thinkingLevelMap&&(0,r.jsx)("button",{type:"button",onClick:()=>C("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 5px",background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer"},children:c("models.clearAll")})]}),(0,r.jsx)(lf,{value:s.thinkingLevelMap,onChange:e=>C("thinkingLevelMap",e)})]})]})]})]})]})}function lw(e){let{provider:t,onRefresh:n,enabledModels:s,contextSettings:a}=e,[l,o]=(0,i.useState)({phase:"idle"}),{t:d}=(0,eX.s)(),[c,u]=(0,i.useState)(""),p=(0,i.useRef)(null),h=(0,i.useRef)(null);(0,i.useEffect)(()=>{("auth"===l.phase||"prompt"===l.phase)&&setTimeout(()=>h.current?.focus(),50)},[l.phase]),(0,i.useEffect)(()=>{o({phase:"idle"}),u(""),p.current?.close(),p.current=null},[t.id]),(0,i.useEffect)(()=>()=>{p.current?.close()},[]);let m=(0,i.useCallback)(()=>{p.current?.close(),o({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?(o({phase:"auth",url:r.url,instructions:r.instructions??null,token:r.token}),window.open(r.url,"_blank","noopener,noreferrer")):"device_code"===r.type?(o({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?o({phase:"prompt",message:r.message,placeholder:r.placeholder??null,token:r.token}):"select_request"===r.type?o({phase:"select",message:r.message,options:r.options??[],token:r.token}):"progress"===r.type?o({phase:"progress",message:r.message}):"success"===r.type?(e.close(),o({phase:"success"}),n()):"error"===r.type?(e.close(),o({phase:"error",message:r.message})):"cancelled"===r.type&&(e.close(),o({phase:"idle"}))},e.onerror=()=>{e.close(),o(e=>"success"===e.phase?e:{phase:"error",message:d("models.connectionLost")})}},[t.id,n,d]),g=(0,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(t.id)}`,{method:"POST"}),o({phase:"idle"}),n()},[t.id,n]),f=(0,i.useCallback)(async(e,n)=>{if(n.trim()){o({phase:"progress",message:d("models.verifying")});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,code:n.trim()})});if(!r.ok){let e=await r.json().catch(()=>({}));o({phase:"error",message:e.error??d("models.serverError",{status:r.status})});return}u("")}catch(e){o({phase:"error",message:e instanceof Error?e.message:d("i18n.networkError")})}}},[t.id,d]),x=(0,i.useCallback)(async(e,n)=>{o({phase:"progress",message:d("i18n.continuing")});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,code:n})});if(!r.ok){let e=await r.json().catch(()=>({}));o({phase:"error",message:e.error??d("models.serverError",{status:r.status})})}}catch(e){o({phase:"error",message:e instanceof Error?e.message:d("i18n.networkError")})}},[t.id,d]),b="connecting"===l.phase||"progress"===l.phase||"auth"===l.phase||"device_code"===l.phase||"prompt"===l.phase||"select"===l.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:t.loggedIn&&"idle"===l.phase?0:16},children:[(0,r.jsxs)(aj,{children:[(0,r.jsx)(aw,{children:(0,r.jsx)(lp,{children:d("i18n.subscription")})}),(0,r.jsxs)(aS,{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:t.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:t.loggedIn?"#4ade80":"var(--text-dim)"},children:t.loggedIn?d("i18n.connected"):d("i18n.notConnected")})]}),b?(0,r.jsx)(aB,{size:"small",onClick:()=>{p.current?.close(),o({phase:"idle"})},children:d("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(aB,{variant:"primary",size:"small",onClick:m,children:t.loggedIn?d("i18n.relogin"):d("i18n.login")}),t.loggedIn&&(0,r.jsx)(aB,{variant:"danger",size:"small",onClick:g,children:d("i18n.disconnect")})]})]})]}),(0,r.jsxs)("div",{style:{minHeight:t.loggedIn&&"idle"===l.phase?0:48},children:["idle"===l.phase&&!t.loggedIn&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:d("models.oauthConnect",{provider:t.name})}),"connecting"===l.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:d("i18n.openingBrowser")}),"select"===l.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:l.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:l.options.map(e=>(0,r.jsx)("button",{onClick:()=>x(l.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"===l.phase||"prompt"===l.phase)&&(0,r.jsx)(a2,{message:"auth"===l.phase?d("models.oauthPasteRedirect"):l.message,hint:"auth"===l.phase?(0,r.jsxs)(r.Fragment,{children:[d("models.oauthNoBrowser")," ",(0,r.jsx)("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",children:d("models.oauthOpenLoginPage")}),d("models.oauthOpenLoginPageEnd")]}):void 0,value:c,placeholder:"auth"===l.phase?"http://localhost:1455/auth/callback?code=…":l.placeholder??d("models.oauthValuePlaceholder"),submitLabel:d("i18n.submit"),inputRef:h,onValueChange:u,onSubmit:()=>void f(l.token,c)}),"device_code"===l.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:d("models.oauthDeviceCode")}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:l.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:l.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:l.verificationUri}),l.expiresInSeconds?` ${d("models.deviceCodeExpires",{minutes:Math.ceil(l.expiresInSeconds/60)})}`:""]})]}),"progress"===l.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:l.message}),"success"===l.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:d("i18n.connectedSuccessfully")}),"error"===l.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:l.message})]}),(0,r.jsx)(a5,{providerId:t.id,enabled:t.loggedIn}),t.loggedIn&&(0,r.jsx)(a1,{providerId:t.id,controller:s,contextSettings:a})]})}let lS="http://127.0.0.1:8080";function lC(e){let{provider:t,onRefresh:n,enabledModels:s,contextSettings:a,definition:l}=e,o=t.id===sZ,[d,c]=(0,i.useState)(o&&!t.configured?lS:""),[u,p]=(0,i.useState)(""),[h,m]=(0,i.useState)(!1),[g,f]=(0,i.useState)(!1),[x,b]=(0,i.useState)(null),[v,y]=(0,i.useState)(!1),{t:k}=(0,eX.s)(),j=!!(o?d.trim():u.trim());async function w(){if(j&&!h){m(!0),b(null),y(!1);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:u.trim(),...o?{serverUrl:d.trim()}:{}})}),r=await e.json();!e.ok||r.error?b(r.error??`HTTP ${e.status}`):(p(""),o&&(c(""),s.refresh(),r.catalog?.completed||b(k(r.catalog?.reason==="offline"?"models.catalogOffline":"models.catalogUnreachable"))),y(!0),setTimeout(()=>y(!1),2e3),n())}catch(e){b(String(e))}finally{m(!1)}}}let S=(0,i.useCallback)(async()=>{f(!0),b(null);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"DELETE"}),r=await e.json();!e.ok||r.error?b(r.error??`HTTP ${e.status}`):n()}catch(e){b(String(e))}finally{f(!1)}},[t.id,n]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(aj,{children:[(0,r.jsx)(aw,{children:(0,r.jsx)(lp,{children:o?t.displayName:"API Key"})}),(0,r.jsxs)(aS,{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:t.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:t.configured?"#4ade80":"var(--text-dim)"},children:t.configured?k("i18n.configured"):k("i18n.notConfigured")})]}),t.configured&&(0,r.jsx)(aB,{variant:"danger",size:"small",onClick:S,disabled:g,children:g?k("i18n.removing"):k("i18n.disconnect")})]})]}),o&&(0,r.jsxs)("label",{style:{display:"grid",gap:6},children:[k("models.llamaRouterUrl"),(0,r.jsx)("input",{type:"url",style:la,value:d,placeholder:lS,onChange:e=>c(e.target.value),spellCheck:!1})]}),!o&&!t.configured&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:1===t.modelCount?k("models.apiKeyEnableOne",{provider:t.displayName}):k("models.apiKeyEnable",{provider:t.displayName,count:t.modelCount})}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(lo,{value:u,onChange:p,onKeyDown:e=>{"Enter"===e.key&&w()},placeholder:o?k("models.optionalApiKey"):t.configured?k("models.replaceApiKey"):"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:w,disabled:h||!j||v,style:{padding:"6px 12px",background:v?"#16a34a":j?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:v?"#fff":j?"var(--accent-contrast)":"var(--text-dim)",cursor:h||!j||v?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[v&&(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"})}),v?k("i18n.saved"):h?k("i18n.saving"):k("i18n.save")]})]}),x&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:x}),(0,r.jsx)(a5,{providerId:t.id,enabled:t.configured}),t.configured&&(0,r.jsx)(a1,{providerId:t.id,controller:s,contextSettings:a,emptyCatalogHint:o?k("models.llamaEmptyCatalog"):void 0}),l&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{borderTop:"1px solid var(--border)"}}),(0,r.jsx)(lh,{name:t.id,editingName:t.id,fallbackLabel:l.fallbackLabel,provider:l.entry,onChange:l.update,onEditingNameChange:()=>{},onRename:()=>{},onDelete:l.remove,onAddModels:l.addModels,enabledModels:s,managedCredential:!0})]})]})}function lN(e){let{oauthProviders:t,apiKeyProviders:n,onSelectOAuth:s,onSelectApiKey:a,onAddCustom:l,onClose:o}=e,[d,c]=(0,i.useState)(""),{t:u}=(0,eX.s)(),p=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>p.current?.focus(),30)},[]);let h=d.trim().toLowerCase(),m=t.filter(e=>!e.loggedIn&&as(h,e.id,e.name)),g=n.filter(e=>!e.configured&&as(h,e.id,e.displayName)),f=!h||"custom".includes(h)||"openai-compatible".includes(h)||"anthropic-compatible".includes(h),x=m.length+g.length+ +!!f,b={display:"flex",flexDirection:"row",alignItems:"center",gap:8,padding:"10px 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:7,boxSizing:"border-box",cursor:"pointer",minWidth:0,textAlign:"left",transition:"border-color 0.12s, background 0.12s",width:"100%"};return(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&o()},onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.preventDefault(),e.stopPropagation(),o())},children:(0,r.jsxs)("div",{style:{width:820,maxWidth:"calc(100vw - 32px)",maxHeight:"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{ref:p,value:d,onChange:e=>c(e.target.value),placeholder:u("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===x?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:u("i18n.noProviders")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[f&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:u("i18n.custom")}),f&&(0,r.jsxs)("button",{onClick:()=>{l(),o()},style:b,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:u("i18n.customEndpoint")})]}),(0,r.jsx)("span",{style:{width:26,height:26,borderRadius:5,background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),m.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!f,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:u("i18n.subscriptions")}),m.map(e=>(0,r.jsxs)("button",{onClick:()=>{s(e.id),o()},style:b,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(a8,{id:e.id,size:28})]},e.id)),g.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(m.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),g.map(e=>(0,r.jsxs)("button",{onClick:()=>{a(e.id),o()},style:b,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:e.id===sZ?u("models.optionalApiKey"):u(1===e.modelCount?"models.modelCountOne":"models.modelCount",{count:e.modelCount})})]}),(0,r.jsx)(a8,{id:e.id,size:28})]},e.id))]})})]})})}function lI(e){let{onClose:t,embedded:n=!1,cwd:s=null}=e,{t:a}=(0,eX.s)(),{openDetail:l,closeDetail:o}=ac(),d=function(e){let[t,n]=(0,i.useState)(null),[r,s]=(0,i.useState)(!0),[a,l]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),c=(0,i.useRef)(null),u=(0,i.useRef)(null),p=(0,i.useRef)(null),[h,m]=(0,i.useState)(0);(0,i.useEffect)(()=>{let t=new AbortController;s(!0);let r=e?`?cwd=${encodeURIComponent(e)}`:"";return fetch(`/api/models/enabled${r}`,{signal:t.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);n(t),d(null)}).catch(e=>{t.signal.aborted||d({message:e instanceof Error?e.message:String(e)})}).finally(()=>{t.signal.aborted||s(!1)}),()=>t.abort()},[e,h]);let g=(0,i.useCallback)((t,r)=>{if(c.current){u.current={key:t,body:r};return}c.current=t,l(t),d(null),(async()=>{try{let t=await fetch("/api/models/enabled",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...e?{cwd:e}:{}})}),i=await t.json();if(!t.ok||i.error){let e=i.reason?aG[i.reason]:void 0;d(e?{messageKey:e}:{message:i.error??`HTTP ${t.status}`});return}n(i)}catch(e){d({message:e instanceof Error?e.message:String(e)})}finally{c.current=null,l(null);let e=u.current;u.current=null,e&&p.current?.(e.key,e.body)}})()},[e]);p.current=g;let f=(0,i.useCallback)((e,t,n)=>{g(e,{op:"models",refs:t,enabled:n})},[g]),x=(0,i.useCallback)((e,t)=>{g(`provider:${e}`,{op:"provider",provider:e,enabled:t})},[g]),b=(0,i.useCallback)(()=>g("clear",{op:"clear"}),[g]),v=(0,i.useCallback)(()=>g("prune",{op:"prune"}),[g]),y=(0,i.useCallback)(()=>m(e=>e+1),[]),k=(0,i.useCallback)((e,n)=>{g("resync",{op:"resync",renames:e,modelRenames:n,fullyEnabled:(t?.providers??[]).filter(e=>e.models.length>0&&e.enabledCount===e.models.length).map(e=>e.id)})},[g,t]);return{view:t,loading:r,pending:a,failure:o,setModels:f,setProvider:x,clearScope:b,pruneStale:v,refresh:y,resync:k}}(s),[c,u]=(0,i.useState)({providers:{}}),[p,h]=(0,i.useState)(!0),[m,g]=(0,i.useState)(!1),[f,x]=(0,i.useState)(null),[b,v]=(0,i.useState)(null),[y,k]=(0,i.useState)(!1),[j,w]=(0,i.useState)(le),[S,C]=(0,i.useState)([]),[N,I]=(0,i.useState)([]),[E,$]=(0,i.useState)({}),[T,M]=(0,i.useState)(()=>new Map),[R,A]=(0,i.useState)(!1),[L,P]=(0,i.useState)(!1),z=(0,i.useRef)(new Set),O=(0,i.useRef)(new Map),W=(0,i.useRef)(new Map),F=(0,i.useRef)(new WeakMap),D=(0,i.useRef)(0),B=(0,i.useRef)(null),[H,_]=(0,i.useState)(null),[U,K]=(0,i.useState)(null),q=(0,i.useCallback)(()=>fetch("/api/auth/providers").then(e=>e.json()).then(e=>(Array.isArray(e.oauthProviders)&&C(e.oauthProviders),Array.isArray(e.apiKeyProviders)&&I(e.apiKeyProviders),$(e.providerNames??{}),!0)).catch(()=>!1).finally(()=>A(!0)),[]);(0,i.useEffect)(()=>{fetch("/api/models-config").then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);return t}).then(e=>{let t=e.providers?e:{...e,providers:{}};u(t),z.current=new Set(Object.keys(t.providers??{})),W.current=at(t),M(al(t));let n=Object.keys(t.providers??{});w(e=>e&&("provider"===e.type?t.providers?.[e.name]:"model"!==e.type||t.providers?.[e.providerName]?.models?.[e.index])?e:n[0]?{type:"provider",name:n[0]}:null)}).catch(e=>v(e instanceof Error?e.message:String(e))).finally(()=>h(!1)),q()},[q]),(0,i.useEffect)(()=>{j&&sK("models",JSON.stringify(j))},[j]),(0,i.useEffect)(()=>{if(j?.type!=="provider")return;let e=c.providers?.[j.name];!(!e||!lt(e)||T.has(j.name))&&(S.some(e=>e.id===j.name)?w({type:"oauth",providerId:j.name}):N.some(e=>e.id===j.name)&&w({type:"apikey",providerId:j.name}))},[N,c.providers,S,T,j]);let Z=e=>({overrides:c.providers?.[e]?.modelOverrides,disabled:p||m||null!==b,onChange:(t,n)=>{try{u(function(e,t,n,r){let i={...e.providers},s={...Object.hasOwn(i,t)?i[t]:{}},a={...s.modelOverrides},l=Object.hasOwn(a,n)?a[n]:void 0;if(void 0!==l&&!sV(l))throw Error("Model override must be an object");let o={...l};return void 0===r?delete o.contextWindow:o.contextWindow=r,Object.keys(o).length?Object.defineProperty(a,n,{value:o,enumerable:!0,configurable:!0}):delete a[n],Object.keys(a).length?s.modelOverrides=a:delete s.modelOverrides,Object.keys(s).length?Object.defineProperty(i,t,{value:s,enumerable:!0,configurable:!0}):delete i[t],{...e,providers:i}}(c,e,t,n)),k(!1),x(null)}catch(e){x(String(e))}}}),V=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;c.providers?.[e];)e=`new-provider-${t++}`;u(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),w({type:"provider",name:e})},[c.providers]),J=(0,i.useCallback)((e,t)=>{u(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),G=(0,i.useCallback)((e,t,n)=>{let r=function(e,t,n,r){let i=e.providers??{};if(!Object.hasOwn(i,n))return null;if(n===r)return e;if(Object.hasOwn(i,r))return null;let{renames:s,slots:a}=t,l=ai(t,n);l===r?s.delete(l):null!==l&&s.set(l,r);let o=a.get(n);o&&(a.delete(n),a.set(r,o));let d=Object.entries(i),c=d.findIndex(e=>{let[t]=e;return t===n});return d[c]=[r,d[c][1]],{...e,providers:Object.fromEntries(d)}}(e,{savedProviders:z.current,renames:O.current,slots:W.current},t,n);return r?(u(r),K(null),w(e=>e?"provider"===e.type&&e.name===t?{type:"provider",name:n}:"model"===e.type&&e.providerName===t?{...e,providerName:n}:e:e),r):null},[]),Y=(0,i.useCallback)((e,t)=>{G(c,e,t)?x(null):x(a("models.providerIdTaken",{name:t}))},[G,c,a]),X=(0,i.useCallback)(e=>{var t;let n,r,i=(null!==(n=ai(t={savedProviders:z.current,renames:O.current,slots:W.current},e))&&(t.renames.delete(n),t.savedProviders.delete(n)),t.slots.delete(e),r={...c.providers??{}},delete r[e],{...c,providers:r}),s=Object.keys(i.providers??{});K(t=>t?.provider===e?null:t),u(i),w(s.length>0?{type:"provider",name:s[0]}:null),o()},[c,o]),Q=(0,i.useCallback)(e=>{an(W.current,e,1),u(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),u(t=>{let n=(t.providers?.[e]?.models?.length??1)-1;return w({type:"model",providerName:e,index:n}),t})},[]),ee=(0,i.useCallback)((e,t)=>{u(n=>{let r=new Set((n.providers?.[e]?.models??[]).map(e=>e.id));an(W.current,e,t.filter(e=>!r.has(e.id)).length);let i=n.providers?.[e]??{},s=[...i.models??[]],a=new Set(s.map(e=>e.id));for(let e of t)a.has(e.id)||(a.add(e.id),s.push({...e}));return{...n,providers:{...n.providers??{},[e]:{...i,models:s}}}})},[]),et=(0,i.useCallback)((e,t,n)=>{u(r=>{let i=r.providers?.[e]??{},s=[...i.models??[]],a=F.current.get(s[t]);return a&&F.current.set(n,a),s[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:s}}}})},[]),en=(0,i.useCallback)(e=>{e&&(u(e.config),k(!1),x(null),w(t=>t?.type==="model"&&t.providerName===e.providerName?{...t,index:e.order.indexOf(t.index)}:t))},[]),er=(0,i.useCallback)((e,t,n)=>{m||b||en(function(e,t,n,r,i){let s=e.providers?.[n]?.models??[];if(r<0||r>=s.length||i<0||i>=s.length)return null;let a=[...s.keys()];return a.splice(r,1),a.splice(i,0,r),ar(e,t,n,a)}(c,W.current,e,t,n))},[en,c,b,m]),ei=(0,i.useCallback)(e=>{if(!m&&!b){var t;let n,r;en((t=W.current,n=c.providers?.[e]?.models??[],r=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),ar(c,t,e,[...n.keys()].sort((e,t)=>r.compare(aa(n[e]),aa(n[t]))))))}},[en,c,b,m]),es=(0,i.useCallback)((e,t)=>{W.current.get(e)?.splice(t,1),u(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]];return i.splice(t,1),{...n,providers:{...n.providers??{},[e]:{...r,models:i.length?i:void 0}}}}),w({type:"provider",name:e}),o()},[o]),ea=(0,i.useCallback)(async()=>{if(b)return;g(!0),x(null),k(!1);let e=c,t=U?.name.trim();if(U&&t&&c.providers?.[U.provider]){let n=G(c,U.provider,t);if(!n){x(a("models.providerIdTaken",{name:t})),g(!1);return}e=n}try{var n=e=function(e){let t=structuredClone(e);if(!sV(t.providers))return t;for(let[e,n]of Object.entries(t.providers))if(sV(n)&&sV(n.modelOverrides))for(let[t,r]of Object.entries(n.modelOverrides)){if(!sV(r)||!Object.hasOwn(r,"contextWindow"))continue;let n=sG(r.contextWindow);if(void 0===n)throw new sJ(`${e}/${t}`);r.contextWindow=n}return t}(e);if(sQ(n.providers))for(let[e,t]of Object.entries(n.providers)){if(!sQ(t))continue;if(t.oauth&&!t.baseUrl)throw new sX(e,"baseUrl");let n=Array.isArray(t.models)&&t.models.some(s0),r=sQ(t.modelOverrides)&&Object.keys(t.modelOverrides).length>0;if(!n&&!t.baseUrl&&!t.headers&&!t.compat&&!r&&!t.apiKey&&!t.oauth&&void 0===t.authHeader)throw new sX(e,"empty")}var r=e;if(s1(r.providers)){for(let[e,t]of Object.entries(r.providers))if(s1(t)&&Array.isArray(t.models))for(let n of t.models){if(!s1(n)||"string"==typeof n.id&&!n.id.trim())continue;let t=s2(n);if(void 0!==t&&void 0===s4(t))throw new s6(`${e}/${"string"==typeof n.id?n.id:"?"}`)}}let t=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),i=await t.json();if(!t.ok||i.error)x(i.error??`HTTP ${t.status}`);else{k(!0),setTimeout(()=>k(!1),2e3);let t=[...O.current].map(e=>{let[t,n]=e;return{from:t,to:n}}),n=function(e,t,n){let r=e=>{for(let[t,r]of n)if(r===e)return t;return e},i=[];for(let[n,s]of Object.entries(e.providers??{})){let e=t.get(n);e&&(s.models??[]).forEach((t,s)=>{let a=e[s];a&&t.id&&a!==t.id&&i.push({from:`${r(n)}/${a}`,to:`${n}/${t.id}`})})}return i}(e,W.current,O.current);z.current=new Set(Object.keys(e.providers??{})),W.current=at(e),O.current.clear(),d.resync(t,n);let r=al(e);q().then(e=>{e&&M(r)})}}catch(e){e instanceof sX?(x(a(li[e.problem],{provider:e.provider})),w({type:"provider",name:e.provider})):e instanceof sJ?x(a("models.contextInvalid",{model:e.model})):x(e instanceof s6?a("models.imageMaxBytesInvalid",{model:e.model}):String(e))}finally{g(!1)}},[G,c,d,b,U,q,a]),el=Object.entries(c.providers??{}).filter(e=>{let[t,n]=e;if(N.some(e=>e.id===t&&e.configured))return!1;if(!lt(n)||T.has(t))return!0;let r=S.some(e=>e.id===t)||N.some(e=>e.id===t);return R&&!r}),eo=(e,t)=>{var n,r,i;return n=E[e]??d.view?.providers.find(t=>t.id===e)?.name,i=void 0!==(r=T.get(e))&&n?.trim()===r.trim()?void 0:n,t.name?.trim()||i?.trim()||e},ed=e=>{let t=function(e,t){if(!e||e.allEnabled)return null;let n=aV(e,t);return n?`${n.enabledCount}/${n.models.length}`:null}(d.view,e);return t?(0,r.jsx)("span",{className:"models-sidebar-badge",children:t}):null},ec=S.filter(e=>e.loggedIn),eu=N.filter(e=>e.configured),ep=e=>{let t=c.providers?.[e.id];return(0,r.jsx)(lC,{provider:e,onRefresh:q,enabledModels:d,contextSettings:Z(e.id),definition:t?{entry:t,fallbackLabel:eo(e.id,{}),update:t=>J(e.id,t),remove:()=>X(e.id),addModels:t=>ee(e.id,t)}:void 0},e.id)},eh=(()=>{if(!j)return null;if("oauth"===j.type){let e=S.find(e=>e.id===j.providerId);return e?(0,r.jsx)(lw,{provider:e,onRefresh:q,enabledModels:d,contextSettings:Z(e.id)},e.id):null}if("apikey"===j.type){let e=N.find(e=>e.id===j.providerId);return e?ep(e):null}if("provider"===j.type){let e=N.find(e=>e.id===j.name&&e.configured);if(e)return ep(e);let t=c.providers?.[j.name];return t&&el.some(e=>{let[t]=e;return t===j.name})?(0,r.jsx)(lh,{name:j.name,editingName:U?.provider===j.name?U.name:j.name,fallbackLabel:eo(j.name,{}),provider:t,onChange:e=>J(j.name,e),onEditingNameChange:e=>K(e===j.name?null:{provider:j.name,name:e}),onRename:e=>Y(j.name,e),onDelete:()=>X(j.name),onAddModels:e=>ee(j.name,e),enabledModels:d},j.name):null}let e=c.providers?.[j.providerName],t=e?.models?.[j.index];return t?(0,r.jsx)(lj,{providerName:j.providerName,provider:e,model:t,onChange:e=>et(j.providerName,j.index,e),onDelete:()=>es(j.providerName,j.index)},`${j.providerName}-${j.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(ao,{embedded:n,title:a("common.models"),subtitle:"~/.pi/agent/models.json",closeLabel:a("i18n.close"),onClose:t,children:[(0,r.jsx)(aY,{controller:d}),(0,r.jsxs)(ah,{children:[(0,r.jsxs)(am,{children:[(0,r.jsxs)(ag,{children:[ec.map(e=>{let t=j?.type==="oauth"&&j.providerId===e.id;return(0,r.jsxs)(av,{active:t,onClick:()=>w({type:"oauth",providerId:e.id}),children:[(0,r.jsx)(a8,{id:e.id,size:16}),(0,r.jsx)(ay,{className:"is-grow",children:e.name}),ed(e.id)]},e.id)}),eu.map(e=>{let t=j?.type==="apikey"&&j.providerId===e.id;return(0,r.jsxs)(av,{active:t,onClick:()=>w({type:"apikey",providerId:e.id}),children:[(0,r.jsx)(a8,{id:e.id,size:16}),(0,r.jsx)(ay,{className:"is-grow",children:e.displayName}),ed(e.id)]},e.id)}),(ec.length>0||eu.length>0)&&el.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),p?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:a("i18n.loading")}):el.map(e=>{let[t,n]=e,i=j?.type==="provider"&&j.name===t,s=n.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)(av,{onClick:()=>w({type:"provider",name:t}),active:i,children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)(ay,{className:"is-grow",children:eo(t,n)}),ed(t)]}),s.map((e,n)=>{var i;let s,l,o=j?.type==="model"&&j.providerName===t&&j.index===n,d=F.current.get(e);d||(d=`model-${++D.current}`,F.current.set(e,d));let c=H?.providerName===t&&H.index===n?H:null;return(0,r.jsxs)(av,{active:o,className:"models-sidebar-indented-item",style:c?{boxShadow:`inset 0 ${c.after?"-2px":"2px"} 0 var(--accent)`}:void 0,"aria-keyshortcuts":"Alt+ArrowUp Alt+ArrowDown",onClick:()=>w({type:"model",providerName:t,index:n}),onKeyDown:e=>{if(!e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let r="ArrowUp"===e.key?-1:"ArrowDown"===e.key?1:null;null!==r&&(e.preventDefault(),er(t,n,n+r))},...(i=e.id,s=e=>{var r;let i,s=B.current;if(s?.providerName!==t)return null;let a=e.currentTarget.getBoundingClientRect(),l=e.clientY>=a.top+a.height/2;return{from:s.index,to:(r=s.index,r<(i=l?n+1:n)?i-1:i),after:l}},{draggable:!m&&!b,onDragStart:e=>{B.current={providerName:t,index:n},e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",i)},onDragOver:e=>{let r=s(e);if(!r)return;e.preventDefault(),e.dataTransfer.dropEffect="move";let i=r.to===r.from?null:{providerName:t,index:n,after:r.after};_(e=>e?.providerName===i?.providerName&&e?.index===i?.index&&e?.after===i?.after?e:i)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||_(e=>e?.providerName===t&&e.index===n?null:e)},onDrop:e=>{let n=s(e);n&&(e.preventDefault(),er(t,n.from,n.to),l())},onDragEnd:l=()=>{B.current=null,_(null)}}),children:[(0,r.jsx)(ay,{className:"is-grow",style:{color:e.id?"var(--text-muted)":"var(--text-dim)"},children:aa(e)||a("i18n.newModel")}),e.reasoning&&(0,r.jsx)("span",{style:{fontSize:9,padding:"1px 4px",background:"rgba(99,102,241,0.12)",color:"rgba(99,102,241,0.8)",borderRadius:3,flexShrink:0},children:"T"})]},d)}),(0,r.jsxs)("div",{className:"models-sidebar-model-footer",children:[(0,r.jsx)(av,{className:"models-sidebar-indented-item models-sidebar-add-item",onClick:e=>{e.stopPropagation(),Q(t)},children:(0,r.jsxs)(ay,{children:["+ ",a("i18n.model")]})}),(0,r.jsx)("button",{type:"button",className:"models-sidebar-sort-button","aria-label":a("models.sortByName"),title:a("models.sortByName"),disabled:m||null!==b||s.length<2,onClick:()=>ei(t),children:"A–Z"})]})]},t)})]}),(0,r.jsx)(a_,{onClick:e=>{e.preventDefault(),P(!0)},children:a("i18n.addProvider")})]}),(0,r.jsx)(aW,{children:(0,r.jsx)(ak,{className:"is-fill",children:p?null:eh??(0,r.jsx)(aO,{children:a("i18n.selectProviderModel")})})})]}),(0,r.jsxs)(aF,{status:b||f?(0,r.jsx)("span",{style:{color:"#f87171"},children:b?a("models.configUnreadable",{error:b}):f}):a("models.applyHelp"),children:[!n&&(0,r.jsx)(aB,{onClick:t,children:a("i18n.cancel")}),(0,r.jsxs)(aB,{variant:"primary",onClick:ea,disabled:m||y||null!==b,className:y?"is-success":void 0,children:[y&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:y?a("i18n.saved"):m?a("i18n.saving"):a("i18n.save")})]})]})]}),L&&(0,r.jsx)(lN,{oauthProviders:S,apiKeyProviders:N,onSelectOAuth:e=>{w({type:"oauth",providerId:e}),l()},onSelectApiKey:e=>{w({type:"apikey",providerId:e}),l()},onAddCustom:()=>{V(),l()},onClose:()=>P(!1)})]})}let lE=null;async function l$(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(lE)return lE;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 lE=null,!1}})();return lE=t,t.then(e=>{e||lE!==t||(lE=null)}),t}var lT=n(9258);function lM(e,t,n,r){return e.filter(e=>n(e)!==t&&(t||!r?.(e)))}function lR(e){return e?JSON.stringify([e.requiresTrust,e.trusted,e.decision,e.decisionPath??null,e.inherited]):""}function lA(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function lL(e,t){return t("project"===e?"skills.scope.project":"global"===e?"skills.scope.global":"skills.scope.path")}function lP(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function lz(e,t){return e?e.slice(0,8):t}function lO(e){let{skill:t,cwd:n,onToggle:s,toggling:a,saveError:l,updateStatus:o,checkingUpdate:d,updating:c,updateError:u,onCheckUpdate:p,onUpdate:h}=e,{t:m}=(0,eX.s)(),g=lA(t),f=!t.disableModelInvocation,[x,b]=(0,i.useState)(null),[v,y]=(0,i.useState)(null),k=t.filePath.split(/[\\/]/).pop(),[j,w]=(0,i.useState)([]),S=j.at(-1)??k,C=(0,i.useRef)(null),N=(0,i.useRef)(null),[I,E]=(0,i.useState)(0),$=(0,i.useCallback)(e=>{let t=function(e,t){let n=e.indexOf("#"),[r,i]=[n<0?e:e.slice(0,n),n<0?"":e.slice(n+1)].map(e=>{try{return decodeURIComponent(e)}catch{return e}});if(!r)return{document:t,anchor:i};if(r.startsWith("/"))return{document:r,anchor:i};let s=t.split("/").slice(0,-1);for(let e of r.split("/"))".."===e&&s.length&&".."!==s[s.length-1]?s.pop():e&&"."!==e&&s.push(e);return{document:s.join("/"),anchor:i}}(e,S);N.current=t.anchor,t.document===S?E(e=>e+1):w(e=>[...e,t.document])},[S]);return(0,i.useLayoutEffect)(()=>{let e=N.current,t=C.current;null!==e&&(null!==x||v)&&t&&(N.current=null,((e?t.querySelector(`[data-heading-anchor="${CSS.escape(e)}"]`):null)??t).scrollIntoView({block:"start"}))},[x,v,I]),(0,i.useEffect)(()=>{let e=new AbortController;return b(null),y(null),(async()=>{try{let r=new URLSearchParams({cwd:n,filePath:t.filePath});S!==k&&r.set("document",S);let i=await fetch(`/api/skills/content?${r}`,{signal:e.signal}),s=await i.json();if(!i.ok||s.error||"string"!=typeof s.content)throw Error(s.error??`HTTP ${i.status}`);b(function(e,t){let n=(0,lT.yv)(e).rest.trim();if(!t)return n;let r=n.match(/^#{1,6}[ \t]+(.*?)[ \t]*#*[ \t]*(?:\r?\n|$)/);return r&&r[1].trim().toLowerCase()===t.trim().toLowerCase()?n.slice(r[0].length).trim():n}(s.content,S===k?t.name:void 0))}catch(t){if(e.signal.aborted)return;y(t instanceof Error?t.message:String(t))}})(),()=>e.abort()},[n,t.filePath,t.name,S,k]),(0,r.jsxs)(ak,{children:[(0,r.jsxs)("div",{className:"skill-detail-heading",children:[(0,r.jsxs)(aj,{children:[(0,r.jsxs)(aw,{children:[(0,r.jsx)(aT,{scope:g,children:lL(g,m)}),(0,r.jsx)("span",{className:"config-detail-path",children:"project"===g?eh(t.filePath,n):ep(t.filePath)})]}),(0,r.jsx)(aS,{children:(0,r.jsx)(aH,{checked:f,loading:a,label:m(f?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),onChange:()=>s(t)})})]}),(0,r.jsxs)("div",{className:"skill-detail-status-row",children:[!f&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:m("i18n.hiddenButInvocable")}),l&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:l})]})]}),t.install?.skillsShUrl&&(0,r.jsx)(aI,{label:m("config.source"),children:(0,r.jsx)("a",{href:t.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:t.install.skillsShUrl,className:"skill-source-link",children:(0,r.jsxs)("span",{className:"skill-source-link-text",children:[t.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})}),t.install&&(0,r.jsxs)(aI,{label:m("i18n.version"),children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:lz(o?.currentVersion??t.install.versionHash,m("i18n.unknown"))}),t.install.canCheckForUpdates&&(0,r.jsx)(aB,{size:"small",onClick:p,disabled:d||c,children:m("i18n.check")}),o?.state==="update-available"&&(0,r.jsx)("span",{className:"skill-version-value is-update",children:lz(o.latestVersion,m("i18n.unknown"))}),(d||o&&"update-available"!==o.state)&&(0,r.jsx)("span",{className:`skill-update-status ${d?"is-checking":o?.state==="up-to-date"?"is-success":o?.state==="error"?"is-error":"is-muted"}`,children:d?m("i18n.checking"):o?.state==="up-to-date"?m("i18n.upToDate"):o?.state==="unsupported"?m("i18n.automaticChecksUnavailable"):o?.message||m("i18n.checkFailed")}),o?.state==="update-available"&&(0,r.jsx)(aB,{variant:"primary",size:"small",onClick:h,disabled:c||d,children:m(c?"i18n.updating":"i18n.update")})]}),u&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:u})]}),(0,r.jsx)(aI,{label:m("config.name"),children:(0,r.jsx)("span",{className:"skill-name-value",children:t.name})}),(0,r.jsx)(aI,{label:m("i18n.description"),children:(0,r.jsx)("span",{className:"skill-description",children:t.description})}),(0,r.jsxs)(aI,{label:m("skills.instructions"),ref:C,children:[j.length>0&&(0,r.jsx)(aj,{children:(0,r.jsxs)(aw,{children:[(0,r.jsx)(aB,{size:"small",onClick:()=>{N.current="",w(e=>e.slice(0,-1))},children:m("skills.documentBack")}),(0,r.jsx)("span",{className:"config-detail-path",title:S,children:S})]})}),v?(0,r.jsx)("span",{role:"alert",className:"skill-instructions-status is-error",children:v}):null===x?(0,r.jsx)("span",{role:"status",className:"skill-instructions-status",children:m("i18n.loading")}):x?(0,r.jsx)(nZ.m,{className:"skill-instructions",cwd:[t.baseDir,...S.split("/").slice(0,-1)].join("/"),onNavigateLink:$,children:x}):(0,r.jsx)("span",{className:"skill-instructions-status",children:m("skills.noInstructions")})]})]})}function lW(e){let{cwd:t,installedPackages:n,projectResourcesLoaded:s,onInstalled:a}=e,{t:l}=(0,eX.s)(),[o,d]=(0,i.useState)(""),[c,u]=(0,i.useState)([]),[p,h]=(0,i.useState)(!1),[m,g]=(0,i.useState)(null),[f,x]=(0,i.useState)(null),[b,v]=(0,i.useState)(null),[y,k]=(0,i.useState)(new Set),[j,w]=(0,i.useState)("global"),S=(0,i.useRef)(null);(0,i.useEffect)(()=>{S.current?.focus()},[]);let C=(0,i.useCallback)(async e=>{if(e.trim()){h(!0),g(null),u([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),n=await t.json();if(n.error)return void g(n.error);u(n.results??[]),0===(n.results??[]).length&&g(l("i18n.noSkills"))}catch(e){g(String(e))}finally{h(!1)}}},[l]),N=(0,i.useCallback)(async e=>{x(e),v(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:e,scope:j,cwd:t})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);k(t=>new Set(t).add(`${j}:${e}`)),a()}catch(e){v(String(e))}finally{x(null)}},[a,j,t]),I="global"===j?"~/.pi/agent/skills/":`${ep(t)}/.pi/skills/`;return(0,r.jsxs)(ak,{className:"is-full-height",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)(aA,{title:l("i18n.addSkill"),catalogs:[{href:"https://skills.sh",label:"skills.sh"}],target:(0,r.jsx)(aR,{value:j,label:l("config.saveTo"),options:[{value:"global",label:lL("global",l)},{value:"project",label:lL("project",l),disabled:!s}],path:I,disabledReason:l("trust.projectScopeUnavailable"),onChange:w})}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:S,value:o,onChange:e=>d(e.target.value),onKeyDown:e=>{!e.nativeEvent.isComposing&&229!==e.keyCode&&("Enter"!==e.key||p||C(o))},placeholder:l("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)(aB,{variant:"primary",onClick:()=>C(o),disabled:p||!o.trim(),children:p?l("i18n.searching"):l("i18n.search")})]}),m&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:m}),b&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:b})]}),c.length>0&&(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:c.map(e=>{let t=n[j].has(e.package)||y.has(`${j}:${e.package}`),i=f===e.package,s=e.package.indexOf("@"),a=s>-1?e.package.slice(0,s):e.package,o=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:o??a}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:a}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,r.jsx)(aB,{size:"small",onClick:()=>!t&&!i&&N(e.package),disabled:t||i||null!==f,style:{flexShrink:0,background:t?"rgba(34,197,94,0.1)":"none",color:t?"#16a34a":i?"var(--accent)":"var(--text-muted)"},children:t?`✓ ${l("i18n.installed")}`:i?l("i18n.installing"):l("i18n.install")})]},e.package)})})]})}function lF(e){let{cwd:t,onClose:n,embedded:s=!1,trust:a}=e,{t:l}=(0,eX.s)(),[o,d]=(0,i.useState)([]),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(null),[m,g]=(0,i.useState)(()=>sU("skills",t)),[f,x]=(0,i.useState)(new Set),[b,v]=(0,i.useState)(null),[y,k]=(0,i.useState)(null),[j,w]=(0,i.useState)(null),[S,C]=(0,i.useState)(!1),[N,I]=(0,i.useState)({}),[E,$]=(0,i.useState)(new Set),[T,M]=(0,i.useState)(!1),[R,A]=(0,i.useState)(null),[L,P]=(0,i.useState)(null),[z,O]=(0,i.useState)(!0),W=(0,i.useCallback)(async()=>{u(!0),h(null);try{let e=await fetch(`/api/skills?cwd=${encodeURIComponent(t)}`),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);let r=n.skills??[];return d(r),O(n.projectResourcesLoaded??!0),g(e=>{if(e&&r.some(t=>t.filePath===e))return e;let t=r.find(e=>!e.disableModelInvocation)??r[0];return t?.filePath??null}),r}catch(e){return h(String(e)),[]}finally{u(!1)}},[t]);(0,i.useEffect)(()=>{I({}),P(null),W()},[t]);let F=lR(a),D=(0,i.useRef)(F);(0,i.useEffect)(()=>{D.current!==F&&(D.current=F,W())},[F,W]),(0,i.useEffect)(()=>{m&&sK("skills",m,t)},[t,m]);let B=(0,i.useCallback)(async e=>{let n=(e?[e]:o.filter(e=>!!e.install)).map(lP).filter(e=>!!e);if(0!==n.length){P(null),$(e=>new Set([...e,...n])),e||M(!0);try{let n=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,package:e?.install?.package,scope:e?.install?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);I(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){P(e instanceof Error?e.message:String(e))}finally{$(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),e||M(!1)}}},[t,o]),H=(0,i.useCallback)(async e=>{if(!e.install)return;let n=lP(e);A(n),P(null);try{let r=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,package:e.install.package,scope:e.install.scope})}),i=await r.json();if(!r.ok||i.error||!i.success)throw Error(i.error??`HTTP ${r.status}`);await W();let s=i.skill?.install?.versionHash;I(t=>({...t,[n]:{package:e.install.package,scope:e.install.scope,state:"up-to-date",currentVersion:s,latestVersion:s}}))}catch(e){P(e instanceof Error?e.message:String(e))}finally{A(null)}},[t,W]),_=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;x(t=>new Set(t).add(e.filePath)),v(null),w(null);try{let n=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);d(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n))}catch(e){v(String(e))}finally{x(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),U=(0,i.useCallback)(async(e,t,n)=>{let r=lM(t,n,e=>!e.disableModelInvocation);if(0===r.length)return;let i=r.map(e=>e.filePath),s=!n;x(e=>new Set([...e,...i])),k(e),v(null),w(null);try{let t=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePaths:i,disableModelInvocation:s})}),n=await t.json();if(!t.ok||n.error||!n.results)throw Error(n.error??`HTTP ${t.status}`);let a=n.results;d(e=>{let t;return t=new Set(a.filter(e=>!e.error).map(e=>e.filePath)),e.map(e=>t.has(e.filePath)?{...e,disableModelInvocation:s}:e)});let o=a.filter(e=>e.error);if(o.length>0){let t=new Map(r.map(e=>[e.filePath,e.name]));w({group:e,error:[l("skills.bulkFailed",{count:o.length,total:a.length}),...o.map(e=>`${t.get(e.filePath)??e.filePath}: ${e.error}`)].join("\n")})}}catch(t){w({group:e,error:t instanceof Error?t.message:String(t)})}finally{k(null),x(e=>{let t=new Set(e);for(let e of i)t.delete(e);return t})}},[l]),K=o.find(e=>e.filePath===m)??null,q=c||f.size>0||null!==R;return(0,r.jsxs)(ao,{embedded:s,title:l("common.skills"),subtitle:ep(t),closeLabel:l("i18n.close"),onClose:n,children:[!z&&(0,r.jsx)(az,{message:l("trust.skillsNotLoaded")}),(0,r.jsxs)(ah,{children:[(0,r.jsxs)(am,{children:[(0,r.jsx)(ag,{children:c?(0,r.jsx)("div",{className:"config-sidebar-message",children:l("i18n.loading")}):p?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:p}):0===o.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:l("i18n.noSkills")}):(()=>{let e=[],t={project:l("skills.scope.project"),global:l("skills.scope.global"),path:l("skills.scope.path")};for(let{label:n,matches:r}of[{label:`${t.project} / skills.sh`,matches:e=>"project"===lA(e)&&!!e.install?.skillsShUrl},{label:t.project,matches:e=>"project"===lA(e)&&!e.install?.skillsShUrl},{label:`${t.global} / skills.sh`,matches:e=>"global"===lA(e)&&!!e.install?.skillsShUrl},{label:t.global,matches:e=>"global"===lA(e)&&!e.install?.skillsShUrl},{label:t.path,matches:e=>"path"===lA(e)}]){let t=o.filter(r);t.length>0&&e.push({label:n,skills:t})}let n=e=>{let t,n,i=!S&&m===e.filePath,s=e.disableModelInvocation;return(0,r.jsxs)(av,{active:i,onClick:()=>{g(e.filePath),C(!1)},children:[(0,r.jsx)(aU,{active:!s}),(0,r.jsx)(ay,{className:`is-grow${s?" is-muted":""}`,children:e.name}),(n=(t=lP(e))?N[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:l("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"}))]},e.filePath)};return e.map(e=>{let{label:t,skills:i}=e,s=i.filter(e=>!e.disableModelInvocation).length,a=s===i.length;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(af,{aside:(0,r.jsx)(ax,{enabled:s,total:i.length,disabled:q,loading:y===t,label:l(a?"skills.groupSwitchOn":"skills.groupSwitchOff",{group:t}),onChange:e=>void U(t,i,e)}),children:t}),j?.group===t&&(0,r.jsx)(ab,{error:j.error}),[...i.filter(e=>!e.disableModelInvocation),...i.filter(e=>e.disableModelInvocation)].map(n)]},t)})})()}),(0,r.jsx)(a_,{onClick:()=>C(!0),active:S,children:l("i18n.addSkill")})]}),(0,r.jsx)(aW,{children:(0,r.jsx)(ak,{className:"is-fill",children:S?(0,r.jsx)(lW,{cwd:t,projectResourcesLoaded:z,installedPackages:{global:new Set(o.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(o.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{W()}}):c?null:K?(0,r.jsx)(lO,{skill:K,cwd:t,onToggle:_,toggling:f.has(K.filePath),saveError:b,updateStatus:lP(K)?N[lP(K)]:void 0,checkingUpdate:!!lP(K)&&E.has(lP(K)),updating:R===lP(K),updateError:L,onCheckUpdate:()=>void B(K),onUpdate:()=>void H(K)},K.filePath):(0,r.jsx)(aO,{children:l("i18n.selectSkill")})})})]}),(0,r.jsxs)(aF,{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?l("i18n.update"):l("i18n.updates")]}),children:[!s&&(0,r.jsx)(aB,{onClick:n,children:l("i18n.close")}),o.some(e=>!!e.install)&&(0,r.jsx)(aB,{variant:"secondary",onClick:()=>void B(),disabled:T||null!==R,children:T?l("i18n.checking"):l("i18n.checkUpdates")})]})]})}let lD={builtin:0,global:1,workspace:2,project:3},lB=["read","bash","edit","write","grep","find","ls"],lH=["","off","minimal","low","medium","high","xhigh","max"],l_={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},lU={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"},lK={background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"default"};function lq(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 lZ(e){return`${e.scope}:${e.name}`}function lV(e){return"global"===e||"project"===e}function lJ(e){return lV(e)||"builtin"===e}function lG(e){let{label:t,children:n}=e;return(0,r.jsx)(aI,{label:t,children:n})}function lY(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 lX(e){let{cwd:t,sessionId:n=null,onClose:s,onReloaded:a,embedded:l=!1,trust:o}=e,d=(0,eQ.a)(),{t:c}=(0,eX.s)(),[u,p]=(0,i.useState)([]),[h,m]=(0,i.useState)([]),[g,f]=(0,i.useState)(!0),[x,b]=(0,i.useState)(null),[v,y]=(0,i.useState)(()=>sU("agents",t)),[k,j]=(0,i.useState)(l_),[w,S]=(0,i.useState)("view"),[C,N]=(0,i.useState)("global"),[I,E]=(0,i.useState)(!0),[$,T]=(0,i.useState)(!1),[M,R]=(0,i.useState)(!1),[A,L]=(0,i.useState)(!1),[P,z]=(0,i.useState)(null),[O,W]=(0,i.useState)(!1),[F,D]=(0,i.useState)(10),[B,H]=(0,i.useState)(!0),[_,U]=(0,i.useState)(!1),[K,q]=(0,i.useState)(null),[Z,V]=(0,i.useState)(!1),[J,G]=(0,i.useState)(!1),Y=(0,i.useMemo)(()=>u.find(e=>lZ(e)===v)??null,[u,v]),X=(0,i.useMemo)(()=>h.map(e=>({provider:e.provider,providerName:e.providerName,modelId:e.id,name:e.name})),[h]),Q=(0,i.useCallback)(async e=>{E(!0),z(null);try{let n=await fetch(`/api/subagents/profiles?cwd=${encodeURIComponent(t)}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);let i=r.profiles??[];p(i);let s=e??sU("agents",t),a=i.find(e=>lZ(e)===s)??i.find(e=>"project"===e.scope)??i.find(e=>"global"===e.scope)??i[0]??null;y(a?lZ(a):null),a&&(j(lq(a)),S(lV(a.scope)?"edit":"view"),lV(a.scope)&&N(a.scope))}catch(e){z(e instanceof Error?e.message:String(e))}finally{E(!1)}},[t]);(0,i.useEffect)(()=>{Q()},[Q]),(0,i.useEffect)(()=>{let e=new AbortController;return H(!0),q(null),(async()=>{try{let t=await fetch("/api/subagents/settings",{cache:"no-store",signal:e.signal}),n=await t.json();if(!t.ok||n.error||"boolean"!=typeof n.enabled)throw Error(n.error??`HTTP ${t.status}`);W(n.enabled),"number"==typeof n.maxConcurrent&&D(n.maxConcurrent)}catch(t){if(e.signal.aborted)return;q(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||H(!1)}})(),()=>e.abort()},[]),(0,i.useEffect)(()=>{v&&sK("agents",v,t)},[t,v]);let ee=lR(o);(0,i.useEffect)(()=>{let e=new AbortController;return f(!0),b(null),(async()=>{try{let n=await fetch(`/api/models?cwd=${encodeURIComponent(t)}`,{signal:e.signal}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);m(r.modelList??[]),b(r.modelError??null)}catch(t){if(e.signal.aborted)return;b(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||f(!1)}})(),()=>e.abort()},[t,ee]);let et=async()=>{T(!0),z(null),R(!1);try{let e=await fetch("/api/subagents/profiles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:C,profile:k})}),n=await e.json();if(!e.ok||n.error||!n.profile)throw Error(n.error??`HTTP ${e.status}`);await Q(lZ(n.profile)),R(!0),setTimeout(()=>R(!1),2e3)}catch(e){z(e instanceof Error?e.message:String(e))}finally{T(!1)}},en=async()=>{if(Y&&lV(Y.scope)&&window.confirm(c("agents.deleteConfirm",{name:Y.displayName}))){T(!0),z(null);try{let e=await fetch("/api/subagents/profiles",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:Y.scope,name:Y.name})}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);await Q()}catch(e){z(e instanceof Error?e.message:String(e))}finally{T(!1)}}},er="view"!==w,ei="create"===w,es=!er||$||A,ea=ei?C:Y?.scope,el=ei?"global"===C?`~/.pi/agent/agents/${k.name||"..."}.md`:`./.pi/agents/${k.name||"..."}.md`:Y?(Y.filePath?"project"===Y.scope||"workspace"===Y.scope?eh(Y.filePath,t):ep(Y.filePath):null)??c("agents.builtinPath"):"",eo=ei?el:Y?.filePath??el,ed=e=>h.some(t=>`${t.provider}/${t.id}`===e),ec=k.model&&function(e,t){if(t(e))return e;let n=e.lastIndexOf(":"),r=e.slice(n+1);return n>0&&r&&lH.includes(r)?e.slice(0,n):e}(k.model,ed),eu=!ec||ed(ec),em=(()=>{if(!ec)return null;let e=ec.indexOf("/");return e<0?{provider:"",modelId:ec}:{provider:ec.slice(0,e),modelId:ec.slice(e+1)}})(),eg=es?{...lU,...lK}:lU,ef=ei?es:!Y||!lJ(Y.scope)||$||A,ex=(e,t)=>{j(n=>({...n,[e]:t}))},eb=0===k.tools.length&&!k.loadSkills&&!k.loadExtensions,ev=async e=>{if(ei)return void ex("enabled",e);if(Y&&lJ(Y.scope)){L(!0),z(null);try{let n=await fetch("/api/subagents/profiles",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:Y.scope,name:Y.name,enabled:e})}),r=await n.json();if(!n.ok||r.error||!r.profile)throw Error(r.error??`HTTP ${n.status}`);let i=r.profile;p(e=>e.map(e=>lZ(e)===lZ(i)?i:e)),j(e=>({...e,enabled:i.enabled}))}catch(e){z(e instanceof Error?e.message:String(e))}finally{L(!1)}}},ey=async e=>{U(!0),q(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),r=await t.json();if(!t.ok||r.error||"boolean"!=typeof r.enabled)throw Error(r.error??`HTTP ${t.status}`);W(r.enabled),V(!!n)}catch(e){q(e instanceof Error?e.message:String(e))}finally{U(!1)}},ek=async e=>{D(e),q(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxConcurrent:e})}),n=await t.json();if(!t.ok||n.error||"number"!=typeof n.maxConcurrent)throw Error(n.error??`HTTP ${t.status}`);D(n.maxConcurrent)}catch(e){q(e instanceof Error?e.message:String(e))}},ej=async()=>{if(n){G(!0),q(null);try{await iE(n,{type:"reload"}),V(!1),a?.()}catch(e){q(e instanceof Error?e.message:String(e))}finally{G(!1)}}};return(0,r.jsxs)(ao,{embedded:l,title:c("common.agents"),subtitle:ep(t),closeLabel:c("agents.close"),onClose:s,children:[(0,r.jsxs)("div",{className:"agents-feature-setting",children:[(0,r.jsxs)("div",{className:"agents-feature-copy",children:[(0,r.jsx)("strong",{children:c("agents.builtInTitle")}),(0,r.jsx)("span",{children:c("agents.builtInDescription")}),Z&&(0,r.jsx)("span",{role:"status",className:"agents-feature-reload-notice",children:c("agents.reloadRequired")})]}),(0,r.jsxs)("div",{className:"agents-feature-actions",children:[Z&&n&&(0,r.jsx)(aB,{size:"small",onClick:()=>void ej(),disabled:J||_,children:J?c("agents.reloading"):c("agents.reloadSession")}),(0,r.jsxs)("label",{className:"agents-concurrency-control",title:c("agents.maxConcurrentDescription"),children:[(0,r.jsx)("span",{children:c("agents.maxConcurrent")}),(0,r.jsx)("input",{"aria-label":c("agents.maxConcurrent"),type:"number",min:1,max:32,value:F,disabled:B||_,onChange:e=>D(Number(e.target.value)),onBlur:()=>void ek(F)})]}),(0,r.jsx)(aH,{checked:O,disabled:B||J,loading:_,label:c("agents.builtInTitle"),onChange:e=>void ey(e)})]})]}),(0,r.jsxs)(ah,{children:[(0,r.jsxs)(am,{children:[(0,r.jsx)(ag,{children:I?(0,r.jsx)("div",{style:{padding:10,color:"var(--text-dim)",fontSize:12},children:c("agents.loading")}):["project","global","workspace","builtin"].map(e=>{let t=u.filter(t=>t.scope===e);return 0===t.length?null:(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(af,{children:c(`agents.scope.${e}`)}),t.map(e=>{let t,n,i=(t=e.name.toLowerCase(),n=lD[e.scope],u.some(e=>e.name.toLowerCase()===t&&lD[e.scope]>n));return(0,r.jsxs)(av,{active:v===lZ(e)&&!ei,onClick:()=>{y(lZ(e)),j(lq(e)),S(lV(e.scope)?"edit":"view"),lV(e.scope)&&N(e.scope),z(null)},children:[(0,r.jsx)(aU,{active:e.enabled}),(0,r.jsx)(ay,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.displayName}),i&&(0,r.jsx)("span",{className:"agents-overridden-label",children:c("agents.overridden")})]},lZ(e))})]},e)})}),(0,r.jsx)(a_,{active:ei,onClick:()=>{let e="custom-agent",t=2;for(;u.some(t=>t.name===e);)e=`custom-agent-${t++}`;y(null),j({...l_,name:e,displayName:e}),S("create"),N("global"),z(null)},children:c("agents.new")})]}),(0,r.jsx)(aW,{children:(0,r.jsx)(ak,{className:"is-fill",children:Y||ei?(0,r.jsxs)(ak,{children:[(0,r.jsxs)(aj,{children:[(0,r.jsx)(aw,{children:ei?(0,r.jsx)(aR,{value:C,label:c("config.saveTo"),options:["global","project"].map(e=>({value:e,label:c(`agents.scope.${e}`),disabled:$})),path:el,onChange:N}):(0,r.jsxs)(r.Fragment,{children:[ea&&(0,r.jsx)(aT,{scope:ea,children:c(`agents.scope.${ea}`)}),(0,r.jsx)("span",{title:eo,className:"config-detail-path",children:el})]})}),(0,r.jsxs)(aS,{children:[Y&&("view"===w||"edit"===w)&&(0,r.jsx)(aB,{size:"small",onClick:()=>{if(!Y)return;let e=function(e,t){let n=new Set(t.map(e=>e.name.toLowerCase())),r=`${e}-copy`,i=r,s=2;for(;n.has(i.toLowerCase());)i=`${r}-${s++}`;return i}(Y.name,u);y(null),j({...lq(Y),name:e,displayName:c("agents.copyName",{name:Y.displayName})}),S("create"),N(lV(Y.scope)?Y.scope:"global"),z(null)},disabled:$||A,children:c("agents.duplicate")}),Y&&lV(Y.scope)&&"edit"===w&&(0,r.jsx)(aB,{variant:"danger",size:"small",onClick:()=>void en(),disabled:$||A,children:c("agents.delete")}),(0,r.jsx)(aH,{checked:k.enabled,disabled:ef,label:k.enabled?c("agents.disable"):c("agents.enable"),onChange:e=>void ev(e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:d?"1fr":"minmax(0, 1fr) minmax(0, 1fr)",gap:12},children:[(0,r.jsx)(lG,{label:c("agents.name"),children:ei?(0,r.jsx)("input",{"aria-label":c("agents.name"),value:k.name,disabled:es,onChange:e=>ex("name",e.target.value),style:lU}):(0,r.jsx)("code",{style:{minHeight:34,display:"flex",alignItems:"center",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:k.name})}),(0,r.jsx)(lG,{label:c("agents.displayName"),children:(0,r.jsx)("input",{"aria-label":c("agents.displayName"),value:k.displayName,disabled:es,onChange:e=>ex("displayName",e.target.value),style:eg})})]}),(0,r.jsx)(lG,{label:c("agents.description"),children:(0,r.jsx)("input",{"aria-label":c("agents.description"),value:k.description,disabled:es,onChange:e=>ex("description",e.target.value),style:eg})}),(0,r.jsx)(lG,{label:c("agents.prompt"),children:(0,r.jsx)("textarea",{className:"agents-system-prompt","aria-label":c("agents.prompt"),value:k.systemPrompt,disabled:es,onChange:e=>ex("systemPrompt",e.target.value),style:{...eg,height:195,minHeight:195,maxHeight:"60vh",padding:9,overflow:"auto",resize:es?"none":"vertical",lineHeight:1.5}})}),(0,r.jsx)(lG,{label:c("agents.tools"),children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 16px"},children:[...lB,...k.tools.filter(e=>"powershell"===e)].map(e=>(0,r.jsx)(lY,{label:e,disabled:es,checked:k.tools.includes(e),onChange:t=>ex("tools",t?[...k.tools,e]:k.tools.filter(t=>t!==e))},e))})}),(0,r.jsxs)(lG,{label:c("agents.resources"),children:[(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 20px"},children:[(0,r.jsx)(lY,{label:c("agents.loadSkills"),disabled:es,checked:k.loadSkills,onChange:e=>ex("loadSkills",e)}),(0,r.jsx)(lY,{label:c("agents.loadExtensions"),disabled:es,checked:k.loadExtensions,onChange:e=>ex("loadExtensions",e)}),(0,r.jsx)(lY,{label:c("agents.mcp"),disabled:es||eb&&"on"!==k.mcp,checked:"on"===k.mcp,onChange:e=>ex("mcp",e?"on":"off")})]}),k.loadSkills&&void 0!==k.skills&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:k.skills.length>0?c("agents.skillsOnly",{skills:k.skills.join(", ")}):c("agents.skillsNone")}),k.loadExtensions&&void 0!==k.extensions&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:k.extensions.length>0?c("agents.extensionsOnly",{extensions:k.extensions.join(", ")}):c("agents.extensionsNone")}),!es&&eb?(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:c("agents.mcpChatOnly")}):"on"===k.mcp&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:c("agents.mcpHint")})]}),(0,r.jsx)(lG,{label:c("agents.codemode"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[(0,r.jsxs)("select",{"aria-label":c("agents.codemode"),value:k.codemode??"off",disabled:es,onChange:e=>ex("codemode",e.target.value),style:{...eg,width:"auto",minWidth:180,alignSelf:"flex-start"},children:[(0,r.jsx)("option",{value:"inherit",children:c("agents.codemode.inherit")}),(0,r.jsx)("option",{value:"on",children:c("agents.codemode.on")}),(0,r.jsx)("option",{value:"off",children:c("agents.codemode.off")})]}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:c("agents.codemodeHint")})]})}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:d?"1fr":"minmax(0, 1.5fr) minmax(120px, 0.75fr) minmax(100px, 0.5fr)",gap:12},children:[(0,r.jsx)(lG,{label:c("agents.model"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(ry,{options:X,value:em,onChange:(e,t)=>ex("model",`${e}/${t}`),onClear:()=>ex("model",void 0),emptyLabel:g?c("agents.modelsLoading"):c("agents.inherit"),selectedLabel:k.model&&!eu?c("agents.modelUnavailable",{model:k.model}):k.model!==ec?k.model:void 0,disabled:es||g||0===h.length&&!k.model,ariaLabel:c("agents.model"),variant:"field",placement:"auto"}),x&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:10},children:x})]})}),(0,r.jsx)(lG,{label:c("agents.thinking"),children:(0,r.jsx)("select",{"aria-label":c("agents.thinking"),value:k.thinking??"",disabled:es,onChange:e=>ex("thinking",e.target.value||void 0),style:eg,children:lH.map(e=>(0,r.jsx)("option",{value:e,children:e||c("agents.inherit")},e||"default"))})}),(0,r.jsx)(lG,{label:c("agents.maxTurns"),children:(0,r.jsx)("input",{"aria-label":c("agents.maxTurns"),type:"number",min:1,value:k.maxTurns??"",disabled:es,onChange:e=>ex("maxTurns",e.target.value?Number(e.target.value):void 0),style:eg})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"10px 20px"},children:[(0,r.jsx)(lY,{label:c("agents.inheritContext"),disabled:es,checked:k.inheritContext,onChange:e=>ex("inheritContext",e)}),(0,r.jsx)(lY,{label:c("agents.background"),disabled:es,checked:k.runInBackground,onChange:e=>ex("runInBackground",e)})]})]}):(0,r.jsx)(aO,{children:c("agents.empty")})})})]}),(0,r.jsx)(aF,{status:(K||P)&&(0,r.jsx)("span",{role:"alert",style:{color:"#ef4444"},children:K||P}),children:er&&(0,r.jsxs)(aB,{variant:"primary",onClick:()=>void et(),disabled:$||M||A||!k.name.trim(),className:M?"is-success":void 0,children:[M&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:M?c("i18n.saved"):$?c("agents.saving"):c("agents.save")})]})})]})}let lQ=["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"];function l0(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function l1(e){return`${e.scope}\0${e.source}`}function l2(e){return`extension\0${e.path}`}function l4(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function l8(e,t){return t(`plugins.status.${e}`)}function l6(e){return`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`}function l3(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function l5(e){let{pkg:t}=e,{t:n}=(0,eX.s)(),i=[["extension",n("i18n.extensions")],["skill",n("i18n.skills")],["prompt",n("i18n.prompts")],["theme",n("i18n.themes")]].map(e=>{let[n,r]=e;return{kind:n,label:r,resources:t.resources.filter(e=>e.kind===n)}}).filter(e=>e.resources.length>0);return 0===i.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:n("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 l9(e){let{cwd:t,source:n,scope:i,projectResourcesLoaded:s,busy:a,actionError:l,onSourceChange:o,onScopeChange:d,onInstall:c}=e,{t:u}=(0,eX.s)();return(0,r.jsx)(aL,{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)(aR,{value:i,label:u("config.saveTo"),options:[{value:"global",label:l4("global",u)},{value:"project",label:l4("project",u),disabled:!s}],path:"project"===i?`${ep(t)}/.pi/{npm,git}`:"~/.pi/agent/{npm,git}",disabledReason:u("trust.projectScopeUnavailable"),onChange:d}),inputLabel:u("config.source"),inputId:"plugin-source",placeholder:"npm:@scope/package",value:n,canSubmit:!a&&!!n.trim(),normalizeValue:l0,onValueChange:o,onSubmit:c,examplesLabel:u("config.examples"),examples:lQ,error:l,children:(0,r.jsx)(aB,{variant:"primary",onClick:c,disabled:a||!n.trim(),className:"is-pushed-right",children:u(a?"i18n.installing":"i18n.install")})})}function l7(e){let t,n,{pkg:s,cwd:a,busyKey:l,actionError:o,actionMessage:d,sessionId:c,updateStatus:u,checkingUpdate:p,updateError:h,onAction:m,onCheckUpdate:g,onReloadSession:f}=e,{t:x}=(0,eX.s)(),b=l1(s),v=(l?.endsWith(b)||l?.startsWith("bulk:"))??!1,y="reload"===l,k=!s.disabled,j=s.canCheckForUpdates,w=u?.state==="update-available",S=s.description?.trim(),C=(0,i.useId)();return(0,r.jsxs)(ak,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(aj,{className:"is-top-aligned",children:[(0,r.jsxs)(aw,{children:[(0,r.jsx)(aT,{scope:s.scope,children:l4(s.scope,x)}),!s.disabled&&s.filtered&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:x("i18n.filtered")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s.source})]}),(0,r.jsxs)(aS,{children:[(0,r.jsx)(aB,{size:"small",variant:w?"primary":void 0,onClick:w||!j?()=>m("update",s):g,disabled:v||y||p,title:w?x("i18n.updateAvailable"):void 0,children:x(l===`update:${b}`?"i18n.updating":p?"i18n.checking":w||!j?"i18n.update":"i18n.check")}),(0,r.jsx)(aB,{size:"small",onClick:f,disabled:!c||y||v,"aria-describedby":c?void 0:C,children:x(y?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)(aB,{variant:"danger",size:"small",onClick:()=>m("remove",s),disabled:v||y,children:x(l===`remove:${b}`?"i18n.removing":"i18n.remove")}),(0,r.jsx)(aH,{checked:k,loading:v||y,onChange:()=>m(s.disabled?"enable":"disable",s),label:x(s.disabled?"i18n.enablePackage":"i18n.disablePackage")})]})]}),!c&&(0,r.jsx)("div",{id:C,className:"config-detail-heading-note",children:x("i18n.openSessionToReload")})]}),(0,r.jsxs)(aE,{children:[S&&(0,r.jsx)(a$,{label:x("i18n.description"),children:S}),(0,r.jsx)(a$,{label:x("i18n.status"),tone:"plain",style:{color:l3(s.status),textTransform:"capitalize"},children:l8(s.status,x)}),(0,r.jsxs)(a$,{label:x("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=[],s.version&&t.push(x("i18n.installedVersion",{version:s.version})),s.configuredVersion&&t.push(x("i18n.configuredVersion",{version:s.configuredVersion})),t.length?t.join(" \xb7 "):x("i18n.unknown"))}),w&&(0,r.jsx)("span",{className:"skill-version-value is-update",title:u.displayName,children:x("i18n.updateAvailable")}),j&&(p||u&&!w)&&(0,r.jsx)("span",{className:`skill-update-status ${p?"is-checking":u?.state==="up-to-date"?"is-success":u?.state==="error"?"is-error":"is-muted"}`,children:p?x("i18n.checking"):u?.state==="up-to-date"?x("i18n.upToDate"):u?.state==="unsupported"?x("i18n.automaticChecksUnavailable"):u?.message||x("i18n.checkFailed")})]}),h&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:h})]}),!(s.packageName&&s.source.endsWith(s.packageName))&&(0,r.jsx)(a$,{label:x("i18n.package"),mono:!0,children:s.packageName??x("i18n.unknown")}),!s.disabled&&(0,r.jsx)(a$,{label:x("i18n.resources"),children:(n=[s.counts.extensions?x("i18n.resourceCount",{count:s.counts.extensions,label:x("i18n.extensionShort")}):"",s.counts.skills?x("i18n.resourceCount",{count:s.counts.skills,label:x("i18n.skillShort")}):"",s.counts.prompts?x("i18n.resourceCount",{count:s.counts.prompts,label:x("i18n.promptShort")}):"",s.counts.themes?x("i18n.resourceCount",{count:s.counts.themes,label:x("i18n.themeShort")}):""].filter(Boolean)).length?n.join(" \xb7 "):x("i18n.noResources")}),(0,r.jsx)(a$,{label:x("i18n.installedPath"),tone:s.installedPath?"muted":"error",mono:!0,children:s.installedPath?ep(s.installedPath):x("i18n.notFound")}),(0,r.jsx)(a$,{label:x("i18n.cwd"),tone:"dim",mono:!0,children:ep(a)})]}),!s.disabled&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)(aN,{children:x("i18n.resolvedResources")}),(0,r.jsx)(l5,{pkg:s})]}),d&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:d}),o&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:o})]})}function oe(e){let{extension:t}=e,{t:n}=(0,eX.s)(),i=t.enabled?"loaded":"disabled";return(0,r.jsxs)(ak,{children:[(0,r.jsx)(aj,{children:(0,r.jsxs)(aw,{children:[(0,r.jsx)(aT,{scope:t.scope,children:l4(t.scope,n)}),(0,r.jsx)(aC,{children:t.name})]})}),(0,r.jsxs)(aE,{children:[(0,r.jsx)(a$,{label:n("i18n.status"),tone:"plain",style:{color:t.enabled?"var(--accent)":"var(--text-dim)"},children:l8(i,n)}),(0,r.jsx)(a$,{label:n("i18n.installedPath"),mono:!0,children:ep(t.path)})]})]})}function ot(e){var t;let{cwd:n,sessionId:s,onClose:a,onReloaded:l,embedded:o=!1,trust:d}=e,{t:c}=(0,eX.s)(),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(!0),[g,f]=(0,i.useState)(null),[x,b]=(0,i.useState)(()=>sU("plugins",n)),[v,y]=(0,i.useState)(!1),[k,j]=(0,i.useState)(""),[w,S]=(0,i.useState)("global"),[C,N]=(0,i.useState)(null),[I,E]=(0,i.useState)(null),[$,T]=(0,i.useState)(null),[M,R]=(0,i.useState)(null),[A,L]=(0,i.useState)({}),[P,z]=(0,i.useState)(new Set),[O,W]=(0,i.useState)(!1),[F,D]=(0,i.useState)(null),[B,H]=(0,i.useState)(!1),_=(0,i.useMemo)(()=>u?.packages??[],[u?.packages]),U=(0,i.useMemo)(()=>u?.standaloneExtensions??[],[u?.standaloneExtensions]),K=_.find(e=>l1(e)===x)??null,q=U.find(e=>l2(e)===x)??null,Z=u?.projectResourcesLoaded??!0,V=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:_.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[_]),J=(0,i.useCallback)(async()=>{m(!0),f(null),R(null);try{let e=await fetch(`/api/plugins?cwd=${encodeURIComponent(n)}`),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);p(t),y(e=>0===t.packages.length&&0===t.standaloneExtensions.length||e),b(e=>e&&(t.packages.some(t=>l1(t)===e)||t.standaloneExtensions.some(t=>l2(t)===e))?e:t.packages[0]?l1(t.packages[0]):t.standaloneExtensions[0]?l2(t.standaloneExtensions[0]):null)}catch(e){f(e instanceof Error?e.message:String(e))}finally{m(!1)}},[n]);(0,i.useEffect)(()=>{L({}),D(null),J()},[n]);let G=lR(d),Y=(0,i.useRef)(G);(0,i.useEffect)(()=>{Y.current!==G&&(Y.current=G,J())},[G,J]),(0,i.useEffect)(()=>{x&&sK("plugins",x,n)},[n,x]);let X=(0,i.useCallback)(async e=>{let t=(e?[e]:_.filter(e=>e.canCheckForUpdates)).map(l1);if(0!==t.length){D(null),z(e=>new Set([...e,...t])),e||W(!0);try{let t=await fetch("/api/plugins/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n,source:e?.source,scope:e?.scope})}),r=await t.json();if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);L(e=>{let t={...e};for(let e of r.updates??[])t[l1(e)]=e;return t})}catch(e){D(e instanceof Error?e.message:String(e))}finally{z(e=>{let n=new Set(e);for(let e of t)n.delete(e);return n}),e||W(!1)}}},[n,_]),Q=(0,i.useCallback)(async()=>{H(!0),E(null),T(null),D(null);try{let e=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"update",cwd:n})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);p(t),L({}),T(c("i18n.packagesUpdated")),s&&T(`${c("i18n.packagesUpdated")} ${c("agents.reloadRequired")}`)}catch(e){E(e instanceof Error?e.message:String(e))}finally{H(!1)}},[n,s,c]),ee=(0,i.useCallback)(async(e,t)=>{let r=l1(t);N(`${e}:${r}`),E(null),T(null),R(null);try{let i=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,source:t.source,scope:t.scope,cwd:n})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);if(p(s),"remove"===e)b(s.packages[0]?l1(s.packages[0]):s.standaloneExtensions[0]?l2(s.standaloneExtensions[0]):null),0===s.packages.length&&0===s.standaloneExtensions.length&&y(!0),T(c("i18n.packageRemoved")),L(e=>{let t={...e};return delete t[r],t});else{let t={install:c("i18n.packageInstalled"),update:c("i18n.packageUpdated"),disable:c("i18n.packageDisabled"),enable:c("i18n.packageEnabled")};T(t[e]),"update"===e&&L(e=>{let t={...e};return delete t[r],t})}}catch(e){E(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,c]),et=(0,i.useCallback)(async(e,t,r)=>{let i=lM(t,r,e=>!e.disabled,e=>e.filtered),a=r?0:t.filter(e=>!e.disabled&&e.filtered).length,l=a>0?c("plugins.bulkKeptFiltered",{count:a}):void 0;if(E(null),T(null),R(l?{scope:e,note:l}:null),0===i.length)return;let o=r?"enable":"disable";N(`bulk:${e}`);try{let t=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:o,cwd:n,packages:i.map(t=>{let{source:n}=t;return{source:n,scope:e}})})}),a=await t.json();if(!t.ok||a.error||!a.results)throw Error(a.error??`HTTP ${t.status}`);let{results:d,...u}=a;p(u);let h=d.filter(e=>e.error);if(h.length<d.length){let e=r?c("plugins.bulkEnabled"):c("plugins.bulkDisabled");T(s?`${e} ${c("agents.reloadRequired")}`:e)}h.length>0&&R({scope:e,note:l,error:[c("plugins.bulkFailed",{count:h.length,total:d.length}),...h.map(e=>`${e.source}: ${e.error}`)].join("\n")})}catch(t){R({scope:e,note:l,error:t instanceof Error?t.message:String(t)})}finally{N(null)}},[n,s,c]),en=(0,i.useCallback)(async()=>{let e=l0(k).trim();if(!e)return;j(e);let t=`${w}\0${e}`;N(`install:${t}`),E(null),T(null),R(null);try{var r;let i,s,a=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:e,scope:w,cwd:n})}),l=await a.json();if(!a.ok||l.error)throw Error(l.error??`HTTP ${a.status}`);p(l);let o=(r=l.packages,s=(i=e.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===w&&e.source===i)??r.find(e=>e.scope===w&&e.source===`npm:${s}`)??r.find(e=>e.scope===w&&e.source.endsWith(i)));b(o?l1(o):t),y(!1),j(""),T(c("i18n.packageInstalled"))}catch(e){E(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,w,k,c]),er=(0,i.useCallback)(async()=>{if(s){N("reload"),E(null),T(null),R(null);try{await iE(s,{type:"reload"}),l?.(),await J(),T(c("i18n.sessionReloaded"))}catch(e){E(e instanceof Error?e.message:String(e))}finally{N(null)}}},[J,l,s,c]),ei=C?.startsWith("install:")??!1,es=Object.values(A).filter(e=>"update-available"===e.state).length,ea=_.some(e=>e.canCheckForUpdates),el=h||null!==C||P.size>0||B;return(0,r.jsxs)(ao,{embedded:o,title:c("common.plugins"),subtitle:ep(n),closeLabel:c("i18n.close"),onClose:a,children:[!Z&&(0,r.jsx)(az,{message:c("trust.pluginsNotLoaded")}),(0,r.jsxs)(ah,{children:[(0,r.jsxs)(am,{children:[(0,r.jsx)(ag,{children:h?(0,r.jsx)("div",{className:"config-sidebar-message",children:c("i18n.loading")}):g?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:g}):0===_.length&&0===U.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:c("i18n.noPlugins")}):(0,r.jsxs)(r.Fragment,{children:[U.length>0&&(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(af,{children:c("i18n.extensions")}),U.map(e=>{let t=l2(e);return(0,r.jsxs)(av,{active:!v&&x===t,title:e.path,onClick:()=>{b(t),y(!1),E(null),T(null)},children:[(0,r.jsx)(aU,{active:e.enabled}),(0,r.jsx)(ay,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.name})]},t)})]}),V.map(e=>{let t=e.packages.filter(e=>!e.disabled).length,n=t===e.packages.length;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(af,{aside:(0,r.jsx)(ax,{enabled:t,total:e.packages.length,disabled:el,loading:C===`bulk:${e.scope}`,label:c(n?"plugins.groupSwitchOn":"plugins.groupSwitchOff",{group:l4(e.scope,c)}),onChange:t=>void et(e.scope,e.packages,t)}),children:l4(e.scope,c)}),M?.scope===e.scope&&(0,r.jsx)(ab,{error:M.error,note:M.note}),e.packages.map(e=>{let t=l1(e),n=!v&&x===t;return(0,r.jsxs)(av,{active:n,title:e.description??e.source,onClick:()=>{b(t),y(!1),E(null),T(null)},children:[(0,r.jsx)(aU,{active:!e.disabled,color:l3(e.status)}),(0,r.jsx)(ay,{className:`is-grow${e.disabled?" is-muted":""}`,children:e.source}),A[l1(e)]?.state==="update-available"&&(0,r.jsx)("span",{title:c("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"})]},t)})]},e.scope)})]})}),(0,r.jsx)(a_,{active:v,onClick:()=>{y(!0),E(null),T(null)},children:c("i18n.addPlugin")})]}),(0,r.jsx)(aW,{children:(0,r.jsx)(ak,{className:"is-fill",children:v?(0,r.jsx)(l9,{cwd:n,source:k,scope:w,projectResourcesLoaded:Z,busy:ei,actionError:I,onSourceChange:j,onScopeChange:S,onInstall:en}):h?null:q?(0,r.jsx)(oe,{extension:q}):K?(0,r.jsx)(l7,{pkg:K,cwd:n,busyKey:C,actionError:I,actionMessage:$,sessionId:s,updateStatus:A[l1(K)],checkingUpdate:P.has(l1(K)),updateError:F,onAction:ee,onCheckUpdate:()=>void X(K),onReloadSession:er},l1(K)):(0,r.jsx)(aO,{children:c("i18n.selectPackage")})})})]}),(0,r.jsxs)(aF,{status:es>0?(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--accent)"},children:[es," ",1===es?c("i18n.update"):c("i18n.updates")]}):u?.diagnostics.length?(0,r.jsx)(aD,{tone:u.diagnostics.some(e=>"error"===e.type)?"error":"warning",summary:1===u.diagnostics.length?c("plugins.diagnostic"):c("plugins.diagnostics",{count:u.diagnostics.length}),details:u.diagnostics.map(l6)}):(0,r.jsx)(aD,{summary:u?[c("i18n.resourceCount",{count:(t=u.totals).extensions,label:c("i18n.extensionShort")}),c("i18n.resourceCount",{count:t.skills,label:c("i18n.skillShort")}),c("i18n.resourceCount",{count:t.prompts,label:c("i18n.promptShort")}),c("i18n.resourceCount",{count:t.themes,label:c("i18n.themeShort")})].join(" \xb7 "):""}),children:[!o&&(0,r.jsx)(aB,{onClick:a,children:c("i18n.close")}),ea&&(0,r.jsx)(aB,{variant:es>0?"primary":"secondary",onClick:()=>void(es>0?Q():X()),disabled:el,title:es>0?c("i18n.updateAllPluginsHint"):void 0,children:B?c("i18n.updating"):O?c("i18n.checking"):es>0?`${c("i18n.updateAllPlugins")} (${es})`:c("i18n.checkUpdates")}),(0,r.jsx)(aB,{variant:"secondary",onClick:()=>void J(),disabled:el,children:c("i18n.refresh")})]})]})}let on="\\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",or=RegExp(`[${on}]`,"gu"),oi=RegExp(`[${on}]`,"u");function os(e){return e.replace(or,e=>{let t=e.codePointAt(0)??0;return`\\u{${t.toString(16).toUpperCase().padStart(4,"0")}}`})}let oa=/[\s"'`$|&;<>()*?#~]/;function ol(e){let t=oi.test(e),n=os(e);return""===n||t||oa.test(n)?`"${n.replace(/"/g,'\\"')}"`:n}function oo(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return[e,...t].map(ol).join(" ")}function od(e){let t=void 0!==e.command?oo(e.command,e.args):void 0,n=void 0!==e.url?os(e.url):void 0;return"http"===e.transport?n:"stdio"===e.transport?t:n??t}function oc(e){return[e.name,e.command,e.cwd,e.url,...e.args??[],...e.envNames,...e.headerNames].some(e=>void 0!==e&&oi.test(e))}function ou(e){return"oauth-client-secret"===e.kind?{key:"mcp.field.oauthClientSecret"}:{key:"env"===e.kind?"mcp.field.env":"mcp.field.header",params:{name:os(e.name??"")}}}function op(e){return"http"===e.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables"}function oh(e){return e.length>0?{key:"mcp.server.overridesGlobal",params:{keys:e.join(", ")}}:{key:"mcp.server.overridesGlobalNothing"}}function om(e){return e.flatMap(e=>{let{variables:t,...n}=e;return t.map(e=>({variable:e,field:n}))})}function og(e,t){return"unparsable"===e.reason||"unreadable"===e.reason?os(e.error):"link-outside"===e.reason?void 0===t?void 0:os(t):void 0}let of="codemode";function ox(e){return`${e.scope}\0${e.name}`}function ob(e){return e?.trust?.decision===!0}function ov(e){return"test"===e.origin?e.state:void 0!==e.closedAt||"not-trusted"===e.state?"on":e.state}function oy(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?ov(e.status):"on":"mcp-off":"not-trusted":"disabled"}let ok={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"},oj={connected:"mcp.state.session.connected",failed:"mcp.state.session.failed"};function ow(e,t){return(t?.origin==="session"?oj[e]:void 0)??ok[e]}let oS={disconnected:"mcp.stateDetail.disconnected",conflict:"mcp.stateDetail.conflict"},oC={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 oN(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 oI(e){return"on"===e?{active:!0}:"off"===e?{active:!1}:{color:"error"===e?"#ef4444":"#f59e0b"}}function oE(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 o$={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"},oT={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"},oM={connecting:"off",connected:"on","needs-auth":"warning",failed:"error",disconnected:"warning",conflict:"error","not-trusted":"warning"},oR={codemode:"mcp.exposure.codemode",deferred:"mcp.exposure.deferred",direct:"mcp.exposure.direct",hidden:"mcp.exposure.hidden"},oA=["codemode","deferred","direct","hidden"],oL={codemode:"mcp.exposureShort.codemode",deferred:"mcp.exposureShort.deferred",direct:"mcp.exposureShort.direct",hidden:"mcp.exposureShort.hidden"};function oP(e){return"auto-enable-codemode-invalid"!==e.reason}function oz(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 oO(e){return{enabled:e.filter(e=>e.enabled).length,total:e.length}}function oW(e,t){let n=e.flatMap(e=>e.servers.map(ox));return t===of||null!==t&&n.includes(t)?t:n[0]??null}function oF(e){let t=e?.trust;return void 0!==t&&t.requiresTrust&&!t.trusted}function oD(e){return e.projectOverride?.preference??e.preference}let oB={always:"mcp.codemode.projectOverride.always",automatic:"mcp.codemode.projectOverride.automatic"},oH={on:"mcp.codemode.toolMode.onDescription",only:"mcp.codemode.toolMode.onlyDescription"},o_={on:"mcp.codemode.toolMode.projectOverride.on",only:"mcp.codemode.toolMode.projectOverride.only"},oU={automatic:"mcp.codemode.automatic",always:"mcp.codemode.always",unavailable:"mcp.codemode.unavailable",unknown:"i18n.unknown"};function oK(e){return"unavailable"===e?"error":"unknown"===e?"off":"on"}let oq=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e);function oZ(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}:{},...oq(n.names)?{names:n.names}:{},...oq(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 oV(e,t,n,r){let i,{abortAtDeadline:s=!0}=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},a=new AbortController,l=()=>a.abort();r?.aborted?a.abort():r?.addEventListener("abort",l,{once:!0});let o=new Promise(e=>{i=setTimeout(()=>{e(t()),s&&a.abort()},n)});try{return await Promise.race([e(a.signal),o])}finally{clearTimeout(i),r?.removeEventListener("abort",l)}}function oJ(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 oG(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&&oJ(i)?{ok:!0,data:i}:{ok:!1,error:oZ(i,r.status)}}let oY=new Set(["cwd-invalid","cwd-denied","cwd-not-directory"]);async function oX(e,t,n){let r=await oG(e,t,n);if(r.ok||!e||!r.error.reason||!oY.has(r.error.reason))return r;let i=await oG(null,t,n);return i.ok?{...i,projectError:r.error}:i}async function oQ(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 oV(n=>oX(e,t,n),()=>({ok:!1,error:{error:`GET /api/mcp did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function o0(e,t,n,r){let i,s;try{i=await n("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store",signal:r})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{s=await i.json()}catch{return{ok:!1,error:{error:`HTTP ${i.status}`}}}let a=i.ok&&null!==s&&"object"==typeof s?t(s):void 0;return void 0!==a?{ok:!0,stored:a}:{ok:!1,error:oZ(s,i.status)}}async function o1(e,t,n){let r=await o0({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 o2(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 oV(n=>o1(e,t,n),()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function o4(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 oV(async n=>{let r=await o0({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 o8(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 oV(async n=>{let r=await o0({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 o6(e){return!e.available&&"builtin-disabled"!==e.reason}function o3(e,t){if(o6(t.mcp))return"mcp-off";if("project"===e){if(!t.project?.trust)return"trust-unreadable";if(!ob(t.project))return"project-untrusted"}}let o5={"mcp-off":"mcp.readOnly.mcp-off","project-untrusted":"mcp.readOnly.project-untrusted","trust-unreadable":"mcp.readOnly.trust-unreadable"};function o9(e){return!0!==e.notAnObject}function o7(e){return o9(e)&&void 0===e.webPasswordField}async function de(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&&oJ(i)?{ok:!0,data:i}:{ok:!1,error:oZ(i,r.status)}}async function dt(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 oV(e=>de(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp did not answer within ${i} ms`,timedOut:!0}}),i,r)}let dn={"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 dr(e,t){let n=o3(e.scope,t);return n||(void 0===e.invalidError&&e.validated?e.webPasswordField?"web-password":void 0:"invalid")}let di={"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"},ds={connected:"mcp.test.state.connected","needs-auth":"mcp.test.state.needs-auth",failed:"mcp.test.state.failed",timedOut:"mcp.test.state.timedOut"},da={connected:"mcp.test.summary.connected","needs-auth":"mcp.test.summary.needs-auth",failed:"mcp.test.summary.failed",timedOut:"mcp.test.summary.timedOut"},dl={connected:"mcp.signIn.summary.connected","needs-auth":"mcp.signIn.summary.needs-auth",failed:"mcp.signIn.summary.failed",timedOut:"mcp.signIn.summary.timedOut"};function dd(e){return(Math.max(0,e)/1e3).toFixed(1)}async function dc(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:oZ(i,r.status)}}async function du(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 oV(e=>dc(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp/test did not answer within ${i} ms`,timedOut:!0}}),i,r,{abortAtDeadline:!1})}let dp="•••",dh=new Set(["key","apikey","token","secret","password","passwd","passphrase","pwd","pass","credential","credentials","authorization","bearer","jwt","cookie","signature","pat"]),dm=new Set([...dh,"auth","sig","code","pw"]),dg=["token","secret","password","passwd","apikey"],df=new Set(["file","path","dir","url","uri","endpoint","id","name","type","header","env","var","length","ttl","expiry","expires","timeout","mode","format"]),dx=new Set(["-k"]);function db(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 dv(e,t){let n=db(e);return!(n.length>1&&df.has(n[n.length-1]))&&n.some(e=>t.has(e)||dg.some(t=>e.length>t.length&&e.endsWith(t)))}function dy(e){return dv(e,dh)}let dk=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,})"),dj=/^eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*$/,dw=/^[A-Za-z0-9_\-+/=.~]+$/;function dS(e){return!(/\s/.test(e)||d$(e))&&(!!(dk.test(e)||dj.test(e))||!(e.length<24||!dw.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 dC=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Za-z_][A-Za-z0-9_]*/,dN=RegExp(dC.source,"g"),dI=/^(?:bearer|basic|token)\s+/i;function dE(e,t,n){let r=e.replace(dI,"");return t.test(r)&&/^[^A-Za-z0-9]*$/.test(r.replace(n,""))}function d$(e){return dE(e.replace(/\$[$!]/g,"_x"),dC,dN)}let dT=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Z_][A-Z0-9_]*(?![A-Za-z0-9_])/,dM=RegExp(dT.source,"g");function dR(e){return dE(e,dT,dM)}function dA(e,t){if(!e||""===t)return;e.push(t);let n=dz(t);n!==t&&e.push(n)}let dL=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#]*)/;function dP(e,t,n){let r=!1,i=e,s="",a=dL.exec(e);if(a){let[l,o,d]=a,c=d.lastIndexOf("@");if(c>=0&&!t(dz(d.slice(0,c)))){s=`${o}${dp}${d.slice(c)}`,r=!0;let e=d.slice(0,c);dA(n,e);let t=e.indexOf(":");t>=0&&dA(n,e.slice(t+1))}else s=l;i=e.slice(l.length)}let l=i.search(/[?#]/),o=l<0?i:i.slice(0,l),d=l<0?"":i.slice(l),c=o.split("/").map(e=>dS(dz(e))?(r=!0,dA(n,e),dp):e).join("/");return d=d.replace(/([?&#;])([^&#;]*)/g,(e,i,s)=>{let a=s.indexOf("=");if(a<0){let a=dz(s);return!dS(a)||t(a)?e:(r=!0,dA(n,s),`${i}${dp}`)}let l=s.slice(0,a),o=dz(s.slice(a+1));return""===o||t(o)||!function(e){let t=e;try{t=decodeURIComponent(e)}catch{}return dv(t,dm)}(l)&&!dS(o)?e:(r=!0,dA(n,s.slice(a+1)),`${i}${l}=${dp}`)}),{value:`${s}${c}${d}`,masked:r}}function dz(e){try{return decodeURIComponent(e)}catch{return e}}let dO=/^(\s*[A-Za-z][A-Za-z0-9 _.-]*=)([\s\S]*)$/;function dW(e,t,n){let r=/^([A-Za-z0-9_-]+):(\s*)([\s\S]*)$/.exec(e);if(r&&""!==r[3]&&!r[3].startsWith("//")&&dy(r[1])){let[,i,s,a]=r;return t(a)?{value:e,masked:!1}:(dA(n,a.trim()),{value:`${i}:${s}${dp}`,masked:!0})}let i=e.includes(";")?function(e,t,n){let r=e.split(";");if(r.length<2||!r.every(e=>""===e.trim()||dO.test(e)))return;let i=!1;return{value:r.map(e=>{let r=dO.exec(e);if(!r)return e;let[,s,a]=r;if(""===a.trim()||t(a))return e;if(dy(s.slice(0,-1).trim()))return i=!0,dA(n,a.trim()),`${s}${dp}`;let l=dW(a,t,n);return i||=l.masked,`${s}${l.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]&&dy(s[1]))return t(s[2])?{value:e,masked:!1}:(dA(n,s[2]),{value:`${s[1]}=${dp}`,masked:!0});if(/\s/.test(e)){var a,l,o;let r,i;return a=e,l=t,o=n,i=dB((r=a.split(/(\s+)/)).filter((e,t)=>t%2==0),l,!0,o),{value:r.map((e,t)=>t%2==0?i.values[t/2]:e).join(""),masked:i.masked}}if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(e))return dP(e,t,n);if(s&&""!==s[2]){let e=dW(s[2],t,n);return{value:`${s[1]}=${e.value}`,masked:e.masked}}return dS(e)&&!t(e)?(dA(n,e),{value:dp,masked:!0}):{value:e,masked:!1}}function dF(e){if(dx.has(e))return!0;if(!/^--?[A-Za-z]/.test(e))return!1;let t=e.replace(/^-+/,"");return dy(t)||"auth"===db(t).at(-1)}let dD=/^(?:bearer|basic|token)$/i;function dB(e,t,n,r){let i=!1,s=!1;return{values:e.map(e=>{if(""===e)return e;if(s){if(n&&dD.test(e))return e;if(s=!1,!/^-[A-Za-z-]/.test(e))return t(e)?e:(i=!0,dA(r,e),dp)}let a=/^(--?[A-Za-z][A-Za-z0-9_.-]*)=([\s\S]*)$/.exec(e);if(a){let[,e,n]=a;if(""!==n&&dF(e)&&!t(n))return i=!0,dA(r,n),`${e}=${dp}`;let s=dW(n,t,r);return i||=s.masked,`${e}=${s.value}`}if(/^--?[A-Za-z][A-Za-z0-9_.-]*$/.test(e))return s=dF(e),e;if(n){let t=/^([A-Za-z0-9_-]+):$/.exec(e);if(dD.test(e)||t&&dy(t[1]))return s=!0,e}let l=dW(e,t,r);return i||=l.masked,l.value}),masked:i}}function dH(e){let{values:t,masked:n}=dB(e,dR,!1);return{args:t,masked:n}}function d_(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function dU(e){return!e.startsWith("!")&&!d$(e)}function dK(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 dq={"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(dq);let dZ={dollarBrace:!1,bareDollar:!1,percent:!1,braceEnv:!1},dV={dollarBrace:!0,bareDollar:!1,percent:!0,braceEnv:!0},dJ={...dV,bareDollar:!0},dG={...dZ,braceEnv:!0},dY=/^[A-Za-z_][A-Za-z0-9_]*$/,dX=/\$\{([^{}]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)|%([A-Za-z_][A-Za-z0-9_]*)%|\{(env|file):([^{}]*)\}/g;function dQ(e,t){if(!t)return;let n=e[e.length-1];n?.kind==="text"?n.text+=t:e.push({kind:"text",text:t})}function d0(e,t,n){let r=[],i=0;dX.lastIndex=0;for(let s=dX.exec(e);s;s=dX.exec(e)){let[a,l,o,d,c,u]=s,p=a;if(void 0!==l&&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(dY.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}(l,a);else if(void 0!==o&&t.bareDollar)p={kind:"env",name:o,from:a};else if(void 0!==d&&t.percent&&n)p={kind:"env",name:d,from:a};else if(void 0!==c&&t.braceEnv)p="env"===c&&dY.test(u)?{kind:"env",name:u,from:a}:{kind:"unsupported",from:a};else if(void 0!==d||void 0!==c){dQ(r,e.slice(i,s.index+1)),i=s.index+1,dX.lastIndex=s.index+1;continue}dQ(r,e.slice(i,s.index)),"string"==typeof p?dQ(r,p):r.push(p),i=s.index+a.length}return dQ(r,e.slice(i)),r}function d1(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 d2(e){return e.startsWith("!")}function d4(e){if(d2(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);dY.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 d8=/<[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,d6=/^(?:\.\.\.|…|\*{3,}|x{3,}|TODO|FIXME|changeme|change[-_]me|replace[-_]?me|placeholder|redacted|\[[^\]]+\])$/i,d3=/(?:^|[\\/])(?:path[\\/]to(?:[\\/]|$)|Users[\\/](?:username|yourname|your[-_][A-Za-z_-]+|user[-_]?name|<[^>]+>)(?:[\\/]|$)|home[\\/](?:username|yourname|your[-_][A-Za-z_-]+|<[^>]+>)(?:[\\/]|$))/i,d5=/^(Bearer|Basic|Token|Bot|ApiKey|Api-Key)\s+(.+)$/i;function d9(e){return e.join("\0")}function d7(e){return"args"===e[0]?`args[${e[1]}]`:e.join(".")}function ce(e){return"env"===e[0]||"headers"===e[0]||"oauth"===e[0]&&"clientSecret"===e[1]}function ct(e){return"command"===e[0]||"args"===e[0]||"cwd"===e[0]}let cn=new Set(["HOME","USERPROFILE"]);class cr{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 ci(e){return e.map(e=>"text"in e?e.text:e.from).join("")}let cs=/\$\{[^{}]*\}/g,ca=new Set(["variable","home","workspace-basename","unsupported-variable","input"]);class cl{constructor(e){this.draft=e,this.fields=new Map,this.argTexts=e.args.map(ci),this.urlText=ci(e.url??[])}encode(e,t){let n,r=ce(e),i=d7(e),s=ci(t),a=[],l=!1,o=()=>a.every(e=>""===e),d=e=>{if(!r)return void a.push(e);let t=/\$([A-Za-z_][A-Za-z0-9_]*)/.exec(e);t&&this.draft.note("bare-dollar-literal",{field:i,name:t[1]});let n=d1(e,{atStart:o()});n!==e&&(l=!0),a.push(n)},c=e=>a.push(e),u=e=>a.push({field:e});if(!r&&ct(e)&&1===t.length&&"text"in t[0]&&d3.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(d3.test(n))return t&&c(t),u(this.field(e,"placeholder-path",n,n,"text")),this.target(e,a,void 0)}let p=0;return t.forEach((a,l)=>{let h=t[l+1],m=void 0===h||"text"in h&&/^[\\/]/.test(h.text),g=(t,r,i)=>{let a=0;for(let[d,c]of function(e){let t=e.trim();if(d6.test(t)){let n=e.indexOf(t);return[[n,n+t.length]]}let n=d5.exec(t);if(n&&d6.test(n[2].trim())){let t=e.lastIndexOf(n[2].trim());return[[t,t+n[2].trim().length]]}let r=[];d8.lastIndex=0;for(let t=d8.exec(e);t;t=d8.exec(e))/^your[-_]/.test(t[0])&&/[@/]/.test(e[t.index-1]??"")||r.push([t.index,t.index+t[0].length]);return r}(t)){var l,o;if(i.some(e=>{let[t,n]=e;return d<n&&c>t}))continue;d>a&&r(t.slice(a,d)),"url"===e[0]&&co(s,p+d)&&(n="uri-component");let h=t.slice(d,c);u(this.field(e,"placeholder",(l=e,o=h,"env"===l[0]||"headers"===l[0]?l[1]:o.replace(/^[<{\s]+|[>}\s]+$/g,"")||d7(l)),h)),a=c}a<t.length&&r(t.slice(a))};switch(a.kind){case"text":g(a.text,d,[]);break;case"pi":{var f;let e=h?(f=a.text,(/\$+$/.exec(f)?.[0].length??0)%2==1?`${f}$`:f):a.text;if(r&&o()&&d2(e)){this.draft.note("shell-command-value",{field:i}),c(e);break}let t=[...e.matchAll(cs)].map(e=>[e.index,e.index+e[0].length]);g(e,c,t);break}case"env":r?(c(`$\{${a.name}}`),void 0!==a.fallback&&this.draft.note("variable-fallback-dropped",{field:i,name:a.name,fallback:a.fallback}),a.shell?this.draft.note("shell-variable",{field:i,name:a.name}):a.from!==`$\{${a.name}}`&&this.draft.note("variable-translated",{field:i,from:a.from,to:`$\{${a.name}}`})):ct(e)&&o()&&cn.has(a.name)&&m?(c("~"),this.draft.note("home-translated",{field:i,from:a.from})):(u(this.field(e,"variable",a.name,a.from,void 0,a.fallback)),this.draft.note(a.shell?"shell-variable":"variable-unsupported-here",{field:i,name:a.name}));break;case"input":u(this.inputField(e,a));break;case"home":r?(c("${HOME}"),this.draft.note("home-variable-translated",{field:i,from:a.from,to:"${HOME}"})):ct(e)&&o()&&m?(c("~"),this.draft.note("home-translated",{field:i,from:a.from})):u(this.field(e,"home","userHome",a.from,"text"));break;case"workspace":"url"===e[0]||"oauth"===e[0]?u(this.field(e,"variable","workspaceFolder",a.from,"text")):(c("."),this.draft.note("workspace-folder-relative",{field:i,from:a.from}));break;case"workspace-basename":u(this.field(e,"workspace-basename","workspaceFolderBasename",a.from,"text"));break;case"unsupported":u(this.field(e,"unsupported-variable",a.from,a.from)),this.draft.note("unsupported-variable",{field:i,variable:a.from});break;case"prompt":"url"===e[0]&&co(s,p)&&(n="uri-component"),u(this.promptField(e,a))}p+=("text"in a?a.text:a.from).length}),l&&this.draft.note("escaped-value",{field:i}),this.target(e,a,n)}target(e,t,n){let r=t.filter(e=>""!==e);for(let t of new Set(r.flatMap(e=>"string"==typeof e?[]:[e.field]))){let i=this.fields.get(t);i.targets.some(t=>d9(t.path)===d9(e))||i.targets.push({path:e,parts:r,...n?{encoding:n}:{}})}return r.map(e=>"string"==typeof e?e:this.fields.get(e.field).placeholder??"").join("")}field(e,t,n,r,i,s){let a=ca.has(t)?`${t}.${n}`:d7(e);if(ca.has(t)){if(this.fields.has(a))return a}else for(let t=2;this.fields.has(a);t++)a=`${d7(e)}#${t}`;let l=this.isSecretContext(e,r)||dy(n),o="headers"===e[0]&&"authorization"===e[1].toLowerCase();return this.fields.set(a,{id:a,kind:i??(l?"password":"text"),reason:t,label:n,placeholder:r,...void 0!==s?{defaultValue:s}:{},..."placeholder"===t&&o?{optional:!0}:{},targets:[]}),a}inputField(e,t){let n=`input.${t.id}`;if(this.fields.has(n))return n;let r=this.draft.inputs?.get(t.id);r?"command"===r.type&&this.draft.note("input-command-unsupported",{id:t.id}):this.draft.note("input-undefined",{id:t.id});let i=r?.type==="pickString"&&r.options&&r.options.length>0?r.options:void 0,s=r?.password===!0||this.isSecretContext(e,t.from);return this.fields.set(n,{id:n,kind:i?"select":s?"password":"text",reason:"input",label:t.id,placeholder:t.from,...r?.description?{description:r.description}:{},...r?.default!==void 0?{defaultValue:r.default}:{},...i?{options:i}:{},targets:[]}),n}promptField(e,t){return this.fields.has(t.id)||this.fields.set(t.id,{id:t.id,kind:t.options?"select":t.secret||this.isSecretContext(e,t.from)?"password":"text",reason:t.reason,label:t.label,placeholder:t.from,...t.description?{description:t.description}:{},...void 0!==t.defaultValue?{defaultValue:t.defaultValue}:{},...t.options?{options:t.options}:{},...t.optional?{optional:!0}:{},targets:[]}),t.id}isSecretContext(e,t){switch(e[0]){case"env":case"headers":return dy(e[1]);case"oauth":return"clientSecret"===e[1];case"args":{if(dH([this.argTexts[e[1]]??""]).masked)return!0;let t=this.argTexts[e[1]-1];return void 0!==t&&dH([t,"x"]).args[1]===dp}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,dP(`https://host.invalid/?${n}=x`,dR).masked)}default:return!1}}}function co(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 cd(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 cc=/^[A-Za-z0-9_-]+$/;function cu(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 cp=new Set(["mcp","server","mcp-server","mcpserver","cli","index","main","app","src","dist","build","bin","lib"]);function ch(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=cg(t);return s&&!cp.has(s.toLowerCase())?s:cg(r)||r||s||t}let cm=[/^mcp[-_]server[-_]/i,/^server[-_]/i,/^mcp[-_]/i,/[-_]mcp[-_]server$/i,/[-_]mcp$/i,/[-_]server$/i];function cg(e){let t=e;for(let e=!0;e;)for(let n of(e=!1,cm)){let r=t.replace(n,"");r!==t&&r&&(t=r,e=!0)}return t}let cf=new Set(["mcp","www","api","app","server","servers","remote","gateway"]);function cx(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=>!cf.has(e.toLowerCase()));return r[r.length-1]??n[n.length-1]??""}let cb=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 cv(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 cy(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(!cp.has(n.toLowerCase())&&"."!==n&&".."!==n)return cg(n.replace(/_/g,"-"))||n}return""}function ck(e,t){cj(e,t)&&cw(e,Math.ceil(t/1e3),t)}function cj(e,t){return!!("number"==typeof t&&Number.isFinite(t))&&t>0||(void 0!==t&&e.note("timeout-dropped",{value:String(t)}),!1)}function cw(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 cS=["codemode","deferred","direct","hidden"],cC={"codemode-deferred":"codemode"},cN=["localhost","127.0.0.1","[::1]"];function cI(e){return"string"==typeof e&&cS.includes(e)?e:"string"==typeof e&&Object.hasOwn(cC,e)?cC[e]:void 0}function cE(e){try{return new URL(e)}catch{return}}function c$(e){let t=cE(e);return void 0!==t&&"http:"===t.protocol&&cN.includes(t.hostname)&&""===t.search&&""===t.hash}function cT(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cM(e){return cT(e)&&Object.values(e).every(e=>"string"==typeof e)}function cR(e,t){if(!cc.test(e))return{problem:"name",name:e};if(!cT(t))return{problem:"not-an-object"};let{type:n,exposure:r,enabled:i,timeout:s,toolExposure:a,description:l}=t;if(void 0!==r&&!cI(r))return{problem:"exposure",value:String(r)};if(void 0!==a){if(!cT(a))return{problem:"tool-exposure"};for(let[e,t]of Object.entries(a))if(!cI(t))return{problem:"tool-exposure",tool:e}}if(void 0!==i&&"boolean"!=typeof i)return{problem:"enabled"};if(void 0!==l&&"string"!=typeof l)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=cE(t.url);if(!e||!/^https?:$/.test(e.protocol))return{problem:"url",url:t.url};if(void 0!==t.headers&&!cM(t.headers))return{problem:"headers"};let n=function(e){var t;let n;if(void 0===e)return;if(!cT(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||!c$(e.callbackUrl))return{problem:"callback-url",value:String(e.callbackUrl)};let t=new URL(e.callbackUrl).port;if(t&&void 0!==r&&Number(t)!==r)return{problem:"callback-port-mismatch",value:t}}if(void 0!==e.scope&&"string"!=typeof e.scope)return{problem:"oauth-scope"};if(void 0!==e.clientName&&("string"!=typeof e.clientName||!e.clientName.trim()))return{problem:"oauth-client-name"};if(void 0!==e.clientRegistration&&"auto"!==e.clientRegistration&&"dcr"!==e.clientRegistration){if("cimd"!==e.clientRegistration)return{problem:"oauth-client-registration",value:String(e.clientRegistration)};if(void 0!==e.clientId||void 0!==e.clientName)return{problem:"oauth-client-registration-client"};let t="string"==typeof e.callbackUrl?cE(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)?cE(t):void 0)&&("https:"===n.protocol||"http:"===n.protocol&&cN.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(!cT(r)||"string"!=typeof r.provider||!r.provider)return{problem:"auth"};if("https:"!==e.protocol&&!cN.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||cM(t.env)?void 0!==t.cwd&&"string"!=typeof t.cwd?{problem:"cwd"}:void 0:{problem:"env"}:{problem:"args"}:{problem:"no-command-or-url"}}let cA=/[A-Za-z_]/,cL=/[A-Za-z0-9_]/,cP=/^[A-Za-z_][A-Za-z0-9_]*$/,cz=new Set([..." \n'\"\\$`|&;<>()#*?[]{}!~="]),cO=new Set([..."|&;<>()"]),cW=/[0-9@*#?$!-]/,cF={n:"\n",t:" ",r:"\r",a:"\x07",b:"\b",e:"\x1b",E:"\x1b",f:"\f",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function cD(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 cB(e,t){return/^(?:[A-Za-z]:\\|\\\\[A-Za-z0-9.$_-])/.test(e.slice(t,t+4))}class cH{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 c_)return{ok:!1,error:e.detail};throw e}return{ok:!0,words:this.words}}fail(e){throw new c_(e)}startWord(){return this.parts||(this.lineBreak&&this.fail({code:"multiple-commands"}),this.parts=[],this.windowsWord=cB(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)&&cD(e,this.index)>0)this.index+=cD(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:"`"}):cO.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||!cz.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=cB(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 cF?(t+=cF[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&&cA.test(n)){let n=this.index+1;for(;n<t.length&&cL.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&&cW.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}),cP.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 c_ extends Error{constructor(e){super(e.code),this.detail=e}}function cU(e){return new cH(e).run()}function cK(e){return e.parts.every(e=>"text"===e.type)?e.text:void 0}function cq(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let cZ=["httpUrl","trust","includeTools","excludeTools","authProviderType","targetAudience","targetServiceAccount","tcp"];function cV(e){if(cZ.some(t=>t in e))return!0;let t=e.oauth;return cq(t)&&["redirectUri","authorizationUrl","tokenUrl","audiences","tokenParamName"].some(e=>e in t)}function cJ(e){if(!cq(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]||cq(t)&&"string"==typeof t.path||"string"==typeof n||"string"==typeof r||"string"==typeof i}function cG(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 cY(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 cX(e,t){let n=t?cY(t):void 0;return{code:"sse-transport",params:{...e?{server:e}:{},...t?{url:t}:{},...n?{suggestedUrl:n}:{}}}}function cQ(e){return e?{server:e}:{}}function c0(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?String(e):void 0}function c1(e,t,n){let r;if(!cq(t))return{note:{code:"no-command-or-url",params:cQ(e)}};let i=new Set,s=e=>(i.add(e),t[e]),a=n.rawPi,l=function(e,t){switch(e.flavor){case"zed":return dZ;case"opencode":return dG;case"vscode":return dV;default:return cV(t)?dJ:dV}}(n,t),o=s("name"),d=e??("string"==typeof o?o:void 0),c=new cr(n.source,a),u=(e,t)=>{if(a)return e?[{kind:"pi",text:e}]:[];return t&&"mcp-servers"===n.flavor&&/^!|\$\$|\$!/.test(e)&&c.note("looks-like-pi-config"),d0(e,l,t)};c.name=d,c.inputs=n.inputs;let p=s("inputs");Array.isArray(p)&&(c.inputs=new Map([...n.inputs??[],...c8(p)]));let h=s("type"),m=s("command"),g=[s("httpUrl"),s("url"),s("serverUrl")].find(e=>"string"==typeof e);if("tcp"in t)return{note:{code:"websocket-transport",params:cQ(d)}};if(void 0!==h&&"unknown"===(r="string"==typeof h?cG(h):"unknown"))return{note:{code:"unsupported-transport",params:{...cQ(d),type:String(h)}}};let f="string"==typeof m&&""!==m||Array.isArray(m)||cq(m),x=void 0!==g;if("sse"===r)return{note:cX(d,g)};if("ws"===r)return{note:{code:"websocket-transport",params:{...cQ(d),...g?{url:g}:{}}}};if(void 0===r){if(f&&x)return{note:{code:"ambiguous-command-and-url",params:cQ(d)}};if(x){if(void 0!==cY(g))return{note:cX(d,g)};r="http","mcp-servers"===n.flavor&&"string"==typeof t.url&&"string"!=typeof t.httpUrl&&c.note("transport-guessed")}else{if(!f)return{note:{code:"no-command-or-url",params:cQ(d)}};r="stdio"}}if("stdio"!==r&&"http"!==r)return{note:{code:"unsupported-transport",params:{...cQ(d),type:String(h)}}};if("stdio"===r&&!f||"http"===r&&!x)return{note:{code:"no-command-or-url",params:cQ(d)}};if(c.transport=r,"stdio"===r){let e=function(e,t,n,r,i,s){let a,l=r("args"),o=r("opencode"===s.flavor?"environment":"env");if("opencode"===s.flavor&&void 0===o&&(o=r("env")),Array.isArray(n)){if(!n.every(e=>"string"==typeof e)||0===n.length)return{code:"invalid-config",params:{...cQ(e.name),problem:"args"}};a=n[0],l=[...n.slice(1),...Array.isArray(l)?l:[]]}else if(cq(n))for(let t of(a="string"==typeof n.path?n.path:void 0,void 0===l&&(l=n.args),void 0===o&&(o=n.env),Object.keys(n)))["path","args","env"].includes(t)||e.note("dropped-key",{key:`command.${t}`});else"string"==typeof n&&(a=n);if(!a)return{code:"no-command-or-url",params:cQ(e.name)};let d=Array.isArray(l)?[...l]:[];if(void 0!==l&&!Array.isArray(l))return{code:"invalid-config",params:{...cQ(e.name),problem:"args"}};if(0===d.length&&/\s/.test(a.trim())&&!/^(?:[A-Za-z]:[\\/]|[\\/]|~[\\/]|\.{1,2}[\\/])/.test(a.trim())){let t=cU(a.trim()),n=t.ok?t.words.map(cK):void 0;n&&n.length>1&&n.every(e=>void 0!==e)&&(e.note("command-split",{command:a}),a=n[0],d.push(...n.slice(1)))}for(let[t,n]of(e.command=i(a,!1),d.entries())){let r=c0(n);if(void 0===r)return{code:"invalid-config",params:{...cQ(e.name),problem:"args",index:t}};e.args.push(i(r,!1))}if(void 0!==o){if(!cq(o))return{code:"invalid-config",params:{...cQ(e.name),problem:"env"}};for(let[t,n]of Object.entries(o)){if(null===n){e.note("env-null-dropped",{name:t});continue}let r=c0(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&&dy(t)){e.env.push([t,[{kind:"prompt",id:`env.${t}`,reason:"empty",label:t,from:"",secret:!0}]]);continue}e.env.push([t,i(r,!0)])}}let c=r("cwd");for(let n of("string"==typeof c&&""!==c?e.cwd=i(c,!1):void 0!==c&&""!==c&&e.note("dropped-key",{key:"cwd"}),["headers","oauth","auth","url","httpUrl","serverUrl"]))n in t&&(r(n),e.note("dropped-key",{key:n}))}(c,t,m,s,u,n);if(e)return{note:e}}else!function(e,t,n,r,i){let s=r("headers"),a=i(n,!1),l=cq(s)&&Object.keys(s).some(e=>"authorization"===e.toLowerCase());if(1===a.length&&"text"in a[0]?cd(e,n,l):e.url=a,cq(s))for(let[t,n]of Object.entries(s)){let r=c0(n);if(void 0===r){e.note("dropped-key",{key:`headers.${t}`});continue}if(""===r.trim()){"authorization"===t.toLowerCase()?e.note("empty-authorization-dropped"):dy(t)?e.headers.push([t,[{kind:"prompt",id:`headers.${t}`,reason:"empty",label:t,from:"",secret:!0,optional:!0}]]):e.headers.push([t,[]]);continue}e.headers.push([t,i(r,!0)])}else void 0!==s&&e.note("dropped-key",{key:"headers"});let o=r("oauth"),d=r("auth");if(!1===o?e.note("oauth-disable-unsupported"):cq(o)?c2(e,o,i):void 0!==o&&e.note("dropped-key",{key:"oauth"}),cq(d))for(let t of(c2(e,{...void 0!==d.CLIENT_ID?{clientId:d.CLIENT_ID}:{},...void 0!==d.CLIENT_SECRET?{clientSecret:d.CLIENT_SECRET}:{},...void 0!==d.scopes?{scopes:d.scopes}:{}},i,"auth."),Object.keys(d)))["CLIENT_ID","CLIENT_SECRET","scopes"].includes(t)||e.note("oauth-option-dropped",{key:`auth.${t}`});else void 0!==d&&e.note("dropped-key",{key:"auth"});for(let n of["command","args","env","environment","cwd"])n in t&&(r(n),e.note("dropped-key",{key:n}))}(c,t,g,s,u);let b=s("timeout");if(void 0!==b)if(a)"number"==typeof b&&b>0?c.timeout=b:c.note("timeout-dropped",{value:String(b)});else if("opencode"===n.flavor)c.note("timeout-dropped",{value:String(b)});else if(cV(t))ck(c,b);else["autoApprove","alwaysAllow","transportType"].some(e=>e in t)||"streamableHttp"===t.type?cj(c,b)&&cw(c,Math.ceil(b),void 0):!function(e,t){if(!cj(e,t))return;let n=t>=1e3;e.note("timeout-unit-guessed",{value:t,unit:n?"milliseconds":"seconds"}),n?cw(e,Math.ceil(t/1e3),t):cw(e,Math.ceil(t),void 0)}(c,b);let v=s("enabled"),y=s("disabled");!1===v||!0===y?(c.enabled=!1,c.note("imported-disabled")):(void 0!==v&&"boolean"!=typeof v||void 0!==y&&"boolean"!=typeof y)&&c.note("dropped-key",{key:void 0!==v?"enabled":"disabled"});let k=s("exposure");if(void 0!==k){let e=cI(k);e?c.exposure=e:c.note("invalid-exposure-dropped",{value:String(k)})}let j=s("toolExposure");if(void 0!==j){let e=cq(j)?Object.entries(j).map(e=>{let[t,n]=e;return[t,cI(n)]}):void 0;e?.every(e=>{let[,t]=e;return void 0!==t})?c.toolExposure=Object.fromEntries(e):c.note("invalid-exposure-dropped",{value:"toolExposure"})}if(a||void 0===k&&void 0===j||c.note("looks-like-pi-config"),a){let e=s("description");"string"==typeof e?c.description=e:void 0!==e&&c.note("dropped-key",{key:"description"})}for(let e of(c4(c,s("includeTools"),s("excludeTools")),Object.keys(t)))i.has(e)||c.note("dropped-key",{key:e});return{draft:c}}function c2(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"oauth.";for(let[i,s]of Object.entries(t))switch(i){case"clientId":"string"==typeof s&&""!==s&&(e.oauth.clientId=n(s,!1));break;case"clientSecret":"string"==typeof s&&""!==s&&(e.oauth.clientSecret=n(s,!0));break;case"callbackPort":"number"==typeof s&&Number.isInteger(s)&&s>=1&&s<=65535?e.oauth.callbackPort=s:e.note("callback-port-dropped",{value:String(s)});break;case"clientName":"string"==typeof s&&s.trim()?e.oauth.clientName=n(s,!1):e.note("oauth-option-dropped",{key:`${r}${i}`});break;case"clientRegistration":"auto"===s||"dcr"===s||"cimd"===s?e.oauth.clientRegistration=s:e.note("oauth-option-dropped",{key:`${r}${i}`});break;case"authServerMetadataUrl":"string"==typeof s&&""!==s?e.oauth.authServerMetadataUrl=n(s,!1):e.note("oauth-option-dropped",{key:`${r}${i}`});break;case"callbackUrl":case"redirectUri":"string"==typeof s&&c$(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 c4(e,t,n){let r=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e&&""!==e):[],i=r(t),s=r(n);if(0===i.length&&0===s.length)return;let a={...e.toolExposure??{}};if(i.length>0){let t=e.exposure??"codemode";for(let n of(e.exposure="hidden",i))a[n]=t;e.note("tool-filter-imported",{mode:"include",tools:i.join(", ")})}for(let e of s)a[e]="hidden";s.length>0&&e.note("tool-filter-imported",{mode:"exclude",tools:s.join(", ")}),e.toolExposure=a}function c8(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e)cq(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=>cq(e)?e.value:e).filter(e=>"string"==typeof e)}:{}});return t}function c6(e,t,n,r){let i=[],s=0;for(let a of e.matchAll(/\{([A-Za-z_][A-Za-z0-9_-]*)\}/g)){a.index>s&&i.push({kind:"text",text:e.slice(s,a.index)});let l=cq(t)&&cq(t[a[1]])?t[a[1]]:{};i.push(c3(`${n}${a[1]}`,a[1],a[0],l,r)),s=a.index+a[0].length}return s<e.length&&i.push({kind:"text",text:e.slice(s)}),i}function c3(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 c5(e,t,n){let r=[],i="",s=()=>{i&&("pi"===t?r.push({kind:"pi",text:i}):r.push(...d0(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 c9(e,t){let n="";for(let r=0;r<e.length;r++){let i=e[r];if("variable"===i.type){n+=i.raw;continue}let s=i.value.indexOf(t);if(s<0){n+=i.value;continue}n+=i.value.slice(0,s);let a=i.value.slice(s+t.length);return[n,[...a?[{...i,value:a}]:[],...e.slice(r+1)]]}}let c7=/^https?:\/\//i,ue=/^wss?:\/\//i,ut={"@earendil-works/pi-coding-agent":"pi","@anthropic-ai/claude-code":"claude","@openai/codex":"codex","@google/gemini-cli":"gemini"},un=new Set(["pi","claude","codex","gemini"]),ur=new Set(["install","remove","uninstall","update","list","config"]);function ui(e){return"error"in e?{error:e.error}:{entries:[e],notes:[]}}let us={local:"flag",url:"value",env:"list",cwd:"value",header:"list","bearer-token-env-var":"value","oauth-client-id":"value","oauth-client-secret":"value","oauth-callback-port":"value","oauth-client-name":"value","oauth-client-registration":"value",exposure:"value",description:"value"},ua=new Map([["-l","--local"]]),ul=["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name","oauth-client-registration"],uo=["env","cwd"];function ud(e,t,n,r){let i={positional:[],afterDashDash:[],values:new Map,lists:new Map,seen:new Map};for(let s=0;s<t.length;s++){let a=t[s],l=a.text;if("--"===l){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(!l.startsWith("-")||"-"===l){i.positional.push(a);continue}let o=l.startsWith("--")?l.indexOf("="):-1,d=o>0?l.slice(0,o):l,c=n[d];if(!c){if(i.positional.length>=r.asArgAfter){i.positional.push(a),i.seen.set(`as-arg:${d}`,d);continue}return{error:{code:"cli-unknown-option",params:{cli:e,option:d}}}}if(i.seen.set(c.name,d),"flag"===c.kind){i.values.set(c.name,!0);continue}let u=o>0?uc(a,o+1):void 0;if("value"===c.kind||"list"===c.kind){let n=u??t[++s];if(void 0===n)return{error:{code:"cli-option-needs-value",params:{cli:e,option:d}}};"value"===c.kind?i.values.set(c.name,n):i.lists.set(c.name,[...i.lists.get(c.name)??[],n]);continue}let p=u?[u]:[];if(!u)for(;s+1<t.length&&r.variadic(c.name,t[s+1]);)p.push(t[++s]);if(0===p.length)return{error:{code:"cli-option-needs-value",params:{cli:e,option:d}}};i.lists.set(c.name,[...i.lists.get(c.name)??[],...p])}return i}function uc(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 uu=/^[A-Za-z_][A-Za-z0-9_]*=/,up=/^[^\s:]+:/;function uh(e,t,n,r){for(let i of t??[]){let t=c9(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],c5(t[1],n,!0)])}}function um(e,t,n,r){for(let i of t??[]){let t=c9(i.parts,":"),s=t?.[0].trim();if(!t||!s)return{code:"cli-invalid-pair",params:{cli:r,option:"--header",value:i.text}};let a=function(e){let t=e.map(e=>({...e})),n=t[0];n?.type==="text"&&(n.value=n.value.replace(/^\s+/,""));let r=t[t.length-1];return r?.type==="text"&&(r.value=r.value.replace(/\s+$/,"")),t}(t[1]);if("authorization"===s.toLowerCase()&&a.every(e=>"text"===e.type&&""===e.value)){e.note("empty-authorization-dropped");continue}e.headers.push([s,c5(a,n,!0)])}}function ug(e){if(void 0!==e&&!0!==e){if("user"===e.text)return"global";if("project"===e.text)return"project"}}function uf(e,t,n,r,i){let s,[a,l,...o]=r;if(!a||!l)return{code:"cli-usage",params:{cli:t}};e.name=a.text;let d=void 0===n||!0===n?void 0:n.text.toLowerCase();if(void 0===d){if("http"==(s=c7.test(l.text)?"http":ue.test(l.text)?"ws":"stdio")&&void 0!==cY(l.text))return cX(a.text,l.text);"http"===s&&"gemini"===t&&e.note("transport-assumed-http")}else s="streamable-http"===d?"http":d;return"sse"===s?cX(a.text,l.text):"ws"===s?{code:"websocket-transport",params:{server:a.text,url:l.text}}:"http"===s?(e.transport="http",e.url=c5(l.parts,i,!1),o.length>0&&e.note("cli-extra-arguments",{cli:t,arguments:o.map(e=>e.text).join(" ")}),"http"):"stdio"!==s?{code:"unsupported-transport",params:{server:a.text,type:s}}:(e.transport="stdio",e.command=c5(l.parts,i,!1),e.args=o.map(e=>c5(e.parts,i,!1)),"stdio")}let ux={"-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 ub(e,t){return"env"===e?uu.test(t.text):up.test(t.text)&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(t.text)}function uv(e){e.oauth.clientSecret=[{kind:"prompt",id:"oauth.clientSecret",reason:"client-secret",label:"clientSecret",from:"",secret:!0}],e.note("client-secret-prompt")}let uy={"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"--client-secret":{name:"client-secret",kind:"flag"}};function uk(e){let t,n=cK(e)??e.text;try{t=dK(n)}catch(e){return{error:{code:"invalid-json",params:{detail:e instanceof Error?e.message:String(e)}}}}return cq(t)?{value:t}:{error:{code:"no-servers-found"}}}let uj={"--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"}},uw={"-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 uS(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(uC(r),uC(i))}return t}function uC(e){try{return decodeURIComponent(e)}catch{return e}}function uN(e){let t=e.trim();for(let e=0;e<4;e++)try{return dK(t)}catch{let e=uC(t);if(e===t)break;t=e.trim()}}function uI(e){return{error:{code:"install-link-invalid",params:{detail:e}}}}function uE(e){let t=e.get("config");if(!t)return uI("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:uN(n);return cq(r)?{entries:[c1(e.get("name")||void 0,r,{source:"cursor-install-link",flavor:"mcp-servers",rawPi:!1})],notes:[]}:uI("config")}function u$(e,t,n,r){return cq(e)?{entries:[c1(n,e,{source:t,flavor:"vscode",rawPi:!1,inputs:c8(r)})],notes:[]}:uI("config")}function uT(e){return{error:{code:"by-name-link",params:{name:e}}}}function uM(e){let t=e.indexOf("?");return t<0?"":e.slice(t+1)}function uR(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:[uL(void 0,r)],notes:[]};return{error:{code:"unrecognized-input"}}}if(n>3)return uI("nesting");let i=t.protocol.replace(/:$/,"").toLowerCase();switch(i){case"cursor":if(/\/mcp\/install\/?$/.test(t.pathname))return uE(uS(t.search));return uI("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 uT(uC(t[1]));if(/^mcp\/api\.mcp\.github\.com\//.test(e))return uT(e.replace(/^mcp\//,""));if(/^mcp\/install\?/.test(e))return u$(uN(uM(r)),"vscode-install-link");return uI(i)}case"vsweb+mcp":return u$(uN(uM(r)),"visual-studio-install-link");case"ghapp":if(/^\/\/mcp\/install/.test(r.slice(r.indexOf(":")+1)))return u$(uN(uM(r)),"copilot-app-install-link");return uI(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 uE(uS(e.search));if("vscode.dev"===r||"insiders.vscode.dev"===r){let t=uS(e.search);if(/^\/redirect\/?$/.test(i)&&t.get("url"))return uR(t.get("url"),n+1);if(/^\/redirect\/mcp\/install\/?$/.test(i)){let e=t.get("config");return e?u$(uN(e),"vscode-install-link",t.get("name")||void 0,uN(t.get("inputs")??"[]")):uI("config")}}if("aka.ms"===r&&/^\/vs\/mcp-install\/?$/i.test(i))return u$(uN(e.search.slice(1)),"visual-studio-install-link");if("github.com"===r&&/^\/copilot\/app\/launch\/?$/.test(i)){let t=uS(e.search).get("open");return t?uR(t,n+1):uI("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:[uL(e,t)],notes:[]}}(t,r,n);default:return{error:{code:"unsupported-url-scheme",params:{scheme:i}}}}}let uA=new Set(["localhost","127.0.0.1","[::1]"]);function uL(e,t){let n=cx(t)||void 0;if(void 0!==cY(t))return{note:cX(n,t)};let r=new cr("url",!1);return r.transport="http",cd(r,t,!1),e?.protocol!=="http:"||uA.has(e.hostname)||r.note("insecure-http",{host:e.hostname}),{draft:r}}let uP=/[\u200B-\u200D\u2060\uFEFF]/g,uz=/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]\S*)?$/i,uO={"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 uW(e){return new Set(e.fields.flatMap(e=>e.targets.map(e=>d9(e.path))))}function uF(e){var t;let n,r,i,s,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},l=(n=e.replace(uP,"").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(!l)return{ok:!1,notes:[{code:"empty-input"}]};if(l.startsWith("{")||l.startsWith("[")||/^"[^"\n]+"\s*:/.test(l))s=function(e,t){let n;try{n=dK(e)}catch(t){try{n=dK(`{${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 c1(n,r,t)});if(Array.isArray(e)){let r=e.filter(cJ);return 0===r.length?{error:{code:"no-servers-found"}}:{entries:r.map(e=>c1(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})),notes:n}}if(!cq(e))return{error:{code:"no-servers-found"}};let i=cq(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?ch(t.split("/").pop()??t):void 0,r=Array.isArray(e.remotes)?e.remotes.filter(cq):[],i=r.filter(e=>"string"==typeof e.type&&"http"===cG(e.type)&&"string"==typeof e.url);if(0===i.length){let e=r.find(e=>"sse"===e.type);return e?[{note:cX(n,"string"==typeof e.url?e.url:void 0)}]:[{note:{code:"registry-packages-unsupported",params:cQ(n)}}]}return i.map(e=>{let r=new cr("registry-server-json",!1);for(let i of(r.name=n,t&&n!==t&&(r.originalName=t),r.transport="http",r.url=c6(e.url,e.variables,"url.","registry-variable"),Array.isArray(e.headers)?e.headers.filter(cq):[])){if("string"!=typeof i.name||""===i.name)continue;let e=i.name;"string"==typeof i.value&&""!==i.value?r.headers.push([e,c6(i.value,i.variables,`headers.${e}.`,"registry-header")]):r.headers.push([e,[c3(`headers.${e}`,e,"",i,"registry-header")]])}return{draft:r}})}(i),notes:n};if(cq(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(cq(e.servers)){let t=c8(e.inputs);return{entries:r(e.servers,{source:"vscode-json",flavor:"vscode",rawPi:!1,inputs:t}),notes:n}}if(cq(e.mcp)){let t=e.mcp;if(cq(t.servers)){let e=c8(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(cq(e.context_servers))return{entries:Object.entries(e.context_servers).map(e=>{let t,[n,r]=e;return cq(r)&&("extension"===r.source||!cJ(r))?{note:{code:"zed-extension-server",params:{server:n}}}:c1(n,cq(r)?(t={...r},delete t.source,t):r,{source:"zed-json",flavor:"zed",rawPi:!1})}),notes:n};if(cJ(e))return{entries:[c1(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})],notes:n};let s=Object.values(e);return s.length>0&&s.every(cq)&&s.some(cJ)?{entries:r(e,{source:"server-map",flavor:"mcp-servers",rawPi:t}),notes:n}:{error:{code:"no-servers-found"}}}(n,t)}(l,!0===a.rawPi);else if(uz.test(l)){if(!("error"in(s=uR(`http://${l}`))))for(let e of s.entries)"draft"in e&&e.draft.note("scheme-assumed",{url:`http://${l}`})}else{let e;s=!/\s/.test(l)&&/^[A-Za-z][A-Za-z0-9+.-]+:/.test(l)?uR(l):(e=cU(l.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&&ut[i]&&e[t+1]?.text==="mcp"&&(n=t,r=ut[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 ui(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=ua.get(e[t].text)??e[t].text;if("--"===s||n.length>=2){n.push(...e.slice("--"===s?t+1:t));break}if(!s.startsWith("--")){n.push(e[t]);continue}let a=s.slice(2),l=us[a];if(!l)return{error:{code:"cli-unknown-option",params:{cli:"pi",option:s}}};if("flag"===l){r.set(a,!0);continue}let o=e[++t];if(void 0===o)return{error:{code:"cli-option-needs-value",params:{cli:"pi",option:s}}};"list"===l?i.set(a,[...i.get(a)??[],o]):r.set(a,o)}let[s,...a]=n,l=r.get("url");if(!s||""===s.text||void 0===l==(0===a.length))return{error:{code:"cli-usage",params:{cli:"pi"}}};let o=e=>{let t=r.get(e);return!0===t?void 0:t},d=(void 0===l?ul:uo).find(e=>r.has(e)||i.has(e));if(d)return{error:{code:"cli-option-wrong-transport",params:{cli:"pi",option:`--${d}`,transport:void 0===l?"stdio":"http"}}};let c=new cr("pi-mcp-add",!0);c.name=s.text,c.scopeHint=r.has("local")?"project":"global";let u=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"=",n=[];for(let r of i.get(e)??[]){let i=c9(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!==l&&!0!==l){c.transport="http",c.url=c5(l.parts,"pi",!1);let e=u("header");if("error"in e)return e;for(let[t,n]of e)c.headers.push([t,c5(n,"pi",!0)]);let t=o("bearer-token-env-var");if(void 0!==t){let e=["Authorization",[{kind:"pi",text:`Bearer $\{${t.text}}`}]],n=c.headers.findIndex(e=>{let[t]=e;return"Authorization"===t});n>=0?c.headers[n]=e:c.headers.push(e)}let n=o("oauth-client-id"),r=o("oauth-client-secret"),i=o("oauth-callback-port"),s=o("oauth-client-name"),a=o("oauth-client-registration");n&&(c.oauth.clientId=c5(n.parts,"pi",!1)),r&&(c.oauth.clientSecret=c5(r.parts,"pi",!0)),i&&(c.oauth.callbackPort=Number(i.text)),s&&(c.oauth.clientName=c5(s.parts,"pi",!1)),a&&(c.oauth.clientRegistration=a.text),p.url=l.parts.some(e=>"variable"===e.type)?"https://placeholder.invalid/":l.text,(i||s||a)&&(p.oauth={...n?{clientId:n.text}:{},...i?{callbackPort:Number(i.text)}:{},...s?{clientName:s.text}:{},...a?{clientRegistration:a.text}:{}})}else{c.transport="stdio";let e=u("env");if("error"in e)return e;for(let[t,n]of e)c.env.push([t,c5(n,"pi",!0)]);let[t,...n]=a;c.command=c5(t.parts,"pi",!1),c.args=n.map(e=>c5(e.parts,"pi",!1));let r=o("cwd");r&&(c.cwd=c5(r.parts,"pi",!1)),p.command=t.text}let h=o("exposure");void 0!==h&&(p.exposure=h.text,c.exposure=cI(h.text)??h.text);let m=o("description");void 0!==m&&(p.description=m.text,c.description=m.text);let g=cR("server",p);return g?{note:{code:"invalid-config",params:{server:s.text,...g}}}:{draft:c}}(t,i.slice(1)));if("claude"===r&&"add"===e)return ui(function(e){let t=ud("claude",e,ux,{asArgAfter:2,variadic:ub});if("error"in t)return{error:t.error};let n=new cr("claude-mcp-add",!1),r=uf(n,"claude",t.values.get("transport"),[...t.positional,...t.afterDashDash],dV);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=ug(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=um(n,t.lists.get("header"),dV,"claude");if(r)return{error:r};let a=t.values.get("client-id");a&&!0!==a&&(n.oauth.clientId=c5(a.parts,dV,!1)),t.values.has("client-secret")&&uv(n);let l=t.values.get("callback-port");l&&!0!==l&&(i=n,Number.isInteger(e=Number(s=l.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=uh(n,t.lists.get("env"),dV,"claude");if(e)return{error:e}}return{draft:n}}(t));if("claude"===r&&"add-json"===e)return ui(function(e){let t=ud("claude",e,uy,{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=uk(r);if("error"in s)return s;let a=c1(n.text,s.value,{source:"claude-mcp-add-json",flavor:"mcp-servers",rawPi:!1});return"note"in a||(a.draft.scopeHint=ug(t.values.get("scope")),t.values.has("client-secret")&&"http"===a.draft.transport&&!a.draft.oauth.clientSecret&&uv(a.draft)),a}(t));if("claude"===r&&"add-from-claude-desktop"===e)return{error:{code:"claude-desktop-import"}};if("codex"===r&&"add"===e)return ui(function(e){let t=ud("codex",e,uj,{asArgAfter:1/0,stopAfter:2});if("error"in t)return{error:t.error};let n=t.afterDashDash,r=t.lists.get("env")??[],[i,...s]=t.positional,a=n.length>0?n:s,l=t.values.get("url");if(!i||void 0===l==(0===a.length)||n.length>0&&s.length>0)return{error:{code:"cli-usage",params:{cli:"codex"}}};let o=new cr("codex-mcp-add",!1);for(let e of(o.name=i.text,["config","enable","disable"]))t.values.has(e)&&o.note("cli-option-ignored",{cli:"codex",option:t.seen.get(e)});if(t.values.has("oauth-resource")&&o.note("oauth-option-dropped",{key:"--oauth-resource"}),void 0!==l&&!0!==l){if(r.length>0)return{error:{code:"cli-option-wrong-transport",params:{cli:"codex",option:"--env",transport:"http"}}};if(void 0!==cY(l.text))return{note:cX(i.text,l.text)};o.transport="http",o.url=c5(l.parts,dZ,!1);let e=t.values.get("bearer-token-env-var");e&&!0!==e&&o.headers.push(["Authorization",[{kind:"text",text:"Bearer "},{kind:"env",name:e.text,from:`$\{${e.text}}`}]]);let n=t.values.get("oauth-client-id");n&&!0!==n&&(o.oauth.clientId=c5(n.parts,dZ,!1))}else{for(let e of["bearer-token-env-var","oauth-client-id","oauth-resource"])if(t.values.has(e))return{error:{code:"cli-option-wrong-transport",params:{cli:"codex",option:`--${e}`,transport:"stdio"}}};o.transport="stdio";let e=uh(o,r,dZ,"codex");if(e)return{error:e};o.command=c5(a[0].parts,dZ,!1),o.args=a.slice(1).map(e=>c5(e.parts,dZ,!1))}return{draft:o}}(t));if("gemini"===r&&"add"===e)return ui(function(e){let t=ud("gemini",e,uw,{asArgAfter:2});if("error"in t)return{error:t.error};let n=new cr("gemini-mcp-add",!1),r=uf(n,"gemini",t.values.get("transport"),[...t.positional,...t.afterDashDash],dJ);if("string"!=typeof r)return"cli-usage"===r.code?{error:r}:{note:r};if(n.scopeHint=ug(t.values.get("scope")),"http"===r){t.lists.has("env")&&n.note("cli-option-wrong-transport",{cli:"gemini",option:"--env",transport:"http"});let e=um(n,t.lists.get("header"),dJ,"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=uh(n,t.lists.get("env"),dJ,"gemini");if(e)return{error:e}}let i=t.values.get("timeout");for(let e of(i&&!0!==i&&ck(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 c4(n,s("include-tools"),s("exclude-tools")),{draft:n}}(t));if("add"===e||"install"===e)return{error:{code:"cli-unsupported",params:{cli:r}}};if(un.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]&&ur.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=uc(e[n],10)}if(!r)return{error:{code:"cli-option-needs-value",params:{cli:"code",option:"--add-mcp"}}};let s=uk(r);if("error"in s)return s;t.push(c1(void 0,s.value,{source:"vscode-add-mcp",flavor:"vscode",rawPi:!1}))}return{entries:t,notes:[]}}(e.slice(1)):ui(function(e){let t=new cr("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,c5(r.value,dZ,!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=c5(i.parts,dZ,!1),t.args=e.slice(n+1).map(e=>c5(e.parts,dZ,!1));let s=e.slice(n+1).map(e=>e.text),a=s.some(e=>/^mcp-remote(?:@|$)/.test(e))?s.find(e=>c7.test(e)):void 0;return a&&t.note("mcp-remote-bridge",{url:a}),{draft:t}}(e))}(e.words):{error:function(e){let{code:t,...n}=e;return Object.keys(n).length>0?{code:uO[t],params:n}:{code:uO[t]}}(e.error)}}if("error"in s)return{ok:!1,notes:[s.error]};let o=[...s.notes],d=[],c=[...a.takenNames??[]],u=new Set;for(let e of s.entries){if("note"in e){o.push(e.note);continue}let n=function(e){let t,n=new cl(e);if("stdio"===e.transport&&e.command&&""!==ci(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||""===ci(e.url))return{note:{code:"no-command-or-url",...e.name?{params:{server:e.name}}:{}}};let r=n.encode(["url"],e.url),i={};for(let[t,r]of e.headers)i[t]=n.encode(["headers",t],r);let s={},{clientId:a,clientSecret:l,callbackPort:o,clientName:d,clientRegistration:c,callbackUrl:u,scope:p,authServerMetadataUrl:h}=e.oauth;a&&(s.clientId=n.encode(["oauth","clientId"],a)),l&&(s.clientSecret=n.encode(["oauth","clientSecret"],l)),void 0!==o&&(s.callbackPort=o),d&&(s.clientName=n.encode(["oauth","clientName"],d)),c&&(s.clientRegistration=c),u&&(s.callbackUrl=n.encode(["oauth","callbackUrl"],u)),p&&(s.scope=n.encode(["oauth","scope"],p)),h&&(s.authServerMetadataUrl=n.encode(["oauth","authServerMetadataUrl"],h)),t={url:r,...Object.keys(i).length>0?{headers:i}:{},...Object.keys(s).length>0?{oauth:s}:{}}}return void 0!==e.exposure&&(t.exposure=e.exposure),void 0!==e.toolExposure&&(t.toolExposure=e.toolExposure),!1===e.enabled&&(t.enabled=!1),void 0!==e.timeout&&(t.timeout=e.timeout),void 0!==e.description&&(t.description=e.description),{server:{name:e.name??"",...void 0!==e.originalName?{originalName:e.originalName}:{},config:t,fields:[...n.fields.values()],notes:e.notes,source:e.source,rawPi:e.rawPi,...e.scopeHint?{scopeHint:e.scopeHint}:{}}}}(e.draft);if("note"in n){o.push(n.note);continue}let r=n.server,i=r.name,s=!i;s&&(i=function(e){if("url"in e)return cx(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&&cx(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=cv(t,new Set(["-p","--package","-c","--call"]));return e?ch(e):""}case"pnpm":case"yarn":case"bun":case"npm":{let e=t.findIndex(e=>"dlx"===e||"exec"===e||"x"===e),n=e>=0?cv(t.slice(e+1),new Set(["-p","--package"])):void 0;return n?ch(n):""}case"uvx":case"pipx":{let e=cv("pipx"===n&&"run"===t[0]?t.slice(1):t,new Set(["--from","--with","--python","-p","--index-url","--spec"]));return e?ch(e):""}case"uv":{let e=t.indexOf("run"),n=e>=0?cv(t.slice(e+1),new Set(["--with","--directory","--python","-p","--from","--project"])):void 0;return n?cy(n):""}case"docker":case"podman":{let e=t.indexOf("run"),n=e>=0?cv(t.slice(e+1),cb):void 0;if(!n)return"";let r=n.split("/").pop().replace(/[:@].*$/,"");return cg(r)||r}case"python":case"python3":case"py":{let e=t.indexOf("-m");if(e>=0&&t[e+1])return ch(t[e+1].replace(/_/g,"-"));let n=cv(t,new Set(["-X","-W"]));return n?cy(n):""}case"node":case"deno":case"tsx":case"ts-node":{let e=cv("deno"===n&&"run"===t[0]?t.slice(1):t,new Set(["-r","--require","--import","--loader"]));return e?cy(e):""}default:return cg(n.replace(/_/g,"-"))||n}}(e.command,t)}(r.config))&&r.notes.push({code:"name-derived",params:{name:i}});let a=(t=i,cc.test(t))?i:i.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/-{2,}/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,48).replace(/[-_]+$/g,"")||"server";a!==i&&i&&(r.originalName=r.originalName??i,r.notes.push({code:"name-sanitized",params:{original:i,name:a}}));let l=cu(a,s?[...c,...u]:u);l!==a&&(r.notes.push({code:"name-deduplicated",params:{original:a,name:l}}),a=l),!s&&c.includes(a)&&r.notes.push({code:"name-taken",params:{name:a,suggestedName:cu(a,[...c,...u])}}),r.name=a;let p=cR(a,function(e){let t=uW(e),n=JSON.parse(JSON.stringify(e.config));t.has(d9(["url"]))&&(n.url="https://placeholder.invalid/");let r=n.oauth;return r&&t.has(d9(["oauth","callbackUrl"]))&&delete r.callbackUrl,n}(r));if(p){o.push({code:"invalid-config",params:{server:a,...p}});continue}!function(e){let t=uW(e);for(let n of uZ(e.config))t.has(d9(n))||e.notes.push({code:"literal-secret",params:{field:d7(n)}});let n=e.config;if("url"in n){for(let[t,r]of Object.entries(n.headers??{})){let n=d4(r);n.length>0&&e.notes.push({code:"header-env-reference",params:{header:t,names:n.join(", ")}})}let t=d4(n.oauth?.clientSecret??"");t.length>0&&e.notes.push({code:"client-secret-env-reference",params:{names:t.join(", ")}})}}(r),u.add(a),d.push(r)}return 0===d.length?{ok:!1,notes:o.length>0?o:[{code:"no-servers-found"}]}:{ok:!0,servers:d,notes:o}}let uD=/^[A-Za-z_][A-Za-z0-9_]*$/;function uB(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 uH(e){let t=uW(e);return uZ(e.config).filter(e=>ce(e)&&!t.has(d9(e)))}function u_(e){return"string"==typeof e&&""===e.trim()?"missing":"name"}let uU=/^(?:bearer|basic|token)\s+/i;function uK(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.parse(JSON.stringify(e.config)),i=new Map,s=[],a=new Map(uH(e).map(e=>[d7(e),e])),l=[];for(let[e,t]of Object.entries(n)){let n="string"==typeof t?t.trim():"",r=a.get(e);r?uD.test(n)?l.push([r,n]):s.push({code:"field-reference-invalid",params:{field:e,problem:u_(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():"";uD.test(r)?"select"!==n.kind&&n.targets.every(e=>ce(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:u_(t)}});continue}let r=("string"==typeof e?e:n.defaultValue??"").trim();""===r?n.optional?i.set(n.id,void 0):s.push({code:"field-required",params:{field:n.id}}):"select"===n.kind&&n.options&&!n.options.includes(r)?s.push({code:"field-invalid-option",params:{field:n.id}}):i.set(n.id,{text:r})}if(s.length>0)return{ok:!1,notes:s};let o=new Set,d=new Set;for(let t of e.fields)for(let e of t.targets){let n=i.get(t.id);"password"===t.kind&&void 0!==n&&"text"in n&&o.add(d7(e.path));let s=d9(e.path);if(d.has(s))continue;if(d.add(s),e.parts.some(e=>"string"!=typeof e&&void 0===i.get(e.field))){uB(r,e.path,void 0);continue}let a="";for(let t of e.parts){var c,u,p,h;a+="string"==typeof t?t:(c=i.get(t.field),u=e.path,p=""===a,h=e.encoding,"reference"in c?`$\{${c.reference}}`:"uri-component"===h?encodeURIComponent(c.text):ce(u)?d1(c.text,{atStart:p}):c.text)}uB(r,e.path,a)}for(let[e,t]of l){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(uU)?.[0]??"":"";uB(r,e,`${i}$\{${t}}`)}for(let e of uZ(r))o.add(d7(e));return{ok:!0,config:r,secretPaths:[...o]}}let uq=["command","args","env","cwd","url","headers","oauth"];function uZ(e){let t=[];for(let n of function(e){if(!d_(e))return[];let t=[];for(let n of["env","headers"]){let r=e[n];if(d_(r))for(let[e,i]of Object.entries(r))"string"==typeof i&&dU(i)&&""!==i&&(dy(e)||/^(?:bearer|basic|token)\s+\S/i.test(i)||dW(i,d$).masked)&&t.push({kind:"env"===n?"env":"header",name:e})}let n=d_(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&""!==n&&dU(n)&&t.push({kind:"oauth-client-secret"}),"string"==typeof e.url&&dP(e.url,dR).masked&&t.push({kind:"url"}),"string"==typeof e.command&&dW(e.command,dR).masked&&t.push({kind:"command"}),Array.isArray(e.args)&&dH(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:""):[];dH(n).args.forEach((e,r)=>{e!==n[r]&&t.push(["args",r])})}}return t.sort((e,t)=>uq.indexOf(e[0])-uq.indexOf(t[0]))}let uV="PI_WEB_PASSWORD";function uJ(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function uG(e){return uJ(e)?Object.entries(e).filter(e=>"string"==typeof e[1]):[]}function uY(e){if(!uJ(e))return[];if(!("url"in e))return uG(e.env).map(e=>{let[t,n]=e;return{kind:"env",name:t,value:n}});let t=uG(e.headers).map(e=>{let[t,n]=e;return{kind:"header",name:t,value:n}}),n=uJ(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&t.push({kind:"oauth-client-secret",value:n}),t}let uX={text:"",rawPi:!1,server:0,values:{},references:{},secretReferences:{}};function uQ(e,t,n){let r=uF(e,{rawPi:t});if(!r.ok)return;let i=r.servers[Math.min(n,r.servers.length-1)],{config:s}=i,a="url"in s?["url",s.url]:["command",s.command,s.args??[]];return JSON.stringify([i.source,i.originalName??i.name,a])}function u0(e,t){let n={...e,...t},r=uQ(e.text,e.rawPi,e.server);if(void 0!==r&&r===uQ(n.text,n.rawPi,e.server))return n;let i={...n,server:0,values:{},references:{},secretReferences:{}};return delete i.name,i}function u1(e){return dq[e.code]??"warning"}function u2(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?os(t):t;if("string"==typeof i.field&&e.code.startsWith("field-")){let e=r.find(e=>e.id===i.field);e&&(s.field=os(e.label))}"invalid-config"===e.code&&(s.problem=t("tool-exposure"===(n=String(i.problem??"no-command-or-url"))&&void 0!==i.tool?"mcp.importProblem.tool-exposure.tool":"args"===n&&void 0!==i.index?"mcp.importProblem.args.index":`mcp.importProblem.${n}`,s)),"cli-option-wrong-transport"===e.code&&("stdio"===i.transport||"http"===i.transport)&&(s.transport=t(`mcp.transport.${i.transport}`));let a=t(function(e){let t=e.params??{};switch(e.code){case"field-reference-invalid":return`mcp.importNote.field-reference-invalid.${"target"===t.problem||"missing"===t.problem?t.problem:"name"}`;case"sse-transport":return void 0===t.suggestedUrl?"mcp.importNote.sse-transport":"mcp.importNote.sse-transport.suggested";case"timeout-unit-guessed":return`mcp.importNote.timeout-unit-guessed.${"milliseconds"===t.unit?"milliseconds":"seconds"}`;case"tool-filter-imported":return`mcp.importNote.tool-filter-imported.${"exclude"===t.mode?"exclude":"include"}`;default:return`mcp.importNote.${e.code}`}}(e),s);return"string"==typeof s.server?t("mcp.importNote.forServer",{server:s.server,note:a}):a}let u4={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"},u8={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"},u6=JSON.stringify({command:"uvx",args:["mcp-server-fetch"]}),u3=JSON.stringify({name:"fetch",command:"uvx",args:["mcp-server-fetch"]}),u5=[{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 '${u3}'`},{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(u6)}`},{source:"vscode-install-link",text:`vscode:mcp/install?${encodeURIComponent(u3)}`},{source:"visual-studio-install-link",text:`vsweb+mcp:/install?${encodeURIComponent(u3)}`},{source:"copilot-app-install-link",text:`ghapp://mcp/install?${encodeURIComponent(u3)}`}];function u9(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?os(r):r.field===e.id?n:`‹${os(t.find(e=>{let{id:t}=e;return t===r.field})?.label??r.field)}›`).join("")}))].join(", ")}function u7(e){return"select"!==e.kind&&e.targets.every(e=>ce(e.path)&&void 0===e.encoding)}let pe=/^[A-Za-z_][A-Za-z0-9_]*$/;function pt(){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 pe.test(r)?r:void 0}let pn=/^(?:proxy-)?authorization$/i;function pr(e,t){let n=function(e,t){if(e.startsWith("env.")){let t=e.slice(4);return pe.test(t)?t:pt(t)}let n=function(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];return pt(t,...n)??pt(...n)};if(e.startsWith("headers.")){let t=e.slice(8);return n(pn.test(t)?"TOKEN":t.replace(/^x-/i,""))}if("oauth.clientSecret"===e)return n("CLIENT_SECRET")}(e,t);return n===uV?void 0:n}function pi(e){return e.startsWith("env.")||e.startsWith("headers.")||"oauth.clientSecret"===e}function ps(e,t){let n=e;for(let e of t)n=n.split(e).join(dp);return{text:n,masked:n!==e}}function pa(e){let{kind:t,name:n}=e;return void 0===n?{kind:t}:{kind:t,name:n}}function pl(e,t){let n=t.files.find(t=>t.scope===e),r=n?.problems.find(oP);return n&&r?{kind:"file-problem",path:n.path,reason:r.reason}:void 0}function po(e,t){return e.servers.filter(e=>e.scope===t).map(e=>e.name)}function pd(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 pc(e,t,n){switch(e.kind){case"trust-too-broad":return t(pp[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(pu[e.kind])}}let pu={"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"},pp={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 ph(e){return os(ep(e))}function pm(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}let pg=[{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"}],pf=new Set(["name-derived","name-sanitized","name-deduplicated","name-taken"]);function px(e){let{notes:t,fields:n=[]}=e,{t:i}=(0,eX.s)();if(0===t.length)return null;let s={error:0,warning:1,info:2},a=[...t].sort((e,t)=>s[u1(e)]-s[u1(t)]);return(0,r.jsx)("ul",{className:"mcp-add-notes",children:a.map((e,t)=>(0,r.jsx)("li",{className:`mcp-add-note is-${u1(e)}`,children:u2(e,i,n)},`${t}\0${e.code}`))})}let pb={"server-invalid":"mcp.add.refused.server-invalid","web-password":"mcp.add.blocked.web-password"};function pv(e){let{data:t,cwd:n,draft:s,busy:a,controlsBusy:l,failure:o,onDraftChange:d,onSubmit:c,onTrustProject:u}=e,{t:p}=(0,eX.s)(),h=(0,i.useId)(),m=(0,i.useId)(),g=(0,i.useMemo)(()=>(function e(t,n,r){let i,s=function(e,t){let n=e=>({kind:"blocked",block:e});if(!t)return n({kind:"no-project"});let r=e.project;if(!r)return n({kind:"project-not-listed"});let i=r.trust;if(!i||void 0!==i.decisionError)return n({kind:"trust-unreadable"});if(!0===i.decision)return{kind:"write"};if(!1===i.decision)return n({kind:"untrusted-decision"});if(i.requiresTrust)return n({kind:"project-untrusted",trustable:oF(r)});let s=r.trustFolder;return s?s.allowed?{kind:"trust-and-write",folder:r.cwd}:n("trust-too-broad"===s.reason?{kind:"trust-too-broad",breadth:s.breadth}:{kind:"folder-not-fresh"}):n({kind:"project-untrusted",trustable:!1})}(n,r),a=e=>uF(t.text,{rawPi:t.rawPi,takenNames:po(n,e)}),l=a(t.scope??"global"),o=l.ok?l.servers[Math.min(t.server,l.servers.length-1)]:void 0,d=t.scope??(o?.scopeHint==="project"&&"write"===s.kind?"project":"global");d!==(t.scope??"global")&&(o=(l=a(d)).ok?l.servers[Math.min(t.server,l.servers.length-1)]:void 0);let c={parsed:l,name:t.name??"",scope:d,projectMode:s,..."blocked"===s.kind?{projectBlock:s.block}:{},values:{},pasteSecrets:[],secretReferences:{},fieldProblems:{},secretPaths:[],trustFolder:!1},u=o6(n.mcp);if(!o)return{...c,submitBlock:{kind:u?"mcp-off":"nothing"}};let p=t.name??o.name,h=function(e,t){let n={};for(let r of e.fields){let e=t.references[r.id];void 0!==e&&u7(r)?n[r.id]={reference:e}:void 0!==t.values[r.id]&&(n[r.id]=t.values[r.id])}return n}(o,t),m=uH(o).map(d7),g=Object.fromEntries(m.flatMap(e=>{let n=t.secretReferences[e];return void 0===n?[]:[[e,n]]})),f=uK(o,h,g),x={};if(!f.ok)for(let e of f.notes){let t=e.params?.field;"field-required"===e.code||"string"!=typeof t||t in x||(x[t]=e)}let b=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={};for(let n of e.fields){let e=t[n.id];"object"==typeof e?r[n.id]=pe.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=uK(e,r,Object.fromEntries(Object.entries(n).map(e=>{let[t,n]=e;return[t,pe.test(n.trim())?n:"VALUE"]})));return i.ok?i.secretPaths:[]}(o,h,g),v=function(e,t,n){let r=n?.ok?n.config:e.config,i=n?.ok?function(e,t){let n=new Set;for(let r of e.fields){let e=t[r.id];if("password"!==r.kind||"string"!=typeof e||""===e.trim())continue;let i=e.trim();n.add(i),n.add(i.replace(/\$/g,"$$$$")),n.add(encodeURIComponent(i))}return[...n].filter(e=>""!==e).sort((e,t)=>t.length-e.length)}(e,t):[],s=!1!==r.enabled,a={source:e.source,commandFields:uY(r).filter(e=>{let{value:t}=e;return d2(t)}).map(pa),variableReferences:uY(r).map(e=>({...pa(e),variables:d4(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=ps(r.url,i);return{...a,transport:"http",target:os(e.text),envNames:[],headerNames:Object.keys(r.headers??{}),masked:e.masked}}let l=ps(oo(r.command,r.args??[]),i);return{...a,transport:"stdio",target:l.text,...void 0!==r.cwd?{cwd:os(r.cwd)}:{},envNames:Object.keys(r.env??{}),headerNames:[],masked:l.masked}}(o,h,f),y=f.ok?cR(p,f.config):void 0,k="blocked"===s.kind?s.block:b.length>0?{kind:"secret",fields:b,fixed:!b.every(pi)}:pl("project",n),j=po(n,d),w=n.files.find(e=>e.scope===d);if(u)i={kind:"mcp-off"};else if(cc.test(p))if(j.includes(p))i={kind:"name-taken",name:p,suggestedName:cu(p,j),...w?{path:w.path}:{}};else if(f.ok)if(y)i={kind:"config-invalid",note:{code:"invalid-config",params:"url"===y.problem?{...y,url:v.target}:y}};else if(void 0!==function(e,t){for(let{value:n,...r}of uY(e))if(t.isCommandConfigValue(n)?n.toUpperCase().includes(uV):t.getConfigValueEnvVarNames(n).some(e=>e.toUpperCase()===uV))return r}(f.config,{isCommandConfigValue:d2,getConfigValueEnvVarNames:d4}))i={kind:"web-password"};else if("project"===d&&k)i={kind:"scope",block:k};else{let e=pl(d,n);e&&(i={kind:"scope",block:e})}else{let e=e=>{let t=String(e.params?.field??"");return o.fields.find(e=>e.id===t)?.label??t},t=f.notes.filter(e=>"field-required"===e.code||"field-reference-invalid"===e.code&&e.params?.problem==="missing");i=t.length>0?{kind:"fields",fields:[...new Set(t.map(e))]}:{kind:"field-invalid",fields:[...new Set(f.notes.map(e))]}}else i={kind:"name-invalid"};return void 0===t.scope&&"project"===d&&k?e({...t,scope:"global"},n,r):{parsed:l,server:o,name:p,scope:d,projectMode:s,...k?{projectBlock:k}:{},values:h,pasteSecrets:m,secretReferences:g,fill:f,fieldProblems:x,secretPaths:b,preview:v,...i?{submitBlock:i}:{},trustFolder:"project"===d&&"trust-and-write"===s.kind}})(s,t,n),[s,t,n]),f=(0,i.useMemo)(()=>(function(e){let t=uF(e,{rawPi:!0});if(!t.ok)return!1;let n=uF(e,{rawPi:!1});return t.servers.some((e,t)=>e.rawPi&&!(n.ok&&n.servers[t]?.rawPi))})(s.text),[s.text]),{parsed:x,server:b,preview:v,projectBlock:y,submitBlock:k}=g,j=b?[...b.notes,...x.notes].filter(e=>"literal-secret"!==e.code||!g.pasteSecrets.includes(String(e.params?.field))):[],w=void 0!==s.name&&s.name!==b?.name?[]:j.filter(e=>pf.has(e.code)),S=j.filter(e=>!pf.has(e.code)),C=!a&&!l&&void 0===k,N=()=>{C&&c(pd(s,g))},I=e=>d({...s,...e}),E=t.files.find(e=>e.scope===g.scope)?.path??("project"===g.scope&&n?`${n.replace(/[\\/]+$/,"")}/.pi/mcp.json`:"mcp.json"),$=k&&(""!==s.text.trim()||"mcp-off"===k.kind)?function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];switch(e.kind){case"mcp-off":return t("mcp.reason.mcp-off");case"nothing":return t("mcp.add.blocked.nothing");case"name-invalid":return t("mcp.add.nameInvalid");case"name-taken":return t("mcp.add.nameTaken",{name:os(e.name),path:e.path?ph(e.path):"mcp.json"});case"fields":return t("mcp.add.blocked.fields",{fields:e.fields.map(os).join(", ")});case"field-invalid":return t("mcp.add.blocked.fieldsInvalid",{fields:e.fields.map(os).join(", ")});case"config-invalid":return u2(e.note,t,n);case"web-password":return t("mcp.add.blocked.web-password");case"scope":return pc(e.block,t,ph)}}(k,p,b?.fields):void 0,T=y?.kind==="project-untrusted"&&y.trustable&&u,M=v?"http"===v.transport?v.headerNames:v.envNames:[];return(0,r.jsxs)(aL,{title:p("mcp.add.title"),catalogs:pg,target:(0,r.jsxs)(aR,{value:g.scope,label:p("config.saveTo"),options:[{value:"global",label:pm("global",p)},{value:"project",label:pm("project",p),disabled:void 0!==y&&"project"!==g.scope}],path:ph(E),disabledReason:y?pc(y,p,ph):null,onChange:e=>I({scope:e}),children:[T&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aB,{size:"small",onClick:u,children:p("mcp.trust.trustButton")})}),g.trustFolder&&"trust-and-write"===g.projectMode.kind&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:p("mcp.add.trustExplain",{path:ph(g.projectMode.folder)})})]}),inputLabel:p("mcp.add.inputLabel"),inputId:"mcp-add-source",placeholder:p("mcp.add.placeholder"),value:s.text,canSubmit:C,onValueChange:e=>d(u0(s,{text:e})),onSubmit:N,examplesLabel:p("mcp.add.examples"),examples:""===s.text.trim()?u5.map(e=>{let{source:t,text:n}=e;return{label:p(u8[t]),value:n}}):[],multiline:!0,children:[f&&(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:s.rawPi,onChange:e=>d(u0(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)(px,{notes:x.notes}),x.ok&&x.servers.length>1&&(0,r.jsxs)(aI,{label:p("mcp.add.serverLabel"),children:[(0,r.jsx)("select",{className:"mcp-add-input","aria-label":p("mcp.add.serverLabel"),value:String(x.servers.indexOf(b??x.servers[0])),onChange:e=>I({server:Number(e.target.value),name:void 0,values:{},references:{},secretReferences:{}}),children:x.servers.map((e,t)=>(0,r.jsx)("option",{value:t,children:os(e.name)},`${t}\0${e.name}`))}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.serverCount",{count:x.servers.length})})]}),b&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(aI,{label:p("config.name"),children:(0,r.jsx)("input",{id:m,className:"mcp-add-input","aria-label":p("config.name"),value:g.name,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>I({name:e.target.value})})}),(0,r.jsx)(px,{notes:w,fields:b.fields}),k?.kind==="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aB,{size:"small",onClick:()=>I({name:k.suggestedName}),children:p("mcp.add.useName",{name:os(k.suggestedName)})})})]}),b&&v&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(aN,{children:p("mcp.add.preview")}),(0,r.jsxs)(aE,{children:[(0,r.jsx)(a$,{label:p("mcp.add.readAs"),children:p(u8[v.source])}),(0,r.jsx)(a$,{label:p("mcp.detail.transport"),children:p(`mcp.transport.${v.transport}`)}),(0,r.jsx)(a$,{label:"http"===v.transport?p("mcp.detail.url"):p("mcp.detail.command"),tone:"plain",mono:!0,children:v.target}),"stdio"===v.transport&&void 0!==v.cwd&&(0,r.jsx)(a$,{label:p("mcp.detail.cwd"),mono:!0,children:v.cwd}),M.length>0&&(0,r.jsx)(a$,{label:"http"===v.transport?p("mcp.detail.headers"):p("mcp.detail.env"),children:(0,r.jsx)(py,{names:M})}),v.commandFields.length>0&&(0,r.jsx)(a$,{label:p("mcp.detail.shellCommands"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.server.commandFields")}),(0,r.jsx)("span",{className:"mcp-config-chips",children:v.commandFields.map(e=>{let t=ou(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})]})}),v.variableReferences.length>0&&(0,r.jsx)(a$,{label:p("mcp.detail.variables"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("http"===v.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables")}),(0,r.jsx)("span",{className:"mcp-config-chips",children:om(v.variableReferences).map(e=>{let{variable:t,field:n}=e,i=ou(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p("mcp.server.variableIn",{variable:os(t),field:p(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[v.unfilled&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.previewUnfilled")}),v.masked&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.server.masked")})]}),(0,r.jsx)(px,{notes:S,fields:b.fields}),b.fields.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(aN,{children:p("mcp.add.fields")}),b.fields.map(e=>{var t;let n;return(0,r.jsx)(pk,{field:e,fields:b.fields,draft:s,suggestedName:(t=g.name,(n=e.targets[0])?pr(d7(n.path),t):void 0),problem:g.fieldProblems[e.id],onDraftChange:d},e.id)})]}),g.pasteSecrets.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(aN,{children:p("mcp.add.secrets")}),g.pasteSecrets.map(e=>{var t,n;let i;return(0,r.jsx)(pj,{label:e,draft:s,suggestedName:pr(e,g.name),stored:g.fill?.ok?(t=g.fill.config,void 0!==(i="oauth.clientSecret"===(n=e)?"url"in t?t.oauth?.clientSecret:void 0:n.startsWith("headers.")?"url"in t?t.headers?.[n.slice(8)]:void 0:n.startsWith("env.")&&"command"in t?t.env?.[n.slice(4)]:void 0)&&d$(i)?i:void 0):void 0,problem:g.fieldProblems[e],onDraftChange:d},e)})]})]}),(0,r.jsx)(aB,{variant:"primary",className:"is-pushed-right",disabled:!C,"aria-busy":a||void 0,"aria-describedby":$?h:void 0,onClick:N,children:a?p("mcp.add.adding"):g.trustFolder?p("mcp.add.buttonTrust"):p("mcp.add.button")}),$&&(0,r.jsx)("p",{id:h,className:`mcp-config-line ${k?.kind==="scope"?"is-warning":"is-dim"}`,children:$}),b&&!k&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:p("mcp.add.afterAdd")}),o&&(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(pp[e.breadth.kind],{path:ph(e.breadth.path)});if("secret-global-only"===e.reason&&e.fields)return t(e.fields.every(pi)?"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:os(e.name),path:e.path?ph(e.path):"mcp.json"});let n=e.reason?pb[e.reason]:void 0;return n?t(n,{error:os(e.error)}):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):os(e.error)}(o,p)]}),o.trustKept&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.trustKept",{folder:ph(o.trust?.decisionPath??n??"")})}),o.notes&&o.notes.length>0&&(0,r.jsx)(px,{notes:o.notes,fields:b?.fields}),"name-taken"===o.reason&&o.suggestedName&&k?.kind!=="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aB,{size:"small",onClick:()=>I({name:o.suggestedName}),children:p("mcp.add.useName",{name:os(o.suggestedName)})})}),"host-env-confirm"===o.reason&&o.names&&o.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:o.names.map(os).join(", ")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aB,{variant:"danger",size:"small",disabled:a||l||void 0!==k,onClick:()=>c(pd(s,g,o.names)),children:p("mcp.add.hostEnv.confirm")})})]})]})]})}function py(e){let{names:t}=e,{t:n}=(0,eX.s)();return(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>(0,r.jsx)("code",{className:"mcp-config-chip",children:os(e)},e))}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.detail.valuesHidden")})]})}function pk(e){let t,{field:n,fields:s,draft:a,suggestedName:l,problem:o,onDraftChange:d}=e,{t:c}=(0,eX.s)(),u=(0,i.useId)(),p=o?{"aria-invalid":!0,"aria-describedby":u}:{},h=u7(n),m=h?a.references[n.id]:void 0,g=void 0!==m,f=os(n.label),x=a.values[n.id]??n.defaultValue??"",b=u4[n.reason],v=n.optional&&1===(t=new Set(n.targets.map(e=>{let{path:t}=e;return"headers"===t[0]?t[1]:void 0}))).size?[...t][0]:void 0,y=g?m&&!o?u9(n,s,"${"+m+"}",!0):void 0:u9(n,s,`‹${c("mcp.add.field.slot")}›`),k=e=>d({...a,values:{...a.values,[n.id]:e}}),j=e=>{let t={...a.references};void 0===e?delete t[n.id]:t[n.id]=e,d({...a,references:t})};return(0,r.jsxs)("div",{className:"mcp-add-field",children:[(0,r.jsx)(aI,{label:f,children:g?(0,r.jsx)("input",{className:"mcp-add-input","aria-label":c("mcp.add.field.variableName",{field:f}),value:m,placeholder:l??"GITHUB_TOKEN",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...p,onChange:e=>j(e.target.value)}):"select"===n.kind?(0,r.jsxs)("select",{className:"mcp-add-input","aria-label":f,value:x,...p,onChange:e=>k(e.target.value),children:[!n.options?.includes(x)&&(0,r.jsx)("option",{value:"",children:c("mcp.add.field.choose")}),(n.options??[]).map(e=>(0,r.jsx)("option",{value:e,children:os(e)},e))]}):(0,r.jsx)("input",{className:"mcp-add-input",type:"password"===n.kind?"password":"text","aria-label":f,value:x,autoComplete:"off",placeholder:n.placeholder?os(n.placeholder):void 0,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...p,onChange:e=>k(e.target.value)})}),o&&(0,r.jsx)("span",{id:u,className:"mcp-config-line is-error",children:u2(o,c,[n])}),(0,r.jsxs)("span",{className:"mcp-config-lines",children:[n.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:os(n.description)}),b&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:c(b)}),g?(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:y?c("mcp.add.field.storedAsVariable",{value:y}):c("mcp.add.field.variableHint")}):(0,r.jsxs)(r.Fragment,{children:[y&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:c("mcp.add.field.storedAs",{value:y})}),n.optional&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:v?c("mcp.add.field.optionalHeader",{name:os(v)}):c("mcp.add.field.optional")})]})]}),h&&(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:g,onChange:e=>j(e.target.checked?l??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:c("mcp.add.field.useVariable")})]})]})}function pj(e){let{label:t,draft:n,suggestedName:s,stored:a,problem:l,onDraftChange:o}=e,{t:d}=(0,eX.s)(),c=(0,i.useId)(),u=n.secretReferences[t],p=void 0!==u,h=os(t),m=e=>{let r={...n.secretReferences};void 0===e?delete r[t]:r[t]=e,o({...n,secretReferences:r})};return(0,r.jsxs)("div",{className:"mcp-add-field",children:[(0,r.jsx)("span",{className:"mcp-config-lines",children:(0,r.jsxs)("span",{className:"mcp-config-line",children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:h})," ",d("mcp.add.secret.holds")]})}),(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:p,onChange:e=>m(e.target.checked?s??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("mcp.add.field.useVariable")})]}),p&&(0,r.jsx)(aI,{label:d("mcp.add.field.variableName",{field:h}),children:(0,r.jsx)("input",{className:"mcp-add-input","aria-label":d("mcp.add.field.variableName",{field:h}),value:u,placeholder:s??"API_TOKEN",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...l?{"aria-invalid":!0,"aria-describedby":c}:{},onChange:e=>m(e.target.value)})}),l&&(0,r.jsx)("span",{id:c,className:"mcp-config-line is-error",children:u2(l,d)}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p?void 0!==a?d("mcp.add.secret.storedAs",{value:os(a)}):d("mcp.add.field.variableHint"):d("mcp.add.secret.asPasted")})]})}let pw=new Set(["done","failed","cancelled","expired"]);function pS(e){var t;return e?.flow!==void 0&&!e.gone&&(t=e.flow.phase,!pw.has(t))}let pC={"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"},pN={"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"},pI={connecting:"mcp.signIn.phase.connecting",starting:"mcp.signIn.phase.starting",finishing:"mcp.signIn.phase.finishing"},pE={"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 p$(e,t,n){var r;let i={...e,flow:t,deadlineAt:n+t.expiresInMs,gone:!1};return r=t.phase,pw.has(r)&&(delete i.pasteError,delete i.cancelError,i.pasting&&(i.pasting=!1),i.cancelling&&(i.cancelling=!1)),i}function pT(e){return"sign-in-unknown"===e.reason}async function pM(e,t,n,r){var i;let s,a;try{s=await n(e,{...t,cache:"no-store",signal:r})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{a=await s.json()}catch{return{ok:!1,error:{error:`HTTP ${s.status}`}}}return s.ok&&null!==(i=a)&&"object"==typeof i&&"string"==typeof i.flowId&&"string"==typeof i.phase&&"string"==typeof i.name&&("global"===i.scope||"project"===i.scope)&&"number"==typeof i.expiresInMs?{ok:!0,data:a}:{ok:!1,error:oZ(a,s.status)}}function pR(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},a=t.method??"GET";return oV(r=>pM(e,t,n,r),()=>({ok:!1,error:{error:`${a} ${e} did not answer within ${i} ms`,timedOut:!0}}),i,r,s)}function pA(e){return`/api/mcp/sign-in/${encodeURIComponent(e)}`}function pL(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?pN[e.reason]:void 0;return r?t(r):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function pP(e){let{server:t,run:n,block:s,signOutBlock:a,blockSaidBy:l,signOutBlockSaidBy:o,controlsBusy:d,signingOut:c,onSignIn:u,onSignOut:p,onPaste:h,onCancel:m}=e,{t:g}=(0,eX.s)(),f=(0,i.useId)(),x=(0,i.useId)(),b=(0,i.useId)(),v=(0,i.useRef)(null),y=(0,i.useRef)(null),k=pS(n),j=(0,i.useRef)(k);if((0,i.useEffect)(()=>{let e=j.current;j.current=k,!e&&k?eE(document,y.current):e&&!k&&eE(document,v.current)},[k]),!t.usesOAuth)return void 0===t.authProvider&&t.headerNames.some(e=>"authorization"===e.toLowerCase())?null:(0,r.jsx)(a$,{label:g("mcp.detail.signIn"),children:void 0!==t.authProvider?g("mcp.signIn.provider",{provider:os(t.authProvider)}):g("mcp.signIn.header")});let w=n?.flow,S=n?.starting===!0,C=void 0!==w&&(w.scope!==t.scope||w.name!==t.name),N=(t.oauthStateStored??t.signedIn)!==!1,I=S||c||void 0!==s,E=d||S||void 0!==a,$=w?.phase==="finishing";return(0,r.jsx)(a$,{label:g("mcp.detail.signIn"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line",children:g(!0===t.signedIn?"mcp.signIn.signedIn":!1===t.signedIn?t.oauthStateStored?"mcp.signIn.registrationOnly":"mcp.signIn.notSignedIn":"mcp.signIn.unknown")}),w&&k&&C&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:g("mcp.signIn.shared",{name:os(w.name)})}),w&&k&&("authorize"===w.phase?(0,r.jsx)(pz,{flow:w,pasting:n?.pasting===!0,pasteError:n?.pasteError,onPaste:e=>h(t,w.flowId,e)},w.flowId):(0,r.jsx)("span",{role:"status",className:"mcp-config-line",children:g(pI[w.phase]??"mcp.signIn.phase.connecting")})),w&&k&&$&&(0,r.jsx)("span",{id:b,className:"mcp-config-line is-dim",children:g("mcp.signIn.phase.noCancel")}),w&&!k&&!n?.gone&&(0,r.jsx)(pO,{flow:w,shared:C}),n?.gone&&(0,r.jsx)("span",{role:"alert",className:"mcp-config-line is-warning",children:g("mcp.signIn.gone")}),n?.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[g("mcp.signIn.requestFailed")," ",pL(n.error,g)]}),k&&n?.cancelError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[g("mcp.signIn.cancelFailed")," ",pL(n.cancelError,g,"mcp.signIn.cancelTimedOut")]}),n?.signOutError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[g("mcp.signIn.signOutFailed")," ",pL(n.signOutError,g,"mcp.actionTimedOut")]}),n?.signedOut&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line",children:g(n.signedOut.removed?"mcp.signIn.signedOutDone":"mcp.signIn.signedOutNothing")}),s&&!l&&(0,r.jsx)("span",{id:f,className:"mcp-config-line is-dim",children:g(pC[s])}),!s&&a&&!o&&N&&!k&&(0,r.jsx)("span",{id:x,className:"mcp-config-line is-dim",children:g(pC[a])}),(0,r.jsxs)("div",{className:"mcp-sign-in-actions",children:[k&&w?(0,r.jsx)(aB,{ref:y,size:"small",disabled:n?.cancelling===!0||$,"aria-busy":n?.cancelling===!0||void 0,"aria-describedby":$?b:void 0,onClick:()=>m(t,w.flowId),children:g(n?.cancelling?"mcp.signIn.cancelling":"mcp.signIn.cancel")}):(0,r.jsx)(aB,{ref:v,size:"small",variant:"primary",disabled:I,"aria-busy":S||void 0,"aria-describedby":s?l??f:void 0,onClick:()=>u(t),children:g(S?"mcp.signIn.starting":"mcp.signIn.button")}),N&&!k&&(0,r.jsx)(aB,{size:"small",disabled:E,"aria-busy":c||void 0,"aria-describedby":a?s?l??f:o??x:void 0,onClick:()=>p(t),children:g(c?"mcp.signIn.signingOut":"mcp.signIn.signOut")})]}),!s&&!k&&N&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:g("mcp.signIn.replaces")}),N&&!a&&!k&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:g("mcp.signIn.signOutExplain")})]})})}function pz(e){let{flow:t,pasting:n,pasteError:s,onPaste:a}=e,{t:l}=(0,eX.s)(),[o,d]=(0,i.useState)(""),c=(0,i.useRef)(null),u=(0,i.useRef)(n);(0,i.useEffect)(()=>{let e=u.current;u.current=n,e&&!n&&eE(document,c.current)},[n]);let p=function(e){if(void 0!==e)try{let t=new URL(e);return"https:"===t.protocol||"http:"===t.protocol?t.href:void 0}catch{return}}(t.authorizationUrl);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(a2,{message:l("mcp.signIn.authorize.message"),hint:p?(0,r.jsxs)(r.Fragment,{children:[l("mcp.signIn.authorize.link")," ",(0,r.jsx)("a",{href:p,target:"_blank",rel:"noopener noreferrer",children:os(p)})]}):(0,r.jsxs)(r.Fragment,{children:[l("mcp.signIn.authorize.notALink")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:os(t.authorizationUrl??"")})]}),value:o,placeholder:l("mcp.signIn.paste.placeholder"),inputLabel:l("mcp.signIn.paste.label"),submitLabel:l(n?"mcp.signIn.paste.checking":"mcp.signIn.paste.submit"),disabled:n,plainEnterSubmits:!1,inputRef:c,onValueChange:d,onSubmit:()=>a(o)}),s&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[l("mcp.signIn.paste.refused")," ",pL(s,l,"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:os(s.error)})]})]}),t.redirectUrl&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:l("mcp.signIn.authorize.redirect",{url:os(t.redirectUrl)})}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:l("mcp.signIn.authorize.wait")})]})}function pO(e){let{flow:t,shared:n}=e,{t:i}=(0,eX.s)(),s=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];switch(e.phase){case"done":{if(t)return e.alreadySignedIn?"mcp.signIn.shared.already":"mcp.signIn.shared.done";if(e.alreadySignedIn)return"mcp.signIn.done.already";let n=e.result;if(n&&"needs-auth"===n.state)return"mcp.signIn.done.needsAuthAfter";if(n&&"failed"===n.state)return"mcp.signIn.done.failedAfter";if(!n)return"mcp.signIn.done.notConnected";return e.refreshed?"mcp.signIn.done.refreshed":"mcp.signIn.done.signedIn"}case"failed":if(t&&"connect-failed"===e.failure)return"mcp.signIn.shared.connect-failed";return pE[e.failure??"internal"];case"cancelled":return"mcp.signIn.cancelled";case"expired":return"mcp.signIn.expired";default:return}}(t,n);if(!s)return null;let a=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return"done"===e.phase?!t&&e.result&&"connected"!==e.result.state?"warning":"on":"failed"===e.phase?"error":"expired"===e.phase?"warning":"off"}(t,n);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{role:"status",className:"error"===a?"mcp-config-line is-error":"warning"===a?"mcp-config-line is-warning":"mcp-config-line",children:i(s,{name:os(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:os(t.error)})]})]})}function pW(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function pF(e){return os(ep(e))}function pD(e,t){let{key:n,params:r}=e;return r?t(n,void 0===r.path?r:{...r,path:pF(r.path)}):t(n)}function pB(e,t){return e.timedOut?t("mcp.loadTimedOut"):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function pH(e,t){return e.timedOut?t("mcp.actionTimedOut"):pB(e,t)}function p_(){if("u"<typeof document)return null;let e=document.activeElement;return e instanceof HTMLButtonElement||e instanceof HTMLSelectElement?e:null}function pU(e){let{cwd:t,onClose:n,embedded:s=!1,trust:a,onTrustProject:l,onProjectTrustChanged:o}=e,[d,c]=(0,i.useState)({state:"loading"}),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(()=>sU("mcp",t)),[g,f]=(0,i.useState)({saving:!1,error:null}),[x,b]=(0,i.useState)(null),[v,y]=(0,i.useState)(null),[k,j]=(0,i.useState)(null),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),[I,E]=(0,i.useState)({}),$=(0,i.useRef)(0),T=(0,i.useRef)(null),M=(0,i.useRef)(null),R=(0,i.useRef)(null),A=(0,i.useRef)(new Map),[L,P]=(0,i.useState)({}),z=(0,i.useRef)(L);z.current=L;let[O,W]=(0,i.useState)(0),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)(uX),_=(0,i.useRef)(B);_.current=B;let[U,K]=(0,i.useState)(null),[q,Z]=(0,i.useState)(null),V=(0,i.useRef)(!0),J=(0,i.useRef)(d);J.current=d;let G=(0,i.useCallback)(async()=>{let e=++$.current;T.current?.abort();let n=new AbortController;T.current=n,p(!0);let r=await oQ(t,void 0,n.signal);if(e===$.current){if(p(!1),!r.ok)return void c({state:"failed",error:r.error});c({state:"loaded",data:r.data,...r.projectError?{projectError:r.projectError}:{}}),m(e=>oW(oz(r.data,!!t),e))}},[t]),Y=lR(a);(0,i.useEffect)(()=>(G(),()=>{$.current+=1,T.current?.abort()}),[G,Y]);let X=(0,i.useCallback)(async e=>{let t=new AbortController;M.current=t,f({saving:!0,error:null,target:"preference"});let n=await o2(e,void 0,t.signal);M.current===t&&(M.current=null,f({saving:!1,error:n.ok?null:n.error,target:"preference"}),n.ok&&c(e=>{var t,r;let i;return"loaded"===e.state?{...e,data:(t=e.data,r=n.preference,i={...t.codemode,preference:r},delete i.preferenceError,{...t,codemode:i})}:e}),G())},[G]),Q=(0,i.useCallback)(async e=>{let t=new AbortController;M.current=t,f({saving:!0,error:null,target:"mode"});let n=await o4(e,void 0,t.signal);M.current===t&&(M.current=null,f({saving:!1,error:n.ok?null:n.error,target:"mode"}),n.ok&&c(e=>"loaded"===e.state?{...e,data:function(e,t){let n=e.codemode.mode;if(!n)return e;let r={settingsPath:n.settingsPath,...n.projectOverride?{projectOverride:n.projectOverride}:{},...t};return{...e,codemode:{...e.codemode,mode:r}}}(e.data,n.mode)}:e),G())},[G]),ee=(0,i.useCallback)(async e=>{let t=new AbortController;M.current=t,f({saving:!0,error:null,target:"inlineBudget"});let n=await o8(e,void 0,t.signal);M.current===t&&(M.current=null,f({saving:!1,error:n.ok?null:n.error,target:"inlineBudget"}),n.ok&&c(e=>"loaded"===e.state?{...e,data:function(e,t){let n=e.codemode.inlineBudget;if(!n)return e;let r={settingsPath:n.settingsPath,default:n.default,max:n.max,...n.projectOverride?{projectOverride:n.projectOverride}:{},...t};return{...e,codemode:{...e.codemode,inlineBudget:r}}}(e.data,n.inlineBudget)}:e),G())},[G]);(0,i.useEffect)(()=>{let e=A.current;return V.current=!0,()=>{V.current=!1,M.current?.abort(),M.current=null,R.current?.abort(),R.current=null,e.clear()}},[]);let et=(0,i.useCallback)(async e=>{let n=ox(e);if(A.current.has(n))return;let r={};A.current.set(n,r),E(e=>({...e,[n]:{...e[n],running:!0,startedAt:Date.now(),error:void 0,queueTimedOut:void 0,configKey:void 0}}));let i=J.current,s="loaded"===i.state&&i.data.project?t:null,a=await du({scope:e.scope,name:e.name},s);if(A.current.get(n)!==r)return;A.current.delete(n),E(t=>({...t,[n]:function(e,t,n){let r=e?.signedOutAt,i={...e?.startedAt!==void 0?{startedAt:e.startedAt}:{},...void 0!==r?{signedOutAt:r}:{}};if(void 0!==r&&(e?.startedAt??0)<=r)return{running:!1,...i};let s=e?.response?{response:e.response}:{};return t.ok?t.data.result.queueTimedOut?{running:!1,...i,...s,queueTimedOut:!0,configKey:t.data.configKey}:{running:!1,...i,response:t.data}:{running:!1,...i,...s,error:t.error,...void 0!==n?{configKey:n}:{}}}(t[n],a,e.configKey)}));let l=J.current,o="loaded"===l.state?l.data.servers.find(e=>ox(e)===n):void 0;(a.ok?o?.configKey===a.data.configKey:void 0===a.error.reason||a.error.timedOut)||G()},[t,G]),en=(0,i.useCallback)((e,n)=>{$.current+=1,T.current?.abort(),p(!1),c(t=>({state:"loaded",data:e,..."loaded"===t.state&&t.projectError?{projectError:t.projectError}:{}})),m(r=>oW(oz(e,!!t),n??r))},[t]),er=(0,i.useCallback)(async e=>{let n=ox(e),r=z.current[n];if(r?.starting||pS(r))return;P(e=>({...e,[n]:{starting:!0}}));let i=J.current,s="loaded"===i.state&&i.data.project?t:null,a=await function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(e,t)=>fetch(e,t),r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:15e3;return pR("/api/mcp/sign-in",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:e.scope,name:e.name,...t?{cwd:t}:{}})},n,r,i,{abortAtDeadline:!1})}({scope:e.scope,name:e.name},s);V.current&&(P(e=>({...e,[n]:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();return e.ok?p$({},e.data,t):{error:e.error}}(a)})),a.ok||void 0===a.error.reason||a.error.timedOut||G())},[t,G]),ei=(0,i.useCallback)(async(e,t,n)=>{let r=ox(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 pR(pA(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirectUrl:t})},n,r,i)}(t,n);V.current&&P(e=>{let n=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Date.now();if(!e?.flow||e.flow.flowId!==t)return e;let i={...e,pasting:!1,version:(e.version??0)+1};return n.ok?{...p$(i,n.data,r),pasteError:void 0}:pT(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=ox(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 pR(pA(e),{method:"DELETE"},t,n,r)}(t);V.current&&P(e=>{let i=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Date.now();if(!e?.flow||e.flow.flowId!==t)return e;let i={...e,cancelling:!1,cancelError:void 0,version:(e.version??0)+1};return n.ok?p$(i,n.data,r):pT(n.error)?{...i,gone:!0}:{...i,cancelError:n.error}}(e[n],t,r);return void 0===i||i===e[n]?e:{...e,[n]:i}})},[]),ea=Object.entries(L).flatMap(e=>{let[t,n]=e;return pS(n)&&n.flow?[`${t}\x01${n.flow.flowId}`]:[]}).join("\x02");(0,i.useEffect)(()=>{if(!ea)return;let e=new AbortController,t=setTimeout(async()=>{for(let t of ea.split("\x02")){let[n,r]=t.split("\x01"),i=z.current[n]?.version??0,s=await function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return pR(pA(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?p$(e,n.data,r):pT(n.error)||void 0!==e.deadlineAt&&r>e.deadlineAt+5e3?{...e,gone:!0}:e:e}(e[n],r,s,Date.now(),i);return void 0===t||t===e[n]?e:{...e,[n]:t}})}W(e=>e+1)},1e3);return()=>{clearTimeout(t),e.abort()}},[ea,O]);let el=(0,i.useRef)(L);(0,i.useEffect)(()=>{let e=el.current;el.current=L,Object.keys(L).some(t=>{var n,r;return n=e[t],r=L[t],pS(n)&&!pS(r)})&&G()},[L,G]);let eo=(0,i.useCallback)(async(e,n,r)=>{R.current?.abort();let i=new AbortController;R.current=i,b(n);let s=J.current,a="loaded"===s.state&&s.data.project?t:null,l=await dt(e,a,void 0,i.signal);if(R.current===i)return R.current=null,b(null),l.ok?en(l.data,r?.(l.data)):G(),l},[en,t,G]),ed=(0,i.useCallback)(async(e,t)=>{let n=ox(e),r=p_();y(null),j(null);let i=await eo({action:t?"enable":"disable",scope:e.scope,name:e.name},`switch:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[eo]),ec=(0,i.useCallback)(async(e,t)=>{let n=ox(e),r=p_();y(null),j(null);let i=await eo({action:"set-in-project",name:e.name,enabled:t},`in-project:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[eo]),eu=(0,i.useCallback)(async(e,t)=>{let n=ox(e),r=p_();y(null),j(null);let i=await eo({action:"set-exposure",scope:e.scope,name:e.name,exposure:t},`exposure:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[eo]),ep=(0,i.useCallback)(async e=>{let t=ox(e),n=p_();y(null),j(null);let r=await eo({action:"remove",scope:e.scope,name:e.name},`remove:${t}`);if(!r)return;if(!r.ok){y({key:t,failure:r.error}),N({control:n});return}let i=r.data.undo;i&&S({...i,undoing:!1})},[eo]),eh=(0,i.useCallback)(async()=>{if(!w)return;let e=p_();y(null),j(null),S({...w,undoing:!0,error:void 0});let t=await eo({action:"undo",token:w.token},"undo",e=>e.restored?ox(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}))},[eo,w]),em=(0,i.useCallback)(async e=>{let t=ox(e),n=p_();y(null),j(null),P(e=>({...e,[t]:{...e[t],signOutError:void 0,signedOut:void 0}}));let r=await eo({action:"sign-out",scope:e.scope,name:e.name},`sign-out:${t}`);if(r){if(P(e=>({...e,[t]:r.ok?{signedOut:{removed:r.data.signedOut?.removed===!0}}:{...e[t],signOutError:r.error}})),r.ok){let e=Date.now();E(n=>{let r=function(e,t){if(e)return{running:e.running,...void 0!==e.startedAt?{startedAt:e.startedAt}:{},signedOutAt:t}}(n[t],e);return r?{...n,[t]:r}:n})}N({control:n})}},[eo]),eg=(0,i.useCallback)(async e=>{let n=p_(),r=_.current;y(null),j(null),K(null);let i=await eo(e,"add",e=>e.added?ox(e.added):void 0);if(!i)return;let s=_.current!==r;if(!i.ok){s||K(i.error),i.error.trust&&t&&o?.(t,i.error.trust),N({control:n});return}let{added:a,trust:l,trustedFolder:d}=i.data;if(D(!1),s||H(uX),N({control:null,toSelectedRow:!0}),!a)return;Z({...a,key:ox(a),...d&&t?{trustedFolder:t}:{}}),l&&t&&o?.(t,l);let c=i.data.servers.find(e=>ox(e)===ox(a));c&&!dr(c,i.data)&&et(c)},[t,o,eo,et]),ef=w?.token,ex=w?.expiresInMs;(0,i.useEffect)(()=>{if(void 0===ef||void 0===ex)return;let e=setTimeout(()=>S(e=>e?.token===ef?null:e),ex);return()=>clearTimeout(e)},[ef,ex]);let eb=(0,i.useCallback)(async(e,t,n)=>{let{targets:r,keptOff:i}={targets:lM(t,n,e=>e.enabled).filter(n?o7:o9),keptOff:n?t.filter(e=>!e.enabled&&o9(e)&&!o7(e)).length:0},s=p_();if(y(null),j(i>0?{scope:e,keptOff:i,failures:[],total:0}:null),0===r.length)return;let a=await eo({action:"set-enabled",enabled:n,servers:r.map(e=>{let{scope:t,name:n}=e;return{scope:t,name:n}})},`group:${e}`);if(!a)return;if(N({control:s}),!a.ok)return void j({scope:e,keptOff:i,failures:[],total:r.length,error:a.error});let l=a.data.results??[],o=l.filter(e=>void 0!==e.reason).map(e=>({name:e.name,failure:{error:e.error??"",reason:e.reason}}));j(o.length>0||i>0?{scope:e,keptOff:i,failures:o,total:l.length}:null)},[eo]);return(0,i.useEffect)(()=>{h&&sK("mcp",h,t)},[t,h]),(0,r.jsx)(pK,{cwd:t,load:d,selected:h,refreshing:u,embedded:s,codemodeSave:g,busy:x,actionError:v,groupStatus:k,undo:w,focusBack:C,tests:I,signIns:L,adding:F,addDraft:B,addFailure:U,added:q,onAddOpen:()=>{D(!0),Z(null),y(null)},onAddDraftChange:e=>{_.current=e,H(e),K(null)},onAddSubmit:e=>void eg(e),onTest:e=>void et(e),onSignIn:e=>void er(e),onSignOut:e=>void em(e),onSignInPaste:(e,t,n)=>void ei(e,t,n),onSignInCancel:(e,t)=>void es(e,t),onSelect:e=>{m(e),y(null),D(!1),Z(t=>t?.key===e?t:null)},onRefresh:()=>void G(),onCodemodeChange:e=>void X(e),onCodemodeModeChange:e=>void Q(e),onCodemodeInlineBudgetSave:e=>void ee(e),onServerSwitch:(e,t)=>void ed(e,t),onServerSwitchInProject:(e,t)=>void ec(e,t),onExposureChange:(e,t)=>void eu(e,t),onGroupSwitch:(e,t,n)=>void eb(e,t,n),onRemove:e=>void ep(e),onUndo:()=>void eh(),onTrustProject:l,onClose:n})}function pK(e){var t,n,s,a;let l,o,d,{cwd:c,load:u,selected:p,refreshing:h,embedded:m,codemodeSave:g={saving:!1,error:null},busy:f=null,actionError:x=null,groupStatus:b=null,undo:v=null,focusBack:y=null,tests:k={},signIns:j={},adding:w=!1,addDraft:S=uX,addFailure:C=null,added:N=null,onAddOpen:I=()=>{},onAddDraftChange:E=()=>{},onAddSubmit:$=()=>{},onSelect:T,onRefresh:M,onCodemodeChange:R,onCodemodeModeChange:A=()=>{},onCodemodeInlineBudgetSave:L=()=>{},onServerSwitch:P=()=>{},onServerSwitchInProject:z=()=>{},onExposureChange:O=()=>{},onGroupSwitch:W=()=>{},onRemove:F=()=>{},onUndo:D=()=>{},onTest:B=()=>{},onSignIn:H=()=>{},onSignOut:_=()=>{},onSignInPaste:U=()=>{},onSignInCancel:K=()=>{},onTrustProject:q,onClose:Z}=e,{t:V}=(0,eX.s)(),J=(0,i.useId)(),G=(0,i.useId)(),Y="loaded"===u.state?(t=u.data,l=!1,o=t.servers.map(e=>{var t;let n=k[ox(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;l=!0;let r={...n.result,origin:"test"};return{...e,status:r}}),l?{...t,servers:o}:t):void 0,X=Y?oz(Y,!!c):[],Q=Y?{mcpAvailable:Y.mcp.available,projectServersLoad:ob(Y.project)}:void 0,ee=X.flatMap(e=>e.servers),et=ee.find(e=>ox(e)===p),en=N?ee.find(e=>ox(e)===N.key):void 0,er=Y?function(e){if(!e.available)return"builtin-disabled"===e.reason?e.settingsPath?{key:"mcp.unavailable.builtin-disabled",params:{path:e.settingsPath}}:{key:"mcp.unavailable.builtin-disabled-unknown"}:{key:"operator-disabled"===e.reason?"mcp.unavailable.operator-disabled":"mcp.unavailable.internals-unavailable"}}(Y.mcp):void 0,ei=er?void 0:Y?.hostInactive,es=Y?.files.find(e=>"project"===e.scope),ea=Y?function(e,t){if(!e||!t||!t.exists&&0===t.problems.length)return;let{trust:n}=e;return n?n.requiresTrust||!1===n.decision?!0===n.decision?n.inherited&&n.decisionPath?{kind:"inherited",key:"mcp.trust.trustedThrough",params:{path:n.decisionPath}}:void 0:!1===n.decision&&n.inherited&&n.decisionPath?{kind:"untrusted",key:"mcp.trust.untrustedThrough",params:{path:n.decisionPath}}:{kind:"untrusted",key:"mcp.trust.untrusted"}:void 0:{kind:"untrusted",key:"mcp.trust.unreadable"}}(Y.project,es):void 0,el=q&&oF(Y?.project)?q:void 0,eo=ea?.kind==="untrusted"&&void 0!==el,ed=(0,i.useRef)(null),ec=(0,i.useRef)(null),eu=(0,i.useRef)(eo);(0,i.useEffect)(()=>{let e=eu.current;eu.current=eo,e&&!eo&&eE(document,ed.current??ec.current)},[eo]);let eh=(0,i.useRef)(null),em=v?.token,eg=(0,i.useRef)(em);(0,i.useEffect)(()=>{let e=eg.current;eg.current=em,void 0!==em&&em!==e?eE(document,eh.current):void 0!==e&&void 0===em&&eE(document,ed.current??ec.current)},[em]);let ef=Y?[...Y.files].sort((e,t)=>e.scope===t.scope?0:"global"===e.scope?-1:1).flatMap(e=>e.problems.map(t=>({file:e,problem:t}))):[],ex=oO(ee),eb=Y?.files.find(e=>"global"===e.scope),ev=Y?function(e){let t=e.files.find(e=>"project"===e.scope);if(t?.autoEnableCodemode!==void 0&&ob(e.project))return t.autoEnableCodemode?{value:!0,path:t.path}:{value:!1,path:t.path};let n=e.files.find(e=>"global"===e.scope);return n?.autoEnableCodemode!==void 0?n.autoEnableCodemode?{value:!0,path:n.path}:{value:!1,path:n.path}:{value:!0}}(Y):void 0,ey=Y?(n=ee.length,s=Y.files,n>0?"mcp.selectItem":s.some(e=>e.problems.some(oP))?"mcp.emptyFileProblem":"mcp.empty"):void 0,ek=null!==f||h||g.saving,ej=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(y&&!ek&&ej.current!==y)if(ej.current=y,y.toSelectedRow)eE(document,ed.current??ec.current);else{var e,t,n;e=document,t=y.control,n=ed.current??ec.current,t&&eE(e,t.isConnected&&!t.disabled?t:n)}},[y,ek]);let ew=e=>Y?o3(e,Y):void 0,eS=!!Y&&o6(Y.mcp),eC=X.find(e=>"project"===e.scope)?.servers??[],eN=ew("project"),eI=e=>"mcp-off"===e?er?J:void 0:e&&ea?.kind==="untrusted"?G:void 0,e$=ea?.kind==="untrusted"?[pD(ea,V),eN&&"mcp-off"!==eN&&eC.length>0?V(o5[eN]):null].filter(Boolean).join(" "):"";return(0,r.jsxs)(ao,{embedded:m,title:V("settings.mcp"),subtitle:c?ep(c):void 0,closeLabel:V("i18n.close"),onClose:Z,children:[(0,r.jsxs)("div",{className:"mcp-config-notices",children:[er&&(0,r.jsxs)(aP,{id:J,children:[pD(er,V),eS&&(0,r.jsxs)(r.Fragment,{children:[" ",V(o5["mcp-off"])]}),Y&&!Y.mcp.available&&Y.mcp.detail&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:os(Y.mcp.detail)})]})]}),ei&&(0,r.jsx)(aP,{children:V("mcp.hostInactive",{path:pF(ei.cwd),owner:pF(ei.owner)})}),"loaded"===u.state&&u.projectError&&(0,r.jsx)(aP,{children:V("mcp.projectNotListed",{reason:pB(u.projectError,V)})}),ea?.kind==="untrusted"&&(0,r.jsx)(az,{id:G,message:e$,trustLabel:V("mcp.trust.trustButton"),onTrust:el}),ea?.kind==="inherited"&&(0,r.jsx)(aP,{children:pD(ea,V)}),v&&(0,r.jsxs)(aP,{action:v.error?.reason==="undo-unavailable"?void 0:(0,r.jsx)(aB,{ref:eh,size:"small",onClick:D,disabled:v.undoing||ek,children:v.undoing?V("mcp.undoing"):V("mcp.undo")}),children:[V("mcp.removed",{name:os(v.name),path:pF(v.path)}),v.error&&(0,r.jsxs)(r.Fragment,{children:[" ",V("mcp.undoFailed")," ",pH(v.error,V)]})]}),N&&Y&&en&&(0,r.jsx)(pq,{added:N,cwd:c,server:en,testing:k[N.key]?.running===!0,signIn:j[N.key],signingOut:f===`sign-out:${N.key}`,signInBlock:en?dr(en,Y):void 0,onSignIn:H})]}),(0,r.jsxs)(ah,{children:[(0,r.jsxs)(am,{children:[(0,r.jsx)(ag,{children:"loading"===u.state?(0,r.jsx)("div",{className:"config-sidebar-message",children:V("i18n.loading")}):"failed"===u.state?(0,r.jsxs)("div",{role:"alert",className:"config-sidebar-message is-error",children:[V("mcp.loadFailed")," ",pB(u.error,V)]}):Y&&Q?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-sidebar-group",children:(0,r.jsx)(pZ,{codemode:Y.codemode,active:!w&&p===of,rowRef:ed,onSelect:T})}),X.map(e=>{let t=ew(e.scope);return(0,r.jsx)(pV,{group:e,context:Q,selected:w?null:p,selectedRowRef:ed,block:t,blockNoticeId:eI(t),busy:f,controlsBusy:ek,status:b?.scope===e.scope?b:null,onSelect:T,onGroupSwitch:W},e.scope)})]}):null}),Y&&(0,r.jsx)(a_,{ref:ec,active:w,onClick:I,children:V("mcp.add.action")})]}),(0,r.jsx)(aW,{children:(0,r.jsx)(ak,{className:"is-fill",children:Y&&Q&&ev&&ey?w?(0,r.jsx)(pv,{data:Y,cwd:c,draft:S,busy:"add"===f,controlsBusy:ek,failure:C,onDraftChange:E,onSubmit:$,onTrustProject:el}):p===of?(0,r.jsx)(p3,{codemode:Y.codemode,autoEnable:ev,save:g,serverBusy:null!==f,onChange:R,onModeChange:A,onInlineBudgetSave:L}):et?(0,r.jsx)(pY,{server:et,context:Q,codemode:Y.codemode,toolSearchDisabled:Y.toolSearchDisabled,autoEnable:ev,block:ew(et.scope),blockNoticeId:eI(ew(et.scope)),uncheckedSaid:er?.key==="mcp.unavailable.internals-unavailable",inProject:function(e,t){if("global"!==e.scope||void 0!==e.invalidError||e.notAnObject||!ob(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:ox(r),keys:r.override.keys,applies:!0===e.overriddenByProject}:void 0:{kind:"switch"}}(et,Y),inProjectBlock:ew("project"),savedWhileOff:!Y.mcp.available&&!eS,busy:f,controlsBusy:ek,actionError:x?.key===ox(et)?x.failure:null,test:(a=k[ox(et)],a&&void 0!==a.configKey&&a.configKey!==et.configKey?{running:a.running,...a.response?{response:a.response}:{}}:a),testBlock:dr(et,Y),signIn:j[ox(et)],signInBlock:dr(et,Y),signOutBlock:(d=o3(et.scope,Y))||(void 0===et.invalidError&&et.validated?void 0:"invalid"),onSwitch:P,onSwitchInProject:z,onShowServer:e=>{T(e),requestAnimationFrame(()=>eE(document,ed.current??ec.current))},onExposureChange:O,onRemove:F,onTest:B,onSignIn:H,onSignOut:_,onSignInPaste:U,onSignInCancel:K},ox(et)):(0,r.jsx)(aO,{children:"mcp.empty"===ey?V(ey,{globalPath:pF(eb?.path??"~/.pi/agent/mcp.json")}):V(ey)}):null})})]}),(0,r.jsxs)(aF,{status:ef.length>0?(0,r.jsx)(aD,{tone:ef.some(e=>{let{problem:t}=e;return oP(t)})?"error":"warning",summary:1===ef.length?V("mcp.footer.fileProblem"):V("mcp.footer.fileProblems",{count:ef.length}),details:ef.map(e=>{let{file:t,problem:n}=e,i=og(n,t.realPath);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:pF(t.path)})," ",V(`mcp.fileProblem.${n.reason}`),i&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:i})]})]})})}):(0,r.jsx)(aD,{summary:ex.total>0?V("mcp.serverCount",{enabled:ex.enabled,total:ex.total}):""}),children:[!m&&(0,r.jsx)(aB,{onClick:Z,children:V("i18n.close")}),(0,r.jsx)(aB,{variant:"secondary",onClick:M,disabled:ek,children:V("i18n.refresh")})]})]})}function pq(e){let{added:t,cwd:n,server:i,testing:s,signIn:a,signingOut:l,signInBlock:o,onSignIn:d}=e,{t:c}=(0,eX.s)(),u=os(t.name),p="project"===t.scope&&n?os(eh(t.path,n)):pF(t.path),h=i.status,m=!s&&h?.origin==="test"&&"needs-auth"===h.state&&i.usesOAuth,g=a?.starting===!0||pS(a);return(0,r.jsxs)(aP,{action:!m||g||l||o?void 0:(0,r.jsx)(aB,{size:"small",variant:"primary",onClick:()=>d(i),children:c("mcp.signIn.button")}),children:[void 0===t.trustedFolder?c("mcp.add.added",{name:u,path:p}):t.trustedFolder===n?c("mcp.add.addedTrustedHere",{name:u,path:p}):c("mcp.add.addedTrusted",{name:u,path:p,folder:pF(t.trustedFolder)}),s&&(0,r.jsxs)(r.Fragment,{children:[" ",c("mcp.add.testing")]}),m&&(0,r.jsxs)(r.Fragment,{children:[" ",c("mcp.add.needsSignIn")]})]})}function pZ(e){let{codemode:t,active:n,rowRef:i,onSelect:s}=e,{t:a}=(0,eX.s)(),l=t.builtinDisabled||"unavailable"===t.sandbox.state?"unavailable":t.preference??"unknown",o=a(oU[l]);return(0,r.jsxs)(av,{ref:n?i:void 0,active:n,"aria-label":a("mcp.codemode.rowLabel",{state:o}),onClick:()=>s(of),children:[(0,r.jsx)(aU,{...oI(oK(l))}),(0,r.jsx)(ay,{className:"is-grow",children:a("mcp.codemode.title")}),(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${oK(l)}`,children:o})]})}function pV(e){var t;let n,i,{group:s,context:a,selected:l,selectedRowRef:o,block:d,blockNoticeId:c,busy:u,controlsBusy:p,status:h,onSelect:m,onGroupSwitch:g}=e,{t:f}=(0,eX.s)(),{enabled:x,total:b}=oO(s.servers),v=(t=s.servers).some(e=>e.enabled&&o9(e))&&t.every(e=>e.enabled||!o7(e)),y=function(e){if(!(e.servers.length>0))return e.file?e.file.problems.some(oP)?"mcp.group.fileProblem":"mcp.group.empty":"mcp.group.notListed"}(s),k=h?(n=h.keptOff>0?f("mcp.groupKeptOff",{count:h.keptOff}):void 0,i=h.error?`${f("mcp.actionFailed")} ${pH(h.error,f)}`:h.failures.length>0?[f("mcp.bulkFailed",{count:h.failures.length,total:h.total}),...h.failures.map(e=>{let{name:t,failure:n}=e;return`${os(t)}: ${pH(n,f)}`})].join("\n"):void 0,{...n?{note:n}:{},...i?{error:i}:{}}):void 0;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(af,{aside:b>0?(0,r.jsx)(ax,{enabled:x,total:b,checked:v,disabled:p||void 0!==d,loading:u===`group:${s.scope}`,describedBy:d?c:void 0,label:f(v?"mcp.groupSwitchOn":"mcp.groupSwitchOff",{group:pW(s.scope,f)}),onChange:e=>g(s.scope,s.servers,e)}):void 0,children:pW(s.scope,f)}),k&&(0,r.jsx)(ab,{note:k.note,error:k.error}),y&&(0,r.jsx)("div",{className:"mcp-sidebar-group-empty",children:f(y)}),s.servers.map(e=>{let t=ox(e),n=oy(e,a),i=oN(n),s=oC[n],d=os(e.name);return(0,r.jsxs)(av,{ref:l===t?o:void 0,active:l===t,"aria-label":f("mcp.rowLabel",{name:d,state:f(ow(n,e.status))}),onClick:()=>m(t),children:[(0,r.jsx)(aU,{...oI(i)}),(0,r.jsx)(ay,{className:`is-grow${"on"===i?"":" is-muted"}`,children:d}),s&&(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${i}`,children:f(s)})]},t)})]})}function pJ(e){let{fields:t}=e,{t:n}=(0,eX.s)();return(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>{let t=ou(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function pG(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:os(e)},e))})}function pY(e){let{server:t,context:n,codemode:s,toolSearchDisabled:a,autoEnable:l,block:o,blockNoticeId:d,uncheckedSaid:c,inProject:u,inProjectBlock:p,savedWhileOff:h,busy:m,controlsBusy:g,actionError:f,test:x,testBlock:b,signIn:v,signInBlock:y,signOutBlock:k,onSwitch:j,onSwitchInProject:w,onShowServer:S,onExposureChange:C,onRemove:N,onTest:I,onSignIn:E,onSignOut:$,onSignInPaste:T,onSignInCancel:M}=e,{t:R}=(0,eX.s)(),A=(0,i.useId)(),L=(0,i.useId)(),P=oy(t,n),z=od(t),O=t.status,W=O?.origin==="test"&&"connected"===O.state&&O.toolCount>0?O:void 0,F=void 0===t.invalidError,D="http"===t.transport||void 0===t.transport&&void 0!==t.url,B=!D&&("stdio"===t.transport||void 0!==t.command),H=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"===oD(r)?void 0:{key:"mcp.exposure.autoEnableOff",params:{path:n.path}}}if("deferred"!==e||!t.toolSearchDisabled)return;let i=t.toolSearchDisabled.settingsPath;return i?{key:"mcp.exposure.toolSearchDisabled",params:{path:i}}:{key:"mcp.exposure.toolSearchDisabledUnknown"}}(t.exposure,{codemode:s,toolSearchDisabled:a},l):void 0,_=(0,i.useId)(),U=(0,i.useId)(),K=ox(t),q=os(t.name),Z=!t.enabled&&void 0!==t.webPasswordField,V=!0===t.notAnObject,J=o?d?void 0:R(`mcp.reason.${o}`):V?R("mcp.reason.entry-not-object"):Z?R("mcp.reason.web-password"):h?R("mcp.write.savedWhileOff"):void 0,G=J?A:o?d:void 0,Y=e=>void 0!==e&&e===o&&void 0!==d;return(0,r.jsxs)(ak,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(aj,{children:[(0,r.jsxs)(aw,{children:[(0,r.jsx)(aT,{scope:t.scope,children:pW(t.scope,R)}),(0,r.jsx)(aC,{children:q})]}),(0,r.jsxs)(aS,{children:[(0,r.jsx)(p8,{server:t,test:x,testBlock:b,describedBy:Y(b)?d:L,onTest:I}),(0,r.jsx)(aB,{variant:"danger",size:"small",disabled:g||void 0!==o,"aria-describedby":o?G:void 0,onClick:()=>N(t),children:m===`remove:${K}`?R("i18n.removing"):R("i18n.remove")}),(0,r.jsx)(aH,{checked:t.enabled,disabled:g||void 0!==o||V||Z,loading:m===`switch:${K}`,describedBy:G,label:R(t.enabled?"mcp.server.switchOff":"mcp.server.switchOn",{name:q}),onChange:e=>j(t,e)})]})]}),J&&(0,r.jsx)("div",{id:A,className:"config-detail-heading-note",children:J})]}),f&&(0,r.jsxs)("p",{role:"alert",className:"mcp-config-line is-error",children:[R("mcp.actionFailed")," ",pH(f,R)]}),(0,r.jsxs)(aE,{children:[(0,r.jsx)(p6,{server:t,state:P,test:x,testBlock:b,testBlockSaid:Y(b),testBlockId:L}),void 0!==t.description&&(0,r.jsx)(a$,{label:R("mcp.detail.description"),tone:"plain",children:os(t.description)}),void 0!==z?(0,r.jsx)(a$,{label:D?R("mcp.detail.url"):R("mcp.detail.command"),tone:"plain",mono:!0,className:"mcp-config-code",children:z}):t.transport&&(0,r.jsx)(a$,{label:R("mcp.detail.transport"),children:R(`mcp.transport.${t.transport}`)}),B&&void 0!==t.cwd&&(0,r.jsx)(a$,{label:R("mcp.detail.cwd"),mono:!0,className:"mcp-config-code",children:os(t.cwd)}),B&&t.envNames.length>0&&(0,r.jsx)(a$,{label:R("mcp.detail.env"),children:(0,r.jsx)(pG,{names:t.envNames})}),D&&t.headerNames.length>0&&(0,r.jsx)(a$,{label:R("mcp.detail.headers"),children:(0,r.jsx)(pG,{names:t.headerNames})}),F&&t.commandFields.length>0&&(0,r.jsx)(a$,{label:R("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:R("mcp.server.commandFields")}),(0,r.jsx)(pJ,{fields:t.commandFields})]})}),F&&t.variableReferences.length>0&&(0,r.jsx)(a$,{label:R("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:R(op(t))}),(0,r.jsx)("span",{className:"mcp-config-chips",children:om(t.variableReferences).map(e=>{let{variable:t,field:n}=e,i=ou(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:R("mcp.server.variableIn",{variable:t,field:R(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})}),D&&F&&(0,r.jsx)(pP,{server:t,run:v,block:y,signOutBlock:k,blockSaidBy:Y(y)?d:void 0,signOutBlockSaidBy:Y(k)?d:void 0,controlsBusy:g,signingOut:m===`sign-out:${K}`,onSignIn:E,onSignOut:$,onPaste:T,onCancel:M}),(t.exposure||W)&&(0,r.jsx)(a$,{label:R("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":R("mcp.exposure.label",{name:q}),"aria-describedby":[_,o?G:null].filter(Boolean).join(" "),value:t.exposure,disabled:g||void 0!==o,onChange:e=>{let n=e.target.value;n!==t.exposure&&C(t,n)},children:oA.map(e=>(0,r.jsx)("option",{value:e,children:"codemode"===e?R("mcp.exposure.optionDefault",{label:R(oL[e])}):R(oL[e])},e))}),m===`exposure:${K}`&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:R("i18n.saving")})]}),(0,r.jsx)("span",{id:_,className:"mcp-config-line",children:R(oR[t.exposure])}),void 0!==t.toolExposureCount&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:R("mcp.exposure.toolOverrides",{count:t.toolExposureCount})}),H&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:pD(H,R)})]}),W&&(0,r.jsx)(p4,{status:W,serverExposure:t.exposure})]})}),u&&(0,r.jsx)(a$,{label:R("mcp.detail.inProject"),tone:"plain",children:(0,r.jsx)("span",{className:"mcp-config-lines",children:"override"===u.kind?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"mcp-config-line",children:u.applies?R("mcp.inProject.overridden",{keys:u.keys.join(", ")}):R("mcp.inProject.refused")}),(0,r.jsx)("span",{children:(0,r.jsx)(aB,{size:"small",onClick:()=>S(u.key),children:R("mcp.inProject.show")})})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:(0,r.jsx)(aB,{size:"small",disabled:g||void 0!==p||Z,"aria-describedby":[U,p||Z?G:null].filter(Boolean).join(" "),onClick:()=>w(t,!t.enabled),children:m===`in-project:${K}`?R("i18n.saving"):R(t.enabled?"mcp.inProject.turnOff":"mcp.inProject.turnOn")})}),(0,r.jsx)("span",{id:U,className:"mcp-config-line is-dim",children:R("mcp.inProject.saved")})]})})}),(0,r.jsx)(a$,{label:R("mcp.detail.file"),tone:"dim",mono:!0,className:"mcp-config-code",children:pF(t.sourcePath)})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[oc(t)&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:R("mcp.server.hiddenCharacters")}),!t.validated&&!c&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:R("mcp.server.unchecked")}),t.replacesGlobal&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:R("mcp.server.replacesGlobal")}),t.override&&(0,r.jsx)("p",{className:"mcp-config-line",children:pD(oh(t.override.keys),R)}),t.shadowedByProject&&"replaced"!==P&&(0,r.jsx)("p",{className:"mcp-config-line",children:R("mcp.server.shadowedByProject")}),t.overriddenByProject&&"overridden"!==P&&(0,r.jsx)("p",{className:"mcp-config-line",children:R("mcp.server.overriddenByProject")}),t.masked&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:R("mcp.server.masked")})]})]})}function pX(e){let{error:t,stderr:n}=e,{t:i}=(0,eX.s)();return(0,r.jsxs)(r.Fragment,{children:[t&&(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[i("mcp.test.error")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:os(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(os).join("\n")})]})]})}function pQ(e){let{status:t,showState:n,entryCwd:i}=e;return"session"===t.origin?(0,r.jsx)(p2,{status:t,showState:n}):(0,r.jsx)(p1,{status:t,showState:n,entryCwd:i})}function p0(e){let{view:t}=e,{t:n}=(0,eX.s)();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:`mcp-config-state is-${t.tone}`,children:n(t.key)})," "]})}function p1(e){let{status:t,showState:n,entryCwd:i}=e,{t:s,locale:a}=(0,eX.s)(),l=oE(t.testedAt,a),o=t.serverInfo;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,r.jsx)(p0,{view:t.timedOut?{key:ds.timedOut,tone:"error"}:{key:ds[t.state],tone:oN(t.state)}}),s((t.afterSignIn?dl:da)[t.timedOut?"timedOut":t.state],{count:t.toolCount,seconds:dd(t.durationMs),time:l})]}),(0,r.jsx)(pX,{error:t.error,stderr:t.stderr}),o&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.serverInfo",{name:os(o.title??o.name),version:os(o.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:pF(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:dd(t.queuedMs)})})]})}function p2(e){let{status:t,showState:n}=e,{t:i,locale:s}=(0,eX.s)(),a=oE(t.updatedAt,s),l=void 0===t.closedAt?void 0:oE(t.closedAt,s);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,r.jsx)(p0,{view:void 0!==t.closedAt?{key:"mcp.session.state.closed",tone:"off"}:{key:o$[t.state],tone:oM[t.state]}}),i(void 0!==t.closedAt?"mcp.session.summary.closed":oT[t.state],{path:pF(t.cwd),time:a,...void 0===l?{}:{closedTime:l}})]}),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:pF(t.conflict)})]}),(0,r.jsx)(pX,{error:t.error,stderr:t.stderr})]})}function p4(e){let{status:t,serverExposure:n}=e,{t:i}=(0,eX.s)(),s=t.toolCount-t.tools.length;return(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("ul",{className:"mcp-test-tools",children:t.tools.map((e,t)=>(0,r.jsxs)("li",{className:"mcp-test-tool",children:[(0,r.jsxs)("span",{className:"mcp-config-chips",children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:os(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(oL[e.exposure])})]}),e.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:os(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 p8(e){let{server:t,test:n,testBlock:s,describedBy:a,onTest:l}=e,{t:o}=(0,eX.s)(),d=(0,i.useRef)(null),c=n?.running===!0,u=(0,i.useRef)(c);return(0,i.useEffect)(()=>{let e=u.current;u.current=c,e&&!c&&eE(document,d.current)},[c]),(0,r.jsx)(aB,{ref:d,size:"small",disabled:c||void 0!==s,"aria-busy":c||void 0,"aria-describedby":s?a:void 0,onClick:()=>l(t),children:o(c?"mcp.test.testing":"mcp.test.button")})}function p6(e){let{server:t,state:n,test:i,testBlock:s,testBlockSaid:a,testBlockId:l}=e,{t:o}=(0,eX.s)(),d=t.status,c=oS[n],u="invalid"===s&&"invalid"===n?"state":"web-password"===s&&void 0!==t.webPasswordField?"password":void 0;return(0,r.jsx)(a$,{label:o("i18n.status"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:`mcp-config-state is-${oN(n)}`,children:o(ow(n,d))}),"invalid"===n&&(0,r.jsxs)("span",{id:"state"===u?l:void 0,className:"mcp-config-line is-warning",children:[o("mcp.server.invalid")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:os(t.invalidError??"")})]}),t.webPasswordField&&(0,r.jsxs)("span",{id:"password"===u?l:void 0,className:"mcp-config-line is-warning",children:[o("mcp.server.webPassword")," ",(0,r.jsx)(pJ,{fields:[t.webPasswordField]})]}),d?(0,r.jsx)(pQ,{status:d,showState:ov(d)!==n,entryCwd:t.cwd}):!s&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.test.never")}),c&&(0,r.jsx)("span",{className:"mcp-config-line",children:o(c)}),i?.queueTimedOut&&(0,r.jsx)("span",{role:"alert",className:"mcp-config-line is-error",children:o("mcp.test.queueTimedOut")}),i?.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[o("mcp.test.requestFailed")," ",function(e,t){if(e.timedOut)return t("mcp.test.requestTimedOut");let n=e.reason?di[e.reason]:void 0;return n?t(n):pB(e,t)}(i.error,o)]}),s&&!u&&!a&&(0,r.jsx)("span",{id:l,className:"mcp-config-line is-dim",children:o(dn[s])}),!s&&t.commandFields.length>0&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.test.serial")})]})})}function p3(e){let{codemode:t,autoEnable:n,save:i,serverBusy:s,onChange:a,onModeChange:l,onInlineBudgetSave:o}=e,{t:d}=(0,eX.s)(),c=t.sandbox,u=t.preference,p=i.saving||s,h=void 0===i.target||"preference"===i.target?i:{saving:!1,error:null},m=function(e,t){if("automatic"===oD(e)&&!t.value)return{key:"mcp.codemode.autoEnableOff",params:{path:t.path}}}(t,n),g="unavailable"===t.sandbox.state?{key:"mcp.codemode.alwaysUnavailable.sandbox"}:t.globalBuiltinSettingsPath?{key:"mcp.codemode.alwaysUnavailable.builtin",params:{path:t.globalBuiltinSettingsPath}}:void 0,f=function(e){if(!e.builtinDisabled)return;let t=e.builtinSettingsPath;return t?e.globalBuiltinSettingsPath?{key:"mcp.codemode.builtinDisabled",params:{path:t}}:{key:"mcp.codemode.builtinDisabledProject",params:{path:t}}:{key:"mcp.codemode.builtinDisabledUnknown"}}(t),x=function(e){let t=e.projectOverride;if(t)return{key:oB[t.preference],params:{path:t.settingsPath}}}(t);return(0,r.jsxs)(ak,{children:[(0,r.jsx)(aj,{children:(0,r.jsx)(aw,{children:(0,r.jsx)(aC,{children:d("mcp.codemode.title")})})}),(0,r.jsx)("p",{className:"mcp-config-line",children:d("mcp.codemode.intro")}),(0,r.jsxs)(aE,{children:[(0,r.jsx)(a$,{label:d("mcp.codemode.mode"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[u?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(aM,{value:u,label:d("mcp.codemode.title"),options:[{value:"automatic",label:d(oU.automatic),disabled:p},{value:"always",label:d(oU.always),disabled:p||void 0!==g}],disabledReason:g?pD(g,d):null,onChange:e=>{e!==u&&a(e)},children:h.saving&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:d("i18n.saving")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("always"===u?"mcp.codemode.alwaysDescription":"mcp.codemode.automaticDescription")})]}):(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[d("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:os(t.preferenceError??"")})]}),h.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[d("mcp.codemode.saveFailed")," ",(0,r.jsx)(p5,{error:h.error})]}),x&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:pD(x,d)}),m&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:pD(m,d)})]})}),t.mode?(0,r.jsx)(p9,{mode:t.mode,codemode:t,save:i,waiting:p,onChange:l}):void 0!==t.modeError&&(0,r.jsx)(a$,{label:d("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[d("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:os(t.modeError)})]})}),t.inlineBudget?(0,r.jsx)(p7,{budget:t.inlineBudget,save:i,waiting:p,onSave:o}):void 0!==t.inlineBudgetError&&(0,r.jsx)(a$,{label:d("mcp.codemode.inlineBudget"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[d("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:os(t.inlineBudgetError)})]})}),(0,r.jsx)(a$,{label:d("mcp.codemode.sandbox"),tone:"plain",children:"unavailable"===c.state?(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[d("mcp.codemode.sandbox.unavailable")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:os(c.error)})]}):(0,r.jsx)("span",{className:"mcp-config-line",children:d("available"===c.state?"mcp.codemode.sandbox.available":"mcp.codemode.sandbox.not-checked")})}),f&&(0,r.jsx)(a$,{label:d("mcp.codemode.builtin"),tone:"error",children:pD(f,d)})]})]})}function p5(e){let{error:t}=e,{t:n}=(0,eX.s)();return t.timedOut?(0,r.jsx)(r.Fragment,{children:n("mcp.codemode.saveTimedOut")}):t.reason&&"internal"!==t.reason?(0,r.jsx)(r.Fragment,{children:n(`mcp.reason.${t.reason}`)}):(0,r.jsx)("code",{className:"mcp-config-chip",children:os(t.error)})}function p9(e){let{mode:t,codemode:n,save:i,waiting:s,onChange:a}=e,{t:l}=(0,eX.s)(),o="mode"===i.target,d=function(e){let t=e.mode;if(!t)return[];let n=[];void 0!==t.invalid&&n.push({key:"mcp.codemode.toolMode.invalid",params:{path:t.settingsPath,value:t.invalid}});let r=t.projectOverride;return r&&n.push({key:o_[r.value],params:{path:r.settingsPath}}),"only"===(r??t).value&&"automatic"===oD(e)&&n.push({key:"mcp.codemode.toolMode.automaticNote"}),n}(n);return(0,r.jsx)(a$,{label:l("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)(aM,{value:t.value,label:l("mcp.codemode.toolMode"),options:[{value:"on",label:l("mcp.codemode.toolMode.on"),disabled:s},{value:"only",label:l("mcp.codemode.toolMode.only"),disabled:s}],onChange:e=>{(e!==t.value||void 0!==t.invalid)&&a(e)},children:o&&i.saving&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:l("i18n.saving")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:l(oH[t.value])}),d.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:pD(e,l)},e.key)),o&&i.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[l("mcp.codemode.toolMode.saveFailed")," ",(0,r.jsx)(p5,{error:i.error})]})]})})}function p7(e){let t,n,{budget:s,save:a,waiting:l,onSave:o}=e,{t:d}=(0,eX.s)(),c=(0,i.useRef)(null),u=(0,i.useId)(),p=void 0===s.value?"":String(s.value),[h,m]=(0,i.useState)(p);(0,i.useEffect)(()=>{m(p)},[p]);let g=function(e,t){let n=e.trim();if(""===n)return{ok:!0,value:null};if(!/^\d+$/.test(n))return{ok:!1};let r=Number(n);return r<=t?{ok:!0,value:r}:{ok:!1}}(h,s.max),f=!!g.ok&&(null===g.value?void 0!==s.value||void 0!==s.invalid:g.value!==s.value),x="inlineBudget"===a.target,b=x&&a.saving,v=(0,i.useRef)(b);(0,i.useEffect)(()=>{let e=v.current;v.current=b,e&&!b&&eE(document,c.current)},[b]);let y=(t=[],void 0!==s.invalid&&t.push({key:"mcp.codemode.inlineBudget.invalid",params:{path:s.settingsPath,value:s.invalid,default:String(s.default)}}),(n=s.projectOverride)&&t.push(void 0!==n.value?{key:"mcp.codemode.inlineBudget.projectOverride",params:{path:n.settingsPath,value:String(n.value)}}:{key:"mcp.codemode.inlineBudget.projectOverrideDefault",params:{path:n.settingsPath,default:String(s.default)}}),t);return(0,r.jsx)(a$,{label:d("mcp.codemode.inlineBudget"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsxs)("form",{className:"mcp-codemode-budget",onSubmit:e=>{e.preventDefault(),g.ok&&f&&!l&&o(g.value)},children:[(0,r.jsx)("input",{ref:c,className:"mcp-add-input mcp-codemode-budget-input",inputMode:"numeric","aria-label":d("mcp.codemode.inlineBudget"),"aria-describedby":u,"aria-invalid":!g.ok||void 0,value:h,placeholder:String(s.default),readOnly:l,autoComplete:"off",spellCheck:!1,onChange:e=>m(e.target.value)}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("mcp.codemode.inlineBudget.unit")}),(0,r.jsx)(aB,{type:"submit",size:"small",disabled:!f||l,children:d("mcp.codemode.inlineBudget.save")}),b&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:d("i18n.saving")})]}),!g.ok&&(0,r.jsx)("span",{className:"mcp-config-line is-error",children:d("mcp.codemode.inlineBudget.invalidDraft",{max:String(s.max)})}),(0,r.jsx)("span",{id:u,className:"mcp-config-line",children:d("mcp.codemode.inlineBudget.description",{default:String(s.default)})}),y.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:pD(e,d)},e.key)),x&&a.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[d("mcp.codemode.inlineBudget.saveFailed")," ",(0,r.jsx)(p5,{error:a.error})]})]})})}async function he(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 ht(e){var t;let n,{embedded:s=!0,onClose:a}=e,{t:l}=(0,eX.s)(),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(""),[m,g]=(0,i.useState)(""),[f,x]=(0,i.useState)(null),[b,v]=(0,i.useState)(null),y=(0,i.useRef)(!1),k=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/channels",{cache:"no-store"}),t=await e.json();if(!e.ok||t.error)return void u(t.error??`HTTP ${e.status}`);d(t),u(null),y.current||g(t.config.defaultCwd??"")}catch(e){u(e instanceof Error?e.message:String(e))}},[]);(0,i.useEffect)(()=>{k();let e=setInterval(()=>void k(),5e3);return()=>clearInterval(e)},[k]);let j=(0,i.useCallback)(async(e,t,n)=>{x(e),v(null);let r=await he(t);if(x(null),!r.ok)return void v({kind:"error",message:r.error??l("telegram.actionFailed")});let i=n();i&&v(i),await k()},[k,l]),{config:w}=o??{};return(0,r.jsxs)(ao,{embedded:s,title:l("settings.channels"),closeLabel:l("i18n.close"),onClose:()=>a?.(),children:[(0,r.jsxs)(ah,{children:[(0,r.jsx)(am,{children:(0,r.jsx)(ag,{children:c&&!o?(0,r.jsx)("div",{role:"alert",className:"config-sidebar-message is-error",children:l("channels.loadFailed",{error:c})}):o?(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(af,{children:l("channels.group")}),(n=o.config.tokenSet?o.config.enabled?o.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)(av,{active:!0,"aria-label":`Telegram — ${l(n.badge)}`,children:[(0,r.jsx)(aU,{..."on"===(t=n.tone)?{active:!0}:"off"===t?{active:!1}:{color:"#ef4444"}}),(0,r.jsx)(ay,{className:"is-grow",children:"Telegram"}),(0,r.jsx)("span",{className:`mcp-sidebar-badge${"error"===n.tone?" is-error":""}`,children:l(n.badge)})]}))]}):(0,r.jsx)("div",{className:"config-sidebar-message",children:l("i18n.loading")})})}),(0,r.jsx)(aW,{children:(0,r.jsx)(ak,{className:"is-fill",children:o&&w?(0,r.jsxs)(r.Fragment,{children:[b&&(0,r.jsx)(aP,{children:b.message}),o.lastError&&(0,r.jsx)(aP,{children:l("telegram.loopError",{error:o.lastError})}),(0,r.jsxs)(aj,{children:[(0,r.jsx)(aw,{children:(0,r.jsx)(aC,{children:"Telegram"})}),(0,r.jsx)(aS,{children:(0,r.jsx)(aH,{checked:w.enabled,disabled:!w.tokenSet||null!==f,label:l("telegram.enabledLabel"),onChange:e=>void j("enabled",{action:"set-enabled",enabled:e},()=>null)})})]}),!w.tokenSet&&(0,r.jsx)(aP,{children:l("telegram.setupHint")}),(0,r.jsxs)(aE,{children:[(0,r.jsx)(a$,{label:l("telegram.botStatus"),children:o.running?l("telegram.connected",{bot:o.botUsername??""}):l("telegram.notConnected")}),(0,r.jsx)(a$,{label:l("telegram.tokenLabel"),children:(0,r.jsx)("input",{type:"password",autoComplete:"off",spellCheck:!1,className:"mcp-add-input",placeholder:w.tokenSet?l("telegram.tokenPlaceholder",{hint:w.tokenHint??""}):"1234567890:AA…","aria-label":l("telegram.tokenLabel"),value:p,onChange:e=>h(e.target.value)})})]}),(0,r.jsxs)(aS,{children:[(0,r.jsx)(aB,{size:"small",disabled:""===p.trim()||null!==f,onClick:()=>void j("token",{action:"set-token",token:p.trim()},()=>(h(""),{kind:"ok",message:l("telegram.tokenSaved")})),children:l("telegram.tokenSave")}),w.tokenSet&&(0,r.jsx)(aB,{size:"small",variant:"secondary",disabled:null!==f,onClick:()=>void j("remove-token",{action:"remove-token"},()=>({kind:"info",message:l("telegram.tokenRemoved")})),children:l("telegram.tokenRemove")})]}),(0,r.jsx)(aN,{children:l("telegram.chatsHeading")}),(0,r.jsx)(aw,{children:l("telegram.chatsDescription")}),o.lastUnknownChat&&(0,r.jsx)(aP,{action:(0,r.jsx)(aB,{size:"small",disabled:null!==f||w.allowedChats.some(e=>e.id===o.lastUnknownChat?.id),onClick:()=>void j("allow",{action:"allow-chat",chatId:o.lastUnknownChat?.id,title:o.lastUnknownChat?.title},()=>({kind:"ok",message:l("telegram.chatAllowed")})),children:l("telegram.allowChat")}),children:l("telegram.unknownChatPrompt",{title:o.lastUnknownChat.title??l("telegram.unnamedChat"),id:String(o.lastUnknownChat.id)})}),0===w.allowedChats.length?(0,r.jsx)(aO,{children:l("telegram.noChats")}):(0,r.jsx)(r.Fragment,{children:w.allowedChats.map(e=>(0,r.jsx)("div",{className:"channels-chat",children:(0,r.jsxs)(aE,{children:[(0,r.jsxs)(a$,{label:e.title??l("telegram.unnamedChat"),mono:!0,children:[e.id,(0,r.jsxs)(aS,{children:[(0,r.jsx)(aB,{size:"small",variant:"secondary",disabled:null!==f,onClick:()=>void j(`test-${e.id}`,{action:"test-send",chatId:e.id},()=>({kind:"ok",message:l("telegram.testSent")})),children:l("telegram.testSend")}),(0,r.jsx)(aB,{size:"small",variant:"secondary",disabled:null!==f,onClick:()=>void j(`remove-${e.id}`,{action:"remove-chat",chatId:e.id},()=>({kind:"info",message:l("telegram.chatRemoved")})),children:l("telegram.chatRemove")})]})]}),(0,r.jsx)(a$,{label:l("telegram.chatCwdLabel"),children:(0,r.jsx)("input",{type:"text",spellCheck:!1,className:"mcp-add-input",placeholder:l("telegram.defaultCwdPlaceholder"),"aria-label":l("telegram.chatCwdLabel"),defaultValue:e.cwd??"",onBlur:t=>{let n=t.target.value.trim();n!==(e.cwd??"")&&j(`cwd-${e.id}`,{action:"set-chat-cwd",chatId:e.id,cwd:n},()=>({kind:"ok",message:l("telegram.chatCwdSaved")}))}},`${e.id}:${e.cwd??""}`)})]})},e.id))}),(0,r.jsx)(aN,{children:l("telegram.defaultCwdLabel")}),(0,r.jsx)(aE,{children:(0,r.jsx)(a$,{label:l("telegram.defaultCwdLabel"),children:(0,r.jsx)("input",{type:"text",spellCheck:!1,className:"mcp-add-input",placeholder:l("telegram.defaultCwdPlaceholder"),"aria-label":l("telegram.defaultCwdLabel"),value:m,onChange:e=>{y.current=!0,g(e.target.value)}})})}),(0,r.jsx)(aS,{children:(0,r.jsx)(aB,{size:"small",disabled:null!==f,onClick:()=>void j("cwd",{action:"set-default-cwd",cwd:m.trim()},()=>({kind:"ok",message:l("telegram.defaultCwdSaved")})),children:l("telegram.defaultCwdSave")})})]}):null})})]}),(0,r.jsx)(aF,{status:o?(0,r.jsx)(aD,{tone:o.lastError?"warning":void 0,summary:o.running?l("telegram.connected",{bot:o.botUsername??""}):l("telegram.notConnected")}):void 0,children:!s&&a&&(0,r.jsx)(aB,{onClick:a,children:l("i18n.close")})})]})}let hn={minutes:6e4,hours:36e5,days:864e5};function hr(e){return String(e).padStart(2,"0")}function hi(e){let t=new Date(e);return`${t.getFullYear()}-${hr(t.getMonth()+1)}-${hr(t.getDate())}T${hr(t.getHours())}:${hr(t.getMinutes())}`}function hs(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)*hn[e.everyUnit];return Number.isFinite(t)&&e.everyValue>0?{kind:"every",everyMs:t}:null}function ha(e){if(!e)return{name:"",kind:"every",cronExpr:"0 9 * * *",cronTz:Intl.DateTimeFormat().resolvedOptions().timeZone,atLocal:hi(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?hi(t.atMs):hi(Date.now()+36e5),everyValue:"every"===t.kind?t.everyMs/hn.hours>=1&&t.everyMs%hn.hours==0?t.everyMs/hn.hours:Math.max(1,Math.round(t.everyMs/hn.minutes)):1,everyUnit:"every"===t.kind&&(t.everyMs%hn.hours!=0||t.everyMs<hn.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 hl(e,t){if(null===e)return t("automations.neverAgain");let n=new Date(e),r=new Date().toDateString()===n.toDateString(),i=`${hr(n.getHours())}:${hr(n.getMinutes())}`;return r?i:`${hr(n.getMonth()+1)}-${hr(n.getDate())} ${i}`}async function ho(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 hd(e){let{embedded:t=!0,onClose:n}=e,{t:s}=(0,eX.s)(),[a,l]=(0,i.useState)(null),[o,d]=(0,i.useState)([]),[c,u]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(()=>ha(null)),[x,b]=(0,i.useState)(null),[v,y]=(0,i.useState)(null),[k,j]=(0,i.useState)(null),w=(0,i.useRef)("ok"),S=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/automations",{cache:"no-store"}),t=await e.json();if(!e.ok||t.error)return;l(t.automations??[]),d(t.runs??[]),t.telegram&&u(t.telegram)}catch{}},[]);(0,i.useEffect)(()=>{S();let e=setInterval(()=>void S(),5e3);return()=>clearInterval(e)},[S]);let C=(0,i.useMemo)(()=>a?.find(e=>e.id===h)??null,[a,h]),N=(0,i.useCallback)(e=>{m(e),b(null),j(null),f(ha(a?.find(t=>t.id===e)??null))},[a]),I=(0,i.useCallback)(()=>{m("new"),b(null),j(null),f(ha(null))},[]);(0,i.useEffect)(()=>{let e=hs(g);if(!e)return;let t=setTimeout(()=>{ho({action:"preview",schedule:e}).then(e=>{e.ok?b({dueAt:"number"==typeof e.payload?.dueAt?e.payload.dueAt:null,problem:"string"==typeof e.payload?.problem?e.payload.problem:null}):b({dueAt:null,problem:e.error??s("automations.actionFailed")})})},400);return()=>clearTimeout(t)},[g,s]);let E=(0,i.useCallback)(async(e,t,n)=>{y(e),j(null);let r=await ho(t);return(y(null),r.ok)?(null!==n&&(w.current="ok",j(n)),await S(),!0):(w.current="error",j(r.error??s("automations.actionFailed")),!1)},[S,s]),$=()=>n?.(),T=null!==C,M=hs(g),R=""!==g.name.trim()&&""!==g.cwd.trim()&&""!==g.prompt.trim()&&null!==M&&x?.problem==null;return(0,r.jsxs)(ao,{embedded:t,title:s("settings.automations"),closeLabel:s("i18n.close"),onClose:$,children:[(0,r.jsxs)(ah,{children:[(0,r.jsxs)(am,{children:[(0,r.jsx)(ag,{children:null===a?(0,r.jsx)("div",{className:"config-sidebar-message",children:s("i18n.loading")}):0===a.length&&null===h?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:s("automations.noneYet")}):(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(af,{children:s("automations.group")}),a.map(e=>(0,r.jsxs)(av,{active:h===e.id,onClick:()=>N(e.id),children:[(0,r.jsx)(aU,{active:e.enabled&&null!==e.nextDueAt}),(0,r.jsx)(ay,{className:"is-grow",children:e.name}),(0,r.jsx)("span",{className:"mcp-sidebar-badge",children:e.enabled?null!==e.nextDueAt?hl(e.nextDueAt,s):"…":s("channels.badge.off")})]},e.id))]})}),(0,r.jsx)(a_,{active:"new"===h,onClick:I,children:s("automations.newAction")})]}),(0,r.jsx)(aW,{children:(0,r.jsxs)(ak,{className:"is-fill",children:[(null===h||"new"===h||T)&&(0,r.jsxs)(r.Fragment,{children:[k&&(0,r.jsx)(aP,{children:k}),null!==h&&"new"!==h&&T&&(0,r.jsxs)(aj,{children:[(0,r.jsx)(aw,{children:(0,r.jsx)(aC,{children:C.name})}),(0,r.jsxs)(aS,{children:[(0,r.jsx)(aH,{checked:C.enabled,disabled:null!==v,label:s("automations.enabledLabel"),onChange:e=>void E(`enabled-${C.id}`,{action:"set-enabled",id:C.id,enabled:e},null)}),(0,r.jsx)(aB,{size:"small",variant:"secondary",disabled:null!==v,onClick:()=>void E(`run-${C.id}`,{action:"run-now",id:C.id},s("automations.runStarted")),children:s("automations.runNow")}),(0,r.jsx)(aB,{size:"small",variant:"danger",disabled:null!==v,onClick:()=>{E(`delete-${C.id}`,{action:"delete",id:C.id},s("automations.deleted")).then(e=>{e&&N(null)})},children:s("automations.delete")})]})]}),(0,r.jsxs)(aE,{children:[(0,r.jsx)(a$,{label:s("automations.nameLabel"),children:(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,"aria-label":s("automations.nameLabel"),value:g.name,onChange:e=>f(t=>({...t,name:e.target.value}))})}),(0,r.jsx)(a$,{label:s("automations.scheduleLabel"),children:(0,r.jsxs)("div",{className:"automations-schedule",children:[(0,r.jsxs)("select",{"aria-label":s("automations.scheduleLabel"),value:g.kind,onChange:e=>f(t=>({...t,kind:e.target.value})),children:[(0,r.jsx)("option",{value:"cron",children:s("automations.kind.cron")}),(0,r.jsx)("option",{value:"every",children:s("automations.kind.every")}),(0,r.jsx)("option",{value:"at",children:s("automations.kind.at")})]}),"cron"===g.kind&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,placeholder:"0 9 * * 1-5","aria-label":s("automations.cronExpr"),value:g.cronExpr,onChange:e=>f(t=>({...t,cronExpr:e.target.value}))}),(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,placeholder:"Asia/Shanghai","aria-label":s("automations.cronTz"),value:g.cronTz,onChange:e=>f(t=>({...t,cronTz:e.target.value}))})]}),"every"===g.kind&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{className:"automations-number-input",type:"number",min:1,"aria-label":s("automations.everyValue"),value:g.everyValue,onChange:e=>f(t=>({...t,everyValue:Number(e.target.value)}))}),(0,r.jsxs)("select",{"aria-label":s("automations.everyUnit"),value:g.everyUnit,onChange:e=>f(t=>({...t,everyUnit:e.target.value})),children:[(0,r.jsx)("option",{value:"minutes",children:s("automations.unit.minutes")}),(0,r.jsx)("option",{value:"hours",children:s("automations.unit.hours")}),(0,r.jsx)("option",{value:"days",children:s("automations.unit.days")})]})]}),"at"===g.kind&&(0,r.jsx)("input",{className:"automations-datetime-input",type:"datetime-local","aria-label":s("automations.atTime"),value:g.atLocal,onChange:e=>f(t=>({...t,atLocal:e.target.value}))})]})}),(0,r.jsx)(a$,{label:s("automations.nextRun"),children:null===x?"…":null!==x.problem?`⚠️ ${x.problem}`:`${hl(x.dueAt,s)}`}),(0,r.jsx)(a$,{label:s("automations.cwdLabel"),children:(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,placeholder:"/Volumes/…","aria-label":s("automations.cwdLabel"),value:g.cwd,onChange:e=>f(t=>({...t,cwd:e.target.value}))})}),(0,r.jsx)(a$,{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)(aH,{checked:g.notify,label:s("automations.notifyBrowser"),onChange:e=>f(t=>({...t,notify:e}))}),(0,r.jsx)("span",{children:s("automations.notifyBrowser")})]}),null!==c&&c.chats.map(e=>{let t=g.notifyChannels.some(t=>t.chatId===e.id);return(0,r.jsxs)("label",{className:"automations-notify-row",children:[(0,r.jsx)("input",{type:"checkbox",checked:t,onChange:t=>f(n=>({...n,notifyChannels:t.target.checked?[...n.notifyChannels,{type:"telegram",chatId:e.id}]:n.notifyChannels.filter(t=>t.chatId!==e.id)}))}),(0,r.jsx)("span",{children:null!==e.title&&""!==e.title.trim()?e.title:`Telegram \xb7 ${e.id}`})]},e.id)}),null!==c&&0===c.chats.length&&(0,r.jsx)("div",{className:"automations-notify-hint",children:s("automations.notifyTelegramHint")}),(0,r.jsxs)("div",{className:"automations-notify-row is-wide",children:[(0,r.jsx)("span",{className:"automations-notify-silent-label",children:s("automations.notifySilentLabel")}),(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,placeholder:"NO_REPLY","aria-label":s("automations.notifySilentLabel"),value:g.silentWhen,onChange:e=>f(t=>({...t,silentWhen:e.target.value}))})]}),(0,r.jsx)("div",{className:"automations-notify-hint",children:s("automations.notifySilentHint")})]})})]}),(0,r.jsx)(aI,{label:s("automations.promptLabel"),children:(0,r.jsx)("textarea",{className:"automations-prompt",rows:5,spellCheck:!1,"aria-label":s("automations.promptLabel"),value:g.prompt,onChange:e=>f(t=>({...t,prompt:e.target.value}))})}),"new"===h&&(0,r.jsx)(aP,{children:s("automations.disclosure")}),(0,r.jsx)(aS,{children:(0,r.jsx)(aB,{disabled:!R||null!==v,onClick:()=>{E("save",{action:T?"update":"create",...T?{id:C.id}:{},name:g.name.trim(),schedule:hs(g),cwd:g.cwd.trim(),prompt:g.prompt,notify:g.notify,notifyChannels:g.notifyChannels,silentWhen:g.silentWhen.trim()},T?s("automations.saved"):s("automations.created")).then(e=>{e&&(T||m(null))})},children:T?s("automations.save"):s("automations.create")})})]}),(0,r.jsx)(aN,{children:s("automations.historyTitle")}),0===o.length?(0,r.jsx)(aO,{children:s("automations.noRuns")}):(0,r.jsx)(aE,{children:o.slice(0,12).map(e=>{let t=a?.find(t=>t.id===e.automationId),n=null!==e.finishedAt?Math.max(1,Math.round((e.finishedAt-e.startedAt)/1e3)):null;return(0,r.jsxs)(a$,{label:t?.name??s("automations.deletedAutomation"),mono:!0,children:[(0,r.jsx)(aU,{..."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)(aB,{size:"small",variant:"secondary",onClick:()=>window.open(p(e.sessionId),"_blank"),children:s("automations.openSession")})]},e.id)})})]})})]}),(0,r.jsx)(aF,{status:null!==a?(0,r.jsx)(aD,{summary:s("automations.footerCount",{count:a.length})}):void 0,children:!t&&$&&(0,r.jsx)(aB,{onClick:$,children:s("i18n.close")})})]})}function hc(e){return e instanceof Error?e.message:String(e)}function hu(e){let{embedded:t=!0,onClose:n,fetchImpl:s}=e,{t:a,locale:l}=(0,eX.s)(),o=s??fetch,[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(()=>new Set),[g,f]=(0,i.useState)(null),[x,b]=(0,i.useState)(null),[v,y]=(0,i.useState)(null),[k,j]=(0,i.useState)(!1),[w,S]=(0,i.useState)({}),C=(0,i.useCallback)(async()=>{try{let e=await o("/api/shares",{cache:"no-store"}),t=await e.json().catch(()=>({}));if(!e.ok||!Array.isArray(t.shares))return void p(t.error??`HTTP ${e.status}`);let n=t.shares;c(n),p(null),y(null),j(!1),m(e=>new Set([...e].filter(e=>n.some(t=>t.sessionId===e)))),S(e=>{let t={};for(let r of n)t[r.sessionId]=e[r.sessionId]??r.durationDays;return t})}catch(e){p(hc(e))}},[o]);(0,i.useEffect)(()=>{C()},[C]);let N=(0,i.useCallback)(e=>{c(t=>t?.filter(t=>!e.has(t.sessionId))??t),m(t=>{let n=new Set(t);for(let t of e)n.delete(t);return n}),S(t=>{let n={...t};for(let t of e)delete n[t];return n}),y(null),j(!1)},[]),I=(0,i.useCallback)(e=>{y(null),j(!1),m(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),E=(0,i.useCallback)(()=>{y(null),j(!1),m(e=>d&&0!==d.length?d.every(t=>e.has(t.sessionId))?new Set:new Set(d.map(e=>e.sessionId)):e)},[d]),$=(0,i.useCallback)(async e=>{try{await (0,tc.D)(t6(window.location.origin,e)),b({kind:"ok",message:a("shares.linkCopied")})}catch{}},[a]),T=(0,i.useCallback)(async e=>{if(null!==g)return;let t=w[e]??7;f(`renew:${e}`),b(null);try{let n=await o("/api/shares",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"renew",sessionId:e,durationDays:t})}),r=await n.json().catch(()=>({}));if(!n.ok||!r.share||null!==r.share.expiresAt&&"string"!=typeof r.share.expiresAt)return void b({kind:"error",message:a("shares.renewError",{error:r.error??`HTTP ${n.status}`})});let i=r.share.expiresAt;c(n=>n?.map(n=>n.sessionId===e?{...n,expiresAt:i,expired:!1,durationDays:t}:n)??n),S(n=>({...n,[e]:t})),b({kind:"ok",message:null===t||null===i?a("shares.renewedPermanent"):a("shares.renewed",{time:(0,tm.fw)(i,l)})})}catch(e){b({kind:"error",message:a("shares.renewError",{error:hc(e)})})}finally{f(null)}},[g,l,w,o,a]),M=(0,i.useCallback)(async e=>{if(null===g){if(v!==e)return void y(e);f(`revoke:${e}`),b(null);try{let t=await o("/api/shares",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"revoke",ids:[e]})}),n=await t.json().catch(()=>({}));if(!t.ok||!0!==n.ok)return void b({kind:"error",message:a("shares.revokeError",{error:n.error??`HTTP ${t.status}`})});N(new Set(n.revoked??[])),b({kind:"ok",message:a("shares.revoked",{count:(n.revoked??[]).length})})}catch(e){b({kind:"error",message:a("shares.revokeError",{error:hc(e)})})}finally{f(null)}}},[g,N,o,v,a]),R=(0,i.useCallback)(async()=>{if(null!==g||0===h.size)return;if(!k)return void j(!0);f("revoke-all"),b(null);let e=[...h],t=[];try{let n=null;for(let r=0;r<e.length&&null===n;r+=500){let i=await o("/api/shares",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"revoke",ids:e.slice(r,r+500)})}),s=await i.json().catch(()=>({}));i.ok&&!0===s.ok?t.push(...s.revoked??[]):n=s.error??`HTTP ${i.status}`}t.length>0&&N(new Set(t)),b(null!==n?{kind:"error",message:a("shares.revokeError",{error:n})}:{kind:"ok",message:a("shares.revoked",{count:t.length})})}catch(e){t.length>0&&N(new Set(t)),b({kind:"error",message:a("shares.revokeError",{error:hc(e)})})}finally{f(null)}},[g,N,o,k,h,a]);return(0,r.jsx)(hp,{embedded:t,onClose:()=>n?.(),items:d,loadError:u,selected:h,busy:g,line:x,revokeArmedRow:v,revokeAllArmed:k,renewDrafts:w,onToggleRow:I,onToggleAll:E,onRenewDraft:(e,t)=>S(n=>({...n,[e]:t})),onRenew:e=>void T(e),onRevoke:e=>void M(e),onRevokeSelected:()=>void R(),onReload:()=>void C(),onCopyLink:e=>void $(e)})}function hp(e){let{embedded:t,onClose:n,items:i,loadError:s,selected:a,busy:l,line:o,revokeArmedRow:d,revokeAllArmed:c,renewDrafts:u,onToggleRow:p,onToggleAll:h,onRenewDraft:m,onRenew:g,onRevoke:f,onRevokeSelected:x,onReload:b,onCopyLink:v}=e,{t:y,locale:k}=(0,eX.s)(),j=(i?.length??0)>0&&i.every(e=>a.has(e.sessionId));return(0,r.jsx)(ao,{embedded:t,title:y("settings.shares"),closeLabel:y("i18n.close"),onClose:n,children:(0,r.jsxs)("div",{className:"shares-config",children:[(0,r.jsxs)("div",{className:"shares-config-head",children:[(0,r.jsx)("p",{className:"shares-config-description",children:y("shares.description")}),(0,r.jsx)(aB,{size:"small",disabled:null!==l,onClick:b,children:y("shares.refresh")})]}),o&&(0,r.jsx)("div",{role:"status",className:`shares-config-line is-${o.kind}`,children:o.message}),null!==i&&null!==s&&(0,r.jsx)("div",{role:"alert",className:"shares-config-line is-error",children:y("shares.loadError",{error:s})}),null===i&&null!==s?(0,r.jsx)("div",{role:"alert",className:"shares-config-line is-error",children:y("shares.loadError",{error:s})}):null===i?(0,r.jsx)("div",{role:"status",className:"shares-config-loading",children:y("i18n.loading")}):0===i.length?(0,r.jsx)(aO,{children:y("shares.empty")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"shares-config-count",children:y("shares.count",{count:i.length})}),(0,r.jsx)("div",{className:"shares-table-wrap",children:(0,r.jsxs)("table",{className:"shares-table",children:[(0,r.jsx)("thead",{children:(0,r.jsxs)("tr",{children:[(0,r.jsx)("th",{scope:"col",className:"shares-table-check",children:(0,r.jsx)("input",{type:"checkbox",checked:j,onChange:h,"aria-label":y("shares.selectAll")})}),(0,r.jsx)("th",{scope:"col",children:y("shares.columnSession")}),(0,r.jsx)("th",{scope:"col",children:y("shares.columnCreated")}),(0,r.jsx)("th",{scope:"col",children:y("shares.columnValidity")}),(0,r.jsx)("th",{scope:"col",children:y("shares.columnStatus")}),(0,r.jsx)("th",{scope:"col"})]})}),(0,r.jsx)("tbody",{children:i.map(e=>{let t=u[e.sessionId]??7,n=d===e.sessionId;return(0,r.jsxs)("tr",{children:[(0,r.jsx)("td",{className:"shares-table-check",children:(0,r.jsx)("input",{type:"checkbox",checked:a.has(e.sessionId),onChange:()=>p(e.sessionId),"aria-label":`${y("shares.selectRow")}: ${e.title}`})}),(0,r.jsxs)("td",{className:"shares-table-session",children:[(0,r.jsx)("a",{className:"shares-table-title",href:`/share/${e.code}`,target:"_blank",rel:"noreferrer",children:e.title}),(0,r.jsxs)("div",{className:"shares-table-code",title:e.code,children:["…",e.code.slice(-6)]})]}),(0,r.jsx)("td",{children:(0,tm.fw)(e.createdAt,k)}),(0,r.jsx)("td",{children:null===e.expiresAt?y("shares.permanent"):e.expired?y("shares.expiredWhen",{time:(0,tm.fw)(e.expiresAt,k)}):y("shares.expiresIn",{time:(0,tm.fw)(e.expiresAt,k)})}),(0,r.jsxs)("td",{className:"shares-table-status",children:[e.expired&&(0,r.jsx)("span",{className:"mcp-sidebar-badge is-warning",children:y("share.expired")}),e.orphan&&(0,r.jsx)("span",{className:"mcp-sidebar-badge",title:y("shares.orphanHint"),children:y("shares.orphan")})]}),(0,r.jsx)("td",{className:"shares-table-actions",children:(0,r.jsxs)("div",{className:"shares-table-actions-row",children:[(0,r.jsx)(aB,{size:"small",onClick:()=>v(e.code),children:y("shares.copyLink")}),(0,r.jsx)("select",{className:"shares-duration-select","aria-label":y("share.durationLabel"),value:t4(t),onChange:t=>m(e.sessionId,t8(t.target.value)),children:t2.map(e=>(0,r.jsx)("option",{value:t4(e.value),children:y(e.labelKey)},e.labelKey))}),(0,r.jsx)(aB,{size:"small",disabled:null!==l,onClick:()=>g(e.sessionId),children:y("shares.renew")}),(0,r.jsx)(aB,{size:"small",variant:n?"danger":"secondary",disabled:null!==l,onClick:()=>f(e.sessionId),children:n?y("shares.confirmRevoke"):y("shares.revoke")})]})})]},e.sessionId)})})]})}),(0,r.jsx)(aF,{children:(0,r.jsx)(aB,{variant:c?"danger":"secondary",disabled:0===a.size||null!==l,onClick:x,children:c?y("shares.confirmRevokeSelected",{count:a.size}):y("shares.revokeSelected",{count:a.size})})})]})]})})}var hh=n(75702);let hm=[{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 hg(){let{t:e}=(0,eX.s)(),t=(0,rx.VE)();return(0,r.jsx)("div",{className:"settings-font-rows",children:hm.map(n=>{let{kind:i,label:s,placeholder:a,reset:l,weightLabel:o}=n,d=t[`${i}Weight`],c=hh.qI.findIndex(e=>e.value===d);return(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option settings-font-row",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header settings-font-header",children:[(0,r.jsx)("label",{htmlFor:`settings-font-${i}`,children:e(s)}),(0,r.jsx)("input",{id:`settings-font-${i}`,className:`settings-font-input${"mono"===i?" is-mono":""}`,type:"text",value:t[i],placeholder:e(a),maxLength:hh.zx,"aria-describedby":"settings-typography-description",autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,onChange:e=>t.setFontPreference(i,e.target.value)}),(0,r.jsx)("output",{htmlFor:`settings-font-${i}-weight`,title:`${e(o)}: ${d}`,children:e(hh.qI[c].label)}),(0,r.jsx)(aB,{variant:"ghost",size:"small",className:"settings-chat-reset",title:e(l),"aria-label":e(l),disabled:!t[i]&&d===hh.Fj,onClick:()=>t.resetFontPreference(i),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:`settings-font-${i}-weight`,type:"range",min:hh.qI[0].value,max:hh.qI[hh.qI.length-1].value,step:100,value:d,"aria-label":e(o),"aria-valuetext":`${d} ${e(hh.qI[c].label)}`,onChange:e=>t.setFontWeight(i,Number(e.target.value))})]},i)})})}function hf(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"})]}):"shares"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),(0,r.jsx)("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"})]}):(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 hx(e){let{sessionId:t,onSessionReloaded:n,quoteSelectionEnabled:s,onQuoteSelectionChange:a}=e,{locale:l,setLocale:o,supportedLocales:d,t:c}=(0,eX.s)(),{preference:u,setThemePreference:p}=(0,sL.D)(),{width:h,setWidth:m,fontSize:g,setFontSize:f}=(0,rf.Uh)(),x=rh(),b=eY(),[v,y]=(0,i.useState)(null),[k,j]=(0,i.useState)(!1),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(!1),[I,E]=(0,i.useState)(null),[$,T]=(0,i.useState)(!1),[M,R]=(0,i.useState)(null),[A,L]=(0,i.useState)(!1),[P,z]=(0,i.useState)(null),[O,W]=(0,i.useState)(null),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)(null),[_,U]=(0,i.useState)(!1),[K,q]=(0,i.useState)(null),[Z,V]=(0,i.useState)(!1),[J,G]=(0,i.useState)(!1),[Y,X]=(0,i.useState)("");(0,i.useEffect)(()=>{T((0,sq.ql)()),fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>V(e?.enabled===!0)).catch(()=>{})},[]);let Q=async()=>{G(!0),X("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.replace("/login")}catch{X(c("auth.logoutFailed"))}finally{G(!1)}};(0,i.useEffect)(()=>{let e=!1;return fetch("/api/tools/settings").then(async t=>{let n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);e||y(n)}).catch(t=>{e||S(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/cache-miss-notices").then(async t=>{let n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);e||R(!0===n.enabled)}).catch(t=>{e||z(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/auto-title").then(async t=>{let n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);e||W(!0===n.enabled)}).catch(t=>{e||H(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]);let ee=async e=>{L(!0),z(null);try{let r=await fetch("/api/cache-miss-notices",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);R(!0===i.enabled),t&&n()}catch(e){z(e instanceof Error?e.message:String(e))}finally{L(!1)}},et=async e=>{D(!0),H(null);try{let t=await fetch("/api/auto-title",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);W(!0===n.enabled)}catch(e){H(e instanceof Error?e.message:String(e))}finally{D(!1)}},en=async e=>{j(!0),S(null);try{let r=await fetch("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);y(i),t&&(await iE(t,{type:"reload"}),n())}catch(e){S(e instanceof Error?e.message:String(e))}finally{j(!1)}},er=async(e,t)=>{if(v){N(!0),E(null);try{let n=t?[...v.builtinTools,e]:v.builtinTools.filter(t=>t!==e),r=await fetch("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({builtinTools:n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);y(i)}catch(e){E(e instanceof Error?e.message:String(e))}finally{N(!1)}}},ei=async()=>{if(!_){U(!0),q(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 l$(l))throw Error("unsupported or not permitted");q({kind:"ok",message:c("settings.pushRegistered")})}catch(e){q({kind:"error",message:`${c("settings.pushRegisterFailed")} ${e instanceof Error?e.message:String(e)}`})}finally{U(!1)}}};return(0,r.jsxs)("div",{className:"settings-general",children:[(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.appearance")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":c("settings.appearance"),className:"settings-theme-options",children:sP.F$.map(e=>{let t=u===e.id;return(0,r.jsxs)("label",{className:"settings-theme-option","data-system":"auto"===e.id||void 0,"data-wide":"contrast-light"===e.id||"contrast-dark"===e.id||"zenburn"===e.id||void 0,children:[(0,r.jsx)("input",{type:"radio",name:"theme",value:e.id,checked:t,onChange:()=>p(e.id),className:"sr-only"}),"auto"===e.id?(0,r.jsxs)("span",{className:"settings-theme-swatch settings-theme-system","aria-hidden":"true",children:[(0,r.jsx)("span",{"data-theme":"light",className:"settings-theme-chip"}),(0,r.jsx)("span",{"data-theme":"dark",className:"settings-theme-chip"}),(0,r.jsx)("span",{className:"settings-theme-system-name",children:c(e.label)})]}):(0,r.jsx)("span",{className:"settings-theme-swatch","aria-hidden":"true",children:(0,r.jsx)("span",{"data-theme":e.id,className:"settings-theme-fill",children:(0,r.jsx)("span",{className:"settings-theme-name",children:c(e.label)})})}),(0,r.jsx)("span",{className:"sr-only",children:c(e.label)})]},e.id)})})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.typography")}),(0,r.jsx)("p",{id:"settings-typography-description",className:"settings-general-description",children:c("settings.fontDescription")}),(0,r.jsxs)("div",{className:"settings-chat-options",children:[(0,r.jsx)(hg,{}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-font-size",children:c("settings.chatContentFontSize")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-font-size",children:[g,"px"]}),(0,r.jsx)(aB,{variant:"ghost",size:"small",className:"settings-chat-reset",title:c("settings.resetChatContentFontSize"),"aria-label":c("settings.resetChatContentFontSize"),disabled:g===rf.NN,onClick:()=>f(rf.NN),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:"settings-chat-content-font-size",type:"range",min:rf.WH,max:rf.Oi,step:1,value:g,onChange:e=>f(Number(e.target.value))})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-width",children:c("settings.chatContentWidth")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-width",children:[h,"px"]}),(0,r.jsx)(aB,{variant:"ghost",size:"small",className:"settings-chat-reset",title:c("settings.resetChatContentWidth"),"aria-label":c("settings.resetChatContentWidth"),disabled:h===rf.mi,onClick:()=>m(rf.mi),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:"settings-chat-content-width",type:"range",min:rf.lg,max:rf.fI,step:10,value:h,onChange:e=>m(Number(e.target.value))})]})]})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.chat")}),(0,r.jsxs)("div",{className:"settings-chat-options",children:[(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:c("settings.thinkingExpandedDefault")}),(0,r.jsx)(aH,{checked:$,label:c("settings.thinkingExpandedDefault"),onChange:e=>{(0,sq.kF)(e),T(e)}})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:c("settings.quoteSelection")}),(0,r.jsx)(aH,{checked:s,label:c("settings.quoteSelection"),onChange:a})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",role:"radiogroup","aria-label":c("settings.enterSendMode"),children:[(0,r.jsx)("span",{children:c("settings.enterSendMode")}),(0,r.jsxs)("div",{className:"settings-send-mode-options",children:[(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"enter-send-mode",value:"enter",checked:"enter"===x,onChange:()=>rp("enter"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:c("settings.enterSendModeEnter")})]}),(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"enter-send-mode",value:"ctrlEnter",checked:"ctrlEnter"===x,onChange:()=>rp("ctrlEnter"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:c("settings.enterSendModeCtrlEnter")})]})]})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:c("settings.cacheMissNotices")}),(0,r.jsx)(aH,{checked:!0===M,loading:null===M&&!P||A,label:c("settings.cacheMissNotices"),describedBy:"settings-cache-miss-notices-description",onChange:e=>void ee(e)})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:c("settings.autoTitle")}),(0,r.jsx)(aH,{checked:!1!==O,loading:null===O&&!B||F,label:c("settings.autoTitle"),describedBy:"settings-auto-title-description",onChange:e=>void et(e)})]})]}),(0,r.jsx)("p",{id:"settings-cache-miss-notices-description",className:"settings-general-description",children:c("settings.cacheMissNoticesDescription")}),P&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:P}),(0,r.jsx)("p",{id:"settings-auto-title-description",className:"settings-general-description",children:c("settings.autoTitleDescription")}),B&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:B})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.sidebar")}),(0,r.jsx)("div",{className:"settings-chat-options",children:(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",role:"radiogroup","aria-label":c("settings.filesPlacement"),"aria-describedby":"settings-files-placement-description",children:[(0,r.jsx)("span",{children:c("settings.filesPlacement")}),(0,r.jsxs)("div",{className:"settings-send-mode-options",children:[(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"files-placement",value:"below",checked:"below"===b,onChange:()=>eG("below"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:c("settings.filesPlacementBelow")})]}),(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"files-placement",value:"tab",checked:"tab"===b,onChange:()=>eG("tab"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:c("settings.filesPlacementTab")})]})]})]})}),(0,r.jsx)("p",{id:"settings-files-placement-description",className:"settings-general-description",children:c("settings.filesPlacementDescription")})]}),v&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.builtinTools")}),(0,r.jsx)("p",{id:"settings-builtin-tools-description",className:"settings-general-description",children:c("settings.builtinToolsDescription")}),(0,r.jsx)("div",{className:"settings-send-mode-options settings-builtin-tools",role:"group","aria-label":c("settings.builtinTools"),"aria-describedby":"settings-builtin-tools-description",children:iW.kt.map(e=>(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"checkbox",checked:v.builtinTools.includes(e),disabled:C,onChange:t=>void er(e,t.target.checked),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:"bash"===e&&v.powerShellEnabled?"powershell":e})]},e))}),I&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:I})]}),v?.isWindows&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.shellTool")}),(0,r.jsx)("p",{className:"settings-general-description",children:c("settings.shellToolDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:c("settings.usePowerShell")}),(0,r.jsx)(aH,{checked:v.powerShellEnabled,loading:k,label:c("settings.usePowerShell"),onChange:e=>void en(e)})]}),w&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:w})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.pushPermission")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:c("settings.pushPermissionDescription")}),(0,r.jsx)("button",{type:"button",className:"config-button config-button-small config-button-secondary",disabled:_,onClick:()=>void ei(),children:_?c("settings.pushRegisterLoading"):c("settings.pushRegister")})]}),K&&(0,r.jsx)("p",{role:"status",className:"settings-general-error",style:"ok"===K.kind?{color:"var(--accent)"}:void 0,children:K.message})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("common.language")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":c("common.language"),className:"settings-language-options",children:d.map(e=>{let t=l===e.id;return(0,r.jsxs)("button",{type:"button",role:"radio","aria-checked":t,onClick:()=>o(e.id),className:"settings-language-option",children:[(0,r.jsx)("span",{className:"settings-language-radio",children:t&&(0,r.jsx)("span",{className:"settings-language-radio-dot"})}),(0,r.jsx)("span",{className:"settings-language-label",children:e.label}),(0,r.jsx)("span",{className:"settings-language-code",children:e.id})]},e.id)})})]}),Z&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsxs)(aB,{variant:"secondary",disabled:J,onClick:()=>void Q(),children:[(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M10 17l5-5-5-5M15 12H3M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"})}),J?c("auth.loggingOut"):c("auth.logOut")]}),Y&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:Y})]})]})}let hb={home:"home",section:"home",detail:"section"},hv={home:0,section:1,detail:2},hy="cubic-bezier(0.2, 0.8, 0.2, 1)";function hk(e){let t,{cwd:n,sessionId:s,initialSection:a,openAtHome:l=!1,onClose:o,onSessionReloaded:d,quoteSelectionEnabled:c,onQuoteSelectionChange:u,projectTrust:p,onOpenTrustDialog:h,onProjectTrustChanged:m}=e,{t:g}=(0,eX.s)(),[f,x]=(0,i.useState)(a),[b,v]=(0,i.useState)(()=>new Set([f])),y=[{id:"general",label:g("settings.general")},{id:"models",label:g("common.models")},{id:"skills",label:g("common.skills")},{id:"agents",label:g("common.agents")},{id:"plugins",label:g("common.plugins")},{id:"mcp",label:g("settings.mcp")},{id:"channels",label:g("settings.channels")},{id:"automations",label:g("settings.automations")},{id:"shares",label:g("settings.shares")}].map(e=>({...e,requiresProject:sF(e.id)})),k=sF(f),j=(0,eQ.a)(),w=function(e,t){let[n,r]=(0,i.useState)(t?"home":"section");e||"section"===n||r("section");let s=(0,i.useRef)(n);s.current=n;let a=(0,i.useRef)(0);(0,i.useEffect)(()=>{if(!e)return;let t=()=>{0!==a.current&&(a.current-=1,r(e=>hb[e]))};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[e]);let l=(0,i.useCallback)(t=>{e&&(window.history.pushState(window.history.state,""),a.current+=1,r(t))},[e]);return{level:n,levelRef:s,enter:l,goUp:(0,i.useCallback)(()=>{a.current>0?window.history.back():r(e=>hb[e])},[]),dropHistory:(0,i.useCallback)(()=>{let e=a.current;a.current=0,e>0&&window.history.go(-e)},[])}}(j,l),{dropHistory:S,enter:C,goUp:N,levelRef:I}=w,E=(0,i.useRef)(null),$=(0,i.useRef)(!1),T=(0,i.useRef)(null),M=(0,i.useRef)(w.level);(0,i.useLayoutEffect)(()=>{let e=M.current;M.current=w.level,j&&e!==w.level&&function(e,t,n,r){if(!e||"function"!=typeof e.animate||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;let i=hv[r]>hv[n];e.animate(i?[{transform:"translateX(100%)",boxShadow:"-12px 0 24px rgba(0, 0, 0, 0.12)"},{transform:"translateX(0)",boxShadow:"-12px 0 24px rgba(0, 0, 0, 0)"}]:[{transform:"translateX(-30%)",opacity:.4},{transform:"translateX(0)",opacity:1}],{duration:280,easing:hy}),t?.querySelectorAll(".settings-phone-back, .settings-dialog-title").forEach(e=>{e.animate([{opacity:0,transform:`translateX(${i?16:-16}px)`},{opacity:1,transform:"translateX(0)"}],{duration:220,easing:hy})})}(T.current,E.current,e,w.level)},[j,w.level]);let R=(0,i.useCallback)(()=>{S(),o()},[o,S]),A=y.find(e=>e.id===f)?.label??g("settings.title"),[L,P]=(0,i.useState)(null),z=(0,i.useMemo)(()=>({detailOpen:"detail"===w.level,openDetail:()=>{"section"===I.current&&(P(null),C("detail"))},closeDetail:()=>{"detail"===I.current&&N()},reportDetailTitle:P}),[C,N,w.level,I]);(0,i.useEffect)(()=>s_(a),[a]),(0,i.useEffect)(()=>{var e;let t;return e=document,t=e=>{"Escape"!==e.key||e.defaultPrevented||eI(e)||(e.preventDefault(),R())},e.addEventListener("keydown",t,!1),()=>e.removeEventListener("keydown",t,!1)},[R]);let O=(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,O.current,{restoreTextEntry:!window.matchMedia?.("(pointer: coarse)").matches}),[]),(0,i.useEffect)(()=>{!n&&k&&(x("general"),v(e=>new Set(e).add("general")),s_("general"))},[n,k]);let W=e=>{v(t=>new Set(t).add(e)),x(e),s_(e)},F=(e,t)=>b.has(e)?(0,r.jsx)("div",{hidden:f!==e||"home"===w.level,"data-phone-level":j?w.level:void 0,className:"settings-section-host",children:t},e):null;return(0,r.jsx)("div",{ref:O,role:"dialog","aria-modal":"true","aria-label":g("settings.title"),tabIndex:-1,onPointerDown:e=>{$.current=e.target===e.currentTarget},onPointerCancel:()=>{$.current=!1},onClick:e=>{let t=$.current;$.current=!1,t&&e.target===e.currentTarget&&R()},className:"settings-dialog-backdrop",children:(0,r.jsxs)("div",{className:"settings-dialog-surface",children:[(0,r.jsxs)("div",{ref:E,className:"settings-dialog-header",children:[j&&"home"!==w.level&&(t="detail"===w.level?A:g("settings.title"),(0,r.jsxs)("button",{type:"button",className:"settings-phone-back",onClick:N,"aria-label":g("settings.backTo",{name:t}),children:[(0,r.jsx)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m15 18-6-6 6-6"})}),(0,r.jsx)("span",{children:t})]})),(0,r.jsx)("strong",{className:"settings-dialog-title",children:j&&"home"!==w.level?"section"===w.level?A:L:g("settings.title")}),(0,r.jsx)("nav",{"aria-label":g("settings.title"),className:"settings-section-tabs",children:y.map(e=>{let t=f===e.id,i=e.requiresProject&&!n;return(0,r.jsxs)("button",{type:"button",className:"settings-section-tab",disabled:i,title:i?g("settings.projectRequired"):e.label,"aria-current":t?"page":void 0,onClick:()=>W(e.id),children:[(0,r.jsx)(hf,{section:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id)})}),(0,r.jsx)("button",{type:"button",onClick:R,title:g("i18n.close"),"aria-label":g("i18n.close"),className:"config-close-button settings-dialog-close",children:"\xd7"})]}),(0,r.jsxs)("main",{ref:T,className:"settings-dialog-main",children:[j&&"home"===w.level&&(0,r.jsx)("nav",{"aria-label":g("settings.title"),className:"settings-phone-home",children:y.map(e=>{let t=e.requiresProject&&!n;return(0,r.jsxs)("button",{type:"button",className:"settings-phone-home-item",disabled:t,"aria-describedby":t?`settings-phone-home-${e.id}-note`:void 0,onClick:()=>{W(e.id),C("section")},children:[(0,r.jsx)(hf,{section:e.id,size:20}),(0,r.jsxs)("span",{className:"settings-phone-home-label",children:[(0,r.jsx)("span",{children:e.label}),t&&(0,r.jsx)("span",{id:`settings-phone-home-${e.id}-note`,className:"settings-phone-home-note",children:g("settings.projectRequired")})]}),(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"settings-phone-home-chevron",children:(0,r.jsx)("path",{d:"m9 18 6-6-6-6"})})]},e.id)})}),(0,r.jsxs)(ad.Provider,{value:z,children:[F("general",(0,r.jsx)(hx,{sessionId:s,onSessionReloaded:d,quoteSelectionEnabled:c,onQuoteSelectionChange:u})),F("models",(0,r.jsx)(lI,{embedded:!0,cwd:n,onClose:R})),n&&F("skills",(0,r.jsx)(lF,{embedded:!0,cwd:n,trust:p,onClose:R},n)),n&&F("agents",(0,r.jsx)(lX,{embedded:!0,cwd:n,sessionId:s,trust:p,onClose:R,onReloaded:d},n)),n&&F("plugins",(0,r.jsx)(ot,{embedded:!0,cwd:n,sessionId:s,trust:p,onClose:R,onReloaded:d},n)),F("mcp",(0,r.jsx)(pU,{embedded:!0,cwd:n,trust:p,onTrustProject:h,onProjectTrustChanged:m,onClose:R},n??"")),F("channels",(0,r.jsx)(ht,{})),F("automations",(0,r.jsx)(hd,{})),F("shares",(0,r.jsx)(hu,{}))]})]})]})})}let hj="project-trust-mcp-status";function hw(e){let{cwd:t,busy:n,error:s,onCancel:a,onConfirm:l,onStatus:o}=e,[d,c]=(0,i.useState)({state:"loading"}),u=(0,i.useRef)(o);return(0,i.useEffect)(()=>{u.current=o},[o]),(0,i.useEffect)(()=>{let e=!0,n=!1;c({state:"loading"});let r=new AbortController,i=window.setTimeout(()=>{n=!0,r.abort()},1e4);return fetch(`/api/project-trust?cwd=${encodeURIComponent(t)}`,{signal:r.signal,cache:"no-store"}).then(async t=>{let n=await t.json();if(!e)return;let r=function(e,t,n){let r=Array.isArray(n.mcpServers)?{mcpServers:n.mcpServers,...n.mcpFile?{mcpFile:n.mcpFile}:{},...void 0!==n.mcpError?{mcpError:n.mcpError}:{}}:void 0;if(e&&!n.error&&r&&"boolean"==typeof n.requiresTrust){let e;return{state:"loaded",listing:r,status:(e={requiresTrust:n.requiresTrust,trusted:n.trusted,decision:n.decision,inherited:n.inherited},void 0!==n.decisionPath&&(e.decisionPath=n.decisionPath),void 0!==n.decisionError&&(e.decisionError=n.decisionError),e)}}return"trust-unreadable"===n.reason&&r?{state:"loaded",listing:r,statusError:n.error??`HTTP ${t}`}:{state:"failed",error:n.error??`HTTP ${t}`,reason:n.reason}}(t.ok,t.status,n);c(r),"loaded"===r.state&&r.status&&u.current?.(r.status)}).catch(t=>{e&&c(n?{state:"failed",timedOut:!0}:{state:"failed",error:t instanceof Error?t.message:String(t)})}).finally(()=>window.clearTimeout(i)),()=>{e=!1,window.clearTimeout(i),r.abort()}},[t]),(0,r.jsx)(hS,{cwd:t,busy:n,error:s,listing:d,onCancel:a,onConfirm:l})}function hS(e){let{cwd:t,busy:n,error:s,listing:a,onCancel:l,onConfirm:o}=e,{t:d}=(0,eX.s)(),c="loading"===a.state,u="loaded"===a.state?function(e){if(e){if(!e.requiresTrust)return"mcp.reason.trust-not-required";if(e.trusted)return"trust.alreadyTrusted"}}(a.status):void 0,p=(0,i.useRef)(null),h=(0,i.useRef)(n),m=(0,i.useRef)(l);return(0,i.useEffect)(()=>{h.current=n,m.current=l},[n,l]),(0,i.useEffect)(()=>{var e,t,n;let r,i,s;return e=document,t=p.current,n=()=>{h.current||m.current()},r=e.activeElement,t?.focus({preventScroll:!0}),i=e=>{"Escape"!==e.key||(e.stopPropagation(),eI(e)||(e.preventDefault(),n()))},e.addEventListener("keydown",i,!0),s=()=>e.removeEventListener("keydown",i,!0),()=>{s(),r&&r.isConnected&&"function"==typeof r.focus&&r.focus({preventScroll:!0})}},[]),(0,r.jsx)("div",{role:"presentation",className:"project-trust-backdrop",onClick:e=>{n||e.target!==e.currentTarget||l()},children:(0,r.jsxs)("div",{ref:p,role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title","aria-describedby":"project-trust-description",tabIndex:-1,className:"project-trust-dialog",children:[(0,r.jsxs)("div",{className:"project-trust-body",children:[(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"project-trust-icon",children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,r.jsxs)("div",{className:"project-trust-content",children:[(0,r.jsx)("div",{id:"project-trust-title",className:"project-trust-title",children:d("trust.dialogTitle")}),(0,r.jsx)("div",{id:"project-trust-description",className:"project-trust-text",children:d("trust.dialogBody")}),(0,r.jsx)("code",{className:"project-trust-path",children:os(t)}),u&&(0,r.jsx)("p",{id:"project-trust-notice",role:"status",className:"project-trust-notice",children:d(u)}),"loaded"===a.state&&void 0!==a.statusError&&(0,r.jsxs)("div",{className:"project-trust-mcp-failed",children:[(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:d("mcp.reason.trust-unreadable")}),(0,r.jsx)("code",{className:"project-trust-mcp-detail",children:os(a.statusError)})]}),(0,r.jsx)(hN,{listing:a})]})]}),s&&(0,r.jsx)(hC,{error:s}),(0,r.jsxs)("div",{className:"project-trust-footer",children:[(0,r.jsx)("button",{type:"button",className:"project-trust-button",onClick:l,disabled:n,children:d(u?"trust.close":"trust.cancel")}),!u&&(0,r.jsx)("button",{type:"button",className:"project-trust-button is-primary",onClick:o,disabled:n||c,"aria-busy":n||void 0,"aria-describedby":c?hj:void 0,children:d(n?"trust.trusting":"trust.trustProject")})]})]})})}function hC(e){let{error:t}=e,{t:n}=(0,eX.s)(),i=void 0!==t.reason&&"internal"!==t.reason;return(0,r.jsxs)("div",{role:"alert",className:"project-trust-error",children:[n(i?`mcp.reason.${t.reason}`:"trust.trustFailed"),!i&&(0,r.jsx)("code",{className:"project-trust-error-detail",children:os(t.error)})]})}function hN(e){let{listing:t}=e,{t:n}=(0,eX.s)();if("loading"===t.state)return(0,r.jsx)("p",{id:hj,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:os(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)(hI,{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)(hT,{server:e},e.name))})]}):null}function hI(e){let{file:t}=e,{t:n}=(0,eX.s)();return(0,r.jsx)(r.Fragment,{children:t.problems.map(e=>{let i=og(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 hE(e){let{fields:t}=e,{t:n}=(0,eX.s)();return(0,r.jsx)(r.Fragment,{children:t.map(e=>{let t=ou(e);return(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function h$(e){let{server:t}=e,{t:n}=(0,eX.s)();return(0,r.jsx)(r.Fragment,{children:om(t.variableReferences).map(e=>{let{variable:t,field:i}=e,s=ou(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 hT(e){let t,{server:n}=e,{t:i}=(0,eX.s)(),s=od(n),a=void 0===n.invalidError;return(0,r.jsxs)("li",{className:"project-trust-mcp-server",children:[(0,r.jsxs)("div",{className:"project-trust-mcp-server-head",children:[(0,r.jsx)("span",{className:"project-trust-mcp-server-name",children:os(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:os(n.cwd)})}),oc(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:os(n.invalidError)})]}),n.webPasswordField&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.webPassword")," ",(0,r.jsx)(hE,{fields:[n.webPasswordField]})]}),!n.enabled&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:i("mcp.server.disabled")}),a&&n.commandFields.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.commandFields")," ",(0,r.jsx)(hE,{fields:n.commandFields})]}),a&&n.variableReferences.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i(op(n))," ",(0,r.jsx)(h$,{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=oh(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 hM(e){return"message"===e.type&&"message"in e&&"system"!==e.message.role}function hR(e){let t=e,n=t.branchPreview,r=hM(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&hM(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function hA(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 hL(e){let{node:t,activePathIds:n,depth:i,isLast:s,parentLines:a,onSelect:l}=e,{node:o,skipped:d,branchPreview:c,labelEntry:u}=hR(t),p=n.has(o.entry.id),h=n.has(t.entry.id)||n.has(o.entry.id),m=c?.text??function(e){if("message"===e.type&&hM(e)){let t=e.message,n=t.content,r="";if("string"==typeof n?r=n:Array.isArray(n)&&(r=n.filter(e=>"text"===e.type).map(e=>e.text).join(" ")),r.length>40&&(r=r.slice(0,40)+"…"),r)return r;if("assistant"===t.role)return"[assistant]"}return e.type}(u),g=c?c.role??null:hM(u)?u.message.role:null;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:l?"pointer":"default"},onClick:l?()=>l(o.entry.id):void 0,children:[a.map((e,t)=>(0,r.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,r.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:s?"50%":0,width:1,background:"var(--border)"}}),(0,r.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,r.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:p?"var(--accent)":h?"var(--text-muted)":"var(--border)",border:p?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),g&&(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===g?"var(--accent)":"var(--text-dim)",background:"user"===g?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===g?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===g?"U":"A"}),d>0&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",d]}),(0,r.jsx)("span",{style:{fontSize:11,color:p?"var(--text)":h?"var(--text-muted)":"var(--text-dim)",fontWeight:p?500:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:m})]}),o.children.map((e,t)=>(0,r.jsx)(hL,{node:e,activePathIds:n,depth:i+1,isLast:t===o.children.length-1,parentLines:[...a,!s],onSelect:l},e.entry.id))]})}function hP(e){let{tree:t,activeLeafId:n,onLeafChange:s,inline:a,containerRef:l,open:o,onToggle:d,hasSession:c,compact:u,hideInlineButton:p,locked:h=!1}=e,{t:m}=(0,eX.s)(),[g,f]=(0,i.useState)(!1),x=void 0!==o?o:g,b=(0,i.useRef)(null),[v,y]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!x||!a)return;let e=l?.current??b.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();y({top:t.bottom,left:t.left,width:t.width})};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[x,a,l]);let k=(0,i.useMemo)(()=>(function(e,t){if(!t)return new Set;let n=e.map(e=>({node:e,path:[e.entry.id]}));for(;n.length>0;){let{node:e,path:r}=n.pop();if(e.entry.id===t||e.compressedEntryIds?.includes(t))return new Set(r);for(let t of e.children)n.push({node:t,path:[...r,t.entry.id]})}return new Set})(t,n),[t,n]),j=(0,i.useCallback)(e=>{s(e)},[s]),w=h?void 0:j,S=h&&(0,r.jsx)("div",{style:{padding:"2px 0 4px",fontSize:11,color:"var(--text-dim)",fontStyle:"italic"},children:m("i18n.branchesLockedWhileRunning")}),C=c?hA(t)?null:m("i18n.noBranches"):m("i18n.noActiveSession"),N=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=hR(e[0]).node;return t.children.length>1?t.children:[]}(t),I=!C&&N.length>0,E=(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:I?"var(--accent)":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),$=(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{marginLeft:2,transform:x?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})});return a?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"stretch"},children:[(0,r.jsxs)("button",{ref:b,onClick:()=>d?d():f(e=>!e),style:{display:p?"none":"flex",alignItems:"center",gap:6,height:"100%",padding:"0 12px",background:x?"var(--bg-selected)":"none",border:"none",borderTop:x?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:"pointer",color:x?"var(--text)":"var(--text-muted)",fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color=x?"var(--text)":"var(--text-muted)"},title:m("i18n.branches"),"aria-label":m("i18n.branches"),"aria-pressed":x,children:[E,!u&&(0,r.jsx)("span",{children:m("i18n.branches")})]}),x&&v&&(0,r.jsx)("div",{style:{position:"fixed",top:v.top,left:v.left,width:v.width,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",zIndex:500},children:I?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(hL,{node:e,activePathIds:k,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:w},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C})})]}):(0,r.jsxs)("div",{style:{borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>f(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"5px 12px",background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",fontSize:11,textAlign:"left"},children:[E,(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:m("i18n.branches")}),$]}),x&&(0,r.jsx)("div",{style:{position:"absolute",top:"100%",left:0,right:0,background:"var(--bg)",borderBottom:"1px solid var(--border)",boxShadow:"0 4px 12px rgba(0,0,0,0.1)",zIndex:100},children:I?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(hL,{node:e,activePathIds:k,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:w},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C??m("i18n.noBranches")})})]})}function hz(e){let{loading:t,prompt:n,translate:i}=e;return(0,r.jsxs)("section",{className:"system-prompt-panel","aria-label":i("system.prompt"),children:[(0,r.jsx)("div",{className:"system-prompt-scroll",children:n?(0,r.jsx)("div",{className:"system-prompt-text",children:n}):(0,r.jsx)("div",{className:"system-prompt-empty",children:i(""===n?"system.empty":t?"system.loading":"system.load")})}),(0,r.jsx)("style",{children:`
8
+ .system-prompt-panel {
9
+ display: flex;
10
+ height: min(600px, 75dvh);
11
+ min-height: 220px;
12
+ flex-direction: column;
13
+ background: var(--bg-panel);
14
+ border-bottom: 1px solid var(--border);
15
+ }
16
+ .system-prompt-scroll {
17
+ min-height: 0;
18
+ flex: 1;
19
+ overflow: auto;
20
+ padding: 12px 16px;
21
+ }
22
+ .system-prompt-text {
23
+ color: var(--text-muted);
24
+ font-family: var(--font-mono);
25
+ font-size: 12px;
26
+ line-height: 1.6;
27
+ overflow-wrap: anywhere;
28
+ white-space: pre-wrap;
29
+ }
30
+ .system-prompt-empty {
31
+ padding: 10px 0;
32
+ color: var(--text-muted);
33
+ font-size: 12px;
34
+ font-style: italic;
35
+ }
36
+ `})]})}function hO(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e)}catch{return String(e)}}function hW(e){let{children:t}=e;return(0,r.jsx)("div",{className:"tool-definitions-empty",children:t})}function hF(e){let{loading:t,tools:n,translate:s}=e,a=(0,i.useMemo)(()=>n?.filter(e=>e.active&&!e.declarationHidden)??null,[n]),[l,o]=(0,i.useState)(null);(0,i.useEffect)(()=>{o(e=>a?.some(t=>t.name===e)?e:a?.[0]?.name??null)},[a]);let d=a?.find(e=>e.name===l)??a?.[0]??null,c=d?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 hO(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(hO).join(", "):void 0,defaultValue:void 0===i.default?void 0:hO(i.default)}})}(d.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:a&&a.length>0?a.map(e=>{let t=e.name===d?.name;return(0,r.jsx)("button",{type:"button",className:`tool-definitions-item${t?" selected":""}`,"aria-pressed":t,onClick:()=>o(e.name),children:(0,r.jsx)("code",{children:e.name})},e.name)}):a?(0,r.jsx)(hW,{children:s("tools.noTools")}):(0,r.jsx)(hW,{children:t?s("tools.loading"):s("tools.load")})})}),(0,r.jsx)("section",{className:"tool-definition-detail","aria-label":s("tools.details"),children:d?(0,r.jsxs)("div",{className:"tool-definition-scroll",children:[d.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:d.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:c.length})})]}),c.length>0?(0,r.jsx)("div",{className:"tool-definition-fields",children:c.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")})]}),d.promptGuidelines&&d.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:d.promptGuidelines.map((e,t)=>(0,r.jsx)("li",{children:e},`${d.name}:${t}`))})]})]}):(0,r.jsx)(hW,{children:a?s("tools.noTools"):t?s("tools.loading"):s("tools.load")})}),(0,r.jsx)("style",{children:`
37
+ .tool-definitions-panel {
38
+ display: grid;
39
+ grid-template-columns: clamp(112px, 26%, 220px) minmax(0, 1fr);
40
+ height: min(600px, 75dvh);
41
+ min-height: 240px;
42
+ overflow: hidden;
43
+ background: var(--bg-panel);
44
+ border-bottom: 1px solid var(--border);
45
+ }
46
+ .tool-definitions-sidebar,
47
+ .tool-definition-detail {
48
+ display: flex;
49
+ min-width: 0;
50
+ min-height: 0;
51
+ flex-direction: column;
52
+ }
53
+ .tool-definitions-sidebar {
54
+ border-right: 1px solid var(--border);
55
+ background: color-mix(in srgb, var(--bg-panel) 94%, var(--bg));
56
+ }
57
+ .tool-definitions-list,
58
+ .tool-definition-scroll {
59
+ min-height: 0;
60
+ flex: 1;
61
+ overflow: auto;
62
+ }
63
+ .tool-definitions-item {
64
+ display: flex;
65
+ width: 100%;
66
+ min-height: 38px;
67
+ align-items: center;
68
+ padding: 8px 12px;
69
+ border: none;
70
+ border-bottom: 1px solid var(--border);
71
+ background: transparent;
72
+ color: var(--text-muted);
73
+ cursor: pointer;
74
+ text-align: left;
75
+ }
76
+ .tool-definitions-item:hover {
77
+ background: var(--bg-hover);
78
+ color: var(--text);
79
+ }
80
+ .tool-definitions-item.selected {
81
+ background: var(--bg-selected);
82
+ box-shadow: inset 2px 0 0 var(--accent);
83
+ color: var(--text);
84
+ }
85
+ .tool-definitions-item code {
86
+ max-width: 100%;
87
+ color: inherit;
88
+ font-size: 11px;
89
+ font-weight: 600;
90
+ overflow-wrap: anywhere;
91
+ }
92
+ .tool-definition-scroll {
93
+ padding: 14px 16px 20px;
94
+ }
95
+ .tool-definition-section + .tool-definition-section {
96
+ margin-top: 18px;
97
+ }
98
+ .tool-definition-section-label {
99
+ display: flex;
100
+ align-items: center;
101
+ justify-content: space-between;
102
+ gap: 8px;
103
+ margin-bottom: 7px;
104
+ color: var(--text-dim);
105
+ font-size: 11px;
106
+ font-weight: 600;
107
+ }
108
+ .tool-definition-section-label > span:last-child {
109
+ font-weight: 400;
110
+ white-space: nowrap;
111
+ }
112
+ .tool-definition-description {
113
+ color: var(--text-muted);
114
+ font-size: 12px;
115
+ line-height: 1.55;
116
+ overflow-wrap: anywhere;
117
+ white-space: pre-wrap;
118
+ }
119
+ .tool-definition-fields {
120
+ border-top: 1px solid var(--border);
121
+ }
122
+ .tool-definition-field {
123
+ display: grid;
124
+ grid-template-columns: minmax(88px, 0.75fr) minmax(0, 1.5fr);
125
+ gap: 12px;
126
+ padding: 9px 0;
127
+ border-bottom: 1px solid var(--border);
128
+ font-size: 11px;
129
+ line-height: 1.45;
130
+ }
131
+ .tool-definition-field-name {
132
+ display: flex;
133
+ min-width: 0;
134
+ flex-direction: column;
135
+ gap: 3px;
136
+ color: var(--text);
137
+ }
138
+ .tool-definition-field-name code {
139
+ overflow-wrap: anywhere;
140
+ }
141
+ .tool-definition-field-name span {
142
+ color: var(--text-dim);
143
+ font-size: 10px;
144
+ }
145
+ .tool-definition-field-name span.required {
146
+ color: var(--accent);
147
+ }
148
+ .tool-definition-field-value {
149
+ min-width: 0;
150
+ color: var(--text-muted);
151
+ overflow-wrap: anywhere;
152
+ }
153
+ .tool-definition-type {
154
+ display: block;
155
+ margin-bottom: 3px;
156
+ color: var(--text);
157
+ }
158
+ .tool-definition-meta {
159
+ margin-top: 4px;
160
+ color: var(--text-dim);
161
+ }
162
+ .tool-definition-meta code {
163
+ color: var(--text-muted);
164
+ }
165
+ .tool-definition-no-parameters {
166
+ padding: 2px 0 10px;
167
+ color: var(--text-dim);
168
+ font-size: 11px;
169
+ }
170
+ .tool-definition-guidelines {
171
+ margin: 0;
172
+ padding-left: 18px;
173
+ color: var(--text-muted);
174
+ font-size: 11px;
175
+ line-height: 1.5;
176
+ }
177
+ .tool-definitions-empty {
178
+ padding: 14px 12px;
179
+ color: var(--text-muted);
180
+ font-size: 12px;
181
+ font-style: italic;
182
+ overflow-wrap: anywhere;
183
+ }
184
+ @media (max-width: 640px) {
185
+ .tool-definitions-panel {
186
+ grid-template-columns: 112px minmax(0, 1fr);
187
+ }
188
+ .tool-definitions-item {
189
+ padding: 8px 10px;
190
+ }
191
+ .tool-definition-scroll {
192
+ padding: 12px;
193
+ }
194
+ .tool-definition-field {
195
+ grid-template-columns: minmax(74px, 0.7fr) minmax(0, 1.3fr);
196
+ gap: 9px;
197
+ }
198
+ }
199
+ `})]})}var hD=n(13194);function hB(e){let{usage:t,style:n}=e,{locale:i,t:s}=(0,eX.s)(),a=(0,i_.tb)(t.cost);return(0,r.jsxs)("span",{title:function(e,t,n){let{tokens:r}=e;return[`${t("session.totalActive")}: ${(0,i_.ik)(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"})]}),(0,i_.ik)(t.totalActiveMs)]}),t.tokens.total>0&&(0,r.jsx)("span",{children:s("agentSwitcher.tokens",{count:(0,i_.eX)(t.tokens.total)})}),a&&(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:a})]})}function hH(e){return!!(e&&(e.tokens.total>0||e.totalActiveMs>0))}function h_(e){return e.name||e.firstMessage||e.id.slice(0,12)}function hU(e){let t=e.relation?.kind==="subagent"?e.relation:null;return t?.description||h_(e)}function hK(e){let{kind:t,size:n}=e;return(0,r.jsx)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:"main"===t?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"8",r:"4"}),(0,r.jsx)("path",{d:"M4 21a8 8 0 0 1 16 0"})]}):"side"===t?(0,r.jsx)("path",{d:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"}):(0,r.jsxs)(r.Fragment,{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"})]})})}function hq(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 a=Math.round(s/60);return 24>Math.abs(a)?i.format(a,"hour"):i.format(Math.round(a/24),"day")}function hZ(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 hV(e){let{session:t,main:n,sideTitle:s,selected:a,running:l,usage:o,onSelect:d,tabShown:c,onToggleTab:u,onNewSideChat:p,newSideChatPending:h,onDelete:m,confirming:g,onDeleteConfirm:f,onDeleteCancel:x}=e,{locale:b,t:v}=(0,eX.s)(),y=t.relation?.kind==="subagent"?t.relation:null,k=t.relation?.kind==="side",j=l?"running":y?.status??"completed",w=n?v("agentSwitcher.main"):k?s??v("agentSwitcher.sideChat"):hU(t),S=k?v("agentSwitcher.sideChat"):y?.profile??v("agentSwitcher.subagent"),C=o?.model?.modelId,N=o?.thinkingLevel&&"off"!==o.thinkingLevel?o.thinkingLevel:void 0,I=n?h_(t):k?hq(t.modified,b):S,E=n?I:[S,o?.model?`${o.model.provider}/${o.model.modelId}`:void 0,N,hq(t.modified,b)].filter(Boolean).join(" \xb7 "),$=(0,i.useRef)(null),[T,M]=(0,i.useState)();return g&&f&&x?(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:5,height:T,minHeight:56,padding:"7px 12px",borderBottom:"1px solid var(--border)",background:"rgba(239, 68, 68, 0.06)",boxShadow:"inset 0 0 0 1px rgba(239, 68, 68, 0.35)"},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),x())},children:(0,r.jsx)(tN,{label:v("sidebar.deleteSession",{title:w}),deleteLabel:v("sidebar.delete"),cancelLabel:v("sidebar.cancel"),onConfirm:f,onCancel:x})}):(0,r.jsxs)("div",{ref:$,style:{display:"flex",borderBottom:"1px solid var(--border)",borderLeft:a?"2px solid var(--accent)":"2px solid transparent",background:a?"var(--bg-selected)":"transparent"},children:[(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":a,onClick:d,className:a?"bg-transparent":"bg-transparent hover:bg-bg-hover",style:{flex:1,minWidth:0,minHeight:56,display:"grid",gridTemplateColumns:"28px minmax(0, 1fr) auto",alignItems:"center",gap:9,padding:"7px 12px",border:"none",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{width:28,height:28,display:"grid",placeItems:"center",color:n?"var(--text-muted)":"var(--accent)"},children:(0,r.jsx)(hK,{kind:n?"main":k?"side":"subagent",size:17})}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12,fontWeight:a?600:500},title:w,children:w}),(0,r.jsxs)("span",{style:{display:"flex",alignItems:"baseline",gap:4,marginTop:2,minWidth:0,whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11},title:E,children:[(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flexShrink:C&&!n?0:1,maxWidth:C&&!n?"40%":void 0},children:I}),!n&&C&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{"aria-hidden":"true",children:"\xb7"}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:C})]}),!n&&N&&(0,r.jsxs)("span",{style:{flexShrink:0},children:["\xb7 ",N]})]}),hH(o)&&(0,r.jsx)(hB,{usage:o,style:{marginTop:3}})]}),(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",gap:6,color:(n||k)&&!l?"var(--text-dim)":"running"===j||"starting"===j?"var(--accent)":"completed"===j?"#16a34a":"failed"===j?"#dc2626":"aborted"===j?"#d97706":"var(--text-dim)",fontSize:11,whiteSpace:"nowrap"},children:(n||k)&&!l?a?v("agentSwitcher.current"):null:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(hZ,{status:j}),(0,r.jsx)("span",{children:v(`agentSwitcher.status.${j}`)})]})})]}),p&&(0,r.jsx)(hJ,{title:v("sideChat.new"),disabled:h,onClick:p,children:(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"}),(0,r.jsx)("path",{d:"M13 8.5v7M9.5 12h7"})]})}),u&&(0,r.jsx)(hJ,{title:v(a?"agentSwitcher.openInMainChat":c?k?"sideChat.closeTab":"subagent.closeTab":k?"sideChat.openTab":"subagent.openTab"),pressed:c,disabled:a,onClick:u,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"}),c&&(0,r.jsx)("path",{d:"M15 4h4a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-4z",fill:"currentColor"})]})}),m&&(0,r.jsx)(hJ,{title:v("sidebar.delete"),danger:!0,onClick:()=>{M($.current?.offsetHeight),m()},children:(0,r.jsx)(tv.uc,{size:14})})]})}function hJ(e){let{title:t,pressed:n,danger:i,disabled:s,onClick:a,children:l}=e,o=s?"cursor-not-allowed text-text-dim opacity-40":i?"cursor-pointer text-text-muted hover:bg-[rgba(239,68,68,0.08)] hover:text-[#ef4444] focus-visible:bg-[rgba(239,68,68,0.08)] focus-visible:text-[#ef4444]":n?"cursor-pointer text-accent hover:bg-bg-hover":"cursor-pointer text-text-muted hover:bg-bg-hover hover:text-text";return(0,r.jsx)("button",{type:"button",onClick:a,title:t,"aria-label":t,"aria-pressed":n,disabled:s,className:`bg-transparent ${o}`,style:{width:36,display:"grid",placeItems:"center",border:"none",borderLeft:"1px solid var(--border)",flexShrink:0},children:l})}function hG(e){let{rootSession:t,subagents:n,selectedSessionId:s,runningSessionIds:a,onSelectSession:o,openSubagentTabIds:d,onToggleSubagentTab:c,onNewSideChat:p,onDeleteSideChat:h}=e,{t:m}=(0,eX.s)(),[g,f]=(0,i.useState)(""),[x,b]=(0,i.useState)(!1),[v,y]=(0,i.useState)(null),[k,j]=(0,i.useState)(null),[w,S]=(0,i.useState)(null),C=async()=>{b(!0),y(null);try{y(await p())}catch(e){y(e instanceof Error?e.message:String(e))}finally{b(!1)}},N=async e=>{let t;j(null),S(null);try{t=await h(e)}catch(e){t=e instanceof Error?e.message:String(e)}t&&S(m("sidebar.deleteFailed",{error:t}))},I=(0,i.useMemo)(()=>[...n].sort((e,t)=>{let n=a.has(e.id);return n!==a.has(t.id)?n?-1:1:t.modified.localeCompare(e.modified)}),[a,n]),E=g.trim().toLowerCase(),$=E?I.filter(e=>{let t=e.relation?.kind==="subagent"?e.relation:null,n=e.relation?.kind==="side"?m("agentSwitcher.sideChat"):null;return[t?.description,t?.profile,n,e.name,e.firstMessage].some(e=>e?.toLowerCase().includes(E))}):I,T=u(n,a),M=(0,i.useMemo)(()=>[t.id,...n.map(e=>e.id)],[t.id,n]),R=M.filter(e=>a.has(e)).join(","),A=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,a=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(a(),!t)return()=>n.abort();let l=setInterval(()=>{"visible"===document.visibilityState&&a()},3e3);return()=>{clearInterval(l),n.abort()}},[s,t]),n}(M,R),L=(0,i.useMemo)(()=>{let e=M.map(e=>A[e]).filter(hH);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},[M,A]);return(0,r.jsx)("div",{role:"listbox","aria-label":m("agentSwitcher.title"),style:{background:"var(--bg-panel)",borderRight:"1px solid var(--border)",borderBottom:"1px solid var(--border)",borderRadius:"0 0 6px 0",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:m("agentSwitcher.title")}),n.length>0&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:1===n.length?m("agentSwitcher.countOne",{count:n.length}):m("agentSwitcher.count",{count:n.length})}),(0,r.jsxs)("span",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:10,minWidth:0},children:[L&&(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:m("agentSwitcher.totalUsageHint"),children:m("agentSwitcher.totalUsage")}),(0,r.jsx)(hB,{usage:L})]}),T>0&&(0,r.jsx)("span",{style:{color:"var(--accent)",fontSize:11,whiteSpace:"nowrap"},children:m("agentSwitcher.runningCount",{count:T})})]})]}),n.length>8&&(0,r.jsx)("div",{style:{padding:8,borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{type:"search",value:g,onChange:e=>f(e.target.value),placeholder:m("agentSwitcher.search"),"aria-label":m("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)(hV,{session:t,main:!0,selected:t.id===s,running:a.has(t.id),usage:A[t.id],onSelect:()=>o(t),onNewSideChat:C,newSideChatPending:x}),(v||w)&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 12px",borderBottom:"1px solid var(--border)",color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:v??w}),$.map(e=>(0,r.jsx)(hV,{session:e,sideTitle:e.relation?.kind==="side"?l(e,m("agentSwitcher.sideChat"),n):void 0,selected:e.id===s,running:a.has(e.id),usage:A[e.id],onSelect:()=>o(e),tabShown:d.has(e.id),onToggleTab:()=>{let t=e.relation?.kind==="subagent"?e.relation:null;e.relation?.kind==="side"?c(e.id,m("sideChat.title"),!0):c(e.id,t?.description||t?.profile||h_(e))},onDelete:e.relation?.kind==="side"?()=>j(e.id):void 0,confirming:k===e.id,onDeleteConfirm:()=>{N(e.id)},onDeleteCancel:()=>j(null)},e.id)),n.length>0&&0===$.length&&(0,r.jsx)("div",{style:{padding:"22px 12px",color:"var(--text-dim)",fontSize:12,textAlign:"center"},children:m("agentSwitcher.noMatches")})]})]})})}let hY="\0lock";function hX(e){let{rootSession:t,members:n,selectedSessionId:s,runningSessionIds:a,onSelectSession:o,locked:d,onToggleLock:c}=e,{t:u}=(0,eX.s)(),p=(0,i.useRef)(null),h=(0,hD.Y)('[aria-current="true"]',`${n.length}
200
+ ${s}`),[m,g]=(0,i.useState)(null),f=m&&(m===t.id||m===hY||n.some(e=>e.id===m))?m:s,x=s===t.id,b=u("agentSwitcher.status.running"),v=a.has(t.id);return(0,r.jsxs)("div",{ref:p,role:"toolbar","aria-label":u("agentSwitcher.strip"),onKeyDown:e=>{let t=[...p.current?.querySelectorAll("button")??[]],n=t.indexOf(document.activeElement);if(n<0)return;let r="ArrowRight"===e.key?Math.min(n+1,t.length-1):"ArrowLeft"===e.key?Math.max(n-1,0):"Home"===e.key?0:"End"===e.key?t.length-1:-1;r<0||(e.preventDefault(),t[r].focus())},style:{display:"flex",alignItems:"center",gap:6,height:34,padding:"0 8px",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)(hQ,{label:u("agentSwitcher.main"),title:x?u("agentSwitcher.main"):u("agentSwitcher.backToMain"),current:x,tabStop:f===t.id,icon:v?(0,r.jsx)(hZ,{status:"running"}):x?(0,r.jsx)(hK,{kind:"main",size:12}):(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)("path",{d:"M19 12H5M11 6l-6 6 6 6"})}),running:v,onFocus:()=>g(t.id),onClick:()=>o(t)}),(0,r.jsx)("span",{"aria-hidden":"true",style:{width:1,height:16,flexShrink:0,background:"var(--border)"}}),(0,r.jsx)("div",{ref:h,className:"tabbar-scroll",style:{flex:1,minWidth:0,height:"100%",display:"flex",alignItems:"center",gap:6,overflowX:"auto",overflowY:"hidden"},children:n.map(e=>{let t=e.relation?.kind==="side",i=e.relation?.kind==="subagent"?e.relation:null,d=t?l(e,u("agentSwitcher.sideChat"),n):hU(e),c=a.has(e.id),p=t?u("agentSwitcher.sideChat"):i?.profile??u("agentSwitcher.subagent");return(0,r.jsx)(hQ,{label:d,title:[d,p,c?b:null].filter(Boolean).join(" \xb7 "),current:e.id===s,tabStop:f===e.id,icon:c?(0,r.jsx)(hZ,{status:"running"}):(0,r.jsx)(hK,{kind:t?"side":"subagent",size:12}),running:c,onFocus:()=>g(e.id),onClick:()=>o(e)},e.id)})}),(0,r.jsx)("span",{"aria-hidden":"true",style:{width:1,height:16,flexShrink:0,background:"var(--border)"}}),(0,r.jsx)(is,{locked:d,iconSize:14,onClick:c,onFocus:()=>g(hY),"aria-label":u("agentSwitcher.lockStrip"),title:d?u("agentSwitcher.unlockStrip"):u("agentSwitcher.lockStrip"),tabIndex:f===hY?0:-1,style:{flexShrink:0,width:24,height:24,borderRadius:6}})]})}function hQ(e){let{label:t,title:n,current:i,tabStop:s,icon:a,running:l,onFocus:o,onClick:d}=e;return(0,r.jsxs)("button",{type:"button",onClick:d,onFocus:o,title:n,tabIndex:s?0:-1,"aria-current":i?"true":void 0,className:i?"cursor-pointer text-text":"cursor-pointer bg-transparent text-text-muted hover:bg-bg-hover hover:text-text",style:{display:"flex",alignItems:"center",gap:5,flexShrink:0,maxWidth:200,height:24,padding:"0 9px",border:`1px solid ${i?"var(--accent)":"var(--border)"}`,borderRadius:12,background:i?"var(--bg-selected)":void 0,fontSize:11,fontWeight:i?600:500,whiteSpace:"nowrap"},children:[(0,r.jsx)("span",{style:{display:"grid",placeItems:"center",flexShrink:0,color:l||i?"var(--accent)":"var(--text-dim)"},children:a}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})]})}let h0={idle:"debug.stream.state.idle",connecting:"debug.stream.state.connecting",connected:"debug.stream.state.connected",retrying:"debug.stream.state.retrying"},h1={ready_timeout:"debug.stream.error.readyTimeout",startup_error:"debug.stream.error.startup",error:"debug.stream.error.error",stale:"debug.stream.error.stale"},h2={visible:"debug.stream.reattach.visible",activity:"debug.stream.reattach.activity"},h4={agent:"debug.page.source.agent","file-watch":"debug.page.source.fileWatch",terminal:"debug.page.source.terminal"},h8={connecting:"debug.page.source.connecting",open:"debug.page.source.open"},h6={reply:"debug.lease.outcome.reply",unanswered:"debug.lease.outcome.unanswered",error:"debug.lease.outcome.error"},h3={alive:"debug.state.alive",closing:"debug.state.closing",none:"debug.state.none"},h5={timeout:"debug.poll.timeout",http:"debug.poll.http",network:"debug.poll.network",invalid:"debug.poll.invalid"},h9={starting:"agentSwitcher.status.starting",queued:"agentSwitcher.status.queued",running:"agentSwitcher.status.running",completed:"agentSwitcher.status.completed",failed:"agentSwitcher.status.failed",aborted:"agentSwitcher.status.aborted",interrupted:"agentSwitcher.status.interrupted",unknown:"debug.unknown"},h7={released:"debug.stream.close.released",grace_end:"debug.stream.close.graceEnd",send_failed:"debug.stream.close.sendFailed",set_tools:"debug.stream.close.setTools",rebuilt:"debug.stream.close.rebuilt",deselected:"debug.stream.close.deselected",stuck:"debug.stream.close.stuck",replaced:"debug.stream.close.replaced"};function me(e,t,n){return Object.prototype.hasOwnProperty.call(t,e)?n(t[e]):e}function mt(e){return Number.isFinite(e)?Math.max(0,e):0}function mn(e){return String(e).padStart(2,"0")}function mr(e,t){let n=mt(e);return n<1e3?t("debug.duration.ms",{count:Math.floor(n)}):n<6e4?t("debug.duration.seconds",{count:Math.floor(n/1e3)}):n<36e5?t("debug.duration.minutesSeconds",{minutes:Math.floor(n/6e4),seconds:mn(Math.floor(n%6e4/1e3))}):n<864e5?t("debug.duration.hoursMinutes",{hours:Math.floor(n/36e5),minutes:mn(Math.floor(n%36e5/6e4))}):t("debug.duration.daysHours",{days:Math.floor(n/864e5),hours:Math.floor(n%864e5/36e5)})}function mi(e,t){return t("debug.time.ago",{time:mr(e,t)})}function ms(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"floor",r=Math[n](mt(e)/1e3);return r<60?t("debug.duration.seconds",{count:r}):mr(1e3*r,t)}function ma(e,t){return e>0?t("debug.time.in",{time:ms(e,t,"ceil")}):t("debug.time.due")}function ml(e,t){return e>0?t("debug.time.in",{time:mr(e,t)}):t("debug.time.due")}function mo(e){return e.length>8?e.slice(0,8):e}function md(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function mc(e){return"number"==typeof e&&Number.isFinite(e)}function mu(e){var t;return md(e)&&"string"==typeof e.sessionId&&"string"==typeof e.state&&mc(e.eventStreams)&&(null===(t=e.nextIdleCheckAt)||mc(t))}function mp(e,t){try{return e()}catch{return t}}function mh(e){if(!e)return{client:null,failed:!1};try{return{client:e()??null,failed:!1}}catch{return{client:null,failed:!0}}}function mm(e,t){return e?.sessionId??t}let mg={sessionId:null,reply:null,receivedAt:null,roundTripMs:null,failure:null,requests:0,failures:0,consecutiveFailures:0},mf=e=>e.filter(Boolean).join(" \xb7 ");function mx(e,t,n){return null===e?n("debug.holder.none"):`${n(e===t?"debug.holder.thisPage":"debug.holder.otherPage")} ${mo(e)}`}function mb(e,t){let n=e.filter(e=>null!==e.holder&&e.holder===t);return[...n,...e.filter(e=>!n.includes(e))]}let mv={running:"debug.overlay.running",awaiting:"debug.overlay.awaiting",alive:"debug.state.alive",closing:"debug.state.closing",none:"debug.state.none",starting:"debug.server.starting"};function my(e){return e.awaitingInput?"awaiting":e.running?"running":e.state}function mk(e,t){return null===e.label?"—":"agent"===e.kind?t?.(e.label)??mo(e.label):J(e.label)}function mj(e,t){if(!(t>0))return null;let n=e/t;return Number.isFinite(n)?Math.min(1,Math.max(0,n)):0}function mw(e,t){if(!e||"connected"!==e.state||!e.watchdogArmed)return null;let n=e.staleAfterMs;return null!==n&&n>0&&null!==e.lastSeenAt?{ageMs:Math.max(0,t-e.lastSeenAt),staleAfterMs:n}:null}function mS(e,t){return t>0?e>=t?"error":e>=t/2?"warning":"dim":"dim"}let mC={poll:[],running:[]};function mN(e){let t=mt(e);return{ms:t,tone:t>=2e3?"warning":"dim",failed:!1}}function mI(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:30,r=[...e,t];return r.length>n?r.slice(r.length-n):r}function mE(e){let t=Date.parse(e.modified);return Number.isFinite(t)?t:-1/0}function m$(e,t){return e===t?0:t>e?1:-1}class mT extends i.Component{static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(e){console.error("Debug panel failed:",e)}render(){return this.state.failed?(0,r.jsx)("div",{role:"status",style:{padding:"10px 16px",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",color:"var(--text-muted)",fontSize:12},children:this.props.fallback}):this.props.children}constructor(...e){super(...e),this.state={failed:!1}}}function mM(e){let{readerRef:t,selectedSessionId:n,sessions:s,onClose:a}=e,{t:l}=(0,eX.s)(),o=(0,i.useRef)(n);o.current=n;let d=(0,i.useRef)(a);d.current=a;let c=(0,i.useRef)(null),u=(0,i.useRef)(!1),p=(0,i.useRef)(null),h=(0,i.useRef)(null),m=(0,i.useRef)(null),[g,f]=(0,i.useState)(null),[x,b]=(0,i.useState)(mg),[v,y]=(0,i.useState)(mC),[k,j]=(0,i.useState)(!1),[w,S]=(0,i.useState)(null),C=(0,i.useRef)({page:g,server:x,samples:v});C.current={page:g,server:x,samples:v},(0,i.useEffect)(()=>{let e=h.current;if(!e)return;let t=null,n=n=>{if("mouse"!==n.pointerType)return;let r=n.target instanceof Element?n.target.closest("[title]"):null,i=r&&e.contains(r)?r:null;i!==t&&(t=i,S(i?C.current:null))},r=()=>{t=null,S(null)};return e.addEventListener("pointerover",n),e.addEventListener("pointerleave",r),()=>{e.removeEventListener("pointerover",n),e.removeEventListener("pointerleave",r)}},[]),(0,i.useEffect)(()=>{var e;let n,r,i,s,a,l,d,h,g;u.current=!1;let x=(r=(e={fetch:(e,t)=>fetch(e,t),sessionId:()=>mm(mh(t.current).client,o.current),isVisible:()=>"visible"===document.visibilityState,onReading:e=>{b(e);let t=function(e){if(e.failure){let t="timeout"===e.failure.kind;return{ms:5e3*!!t,tone:t?"warning":"error",failed:!0}}return null===e.roundTripMs?null:mN(e.roundTripMs)}(e);t&&y(e=>({...e,poll:mI(e.poll,t)}))}}).now??(()=>Date.now()),i=e.setTimeout??((e,t)=>setTimeout(e,t)),s=e.clearTimeout??(e=>clearTimeout(e)),a=!1,l=null,d=mg,h=async t=>{let o=new AbortController,c={sessionId:t,controller:o,startedAt:r()};l=c,n=t;let u=!1,p=i(()=>{u=!0,o.abort()},5e3),h=null,m=null;try{var g,f;let n=await e.fetch(t?`/api/agent/debug?session=${encodeURIComponent(t)}`:"/api/agent/debug",{cache:"no-store",signal:o.signal});if(n.ok){let e=null;try{e=await n.json()}catch(e){if(o.signal.aborted)throw e}(g=e,md(g)&&mc(g.now)&&md(f=g.server)&&mc(f.startedAt)&&md(f.wrappers)&&md(f.eventStreams)&&mc(f.sseTotal)&&Array.isArray(f.pages)&&md(f.terminals)&&Array.isArray(g.sessions)&&g.sessions.every(mu)&&(null===g.session||function(e){if(!md(e)||"string"!=typeof e.sessionId)return!1;let t=e.wrapper,n=e.subagents,r=e.mcp;return(null===t||md(t)&&"string"==typeof t.state&&md(t.run)&&md(t.idle))&&(null===e.lifecycle||md(e.lifecycle))&&(null===e.providers||Array.isArray(e.providers))&&Array.isArray(e.eventStreams)&&md(n)&&Array.isArray(n.runs)&&Array.isArray(n.notifications)&&(null===r||md(r)&&Array.isArray(r.servers))}(g.session)))?h=e:m={kind:"invalid",status:n.status}}else m={kind:"http",status:n.status}}catch{m={kind:u?"timeout":"network",status:null}}finally{s(p),l===c&&(l=null)}if(a||o.signal.aborted&&!u||e.sessionId()!==t)return;let x=r(),b=d.sessionId===t;d=h?{sessionId:t,reply:h,receivedAt:x,roundTripMs:Math.max(0,x-c.startedAt),failure:null,requests:d.requests+1,failures:d.failures,consecutiveFailures:0}:{sessionId:t,reply:b?d.reply:null,receivedAt:b?d.receivedAt:null,roundTripMs:b?d.roundTripMs:null,failure:{...m??{kind:"invalid",status:null},at:x},requests:d.requests+1,failures:d.failures+1,consecutiveFailures:d.consecutiveFailures+1},e.onReading(d)},{poll:g=()=>{if(a||!e.isVisible())return;let t=e.sessionId();if(l){if(l.sessionId===t)return;l.controller.abort()}h(t)},sync(){a||(l?l.sessionId:n)!==e.sessionId()&&g()},inFlightSince:()=>l?.startedAt??null,dispose(){a=!0,l?.controller.abort(),l=null}});c.current=x;let v=()=>{let e=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Date.now(),{client:r,failed:i}=mh(e);return{at:n,client:r,clientFailed:i,sources:mp(e$.X6,[]),visibility:mp(e$._L,null),protocol:mp(e$.rv,null),runningPoll:mp(e$.RK,null),pollInFlightSince:t}}(t.current,x.inFlightSince());f(e);let n=e.runningPoll?.last??null;if(n&&n.at!==m.current){m.current=n.at;let e=n&&"aborted"!==n.outcome?"error"===n.outcome?{ms:mt(n.durationMs),tone:"error",failed:!0}:mN(n.durationMs):null;e&&y(t=>({...t,running:mI(t.running,e)}))}};v(),x.poll();let k=window.setInterval(()=>{"visible"===document.visibilityState&&(v(),x.sync())},1e3),j=window.setInterval(()=>x.poll(),2e3),w=()=>{"visible"===document.visibilityState&&(v(),x.poll())};return document.addEventListener("visibilitychange",w),()=>{u.current=!0,x.dispose(),c.current=null,window.clearInterval(k),window.clearInterval(j),document.removeEventListener("visibilitychange",w),p.current&&clearTimeout(p.current)}},[t]),(0,i.useEffect)(()=>{c.current?.sync()},[n]),(0,i.useEffect)(()=>{var e,t,n;let r=(e=document,t=()=>h.current,n=e=>d.current(e),r=>{var i;if(i=null!==e.querySelector('[aria-modal="true"]'),"Escape"!==r.key||r.defaultPrevented||r.cancelBubble||r.isComposing||229===r.keyCode||i)return;r.preventDefault();let s=e.activeElement;n(!!(s&&t()?.contains(s)))});return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[]);let N=w??{page:g,server:x,samples:v};return(0,r.jsx)(mR,{page:N.page,server:N.server,samples:N.samples,selectedSessionId:n,sessions:s,copied:k,onCopy:()=>{let e={client:g,server:x.reply};(0,tc.D)(JSON.stringify(e,null,2)).then(()=>{u.current||(p.current&&clearTimeout(p.current),j(!0),p.current=setTimeout(()=>j(!1),1400))},()=>{})},t:l,sectionRef:h})}function mR(e){var t;let n,{page:s,server:a,samples:l=mC,selectedSessionId:o,sessions:d,copied:c,onCopy:u,t:p,sectionRef:h}=e,m=s?.at??a.receivedAt??0,g=s?.client??null,f=mm(g,o),b=a.reply,v=b&&null!==a.receivedAt?(t=b.now,n=Math.max(0,m-a.receivedAt),{remaining:e=>e-t-n,age:e=>t-e+n}):null,y=b?.session&&b.session.sessionId===f?b.session:null,k=g?.pageId??null,j=(0,i.useMemo)(()=>new Map(d.map(e=>[e.id,e])),[d]),w=(0,i.useMemo)(()=>e=>{let t=j.get(e);return t?ty(t):null},[j]),S=(0,i.useMemo)(()=>b?function(e,t,n){let r=e=>{let n=e,r=new Set([e.id]);for(let i=0;i<32;i++){let i=n.relation;if(i?.kind!=="subagent")break;let s=t.get(i.parentSessionId);if(!s)break;if(r.has(s.id))return e;r.add(s.id),n=s}return n},i=new Map,s=[];for(let n of e){let e=t.get(n.sessionId);if(!e){s.push(n);continue}let a=r(e),l=i.get(a.id);l||(l={root:a,summary:null,subagents:[]},i.set(a.id,l)),a.id===e.id?l.summary=n:l.subagents.push({info:e,summary:n})}let a=null===n?void 0:t.get(n),l=a?r(a).id:null,o=(e,t)=>m$(mE(e.root),mE(t.root)),d=(e,t)=>Number(t.root.id===l)-Number(e.root.id===l),c=new Map;for(let e of i.values()){let t=x(e.root),n=c.get(t);n||(n={key:t,name:J(e.root.projectRoot??e.root.cwd),families:[]},c.set(t,n)),n.families.push(e)}let u=e=>Math.max(...e.families.map(e=>mE(e.root))),p=e=>e.families.some(e=>e.root.id===l),h=[...c.values()].sort((e,t)=>Number(p(t))-Number(p(e))||m$(u(e),u(t))).map(e=>{let t=[];for(let r of[...e.families].sort(o).sort(d))for(let{info:e,summary:i}of(t.push({id:r.root.id,depth:0,info:r.root,summary:r.summary,current:r.root.id===n,placeholder:null===r.summary}),[...r.subagents].sort((e,t)=>m$(mE(e.info),mE(t.info)))))t.push({id:e.id,depth:1,info:e,summary:i,current:e.id===n,placeholder:!1});return{key:e.key,name:e.name,rows:t}});if(s.length>0){let e=null!==n&&!a&&s.some(e=>e.sessionId===n),t=(e,t)=>e<t?-1:+(e>t),r={key:"\0unlisted",name:null,rows:[...s].sort((e,r)=>Number(r.sessionId===n)-Number(e.sessionId===n)||t(mo(e.sessionId),mo(r.sessionId))||t(e.sessionId,r.sessionId)).map(e=>({id:e.sessionId,depth:0,info:null,summary:e,current:e.sessionId===n,placeholder:!1}))};e?h.unshift(r):h.push(r)}return h}(b.sessions,j,f):null,[b,j,f]),C=s?function(e){let{page:t,server:n,detail:r,t:i,titleOf:s}=e,a=t.at,l=[],o=(e,t,n)=>{l.push({id:e,tone:t,text:mf(n)})},d=n.failure;d?o("poll","timeout"===d.kind?"warning":"error",[i(h5[d.kind],{status:d.status??"?"}),mi(a-d.at,i)]):null!==t.pollInFlightSince&&a-t.pollInFlightSince>=2e3&&o("poll","warning",[i("debug.poll.inFlight",{time:mr(a-t.pollInFlightSince,i)})]),t.clientFailed&&o("reader","error",[i("debug.stream.readerFailed")]);let c=t.runningPoll?.last??null;c?.outcome==="error"&&o("runningPoll","warning",[i("debug.page.runningPoll"),i("debug.page.poll.error"),null!==c.httpStatus&&`HTTP ${c.httpStatus}`,mi(a-c.at,i)]);let u=t.sources.filter(e=>"open"===e.state).length;"http/1.1"===t.protocol&&u>=5&&o("pool",u>=6?"error":"warning",[i("debug.issue.pool",{count:u})]);let p=t.client,h=p?.connection??null,m=h?.sessionId??null;for(let e of t.sources)"connecting"===e.state&&0!==e.errors&&("agent"!==e.kind||null===m||e.label!==m)&&o("source","warning",[i(h4[e.kind]),mk(e,s),i("debug.page.source.connecting"),i("debug.page.sourceCounts",{opens:e.opens,errors:e.errors})]);if(h){let e=null!==h.retryDueAt&&i("debug.stream.retryDue",{time:ml(h.retryDueAt-a,i)}),t=h.lastError;t&&"connected"!==h.state&&!(h.lastClose&&h.lastClose.at>=t.at)?o("stream","error",[me(t.reason,h1,i),t.message,mi(a-t.at,i),e]):"retrying"===h.state&&o("stream","warning",[i(h0.retrying),e]);let n=mw(h,a),r=n?mS(n.ageMs,n.staleAfterMs):"dim";n&&"dim"!==r&&o("streamSilent",r,[`${i("debug.stream.lastData")} ${mi(n.ageMs,i)}`])}let g=p?.pageId??null,f=null!==n.receivedAt?n.receivedAt-(n.roundTripMs??0):null;for(let e of(r&&g&&h&&null!==f&&"connected"===h.state&&h.sessionId===r.sessionId&&null!==h.connectedAt&&h.connectedAt<f&&!r.eventStreams.some(e=>e.holder===g)&&o("noServerStream","warning",[i("debug.issue.noServerStream")]),r?.eventStreams??[]))e.droppedEvents>0&&o("dropped","warning",[mx(e.holder,g,i),i("debug.server.dropped",{count:e.droppedEvents})]);let x=p?.lease??null;if(x){let e=x.last;null!==x.inFlightSince&&a-x.inFlightSince>=2e3?o("lease","warning",[i("debug.section.lease"),i("debug.lease.inFlight",{time:mr(a-x.inFlightSince,i)})]):e?.outcome==="error"?o("lease","error",[i("debug.section.lease"),i(h6.error),null!==e.httpStatus&&`HTTP ${e.httpStatus}`,mi(a-e.at,i)]):e?.outcome==="unanswered"&&o("lease","warning",[i("debug.section.lease"),i(h6.unanswered),mi(a-e.at,i)])}let b=r?.wrapper??null;for(let e of(b&&!b.stale&&"failed"===b.extensions&&o("extensions","error",[i("debug.server.extensions"),i("debug.server.extensions.failed")]),r?.providers??[]))"error"===e.active&&o("provider","error",[e.name,i("debug.server.providerError")]);for(let e of r?.mcp?.servers??[])(e.hasError||"failed"===e.state||"conflict"===e.state)&&o("mcp","error",[`MCP ${e.name}`,me(e.state,o$,i)]);return l.sort((e,t)=>Number("error"===t.tone)-Number("error"===e.tone))}({page:s,server:a,detail:y,t:p,titleOf:w}):[],N=null===s?{kind:"reading",tone:"dim",count:0}:s.visibility?.state==="hidden"?{kind:"hidden",tone:"dim",count:0}:C.length>0?{kind:"issues",tone:C.some(e=>"error"===e.tone)?"error":"warning",count:C.length}:null===a.receivedAt?{kind:"waiting",tone:"dim",count:0}:{kind:"ok",tone:"ok",count:0},I={t:p,now:m,clock:v,myHolder:k,titleOf:w};return(0,r.jsxs)("section",{ref:h,className:"debug-panel","aria-label":p("debug.panelLabel"),children:[(0,r.jsxs)("div",{className:"debug-panel-header",children:[(0,r.jsx)("span",{className:"debug-panel-heading",title:p("debug.readOnly"),children:p("debug.title")}),(0,r.jsx)(mU,{verdict:N,t:p}),(0,r.jsx)("button",{type:"button",className:"debug-panel-copy",onClick:u,title:p("debug.copyTitle"),children:p(c?"debug.copied":"debug.copyJson")})]}),null!==s&&(0,r.jsxs)("div",{className:"debug-panel-scroll",children:[C.length>0&&(0,r.jsx)(mK,{issues:C}),(0,r.jsxs)("div",{className:"debug-cols",children:[(0,r.jsx)(mV,{page:s,samples:l,reply:b,ctx:I}),(0,r.jsxs)("div",{className:"debug-col debug-col-server",children:[(0,r.jsx)(m2,{reply:b,ctx:I}),(0,r.jsx)(m4,{reply:b,ctx:I})]}),(0,r.jsx)("div",{className:"debug-col debug-col-sessions",children:(0,r.jsx)(m8,{reply:b,detail:y,groups:S,targetSessionId:f,sources:s.sources,ctx:I})})]})]}),(0,r.jsx)("style",{children:gl})]})}function mA(e){let{kind:t,size:n=12}=e;return(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:["server"===t&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"8",rx:"2"}),(0,r.jsx)("rect",{x:"3",y:"13",width:"18",height:"8",rx:"2"}),(0,r.jsx)("path",{d:"M7 7h.01M7 17h.01"})]}),"warning"===t&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z"}),(0,r.jsx)("path",{d:"M12 9v4"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),"error"===t&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M15 9l-6 6M9 9l6 6"})]})]})}function mL(e,t){return["debug-badge",t,`is-${e.tone}`,e.filled&&"is-filled",e.dashed&&"is-dashed",e.faded&&"is-faded"].filter(Boolean).join(" ")}function mP(e){let{text:t,items:n,cap:i,label:s,plain:a=!1}=e;return 0===n.length?null:(0,r.jsxs)("span",{className:"debug-run",title:s,...a?{}:{role:"img","aria-label":s},children:[n.slice(0,i).map((e,n)=>(0,r.jsx)("span",{className:mL(e,void 0!==e.text?"is-name":void 0),title:e.title,children:e.text??t},n)),n.length>i&&(0,r.jsx)("span",{className:"debug-run-more",children:`+${n.length-i}`})]})}let mz={Chrome:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M21.17 8H12M3.95 6.06 8.54 14M10.88 21.94 15.46 14"})]}),Safari:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("path",{d:"M16.24 7.76 14.12 14.12 7.76 16.24 9.88 9.88z"})]}),Firefox:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("path",{d:"M12 17a3.5 3.5 0 0 0 3.5-3.5c0-2.5-2-3.5-2.5-6-1.5 1.5-1 3-2 3.5-.5-.5-1-1-1-2-1.5 1-1.5 2.5-1.5 4.5A3.5 3.5 0 0 0 12 17z"})]}),Edge:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M21 12a9 9 0 1 0-4.5 7.8"}),(0,r.jsx)("path",{d:"M7 13.5c0-3 2.5-5 5.5-5 2.5 0 4.5 1.5 4.5 3.5 0 1.3-1 2-2.5 2H10"})]}),Opera:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("ellipse",{cx:"12",cy:"12",rx:"4",ry:"7"})]}),macOS:(0,r.jsx)(mO,{}),iOS:(0,r.jsx)(mO,{}),Windows:(0,r.jsx)("path",{fill:"currentColor",stroke:"none",d:"M0 0h11.377v11.372H0zm12.623 0H24v11.372H12.623zM0 12.623h11.377V24H0zm12.623 0H24V24H12.623z"}),Android:(0,r.jsx)("path",{d:"M4.5 18a7.5 7.5 0 0 1 15 0zM8 12 6.5 9.5M16 12l1.5-2.5M9.5 15h.01M14.5 15h.01"}),Linux:(0,r.jsx)("path",{d:"m4 17 6-5-6-5M12 19h8"}),ChromeOS:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"12",rx:"2"}),(0,r.jsx)("path",{d:"M2 20h20"})]})};function mO(){return(0,r.jsx)("path",{fill:"currentColor",stroke:"none",d:"M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09zM15.53 3.83c.843-1.012 1.4-2.427 1.245-3.83-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.559-1.701"})}function mW(e){let{client:t}=e,n=t?t.split(" \xb7 ").filter(e=>e in mz):[];return 0===n.length?null:(0,r.jsx)("span",{className:"debug-client","aria-hidden":"true",children:n.map(e=>(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2.2,strokeLinecap:"round",strokeLinejoin:"round",children:mz[e]},e))})}function mF(e){let{tone:t,ring:n=!1}=e;return(0,r.jsx)("span",{className:`debug-dot is-${t}${n?" is-ring":""}`,"aria-hidden":"true"})}function mD(e){let{tone:t,children:n,title:i}=e;return(0,r.jsx)("span",{className:`debug-chip is-${t}`,title:i,children:n})}function mB(e){let{fraction:t,tone:n,width:i,height:s=4,notches:a,title:l,className:o}=e;return(0,r.jsxs)("span",{className:`debug-bar is-${n}${o?` ${o}`:""}`,style:{width:i,height:s},title:l,"aria-hidden":"true",children:[(0,r.jsx)("span",{className:"debug-bar-fill",style:{width:`${100*t}%`}}),a?.map(e=>(0,r.jsx)("span",{className:"debug-bar-notch",style:{left:`${100*e}%`}},e))]})}function mH(e){let{samples:t,label:n}=e,i=t.slice(-30);return(0,r.jsx)("span",{className:"debug-spark",role:"img","aria-label":n,title:n,children:(0,r.jsxs)("svg",{width:"120",height:"15",viewBox:"0 0 120 15","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"0",y:"14",width:"120",height:"1",style:{fill:"var(--border)"}}),i.map((e,t)=>{let n=e.failed?14:Math.max(1,Math.round(14*Math.min(1,Math.max(.08,Math.sqrt(mt(e.ms)/5e3)))));return(0,r.jsx)("rect",{className:`is-${e.tone}`,x:120-(i.length-t)*4+1,y:14-n,width:"3",height:n,fill:"currentColor"},t)})]})})}function m_(e){let{state:t,label:n}=e;return"awaiting"===t?(0,r.jsx)("span",{className:"debug-status",children:(0,r.jsx)("span",{className:"session-tree-awaiting",role:"img","aria-label":n,title:n})}):"running"===t?(0,r.jsx)("span",{className:"debug-status is-accent",title:n,children:(0,r.jsx)(tv.Nl,{size:12,label:n})}):(0,r.jsx)("span",{className:"debug-status",role:"img","aria-label":n,title:n,children:(0,r.jsx)("span",{className:`debug-status-ring is-${t}`})})}function mU(e){let{verdict:t,t:n}=e,i=({reading:()=>n("debug.reading"),hidden:()=>n("debug.poll.hidden"),issues:()=>n("debug.health.issues",{count:t.count}),waiting:()=>n("debug.poll.waiting"),ok:()=>n("debug.health.ok")})[t.kind]();return(0,r.jsxs)("span",{className:`debug-panel-status is-${"ok"===t.kind?"muted":t.tone}`,children:["issues"===t.kind&&(0,r.jsx)(mA,{kind:"error"===t.tone?"error":"warning"}),"ok"===t.kind&&(0,r.jsx)(mF,{tone:"ok"}),("hidden"===t.kind||"waiting"===t.kind)&&(0,r.jsx)(mF,{tone:"dim",ring:!0}),(0,r.jsx)("span",{className:"debug-panel-status-text",children:i})]})}function mK(e){let{issues:t}=e;return(0,r.jsx)("ul",{className:"debug-issues",children:t.map((e,t)=>(0,r.jsxs)("li",{className:`debug-issue is-${e.tone}`,children:[(0,r.jsx)(mA,{kind:e.tone}),(0,r.jsx)("span",{className:"debug-issue-text",children:e.text})]},`${e.id}:${t}`))})}function mq(e,t){let n=function(e){let t=e.filter(e=>!e.failed).map(e=>e.ms).sort((e,t)=>e-t);if(0===t.length)return{count:0,median:0,max:0};let n=Math.floor(t.length/2),r=t.length%2==1?t[n]:(t[n-1]+t[n])/2;return{count:t.length,median:r,max:t[t.length-1]}}(e);return 0===n.count?t("debug.notYet"):t("debug.spark.title",{count:n.count,median:mr(n.median,t),max:mr(n.max,t)})}function mZ(e){let{samples:t,t:n}=e,i=t[t.length-1];return i?(0,r.jsx)("span",{className:`debug-value is-${i.tone}`,children:i.failed?"—":mr(i.ms,n)}):(0,r.jsx)("span",{className:"debug-value is-dim",children:"—"})}function mV(e){let{page:t,samples:n,reply:i,ctx:s}=e,{t:a}=s,l=function(e,t,n){let r=[...e].sort((e,t)=>e.createdAt-t.createdAt).map(e=>({id:e.id,kind:e.kind,label:e.label,chat:"agent"===e.kind&&null!==n&&e.label===n,connecting:"connecting"===e.state,opens:e.opens,errors:e.errors,createdAt:e.createdAt})),i="http/1.1"===t?6:null,s=r.length,a=r.filter(e=>!e.connecting).length,l={agent:0,"file-watch":0,terminal:0};for(let e of r)l[e.kind]=(l[e.kind]??0)+1;return{protocol:t,cap:i,slots:null===i?r:r.slice(0,i),mine:s,overflow:null===i?0:Math.max(0,s-i),kinds:l,tone:null===i?"dim":a>=i?"error":a>=i-1?"warning":"dim"}}(t.sources,t.protocol,t.client?.connection?.sessionId??null),o=t.runningPoll;return(0,r.jsxs)("div",{className:"debug-col debug-col-page",children:[(0,r.jsx)("div",{className:"debug-col-head",children:(0,r.jsx)("span",{className:"debug-section-title",children:a("debug.section.page")})}),(0,r.jsx)(mJ,{pool:l,ctx:s}),(0,r.jsxs)("div",{className:"debug-measures",children:[(0,r.jsx)("span",{className:"debug-measure-name",children:(0,r.jsx)("span",{className:"debug-label",children:a("debug.page.debugPoll")})}),(0,r.jsx)(mH,{samples:n.poll,label:mq(n.poll,a)}),(0,r.jsx)(mZ,{samples:n.poll,t:a}),(0,r.jsx)("span",{className:"debug-measure-name",children:(0,r.jsx)("span",{className:"debug-label",children:a("debug.page.runningPoll")})}),(0,r.jsx)(mH,{samples:n.running,label:mf([o&&a("debug.page.pollCounts",{count:o.count,failures:o.failures}),mq(n.running,a)])}),(0,r.jsx)(mZ,{samples:n.running,t:a}),(0,r.jsx)(mQ,{page:t,reply:i,ctx:s}),(0,r.jsx)(m1,{page:t,ctx:s})]})]})}function mJ(e){let{pool:t,ctx:n}=e,{t:i,now:s,titleOf:a}=n,l=Object.keys(h4).filter(e=>t.kinds[e]>0).map(e=>`${i(h4[e])} ${t.kinds[e]}`),o=null!==t.cap?mf([`${i("debug.page.http1",{protocol:t.protocol??""})} \xb7 ${t.mine}/${t.cap}`,...l]):mf([i("debug.section.page"),...l,t.protocol??i("debug.unknown")]),d=null!==t.cap?Array.from({length:t.cap},(e,n)=>t.slots[n]??null):t.slots;return(0,r.jsxs)("div",{className:"debug-meter-row",children:[(0,r.jsxs)("span",{className:`debug-meter${null===t.cap?" is-inline":""}`,role:"img","aria-label":o,title:o,children:[d.map((e,t)=>e?(0,r.jsx)("span",{className:mL({tone:e.connecting?"warning":e.chat?"accent":"muted",filled:e.chat,dashed:e.connecting},"debug-slot"),title:mf([i(h4[e.kind]),mk(e,a),i(h8[e.connecting?"connecting":"open"]),i("debug.page.sourceCounts",{opens:e.opens,errors:e.errors}),mi(s-e.createdAt,i)]),children:"agent"===e.kind?"SSE":i(mG[e.kind])},e.id):(0,r.jsx)("span",{className:"debug-slot is-empty"},`empty:${t}`)),t.overflow>0&&(0,r.jsx)("span",{className:"debug-meter-overflow is-error",children:`+${t.overflow}`})]}),null===t.cap&&null!==t.protocol&&(0,r.jsx)(mD,{tone:"dim",children:t.protocol})]})}let mG={"file-watch":"debug.box.file",terminal:"debug.box.terminal"},mY={connected:{tone:"ok",ring:!1},connecting:{tone:"warning",ring:!0},retrying:{tone:"warning",ring:!1},idle:{tone:"dim",ring:!0}};function mX(e,t,n,r){let i=n.at,s=[null!==t.readyState&&r("debug.stream.readyState",{value:t.readyState}),null!==t.openedAt&&`${r("debug.stream.opened")} ${mi(i-t.openedAt,r)}`,null!==t.connectedAt&&`${r("debug.stream.connected")} ${mi(i-t.connectedAt,r)}`,`${r("debug.stream.opens")} ${r("debug.stream.opensRetries",{opens:t.opens,retries:t.retries})}`,null!==t.lastError&&`${r("debug.stream.lastError")} ${mf([me(t.lastError.reason,h1,r),t.lastError.message,mi(i-t.lastError.at,r)])}`,null!==t.lastClose&&`${r("debug.stream.lastClose")} ${mf([t.lastClose.reason?me(t.lastClose.reason,h7,r):"—",mi(i-t.lastClose.at,r)])}`,`${r("debug.stream.wanted")} ${r(e.wantsStream?"debug.yes":"debug.no")}`],a=n.visibility;return a&&a.hiddenCount>0&&s.push(mf([r("debug.page.hiddenCount",{count:a.hiddenCount}),null!==a.lastHiddenAt&&r("debug.page.lastHidden",{time:mi(i-a.lastHiddenAt,r)})])),e.released.count>0&&s.push(`${r("debug.stream.released")} ${mf([r("debug.times",{count:e.released.count}),null!==e.released.lastAt&&mi(i-e.released.lastAt,r)])}`),e.reattached.count>0&&s.push(`${r("debug.stream.reattached")} ${mf([r("debug.times",{count:e.reattached.count}),null!==e.reattached.lastAt&&mi(i-e.reattached.lastAt,r),e.reattached.lastReason&&r(h2[e.reattached.lastReason])])}`),s.filter(Boolean).join("\n")}function mQ(e){let{page:t,reply:n,ctx:i}=e,{t:s,now:a}=i,l=t.client,o=l?.connection??null,d=(0,r.jsx)("span",{className:"debug-measure-name",title:l&&o?mX(l,o,t,s):void 0,children:(0,r.jsx)("span",{className:"debug-label",children:s("debug.section.stream")})});if(!l||!o)return(0,r.jsxs)(r.Fragment,{children:[d,(0,r.jsx)("span",{className:"debug-measure-empty",children:l?s("debug.stream.noConnection"):t.clientFailed?"—":s("debug.stream.noChat")})]});let c=mw(o,a),u=mY[o.state];return(0,r.jsxs)(r.Fragment,{children:[d,c?(0,r.jsx)(m0,{connection:o,freshness:c,heartbeatMs:n?.server.heartbeatMs??0,ctx:i}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{className:"debug-value is-dim",children:"—"})]}),(0,r.jsxs)("span",{className:"debug-measure-sub",title:mX(l,o,t,s),children:[(0,r.jsx)(mF,{tone:u?.tone??"dim",ring:u?.ring??!0}),mf([s(h0[o.state]??"debug.unknown"),`${s("debug.stream.events")} ${o.events}`,o.retries>0&&`${s("debug.stream.opens")} ${s("debug.stream.opensRetries",{opens:o.opens,retries:o.retries})}`])]}),(l.released.active||null!==l.graceDueAt)&&(0,r.jsxs)("span",{className:"debug-measure-sub debug-chips",children:[l.released.active&&(0,r.jsx)(mD,{tone:"accent",children:s("debug.stream.close.released")}),null!==l.graceDueAt&&(0,r.jsx)(mD,{tone:"accent",children:`${s("debug.stream.grace")} ${ma(l.graceDueAt-a,s)}`})]})]})}function m0(e){let{connection:t,freshness:n,heartbeatMs:i,ctx:s}=e,{t:a,now:l}=s,{ageMs:o,staleAfterMs:d}=n,c=mS(o,d),u=[];if(i>0)for(let e=i;e<d&&u.length<12;e+=i)u.push(e/d);let p=mf([`${a("debug.stream.lastData")} ${mi(o,a)}`,null!==t.lastHeartbeatAt&&a("debug.stream.heartbeat",{time:mi(l-t.lastHeartbeatAt,a)}),a("debug.stream.watchdogArmed",{time:mr(d,a)})]);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(mB,{fraction:mj(o,d)??0,tone:c,width:120,notches:u,title:p}),(0,r.jsx)("span",{className:`debug-value is-${c}`,title:p,children:a("debug.stream.dataAgo",{time:ms(o,a)})})]})}function m1(e){let{page:t,ctx:n}=e,{t:i,now:s}=n,a=t.client?.lease??null,l=t.client?.pageId??null,o=(0,r.jsx)("span",{className:"debug-measure-name",children:(0,r.jsx)("span",{className:"debug-label",children:i("debug.section.lease")})});if(!a||0===a.requests)return(0,r.jsxs)(r.Fragment,{children:[o,(0,r.jsx)("span",{className:"debug-measure-empty",children:a?i("debug.lease.noHolder"):t.clientFailed?"—":i("debug.stream.noChat")})]});let d=a.last,c=function(e,t,n){if(null===e||!(t>0))return null;let r=Math.max(0,n-e);return e+(Math.floor(r/t)+1)*t}(a.renewStartedAt,a.renewIntervalMs,s),u=null!==a.inFlightSince&&s-a.inFlightSince>=2e3,p=u||d?.outcome==="unanswered"?"warning":d?.outcome==="error"?"error":"dim",h=i("debug.lease.countsValue",{requests:a.requests,unanswered:a.unanswered,errors:a.errors}),m=mf([null!==c&&`${i("debug.lease.next")} ${ma(c-s,i)}`,i("debug.lease.every",{time:mr(a.renewIntervalMs,i)}),h,null!==l&&`${i("debug.holder.thisPage")} ${mo(l)}`]);return(0,r.jsxs)(r.Fragment,{children:[o,null===c?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{className:"debug-value is-dim",children:"—"})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(mB,{fraction:u?1:1-(mj(c-s,a.renewIntervalMs)??1),tone:p,width:120,title:m}),(0,r.jsx)("span",{className:"debug-value is-muted",title:m,children:c-s>0?i("debug.lease.renewsIn",{time:ms(c-s,i,"ceil")}):i("debug.lease.renewing")})]}),(0,r.jsx)("span",{className:"debug-measure-sub",children:`${i("debug.lease.last")} ${d?mf([i(h6[d.outcome]??"debug.unknown"),mr(d.durationMs,i),"error"===d.outcome&&null!==d.httpStatus&&`HTTP ${d.httpStatus}`,i("debug.time.ago",{time:ms(s-d.at,i)})]):i("debug.notYet")}`}),(a.unanswered>0||a.errors>0)&&(0,r.jsx)("span",{className:"debug-measure-sub",children:h})]})}function m2(e){let{reply:t,ctx:n}=e,{t:i,clock:s}=n,a=(0,r.jsx)("span",{className:"debug-section-title",children:i("debug.section.server")});if(!t||!s)return(0,r.jsxs)("div",{className:"debug-col-head debug-server-head",children:[a,(0,r.jsx)("span",{children:i("debug.poll.waiting")})]});let l=t.server,o=i("debug.global.wrappersValue",{...l.wrappers}),d=`${i("debug.global.timers")}: ${i("debug.global.timersValue",{idle:l.idleTimeoutMs>0?mr(l.idleTimeoutMs,i):i("debug.server.idleDisabled"),heartbeat:mr(l.heartbeatMs,i)})}
201
+ ${o}`,c=l.terminals,u=mf([`${i("debug.global.terminals")}: ${i("debug.global.terminalsValue",{count:c.count,listeners:c.listeners,detached:c.detached,exited:c.exited})}`,null!==c.nextCleanupAt&&i("debug.global.cleanup",{time:ml(s.remaining(c.nextCleanupAt),i)})]),p=Array.from({length:c.count},(e,t)=>t<c.detached?{tone:"dim",dashed:!0,title:u}:t<c.detached+c.exited?{tone:"muted",faded:!0,title:u}:{tone:"muted",title:u}),h=`${i("debug.global.fileWatches")}: ${l.fileWatches}`,m=l.wrappers.starting;return(0,r.jsxs)("div",{className:"debug-col-head debug-server-head",children:[a,(0,r.jsxs)("span",{className:"debug-server-item",title:d,children:[(0,r.jsx)(mA,{kind:"server"}),(0,r.jsx)("span",{children:`${i("debug.global.uptime")} ${mr(s.age(l.startedAt),i)}`})]}),m>0&&(0,r.jsxs)("span",{className:"debug-run",role:"img","aria-label":o,title:o,children:[Array.from({length:Math.min(m,4)},(e,t)=>(0,r.jsx)("span",{className:"debug-status",children:(0,r.jsx)("span",{className:"debug-status-ring is-starting"})},t)),m>4&&(0,r.jsx)("span",{className:"debug-run-more",children:`+${m-4}`})]}),(0,r.jsx)(mP,{text:i("debug.box.file"),items:Array.from({length:l.fileWatches},()=>({tone:"muted",title:h})),cap:4,label:h}),(0,r.jsx)(mP,{text:i("debug.box.terminal"),items:p,cap:4,label:u})]})}function m4(e){let{reply:t,ctx:n}=e,{t:i,myHolder:s}=n;if(!t)return null;let{pages:a,sseTotal:l}=t.server;if(0===l&&0===a.length)return null;let o=mb(a,s);return(0,r.jsxs)("div",{className:"debug-pages",children:[(0,r.jsxs)("div",{className:"debug-page-row debug-list-head",children:[(0,r.jsx)("span",{className:"debug-pages-title",children:`${i("debug.pages.title")} ${o.length}`}),(0,r.jsx)("span",{className:"debug-page-count",children:`SSE ${i("debug.global.streamTotal",{count:l})}`})]}),o.map((e,t)=>{let n=null!==e.holder&&e.holder===s,a=mx(e.holder,s,i),l=e.agent+e.terminal+e.fileWatch,o=mf([e.agent>0&&`${i(h4.agent)} ${e.agent}`,e.terminal>0&&`${i(h4.terminal)} ${e.terminal}`,e.fileWatch>0&&`${i(h4["file-watch"])} ${e.fileWatch}`]);return(0,r.jsxs)("div",{className:`debug-page-row${n?" is-current":""}`,title:mf([a,e.client,e.address,`SSE ${l}`,o]),children:[(0,r.jsx)("span",{className:"debug-page-icons",children:(0,r.jsx)(mW,{client:e.client})}),(0,r.jsx)("span",{className:`debug-page-client${e.client?"":" is-dim"}`,children:e.client??i("debug.pages.unknownClient")}),(0,r.jsx)("span",{className:"debug-page-address",children:e.address??"—"}),(0,r.jsx)("span",{className:"debug-page-holder",children:n?i("debug.holder.thisPage"):null!==e.holder?mo(e.holder):i("debug.holder.none")}),(0,r.jsx)("span",{className:"debug-page-count",children:l})]},`${e.holder??""}:${t}`)})]})}function m8(e){let{reply:t,detail:n,groups:s,targetSessionId:a,sources:l,ctx:o}=e,{t:d,clock:c}=o;if(!t||!c||!s)return(0,r.jsx)("div",{className:"debug-empty",children:d("debug.poll.waiting")});let u=null!==n&&s.some(e=>e.rows.some(e=>e.current&&e.id===n.sessionId)),p=null;return a?n?u||(p=(0,r.jsx)(m3,{detail:n,clock:c,ctx:o})):p=(0,r.jsx)("div",{className:"debug-empty",children:d("debug.poll.waiting")}):p=(0,r.jsx)("div",{className:"debug-empty",children:d("debug.server.noSession")}),(0,r.jsxs)("div",{className:"debug-list",children:[p,0===s.length&&!(n&&!u)&&(0,r.jsx)("div",{className:"debug-empty",children:d("debug.none")}),s.length>0&&(0,r.jsxs)("div",{className:"debug-row debug-list-head","aria-hidden":"true",children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{children:d("debug.sessions.head.session")}),(0,r.jsx)("span",{className:"debug-list-head-holders",children:d("debug.sessions.head.holders")}),(0,r.jsx)("span",{className:"debug-list-head-idle",children:d("debug.server.idle")})]}),s.map(e=>(0,r.jsxs)("div",{className:"debug-group",children:[(0,r.jsxs)("div",{className:"debug-group-head",children:[null!==e.name&&(0,r.jsx)(tv.sj,{size:11}),(0,r.jsx)("span",{className:"debug-group-name",children:e.name??d("debug.sessions.unlisted")}),(0,r.jsx)("span",{className:"debug-group-count",children:e.rows.filter(e=>null!==e.summary).length})]}),e.rows.map(e=>{let s=e.current&&n?.sessionId===e.id?n:null;return(0,r.jsxs)(i.Fragment,{children:[(0,r.jsx)(gs,{row:e,sources:l,idleTimeoutMs:t.server.idleTimeoutMs,clock:c,ctx:o,current:s?function(e,t,n){let{t:i}=n,s=e=>mi(t.age(e),i),a=e.wrapper?.idle??null,l=e.lifecycle;return{badges:(0,r.jsx)(m7,{detail:e,clock:t,ctx:n}),idleTitle:a&&null!==a.nextCheckAt?mf([`${i("debug.server.idle")} ${mr(t.remaining(a.nextCheckAt),i)}`,a.timeoutMs>0&&i("debug.server.idleTimeout",{time:mr(a.timeoutMs,i)}),null!==a.lastResetAt&&i("debug.server.idleReset",{time:s(a.lastResetAt)}),i(a.forcedByStop?"debug.server.idleForced":"debug.server.idleHint")]):void 0,startsTitle:l&&l.starts>1?m6(l,s,i):void 0}}(s,c,o):void 0}),s&&(0,r.jsx)(m5,{detail:s,clock:c,ctx:o})]},e.id)})]},e.key))]})}function m6(e,t,n){return mf([n("debug.overlay.starts",{count:e.starts}),n("debug.server.lastStart",{time:t(e.lastStartedAt)}),null!==e.lastClosedAt&&n("debug.server.lastClosed",{time:t(e.lastClosedAt)})])}function m3(e){var t;let n,{detail:i,clock:s,ctx:a}=e,{t:l,titleOf:o}=a,d=o(i.sessionId)??mo(i.sessionId),c=(n=(t=i).wrapper)?my({awaitingInput:n.awaitingInput,running:n.run.running,state:n.state}):t.starting?"starting":"none";return(0,r.jsxs)("div",{className:"debug-group",children:[(0,r.jsxs)("div",{className:"debug-row is-current has-detail is-placeholder",title:l("debug.sessions.current"),children:[(0,r.jsx)("span",{className:"debug-row-status",children:(0,r.jsx)(m_,{state:c,label:l(mv[c])})}),(0,r.jsx)("span",{className:"debug-row-title",children:(0,r.jsx)("span",{className:"debug-row-name",children:d})})]}),(0,r.jsx)(m5,{detail:i,clock:s,ctx:a,unlisted:!0})]})}function m5(e){let{detail:t,clock:n,ctx:i,unlisted:s=!1}=e,{t:a,titleOf:l}=i,o=t.wrapper,d=t.lifecycle,c=e=>mi(n.age(e),a),u=null!==o&&!o.stale,p=o?.state==="closing"?null!==o.closingAt?a("debug.server.closingSince",{time:c(o.closingAt)}):a("debug.state.closing"):null,h=o&&mf([null!=o.startedAt&&`${a("debug.server.started")} ${c(o.startedAt)}`,u&&o.lastEvent&&`${a("debug.server.lastEvent")} ${o.lastEvent.type} ${c(o.lastEvent.at)}`,u&&o.lastCommand&&`${a("debug.server.lastCommand")} ${o.lastCommand.type} ${c(o.lastCommand.at)}`]);return(0,r.jsxs)("div",{className:"debug-detail",children:[(0,r.jsxs)("div",{className:"debug-detail-line",children:[null!==l(t.sessionId)&&(0,r.jsx)("span",{className:"debug-detail-id",children:mo(t.sessionId)}),!o&&(0,r.jsx)("span",{className:"debug-note",children:a(t.starting?"debug.server.starting":"debug.server.noWrapper")}),s&&d&&d.starts>1&&(0,r.jsx)("span",{className:"debug-starts",title:m6(d,c,a),children:`↻${d.starts}`}),p&&(0,r.jsx)(mD,{tone:"warning",children:p}),o?.chatOnly&&(0,r.jsx)(mD,{tone:"dim",children:a("debug.server.chatOnly")}),o?.subagent&&(0,r.jsx)(mD,{tone:"dim",children:a("debug.server.subagent")}),o?.stale&&(0,r.jsx)(mD,{tone:"warning",children:a("debug.server.stale")}),(0,r.jsx)(m9,{detail:t,t:a}),u&&(0,r.jsx)(ge,{detail:t,t:a}),h&&(0,r.jsx)("span",{className:"debug-line",children:h})]}),u&&(0,r.jsx)(gr,{detail:t,clock:n,ctx:i}),u&&(0,r.jsx)(gi,{detail:t,clock:n,ctx:i})]})}function m9(e){let{detail:t,t:n}=e,i=t.wrapper;return null!==i&&!i.stale&&t.eventStreams.every(e=>null!==e.connectedAt)&&i.eventListeners!==t.eventStreams.length&&i?(0,r.jsx)(mD,{tone:"warning",children:`${n("debug.server.listeners")} ${i.eventListeners}`}):null}function m7(e){var t;let n,{detail:i,clock:s,ctx:a}=e,{t:l,myHolder:o}=a,d=e=>mi(s.age(e),l),c=mb([...i.eventStreams].sort((e,t)=>e.openedAt-t.openedAt),o),u=c.map(e=>{var t;let n,r=null===e.connectedAt;return{tone:r||e.droppedEvents>0?"warning":(t=e.holder,null===t?"dim":t===o?"accent":"muted"),filled:null!==e.holder&&e.holder===o,dashed:r,title:mf([mx(e.holder,o,l),e.client,e.address,null!==e.connectedAt?l("debug.server.streamConnected",{time:d(e.connectedAt)}):l("debug.server.streamStarting"),null!==e.lastWriteAt&&l("debug.server.lastWrite",{time:d(e.lastWriteAt)}),e.droppedEvents>0&&l("debug.server.dropped",{count:e.droppedEvents}),e.queuedBytes>0&&l("debug.server.queued",{size:(n=mt(e.queuedBytes))<1024?`${Math.floor(n)} B`:n<1048576?`${(n/1024).toFixed(1)} KB`:`${(n/1048576).toFixed(1)} MB`})])}}),p=i.providers,h=null===p?[{tone:"dim",title:l("debug.server.providersUnknown")}]:p.map(e=>({tone:"error"===e.active?"error":e.active?"muted":"dim",faded:!1===e.active,text:e.name,title:mf([e.name,l("error"===e.active?"debug.server.providerError":e.active?"debug.server.providerActive":"debug.server.providerInactive"),e.byFile&&l("debug.server.byFile")])}));return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(mP,{text:"SSE",items:u,cap:3,label:(t=c.map(e=>e.holder),n=t.filter(e=>null!==e&&e===o).length,`SSE: ${t.length} (${l("debug.holder.thisPage")} ${n}, ${l("debug.holder.otherPage")} ${t.length-n})`)}),(0,r.jsx)(mP,{text:l("debug.box.provider"),items:h,cap:1,label:`${l("debug.server.providers")}: ${null===p?l("debug.server.providersUnknown"):p.length}`})]})}function ge(e){let{detail:t,t:n}=e,i=t.wrapper;if(!i)return null;let s=i.run,a=[s.streaming&&n("debug.run.streaming"),s.promptRunning&&n("debug.run.prompt"),s.bashRunning&&n("debug.run.bash"),s.compacting&&n("debug.run.compacting"),s.queuedMessages>0&&n("debug.run.queued",{count:s.queuedMessages}),s.runningTools>0&&n("debug.run.tools",{count:s.runningTools}),s.mutatingCommands>0&&n("debug.run.mutating",{count:s.mutatingCommands}),s.replacement&&n("debug.run.replacement",{kind:s.replacement}),"binding"===i.extensions&&`${n("debug.server.extensions")} ${n("debug.server.extensions.binding")}`].filter(e=>!!e),l=[s.pendingPrompts>0&&n("debug.run.pending",{count:s.pendingPrompts}),s.retrying&&n("debug.run.retrying"),s.waitingForMcp&&n("debug.run.waitingForMcp"),i.awaitingInput&&i.pendingUiRequests>0&&n("debug.server.uiRequests",{count:i.pendingUiRequests}),i.awaitingInput&&i.customUis>0&&n("debug.server.customUis",{count:i.customUis})].filter(e=>!!e);return(0,r.jsxs)(r.Fragment,{children:[a.map(e=>(0,r.jsx)(mD,{tone:"dim",children:e},e)),l.map(e=>(0,r.jsx)(mD,{tone:"warning",children:e},e))]})}let gt={completed:"ok",failed:"error",aborted:"warning",interrupted:"warning"};function gn(e){let{status:t}=e;if("running"===t||"starting"===t)return(0,r.jsx)("span",{className:"debug-run-icon is-accent",children:(0,r.jsx)(tv.Nl,{size:12})});let n=gt[t];return n?(0,r.jsx)("span",{className:`debug-run-icon is-${n}`,children:(0,r.jsx)(hZ,{status:t})}):(0,r.jsx)("span",{className:"debug-run-icon",children:(0,r.jsx)("span",{className:"debug-status-ring is-alive"})})}function gr(e){let{detail:t,clock:n,ctx:i}=e,{t:s,titleOf:a}=i,l=t.subagents;if(!l.active&&0===l.runs.length&&0===l.notifications.length)return null;let o=e=>mi(n.age(e),s);return(0,r.jsxs)("div",{className:"debug-block",children:[(0,r.jsxs)("div",{className:"debug-subhead",children:[(0,r.jsx)("span",{children:s("debug.server.subagents")}),l.active&&(0,r.jsx)(mD,{tone:"accent",children:s("debug.server.subagentsActive")})]}),l.runs.map((e,t)=>(0,r.jsxs)("div",{className:"debug-run-line",children:[(0,r.jsx)(gn,{status:e.status}),(0,r.jsx)("span",{className:"debug-run-name",children:a(e.sessionId)??e.profile??mo(e.sessionId)}),(0,r.jsx)("span",{className:"debug-line",children:mf([me(e.status,h9,s),e.background&&s("debug.server.background"),e.resumed&&s("debug.server.resumed"),null!==e.dispatchedAt&&o(e.dispatchedAt)])}),e.abortRequested&&(0,r.jsx)(mD,{tone:"warning",children:s("debug.server.abortRequested")}),e.mcpWaiting&&(0,r.jsx)(mD,{tone:"warning",children:s("debug.run.waitingForMcp")})]},`${e.sessionId}:${t}`)),l.notifications.map((e,t)=>(0,r.jsx)("div",{className:"debug-line is-warning",children:mf([s("debug.server.notifying",{parent:mo(e.parentSessionId)}),null!==e.since&&o(e.since)])},`${e.sessionId}:${t}`))]})}function gi(e){let{detail:t,clock:n,ctx:i}=e,{t:s}=i,a=t.mcp;if(!a||0===a.servers.length&&0===a.problems)return null;let l=null!==a.idleReleaseAt&&a.idleMs>0?n.remaining(a.idleReleaseAt):null;return(0,r.jsxs)("div",{className:"debug-block",children:[(0,r.jsxs)("div",{className:"debug-pills",children:[(0,r.jsx)("span",{className:`debug-subhead${a.active?"":" is-dim"}`,children:"MCP"}),a.servers.map((e,t)=>{let{tone:n,filled:i}=e.hasError||"failed"===e.state||"conflict"===e.state?{tone:"error",filled:!0}:e.released?{tone:"dim",filled:!1}:"connected"===e.state?{tone:"ok",filled:!0}:"connecting"===e.state?{tone:"warning",filled:!1}:"needs-auth"===e.state||"not-trusted"===e.state||"disconnected"===e.state?{tone:"warning",filled:!0}:{tone:"muted",filled:!1},a=me(e.state,o$,s),l=mf([`${e.name} (${e.scope})`,a,e.released&&s("debug.server.mcpReleased"),e.hasError&&s("debug.server.mcpError")]),o="connected"!==e.state?a:e.hasError?s("debug.server.mcpError"):null;return(0,r.jsxs)("span",{className:"debug-pill",role:"img","aria-label":l,title:l,children:[(0,r.jsx)(mF,{tone:n,ring:!i}),(0,r.jsx)("span",{className:e.released?"is-dim":void 0,children:e.name}),o&&(0,r.jsx)("span",{className:"debug-pill-state",children:`\xb7 ${o}`})]},`${e.scope}:${e.name}:${t}`)}),a.problems>0&&(0,r.jsx)(mD,{tone:"warning",children:s("debug.server.mcpProblems",{count:a.problems})}),a.disposed&&(0,r.jsx)(mD,{tone:"dim",children:s("debug.server.mcpDisposed")})]}),null!==l&&(0,r.jsxs)("div",{className:"debug-idle-row",children:[(0,r.jsx)(mB,{fraction:mj(l,a.idleMs)??0,tone:"dim",width:80}),(0,r.jsx)("span",{className:"debug-value is-muted",children:s("debug.server.mcpRelease",{time:ml(l,s)})})]})]})}function gs(e){var t;let n,i,{row:s,sources:a,idleTimeoutMs:l,clock:o,ctx:d,current:c}=e,{t:u}=d,p=s.summary,h=s.info?ty(s.info):mo(s.id),m=p&&null!==p.nextIdleCheckAt?o.remaining(p.nextIdleCheckAt):null,g=p?my(p):null,f=["debug-row",1===s.depth&&"is-sub",s.current&&"is-current",c&&"has-detail",s.placeholder&&"is-placeholder"].filter(Boolean).join(" ");return(0,r.jsxs)("div",{className:f,title:mf([s.current&&u("debug.sessions.current"),p?(n=[p.subagent?u("debug.overlay.subagentId",{id:mo(p.sessionId)}):mo(p.sessionId),u(h3[p.state]??h3.none)],p.running&&n.push(u("debug.overlay.running")),p.awaitingInput&&n.push(u("debug.overlay.awaiting")),p.eventStreams>0&&n.push(u("debug.overlay.streams",{count:p.eventStreams})),p.providers>0&&n.push(u("debug.overlay.providers",{count:p.providers})),null!==m&&n.push(u(p.forcedByStop?"debug.overlay.closesIn":"debug.overlay.idle",{time:(i=mt(m))<6e4?u("debug.duration.seconds",{count:Math.floor(i/1e3)}):i<36e5?u("debug.duration.minutes",{count:Math.floor(i/6e4)}):i<864e5?u("debug.duration.hours",{count:Math.floor(i/36e5)}):u("debug.duration.days",{count:Math.floor(i/864e5)})})),p.starts>1&&n.push(u("debug.overlay.starts",{count:p.starts})),n.join(" \xb7 ")):h]),children:[(0,r.jsx)("span",{className:"debug-row-status",children:g&&(0,r.jsx)(m_,{state:g,label:u(mv[g])})}),(0,r.jsxs)("span",{className:"debug-row-title",children:[1===s.depth&&(0,r.jsx)("span",{className:"debug-row-branch","aria-hidden":"true"}),(0,r.jsx)("span",{className:"debug-row-name",children:h}),p&&p.starts>1&&(0,r.jsx)("span",{className:"debug-row-starts",title:c?.startsTitle,children:`↻${p.starts}`})]}),p&&(0,r.jsx)(ga,{summary:p,mine:(t=s.id,a.filter(e=>"agent"===e.kind&&e.label===t).length),remaining:m,idleTimeoutMs:l,t:u,badges:c?.badges,idleTitle:c?.idleTitle})]})}function ga(e){let{summary:t,mine:n,remaining:i,idleTimeoutMs:s,t:a,badges:l,idleTitle:o}=e,d=a("debug.overlay.streams",{count:t.eventStreams}),c=Math.min(t.eventStreams,n),u=Array.from({length:t.eventStreams},(e,t)=>t<c?{tone:"accent",filled:!0,title:d}:{tone:"muted",title:d}),p=a("debug.overlay.providers",{count:t.providers}),h=Array.from({length:t.providers},()=>({tone:"muted",title:p})),m=null!==i&&(s>0||t.forcedByStop),g=t.forcedByStop?"warning":"dim",f=null!==i?a("debug.overlay.closesIn",{time:ms(i,a)}):void 0;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"debug-row-badges",children:l??(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(mP,{text:"SSE",items:u,cap:3,label:d}),(0,r.jsx)(mP,{text:a("debug.box.provider"),items:h,cap:1,label:p})]})}),(0,r.jsx)("span",{className:`debug-row-idle is-${g}`,title:o,children:m&&null!==i&&(0,r.jsxs)(r.Fragment,{children:[s>0&&(0,r.jsx)(mB,{fraction:mj(i,s)??0,tone:g,width:36,height:3,className:"debug-row-idle-bar"}),t.forcedByStop&&(0,r.jsx)("span",{className:"debug-row-forced",role:"img","aria-label":f,title:f}),(0,r.jsx)("span",{className:"debug-row-idle-text",children:ms(i,a)})]})})]})}let gl=`
202
+ .debug-panel {
203
+ --dbg-ok: #16a34a;
204
+ --dbg-warn: #d97706;
205
+ --dbg-err: #ef4444;
206
+ container-type: inline-size;
207
+ container-name: debug-panel;
208
+ display: flex;
209
+ max-height: min(720px, 80dvh);
210
+ flex-direction: column;
211
+ background: var(--bg-panel);
212
+ border-bottom: 1px solid var(--border);
213
+ box-shadow: 0 10px 28px rgba(0,0,0,0.10);
214
+ color: var(--text);
215
+ }
216
+ .debug-panel .is-ok { color: var(--dbg-ok); }
217
+ .debug-panel .is-warning { color: var(--dbg-warn); }
218
+ .debug-panel .is-error { color: var(--dbg-err); }
219
+ .debug-panel .is-accent { color: var(--accent); }
220
+ .debug-panel .is-muted { color: var(--text-muted); }
221
+ .debug-panel .is-dim { color: var(--text-dim); }
222
+ .debug-panel-header {
223
+ display: flex;
224
+ flex-shrink: 0;
225
+ align-items: center;
226
+ gap: 12px;
227
+ min-width: 0;
228
+ padding: 8px 16px;
229
+ border-bottom: 1px solid var(--border);
230
+ font-size: 12px;
231
+ }
232
+ .debug-panel-heading {
233
+ flex-shrink: 0;
234
+ color: var(--text);
235
+ cursor: help;
236
+ font-weight: 700;
237
+ }
238
+ .debug-panel-status {
239
+ display: inline-flex;
240
+ min-width: 0;
241
+ align-items: center;
242
+ gap: 6px;
243
+ font-variant-numeric: tabular-nums;
244
+ }
245
+ .debug-panel-status svg {
246
+ flex-shrink: 0;
247
+ }
248
+ .debug-panel-status-text {
249
+ min-width: 0;
250
+ overflow: hidden;
251
+ text-overflow: ellipsis;
252
+ white-space: nowrap;
253
+ }
254
+ .debug-panel-copy {
255
+ flex-shrink: 0;
256
+ margin-left: auto;
257
+ padding: 2px 8px;
258
+ border: 1px solid var(--border);
259
+ border-radius: 4px;
260
+ background: transparent;
261
+ color: var(--text-muted);
262
+ cursor: pointer;
263
+ font-size: 11px;
264
+ }
265
+ .debug-panel-copy:hover {
266
+ background: var(--bg-hover);
267
+ color: var(--text);
268
+ }
269
+ .debug-panel-scroll {
270
+ display: flex;
271
+ min-height: 0;
272
+ flex: 1;
273
+ flex-direction: column;
274
+ gap: 12px;
275
+ overflow: auto;
276
+ padding: 10px 16px 12px;
277
+ font-size: 12px;
278
+ line-height: 1.5;
279
+ }
280
+ .debug-section-title {
281
+ color: var(--text);
282
+ font-size: 11px;
283
+ font-weight: 700;
284
+ }
285
+ .debug-empty,
286
+ .debug-note {
287
+ color: var(--text-dim);
288
+ font-size: 12px;
289
+ }
290
+ .debug-label {
291
+ color: var(--text-dim);
292
+ font-size: 11px;
293
+ white-space: nowrap;
294
+ }
295
+ .debug-value {
296
+ font-family: var(--font-mono);
297
+ font-size: 11px;
298
+ font-variant-numeric: tabular-nums;
299
+ white-space: nowrap;
300
+ }
301
+ .debug-line {
302
+ color: var(--text-dim);
303
+ font-family: var(--font-mono);
304
+ font-size: 11px;
305
+ font-variant-numeric: tabular-nums;
306
+ overflow-wrap: anywhere;
307
+ }
308
+ .debug-panel .debug-line.is-warning {
309
+ color: var(--dbg-warn);
310
+ }
311
+
312
+ .debug-issues {
313
+ display: flex;
314
+ flex-direction: column;
315
+ gap: 4px;
316
+ margin: 0;
317
+ padding: 0;
318
+ list-style: none;
319
+ }
320
+ .debug-issue {
321
+ display: flex;
322
+ align-items: flex-start;
323
+ gap: 6px;
324
+ padding: 4px 8px;
325
+ border-left: 2px solid currentColor;
326
+ border-radius: 4px;
327
+ background: color-mix(in srgb, currentColor 8%, var(--bg-panel));
328
+ }
329
+ .debug-issue > svg {
330
+ flex-shrink: 0;
331
+ margin-top: 3px;
332
+ }
333
+ .debug-issue-text {
334
+ min-width: 0;
335
+ color: var(--text);
336
+ font-size: 12px;
337
+ overflow-wrap: anywhere;
338
+ }
339
+
340
+ /* Three columns when the panel is wide: the page's as wide as its table, the server's and the
341
+ sessions' each capped, so names never stretch and push the badges to the far edge. */
342
+ .debug-cols {
343
+ display: grid;
344
+ grid-template-areas: "page server sessions";
345
+ grid-template-columns: minmax(320px, max-content) minmax(340px, 480px) minmax(360px, 560px);
346
+ gap: 0;
347
+ }
348
+ .debug-col {
349
+ display: flex;
350
+ min-width: 0;
351
+ flex-direction: column;
352
+ gap: 8px;
353
+ }
354
+ .debug-col-page {
355
+ grid-area: page;
356
+ }
357
+ .debug-col-server {
358
+ grid-area: server;
359
+ }
360
+ .debug-col-sessions {
361
+ grid-area: sessions;
362
+ }
363
+ .debug-col-server,
364
+ .debug-col-sessions {
365
+ margin-left: 20px;
366
+ padding-left: 20px;
367
+ border-left: 1px solid var(--border);
368
+ }
369
+ .debug-list,
370
+ .debug-block {
371
+ display: flex;
372
+ min-width: 0;
373
+ flex-direction: column;
374
+ gap: 6px;
375
+ }
376
+ .debug-block {
377
+ gap: 4px;
378
+ }
379
+ .debug-col-head {
380
+ display: flex;
381
+ min-height: 18px;
382
+ align-items: center;
383
+ gap: 8px;
384
+ }
385
+ /* Name, scale, value; a measure's details span the row below it. */
386
+ /* As wide as the column (the details get the room), never so wide a value drifts off its bar. */
387
+ .debug-measures {
388
+ display: grid;
389
+ max-width: 400px;
390
+ grid-template-columns: max-content minmax(max-content, 1fr) max-content;
391
+ align-items: center;
392
+ gap: 4px 10px;
393
+ }
394
+ /* Numbers line up on the right, as the count in the column's head does. */
395
+ .debug-measures > .debug-value {
396
+ justify-self: end;
397
+ text-align: right;
398
+ }
399
+ .debug-measure-name {
400
+ display: inline-flex;
401
+ align-items: center;
402
+ gap: 6px;
403
+ }
404
+ .debug-measure-name[title] {
405
+ cursor: help;
406
+ }
407
+ /* Wrapped to the table's width rather than widening it (a percentage min-width adds nothing to
408
+ the columns' sizes). */
409
+ .debug-measure-sub,
410
+ .debug-measure-empty {
411
+ grid-column: 2 / -1;
412
+ width: 0;
413
+ min-width: 100%;
414
+ color: var(--text-dim);
415
+ font-family: var(--font-mono);
416
+ font-size: 11px;
417
+ font-variant-numeric: tabular-nums;
418
+ overflow-wrap: anywhere;
419
+ }
420
+ .debug-measure-sub {
421
+ margin-top: -4px;
422
+ }
423
+ .debug-measure-sub > .debug-dot {
424
+ margin-right: 6px;
425
+ vertical-align: 0;
426
+ }
427
+ .debug-measure-empty {
428
+ font-family: inherit;
429
+ font-size: 12px;
430
+ }
431
+ .debug-chips {
432
+ display: flex;
433
+ flex-wrap: wrap;
434
+ gap: 4px;
435
+ }
436
+ .debug-chip {
437
+ display: inline-flex;
438
+ align-items: center;
439
+ padding: 0 6px;
440
+ border: 1px solid color-mix(in srgb, currentColor 35%, transparent);
441
+ border-radius: 9px;
442
+ font-family: var(--font-mono);
443
+ font-size: 11px;
444
+ line-height: 16px;
445
+ white-space: nowrap;
446
+ }
447
+
448
+ /* A boxed word: "SSE", a provider's name, File, Term. Filled is this page's own. */
449
+ .debug-badge {
450
+ display: inline-flex;
451
+ height: 16px;
452
+ box-sizing: border-box;
453
+ flex-shrink: 0;
454
+ align-items: center;
455
+ padding: 0 4px;
456
+ border: 1px solid currentColor;
457
+ border-radius: 3px;
458
+ background-clip: padding-box;
459
+ font: 600 10px/14px var(--font-mono);
460
+ white-space: nowrap;
461
+ }
462
+ .debug-panel .debug-badge.is-filled {
463
+ border-color: var(--accent);
464
+ background-color: var(--accent);
465
+ color: var(--accent-contrast);
466
+ }
467
+ /* This page's, amber: a stream of its own still starting or dropping events. */
468
+ .debug-panel .debug-badge.is-filled.is-warning {
469
+ border-color: var(--dbg-warn);
470
+ background-color: var(--dbg-warn);
471
+ color: var(--bg-panel);
472
+ }
473
+ .debug-badge.is-dashed {
474
+ border-style: dashed;
475
+ }
476
+ .debug-badge.is-faded {
477
+ opacity: 0.45;
478
+ }
479
+ /* A provider's name: twelve characters, then an ellipsis (a block, so the ellipsis applies). */
480
+ .debug-badge.is-name {
481
+ display: inline-block;
482
+ max-width: calc(12ch + 10px);
483
+ overflow: hidden;
484
+ text-overflow: ellipsis;
485
+ }
486
+ /* A page's browser and system marks. */
487
+ .debug-client {
488
+ display: inline-flex;
489
+ align-items: center;
490
+ gap: 3px;
491
+ }
492
+ .debug-client svg {
493
+ display: block;
494
+ flex-shrink: 0;
495
+ }
496
+
497
+ /* The connected pages: marks, browser and system, address, page, its stream count. */
498
+ .debug-pages {
499
+ display: flex;
500
+ flex-direction: column;
501
+ }
502
+ .debug-page-row {
503
+ position: relative;
504
+ display: grid;
505
+ min-height: 22px;
506
+ grid-template-columns: 30px minmax(0, 1.2fr) minmax(0, 1fr) minmax(0, 1fr) 32px;
507
+ align-items: center;
508
+ column-gap: 8px;
509
+ padding: 0 4px;
510
+ border-radius: 4px;
511
+ font-size: 11px;
512
+ }
513
+ .debug-page-row.debug-list-head {
514
+ min-height: 18px;
515
+ grid-template-columns: minmax(0, 1fr) auto;
516
+ color: var(--text-dim);
517
+ font-size: 10px;
518
+ }
519
+ .debug-page-row.is-current {
520
+ background: var(--bg-selected);
521
+ }
522
+ .debug-page-row.is-current::before {
523
+ content: "";
524
+ position: absolute;
525
+ top: 4px;
526
+ left: 0;
527
+ width: 3px;
528
+ height: 14px;
529
+ border-radius: 0 2px 2px 0;
530
+ background: var(--accent);
531
+ }
532
+ .debug-page-icons {
533
+ display: inline-flex;
534
+ padding-left: 4px;
535
+ color: var(--text-muted);
536
+ }
537
+ .debug-page-icons svg {
538
+ width: 12px;
539
+ height: 12px;
540
+ }
541
+ .debug-page-client,
542
+ .debug-page-address,
543
+ .debug-page-holder {
544
+ min-width: 0;
545
+ overflow: hidden;
546
+ text-overflow: ellipsis;
547
+ white-space: nowrap;
548
+ }
549
+ .debug-page-client {
550
+ color: var(--text);
551
+ }
552
+ .debug-page-address {
553
+ color: var(--text-muted);
554
+ font-family: var(--font-mono);
555
+ }
556
+ .debug-page-holder {
557
+ color: var(--text-dim);
558
+ }
559
+ .debug-page-count {
560
+ justify-self: end;
561
+ color: var(--text-muted);
562
+ font-family: var(--font-mono);
563
+ font-variant-numeric: tabular-nums;
564
+ white-space: nowrap;
565
+ }
566
+ .debug-list-head .debug-page-count {
567
+ color: var(--text-dim);
568
+ }
569
+ .debug-run {
570
+ display: inline-flex;
571
+ flex-wrap: wrap;
572
+ align-items: flex-start;
573
+ gap: 3px;
574
+ vertical-align: middle;
575
+ }
576
+ .debug-run-more {
577
+ color: var(--text-dim);
578
+ font-family: var(--font-mono);
579
+ font-size: 10px;
580
+ line-height: 16px;
581
+ }
582
+
583
+ .debug-meter-row {
584
+ display: flex;
585
+ flex-wrap: wrap;
586
+ align-items: center;
587
+ gap: 8px;
588
+ }
589
+ .debug-meter {
590
+ display: flex;
591
+ min-height: 18px;
592
+ flex-wrap: wrap;
593
+ align-items: center;
594
+ gap: 3px;
595
+ }
596
+ .debug-slot {
597
+ display: inline-flex;
598
+ min-width: 32px;
599
+ height: 18px;
600
+ box-sizing: border-box;
601
+ align-items: center;
602
+ justify-content: center;
603
+ border-radius: 3px;
604
+ }
605
+ .debug-slot.is-empty {
606
+ border: 1px dotted var(--border);
607
+ }
608
+ .debug-meter.is-inline .debug-slot {
609
+ min-width: 0;
610
+ height: 16px;
611
+ }
612
+ .debug-meter-overflow {
613
+ margin-left: 2px;
614
+ font-family: var(--font-mono);
615
+ font-size: 11px;
616
+ }
617
+
618
+ .debug-spark {
619
+ display: inline-flex;
620
+ width: 120px;
621
+ height: 15px;
622
+ }
623
+ .debug-spark svg {
624
+ display: block;
625
+ }
626
+ .debug-bar {
627
+ position: relative;
628
+ display: inline-block;
629
+ flex-shrink: 0;
630
+ overflow: hidden;
631
+ border-radius: 2px;
632
+ background: var(--border);
633
+ vertical-align: middle;
634
+ }
635
+ .debug-bar-fill {
636
+ position: absolute;
637
+ top: 0;
638
+ bottom: 0;
639
+ left: 0;
640
+ background: currentColor;
641
+ }
642
+ .debug-bar-notch {
643
+ position: absolute;
644
+ top: 0;
645
+ bottom: 0;
646
+ width: 1px;
647
+ background: var(--bg-panel);
648
+ }
649
+ .debug-dot {
650
+ display: inline-block;
651
+ width: 8px;
652
+ height: 8px;
653
+ flex-shrink: 0;
654
+ border-radius: 50%;
655
+ background: currentColor;
656
+ }
657
+ .debug-dot.is-ring {
658
+ background: transparent;
659
+ box-shadow: inset 0 0 0 1.5px currentColor;
660
+ }
661
+
662
+ .debug-status {
663
+ display: inline-flex;
664
+ width: 14px;
665
+ height: 14px;
666
+ flex-shrink: 0;
667
+ align-items: center;
668
+ justify-content: center;
669
+ }
670
+ .debug-status-ring {
671
+ width: 7px;
672
+ height: 7px;
673
+ box-sizing: border-box;
674
+ border: 1.5px solid var(--text-dim);
675
+ border-radius: 50%;
676
+ }
677
+ .debug-status-ring.is-closing {
678
+ border-style: dashed;
679
+ border-color: var(--dbg-warn);
680
+ }
681
+ .debug-status-ring.is-none {
682
+ border-style: dotted;
683
+ border-color: var(--text-dim);
684
+ }
685
+ .debug-status-ring.is-starting {
686
+ border-style: dashed;
687
+ }
688
+
689
+ /* The chat's details under its row, from the title's edge; the row's tint carried down. */
690
+ .debug-detail {
691
+ display: flex;
692
+ min-width: 0;
693
+ flex-direction: column;
694
+ gap: 4px;
695
+ margin-bottom: 2px;
696
+ padding: 0 4px 5px 24px;
697
+ border-radius: 0 0 4px 4px;
698
+ background: var(--bg-selected);
699
+ }
700
+ .debug-detail-line {
701
+ display: flex;
702
+ min-width: 0;
703
+ flex-wrap: wrap;
704
+ align-items: center;
705
+ gap: 2px 6px;
706
+ }
707
+ .debug-detail-id,
708
+ .debug-starts {
709
+ color: var(--text-dim);
710
+ font-family: var(--font-mono);
711
+ font-size: 11px;
712
+ }
713
+ .debug-idle-row {
714
+ display: flex;
715
+ flex-wrap: wrap;
716
+ align-items: center;
717
+ gap: 4px 8px;
718
+ }
719
+ .debug-subhead {
720
+ display: flex;
721
+ align-items: center;
722
+ gap: 6px;
723
+ color: var(--text);
724
+ font-size: 11px;
725
+ font-weight: 700;
726
+ }
727
+ .debug-panel .debug-subhead.is-dim {
728
+ color: var(--text-dim);
729
+ }
730
+ .debug-run-line {
731
+ display: flex;
732
+ flex-wrap: wrap;
733
+ align-items: center;
734
+ gap: 2px 6px;
735
+ }
736
+ .debug-run-icon {
737
+ display: inline-flex;
738
+ width: 12px;
739
+ height: 12px;
740
+ flex-shrink: 0;
741
+ align-items: center;
742
+ justify-content: center;
743
+ }
744
+ .debug-run-icon svg {
745
+ width: 12px;
746
+ height: 12px;
747
+ }
748
+ .debug-run-name {
749
+ min-width: 0;
750
+ overflow: hidden;
751
+ color: var(--text);
752
+ font-size: 12px;
753
+ text-overflow: ellipsis;
754
+ white-space: nowrap;
755
+ }
756
+ .debug-pills {
757
+ display: flex;
758
+ flex-wrap: wrap;
759
+ align-items: center;
760
+ gap: 4px 10px;
761
+ }
762
+ .debug-pill {
763
+ display: inline-flex;
764
+ align-items: center;
765
+ gap: 4px;
766
+ font-size: 11px;
767
+ }
768
+ .debug-pill-state {
769
+ color: var(--text-dim);
770
+ white-space: nowrap;
771
+ }
772
+
773
+ .debug-group {
774
+ display: flex;
775
+ flex-direction: column;
776
+ }
777
+ .debug-group-head {
778
+ display: flex;
779
+ min-height: 22px;
780
+ align-items: center;
781
+ gap: 5px;
782
+ color: var(--text-dim);
783
+ font-size: 11px;
784
+ }
785
+ .debug-group-head svg {
786
+ flex-shrink: 0;
787
+ }
788
+ .debug-group-name {
789
+ min-width: 0;
790
+ overflow: hidden;
791
+ font-weight: 600;
792
+ text-overflow: ellipsis;
793
+ white-space: nowrap;
794
+ }
795
+ .debug-group-count {
796
+ font-family: var(--font-mono);
797
+ font-size: 10px;
798
+ font-variant-numeric: tabular-nums;
799
+ }
800
+ .debug-row {
801
+ display: grid;
802
+ min-height: 24px;
803
+ /* The title keeps room for a few characters; the badges wrap before they take it all. */
804
+ grid-template-columns: 14px minmax(96px, 1fr) auto 104px;
805
+ align-items: center;
806
+ column-gap: 6px;
807
+ padding: 0 4px;
808
+ border-radius: 4px;
809
+ }
810
+ .debug-row.debug-list-head {
811
+ min-height: 18px;
812
+ color: var(--text-dim);
813
+ font-size: 10px;
814
+ }
815
+ /* At the end of their columns, spilling left rather than out of the row when wider. */
816
+ .debug-list-head-holders,
817
+ .debug-list-head-idle {
818
+ justify-self: end;
819
+ white-space: nowrap;
820
+ }
821
+ .debug-row.is-current {
822
+ position: relative;
823
+ background: var(--bg-selected);
824
+ }
825
+ .debug-row.has-detail {
826
+ border-radius: 4px 4px 0 0;
827
+ }
828
+ /* The sidebar's mark of the selected session (app/sidebar.css): a short bar on the left edge,
829
+ on the first line however many lines the row takes. */
830
+ .debug-row.is-current::before {
831
+ content: "";
832
+ position: absolute;
833
+ top: 5px;
834
+ left: 0;
835
+ width: 3px;
836
+ height: 14px;
837
+ border-radius: 0 2px 2px 0;
838
+ background: var(--accent);
839
+ }
840
+ .debug-row-status {
841
+ display: inline-flex;
842
+ width: 14px;
843
+ justify-content: center;
844
+ }
845
+ .debug-row-title {
846
+ position: relative;
847
+ display: flex;
848
+ min-width: 0;
849
+ align-items: center;
850
+ gap: 4px;
851
+ }
852
+ .debug-row.is-sub .debug-row-title {
853
+ padding-left: 16px;
854
+ }
855
+ .debug-row-branch {
856
+ position: absolute;
857
+ top: calc(50% - 8px);
858
+ left: 4px;
859
+ width: 8px;
860
+ height: 8px;
861
+ border-bottom: 1px solid var(--border);
862
+ border-left: 1px solid var(--border);
863
+ }
864
+ .debug-row-name {
865
+ min-width: 0;
866
+ overflow: hidden;
867
+ color: var(--text);
868
+ font-size: 12px;
869
+ text-overflow: ellipsis;
870
+ white-space: nowrap;
871
+ }
872
+ .debug-row.is-sub .debug-row-name {
873
+ color: var(--text-muted);
874
+ }
875
+ .debug-row.is-current .debug-row-name {
876
+ font-weight: 600;
877
+ }
878
+ .debug-row.is-placeholder .debug-row-name {
879
+ color: var(--text-dim);
880
+ }
881
+ .debug-row-starts {
882
+ flex-shrink: 0;
883
+ color: var(--text-dim);
884
+ font-family: var(--font-mono);
885
+ font-size: 10px;
886
+ }
887
+ .debug-row-badges {
888
+ display: flex;
889
+ min-width: 0;
890
+ flex-wrap: wrap;
891
+ justify-content: flex-end;
892
+ align-items: center;
893
+ gap: 3px 8px;
894
+ }
895
+ .debug-row-idle {
896
+ display: flex;
897
+ align-items: center;
898
+ justify-content: flex-end;
899
+ gap: 4px;
900
+ }
901
+ .debug-row-forced {
902
+ width: 6px;
903
+ height: 6px;
904
+ flex-shrink: 0;
905
+ border-radius: 1px;
906
+ background: currentColor;
907
+ }
908
+ .debug-row-idle-text {
909
+ min-width: 3ch;
910
+ font-family: var(--font-mono);
911
+ font-size: 11px;
912
+ font-variant-numeric: tabular-nums;
913
+ text-align: right;
914
+ }
915
+
916
+ /* The server's totals beside its title. */
917
+ .debug-server-head {
918
+ flex-wrap: wrap;
919
+ gap: 4px 14px;
920
+ color: var(--text-dim);
921
+ font-size: 11px;
922
+ }
923
+ .debug-server-item {
924
+ display: inline-flex;
925
+ flex-wrap: wrap;
926
+ align-items: center;
927
+ gap: 3px 4px;
928
+ }
929
+
930
+ /* Narrower: the sessions under the server's pages, one border down both; the page's column
931
+ beside them, its height going to the sessions' row rather than opening a gap under the pages. */
932
+ @container debug-panel (max-width: 1239px) {
933
+ .debug-cols {
934
+ grid-template-areas: "page server" "page sessions";
935
+ grid-template-columns: minmax(320px, max-content) minmax(0, 560px);
936
+ grid-template-rows: auto 1fr;
937
+ }
938
+ .debug-col-sessions {
939
+ padding-top: 10px;
940
+ }
941
+ }
942
+ @container debug-panel (max-width: 760px) {
943
+ .debug-cols {
944
+ grid-template-areas: "page" "server" "sessions";
945
+ grid-template-columns: minmax(0, 1fr);
946
+ grid-template-rows: none;
947
+ }
948
+ .debug-col-server {
949
+ margin-top: 10px;
950
+ padding-top: 10px;
951
+ border-top: 1px solid var(--border);
952
+ }
953
+ .debug-col-server,
954
+ .debug-col-sessions {
955
+ margin-left: 0;
956
+ padding-left: 0;
957
+ border-left: 0;
958
+ }
959
+ }
960
+ @container debug-panel (max-width: 520px) {
961
+ .debug-detail-id {
962
+ display: none;
963
+ }
964
+ .debug-row {
965
+ grid-template-columns: 14px minmax(0, 1fr) 64px;
966
+ }
967
+ /* The badges take a line of their own under the title, which keeps its width. */
968
+ .debug-row-badges {
969
+ grid-column: 2 / -1;
970
+ grid-row: 2;
971
+ flex-wrap: wrap;
972
+ justify-content: flex-start;
973
+ padding-bottom: 4px;
974
+ }
975
+ .debug-row.is-sub .debug-row-badges {
976
+ padding-left: 16px;
977
+ }
978
+ .debug-row-badges:empty,
979
+ .debug-list-head-holders,
980
+ .debug-page-holder {
981
+ display: none;
982
+ }
983
+ .debug-page-row {
984
+ grid-template-columns: 30px minmax(0, 1fr) minmax(0, 1fr) 24px;
985
+ }
986
+ .debug-row-idle-bar {
987
+ display: none;
988
+ }
989
+ .debug-server-head .debug-section-title {
990
+ flex-basis: 100%;
991
+ }
992
+ }
993
+ `,go=["var(--usage-c1)","var(--usage-c2)","var(--usage-c3)","var(--usage-c4)","var(--usage-c5)","var(--usage-c6)"];function gd(e){return go[e%go.length]}function gc(e){let{daily:t,models:n,formatCount:i,title:s}=e;if(0===t.length)return null;let a=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5;if(e<=0)return[];if(e<=t)return Array.from({length:e},(e,t)=>t);let n=new Set([0,e-1]);for(let r=1;r<t-1;r++)n.add(Math.round(r*(e-1)/(t-1)));return[...n].sort((e,t)=>e-t)}(t.length),l=Math.max(...t.map(e=>e.total),1),o=720/t.length+1,d=e=>8+(t.length>1?704/(t.length-1):0)*e,c=n.map((e,n)=>{let r=t.map(t=>t.models[e]??0),i=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;if(0===e.length)return[];let i=Math.max(...e,1),s=e.length>1?(t-2*r)/(e.length-1):0;return e.map((e,t)=>({x:r+s*t,y:n-r-e/i*(n-2*r)}))}(r,720,96,8);return{model:e,color:gd(n),path:function(e){if(0===e.length)return"";if(1===e.length)return`M ${e[0].x.toFixed(1)} ${e[0].y.toFixed(1)}`;let t=e.length,n=[];for(let r=0;r<t-1;r++){let t=e[r+1].x-e[r].x;n.push(0!==t?(e[r+1].y-e[r].y)/t:0)}let r=Array(t).fill(0);r[0]=n[0],r[t-1]=n[t-2];for(let e=1;e<t-1;e++){let t=n[e-1],i=n[e];t*i<=0?r[e]=0:r[e]=Math.min((t+i)/2,3*Math.min(Math.abs(t),Math.abs(i)))*(t<0?-1:1)}let i=`M ${e[0].x.toFixed(1)} ${e[0].y.toFixed(1)}`;for(let n=0;n<t-1;n++){let t=e[n+1].x-e[n].x,s=e[n].x+t/3,a=e[n].y+r[n]*t/3,l=e[n+1].x-t/3,o=e[n+1].y-r[n+1]*t/3;i+=` C ${s.toFixed(1)} ${a.toFixed(1)} ${l.toFixed(1)} ${o.toFixed(1)} ${e[n+1].x.toFixed(1)} ${e[n+1].y.toFixed(1)}`}return i}(i),some:r.some(e=>e>0)}});return(0,r.jsxs)("div",{className:"usage-trend",children:[(0,r.jsx)("div",{className:"usage-trend-legend",role:"list",children:c.filter(e=>e.some).map(e=>(0,r.jsxs)("span",{className:"usage-trend-legend-item",role:"listitem",children:[(0,r.jsx)("span",{className:"usage-trend-legend-dot",style:{backgroundColor:e.color}}),(0,r.jsx)("span",{className:"usage-trend-legend-label",title:e.model,children:e.model})]},e.model))}),(0,r.jsx)("span",{className:"usage-trend-max",children:i(l)}),(0,r.jsxs)("svg",{viewBox:"0 0 720 96",className:"usage-trend-svg",role:"img","aria-label":s,preserveAspectRatio:"none",children:[c.filter(e=>e.some).map(e=>(0,r.jsx)("path",{d:e.path,className:"usage-trend-line",stroke:e.color,fill:"none"},e.model)),t.length<=400?t.map((e,t)=>(0,r.jsx)("rect",{x:d(t)-o/2,y:0,width:o,height:96,fill:"transparent",children:(0,r.jsx)("title",{children:`${e.date} \xb7 ${i(e.total)}`})},e.date)):null]}),(0,r.jsx)("div",{className:"usage-trend-labels",children:a.map(e=>{let n=d(e)/720*100,i=0===e?"start":e===t.length-1?"end":"center";return(0,r.jsx)("span",{className:"usage-trend-label",style:{left:`${n}%`,transform:"center"===i?"translateX(-50%)":"end"===i?"translateX(-100%)":void 0,textAlign:i},children:t[e].date.slice(5)},e)})})]})}let gu=2*Math.PI*44;function gp(e){let{models:t,otherLabel:n,formatCount:i,tokenUnit:s}=e,a=function(e,t){let n=e.filter(e=>e.total>0);if(n.length<=6)return n.map((e,t)=>({key:e.model,label:e.model,value:e.total,share:0,color:gd(t)}));let r=n.slice(0,5),i=n.slice(5).reduce((e,t)=>e+t.total,0),s=r.map((e,t)=>({key:e.model,label:e.model,value:e.total,share:0,color:gd(t)}));return s.push({key:"__other__",label:t,value:i,share:0,color:gd(5)}),s}(t,n);if(0===a.length)return null;let l=a.reduce((e,t)=>e+t.value,0),o=function(e,t){let n=e.reduce((e,t)=>e+t.value,0),r=[],i=0;for(let s of e){let e=n>0?s.value/n:0,a=e*t;r.push({entry:s,dash:a,gap:Math.max(0,t-a),offset:-i*t}),i+=e}for(let e of r)e.entry.share=n>0?e.entry.value/n:0;return r}(a,gu);return(0,r.jsxs)("div",{className:"usage-donut",children:[(0,r.jsxs)("div",{className:"usage-donut-chart",children:[(0,r.jsxs)("svg",{viewBox:"0 0 120 120",className:"usage-donut-svg",role:"img","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"60",cy:"60",r:"44",fill:"none",stroke:"var(--bg-hover)",strokeWidth:"14"}),o.map(e=>(0,r.jsx)("circle",{cx:"60",cy:"60",r:44,fill:"none",stroke:e.entry.color,strokeWidth:"14",strokeDasharray:`${e.dash} ${e.gap}`,strokeDashoffset:e.offset,transform:"rotate(-90 60 60)",children:(0,r.jsx)("title",{children:`${e.entry.label}: ${i(e.entry.value)}`})},e.entry.key))]}),(0,r.jsxs)("div",{className:"usage-donut-center",children:[(0,r.jsx)("span",{className:"usage-donut-total",children:i(l)}),(0,r.jsx)("span",{className:"usage-donut-unit",children:s})]})]}),(0,r.jsx)("div",{className:"usage-donut-legend",role:"list",children:a.map(e=>(0,r.jsxs)("div",{className:"usage-donut-row",role:"listitem",children:[(0,r.jsx)("span",{className:"usage-donut-dot",style:{backgroundColor:e.color}}),(0,r.jsx)("span",{className:"usage-donut-name",title:e.label,children:e.label}),(0,r.jsx)("span",{className:"usage-donut-share",children:`${Math.round(100*e.share)}%`}),(0,r.jsx)("span",{className:"usage-donut-value",children:`${i(e.value)} ${s}`})]},e.key))})]})}function gh(e,t){return e<=0||t<=0?0:Math.min(4,Math.max(1,Math.ceil(e/t*4)))}function gm(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n.getTime()}function gg(e){let t,n,i,s,a,l,{daily:o,mode:d,titleOf:c,labelOfMonth:u}=e,p=function(e){let t=null;for(let n of e)if(n.total>0||n.messages>0){let e=function(e){let[t,n,r]=e.split("-").map(Number);if(void 0===t||void 0===n||void 0===r)return null;let i=new Date(t,n-1,r).getTime();return Number.isFinite(i)?i:null}(n.date);null!==e&&(t=e)}if(null===t)return[];let n=new Map(e.map(e=>[e.date,e])),r=gm(t,-new Date(t).getDay()-539),i=[];for(let e=0;e<78;e++){let t=[];for(let i=0;i<7;i++){let s=function(e){let t=new Date(e),n=e=>e<10?`0${e}`:String(e);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}`}(gm(r,7*e+i)),a=n.get(s);t.push(a?{date:s,total:a.total,messages:a.messages}:{date:s,total:0,messages:0})}i.push(t)}return i}(o);if(0===p.length)return null;let h="daily"===d?null:(t=p.map(e=>e.reduce((e,t)=>e+t.total,0)),n=p.map(e=>e.reduce((e,t)=>e+t.messages,0)),i="weekly"===d?t:t.reduce((e,t)=>(e.push((e[e.length-1]??0)+t),e),[]),s="weekly"===d?n:n.reduce((e,t)=>(e.push((e[e.length-1]??0)+t),e),[]),a=Math.max(0,...i),l=i.map(e=>e<=0||a<=0?0:Math.min(7,Math.max(1,Math.ceil(e/a*7)))),{values:i,messages:s,barCells:l}),m=h?Math.max(0,...h.values):Math.max(1,...o.map(e=>e.total)),g=function(e,t){let n=[];for(let r of e){let e=r.find(e=>e.date.endsWith("-01"))?.date??r[0]?.date??"";if(!e)continue;let i=e.slice(0,7),s=n[n.length-1];s&&s.key===i?s.span+=1:n.push({key:i,label:t(e),span:1})}return n}(p,u);return(0,r.jsxs)("div",{className:"usage-heatmap",children:[(0,r.jsx)("div",{className:"usage-heatmap-grid",role:"img","aria-hidden":"true",children:p.map((e,t)=>{let n=h?.values[t]??0,i=h?.barCells[t]??0,s=h?gh(n,m):0,a=e[6]?.date??e[0].date,l=h?c({date:a,total:n,messages:h.messages[t]??0},d):null;return(0,r.jsx)("div",{className:"daily"!==d?"usage-heatmap-col is-bar":"usage-heatmap-col",children:e.map((e,t)=>{let a=!h||t>=7-i,o=h?a?s:0:gh(e.total,m),u=h?a&&n>0:e.total>0,p=h?l:c(e,d);return(0,r.jsx)("span",{className:"usage-heat-cell","data-level":o,"data-has-usage":u?"true":void 0,title:p??void 0},e.date)})},t)})}),(0,r.jsx)("div",{className:"usage-heatmap-months",children:g.map(e=>(0,r.jsx)("span",{className:"usage-heatmap-month",style:{gridColumn:`span ${e.span}`},children:e.label},e.key))})]})}let gf=[7,30];function gx(e){var t;let n,s,a,l,o,d,{onClose:c}=e,{t:u,locale:p}=(0,eX.s)(),[h,m]=(0,i.useState)(7),[g,f]=(0,i.useState)(null),[x,b]=(0,i.useState)(null),[v,y]=(0,i.useState)(!1),[k,j]=(0,i.useState)(!0),[w,S]=(0,i.useState)(!1),[C,N]=(0,i.useState)("daily"),I=(0,i.useRef)(null),E=(0,i.useRef)(0),$=(0,i.useCallback)(async(e,t)=>{let n=++E.current;t&&S(!0),y(!1);let r=e=>new URLSearchParams({range:String(e),...t?{force:"1"}:{}});try{let[t,i]=await Promise.all([fetch(`/api/usage?${r(e).toString()}`,{cache:"no-store"}),fetch(`/api/usage?${r("all").toString()}`,{cache:"no-store"})]);if(!t.ok)throw Error(String(t.status));let s=await t.json();if(E.current!==n)return;f(s),i.ok&&b(await i.json()),j(!1)}catch{if(E.current!==n)return;y(!0),j(!1)}finally{E.current===n&&S(!1)}},[]);(0,i.useEffect)(()=>($(h,!1),()=>{E.current+=1}),[h,$]),(0,i.useEffect)(()=>{let e=I.current,t=t=>{if("Escape"!==t.key||null!==document.querySelector('[aria-modal="true"]'))return;t.preventDefault();let n=document.activeElement;c(!!(n instanceof Element&&e?.contains(n)))};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[c]);let T=(0,i.useMemo)(()=>({day:u("usage.durationDay"),hour:u("usage.durationHour"),minute:u("usage.durationMinute")}),[u]),M=(0,i.useCallback)((e,t)=>{let n=`${(0,i_.eX)(e.total)} ${u("usage.tokenUnit")}`,r=u("usage.heatmapMessages",{messages:String(e.messages)});return"weekly"===t?`${u("usage.heatmapWeekOf",{date:e.date})}
994
+ ${n} \xb7 ${r}`:"cumulative"===t?`${u("usage.heatmapThrough",{date:e.date})}
995
+ ${n} \xb7 ${r}`:`${e.date}
996
+ ${n} \xb7 ${r}`},[u]),R=(0,i.useCallback)(e=>{let[t,n]=e.split("-").map(Number);return new Date(t,n-1,1).toLocaleDateString(p,{month:"short"})},[p]),A=x?.overview,L=A&&x?[{key:"total",label:u("usage.lifetimeTotalTokens"),value:(0,i_.eX)(A.tokens.total)},{key:"peak",label:u("usage.peakDayTokens"),value:(0,i_.eX)(A.peakDayTokens)},{key:"longest",label:u("usage.longestSession"),value:(t=A.longestSessionActiveMs,s=Math.floor((n=Math.max(0,Math.floor(t/6e4)))/1440),a=Math.floor(n%1440/60),l=n%60,o=[],s>0&&o.push(`${s} ${T.day}`),a>0&&o.push(`${a} ${T.hour}`),(l>0||0===o.length)&&o.push(`${l} ${T.minute}`),o.join(" "))},{key:"current",label:u("usage.currentStreak"),value:u("usage.streakDays",{days:String(x.activity.currentStreakDays)})},{key:"maxstreak",label:u("usage.longestStreak"),value:u("usage.streakDays",{days:String(x.activity.longestStreakDays)})}]:[],P=(0,i.useMemo)(()=>g?.models.slice(0,6).map(e=>e.model)??[],[g]),z=g?.models??[],O=null!==g&&g.daily.some(e=>e.total>0);return(0,r.jsxs)("section",{ref:I,className:"usage-panel","aria-label":u("usage.title"),children:[(0,r.jsx)("style",{children:gb}),(0,r.jsxs)("header",{className:"usage-panel-header",children:[(0,r.jsx)("span",{className:"usage-panel-heading",children:u("usage.title")}),(0,r.jsx)("span",{className:"usage-panel-status",children:x?[u("usage.sessions",{sessions:String(x.overview.sessions)}),u("usage.refreshedAt",{time:Number.isFinite((d=new Date(x.generatedAt)).getTime())?`${String(d.getHours()).padStart(2,"0")}:${String(d.getMinutes()).padStart(2,"0")}`:""})].join(" \xb7 "):""}),(0,r.jsx)("button",{type:"button",className:"usage-panel-copy",onClick:()=>void $(h,!0),disabled:w,children:u("usage.refresh")})]}),(0,r.jsxs)("div",{className:"usage-panel-scroll",children:[k&&(0,r.jsx)("p",{className:"usage-note",children:u("usage.loading")}),!k&&v&&(0,r.jsxs)("p",{className:"usage-note usage-note-error",children:[u("usage.error"),(0,r.jsx)("button",{type:"button",className:"usage-panel-copy",onClick:()=>void $(h,!0),children:u("usage.retry")})]}),!k&&!v&&(0,r.jsxs)(r.Fragment,{children:[A&&(0,r.jsx)("div",{className:"usage-overview",role:"list",children:L.map((e,t)=>(0,r.jsxs)("div",{className:"usage-overview-item",role:"listitem",children:[t>0&&(0,r.jsx)("span",{className:"usage-overview-divider","aria-hidden":"true"}),(0,r.jsx)("span",{className:"usage-overview-value",children:e.value}),(0,r.jsx)("span",{className:"usage-overview-label",children:e.label})]},e.key))}),null!==x&&x.daily.some(e=>e.total>0)&&(0,r.jsxs)("div",{className:"usage-section",children:[(0,r.jsxs)("div",{className:"usage-heatmap-head",children:[(0,r.jsx)("div",{className:"usage-section-title",children:u("usage.heatmapTitle")}),(0,r.jsx)("span",{className:"usage-panel-range",role:"group","aria-label":u("usage.heatmapModeLabel"),children:["daily","weekly","cumulative"].map(e=>(0,r.jsx)("button",{type:"button",className:"usage-pill","aria-pressed":C===e,onClick:()=>N(e),children:u(`usage.heatmapRange.${e}`)},e))})]}),(0,r.jsx)(gg,{daily:x.daily,mode:C,titleOf:M,labelOfMonth:R})]}),(0,r.jsxs)("div",{className:"usage-range-row",children:[(0,r.jsx)("span",{className:"usage-range-title",children:u("usage.rangeTitle")}),(0,r.jsx)("span",{className:"usage-panel-range",role:"group","aria-label":u("usage.rangeTitle"),children:gf.map(e=>(0,r.jsx)("button",{type:"button",className:"usage-pill","aria-pressed":h===e,onClick:()=>m(e),children:u(`usage.range${e}`)},String(e)))})]}),null!==g&&O&&(0,r.jsxs)("div",{className:"usage-section",children:[(0,r.jsx)("div",{className:"usage-section-title",children:u("usage.dailyTrend")}),(0,r.jsx)(gc,{daily:g.daily,models:P,formatCount:i_.eX,title:u("usage.dailyTrend")})]}),null!==g&&z.length>0&&(0,r.jsxs)("div",{className:"usage-section",children:[(0,r.jsx)("div",{className:"usage-section-title",children:u("usage.models")}),(0,r.jsx)(gp,{models:z,otherLabel:u("usage.modelOther"),formatCount:i_.eX,tokenUnit:u("usage.tokenUnit")})]}),null!==g&&!O&&(0,r.jsx)("p",{className:"usage-note",children:u("usage.empty")}),(0,r.jsx)("p",{className:"usage-footnote",children:u("usage.subagentsIncluded")})]})]})]})}let gb=`
997
+ .usage-panel {
998
+ --usage-c1: #4e9cd4;
999
+ --usage-c2: #57a773;
1000
+ --usage-c3: #d09a4e;
1001
+ --usage-c4: #9a7fd0;
1002
+ --usage-c5: #4eabd0;
1003
+ --usage-c6: #d06e9a;
1004
+ display: flex;
1005
+ max-height: min(720px, 80dvh);
1006
+ flex-direction: column;
1007
+ background: var(--bg-panel);
1008
+ border-bottom: 1px solid var(--border);
1009
+ box-shadow: 0 10px 28px rgba(0,0,0,0.10);
1010
+ color: var(--text);
1011
+ }
1012
+ .usage-panel-header {
1013
+ display: flex;
1014
+ flex-shrink: 0;
1015
+ align-items: center;
1016
+ gap: 12px;
1017
+ min-width: 0;
1018
+ padding: 8px 16px;
1019
+ border-bottom: 1px solid var(--border);
1020
+ font-size: 12px;
1021
+ }
1022
+ .usage-panel-heading {
1023
+ flex-shrink: 0;
1024
+ color: var(--text);
1025
+ font-weight: 700;
1026
+ }
1027
+ .usage-panel-status {
1028
+ display: inline-flex;
1029
+ min-width: 0;
1030
+ align-items: center;
1031
+ gap: 6px;
1032
+ color: var(--text-dim);
1033
+ font-variant-numeric: tabular-nums;
1034
+ overflow: hidden;
1035
+ text-overflow: ellipsis;
1036
+ white-space: nowrap;
1037
+ }
1038
+ .usage-panel-range {
1039
+ display: inline-flex;
1040
+ flex-shrink: 0;
1041
+ margin-left: auto;
1042
+ gap: 4px;
1043
+ }
1044
+ .usage-pill {
1045
+ padding: 2px 8px;
1046
+ border: 1px solid var(--border);
1047
+ border-radius: 4px;
1048
+ background: transparent;
1049
+ color: var(--text-muted);
1050
+ cursor: pointer;
1051
+ font-size: 11px;
1052
+ font-variant-numeric: tabular-nums;
1053
+ }
1054
+ .usage-pill:hover {
1055
+ background: var(--bg-hover);
1056
+ color: var(--text);
1057
+ }
1058
+ .usage-pill[aria-pressed="true"] {
1059
+ background: var(--bg-selected);
1060
+ border-color: var(--accent);
1061
+ color: var(--text);
1062
+ }
1063
+ .usage-panel-copy {
1064
+ flex-shrink: 0;
1065
+ padding: 2px 8px;
1066
+ border: 1px solid var(--border);
1067
+ border-radius: 4px;
1068
+ background: transparent;
1069
+ color: var(--text-muted);
1070
+ cursor: pointer;
1071
+ font-size: 11px;
1072
+ }
1073
+ .usage-panel-copy:hover {
1074
+ background: var(--bg-hover);
1075
+ color: var(--text);
1076
+ }
1077
+ .usage-panel-copy:disabled {
1078
+ opacity: 0.5;
1079
+ cursor: default;
1080
+ }
1081
+ .usage-panel-scroll {
1082
+ display: flex;
1083
+ min-height: 0;
1084
+ flex: 1;
1085
+ flex-direction: column;
1086
+ gap: 12px;
1087
+ overflow: auto;
1088
+ padding: 10px 16px 12px;
1089
+ font-size: 12px;
1090
+ line-height: 1.5;
1091
+ }
1092
+ .usage-section {
1093
+ display: flex;
1094
+ flex-direction: column;
1095
+ gap: 5px;
1096
+ }
1097
+ .usage-section-title {
1098
+ color: var(--text);
1099
+ font-size: 11px;
1100
+ font-weight: 700;
1101
+ }
1102
+ .usage-note {
1103
+ margin: 0;
1104
+ color: var(--text-dim);
1105
+ font-size: 12px;
1106
+ }
1107
+ .usage-note-error {
1108
+ color: var(--text);
1109
+ }
1110
+ .usage-note .usage-panel-copy {
1111
+ margin-left: 8px;
1112
+ }
1113
+ .usage-overview {
1114
+ display: flex;
1115
+ flex-wrap: wrap;
1116
+ }
1117
+ .usage-overview-item {
1118
+ display: flex;
1119
+ min-width: 96px;
1120
+ flex: 1 1 0;
1121
+ flex-direction: column;
1122
+ gap: 1px;
1123
+ padding: 2px 14px;
1124
+ }
1125
+ .usage-overview-item:first-child {
1126
+ padding-left: 0;
1127
+ }
1128
+ .usage-overview-divider {
1129
+ display: none;
1130
+ }
1131
+ @media (min-width: 640px) {
1132
+ .usage-overview-item {
1133
+ border-left: 1px solid var(--border);
1134
+ }
1135
+ .usage-overview-item:first-child {
1136
+ border-left: none;
1137
+ }
1138
+ }
1139
+ .usage-overview-value {
1140
+ color: var(--text);
1141
+ font-size: 15px;
1142
+ font-weight: 650;
1143
+ font-variant-numeric: tabular-nums;
1144
+ line-height: 1.35;
1145
+ overflow-wrap: anywhere;
1146
+ }
1147
+ .usage-overview-label {
1148
+ color: var(--text-dim);
1149
+ font-size: 11px;
1150
+ line-height: 1.35;
1151
+ }
1152
+ .usage-range-row {
1153
+ display: flex;
1154
+ align-items: center;
1155
+ justify-content: space-between;
1156
+ gap: 12px;
1157
+ }
1158
+ .usage-range-title {
1159
+ color: var(--text);
1160
+ font-size: 12px;
1161
+ font-weight: 500;
1162
+ }
1163
+ .usage-trend {
1164
+ position: relative;
1165
+ padding-top: 26px;
1166
+ }
1167
+ .usage-trend-legend {
1168
+ position: absolute;
1169
+ top: 0;
1170
+ left: 0;
1171
+ display: flex;
1172
+ flex-wrap: wrap;
1173
+ gap: 4px 12px;
1174
+ }
1175
+ .usage-trend-legend-item {
1176
+ display: inline-flex;
1177
+ min-width: 0;
1178
+ align-items: center;
1179
+ gap: 5px;
1180
+ }
1181
+ .usage-trend-legend-dot {
1182
+ width: 8px;
1183
+ height: 8px;
1184
+ flex-shrink: 0;
1185
+ border-radius: 2px;
1186
+ }
1187
+ .usage-trend-legend-label {
1188
+ max-width: 220px;
1189
+ overflow: hidden;
1190
+ text-overflow: ellipsis;
1191
+ white-space: nowrap;
1192
+ color: var(--text-muted);
1193
+ font-size: 10.5px;
1194
+ }
1195
+ .usage-trend-max {
1196
+ position: absolute;
1197
+ top: 30px;
1198
+ left: 0;
1199
+ color: var(--text-dim);
1200
+ font-size: 10px;
1201
+ line-height: 1.2;
1202
+ font-variant-numeric: tabular-nums;
1203
+ }
1204
+ .usage-trend-svg {
1205
+ width: 100%;
1206
+ height: 96px;
1207
+ display: block;
1208
+ }
1209
+ .usage-trend-line {
1210
+ stroke-width: 1.5;
1211
+ vector-effect: non-scaling-stroke;
1212
+ }
1213
+ .usage-trend-labels {
1214
+ position: relative;
1215
+ height: 14px;
1216
+ }
1217
+ .usage-trend-label {
1218
+ position: absolute;
1219
+ top: 2px;
1220
+ color: var(--text-dim);
1221
+ font-size: 10px;
1222
+ line-height: 1.2;
1223
+ white-space: nowrap;
1224
+ }
1225
+ .usage-heatmap {
1226
+ display: flex;
1227
+ flex-direction: column;
1228
+ }
1229
+ .usage-heatmap-head {
1230
+ display: flex;
1231
+ align-items: center;
1232
+ justify-content: space-between;
1233
+ gap: 12px;
1234
+ }
1235
+ .usage-heatmap-grid {
1236
+ display: grid;
1237
+ grid-template-columns: repeat(78, minmax(0, 1fr));
1238
+ column-gap: 2px;
1239
+ width: 100%;
1240
+ }
1241
+ .usage-heatmap-col {
1242
+ display: flex;
1243
+ min-width: 0;
1244
+ flex-direction: column;
1245
+ gap: 2px;
1246
+ }
1247
+ .usage-heat-cell {
1248
+ display: block;
1249
+ width: 100%;
1250
+ aspect-ratio: 1;
1251
+ min-width: 0;
1252
+ border-radius: 4px;
1253
+ border: 1px solid transparent;
1254
+ background: var(--bg-hover);
1255
+ transition: transform 0.1s;
1256
+ }
1257
+ .usage-heat-cell[data-has-usage="true"] {
1258
+ border-color: var(--border);
1259
+ }
1260
+ .usage-heat-cell:hover {
1261
+ transform: scale(1.15);
1262
+ border-color: var(--text-dim);
1263
+ }
1264
+ .usage-heatmap-col.is-bar:hover .usage-heat-cell {
1265
+ border-color: var(--text-dim);
1266
+ }
1267
+ .usage-heatmap-months {
1268
+ display: grid;
1269
+ grid-template-columns: repeat(78, minmax(0, 1fr));
1270
+ column-gap: 2px;
1271
+ margin-top: 5px;
1272
+ }
1273
+ .usage-heatmap-month {
1274
+ min-width: 0;
1275
+ overflow: hidden;
1276
+ text-overflow: ellipsis;
1277
+ white-space: nowrap;
1278
+ color: var(--text-dim);
1279
+ font-size: 10px;
1280
+ line-height: 1.2;
1281
+ }
1282
+ .usage-heat-cell[data-level="1"] { background: color-mix(in srgb, var(--usage-c1) 30%, var(--bg-panel)); }
1283
+ .usage-heat-cell[data-level="2"] { background: color-mix(in srgb, var(--usage-c1) 55%, var(--bg-panel)); }
1284
+ .usage-heat-cell[data-level="3"] { background: color-mix(in srgb, var(--usage-c1) 80%, var(--bg-panel)); }
1285
+ .usage-heat-cell[data-level="4"] { background: var(--usage-c1); }
1286
+ .usage-donut {
1287
+ display: flex;
1288
+ align-items: center;
1289
+ gap: 20px;
1290
+ flex-wrap: wrap;
1291
+ }
1292
+ .usage-donut-chart {
1293
+ position: relative;
1294
+ width: 148px;
1295
+ height: 148px;
1296
+ flex-shrink: 0;
1297
+ }
1298
+ .usage-donut-svg {
1299
+ width: 100%;
1300
+ height: 100%;
1301
+ display: block;
1302
+ }
1303
+ .usage-donut-center {
1304
+ position: absolute;
1305
+ inset: 0;
1306
+ display: flex;
1307
+ flex-direction: column;
1308
+ align-items: center;
1309
+ justify-content: center;
1310
+ gap: 1px;
1311
+ pointer-events: none;
1312
+ }
1313
+ .usage-donut-total {
1314
+ color: var(--text);
1315
+ font-size: 15px;
1316
+ font-weight: 650;
1317
+ font-variant-numeric: tabular-nums;
1318
+ max-width: 84px;
1319
+ overflow: hidden;
1320
+ text-overflow: ellipsis;
1321
+ white-space: nowrap;
1322
+ }
1323
+ .usage-donut-unit {
1324
+ color: var(--text-dim);
1325
+ font-size: 10.5px;
1326
+ }
1327
+ .usage-donut-legend {
1328
+ display: flex;
1329
+ min-width: 0;
1330
+ flex: 1 1 240px;
1331
+ flex-direction: column;
1332
+ }
1333
+ .usage-donut-row {
1334
+ display: grid;
1335
+ grid-template-columns: auto minmax(0, 1fr) auto;
1336
+ align-items: baseline;
1337
+ column-gap: 8px;
1338
+ padding: 3px 2px;
1339
+ border-bottom: 1px solid var(--border);
1340
+ }
1341
+ .usage-donut-row:last-child {
1342
+ border-bottom: none;
1343
+ }
1344
+ .usage-donut-dot {
1345
+ width: 8px;
1346
+ height: 8px;
1347
+ align-self: center;
1348
+ border-radius: 2px;
1349
+ }
1350
+ .usage-donut-name {
1351
+ min-width: 0;
1352
+ overflow: hidden;
1353
+ text-overflow: ellipsis;
1354
+ white-space: nowrap;
1355
+ color: var(--text);
1356
+ font-size: 12px;
1357
+ }
1358
+ .usage-donut-share {
1359
+ color: var(--text-muted);
1360
+ font-size: 11.5px;
1361
+ font-variant-numeric: tabular-nums;
1362
+ }
1363
+ .usage-donut-value {
1364
+ grid-column: 2 / 4;
1365
+ color: var(--text-dim);
1366
+ font-size: 10.5px;
1367
+ font-variant-numeric: tabular-nums;
1368
+ }
1369
+ .usage-footnote {
1370
+ margin: 0;
1371
+ color: var(--text-dim);
1372
+ font-size: 11px;
1373
+ }
1374
+ `;function gv(e){let{sessionId:t,running:n,...s}=e,{t:a}=(0,eX.s)(),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)("loading"),u=(0,i.useRef)(null);return((0,i.useEffect)(()=>{let e,r=new AbortController,i=async()=>{try{let s=await fetch(`/api/sessions/${encodeURIComponent(t)}`,{signal:r.signal,cache:"no-store"});if(404===s.status){c("missing"),n&&(e=setTimeout(()=>void i(),1e3));return}let a=await s.json();a.info?o(a.info):c("error")}catch(e){e instanceof Error&&"AbortError"===e.name||c("error")}};return i(),()=>{r.abort(),clearTimeout(e)}},[t,n]),l)?(0,r.jsx)(sy,{...s,session:l,sessionRunning:n,newSessionCwd:null,newSessionDraftKey:null,chatInputRef:u,panel:!0}):(0,r.jsx)("div",{role:"error"===d?"alert":void 0,style:{padding:"24px 16px",color:"var(--text-dim)",fontSize:12,textAlign:"center"},children:a("loading"===d||n?"sessionPanel.loading":"missing"===d?"sessionPanel.missing":"sessionPanel.error")})}var gy=n(60956);class gk{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 gj{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 gw=new gk(-1,"__missing_parent__"),gS=["#4f8cff","#f59e0b","#10b981","#ef4444","#a855f7","#d9a814"];function gC(e){return e.slice(0,7)}function gN(e){let{cwd:t,refreshKey:n=0}=e,{t:s,locale:a}=(0,eX.s)(),[l,o]=(0,i.useState)({commits:[],hasMore:!1}),[d,c]=(0,i.useState)(!0),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(!1),[g,f]=(0,i.useState)(null),[x,b]=(0,i.useState)(null),[v,y]=(0,i.useState)(null),k=(0,i.useRef)(!1),j=(0,i.useRef)(0),w=(0,i.useCallback)(async e=>{let n=new URLSearchParams({cwd:t,skip:String(e),maxCount:String(50)}),r=++j.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===j.current?s:null},[t]);(0,i.useEffect)(()=>{let e=!1;return(async()=>{c(!0),f(null);try{let t=await w(0);!e&&t&&(o(t),b(t.commits[0]?.hash??null))}catch(t){e||f(t instanceof Error?t.message:String(t))}finally{e||c(!1)}})(),()=>{e=!0}},[w,n]);let S=(0,i.useCallback)(async()=>{m(!0),f(null);try{let e=await w(0);e&&(o(e),b(e.commits[0]?.hash??null))}catch(e){f(e instanceof Error?e.message:String(e))}finally{m(!1)}},[w]),C=(0,i.useCallback)(async()=>{if(!k.current&&l.hasMore){k.current=!0,p(!0),f(null);try{let e=await w(l.commits.length);e&&o(t=>({commits:[...t.commits,...e.commits],hasMore:e.hasMore}))}catch(e){f(e instanceof Error?e.message:String(e))}finally{k.current=!1,p(!1)}}},[w,l.commits.length,l.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,a=t.bottomPadding??18,l=function(e){let t=e.map((e,t)=>new gk(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)??gw);return t}(e),o=[],d=[];for(let e=0;e<l.length;){let t=l[e],n=t.nextParent();if(null===n&&t.isOnBranch()){e++;continue}if(n===gw){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 a=n[s],l=a.connectionTo(t,r),o=null!==l,d=l??a.nextPoint();if(r.addLine(i,d,e.hash,t.hash,o||i.laneIndex<d.laneIndex),a.reservePoint(d.laneIndex,t,r),i=d,o){e.markParentProcessed();break}}}(t,n,l):function(e,t,n,r){let i,s=t[e],a=s.nextParent(),l=s.isOnBranch()?s.point():s.nextPoint(),o=new gj((i=r.findIndex(t=>t<e))>=0?i:(r.push(0),r.length-1));s.joinBranch(o,l.laneIndex),s.reservePoint(l.laneIndex,s,o);let d=e+1;for(;d<t.length&&null!==a&&a!==gw;d++){let e=t[d],n=a===e&&e.isOnBranch()?e.point():e.nextPoint();if(o.addLine(l,n,s.hash,a.hash,l.laneIndex<n.laneIndex),e.reservePoint(n.laneIndex,a,o),l=n,a===e){s.markParentProcessed();let t=e.isOnBranch();if(e.joinBranch(o,n.laneIndex),(a=(s=e).nextParent())===gw){s.markParentProcessed();break}if(null===a||t)break}}o.endRowIndex=Math.min(d,t.length),n.push(o),r[o.colorIndex]=o.endRowIndex}(e,l,o,d)}let c=e=>i+e*r,u=e=>s+e*n,p=l.map((t,n)=>({commit:e[n],rowIndex:n,laneIndex:t.getLaneIndex(),x:c(t.getLaneIndex()),y:u(n)})),h=[],m=-1;for(let e of p)m=Math.max(m,e.laneIndex);for(let e of l)m=Math.max(m,e.widestLaneIndex());for(let e of o)for(let t of e.lines)m=Math.max(m,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}`}(c(t.from.laneIndex),u(t.from.rowIndex),c(t.to.laneIndex),u(t.to.rowIndex),t.lockedFirst),colorIndex:e.colorIndex,relatedHashes:t.sourceHash===t.targetHash?[t.sourceHash]:[t.sourceHash,t.targetHash]});let g=Math.max(1,m+1);return{rows:p,paths:h,laneCount:g,width:2*i+(g-1)*r,height:s+Math.max(0,e.length-1)*n+a,rowHeight:n,laneGap:r,lanePadding:i}})(l.commits),[l.commits]),I=(0,i.useMemo)(()=>new Intl.DateTimeFormat(a,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}),[a]),E=(0,i.useMemo)(()=>l.commits.find(e=>e.hash===x)??null,[l.commits,x]),$=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 d?(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")}),l.commits.length>0&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s(l.hasMore?"gitGraph.subtitlePartial":"gitGraph.subtitle",{count:l.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"})]})})]}),g&&(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:g})}),0===l.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:T,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:$,height:N.height+N.rowHeight,viewBox:`0 0 ${$} ${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!==v&&e.relatedHashes.includes(v),n=null!==v&&!t;return(0,r.jsx)("path",{d:e.d,fill:"none",stroke:gS[e.colorIndex%gS.length],strokeWidth:2,opacity:n?.25:t?1:.6},e.id)}),N.rows.map(e=>{let t=e.commit.hash===x,n=gS[e.laneIndex%gS.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:()=>{b(e=>e===t.hash?null:t.hash)},onMouseEnter:()=>y(t.hash),onMouseLeave:()=>y(null),"aria-label":`${gC(t.hash)} ${t.subject}`,style:{display:"grid",gridTemplateColumns:T,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)(gI,{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||gC(t.hash)}),t.parents.length>1&&(0,r.jsx)(gE,{})]}),(0,r.jsx)("span",{style:{padding:"0 8px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-muted)",fontSize:11},children:t.authoredAtMs?I.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:gC(t.hash)})]},t.hash)})]}),l.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")})})]}),E&&(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:E.subject||gC(E.hash)}),E.refs.length>0&&(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:3,marginTop:4},children:E.refs.map(e=>(0,r.jsx)(gI,{gitRef:e},`${E.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:gC(E.hash)})]}),(0,r.jsxs)("span",{children:[s("gitGraph.detailAuthor"),": ",(0,r.jsx)("span",{style:{color:"var(--text)"},children:E.authorName??"—"})]}),(0,r.jsxs)("span",{children:[s("gitGraph.detailDate"),":"," ",(0,r.jsx)("span",{style:{color:"var(--text)"},children:E.authoredAtMs?new Intl.DateTimeFormat(a,{dateStyle:"medium",timeStyle:"short"}).format(new Date(E.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:E.parents.length>0?E.parents.map(gC).join(", "):"—"})]})]})]})]})}function gI(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 gE(){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"})]})}var g$=n(50335);let gT=e=>`pi-web:side-tabs:${e}`;function gM(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let gR=[48,120,240,420,720];var gA=n(99863),gL=n(28999);function gP(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document;return"visible"!==e.visibilityState||!e.hasFocus()}async function gz(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null},n={body:e.body,...e.tag?{tag:e.tag,renotify:!0}:{}};if(t.getServiceWorkerRegistration)try{let r=await t.getServiceWorkerRegistration();if(r)return await r.showNotification(e.title,{...n,data:{url:e.sessionUrl,shownAt:Date.now()}}),"service-worker"}catch{}try{let r=t.createWindowNotification(e.title,n);return r.onclick=()=>{r.close(),e.onClick()},"window"}catch{return null}}let gO="pi-web:tab-open-session";function gW(){try{return window.sessionStorage}catch{return null}}function gF(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 gD(e,t){t.setItem(gO,JSON.stringify(e))}var gB=n(82831);let gH="pi-web:agent-strip-locked";function g_(e){return r3(gH,e)}let gU="var(--top-bar-height)",gK=new Set(iW.kU);function gq(e){let t=e.at(-1);return t?`agent:${t.sessionId}`:null}function gZ(){var e;let t,n,d,p,b,v,y,k,j,w,S,C,N,I=(0,s.useRouter)(),E=(0,s.useSearchParams)(),[$,T]=(0,i.useState)(()=>{let e;return{requestedCwd:e=E.get("cwd")?.trim()||null,sessionId:e?null:E.get("session")||null,sidebarCollapsed:"collapsed"===E.get("sidebar")}});(0,sL.D)(),(0,rx.VE)();let{locale:M,t:R}=(0,eX.s)(),A=(0,eQ.a)(),L=(0,eQ.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:gM(),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)},a=()=>{null!==n&&window.cancelAnimationFrame(n),n=window.requestAnimationFrame(s),(()=>{if(i)return;i=!0;let e=0,t=()=>{if(e>=gR.length){i=!1;return}let n=gR[e++],a=window.setTimeout(()=>{r.delete(a),s(),t()},n);r.add(a)};t()})()},l=()=>{gM()&&a()};return a(),e.addEventListener("resize",a),e.addEventListener("scroll",a),window.addEventListener("resize",a),window.addEventListener("focusin",a),window.addEventListener("focusout",a),window.addEventListener("pageshow",a),document.addEventListener("compositionstart",l),document.addEventListener("compositionupdate",l),document.addEventListener("compositionend",l),document.addEventListener("input",l),document.addEventListener("keyup",l),()=>{for(let t of(e.removeEventListener("resize",a),e.removeEventListener("scroll",a),window.removeEventListener("resize",a),window.removeEventListener("focusin",a),window.removeEventListener("focusout",a),window.removeEventListener("pageshow",a),document.removeEventListener("compositionstart",l),document.removeEventListener("compositionupdate",l),document.removeEventListener("compositionend",l),document.removeEventListener("input",l),document.removeEventListener("keyup",l),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&&l$(M)},[M]);let{soundEnabled:P,onSoundToggle:z,playDoneSound:O,unlockAudio:W,holdAudio:F,soundEnabledRef:D}=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},[]),a=(0,i.useRef)(0),l=(0,i.useRef)(0),o=(0,i.useRef)(void 0),d=(0,i.useCallback)(e=>{clearTimeout(o.current),o.current=setTimeout(()=>{0===a.current&&0===l.current&&e.suspend().catch(()=>{})},1e3)},[]),c=(0,i.useCallback)((e,t)=>{a.current++,e.resume().then(t).catch(()=>{}).then(()=>{a.current--,d(e)})},[d]),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&&c(t,()=>{})},[s,c]),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(l.current++,clearTimeout(o.current),n.current){let e=s();e&&"running"!==e.state&&c(e,()=>{})}let e=!1;return()=>{!e&&(e=!0,l.current--,r.current&&d(r.current))}},[s,c,d]);return{soundEnabled:e,onSoundToggle:p,playDoneSound:(0,i.useCallback)(()=>{if(!n.current)return;let e=s();if(!e)return;let t=Date.now();c(e,()=>{if(n.current&&!(Date.now()-t>3e3))try{let t;t=e.currentTime,[523.25,659.25].forEach((n,r)=>{let i=e.createOscillator(),s=e.createGain();i.connect(s),s.connect(e.destination),i.type="sine",i.frequency.value=n;let a=t+.18*r;s.gain.setValueAtTime(0,a),s.gain.linearRampToValueAtTime(.18,a+.02),s.gain.exponentialRampToValueAtTime(.001,a+.45),i.start(a),i.stop(a+.45)})}catch{}})},[s,c]),unlockAudio:u,holdAudio:h,soundEnabledRef:n}}(),[B,H]=(0,i.useState)(!1);(0,i.useEffect)(()=>{try{H("true"===localStorage.getItem("pi-quote-selection-enabled"))}catch{}},[]);let _=(0,i.useCallback)(e=>{H(e);try{localStorage.setItem("pi-quote-selection-enabled",String(e))}catch{}},[]),U=(0,i.useRef)(new Set),[K,q]=(0,i.useState)(new Set),Z=(0,i.useCallback)((e,t)=>{D.current&&sg(e,t)&&O()},[O,D]),[V,J]=(0,i.useState)(null),G=(0,i.useRef)(V);G.current=V;let[Y,X]=(0,i.useState)([]),[Q,ee]=(0,i.useState)(!1),et=(0,i.useCallback)(e=>{X(e),ee(!0),J(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})},[]),en=(0,i.useMemo)(()=>V?[...Y.filter(e=>e.id!==V.id),V]:Y,[V,Y]),er=(0,i.useMemo)(()=>c(en,V?.id),[V?.id,en]),[ei,es]=(0,i.useState)(()=>new Set),ea=(0,i.useCallback)(e=>{es(t=>t.size===e.size&&[...e].every(e=>t.has(e))?t:e)},[]),el=er?(t=u(e=er.subagents,ei))>0?{count:t,running:!0}:{count:e.length,running:!1}:null,eo=el?.running?R("agentSwitcher.titleRunning",{count:el.count}):R("agentSwitcher.title"),[ed,ec]=(0,i.useState)(g_),eu=(0,i.useMemo)(()=>(function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!e||!t)return null;if(e.root.id===t){if(!n||0===e.subagents.length)return null}else if(!e.subagents.some(e=>e.id===t))return null;return[...e.subagents].sort((e,t)=>e.created.localeCompare(t.created)||e.id.localeCompare(t.id))})(er,V?.id,ed),[er,V?.id,ed]),ep=(0,i.useRef)(null),eh=(0,i.useCallback)(()=>{let e=!ed;ec(e),r5(gH,e,void 0),e||requestAnimationFrame(()=>eE(document,ep.current))},[ed]),[em,eg]=(0,i.useState)(null),[ef,ex]=(0,i.useState)("initial"),eb=(0,i.useRef)(null),ev=(0,i.useRef)(null),[ey,ek]=(0,i.useState)(null),ej=(0,i.useRef)(null),ew=(0,i.useCallback)(e=>{e&&e.cwd===ej.current?.cwd&&(ej.current=null),ek(e)},[]),eS=(0,i.useRef)(null),eC=(0,i.useRef)(null),[eN,eI]=(0,i.useState)(null),eT=(0,i.useCallback)(e=>{eC.current=e,eI(null)},[]),[eM,eR]=(0,i.useState)(()=>$.requestedCwd?"validating":"idle"),[eA,eL]=(0,i.useState)(null),[eP,ez]=(0,i.useState)(0),[eO,eW]=(0,i.useState)(0),eF=(0,i.useRef)(new Map),eD=(0,i.useCallback)((e,t)=>{eF.current.set(e,t)},[]),[eB,eH]=(0,i.useState)(null),e_=(0,i.useCallback)(e=>{eH(t=>t===e?null:t)},[]),[eU,eK]=(0,i.useState)(0),[eq,eZ]=(0,i.useState)(null),[eV,eJ]=(0,i.useState)(!1),[eG,eY]=(0,i.useState)(0),[e1,e2]=(0,i.useState)(null),[e4,e8]=(0,i.useState)(!1),[e6,e3]=(0,i.useState)(!1),[e5,e9]=(0,i.useState)(null),[e7,te]=(0,i.useState)(()=>!$.sidebarCollapsed),tt=(0,i.useRef)(!$.sidebarCollapsed),[tn,tr]=(0,i.useState)(!1),[ti,ts]=(0,i.useState)(!1),ta=tn&&ti&&!A;(0,i.useEffect)(()=>{(!tn||A)&&ts(!1)},[tn,A]);let[tl,to]=(0,i.useState)(!1),td=tl?R("chat.close"):R("chat.moreControls"),[tu,tp]=(0,i.useState)(!1),th=(0,i.useRef)(gB.Qw),tm=(0,i.useRef)(gB.MH),tg=(0,i.useCallback)(()=>(0,gB.YZ)(window.innerWidth),[]),tf=(0,i.useCallback)(()=>(0,gB.VX)({viewportWidth:window.innerWidth,rightPanelOpen:tn,rightPanelWidth:tm.current}),[tn]),tx=(0,i.useCallback)(()=>(0,gB.NC)({viewportWidth:window.innerWidth,sidebarOpen:e7,sidebarWidth:th.current}),[e7]),tb=(0,e0.T)({ariaLabel:R("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:gB.Qw,getMaxWidth:tf,growthDirection:"right",maxWidth:gB.vd,minWidth:gB.hh,storageKey:"pi-sidebar-width",widthRef:th}),tv=(0,e0.T)({ariaLabel:R("layout.resizeFilePanel"),cssVariable:"--right-panel-width",defaultWidth:gB.MH,getDefaultWidth:tg,getMaxWidth:tx,growthDirection:"left",maxWidth:gB.QA,minWidth:gB.I9,storageKey:"pi-right-panel-width",widthRef:tm}),ty=tb.reclampWidth,tk=tv.reclampWidth;(0,i.useEffect)(()=>{te(!A&&tt.current)},[A]),(0,i.useEffect)(()=>{tp(!0)},[]),(0,i.useEffect)(()=>{tn&&(ty(),tk())},[tk,ty,tn]);let tj=(0,i.useRef)(null),[tw,tS]=(0,i.useState)({}),tC=(0,i.useRef)(null),tN=(0,i.useRef)(null),[tI,tE]=(0,i.useState)([]),[t$,tT]=(0,i.useState)(null),[tM,tR]=(0,i.useState)(!1),tA=(0,i.useRef)(null),tL=hA(tI),tP=(0,i.useCallback)((e,t,n,r)=>{tE(e),tT(t),tR(r),tA.current=n},[]),tz=(0,i.useCallback)(e=>{tA.current?.(e)},[]),[tO,tW]=(0,i.useState)(null),[tF,tD]=(0,i.useState)(null),[tB,tH]=(0,i.useState)(!1),t_=(0,i.useRef)(null),tU=(0,i.useRef)(0),tK=(0,i.useRef)(null),tq=(0,i.useCallback)(e=>{tW(e),tH(!1)},[]),tZ=(0,i.useCallback)(e=>{tD(e)},[]),tV=(0,i.useCallback)(e=>{tU.current+=1,t_.current=e,tH(!1)},[]),tJ=(0,i.useRef)(null),tG=(0,i.useCallback)(e=>{tJ.current=e},[]);(0,i.useEffect)(()=>{(0,e$.t0)()},[]);let[tY,tQ]=(0,i.useState)(null),[t0,t1]=(0,i.useState)({kind:"idle"}),t2=(0,i.useRef)(null),t4=(0,i.useRef)(V?.id??null);t4.current=V?.id??null;let t8=(0,i.useCallback)(e=>{tQ(e)},[]),[t6,t3]=(0,i.useState)(null),t5=(0,i.useRef)(null),t9=(0,i.useCallback)((e,t)=>{(0,tc.D)(t).then(()=>{t5.current&&clearTimeout(t5.current),t3(e),t5.current=setTimeout(()=>t3(null),1400)},()=>{})},[]);(0,i.useEffect)(()=>()=>{t5.current&&clearTimeout(t5.current),t2.current&&clearTimeout(t2.current)},[]);let[t7,ne]=(0,i.useState)(null),nt=(0,i.useCallback)(e=>{ne(e)},[]),[nn,nr]=(0,i.useState)(null),[ni,ns]=(0,i.useState)(null);(0,i.useEffect)(()=>{tL||nr(e=>"branches"===e?null:e)},[tL]),(0,i.useEffect)(()=>{er||nr(e=>"agents"===e?null:e)},[er]),(0,i.useEffect)(()=>{ta&&nr(null)},[ta]);let na=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];A&&te(!1),nr(t=>t===e?null:e),A&&L&&t&&to(!0)},[A,L]),nl=(0,i.useRef)(null),no=(0,i.useRef)(null),nd=(0,i.useCallback)(e=>{nr(e=>"debug"===e?null:e),e&&requestAnimationFrame(()=>eE(document,nl.current))},[]),nc=(0,i.useCallback)(e=>{nr(e=>"usage"===e?null:e),e&&requestAnimationFrame(()=>eE(document,no.current))},[]),nu=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=nn!==e;if(na(e,t),!n||tB)return;let r=t_.current;if(!r)return;let i=++tU.current;tH(!0),r().catch(e=>{console.error("Failed to load system information:",e)}).finally(()=>{tU.current===i&&tH(!1)})},[nn,tB,na]),nh=(0,i.useCallback)(()=>{A&&te(!1),to(!1),nr("session")},[A]),nm=(0,i.useCallback)(e=>{eJ(!1),eZ(e)},[]),ng=(0,i.useCallback)(()=>{A&&(nr(null),to(!1)),te(e=>{let t=!e;return A||(tt.current=t),t})},[A]),nf=(0,i.useCallback)(()=>{te(!1),nr(null),to(e=>!e)},[]),nx=(0,i.useCallback)(()=>{A&&(te(!1),nr(null),to(!1)),tr(e=>!e)},[A]),nb=(0,i.useCallback)(()=>{nr(null),ts(e=>!e)},[]);(0,i.useEffect)(()=>{if(!tl)return;let e=e=>{let t=tN.current;t&&e.composedPath().includes(t)||to(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),to(!1))};return document.addEventListener("pointerdown",e,!0),document.addEventListener("keydown",t,!0),()=>{document.removeEventListener("pointerdown",e,!0),document.removeEventListener("keydown",t,!0)}},[tl]),(0,i.useEffect)(()=>{to(!1)},[A,L,V?.id,ef]),(0,i.useEffect)(()=>{if(!nn||!tC.current)return;let e=()=>{let e=tC.current.getBoundingClientRect();"agents"===nn?ns({top:e.bottom,left:e.left,width:Math.min(420,e.width)}):ns({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(tC.current),()=>t.disconnect()},[nn,A]);let[nv,ny]=(0,i.useState)([]),[nk,nj]=(0,i.useState)(null),nw=(0,i.useRef)(new Map),[nS,nC]=(0,i.useState)(0),nN=(0,i.useRef)(0),[nI,nE]=(0,i.useState)([]),[n$,nT]=(0,i.useState)([]),[nM,nR]=(0,i.useState)(!1),[nA,nL]=(0,i.useState)([]),nP=(0,i.useRef)(null),nz=(0,i.useRef)(!1),nO=(0,i.useRef)(!1),[nW,nF]=(0,i.useState)(null),nD=(0,i.useRef)(null),[nB,nH]=(0,i.useState)([]),n_=function(e,t){if(!t.length)return e;let n=new Map(e.map(e=>[e.id,e])),r=[];for(let e of t){let t=n.get(e);t&&(r.push(t),n.delete(e))}return[...r,...n.values()]}([...nv,...nI.map(e=>({id:e.id,label:(0,gL.WP)(e.cwd)||e.cwd,filePath:e.cwd,kind:"terminal",closing:!!e.closing})),...n$.map(e=>({id:`git-graph:${e}`,label:(0,gL.WP)(e)||e,filePath:e,kind:"git-graph"})),...nA.map(e=>{let t=e.side?Y.find(t=>t.id===e.sessionId):void 0,n=t?l(t,R("agentSwitcher.sideChat"),er?.subagents??[]):e.label;return{id:`agent:${e.sessionId}`,label:n,filePath:n,kind:e.side?"side":"agent"}})],nB),nU=n_.map(e=>e.id).join("\n");(0,i.useEffect)(()=>{let e=new Set(nU.split("\n"));nH(t=>t.every(t=>e.has(t))?t:t.filter(t=>e.has(t)))},[nU]),(0,i.useEffect)(()=>{try{let e=(0,g$.PT)(window.sessionStorage.getItem(g$.WT));nE(e.tabs),e.activeId&&(nj(e.activeId),tr(e.open))}catch{}nR(!0)},[]),(0,i.useEffect)(()=>{if(nM)try{window.sessionStorage.setItem(g$.WT,JSON.stringify({tabs:nI.map(e=>{let{id:t,cwd:n}=e;return{id:t,cwd:n}}),activeId:nk,open:tn}))}catch{}},[nI,nk,tn,nM]);let nK=(0,i.useCallback)(e=>{try{let t=nA.filter(e=>e.side);if(!t.length)return void window.sessionStorage.removeItem(gT(e));window.sessionStorage.setItem(gT(e),JSON.stringify({tabs:t,activeId:t.some(e=>`agent:${e.sessionId}`===nk)?nk:null,open:tn}))}catch{}},[nA,nk,tn]),nq=(0,i.useCallback)((e,t,n,r)=>{e!==nN.current?(0,sA.K1)(nw.current,e,t,n,r):ny(e=>(0,sA.ZS)(e,t,n,r))},[]),nZ=(0,i.useCallback)((e,t)=>{if(e===t)return;let n=nk?.startsWith("file:")?nk:null,r=(0,sA.G_)(nw.current,e,t,{tabs:nv,activeTabId:n,open:tn&&!!n},nN.current);nN.current+=1,nC(nN.current),ny(r.tabs),nL(e=>e.filter(e=>e.side)),nz.current&&nP.current&&(nK(nP.current),nO.current=!0),nT([]),(!nk||n||nk.startsWith("agent:")||nk.startsWith("git-graph:"))&&(nj(r.activeTabId),tr(r.open))},[nk,nv,nK,tn]),nV=(0,i.useCallback)((e,t)=>{tj.current?.insertText((0,n3.$C)(e,t)),A&&(tr(!1),te(!1))},[A]),nJ=(0,i.useCallback)(e=>{let t=(0,n3.SO)(e);t&&tj.current?.insertText(t),A&&(tr(!1),te(!1))},[A]),nY=(0,i.useCallback)((e,t,n)=>{tj.current?.insertText((0,n3.sn)(e,t,n)),A&&(tr(!1),te(!1))},[A]),nX=(0,i.useCallback)(async(e,t)=>{let n=await (0,gA.Cn)((0,sM.c)(e,"download",t),(0,gL.WP)(e));if(n.size>0xa00000)throw Error("Image is too large to attach");tj.current?.addImages([n]),tj.current?.focus(),A&&(tr(!1),te(!1))},[A]),n0=$.sessionId,n1=$.sessionFromTab?null:$.sessionId,[n2,n4]=(0,i.useState)(()=>!n0),n8=er?.root.id??null;(0,i.useEffect)(()=>{if(!Q||!n2)return;let e=nP.current;if(!nz.current||e!==n8){nz.current&&e&&!nO.current&&nK(e),nO.current=!1,nz.current=!0,nP.current=n8;let t={tabs:[],activeId:null,open:!1};if(n8)try{t=function(e,t,n){try{let r=JSON.parse(e??"null"),i=[];for(let e of Array.isArray(r?.tabs)?r.tabs:[]){if("string"!=typeof e?.sessionId||"string"!=typeof e.label)continue;let r=n.find(t=>t.id===e.sessionId);r?.relation?.kind!=="side"||r.relation.parentSessionId!==t||i.some(t=>t.sessionId===e.sessionId)||i.push({sessionId:e.sessionId,label:e.label,side:!0})}let s=i.some(e=>`agent:${e.sessionId}`===r?.activeId)?r.activeId:null;return{tabs:i,activeId:s,open:r?.open===!0}}catch{return{tabs:[],activeId:null,open:!1}}}(window.sessionStorage.getItem(gT(n8)),n8,Y)}catch{}nL(e=>[...e.filter(e=>!e.side),...t.tabs]);let n=t.activeId===`agent:${V?.id}`?null:t.activeId;(n||nk?.startsWith("agent:")||!nk)&&(nj(n??nv.at(-1)?.id??nI.at(-1)?.id??null),tr(n?t.open:!!(nv.length||nI.length)&&tn));return}n8&&nK(n8),nO.current=!1},[nk,Q,nv,n2,nK,tn,V?.id,Y,n8,nI]),(0,i.useLayoutEffect)(()=>{var e;let t=(e=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:gW();if(!e)return null;try{return gF(e.getItem(gO))}catch{return null}}(),$.requestedCwd||$.sessionId||!e?$:"session"===e.kind?{...$,sessionId:e.sessionId,sessionFromTab:!0}:{...$,requestedCwd:e.cwd});t!==$&&(T(t),t.sessionId&&n4(!1))},[$]);let n5=(0,i.useRef)(!1),n9=(0,i.useRef)(!1),n7=(0,i.useRef)(0),re=(0,i.useCallback)(()=>{n7.current+=1},[]);(0,i.useEffect)(()=>{if(V){!function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:m();if(n)try{let r=g(n);r[e]=t,n.setItem(h,JSON.stringify(r))}catch{}}(V.projectKey??nD.current??x(V),V.id),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:gW();if(t&&e)try{gD({kind:"session",sessionId:e},t)}catch{}}(V.id);return}em&&function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:gW(),n=e.trim();if(t&&n)try{gD({kind:"new",cwd:n},t)}catch{}}(em)},[em,V]),(0,i.useEffect)(()=>{let e=$.requestedCwd;if(!e)return;let t=new AbortController;return eR("validating"),eL(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}`);n5.current=!0;let r=`initial:${e}`;ex(r),eb.current=`new:${r}:${n.cwd}`,eg(n.cwd),eR("ready"),new URLSearchParams(window.location.search).get("cwd")||I.replace(`?cwd=${encodeURIComponent(n.cwd)}`,{scroll:!1})}).catch(e=>{t.signal.aborted||(eL(e instanceof Error?e.message:String(e)),eR("error"))}),()=>t.abort()},[$,I]);let rt=(0,i.useCallback)((e,t)=>{let n=++n7.current,r=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:m();if(!t)return null;try{let n=g(t)[e];return"string"==typeof n&&n.length>0?n:null}catch{return null}}(e);if(!r)return;let i=i=>{if(n!==n7.current)return;let s=i?.sessions.find(e=>e.id===r);if(!s){i&&f(e);return}if(x(s)!==e)return void f(e);let a=eb.current;a&&n6(a,nG(t)),eb.current=null,J(s),eW(e=>e+1),new URLSearchParams(window.location.search).get("session")!==s.id&&I.replace(`?session=${encodeURIComponent(s.id)}`,{scroll:!1})};Y.length>0?i({sessions:Y}):fetch("/api/sessions").then(e=>e.ok?e.json():null).then(i).catch(()=>{})},[I,Y]),rn=(0,i.useCallback)((e,t,n)=>{re();let r=em??nW;if(nF(e),!e)return;let i=n9.current;n9.current=!1;let s=n??t??e,a=nD.current??(V?x(V):null);if(nD.current=s,n5.current){n5.current=!1;return}if(r===e&&a!==s||a===s&&(null!==V||r===e))return;let l=eb.current;l&&r&&n6(l,nG(r));let o="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,d=`new:${o}:${e}`;n6(nG(e),d),ex(o),eb.current=d,J(null),eg(t=>t&&t!==e?null:t),eW(e=>e+1),tE([]),tT(null),tR(!1),tW(null),tD(null),tH(!1),nr(e=>"debug"===e?e:null),a!==s&&(nZ(a,s),i||rt(s,e)),I.replace(window.location.pathname,{scroll:!1})},[nW,nZ,re,em,I,V,rt]),rr=(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;eH(n?{sessionId:e.id,entryId:n,blockIndex:r}:null),re();let s=eb.current,a=em??(null===V?nW:null);s&&a&&n6(s,nG(a)),eb.current=null;let l=x(e);if(nD.current!==l&&(nZ(nD.current,l),nr(e=>"debug"===e?e:null)),nD.current=l,!t&&V){let t=x(V)===x(e);if(V.id===e.id&&t){A&&te(!1);return}}eg(null),J(e),eW(e=>e+1),tE([]),tT(null),tR(!1),tA.current=null,tW(null),tD(null),tH(!1),n4(!0),!A||t||i?.keepSidebarOpen||te(!1),t&&(n5.current=!0),t&&new URLSearchParams(window.location.search).get("session")===e.id||I.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[nW,nZ,re,I,A,em,V]),ri=(0,i.useCallback)((e,t,n,r)=>{re();let i=`new:${e}:${t}`,s=eb.current,a=em??(null===V?nW:null);if(r?.carryComposer&&null===V&&s){let e=tj.current;e?e.rekeyDraft(s,i):n6(s,i),eI(eC.current)}else s&&a&&a!==t&&n6(s,nG(a));let l=n??(t===nW?nD.current:null)??t;nD.current!==l&&nZ(nD.current,l),nD.current=l,nQ(i)||n6(nG(t),i),eb.current=i,ex(e),J(null),eg(t),eW(e=>e+1),tE([]),tT(null),tR(!1),tW(null),tD(null),tH(!1),nr(e=>"debug"===e?e:null),A&&te(!1),I.replace(`?cwd=${encodeURIComponent(t)}`,{scroll:!1}),A||eS.current||requestAnimationFrame(()=>{document.activeElement?.closest("[aria-modal='true']")||tj.current?.focus()})},[nW,nZ,re,A,em,I,V]),rs=(0,i.useCallback)(e=>{ri(`kb-${Date.now()}`,e)},[ri]);!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||!a)return;let t=e.target?.tagName;"TEXTAREA"!==t&&"INPUT"!==t&&(e.preventDefault(),a())}(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:rs,activeCwd:nW});let ra=(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&&J(t=>t?.id===e?{...t,...n,transient:n.transient??!1}:t)}).catch(()=>{})},[]),rl=(0,i.useCallback)((e,t)=>{ez(e=>e+1),eb.current===t&&(re(),eb.current=null,eg(null),J(e),ra(e.id),I.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1}))},[re,I,ra]),ro=(0,i.useCallback)(e=>{let{targetSession:t,title:n,body:r,tag:i}=e;if(!("Notification"in window))return;let s=()=>{gz({title:n,body:r,sessionUrl:t?`/?session=${encodeURIComponent(t.id)}`:"/",tag:i,onClick:()=>{window.focus(),t&&rr(t)}})};"granted"===Notification.permission?(s(),l$(M)):"default"===Notification.permission&&Notification.requestPermission().then(e=>{"granted"===e&&(s(),l$(M))})},[rr,M]),rd=(0,i.useCallback)(e=>{ez(e=>e+1),eK(e=>e+1),e.aborted||e.subagentsActive||o(V?.relation)||!gP()||(V&&q(e=>{if(e.has(V.id))return e;let t=new Set(e);return t.add(V.id),t}),ro({targetSession:V,title:V?.name??R("i18n.sessionComplete"),body:R("i18n.taskFinished"),tag:V?`pi-session-complete:${V.id}`:"pi-session-complete"}))},[ro,V,R]);(0,i.useEffect)(()=>{let e=()=>{"visible"===document.visibilityState&&document.hasFocus()&&q(e=>0===e.size?e:new Set)};return e(),document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e)}},[]);let rc=(0,i.useCallback)(e=>{var t;!o(V?.relation)&&gP()&&(t=U.current,!(!iv(e)||t.has(e.id))&&(t.add(e.id),1)&&ro({targetSession:V,title:R("i18n.attentionNeeded"),body:"custom"===e.method?R("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[ro,V,R]),ru=(0,i.useCallback)(async()=>{let e=V?.id;if(e&&"naming"!==t0.kind){t2.current&&clearTimeout(t2.current),nr(null),t1({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(ez(e=>e+1),t4.current!==e)return;J(t=>t?.id===e?{...t,name:r}:t),tQ(t=>t?.sessionId===e?{...t,sessionName:r}:t),t1({kind:"success"}),t2.current=setTimeout(()=>t1({kind:"idle"}),1800)}catch(t){if(t4.current!==e)return;t1({kind:"error",message:t instanceof Error?t.message:String(t)}),t2.current=setTimeout(()=>t1({kind:"idle"}),5e3)}}},[t0.kind,V?.id]);(0,i.useEffect)(()=>{t2.current&&clearTimeout(t2.current),t1({kind:"idle"})},[V?.id]);let rp=(0,i.useCallback)(()=>{eK(e=>e+1)},[]),rh=(0,i.useRef)(null),rm=(0,i.useCallback)(e=>{gK.has(e)||rh.current||(rh.current=setTimeout(()=>{rh.current=null,eK(e=>e+1)},1e3))},[]);(0,i.useEffect)(()=>()=>{rh.current&&clearTimeout(rh.current)},[]);let rg=(0,i.useCallback)(e=>{re(),eb.current=null,ez(e=>e+1),eW(e=>e+1),eg(null),J(t=>({...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1})),ra(e),I.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1})},[re,I,ra]),rf=(0,i.useCallback)(()=>{n4(!0),n1&&(n9.current=!0)},[n1]),rb=(0,i.useCallback)(e=>{re(),ez(e=>e+1);let t=G.current;if(t?.id===e){!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:gW();if(t&&e)try{let n=gF(t.getItem(gO));if(n?.kind!=="session"||n.sessionId!==e)return;t.removeItem(gO)}catch{}}(e);let n=t.cwd,r="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;ex(r),eb.current=n?`new:${r}:${n}`:null,J(null),eg(n??null),eW(e=>e+1),tE([]),tT(null),tR(!1),tW(null),tD(null),tH(!1),nr(e=>"debug"===e?e:null),I.replace(n?`?cwd=${encodeURIComponent(n)}`:window.location.pathname,{scroll:!1})}},[re,I]),rv=(0,i.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,i=n?.modeHint,s=n?.page,a=`file:${e}`;ny(n=>(0,sA.cG)(n,{fileName:t,filePath:e,modeHint:i,page:s,sourceSessionId:r,tabId:a})),nj(a),tr(!0),A&&te(!1)},[A]),ry=(0,i.useCallback)((e,t)=>{rv(e,(0,gL.WP)(e),{sourceSessionId:V?.id??null,page:t})},[rv,V?.id]),rk=(0,i.useCallback)(()=>{let e=new URLSearchParams;nW&&e.set("cwd",nW);let t=nv.find(e=>e.id===nk);t?.filePath&&e.set("path",t.filePath);let n=""!==e.toString()?`?${e.toString()}`:"";window.open(`/files${n}`,"_blank","noopener")},[nW,nk,nv]),rj=(0,i.useCallback)(e=>{let t=nI.find(t=>t.cwd===e),n=t??(0,g$.Wg)(e);t||nE(e=>[...e,n]),nj(n.id),tr(!0),A&&te(!1)},[nI,A]),rw=(0,i.useCallback)(e=>{nT(t=>t.includes(e)?t:[...t,e]),nj(`git-graph:${e}`),tr(!0),A&&te(!1)},[A]),rS=(0,i.useCallback)((e,t,n)=>{nL(r=>r.some(t=>t.sessionId===e)?r:[...r,{sessionId:e,label:t,...n?{side:!0}:{}}]),nj(`agent:${e}`),tr(!0),A&&te(!1)},[A]),rC=(0,i.useMemo)(()=>new Set(tn?nA.map(e=>e.sessionId):[]),[nA,tn]),rN=(0,i.useCallback)((e,t)=>{let n=er?er.subagents.find(t=>t.id===e)??(er.root.id===e?er.root:void 0):void 0;n?rr(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}`);rr(n.info)}catch{rS(e,t)}})()},[er,rr,rS]),rI=(0,i.useCallback)((e,t)=>{let n=e.relation?.kind==="side"?e.relation.parentSessionId:null;if(!n||n===nP.current)return rS(e.id,t,!0),!0;try{let r=gT(n);window.sessionStorage.setItem(r,function(e,t,n){let r=[];try{let t=JSON.parse(e??"null");Array.isArray(t?.tabs)&&(r=t.tabs)}catch{}return JSON.stringify({tabs:[...r,{sessionId:t,label:n,side:!0}],activeId:`agent:${t}`,open:!0})}(window.sessionStorage.getItem(r),e.id,t))}catch{}return!1},[rS]),rE=(0,i.useCallback)(e=>{let t=tX(e,Y,R("agentSwitcher.sideChat")),n=t?Y.find(e=>e.id===t.parentSessionId):void 0;t&&n&&(X(t=>t.some(t=>t.id===e.id)?t:[e,...t]),rI(e,t.label)||rr(n))},[rr,rI,Y,R]),r$=(0,i.useCallback)((e,t)=>{t&&tS(n=>({...n,[e.id]:t})),X(t=>[e,...t.filter(t=>t.id!==e.id)]),rI(e,R("agentSwitcher.sideChat")),ez(e=>e+1)},[rI,R]),rT=(0,i.useCallback)(async e=>{let t=await iT(e,R);return"error"in t?t.error:(A&&nr(null),r$(t.session,null),null)},[r$,A,R]),rM=nA.filter(e=>e.side&&ei.has(e.sessionId)).map(e=>e.sessionId).join();(0,i.useEffect)(()=>{rM&&ez(e=>e+1)},[rM]);let rR=(0,i.useCallback)(e=>{if(nI.some(t=>t.id===e))return void nE(t=>t.map(t=>t.id!==e||t.closing?t:{...t,closing:"close"}));if(e.startsWith("git-graph:")){let t=n$.filter(t=>`git-graph:${t}`!==e);nT(t),nj(n=>{if(n!==e)return n;let r=t.at(-1);return nv.at(-1)?.id??nI.at(-1)?.id??(void 0!==r?`git-graph:${r}`:null)??gq(nA)}),0===nv.length&&0===nI.length&&0===t.length&&0===nA.length&&tr(!1);return}if(e.startsWith("agent:")){let t=nA.filter(t=>`agent:${t.sessionId}`!==e);nL(t),nj(n=>{if(n!==e)return n;let r=n$.at(-1);return nv.at(-1)?.id??nI.at(-1)?.id??(void 0!==r?`git-graph:${r}`:null)??gq(t)}),0===nv.length&&0===nI.length&&0===n$.length&&0===t.length&&tr(!1);return}ny(t=>{let n=t.filter(t=>t.id!==e);return 0===n.length&&0===nI.length&&0===n$.length&&0===nA.length&&tr(!1),n}),nj(t=>{if(t!==e)return t;let n=nv.filter(t=>t.id!==e),r=n$.at(-1);return n.at(-1)?.id??nI.at(-1)?.id??(void 0!==r?`git-graph:${r}`:null)??gq(nA)})},[nv,nI,n$,nA]),rA=(0,i.useCallback)(e=>{rb(e),rR(`agent:${e}`)},[rb,rR]),rL=(0,i.useCallback)(async(e,t)=>{let n=await iM(e);return n?n.error:(rR(`agent:${e}`),G.current?.id===e?(rr(t),ez(e=>e+1)):rb(e),null)},[rR,rr,rb]),rP=V?.id;(0,i.useEffect)(()=>{nA.some(e=>e.sessionId===rP)&&rR(`agent:${rP}`)},[nA,rR,rP]);let rz=(0,i.useCallback)(()=>{V&&window.open(`/api/sessions/${encodeURIComponent(V.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[V]),rO=em??(null===V&&nW?nW:null),rW=null===V&&rO?`new:${ef}:${rO}`:null;(0,i.useLayoutEffect)(()=>{eb.current=rW},[rW]);let rF=(0,i.useCallback)((e,t)=>{null===V&&rO&&e.cwd!==rO&&(eS.current=t,e.projectKey&&e.projectRoot&&ej.current?.cwd!==e.cwd&&(ej.current={cwd:e.cwd,project:{key:e.projectKey,root:e.projectRoot},branch:null}),ev.current?.startNewSessionIn({...e,carryComposer:!0}))},[rO,V]),rD=(0,i.useRef)(rF);rD.current=rF;let rB=(0,i.useCallback)(e=>{ev.current?.openFolderForNewSession(e=>rD.current(e,"project"),e)},[]),rH=(0,i.useCallback)(()=>{ev.current?.openDefaultDirectoryForNewSession(e=>rD.current(e,"project"))},[]),r_=(0,i.useCallback)(()=>{ev.current?.refreshWorktrees()},[]),rU=(0,i.useCallback)(async(e,t)=>{let n=ev.current;if(!n)throw Error("The session sidebar is not mounted");let r=await n.createWorktree(e,t);return"path"in r&&(ej.current={cwd:r.path,project:e,branch:t}),r},[]),rK=(0,i.useCallback)(()=>{eS.current=null},[]),rq=null===V&&rO?(0,r.jsx)(sT,{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},a=s.alias??i.find(e=>e.key===s.key)?.alias;return{cwd:t,project:void 0===a?s:{...s,alias:a},worktrees:null,currentWorktreePath:null,projects:i}}(ey,rO,ej.current),mobile:A,initialFocus:eS.current,onInitialFocusDone:rK,onPick:rF,onUseDefaultDirectory:rH,onOpenFolder:rB,onRefreshWorktrees:r_,onCreateWorktree:rU}):null,rZ=null!==V||null!==rO,rV=V?.cwd??rO,rJ=n2&&!rZ;(0,i.useEffect)(()=>{rZ||nr(e=>"debug"===e?null:e)},[rZ]),(0,i.useEffect)(()=>{if(e2(null),e8(!1),e9(null),!rV)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(rV)}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);e2(t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[rV]);let rG=(0,i.useCallback)(async()=>{if(rV&&!e6){e3(!0),e9(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:rV})}),t=await e.json();if(!e.ok||t.error)return void e9({error:t.error??`HTTP ${e.status}`,...t.reason?{reason:t.reason}:{}});e2(t),e8(!1),eY(e=>e+1),eW(e=>e+1)}catch(e){e9({error:e instanceof Error?e.message:String(e)})}finally{e3(!1)}}},[e6,rV]),rY=(0,i.useCallback)(()=>{e9(null),e8(!0)},[]),rX=(0,i.useCallback)((e,t)=>{e===rV&&e2(t)},[rV]),rQ=nv.find(e=>e.id===nk)??null,r0=nA.find(e=>`agent:${e.sessionId}`===nk)??null,r1=nk?.startsWith("git-graph:")?n$.find(e=>`git-graph:${e}`===nk)??null:null,r2=nW?(0,gL.WP)(nW)||nW:null,r4=r2?`${r2} - Pi Web`:"Pi Web";(0,i.useEffect)(()=>{let e=()=>{document.title!==r4&&(document.title=r4)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[r4]);let r8=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(np,{selectedSessionId:V?.id??null,onSelectSession:rr,onSelectSideChat:rE,onNewSession:ri,controlRef:ev,onNewSessionContextChange:ew,initialSessionId:n0,initialSessionLinked:null!==n1,skipInitialProjectSelection:null!==$.requestedCwd,onInitialRestoreDone:rf,refreshKey:eP,onSessionDeleted:rb,selectedCwd:V?.cwd??em??null,onCwdChange:rn,onOpenFile:rv,onOpenTerminal:rj,onOpenGitGraph:rw,explorerRefreshKey:eU,onExplorerRefresh:rp,onAtMention:nV,onAtMentions:nJ,onBackgroundTaskDone:Z,hiddenFinishedSessionIds:K,onRunningSessionIdsChange:ea,onSessionsChange:et}),(0,r.jsxs)("div",{style:{padding:"8px",flexShrink:0,display:"flex",justifyContent:"space-between",gap:4},children:[[["models",R("common.models")],["skills",R("common.skills")],["automations",R("common.automations")]].map(e=>{let[t,n]=e,i=sF(t)&&!rV;return(0,r.jsxs)("button",{type:"button",onClick:()=>nm(t),disabled:i,title:i?R("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)(hf,{section:t,size:14,strokeWidth:2}),(0,r.jsx)("span",{children:n})]},t)}),(0,r.jsxs)("button",{type:"button",onClick:()=>{eJ(!0),eZ(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sD();if(!t)return"general";try{let n=sB(t).section;if(!("string"==typeof n&&sz.includes(n)))return"general";return sF(n)&&!e?"general":n}catch{return"general"}}(rV))},title:R("common.settings"),"aria-label":R("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)(hf,{section:"general",size:14,strokeWidth:2}),(0,r.jsx)("span",{children:R("common.settings")})]})]})]}),r6=e=>rZ&&e1?.requiresTrust&&!e1.trusted?(0,r.jsxs)("button",{type:"button",onClick:rY,title:R("trust.resourcesNotLoaded"),"aria-label":R("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:R("trust.resourcesNotLoaded")})]}):null,r3=e=>(0,r.jsxs)("button",{ref:ep,type:"button",onClick:()=>na("agents",e&&!L),disabled:!er||!0===er.root.ephemeral,title:eo,"aria-label":eo,"aria-pressed":"agents"===nn,style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?gU:void 0,height:"100%",padding:e?0:"0 12px",background:"agents"===nn?"var(--bg-selected)":"none",border:"none",borderTop:"agents"===nn?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"agents"===nn?"var(--text)":er?"var(--text-muted)":"var(--text-dim)",cursor:er?"pointer":"not-allowed",opacity:er?1:.45,flexShrink:0,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},"data-mobile-toolbar-action":e?"agents":void 0,children:[(0,r.jsxs)("svg",{width:e?16:13,height:e?16:13,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,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:R("agentSwitcher.title")}),el&&el.count>0&&(0,r.jsxs)("span",{"aria-hidden":"true",style:{position:"relative",minWidth:15,height:15,padding:"0 4px",display:"grid",placeItems:"center",borderRadius:7,background:el.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:el.running?600:void 0,...e?{position:"absolute",top:3,right:3,minWidth:13,height:13,padding:"0 3px",fontSize:9}:{}},children:[el.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"})]}),el.count]})]}),r9=e=>{let t,n,i,s,a,l;return e||rZ?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",height:"100%"},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>{rz(),e&&L&&to(!0)},disabled:!V,title:V?R("history.full"):R("history.unsaved"),"aria-label":R("history.full"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?gU:void 0,height:"100%",padding:e?0:"0 12px",background:"none",border:"none",borderTop:"2px solid transparent",borderRight:"1px solid var(--border)",color:V?"var(--text-muted)":"var(--text-dim)",cursor:V?"pointer":"not-allowed",opacity:V?1:.45,flexShrink:0,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s, opacity 0.1s"},onMouseEnter:e=>{V&&(e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{e.currentTarget.style.color=V?"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:e?16:12,height:e?16:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:V?"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:R("history.label")})]}),(t=!!(V&&((tY?.userMessages??0)>0||V.messageCount>0)),n=!V||V.transient||!t||"naming"===t0.kind,i="success"===t0.kind,s="error"===t0.kind,a="naming"===t0.kind?R("title.generating"):i?R("title.updated"):s?R("title.failed"):R("title.generate"),l=!V||V.transient?R("title.unsaved"):t?s?t0.message:R("title.generateSession"):R("title.noMessages"),(0,r.jsxs)("button",{type:"button",onClick:()=>{ru(),e&&L&&to(!0)},disabled:n,title:l,"aria-label":a,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?gU: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"!==t0.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"===t0.kind?(0,r.jsxs)("svg",{className:"animate-spin",width:e?16:13,height:e?16:13,viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[(0,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:e?16:13,height:e?16:13,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:e?16:13,height:e?16:13,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,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:a})]})),!(e&&L)&&r3(e),tL&&(e?(0,r.jsx)("button",{type:"button",onClick:()=>na("branches",!0),title:R("i18n.branches"),"aria-label":R("i18n.branches"),"aria-pressed":"branches"===nn,style:{display:"flex",alignItems:"center",justifyContent:"center",width:gU,height:"100%",padding:0,background:"branches"===nn?"var(--bg-selected)":"none",border:"none",borderTop:"branches"===nn?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"branches"===nn?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0},"data-mobile-toolbar-action":"branches",children:(0,r.jsxs)("svg",{width:e?16:12,height:e?16:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:tI.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)(hP,{tree:tI,activeLeafId:t$,onLeafChange:tz,locked:tM,inline:!0,containerRef:tC,open:"branches"===nn,onToggle:()=>na("branches"),hasSession:!0})),(0,r.jsxs)("button",{ref:tK,type:"button",onClick:()=>nu("system",e),disabled:e&&!rZ,title:R("system.prompt"),"aria-label":R("system.prompt"),"aria-pressed":"system"===nn,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?gU:void 0,height:"100%",padding:e?0:"0 12px",background:"system"===nn?"var(--bg-selected)":"none",border:"none",borderTop:"system"===nn?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:e&&!rZ?"not-allowed":"pointer",color:"system"===nn?"var(--text)":"var(--text-muted)",opacity:e&&!rZ?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||rZ)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="system"===nn?"var(--text)":"var(--text-muted)"},"data-mobile-toolbar-action":e?"system":void 0,children:[(0,r.jsxs)("svg",{width:e?16:12,height:e?16:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:tO?"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:R("system.label")})]}),(0,r.jsxs)("button",{type:"button",onClick:()=>nu("tools",e),disabled:e&&!rZ,title:R("tools.title"),"aria-label":R("tools.title"),"aria-pressed":"tools"===nn,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?gU:void 0,height:"100%",padding:e?0:"0 12px",background:"tools"===nn?"var(--bg-selected)":"none",border:"none",borderTop:"tools"===nn?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:e&&!rZ?"not-allowed":"pointer",color:"tools"===nn?"var(--text)":"var(--text-muted)",opacity:e&&!rZ?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||rZ)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="tools"===nn?"var(--text)":"var(--text-muted)"},"data-mobile-toolbar-action":e?"tools":void 0,children:[(0,r.jsx)("svg",{width:e?16:12,height:e?16:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:tF?.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:R("tools.label")})]})]}):null},r7=e=>{if(!e&&(!rZ||!tY&&!t7))return null;let t=tY?.tokens,n=tY?.cost??0,i=i_.eX,s=(0,i_.tb)(n),a="var(--text-muted)",l=null,o=null;if(t7?.contextWindow){let e=t7.percent;null!==e&&e>90?a="#ef4444":null!==e&&e>70&&(a="rgba(234,179,8,0.95)"),l=null!==e?`${e.toFixed(0)}% / ${i(t7.contextWindow)}`:`? / ${i(t7.contextWindow)}`,o=null!==e?`${e.toFixed(0)}%`:null}let d=[];if(t&&(d.push(`${R("session.input")}: ${t.input.toLocaleString(M)}`),d.push(`${R("session.output")}: ${t.output.toLocaleString(M)}`),d.push(`${R("session.cacheRead")}: ${t.cacheRead.toLocaleString(M)}`),d.push(`${R("session.cacheWrite")}: ${t.cacheWrite.toLocaleString(M)}`),n>0&&d.push(`${R("session.cost")}: $${n.toFixed(4)}`)),t7?.contextWindow){let e=t7.percent;d.push(`${R("session.context")}: ${null!==e?`${e.toFixed(1)}%`:"?"} / ${t7.contextWindow.toLocaleString(M)}`)}let c=d.join(" | "),u=e&&L&&tl,p=!!(t&&(t.input>0||t.output>0)||s||o);return(0,r.jsx)("button",{type:"button",onClick:()=>na("session"),disabled:!rZ||u,tabIndex:u?-1:void 0,title:c||R("session.title"),"aria-label":R("session.title"),"aria-pressed":"session"===nn,"aria-hidden":!!u||void 0,className:e?"mobile-session-stats":void 0,"data-mobile-toolbar-stats":e?"true":void 0,style:{marginLeft:0,display:"flex",alignItems:"center",justifyContent:"flex-end",flex:e?1:void 0,minWidth:0,gap:e?7:10,paddingLeft:e?6:12,paddingRight:e?6:12,height:"100%",overflow:"hidden",visibility:u?"hidden":"visible",pointerEvents:u?"none":"auto",background:"session"===nn?"var(--bg-selected)":"none",border:"none",...e?{}:{borderLeft:"1px solid var(--border)"},borderTop:"session"===nn?"2px solid var(--accent)":"2px solid transparent",fontSize:11,color:"var(--text-muted)",whiteSpace:"nowrap",cursor:rZ?"pointer":"default",fontVariantNumeric:"tabular-nums",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{rZ&&!u&&(e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="session"===nn?"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"})]}),i(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"})]}),i(t.output)]}),s&&(0,r.jsx)("span",{className:"mobile-session-stat-cost",style:{color:"var(--text)",fontWeight:500,flexShrink:0},children:s}),o&&(0,r.jsx)("span",{style:{color:a,flexShrink:0},children:o}),!p&&rZ&&(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",color:"var(--text-dim)"},children:R("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"})]}),i(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"})]}),i(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"})]}),i(t.cacheRead)]}),s&&(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",color:"var(--text)",fontWeight:500},children:s}),l&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4,color:a},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"})]}),l]})]})})},ie=e=>{if(!rZ)return null;let t="debug"===nn;return(0,r.jsx)("button",{ref:nl,type:"button",onClick:()=>na("debug",e),title:R("debug.title"),"aria-label":R("debug.title"),"aria-pressed":t,style:{marginLeft:0,display:"flex",alignItems:"center",justifyContent:"center",width:gU,height:"100%",padding:0,background:t?"var(--bg-selected)":"none",border:"none",borderTop:t?"2px solid var(--accent)":"2px solid transparent",...e?{borderRight:"1px solid var(--border)"}:{borderLeft:"1px solid var(--border)"},color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color=t?"var(--text)":"var(--text-muted)"},"data-mobile-toolbar-action":e?"debug":void 0,children:(0,r.jsxs)("svg",{width:e?16:13,height:e?16:13,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:t?"var(--accent)":"var(--text-dim)",flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M8 2l1.9 1.9M16 2l-1.9 1.9M9 7.1v-1a3 3 0 0 1 6 0v1"}),(0,r.jsx)("path",{d:"M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6zM12 20v-9"}),(0,r.jsx)("path",{d:"M6.5 9C4.6 8.8 3 7.1 3 5M6 13H2M3 21c0-2.1 1.7-3.9 3.8-4M21 5c0 2.1-1.6 3.8-3.5 4M22 13h-4M17.2 17c2.1.1 3.8 1.9 3.8 4"})]})})},it=e=>{if(!rZ)return null;let t="usage"===nn;return(0,r.jsx)("button",{ref:no,type:"button",onClick:()=>na("usage",e),title:R("usage.title"),"aria-label":R("usage.title"),"aria-pressed":t,style:{display:"flex",alignItems:"center",justifyContent:"center",width:gU,height:"100%",padding:0,background:t?"var(--bg-selected)":"none",border:"none",borderTop:t?"2px solid var(--accent)":"2px solid transparent",...e?{borderRight:"1px solid var(--border)"}:{},color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color=t?"var(--text)":"var(--text-muted)"},"data-mobile-toolbar-action":e?"usage":void 0,children:(0,r.jsx)("svg",{width:e?16:13,height:e?16:13,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:e?1.9:2,strokeLinecap:"round",strokeLinejoin:"round",style:{color:t?"var(--accent)":"var(--text-dim)",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 20V10M12 20V4M19 20v-7"})})})},ir=e=>{let t=e&&L&&tl;return(0,r.jsx)("button",{type:"button",onClick:nx,disabled:t,tabIndex:t?-1:void 0,"aria-controls":"file-panel","aria-expanded":tn,"aria-hidden":!!t||void 0,title:tn?R("files.hidePanel"):R("files.showPanel"),"aria-label":tn?R("files.hidePanel"):R("files.showPanel"),"data-mobile-toolbar-file":e?"true":void 0,style:{marginLeft:e||rZ?0:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:gU,height:gU,padding:0,visibility:t?"hidden":"visible",pointerEvents:t?"none":"auto",background:tn?"var(--bg-selected)":"none",border:"none",borderLeft:"1px solid var(--border)",color:tn?"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=tn?"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:`
1375
+ @keyframes session-info-pop {
1376
+ 0% {
1377
+ opacity: 0;
1378
+ transform: translateY(-24px);
1379
+ filter: blur(6px);
1380
+ box-shadow: 0 2px 8px rgba(0,0,0,0);
1381
+ }
1382
+ 55% {
1383
+ opacity: 1;
1384
+ transform: translateY(0);
1385
+ filter: blur(0);
1386
+ background: color-mix(in srgb, var(--accent) 8%, var(--bg-panel));
1387
+ box-shadow: 0 18px 44px rgba(37,99,235,0.16);
1388
+ }
1389
+ 100% {
1390
+ opacity: 1;
1391
+ transform: translateY(0);
1392
+ filter: blur(0);
1393
+ background: var(--bg-panel);
1394
+ box-shadow: 0 10px 28px rgba(0,0,0,0.10);
1395
+ }
1396
+ }
1397
+ @keyframes session-info-light-wash {
1398
+ 0% {
1399
+ opacity: 0;
1400
+ transform: translateX(-110%) skewX(-16deg);
1401
+ }
1402
+ 24% {
1403
+ opacity: 0.42;
1404
+ }
1405
+ 100% {
1406
+ opacity: 0;
1407
+ transform: translateX(115%) skewX(-16deg);
1408
+ }
1409
+ }
1410
+ .session-info-popover {
1411
+ position: relative;
1412
+ overflow: hidden;
1413
+ transform-origin: top right;
1414
+ animation: session-info-pop 360ms ease-out both;
1415
+ will-change: transform, opacity, filter, background, box-shadow;
1416
+ }
1417
+ .session-info-popover::after {
1418
+ content: "";
1419
+ position: absolute;
1420
+ top: 0;
1421
+ bottom: 0;
1422
+ left: 0;
1423
+ width: 44%;
1424
+ pointer-events: none;
1425
+ background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--accent) 24%, transparent), transparent);
1426
+ animation: session-info-light-wash 620ms ease-out both;
1427
+ }
1428
+ @media (prefers-reduced-motion: reduce) {
1429
+ .session-info-popover,
1430
+ .session-info-popover::after {
1431
+ animation: none;
1432
+ }
1433
+ }
1434
+ .mobile-session-stats {
1435
+ container-type: inline-size;
1436
+ }
1437
+ @container (max-width: 158px) {
1438
+ .mobile-session-stat-io {
1439
+ display: none !important;
1440
+ }
1441
+ }
1442
+ @container (max-width: 88px) {
1443
+ .mobile-session-stat-cost {
1444
+ display: none !important;
1445
+ }
1446
+ }
1447
+ @media (max-width: 640px) {
1448
+ .sidebar-overlay-backdrop.sidebar-mobile-pending {
1449
+ opacity: 0 !important;
1450
+ pointer-events: none !important;
1451
+ }
1452
+ .sidebar-container.sidebar-mobile-pending.sidebar-open {
1453
+ transform: translateX(calc(-100% - env(safe-area-inset-left)));
1454
+ box-shadow: none;
1455
+ }
1456
+ }
1457
+ `}),(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${tu?"":" sidebar-mobile-pending"}`,onClick:()=>te(!1),style:{position:"fixed",inset:0,zIndex:199,background:"rgba(0,0,0,0.4)",opacity:+!!e7,pointerEvents:e7?"auto":"none",transition:"opacity 0.25s ease"}}),(0,r.jsx)("div",{ref:tb.panelRef,id:"session-sidebar",inert:ta,className:`sidebar-container${e7?" sidebar-open":" sidebar-closed"}${tu?"":" sidebar-mobile-pending"}${tb.isResizing?" sidebar-resizing":""}`,style:{"--sidebar-width":`${tb.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:r8}),e7&&(0,r.jsx)("div",{...tb.separatorProps,inert:ta,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${tb.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${R("layout.resizeSidebar")}: ${R("layout.resizeHint")}`}),(0,r.jsxs)("div",{inert:ta,style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:[(0,r.jsxs)("div",{ref:tC,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(var(--top-bar-height) + env(safe-area-inset-top))",paddingTop:"env(safe-area-inset-top)"},children:[(0,r.jsx)("button",{onClick:ng,title:e7?R("sidebar.hide"):R("sidebar.show"),"aria-label":e7?R("sidebar.hide"):R("sidebar.show"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:gU,height:gU,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:e7?(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"})]})}),(0,r.jsx)("button",{type:"button",onClick:()=>{nW&&rs(nW)},disabled:!nW,title:nW?R("sidebar.newSessionTitle",{path:nW}):R("sidebar.new"),"aria-label":nW?R("sidebar.newSessionTitle",{path:nW}):R("sidebar.new"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:gU,height:gU,padding:0,background:"none",border:"none",borderRight:"1px solid var(--border)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},children:(0,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:"12",y1:"8",x2:"12",y2:"16"}),(0,r.jsx)("line",{x1:"8",y1:"12",x2:"16",y2:"12"})]})}),A&&(0,r.jsxs)("div",{ref:tN,"data-mobile-toolbar":"true",style:{position:"relative",display:"flex",alignItems:"stretch",flex:1,minWidth:0,height:"100%"},children:[L&&r3(!0),L&&(0,r.jsx)("button",{type:"button",onClick:nf,title:td,"aria-label":td,"aria-controls":"mobile-toolbar-actions","aria-expanded":tl,"data-mobile-toolbar-more":"true",style:{position:"relative",zIndex:tl?21:void 0,display:"flex",alignItems:"center",justifyContent:"center",width:gU,height:gU,padding:0,background:tl?"var(--bg-selected)":"none",border:"none",borderRight:"1px solid var(--border)",color:tl?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s, background 0.12s"},children:tl?(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"})]})}),!L&&r9(!0),!L&&it(!0),!L&&ie(!0),r7(!0),ir(!0),L&&tl&&(0,r.jsxs)("div",{id:"mobile-toolbar-actions",role:"toolbar","aria-label":R("chat.moreControls"),"data-mobile-toolbar-actions":"true",style:{position:"absolute",top:0,right:0,bottom:0,left:`calc(2 * ${gU})`,zIndex:20,display:"flex",alignItems:"stretch",overflowX:"auto",overflowY:"hidden",scrollbarWidth:"none",background:"color-mix(in srgb, var(--bg-panel) 94%, var(--bg))",boxShadow:"4px 0 18px rgba(0,0,0,0.12)",backdropFilter:"blur(10px)"},children:[r9(!0),it(!0),ie(!0)]})]}),!A&&r6(!1),!A&&r9(!1),!A&&rZ&&(0,r.jsxs)("div",{style:{marginLeft:"auto",display:"flex",height:"100%",borderLeft:"1px solid var(--border)"},children:[it(!1),ie(!1),r7(!1)]}),!A&&ir(!1),A&&tL&&(0,r.jsx)(hP,{tree:tI,activeLeafId:t$,onLeafChange:tz,locked:tM,inline:!0,compact:!0,containerRef:tC,open:"branches"===nn,onToggle:()=>na("branches"),hasSession:rZ,hideInlineButton:!0}),nn&&ni&&(0,r.jsxs)("div",{style:{position:"fixed",top:ni.top,left:ni.left,width:ni.width,maxHeight:`calc(100dvh - ${ni.top}px)`,overflowY:"auto",zIndex:500},children:["agents"===nn&&er&&!0!==er.root.ephemeral&&V&&(0,r.jsx)(hG,{rootSession:er.root,subagents:er.subagents,selectedSessionId:V.id,runningSessionIds:ei,onSelectSession:e=>{nr(null),rr(e),requestAnimationFrame(()=>eE(document,ep.current))},openSubagentTabIds:rC,onToggleSubagentTab:(e,t,n)=>{rC.has(e)?rR(`agent:${e}`):(A&&nr(null),rS(e,t,n))},onNewSideChat:()=>rT(er.root.id),onDeleteSideChat:e=>rL(e,er.root)}),"system"===nn&&(0,r.jsx)(hz,{loading:tB,prompt:tO,translate:R}),"tools"===nn&&(0,r.jsx)(hF,{loading:tB,tools:tF,translate:R}),"session"===nn&&(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:tY?(n=tY.totalActiveMs??0,d=[...tY.sessionName?[{label:R("session.name"),value:tY.sessionName,copyField:null}]:[],{label:R("session.file"),value:tY.sessionFile??R("session.inMemory"),copyField:"file"},{label:R("session.id"),value:tY.sessionId,copyField:"id"},...n>0?[{label:R("session.totalActive"),value:(0,i_.ik)(n),copyField:null}]:[]],p=[...V?[{label:R("session.projectDir"),value:V.projectRoot??V.cwd,copyField:"projectDir"}]:[],...V?.branch?[{label:R("session.gitBranch"),value:V.branch,copyField:"gitBranch"}]:[],...V?.isWorktree?[{label:R("session.gitWorktree"),value:V.cwd,copyField:"gitWorktree"}]:[]],b=[[R("session.user"),tY.userMessages.toLocaleString(M)],[R("session.assistant"),tY.assistantMessages.toLocaleString(M)],[R("session.toolCalls"),tY.toolCalls.toLocaleString(M)],[R("session.toolResults"),tY.toolResults.toLocaleString(M)],[R("session.total"),tY.totalMessages.toLocaleString(M)]],v=[[R("session.input"),tY.tokens.input.toLocaleString(M)],[R("session.output"),tY.tokens.output.toLocaleString(M)],...tY.tokens.cacheRead>0?[[R("session.cacheRead"),tY.tokens.cacheRead.toLocaleString(M)]]:[],...tY.tokens.cacheWrite>0?[[R("session.cacheWrite"),tY.tokens.cacheWrite.toLocaleString(M)]]:[],[R("session.total"),tY.tokens.total.toLocaleString(M)]],y=t7??tY.contextUsage,k=[...tY.cost>0?[[R("session.cost"),`$${tY.cost.toFixed(4)}`]]:[],...y?.contextWindow?[[R("session.context"),`${null!==y.percent?`${y.percent.toFixed(1)}%`:"?"} / ${(0,i_.eX)(y.contextWindow)}`]]:[],...tY.tokens.cacheRead+tY.tokens.cacheWrite>0&&tY.tokens.cacheRead+tY.tokens.cacheWrite+tY.tokens.input>0?[[R("session.cacheHitRate"),`${(tY.tokens.cacheRead/(tY.tokens.cacheRead+tY.tokens.cacheWrite+tY.tokens.input)*100).toFixed(1)}%`]]:[]],j=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,a]=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:a})]},`${e}:${s}`)})})]})},w={file:"session.copyFile",id:"session.copyId",projectDir:"session.copyProjectDir",gitBranch:"session.copyGitBranch",gitWorktree:"session.copyGitWorktree"},S=(e,t)=>{let n=t6===e;return(0,r.jsx)("button",{type:"button",title:n?R("session.copied"):R(w[e]),onClick:()=>t9(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"})]})})},C=(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:R("session.infoSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:d.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?S(e.copyField,e.value):null})]},`session-info:${e.label}`))})]}),N=p.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:R("session.projectSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:p.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?S(e.copyField,e.value):null})]},`project-info:${e.label}`))})]}):null,(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:A?"1fr":"minmax(360px, 1.7fr) minmax(140px, 0.55fr) minmax(190px, 0.75fr)",gap:A?16:24,fontSize:12,lineHeight:1.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:A?16:20},children:[C,N]}),j(R("session.messages"),b),j(R("session.tokens"),[...v,...k],"right",!0)]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:R("session.load")})}),"debug"===nn&&(0,r.jsx)(mT,{fallback:R("debug.failed"),children:(0,r.jsx)(mM,{readerRef:tJ,selectedSessionId:V?.id??null,sessions:en,onClose:nd})}),"usage"===nn&&(0,r.jsx)(gx,{onClose:nc})]})]}),eu&&er&&!0!==er.root.ephemeral&&V&&"agents"!==nn&&(0,r.jsx)(hX,{rootSession:er.root,members:eu,selectedSessionId:V.id,runningSessionIds:ei,onSelectSession:rr,locked:ed,onToggleLock:eh}),A&&r6(!0)]}),(0,r.jsx)("div",{style:{flex:1,overflow:"hidden",position:"relative"},children:rZ?(0,r.jsx)(sy,{session:V,searchTarget:eB?.sessionId===V?.id?eB:null,onSearchTargetHandled:e_,initialScrollPosition:V?eF.current.get(V.id)??null:null,onScrollPositionChange:eD,sessionRunning:!!(V&&ei.has(V.id)),newSessionCwd:rO,newSessionDraftKey:rW,newSessionContextBar:rq,initialNewSessionChoices:null===V?eN:null,onNewSessionChoicesChange:eT,onAgentEnd:rd,onSessionEnded:rA,onToolEnd:rm,onAttentionNeeded:rc,onSessionCreated:rl,onSessionForked:rg,onSideSession:r$,modelsRefreshKey:eG,chatInputRef:tj,onBranchDataChange:tP,onSystemPromptChange:tq,onSystemToolsChange:tZ,onSystemInfoLoaderChange:tV,onDebugSnapshotReaderChange:tG,onSessionStatsChange:t8,onSessionStatsPanelOpen:nh,onOpenSettings:nm,onContextUsageChange:nt,onOpenFile:ry,onFilesUploaded:rp,onOpenSubagent:rS,onEnterSubagent:rN,quoteSelectionEnabled:B,soundEnabled:P,onSoundToggle:z,playDoneSound:O,unlockAudio:W,holdAudio:F},eO):"validating"===eM?(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:R("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:$.requestedCwd})]}):"error"===eM?(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:R("workspace.unable")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:$.requestedCwd}),(0,r.jsx)("div",{style:{maxWidth:720,fontSize:12},children:eA})]}):rJ?nW?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:R("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:R("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."}),R("workspace.selectProject"),(0,r.jsx)("br",{}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),R("workspace.addModels")]})]})]}):null})]}),(0,r.jsx)("div",{"aria-hidden":"true",className:`right-panel-overlay-backdrop${tn?" is-open":""}`,onClick:()=>tr(!1)}),tn&&(0,r.jsx)("div",{...tv.separatorProps,inert:ta,"aria-controls":"file-panel",className:`panel-resize-handle right-panel-resize-handle${tv.isResizing?" is-resizing":""}`,"data-resize-handle":"right-panel",title:`${R("layout.resizeFilePanel")}: ${R("layout.resizeHint")}`}),(0,r.jsxs)("div",{ref:tv.panelRef,id:"file-panel",className:`right-panel-container${tn?" right-panel-open":" right-panel-closed"}${ta?" right-panel-full-width":""}${tv.isResizing?" right-panel-resizing":""}`,style:{"--right-panel-width":`${tv.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(var(--top-bar-height) + env(safe-area-inset-top))",paddingTop:"env(safe-area-inset-top)",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{flex:1,overflow:"hidden"},children:(0,r.jsx)(sR.V,{tabs:n_,activeTabId:nk??"",onSelectTab:nj,onCloseTab:rR,onReorderTab:(e,t,n)=>nH(function(e,t,n,r){if(t===n||!e.includes(t)||!e.includes(n))return e;let i=e.filter(e=>e!==t);return i.splice(i.indexOf(n)+ +!!r,0,t),i}(n_.map(e=>e.id),e,t,n))})}),(0,r.jsx)("button",{type:"button",className:"file-panel-expand-button",onClick:rk,title:R("files.openInPage"),"aria-label":R("files.openInPage"),children:(0,r.jsxs)("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:"M14 3h7v7"}),(0,r.jsx)("path",{d:"M21 3l-9 9"}),(0,r.jsx)("path",{d:"M19 14v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h5"})]})}),(0,r.jsx)("button",{type:"button",className:"file-panel-expand-button",onClick:nb,"aria-controls":"file-panel","aria-pressed":ta,title:R(ta?"files.restorePanelWidth":"files.expandPanel"),"aria-label":R(ta?"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:ta?"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:()=>tr(!1),"aria-controls":"file-panel","aria-expanded":tn,title:R("files.hidePanel"),"aria-label":R("files.hidePanel"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:gU,height:gU,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:[rQ?.filePath?(0,r.jsx)(sM.h,{filePath:rQ.filePath,cwd:nW??void 0,sourceSessionId:rQ.sourceSessionId,gitRefreshKey:eU,initialDisplayMode:rQ.initialDisplayMode,initialPage:rQ.page,initialState:rQ.viewerState,watchEnabled:tn,onStateChange:e=>nq(nS,rQ.id,rQ.viewerRevision??0,e),onMentionLines:tn?nY:void 0,onAtMention:nV,onOpenFile:(e,t)=>rv(e,(0,gL.WP)(e),{sourceSessionId:rQ.sourceSessionId,page:t}),onAddToChat:e=>nX(e,rQ.sourceSessionId)},`${nS}:${rQ.id}:${rQ.viewerRevision??0}`):nI.some(e=>e.id===nk)||r0||r1?null:(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12},children:R("files.noneOpen")}),null!==r1&&(0,r.jsx)(gN,{cwd:r1,refreshKey:eU},`git-graph:${r1}`),nI.map(e=>(0,r.jsx)("div",{hidden:e.id!==nk,style:{width:"100%",height:"100%"},children:(0,r.jsx)(gy.z,{tab:e,active:tn&&e.id===nk,onRestart:()=>nE(t=>t.map(t=>t.id===e.id?{...t,closing:"restart"}:t)),onClosed:()=>{let t,n;return t="restart"===e.closing?(0,g$.Wg)(e.cwd):null,n=nI.filter(t=>t.id!==e.id),void(nE(n=>n.flatMap(n=>n.id!==e.id?[n]:t?[t]:[])),nj(r=>r!==e.id?r:t?.id??n.at(-1)?.id??nv.at(-1)?.id??gq(nA)),!t&&!n.length&&!nv.length&&!n$.length&&!nA.length&&tr(!1))},onCloseError:()=>nE(t=>t.map(t=>t.id===e.id?{...t,closing:void 0}:t))})},e.id)),r0&&(0,r.jsx)(gv,{sessionId:r0.sessionId,onSessionEnded:rA,running:ei.has(r0.sessionId),initialPrompt:tw[r0.sessionId],onInitialPromptConsumed:()=>tS(e=>{if(!(r0.sessionId in e))return e;let t={...e};return delete t[r0.sessionId],t}),modelsRefreshKey:eG,quoteSelectionEnabled:B,onOpenFile:ry,onOpenSubagent:rS,onSessionForked:e=>{A&&tr(!1),rg(e)},onOpenSettings:nm,onToolEnd:rm,onFilesUploaded:rp,soundEnabled:P,onSoundToggle:z,playDoneSound:O,unlockAudio:W,holdAudio:F},r0.sessionId)]})]})]}),eq&&(0,r.jsx)(hk,{cwd:rV,sessionId:V?.id??null,initialSection:eq,openAtHome:eV,quoteSelectionEnabled:B,onQuoteSelectionChange:_,onClose:()=>{eZ(null),eY(e=>e+1)},onSessionReloaded:()=>eW(e=>e+1),projectTrust:e1,onOpenTrustDialog:rY,onProjectTrustChanged:rX}),e4&&rV&&(0,r.jsx)(hw,{cwd:rV,busy:e6,error:e5,onCancel:()=>{e6||e8(!1)},onConfirm:()=>void rG(),onStatus:e2})]})}},76853:(e,t,n)=>{Promise.resolve().then(n.bind(n,18967)),Promise.resolve().then(n.bind(n,21278))},88576: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"}}},e=>{e.O(0,[1177,7330,3888,1449,8986,5772,9242,1278,6219,7676,284,8441,3794,7358],()=>e(e.s=76853)),_N_E=e.O()}]);