@mcy2015/pi-web 0.15.2 → 0.15.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 (62) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +16 -16
  3. package/.next/build-manifest.json +3 -3
  4. package/.next/prerender-manifest.json +4 -4
  5. package/.next/required-server-files.js +1 -1
  6. package/.next/required-server-files.json +1 -1
  7. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  8. package/.next/server/app/_global-error.html +1 -1
  9. package/.next/server/app/_global-error.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  13. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  14. package/.next/server/app/_not-found.html +1 -1
  15. package/.next/server/app/_not-found.rsc +4 -4
  16. package/.next/server/app/_not-found.segments/_full.segment.rsc +4 -4
  17. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +4 -4
  18. package/.next/server/app/_not-found.segments/_tree.segment.rsc +3 -3
  19. package/.next/server/app/api/app-update/route.js +1 -1
  20. package/.next/server/app/files/page_client-reference-manifest.js +1 -1
  21. package/.next/server/app/files.html +1 -1
  22. package/.next/server/app/files.rsc +5 -5
  23. package/.next/server/app/files.segments/_full.segment.rsc +5 -5
  24. package/.next/server/app/files.segments/_tree.segment.rsc +3 -3
  25. package/.next/server/app/files.segments/files/__PAGE__.segment.rsc +5 -5
  26. package/.next/server/app/index.html +1 -1
  27. package/.next/server/app/index.rsc +7 -7
  28. package/.next/server/app/index.segments/__PAGE__.segment.rsc +7 -7
  29. package/.next/server/app/index.segments/_full.segment.rsc +7 -7
  30. package/.next/server/app/index.segments/_tree.segment.rsc +3 -3
  31. package/.next/server/app/login/page_client-reference-manifest.js +1 -1
  32. package/.next/server/app/login.html +1 -1
  33. package/.next/server/app/login.rsc +5 -5
  34. package/.next/server/app/login.segments/_full.segment.rsc +5 -5
  35. package/.next/server/app/login.segments/_tree.segment.rsc +3 -3
  36. package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +5 -5
  37. package/.next/server/app/page.js +237 -4
  38. package/.next/server/app/page_client-reference-manifest.js +1 -1
  39. package/.next/server/app/share/[code]/page_client-reference-manifest.js +1 -1
  40. package/.next/server/app-paths-manifest.json +16 -16
  41. package/.next/server/chunks/1795.js +1 -1
  42. package/.next/server/chunks/210.js +1 -1
  43. package/.next/server/chunks/2243.js +1 -1
  44. package/.next/server/middleware-build-manifest.js +1 -1
  45. package/.next/server/pages/404.html +1 -1
  46. package/.next/server/pages/500.html +1 -1
  47. package/.next/server/preview-props.json +3 -3
  48. package/.next/server/server-reference-manifest.json +1 -1
  49. package/.next/static/chunks/1278-18168afcae945536.js +1 -0
  50. package/.next/static/chunks/app/{layout-359d2b23511791df.js → layout-8d3937ab2a76815c.js} +1 -1
  51. package/.next/static/chunks/app/page-48aef8a176e49041.js +1308 -0
  52. package/.next/static/chunks/{webpack-cd45b4de345ebf8e.js → webpack-f375baffc2b385a0.js} +1 -1
  53. package/.next/static/css/{2c29b7c4172be516.css → 1c235f9240d931ae.css} +1 -1
  54. package/.next/static/css/c99d24fe85e139cc.css +1 -0
  55. package/.next/trace +206 -206
  56. package/.next/trace-build +1 -1
  57. package/package.json +1 -1
  58. package/.next/static/chunks/1278-4b202bfe4eee1db9.js +0 -1
  59. package/.next/static/chunks/app/page-350d895a60a4035b.js +0 -1075
  60. package/.next/static/css/4b68e9dc21ffa2cb.css +0 -1
  61. /package/.next/static/{d_8gDpXdfGq2Cy2CDqhNN → rUwtj0bvC8-50TXIMaR4Y}/_buildManifest.js +0 -0
  62. /package/.next/static/{d_8gDpXdfGq2Cy2CDqhNN → rUwtj0bvC8-50TXIMaR4Y}/_ssgManifest.js +0 -0
@@ -1,1075 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{14755:(e,t,n)=>{"use strict";n.d(t,{Q8:()=>r,YO:()=>p,getPresetFromTools:()=>u,kU:()=>a,sn:()=>c,xG:()=>h});let r="configured",i=["configured","none","read-only","default","full"],s=[],a=["read","grep","find","ls"],o=["read","bash","edit","write"],l=["bash","read","edit","write","grep","find","ls"],d=new Set([...l,"powershell"]);function c(e){return"string"==typeof e&&i.includes(e)}function u(e){return p(e.filter(e=>e.active).map(e=>e.name))}function p(e){if(0===e.length)return"none";let t=e.map(e=>"powershell"===e?"bash":e).filter(e=>d.has(e)).sort().join(",");return t===[...a].sort().join(",")?"read-only":t===[...o].sort().join(",")?"default":t===[...l].sort().join(",")?"full":"default"}function h(e){if(e!==r)return"none"===e?[...s]:"read-only"===e?[...a]:"full"===e?[...l]:[...o]}},68470:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>mX});var r=n(95155),i=n(12115),s=n(73321);let a=null;function o(e,t,n){if(e.name&&"Side chat"!==e.name)return e.name;let r=n.filter(e=>e.relation?.kind==="side").sort((e,t)=>e.created.localeCompare(t.created)||e.id.localeCompare(t.id)).findIndex(t=>t.id===e.id);return r<0?t:`${t} ${r+1}`}function l(e){return e?.kind==="subagent"||e?.kind==="side"}function d(e){let t=function(e){let t=new Map(e.map(e=>[e.id,e])),n=new Map;for(let r of e){if(n.has(r.id))continue;let e=[],i=new Set,s=r.id,a=null;for(;;){if(n.has(s)){a=n.get(s)??null;break}if(i.has(s))break;i.add(s),e.push(s);let r=t.get(s);if(!r)break;if(!l(r.relation)){a=r.id;break}s=r.relation.parentSessionId}for(let t of e)n.set(t,a)}return n}(e),n=new Map;for(let t of e)l(t.relation)||n.set(t.id,{root:t,subagents:[],latestModified:t.modified});for(let r of e){if(!l(r.relation))continue;let e=t.get(r.id),i=e?n.get(e):void 0;i&&(i.subagents.push(r),r.modified>i.latestModified&&(i.latestModified=r.modified))}return[...n.values()].sort((e,t)=>t.latestModified.localeCompare(e.latestModified))}function c(e,t){return e.filter(e=>t.has(e.id)).length}function u(e){return`?session=${encodeURIComponent(e)}`}let p="pi-web:last-open-by-workspace";function h(){try{return window.localStorage}catch{return null}}function m(e){let t=e.getItem(p);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function g(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:h();if(t)try{let n=m(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(p):t.setItem(p,JSON.stringify(n))}catch{}}function f(e){return e.projectKey??e.projectRoot??e.cwd}function x(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=f(n),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{root:e,modified:n.modified})}return[...t.entries()].sort((e,t)=>t[1].modified.localeCompare(e[1].modified)).map(e=>{let[t,{root:n}]=e;return{key:t,root:n}})}let b=/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/,v=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function y(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function j(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function k(e){return"string"==typeof e&&e.length>0&&e.length<=4096&&"__proto__"!==e}let w=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;function S(e){if(null===e)return null;if("string"!=typeof e)return;let t=e.trim();return t?w.test(t)||[...t].length>80?void 0:t:null}let C=new TextEncoder;function N(e){return C.encode(JSON.stringify(e)).length+1}function I(e){let t=1;for(let n of e)t+=N(n);return t}function $(e,t){return e<=1e3&&t<=262144}function E(e){let t=[],n=1;for(let r of e){if(t.length>=1e3)break;let e=N(r);n+e>262144||(t.push(r),n+=e)}return t}function T(e,t){return C.encode(JSON.stringify(e)).length+C.encode(JSON.stringify(t)).length+2}function M(e,t){return e<=1e3&&t<=262144}function R(){return{version:1,revision:0,sessions:{},projects:{}}}function A(e,t,n){let r=v(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 L(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 P(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 z(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 O={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}},W="pinned";function F(e,t){return Object.hasOwn(e.sessions,t)?e.sessions[t]:void 0}function D(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function B(e,t){return e===t?0:e>t?-1:1}function H(e){return[e.root.id,...e.subagents.map(e=>e.id)]}function _(e,t){return 0!==t.size&&(t.has(e.root.id)||e.subagents.some(e=>t.has(e.id)))}function U(e,t,n){let r=D(F(t,e.root.id)?.archivedAt);if(null===r||_(e,n))return!1;if(e.root.detailsPending)return!0;let i=Date.parse(e.root.modified);return Number.isNaN(i)||r>=i}function q(e,t,n){return null!==D(F(t,e.root.id)?.pinnedAt)&&!U(e,t,n)}function K(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 Z(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 V(e,t){var n;return{running:_(e,t.runningIds),awaiting:!!t.awaitingIds&&_(e,t.awaitingIds),unread:_(e,t.unreadIds),selected:!!(n=t.selectedSessionId)&&(e.root.id===n||e.subagents.some(e=>e.id===n)),transient:!0===e.root.transient}}function J(e,t){let n=0,r=0,i=0;for(let s of e)t.awaitingIds&&_(s,t.awaitingIds)?r++:_(s,t.runningIds)&&n++,_(s,t.unreadIds)&&i++;return{running:n,awaiting:r,unread:i}}function G(e){return f(e.root)}function Y(e,t){let n=new Map,r=new Map;return{noteFamily(e){let t=G(e);n.has(t)||n.set(t,e.root.projectRoot??e.root.cwd)},get(i){let s,a=r.get(i);if(a)return a;let o=Object.hasOwn(e.projects,i)?e.projects[i]:void 0,l=null!==t&&t.key===i,d=n.get(i)??(l?t.root:void 0)??o?.root??i,c=((s=e.projectNames)&&v(s,i)?s[i]:void 0)??null,u={key:i,root:d,name:c??K(d),customName:c,pinned:void 0!==o,current:l};return r.set(i,u),u}}}function X(e,t,n,r){return{kind:"session",key:`session:${t}:${e.root.id}`,family:e,context:t,project:n,status:V(e,r)}}function Q(e,t,n,r){let i=e.map((e,n)=>{if(n<t)return!1;let i=V(e,r);return i.running||i.unread||i.selected}),s=t+n,a=0,o=e.filter((e,n)=>n<t||!!i[n]||n<s&&(a++,!0)),l=Math.max(t,Math.min(s,e.length));for(let t=0;l<e.length&&t<20;l++)!i[l]&&t++;return{visible:o,revealed:a,nextShown:l-t}}function ee(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 et(e,t){if(!Object.hasOwn(e,t))return e;let n={...e};return delete n[t],n}function en(e,t,n){let r=e-t,i=n>0;return r>0||i?{hidden:r,canShowLess:i}:null}function er(e,t,n,r){let i=r-n,s=[];for(let n of d(e.sessions)){if(G(n)!==t||U(n,e.uiState,e.runningIds)||q(n,e.uiState,e.runningIds))continue;let r=V(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 ei(e,t){let n=[],r=0;for(let i of d(e.sessions))if(G(i)===t&&!i.root.transient){if(_(i,e.runningIds)||e.awaitingIds&&_(i,e.awaitingIds)){r++;continue}n.push(i.root.id)}return{ids:n,running:r}}function es(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 ea(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:Math.max(0,s-Math.max(0,(r-(a-s))/2))}var eo=n(23579);async function el(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 ed(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function ec(e,t){let n=t.replace(/[/\\]+$/,"");return n&&(e===n||e.startsWith(`${n}/`)||e.startsWith(`${n}\\`))?`./${e.slice(n.length).replace(/^[/\\]/,"")}`:ed(e)}let eu=/ · [0-9a-f]{4}$/;function ep(e){let t=eu.exec(e);return t&&0!==t.index?{base:e.slice(0,t.index),suffix:t[0]}:null}function eh(e,t){return{cwd:e.current&&t?t:e.root,projectKey:e.key,projectRoot:e.root}}function em(e){let t=e.project;return!t||e.projects.some(e=>e.key===t.key)?[...e.projects]:[t,...e.projects]}function eg(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 ef(e){let t=e.map(e=>({choice:e,name:e.alias??K(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?K(t.slice(0,r)):null}})}let ex={awaiting:"#d97706",unread:"#0891b2"};function eb(e){return Number.isFinite(e)?Math.max(0,Math.floor(e)):0}let ev=null,ey=null,ej=new Map;function ek(){return[...document.querySelectorAll('link[rel="icon"]')]}async function ew(e,t){let n=await (!ey&&(ey=new Promise(e=>{let t=new Image;t.onload=()=>e(t),t.onerror=()=>e(null),t.src="/icons/icon-192.png"})),ey);if(!n||ev!==t)return;let r=document.createElement("canvas");r.width=192,r.height=192;let i=r.getContext("2d");if(!i)return;i.clearRect(0,0,192,192),i.drawImage(n,0,0,192,192);let s=e.count>1,a=s?56:42,o=192-a-10,l=a+10;if(i.beginPath(),i.arc(o,l,a,0,2*Math.PI),i.fillStyle=ex[e.kind],i.fill(),i.lineWidth=10,i.strokeStyle="#ffffff",i.stroke(),s&&(i.fillStyle="#ffffff",i.font=`bold ${e.count>9?56:68}px system-ui, sans-serif`,i.textAlign="center",i.textBaseline="middle",i.fillText(String(e.count),o,l+4)),ev!==t)return;let d=r.toDataURL("image/png");for(let e of ek())e.href=d}function eS(e){return e.isComposing||229===e.keyCode}function eC(e,t){let n=e.activeElement;return!!t&&(!n||n===e.body)&&(t.focus({preventScroll:!0}),!0)}var eN=n(16913);let eI="pi-web:sidebar-files-placement",e$="below";function eE(){try{var e;return e=window.localStorage.getItem(eI),"tab"===e?"tab":e$}catch{return e$}}let eT=null,eM=new Set;function eR(){return null===eT&&(eT=eE()),eT}function eA(){eM.forEach(e=>e())}function eL(e){if(null!==e.key&&e.key!==eI)return;let t=eE();t!==eT&&(eT=t,eA())}function eP(e){return 0===eM.size&&(window.addEventListener("storage",eL),eT=eE()),eM.add(e),()=>{eM.delete(e),0===eM.size&&window.removeEventListener("storage",eL)}}function ez(e){if(e!==eR()){eT=e;try{window.localStorage.setItem(eI,e)}catch{}eA()}}function eO(){return(0,i.useSyncExternalStore)(eP,eR,()=>e$)}var eW=n(21278),eF=n(31590),eD=n(12545);function eB(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];(0,i.useEffect)(()=>{if(!t)return;let n=null,r=null,i=!1,s=null,a=()=>{null!==s&&(clearTimeout(s),s=null)},o=()=>{n&&(a(),n.classList.add("scrollbar-visible"))},l=()=>{n&&(a(),s=setTimeout(()=>{s=null,n?.classList.remove("scrollbar-visible")},500))},d=()=>{o(),l()},c=()=>{if(!i){if(!(n=e.current)){r=requestAnimationFrame(c);return}n.addEventListener("pointerenter",o),n.addEventListener("pointerleave",l),n.addEventListener("scroll",d)}};return c(),()=>{i=!0,null!==r&&cancelAnimationFrame(r),n?.removeEventListener("pointerenter",o),n?.removeEventListener("pointerleave",l),n?.removeEventListener("scroll",d),a(),n?.classList.remove("scrollbar-visible")}},[t,e])}let eH="/api/sessions/ui-state";async function e_(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 eU(e){return e instanceof Error?e.message:String(e)}async function eq(e){if(!e.ok)throw Error(await e_(e));let t=await e.json(),n=t&&"object"==typeof t?function(e){if(!y(e)||void 0!==e.version&&1!==e.version||void 0!==e.sessions&&!y(e.sessions)||void 0!==e.projects&&!y(e.projects))return null;let t=R(),n=e.revision;for(let[r,i]of("number"==typeof n&&Number.isSafeInteger(n)&&n>=0&&(t.revision=n),Object.entries(e.sessions??{}))){if(!("string"==typeof r&&b.test(r)))continue;let e=function(e){if(!y(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(!k(n))continue;let e=y(r)&&j(r.pinnedAt)&&k(r.root)?{pinnedAt:r.pinnedAt,root:r.root}:null;e&&(t.projects[n]=e)}if(Array.isArray(e.projectOrder)){let n=new Set,r=E(e.projectOrder.filter(e=>!(!k(e)||n.has(e))&&(n.add(e),!0)));r.length>0&&(t.projectOrder=r)}if(y(e.projectNames)){let n={},r=0,i=1;for(let[t,s]of Object.entries(e.projectNames)){let e=S(s);if(!k(t)||"string"!=typeof e)continue;let a=T(t,e);M(r+1,i+a)&&(n[t]=e,r++,i+=a)}r>0&&(t.projectNames=n)}return t}(t.state):null;if(!n)throw Error("Invalid session UI state response");return n}function eK(){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 eZ=n(47650);let eV={overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},eJ={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},eG={padding:"6px 16px",borderRadius:6,fontSize:13},eY={...eG,border:0,background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600},eX={...eG,border:"1px solid var(--border)",background:"none",color:"var(--text-muted)"};async function eQ(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 e0(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 e1(){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 e2(){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 e4(e){let{onCancel:t,onSelect:n,initialPath:s,busy:a=!1,error:o}=e,{t:l}=(0,eW.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),[j,k]=(0,i.useState)(null),[w,S]=(0,i.useState)(!0),[C,N]=(0,i.useState)(!1),[I,$]=(0,i.useState)(""),[E,T]=(0,i.useState)(null),[M,R]=(0,i.useState)(!1),A=(0,i.useRef)(!1),L=(0,i.useRef)(!1),P=(0,i.useCallback)(async e=>{S(!0),k(null);try{let t=await eQ(e),n=t.path??e??"/";p(n),m(t.parentPath??null),f(n),b(t.directories??[]),y(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{c(document.body),P(s||void 0)},[s,P]);let z=()=>{M||(N(!1),$(""),T(null))},O=async()=>{let e=I.trim();if(u&&e&&!M){R(!0),T(null);try{let t=await e0(u,e);N(!1),$(""),await P(t)}catch(e){T(e instanceof Error?e.message:String(e))}finally{R(!1)}}},W=g.trim()!==u,F=!!u&&!W&&!a&&!w,D=!!h||/^[a-zA-Z]:[\\/]?$/.test(u);return d?(0,eZ.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":l("directoryPicker.selectDirectory"),onPointerDown:e=>{A.current=e.target===e.currentTarget},onClick:e=>{let n=A.current;A.current=!1,n&&e.target===e.currentTarget&&!a&&t()},onPointerCancel:()=>{A.current=!1},onKeyDown:e=>{"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:{...eV,position:"relative",width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:l("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:t,disabled:a,title:l("i18n.close"),"aria-label":l("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:a?"default":"pointer",opacity:a?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=g.trim();t&&P(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 P(h??void 0),disabled:w||!D,title:l("directoryPicker.goToParent"),"aria-label":l("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:D?"pointer":"default",opacity:D?1:.45},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:l("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:g,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{f(e.target.value),k(null)},style:{...eJ,minWidth:0,flex:1}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:w||!g.trim(),title:l("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:w||!g.trim()?"default":"pointer",opacity:w||!g.trim()?.6:1},children:l("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[w?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.loadingDirectories")}):null!==v?(0,r.jsx)(r.Fragment,{children:v.length>0?v.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void P(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)(e2,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void P(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)(e1,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.noSubdirectories")}),(j||o)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:j??o})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>{N(!0),T(null)},disabled:!F,style:{...eX,marginRight:"auto",opacity:F?1:.6,cursor:F?"pointer":"default"},children:l("directoryPicker.newDirectory")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:t,disabled:a,style:{...eX,cursor:a?"default":"pointer"},children:l("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>n(u),disabled:!F,title:l(W?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{...eY,opacity:F?1:.6,cursor:F?"pointer":"default"},children:l(a?"i18n.checking":"directoryPicker.selectThisFolder")})]}),C&&(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:12,background:"rgba(0,0,0,0.35)"},onPointerDown:e=>{L.current=e.target===e.currentTarget},onClick:e=>{let t=L.current;L.current=!1,t&&e.target===e.currentTarget&&z()},onPointerCancel:()=>{L.current=!1},onKeyDown:e=>{e.stopPropagation(),"Escape"===e.key&&z()},children:(0,r.jsxs)("form",{role:"dialog","aria-modal":"true","aria-label":l("directoryPicker.createDirectory"),onSubmit:e=>{e.preventDefault(),O()},style:{...eV,width:400,maxWidth:"100%"},children:[(0,r.jsx)("div",{style:{padding:"12px 18px",borderBottom:"1px solid var(--border)",color:"var(--text)",fontSize:15,fontWeight:700},children:l("directoryPicker.createDirectory")}),(0,r.jsxs)("div",{style:{padding:"12px 18px"},children:[(0,r.jsx)("label",{htmlFor:"new-directory-name",style:{display:"block",marginBottom:6,color:"var(--text-muted)",fontSize:11},children:l("directoryPicker.directoryName")}),(0,r.jsx)("input",{id:"new-directory-name",value:I,autoFocus:!0,autoComplete:"off",spellCheck:!1,placeholder:l("directoryPicker.directoryNamePlaceholder"),onChange:e=>{$(e.target.value),T(null)},disabled:M,className:"directory-picker-path",style:{...eJ,width:"100%",boxSizing:"border-box"}}),E&&(0,r.jsx)("div",{style:{marginTop:7,color:"#dc2626",fontSize:11,lineHeight:1.35},children:E}),(0,r.jsxs)("div",{style:{display:"flex",gap:6,marginTop:10},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:M||!I.trim(),style:{...eY,flex:1,opacity:M?.65:1,cursor:M||!I.trim()?"default":"pointer"},children:l(M?"directoryPicker.creating":"directoryPicker.create")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:z,disabled:M,style:{...eX,flex:1,cursor:M?"default":"pointer"},children:l("i18n.cancel")})]})]})]})})]})}),d):null}var e8=n(46599),e6=n(65748),e3=n(7834);let e5="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function e9(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:e5[Math.floor(n()*e5.length)]}return s}function e7(e){let{onWidthChange:t}=e,{t:n}=(0,eW.s)(),[s,a]=(0,i.useState)(!1),o=(0,i.useRef)(null),l="0.15.2",d="1.5.0",c=function(e){let[t,n]=(0,i.useState)(e),r=(0,i.useRef)(e);return(0,i.useEffect)(()=>{if(r.current===e)return;if(r.current=e,window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return void n(e);let t=4*e.length,i=0,s=0,a=()=>{n(e9(e,i+=1)),i<t&&(s=requestAnimationFrame(a))};return n(e9(e,0)),s=requestAnimationFrame(a),()=>cancelAnimationFrame(s)},[e]),t}(s?`${l??"0.0.0"}p${d??"0.0.0"}`:"Pi Web");return(0,i.useLayoutEffect)(()=>{t?.()},[c.length,t]),(0,i.useEffect)(()=>()=>{o.current&&clearTimeout(o.current)},[]),(0,r.jsx)("button",{type:"button",className:`sidebar-brand${s?" is-version":""}`,"aria-label":n("sidebar.brandLabel",{app:l??"0.0.0",pi:d??"0.0.0"}),onClick:()=>{(o.current&&clearTimeout(o.current),o.current=null,s)?a(!1):(a(!0),o.current=setTimeout(()=>{o.current=null,a(!1)},3e3))},children:c})}var te=n(2730),tt=n(1518);let tn={desktop:32,mobile:48};function tr(e,t,n,r){return Math.hypot(n-e,r-t)}function ti(e){return e.getClientRects().length>0}var ts=n(72451);function ta(e){let t=(0,tt.d)(e.firstMessage)??e.firstMessage;return e.name||t.slice(0,50)||e.id.slice(0,12)}function to(e){return e.nativeEvent.isComposing||229===e.keyCode}function tl(e){let{rows:t,layout:n,emptyLabel:s,loading:a,error:o,renamingRootId:l,renamingProjectKey:d,confirmDeleteRootId:c,activeMenuRowKey:u,reveal:p}=e,{t:h}=(0,eW.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);eB(f);let[v,y]=(0,i.useState)(0),[j,k]=(0,i.useState)(0),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(()=>Date.now()),I=(0,i.useRef)(null),$=(0,i.useCallback)(()=>{null===I.current&&(I.current=requestAnimationFrame(()=>{I.current=null;let e=f.current;e&&y(e.scrollTop)}))},[]);(0,i.useLayoutEffect)(()=>{let e=f.current;if(!e)return;let t=()=>{let t=`${Math.max(0,e.offsetWidth-e.clientWidth)}px`;e.style.setProperty("--session-tree-scrollbar",t),e.offsetWidth>0&&e.closest(".session-sidebar")?.style.setProperty("--session-tree-scrollbar",t)};if(t(),k(e.clientHeight),y(e.scrollTop),"u"<typeof ResizeObserver)return;let n=new ResizeObserver(()=>{t(),k(e.clientHeight),y(e.scrollTop)});return n.observe(e),()=>n.disconnect()},[]),(0,i.useEffect)(()=>()=>{null!==I.current&&cancelAnimationFrame(I.current)},[]),(0,i.useEffect)(()=>{let e=window.setInterval(()=>N(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let E=(0,i.useCallback)(e=>{let t=e.target instanceof Element?e.target.closest("[data-row-key]"):null;S(t?.getAttribute("data-row-key")??null)},[]),T=(0,i.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||S(null)},[]),M=(0,i.useMemo)(()=>(function(e,t){let n=O[t],r=Array(e.length+1);r[0]=0;for(let t=0;t<e.length;t++)r[t+1]=r[t]+n[e[t].kind];return r})(t,n),[t,n]),R=!!e.onMoveGroup,A=(0,i.useMemo)(()=>{let e={pinned:0,other:0};for(let n of t)"group"===n.kind&&e[n.project.pinned?"pinned":"other"]++;return e},[t]),L=function(e){let{rows:t,offsets:n,enabled:r}=e,s=(0,i.useRef)(e);s.current=e;let a=(0,i.useMemo)(()=>(function(e,t){let n=[],r=0;for(;r<e.length;){var i;let s=e[r];if("group"!==s.kind){r++;continue}let a=r;for(;a>0&&"spacer"===e[a-1].kind;)a--;let o=r+1;for(;o<e.length&&("group-more"===(i=e[o]).kind||"group-empty"===i.kind||"session"===i.kind&&"group"===i.context);)o++;let l=o;for(;l<e.length&&"spacer"===e[l].kind;)l++;n.push({key:s.project.key,pinned:s.project.pinned,top:t[r],bottom:t[o],gapAbove:t[r]-t[a],gapBelow:t[l]-t[o]}),r=o}return n})(t,n),[t,n]),o=(0,i.useRef)(a);o.current=a;let l=(0,i.useRef)(null),d=(0,i.useRef)(0),[c,u]=(0,i.useState)(null),p=(0,i.useMemo)(()=>{let e=e=>{u("armed"===e.phase||"dragging"===e.phase?{projectKey:e.projectKey,phase:e.phase,drop:e.drop}:null)},t=e=>{let t=s.current.innerRef.current;return t?function(e,t,n){let r=e.find(e=>e.key===t);if(!r)return null;let i=e.filter(e=>e.pinned===r.pinned),s=i.indexOf(r),a=i.filter(e=>e!==r);if(0===a.length)return null;let o=a.filter(e=>(e.top+e.bottom)/2<n).length;if(o===s)return null;let l=a[a.length-1],d=Math.max(3,o<a.length?a[o].top-a[o].gapAbove/2:l.bottom+l.gapBelow/2);return o>0?{anchorKey:a[o-1].key,position:"after",lineY:d}:{anchorKey:a[0].key,position:"before",lineY:d}}(o.current,e.projectKey,e.clientY-t.getBoundingClientRect().top):null},n=()=>{let e=l.current,t=s.current.ghostRef.current,n=s.current.treeRef.current,r=s.current.innerRef.current,i=s.current.scrollRef.current;if(!e?.ghost||!t||!n||!i)return;let a=n.getBoundingClientRect().top,o=i.getBoundingClientRect(),d=t.offsetHeight,c=function(e){let{pointerY:t,lineY:n,ghostHeight:r,pointerGap:i,lineGap:s,minTop:a,maxTop:o}=e,l=Math.max(a,o),d=t-i-r,c=null!==n&&n>=a&&n<=l+r?n:null,u=e=>e>=a&&e<=l,p=e=>null!==c&&e>c-s-r&&e<c+s,h=null===c?[d,a,t+i,l]:[d,c-s-r,a,t+i,c+s,l],m=e=>{let t=null;for(let n of h)e(n)&&(null===t||Math.abs(n-d)<Math.abs(t-d))&&(t=n);return t};return m(e=>u(e)&&!(e>d&&e<t+i)&&!p(e))??m(e=>u(e)&&!p(e))??Math.min(l,Math.max(a,d))}({pointerY:e.clientY,lineY:e.drop&&r?r.getBoundingClientRect().top+e.drop.lineY:null,ghostHeight:d,pointerGap:"mouse"===e.pointerType?8:28,lineGap:8,minTop:o.top,maxTop:o.bottom-d});t.style.top=`${c-a}px`,t.style.left=`${e.ghost.left}px`},r=e=>{null!==e.timer&&window.clearTimeout(e.timer),null!==e.frame&&cancelAnimationFrame(e.frame),e.timer=null,e.frame=null,s.current.scrollRef.current?.removeEventListener("scroll",p);try{e.element.hasPointerCapture(e.pointerId)&&e.element.releasePointerCapture(e.pointerId)}catch{}},i=()=>{let e=l.current;e&&(l.current=null,r(e),window.removeEventListener("pointermove",f,!0),window.removeEventListener("pointerup",x,!0),window.removeEventListener("pointercancel",b,!0),window.removeEventListener("pointerdown",v,!0),window.removeEventListener("keydown",y,!0),window.removeEventListener("contextmenu",j,!0),window.removeEventListener("blur",k),document.removeEventListener("visibilitychange",w),u(null))},a=()=>{let e=l.current;if(e){if("armed"!==e.phase&&"dragging"!==e.phase){"pending"===e.phase&&i();return}e.phase="cancelled",e.drop=null,r(e),u(null)}},c=function(){var r;let i=arguments.length>0&&void 0!==arguments[0]&&arguments[0],o=l.current;if(!o||"dragging"!==o.phase)return;let d=s.current.scrollRef.current;if(!d||!ti(d))return void a();let c=t(o),u=i||c!==(r=o.drop)&&(null===c||null===r||c.anchorKey!==r.anchorKey||c.position!==r.position||c.lineY!==r.lineY);o.drop=c,n(),u&&e(o)};function p(){c()}let h=()=>{let e=l.current;if(!e||"dragging"!==e.phase)return;e.frame=null;let t=s.current.scrollRef.current;if(!t||!ti(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,tn[s.current.layout]);if(0!==r){let n=Math.min(Math.max(0,(s.current.offsets[s.current.offsets.length-1]??0)-t.clientHeight),Math.max(0,t.scrollTop+r));n!==t.scrollTop&&(t.scrollTop=n,e.expectedScrollTop=t.scrollTop,c())}l.current===e&&"dragging"===e.phase&&(e.frame=requestAnimationFrame(h))},m=e=>{let t=s.current.scrollRef.current,n=s.current.treeRef.current;if(!t||!n||!ti(t)||!e.element.isConnected)return void a();if(e.phase="dragging","touch"!==e.pointerType)try{e.element.setPointerCapture(e.pointerId)}catch{}e.ghost={left:e.element.getBoundingClientRect().left-n.getBoundingClientRect().left+4},e.expectedScrollTop=t.scrollTop,t.addEventListener("scroll",p,{passive:!0}),e.frame=requestAnimationFrame(h),c(!0)},g=()=>{let t=l.current;t&&"pending"===t.phase&&(t.timer=null,t.phase="armed",t.armX=t.clientX,t.armY=t.clientY,t.expectedScrollTop=s.current.scrollRef.current?.scrollTop??0,e(t))};function f(e){let t=l.current;if(!t||e.pointerId!==t.pointerId)return;if("mouse"===t.pointerType&&0===e.buttons)return void i();t.clientX=e.clientX,t.clientY=e.clientY;let n=tr(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":tr(t.armX,t.armY,e.clientX,e.clientY)>=4&&m(t);break;case"dragging":c()}}function x(e){let n=l.current;if(n&&e.pointerId===n.pointerId){if("dragging"===n.phase){n.clientX=e.clientX,n.clientY=e.clientY;let r=t(n);r&&s.current.onMove(n.projectKey,r.anchorKey,r.position)}"pending"!==n.phase&&(d.current=e.timeStamp+600),i()}}function b(e){l.current&&e.pointerId===l.current.pointerId&&i()}function v(e){l.current&&e.pointerId!==l.current.pointerId&&a()}function y(e){let t=l.current;t&&"Escape"===e.key&&("armed"===t.phase||"dragging"===t.phase)&&(e.preventDefault(),e.stopPropagation(),a())}function j(e){let t=l.current;if(t){if("pending"===t.phase)return void i();e.preventDefault(),e.stopPropagation()}}function k(){i()}function w(){"hidden"===document.visibilityState&&i()}return{handlers:{onPointerDown(e,t){if(!s.current.enabled||l.current||!e.isPrimary||0!==e.button||e.ctrlKey||e.target instanceof Element&&e.target.closest(".session-tree-group-actions"))return;let n=e.currentTarget,r={pointerId:e.pointerId,pointerType:e.pointerType,projectKey:t,element:n,startX:e.clientX,startY:e.clientY,armX:e.clientX,armY:e.clientY,clientX:e.clientX,clientY:e.clientY,phase:"pending",timer:null,frame:null,expectedScrollTop:0,drop:null,ghost:null};l.current=r,window.addEventListener("pointermove",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",j,!0),window.addEventListener("blur",k),document.addEventListener("visibilitychange",w),"mouse"!==e.pointerType&&(r.timer=window.setTimeout(g,350))},onTouchMove(e){let t=l.current;if(!t||"armed"!==t.phase&&"dragging"!==t.phase)return;if(e.cancelable)return void e.preventDefault();let n=s.current.scrollRef.current;n&&n.scrollTop!==t.expectedScrollTop&&i()}},cancel:a,teardown:i,updateDrag:c,placeGhost:n}},[]);(0,i.useLayoutEffect)(()=>{let e=l.current;e&&("armed"===e.phase||"dragging"===e.phase)&&(t.some(t=>"group"===t.kind&&t.project.key===e.projectKey)?p.updateDrag():p.cancel())},[t,n,p]),(0,i.useEffect)(()=>{r||p.cancel()},[r,p]);let h=c?.phase==="dragging";(0,i.useLayoutEffect)(()=>{h&&p.placeGhost()},[h,p]),(0,i.useEffect)(()=>()=>p.teardown(),[p]);let m=(0,i.useCallback)(e=>{let t=d.current;0===t||(d.current=0,e.timeStamp>t||(e.preventDefault(),e.stopPropagation()))},[]),g=(0,i.useCallback)(()=>{d.current=0},[]);return{view:(0,i.useMemo)(()=>{if(!c)return null;let e="dragging"===c.phase?a.find(e=>e.key===c.projectKey)??null:null;return{...c,source:e}},[c,a]),handlers:p.handlers,onClickCapture:m,onPointerDownCapture:g}}({rows:t,offsets:M,layout:n,enabled:R&&!a,scrollRef:f,innerRef:x,treeRef:g,ghostRef:b,onMove:(e,t,n)=>m.current.onMoveGroup?.(e,t,n)}),P=L.view,z=P?`group:${P.projectKey}`:null,[F,D]=(0,i.useState)(null),B=p&&p.id!==F?p:null,H=B?.rowKey??null,_=(0,i.useMemo)(()=>{let e=[];return t.forEach((t,n)=>{t.key===w||t.key===u||t.key===H||t.key===z||"session"===t.kind&&(t.family.root.id===l||t.family.root.id===c)?e.push(n):"group"===t.kind&&t.project.key===d&&e.push(n)}),e},[t,w,u,H,z,l,d,c]),U=(0,i.useMemo)(()=>a?[]:function(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],s=Math.max(0,e.length-1),a=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)&&n>0?n:600,l=Number.isFinite(r)&&r>0?r:0,d=a-l,c=a+o+l,u=0,p=s;for(;u<p;){let t=u+p>>>1;e[t+1]>d?p=t:u=t+1}let h=u;for(u=h,p=s;u<p;){let t=u+p>>>1;e[t]>=c?p=t:u=t+1}let m=u,g=[];for(let e=h;e<m;e++)g.push(e);if(0===i.length)return g;let f=i.filter(e=>Number.isInteger(e)&&e>=0&&e<s&&(e<h||e>=m));return 0===f.length?g:[...new Set([...g,...f])].sort((e,t)=>e-t)}(M,v,j,240,_),[a,M,v,j,_]),q=(0,i.useRef)(null),K=(0,i.useRef)(null),Z=(0,i.useCallback)((e,t,n,r)=>{let i=document.activeElement===r,s=i&&r.matches(":focus-visible");q.current={rowKey:e,fallbackKey:t===W?"pinned-header":`group:${t}`,focus:i,scroll:"less"===n||s},"more"===n?m.current.onShowMore(t):m.current.onShowLess(t)},[]);(0,i.useLayoutEffect)(()=>{let e=q.current;if(!e)return;q.current=null;let n=f.current,r=t.findIndex(t=>t.key===e.rowKey);if(r<0&&(r=t.findIndex(t=>t.key===e.fallbackKey)),e.scroll&&n&&r>=0){let e=ea(M,r,n.scrollTop,n.clientHeight);null!==e&&(n.scrollTop=e),y(n.scrollTop)}e.focus&&(K.current={rowKey:e.rowKey,fallbackKey:e.fallbackKey,tries:0})},[t,M]);let V=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{if(!B)return;let e=t.findIndex(e=>e.key===B.rowKey),n=function(e,t,n,r){let i=e?.id===t.id?e:{id:t.id,misses:0};if(!(r-t.at<=3e3))return{misses:i,action:"drop"};if(n)return{misses:i,action:"reveal"};let s={id:t.id,misses:i.misses+1};return{misses:s,action:s.misses>=3?"drop":"wait"}}(V.current,B,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=ea(M,e,t.scrollTop,t.clientHeight,B.block);null!==n&&(t.scrollTop=n),y(t.scrollTop)}B.takeFocusFrom&&(K.current={rowKey:B.rowKey,fallbackKey:B.rowKey,tries:0,takeFocusFrom:B.takeFocusFrom})}D(B.id),m.current.onRevealHandled?.(B.id)}},[B,t,M]),(0,i.useLayoutEffect)(()=>{let e=K.current;if(!e)return;let t=document.activeElement;if(t&&t!==document.body&&document.contains(t)&&!e.takeFocusFrom?.(t)){K.current=null;return}let n=f.current,r=e=>n?.querySelector(`[data-row-key="${CSS.escape(e)}"]`)??null,i=r(e.rowKey),s=i?.querySelector('[data-more-action="more"]')??i?.querySelector("a[href], button")??r(e.fallbackKey)?.querySelector("a[href], button");s?(s.focus({preventScroll:!0}),K.current=null):++e.tries>2&&(K.current=null)},[U]);let J=t.some(e=>"session"===e.kind||"group"===e.kind||"archive-group"===e.kind),G=!a&&!o&&null!==s&&!J,Y=P?.source??null,X=P?.drop?.lineY??null,Q=P?.phase==="dragging"?t.find(e=>"group"===e.kind&&e.project.key===P.projectKey)?.project??null:null;return(0,r.jsxs)("div",{ref:g,className:`session-tree${"mobile"===n?" is-mobile":""}${Q?" is-group-dragging":""}`,children:[a&&(0,r.jsx)("div",{className:"session-tree-message",children:h("sidebar.loading")}),o&&(0,r.jsx)("div",{className:"session-tree-message is-error",children:o}),G&&(0,r.jsx)("div",{className:"session-tree-message",children:s}),(0,r.jsx)("div",{ref:f,className:"session-tree-scroll scrollbar-subtle",onScroll:$,onFocus:E,onBlur:T,onPointerDownCapture:L.onPointerDownCapture,onClickCapture:L.onClickCapture,children:!a&&(0,r.jsxs)("div",{ref:x,className:"session-tree-inner",style:{height:M[t.length]},children:[U.map(e=>{let i=t[e];if("spacer"===i.kind)return null;let s=M[e],a=M[e+1]-s,o=i.key===u;if("session"===i.kind)return(0,r.jsx)(tc,{row:i,layout:n,top:s,height:a,now:C,renaming:i.family.root.id===l,confirming:i.family.root.id===c,menuOpen:o,handlers:m},i.key);if("archive-group"===i.kind)return(0,r.jsx)(tf,{row:i,top:s,height:a,menuOpen:o,handlers:m},i.key);if("group"===i.kind){let e=i.project.key===d;return(0,r.jsx)(tm,{row:i,top:s,height:a,menuOpen:o,renaming:e,canDrag:R&&!e&&A[i.project.pinned?"pinned":"other"]>1,dragPhase:P?.projectKey===i.project.key?P.phase:null,drag:L.handlers,handlers:m},i.key)}return(0,r.jsx)(tg,{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 td(e,t){return{top:e,height:t}}let tc=(0,i.memo)(function(e){let t,n,{row:i,layout:s,top:a,height:o,now:l,renaming:d,confirming:c,menuOpen:p,handlers:h}=e,{locale:m,t:g}=(0,eW.s)(),{family:f,context:x,status:b}=i,v=f.root,y=ta(v),j=new Date(l),k=["session-tree-row session-tree-session",b.selected?"is-selected":"",b.running?"is-running":"","archive"===x?"is-archived":"",p?"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:k,style:td(a,o),"data-row-key":i.key,onKeyDown:e=>{"Escape"!==e.key||to(e)||(e.preventDefault(),e.stopPropagation(),h.current.onDeleteCancel())},children:(0,r.jsx)(tp,{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:k,style:td(a,o),"data-row-key":i.key,children:(0,r.jsx)(tu,{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"?ep(v.name):null,C=v.detailsPending?"…":g("sidebar.messagesCount",{count:v.messageCount}),N=`${y}
2
- ${C} \xb7 ${(0,te.fw)(v.modified,m,j)}${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)(ts.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,te.Rg)(f.latestModified,m,j);let $="desktop"===s&&("archive"===x||!b.running),E=(0,r.jsxs)(r.Fragment,{children:[S?(0,r.jsxs)("span",{className:"session-tree-title has-fork-suffix",children:[(0,r.jsx)("span",{className:"session-tree-title-base",children:S.base}),(0,r.jsx)("span",{className:"session-tree-title-suffix",children:S.suffix})]}):(0,r.jsx)("span",{className:"session-tree-title",children:y}),w&&(0,r.jsxs)("span",{className:"session-tree-branch",children:[(0,r.jsx)(ts.OK,{size:10,className:"session-tree-branch-icon"}),w]}),(0,r.jsx)("span",{className:`session-tree-meta${I}`,title:n,children:t})]});return(0,r.jsxs)("div",{className:k,style:td(a,o),"data-row-key":i.key,onClick:()=>h.current.onSelectFamily(f),onContextMenu:e=>h.current.onRowContextMenu(i,e),children:[b.transient?(0,r.jsx)("button",{type:"button",className:"session-tree-main",title:N,"aria-current":b.selected?"true":void 0,children:E}):(0,r.jsx)("a",{className:"session-tree-main",href:u(v.id),title:N,"aria-current":b.selected?"true":void 0,onClick:e=>{e.stopPropagation(),e.defaultPrevented||0!==e.button||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||(e.preventDefault(),h.current.onSelectFamily(f))},children:E}),!b.transient&&(0,r.jsxs)("span",{className:"session-tree-actions",children:[$&&("archive"===x?(0,r.jsx)("button",{type:"button",className:"session-tree-action session-tree-quick-action","aria-label":g("sidebar.restore"),title:g("sidebar.restore"),onClick:e=>{e.stopPropagation(),h.current.onRestoreFamily(f)},children:(0,r.jsx)(ts.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)(ts.kb,{size:13})})),(0,r.jsx)("button",{type:"button",className:`session-tree-action session-tree-more-action${p?" is-active":""}`,"aria-label":g("sidebar.moreActions"),title:g("sidebar.moreActions"),"aria-haspopup":"menu","aria-expanded":p,onClick:e=>{let t;e.stopPropagation();let n=e.currentTarget;h.current.onOpenRowMenu(i,{kind:"rect",rect:{left:(t=n.getBoundingClientRect()).left,top:t.top,right:t.right,bottom:t.bottom},align:"end"},n)},children:(0,r.jsx)(ts.Z4,{size:14})})]})]})});function tu(e){let{initialValue:t,label:n,maxLength:s,onCommit:a,onCancel:o}=e,[l,d]=(0,i.useState)(t),c=(0,i.useRef)(null),u=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=c.current;e&&(e.focus(),e.select())},[]);let p=e=>{u.current||(u.current=!0,a(e))};return(0,r.jsx)("input",{ref:c,className:"session-tree-rename",value:l,"aria-label":n,maxLength:s,onChange:e=>d(e.target.value),onBlur:e=>p(e.currentTarget.value),onKeyDown:e=>{if(!to(e)){if("Enter"===e.key)e.preventDefault(),p(e.currentTarget.value);else if("Escape"===e.key){if(e.preventDefault(),e.stopPropagation(),u.current)return;u.current=!0,o()}}}})}function tp(e){let{label:t,deleteLabel:n,cancelLabel:s,onConfirm:a,onCancel:o}=e,l=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=document.activeElement;e&&e!==document.body||l.current?.focus()},[]),(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"session-tree-confirm-text",children:t}),(0,r.jsxs)("button",{type:"button",className:"session-tree-confirm-delete",onClick:a,children:[(0,r.jsx)(ts.uc,{size:12}),n]}),(0,r.jsx)("button",{ref:l,type:"button",className:"session-tree-confirm-cancel",onClick:o,children:s})]})}function th(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)(ts.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 tm=(0,i.memo)(function(e){let{row:t,top:n,height:s,menuOpen:a,renaming:o,canDrag:l,dragPhase:d,drag:c,handlers:u}=e,{t:p}=(0,eW.s)(),{project:h,expanded:m}=t,g=(0,i.useRef)(null),f=["session-tree-row session-tree-group",h.current?"is-current":"",a?"is-active":"","armed"===d?"is-drag-armed":""].filter(Boolean).join(" ");return((0,i.useEffect)(()=>{let e=g.current;if(!l||!e)return;let t=e=>c.onTouchMove(e);return e.addEventListener("touchmove",t,{passive:!1}),()=>e.removeEventListener("touchmove",t)},[l,c]),o)?(0,r.jsx)("div",{ref:g,className:`${f} is-renaming`,style:td(n,s),"data-row-key":t.key,children:(0,r.jsx)(tu,{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:td(n,s),"data-row-key":t.key,onPointerDown:l?e=>c.onPointerDown(e,h.key):void 0,children:[(0,r.jsxs)("button",{type:"button",className:"session-tree-group-toggle","aria-expanded":m,title:h.root,onClick:e=>u.current.onToggleGroup(h.key,e.altKey),children:[(0,r.jsx)(ts.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)(ts.ts,{size:10,className:"session-tree-group-pin",label:p("sidebar.pinnedProject")}),!m&&(0,r.jsx)(th,{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)(ts.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)(ts.Z4,{size:13})})]})]})}),tg=(0,i.memo)(function(e){let{row:t,top:n,height:i,handlers:s,onMoreAction:a}=e,{t:o}=(0,eW.s)(),l=td(n,i);switch(t.kind){case"pinned-header":return(0,r.jsx)("div",{className:"session-tree-row session-tree-pinned-header",style:l,"data-row-key":t.key,children:(0,r.jsxs)("button",{type:"button",className:"session-tree-pinned-toggle","aria-expanded":!t.collapsed,onClick:()=>s.current.onTogglePinned(),children:[(0,r.jsx)(ts.zp,{size:12,strokeWidth:3,className:`session-tree-chevron${t.collapsed?"":" is-open"}`}),(0,r.jsx)("span",{className:"session-tree-pinned-label",children:o("sidebar.pinned")}),(0,r.jsxs)("span",{className:"session-tree-pinned-count",children:["\xb7 ",t.count]}),t.collapsed&&t.running>0&&(0,r.jsx)("span",{className:"session-tree-pinned-dot is-running",role:"img",title:o("sidebar.agentRunning"),"aria-label":`${o("sidebar.agentRunning")} (${t.running})`}),t.collapsed&&t.awaiting>0&&(0,r.jsx)("span",{className:"session-tree-pinned-dot is-awaiting",role:"img",title:o("sidebar.agentAwaitingInput"),"aria-label":`${o("sidebar.agentAwaitingInput")} (${t.awaiting})`}),t.collapsed&&t.unread>0&&(0,r.jsx)("span",{className:"session-tree-pinned-dot is-unread",role:"img",title:o("sidebar.newSessionActivity"),"aria-label":`${o("sidebar.newSessionActivity")} (${t.unread})`})]})});case"pinned-more":case"group-more":{let e="pinned-more"===t.kind?W:t.projectKey;return(0,r.jsxs)("div",{className:"session-tree-row session-tree-more",style:l,"data-row-key":t.key,children:[t.hidden>0&&(0,r.jsx)("button",{type:"button",className:"session-tree-more-toggle","data-more-action":"more",onClick:n=>a(t.key,e,"more",n.currentTarget),children:o("sidebar.showMore",{count:t.hidden})}),t.canShowLess&&(0,r.jsx)("button",{type:"button",className:"session-tree-more-toggle","data-more-action":"less",onClick:n=>a(t.key,e,"less",n.currentTarget),children:o("sidebar.showLess")})]})}case"group-empty":return(0,r.jsxs)("div",{className:"session-tree-row session-tree-group-empty",style:l,"data-row-key":t.key,children:[(0,r.jsx)("span",{className:"session-tree-group-empty-label",children:o("sidebar.noLiveSessions")}),!t.project.pinned&&(0,r.jsx)("button",{type:"button",className:"session-tree-more-toggle",onClick:()=>s.current.onPinEmptyGroup(t.project),children:o("sidebar.pinToKeep")})]});case"footer-open":return(0,r.jsx)("div",{className:"session-tree-row session-tree-footer",style:l,"data-row-key":t.key,children:(0,r.jsxs)("button",{type:"button",className:"session-tree-footer-button",onClick:e=>s.current.onOpenOtherProject(e.currentTarget),children:[(0,r.jsx)(ts.YP,{size:12}),(0,r.jsx)("span",{className:"session-tree-footer-label",children:o("sidebar.openOtherProject")})]})});case"footer-archived":return(0,r.jsx)("div",{className:"session-tree-row session-tree-footer",style:l,"data-row-key":t.key,children:(0,r.jsxs)("button",{type:"button",className:"session-tree-footer-button",onClick:()=>s.current.onOpenArchive(),children:[(0,r.jsx)(ts.kb,{size:12}),(0,r.jsx)("span",{className:"session-tree-footer-label",children:o("sidebar.archivedCount",{count:t.count})}),(0,r.jsx)(ts.zp,{size:10,className:"session-tree-footer-chevron"})]})})}}),tf=(0,i.memo)(function(e){let{row:t,top:n,height:i,menuOpen:s,handlers:a}=e,{t:o}=(0,eW.s)(),{project:l,expanded:d}=t,c=["session-tree-row session-tree-group session-tree-archive-group",l.current?"is-current":"",s?"is-active":""].filter(Boolean).join(" ");return(0,r.jsxs)("div",{className:c,style:td(n,i),"data-row-key":t.key,children:[(0,r.jsxs)("button",{type:"button",className:"session-tree-group-toggle","aria-expanded":d,title:l.root,onClick:e=>a.current.onToggleArchiveGroup?.(l.key,e.altKey),children:[(0,r.jsx)(ts.zp,{size:12,strokeWidth:3,className:`session-tree-chevron${d?" is-open":""}`}),(0,r.jsx)("span",{className:"session-tree-group-name",children:l.name}),(0,r.jsxs)("span",{className:"session-tree-archive-group-count",children:["\xb7 ",t.count]})]}),(0,r.jsx)("span",{className:"session-tree-group-actions",children:(0,r.jsx)("button",{type:"button",className:`session-tree-group-action${s?" is-active":""}`,"aria-label":o("sidebar.archivedProjectActions",{name:l.name}),title:o("sidebar.archivedProjectActions",{name:l.name}),"aria-haspopup":"menu","aria-expanded":s,onClick:e=>{e.stopPropagation(),a.current.onArchiveGroupMenu?.(l,e.currentTarget)},children:(0,r.jsx)(ts.Z4,{size:13})})})]})}),tx="[data-sidebar-menu-filter]",tb="[data-sidebar-menu-autofocus]",tv="button, input, textarea, select, a[href], [tabindex]";function ty(e){return i.Children.toArray(e).length>0}function tj(e){return"item"===e.type&&void 0!==e.checked}function tk(e){return e.getClientRects().length>0}function tw(e){return!e.disabled&&"true"!==e.getAttribute("aria-disabled")&&tk(e)}function tS(e){return Array.from(e.querySelectorAll("[data-sidebar-menu-item]")).filter(tw)}function tC(e){let t=Array.from(e.querySelectorAll(tb)).find(tw);if(t)return t;let n=tS(e);return n.length>0?n[0]:Array.from(e.querySelectorAll(tv)).filter(e=>e.tabIndex>=0&&tw(e))[0]??null}function tN(e){e.stopPropagation()}let tI={onClick:tN,onDoubleClick:tN,onMouseDown:tN,onMouseUp:tN,onPointerDown:tN,onPointerUp:tN,onKeyDown:tN,onKeyUp:tN,onFocus:tN,onBlur:tN,onContextMenu:function(e){e.preventDefault(),e.stopPropagation()}};function t$(e,t){return n=>{"Enter"!==n.key||n.nativeEvent.isComposing||229===n.keyCode||(n.preventDefault(),t(e,n.shiftKey))}}function tE(e){let{item:t,onActivate:n}=e,i=void 0!==t.checked,s=["sidebar-menu-item",i?"is-choice":"",t.danger?"is-danger":"",t.checked?"is-checked":""].filter(Boolean).join(" "),a=["sidebar-menu-label",t.mono?"is-mono":"",t.path?"is-path":""].filter(Boolean).join(" "),o=null;t.disabled&&t.disabledReason?o=(0,r.jsx)("span",{className:"sidebar-menu-note",children:t.disabledReason}):t.note?o=(0,r.jsx)("span",{className:"sidebar-menu-note",children:t.note}):t.shortcut&&(o=(0,r.jsx)("kbd",{className:"sidebar-menu-shortcut",children:t.shortcut}));let l=(0,r.jsxs)("button",{type:"button",role:i?"menuitemradio":"menuitem","aria-checked":i?t.checked:void 0,"aria-disabled":!!t.disabled||void 0,"aria-keyshortcuts":t.shortcut&&!t.disabled?t.shortcut.toUpperCase():void 0,tabIndex:-1,title:t.title,"data-sidebar-menu-item":"",className:s,onClick:e=>n(t,e.shiftKey),onKeyDown:t$(t,n),children:[(0,r.jsx)("span",{className:"sidebar-menu-icon",children:i?t.checked?(0,r.jsx)(ts.Sr,{size:13}):null:t.icon}),(0,r.jsx)("span",{className:a,children:t.path?(0,r.jsx)("span",{children:t.label}):t.label}),t.badge,o]}),d=t.secondary;return d?(0,r.jsxs)("div",{className:i?"sidebar-menu-row is-choice":"sidebar-menu-row",role:"none",children:[l,(0,r.jsx)("button",{type:"button",role:"menuitem","aria-label":d.label,"aria-disabled":!!d.disabled||void 0,tabIndex:-1,title:d.label,"data-sidebar-menu-item":"",className:d.danger?"sidebar-menu-secondary is-danger":"sidebar-menu-secondary",onClick:e=>n(d,e.shiftKey),onKeyDown:t$(d,n),children:d.icon})]}):l}function tT(e){var t;let n,{sheet:i,ariaLabel:s,title:a,items:o,filter:l,filterQuery:d="",onFilterQueryChange:c,children:u,cancelLabel:p,focusCancel:h=!1,width:m=208,classic:g=!1,footer:f,surfaceRef:x,onActivate:b,onClose:v}=e,y=ty(u),j=!y&&ty(f),k=void 0!==l&&!y&&function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;return(e??[]).filter(tj).length>=t}(o,l.minChoices),w=k?(t=o??[],(n=d.trim().toLowerCase())?t.filter(e=>"item"!==e.type||void 0===e.checked||[e.label,e.note,e.title].some(e=>e?.toLowerCase().includes(n))):[...t]):o??[],S=w.map(e=>"separator"===e.type?(0,r.jsx)("div",{className:"sidebar-menu-separator",role:"separator"},e.id):"header"===e.type?(0,r.jsx)("div",{className:"sidebar-menu-header",role:"presentation",children:e.label},e.id):"custom"===e.type?(0,r.jsx)("div",{className:"sidebar-menu-custom",role:"none",children:e.content},e.id):(0,r.jsx)(tE,{item:e,onActivate:b},e.id)),C=y?u:k||j?(0,r.jsxs)(r.Fragment,{children:[k&&(0,r.jsx)("div",{className:"sidebar-menu-filter",children:(0,r.jsx)("input",{className:"sidebar-menu-filter-input",value:d,placeholder:l.placeholder,"aria-label":l.placeholder,autoComplete:"off",spellCheck:!1,"data-sidebar-menu-filter":"","data-sidebar-menu-autofocus":i?void 0:"",onChange:e=>c?.(e.target.value)})}),k&&(0,r.jsx)("div",{role:"status",children:d.trim()&&!w.some(tj)&&(0,r.jsx)("div",{className:"sidebar-menu-empty",children:l.emptyLabel})}),(0,r.jsx)("div",{role:"menu","aria-label":s,children:S}),j&&f]}):S,N=y||k||j?void 0:"menu";return i?(0,r.jsxs)("div",{className:"sidebar-sheet-layer",...tI,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},...tI,children:C})}function tM(e){let{open:t,anchor:n,sheet:s,ariaLabel:a,title:o,items:l,filter:d,children:c,cancelLabel:u,focusCancel:p,onClose:h,returnFocusTo:m,width:g,classic:f=!1,footer:x,focusKey:b=""}=e,[v,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(""),w=(0,i.useRef)(j);w.current=j;let S=(0,i.useRef)(null),C=(0,i.useRef)(h);C.current=h;let N=(0,i.useRef)(l);N.current=l;let I=(0,i.useRef)(m??null);I.current=m??null;let $=(0,i.useRef)(n);$.current=n,(0,i.useEffect)(()=>{y(document.body)},[]);let E=t&&null!==v&&(s||null!==n),T=ty(c),M=n?JSON.stringify(n):"",R=(e,t)=>{if(e.disabled)return;let n=!1;e.onSelect({shiftKey:t,keepOpen:()=>{n=!0}}),n||C.current("select")},A=(0,i.useRef)(R);A.current=R,(0,i.useLayoutEffect)(()=>{let e=S.current;if(!E||s||!e)return;let t=window.visualViewport,n=()=>{let n=$.current;if(!n)return;let r=e.getBoundingClientRect(),{left:i,top:s}=function(e,t,n){let r,i,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8,a=n.left+s,o=n.top+s,l=n.left+n.width-s,d=n.top+n.height-s;if("point"===e.kind)r=e.x+t.width>l&&e.x-t.width>=a?e.x-t.width:e.x,i=e.y+t.height>d&&e.y-t.height>=o?e.y-t.height:e.y;else{let{rect:n}=e;r="end"===e.align?n.right-t.width:n.left;let s=n.bottom+4,a=n.top-4-t.height;i=s+t.height>d&&a>=o?a:s}return{left:Math.max(a,Math.min(r,l-t.width)),top:Math.max(o,Math.min(i,d-t.height))}}(n,{width:r.width,height:r.height},{left:t?.offsetLeft??0,top:t?.offsetTop??0,width:t?.width??window.innerWidth,height:t?.height??window.innerHeight});e.style.left=`${i}px`,e.style.top=`${s}px`};n();let r="u"<typeof ResizeObserver?null:new ResizeObserver(n);return r?.observe(e),window.addEventListener("resize",n),t?.addEventListener("resize",n),t?.addEventListener("scroll",n),()=>{r?.disconnect(),window.removeEventListener("resize",n),t?.removeEventListener("resize",n),t?.removeEventListener("scroll",n)}},[E,s,M,T]),(0,i.useEffect)(()=>{k("")},[E,T]);let L=(0,i.useRef)(!1);return((0,i.useLayoutEffect)(()=>{let e=S.current;if(!E||!e){L.current=!1;return}let t=!L.current;L.current=!0,(t?tC(e):Array.from(e.querySelectorAll(tb)).filter(e=>!e.matches(tx)&&tw(e))[0]??tC(e))?.focus({preventScroll:!0})},[E,s,T,b]),(0,i.useLayoutEffect)(()=>{let e=S.current;if(!E||!e)return;let t=I.current;return()=>{let n=document.activeElement;if(n&&n!==document.body&&!e.contains(n))return;let r=function(e){if(!e||!e.isConnected)return null;if(tk(e))return e;let t=e.closest("[data-row-key]");if(!t)return null;for(let e of Array.from(t.querySelectorAll(tv)))if(e.tabIndex>=0&&tw(e))return e;return null}(t);r&&(r.focus({preventScroll:!0}),t&&r!==t&&tk(t)&&t.focus({preventScroll:!0}))}},[E,s]),(0,i.useEffect)(()=>{if(!E)return;let e=e=>{let t=S.current;if(!t||e.isComposing||229===e.keyCode)return;if("Escape"===e.key){e.preventDefault(),e.stopPropagation();let n=t.querySelector(tx);if(n&&w.current){k(""),n.focus({preventScroll:!0});return}C.current("escape");return}let n=e.target instanceof Element?e.target:null,r=null!==n&&t.contains(n),i=null===n||n===document.body||n===document.documentElement;if(!r&&!i)return;if("Tab"===e.key){var s;let i,a;r&&(s=e.shiftKey,i=Array.from(t.querySelectorAll(tv)).filter(e=>e!==n&&e.tabIndex>=0&&tw(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(tx);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=tS(t);if(0===i.length)return;e.preventDefault(),e.stopPropagation();let s=n?i.indexOf(n):-1;r="Home"===e.key?0:"End"===e.key?i.length-1:"ArrowDown"===e.key?s<0?0:(s+1)%i.length:s<0?i.length-1:(s-1+i.length)%i.length,i[r].focus({preventScroll:!1});return}if(1!==e.key.length||e.ctrlKey||e.metaKey||e.altKey)return;let o=function(e,t){if(!e||1!==t.length)return null;let n=t.toLowerCase();for(let t of e)if("item"===t.type&&!t.disabled&&t.shortcut&&t.shortcut.toLowerCase()===n)return t;return null}(N.current,e.key);o&&!T&&(e.preventDefault(),e.stopPropagation(),A.current(o,e.shiftKey))};return document.addEventListener("keydown",e,!0),()=>document.removeEventListener("keydown",e,!0)},[E,T]),(0,i.useEffect)(()=>{if(!E||s)return;let e=e=>{let t=S.current,n=e.target instanceof Node?e.target:null;if(!t||n&&t.contains(n))return;let r=I.current;r&&n&&0===e.button&&r.contains(n)&&function(e){let t=e.ownerDocument,n=t.defaultView;if(!n)return;let r=0,i=()=>{t.removeEventListener("click",s,!0),n.clearTimeout(r)};function s(t){i(),t.target instanceof Node&&e.contains(t.target)&&(t.preventDefault(),t.stopPropagation())}t.addEventListener("click",s,!0),r=n.setTimeout(i,1e3)}(r),C.current("outside")};return document.addEventListener("pointerdown",e,!0),()=>document.removeEventListener("pointerdown",e,!0)},[E,s]),E&&v)?(0,eZ.createPortal)((0,r.jsx)(tT,{sheet:s,ariaLabel:a,title:o,items:l,filter:d,filterQuery:j,onFilterQueryChange:k,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 tR(e){let{heading:t,busy:n,error:s,showCancel:a,onCreate:o,onCancel:l}=e,{t:d}=(0,eW.s)(),[c,u]=(0,i.useState)(""),p=c.trim(),h=()=>{p&&!n&&o(p)};return(0,r.jsxs)("div",{className:"sidebar-worktree-form",children:[t&&(0,r.jsx)("div",{className:"sidebar-menu-header",children:t}),(0,r.jsx)("input",{className:"sidebar-worktree-input","data-sidebar-menu-autofocus":"",value:c,readOnly:n,placeholder:d("sidebar.branchName"),"aria-label":d("sidebar.branchName"),onChange:e=>u(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.preventDefault(),h())}}),(0,r.jsxs)("div",{className:"sidebar-worktree-form-buttons",children:[(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-create",disabled:n||!p,onClick:h,children:d(n?"sidebar.creating":"sidebar.create")}),a&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-cancel",onClick:l,children:d("sidebar.cancel")})]}),s&&(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:s})]})}function tA(e,t){return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function tL(e){return e.branch??K(e.path)}function tP(e){let{heading:t,dirty:n,busy:i,error:s,showCancel:a,onForce:o,onCancel:l}=e,{t:d}=(0,eW.s)();return(0,r.jsxs)("div",{className:"sidebar-worktree-form",children:[t&&(0,r.jsx)("div",{className:"sidebar-menu-header",children:t}),n&&(0,r.jsx)("div",{className:"sidebar-worktree-message",children:d("sidebar.forceRemoveCheckout")}),(n||a)&&(0,r.jsxs)("div",{className:"sidebar-worktree-form-buttons",children:[n&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-force",disabled:i,onClick:o,children:d("sidebar.force")}),a&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-cancel","data-sidebar-menu-autofocus":"",onClick:l,children:d("sidebar.cancel")})]}),s&&(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:s})]})}function tz(e){let{busy:t,onForce:n,onCancel:s}=e,{t:a}=(0,eW.s)(),o=(0,i.useId)();return(0,r.jsxs)("div",{className:"sidebar-worktree-confirm",children:[(0,r.jsx)("span",{id:o,className:"sidebar-worktree-confirm-text",title:a("sidebar.forceRemoveCheckout"),children:a("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{type:"button",role:"menuitem",tabIndex:-1,"data-sidebar-menu-item":"","aria-describedby":o,"aria-disabled":!!t||void 0,className:"sidebar-worktree-force",onClick:()=>{t||n()},children:a("sidebar.force")}),(0,r.jsx)("button",{type:"button",role:"menuitem",tabIndex:-1,"data-sidebar-menu-item":"","data-sidebar-menu-autofocus":"",className:"sidebar-worktree-cancel",onClick:s,children:a("sidebar.cancel")})]})}function tO(e){let t,n,{layout:s,context:a,mobile:o,label:l,placeholder:d="",homeDir:c,projectActivity:u,worktreeHint:p=null,newWorktreeTitle:h,handleRef:m,onPick:g,onUseDefaultDirectory:f,onOpenFolder:x,onRefreshWorktrees:b,onCreateWorktree:v,onRemoveWorktree:y}=e,{t:j}=(0,eW.s)(),[k,w]=(0,i.useState)(null),S=(0,i.useRef)(k);S.current=k;let C=(0,i.useRef)(0),N=(0,i.useRef)(null),I=(0,i.useRef)(null),$=(0,i.useRef)(!1),E=(0,i.useRef)(g);E.current=g;let T="inline"!==s,M=!T,R=!o,{project:A,worktrees:L}=a,P=(t=a.worktrees??[]).find(e=>e.path===a.currentWorktreePath)??t.find(e=>e.isMain)??null,z=M&&A?ef(em(a)).find(e=>{let{choice:t}=e;return t.key===A.key}):void 0;(0,i.useEffect)(()=>($.current=!0,()=>{$.current=!1}),[]);let O=()=>(C.current+=1,C.current),W=()=>w(null),F=(e,t)=>{let n=t.getBoundingClientRect(),r=Math.max(T?220:"project"===e?260:240,Math.round(n.width));w({id:O(),kind:e,anchor:{kind:"rect",rect:{left:n.left,top:n.top,right:n.right,bottom:n.bottom},align:"row"===s&&"worktree"===e?"end":"start"},opener:t,width:r,body:null,removing:!1}),"worktree"===e&&b()},D=(0,i.useRef)(F);D.current=F,(0,i.useImperativeHandle)(m,()=>({button:e=>("worktree"===e?I:N).current,openMenu:e=>{let t=("worktree"===e?I:N).current;t&&D.current(e,t)}}),[]);let B=(e,t)=>{w(n=>n?.id===e?t(n):n)},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)}}$.current&&("error"in t?i(!1,t.error):S.current?.id===r&&(w(null),E.current({cwd:t.path,projectKey:A.key,projectRoot:A.root},"worktree")))},U=async(e,t)=>{let n,r=S.current;if(!r||!A||!y)return;let{id:i}=r;B(i,e=>({...e,removing:!0,body:e.body?.kind==="remove"?{...e.body,busy:!0,error:null}:e.body}));try{n=await y(A,e.path,t)}catch(e){n={error:e instanceof Error?e.message:String(e)}}$.current&&B(i,t=>{if("removed"===n)return{...t,removing:!1,body:null};let r="dirty"===n||t.body?.kind==="remove"&&t.body.dirty;return{...t,removing:!1,body:{kind:"remove",worktree:e,dirty:r,busy:!1,error:"dirty"===n?null:n.error}}})},q=()=>[...(L??[]).map(e=>R&&Z?.kind==="remove"&&Z.dirty&&Z.worktree.path===e.path?{type:"custom",id:`worktree:${e.path}`,content:(0,r.jsx)(tz,{busy:Z.busy,onForce:()=>{U(e,!0)},onCancel:()=>H(null)})}:{type:"item",id:`worktree:${e.path}`,label:R?e.branch??tA(e.path,c):tL(e),mono:R,path:R,note:e.isMain?j("sidebar.main"):void 0,title:e.path,checked:e.path===P?.path,secondary:y&&!e.isMain?{label:j("sidebar.removeWorktreeTitle",{path:e.path}),icon:(0,r.jsx)(ts.uc,{size:12}),danger:!0,disabled:k?.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&&Z?.kind==="create"?[]:[{type:"item",id:"new-worktree",label:j("sidebar.newWorktree"),icon:(0,r.jsx)(ts.c1,{size:13}),onSelect:e=>{let{keepOpen:t}=e;t(),H({kind:"create",busy:!1,error:null})}}]],Z=k?.kind==="worktree"?k.body:null,V="",J=null,G=null;if(R&&k?.kind==="worktree")V=j("sidebar.switchWorktree"),n=q(),Z?.kind==="create"?G=(0,r.jsx)(tR,{heading:null,busy:Z.busy,error:Z.error,showCancel:!0,onCreate:e=>{_(e)},onCancel:()=>H(null)}):Z?.kind==="remove"&&Z.error&&(G=(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:Z.error}));else if(Z?.kind==="create")V=h,J=(0,r.jsx)(tR,{heading:o?null:V,busy:Z.busy,error:Z.error,showCancel:!o,onCreate:e=>{_(e)},onCancel:W});else if(Z?.kind==="remove")V=j("sidebar.removeWorktreeHeading",{name:tL(Z.worktree)}),J=(0,r.jsx)(tP,{heading:o?null:V,dirty:Z.dirty,busy:Z.busy,error:Z.error,showCancel:!o,onForce:()=>{U(Z.worktree,!0)},onCancel:W});else if(k?.kind==="project"){let e,t;V=j("workspace.project"),t=(e=ef(em(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?tA(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)(th,{running:s.running,unread:s.unread,t:j}):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:j("sidebar.useDefaultDirectory"),icon:(0,r.jsx)(ts.sj,{size:13}),onSelect:()=>f()},{type:"item",id:"open-folder",label:j(R?"sidebar.customPath":"sidebar.openOtherProject"),icon:R?(0,r.jsx)(ts.c1,{size:13}):(0,r.jsx)(ts.YP,{size:13}),onSelect:()=>x(k?.opener??null)}]}else k?.kind==="worktree"&&(V=j("sidebar.switchWorktree"),n=q());let Y=k?.kind==="project"?{placeholder:j("sidebar.filterProjects"),emptyLabel:j("sidebar.noMatchingProjects"),minChoices:R?9:void 0}:{placeholder:j("sidebar.filterWorktrees"),emptyLabel:j("sidebar.noMatchingWorktrees")},X=T&&void 0!==u&&[...u].some(e=>{let[t,{running:n,unread:r}]=e;return t!==A?.key&&(n>0||r>0)});return(0,r.jsxs)("div",{className:`project-picker is-${s}`,role:"group","aria-label":l,children:[(0,r.jsxs)("button",{ref:N,type:"button",className:A?"project-picker-button is-project":"project-picker-button is-project is-empty",title:A?.root??"","aria-haspopup":"menu","aria-expanded":k?.kind==="project",onClick:e=>F("project",e.currentTarget),children:[M&&(0,r.jsx)(ts.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??K(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:tA(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:j("sidebar.newActivity"),"aria-label":j("sidebar.newActivity")}),M&&(0,r.jsx)(ts.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?j("sidebar.worktreePath",{path:P.path}):j("sidebar.switchWorktree"),"aria-haspopup":"menu","aria-expanded":k?.kind==="worktree",onClick:e=>F("worktree",e.currentTarget),children:[(0,r.jsx)(ts.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??tA(P.path,c):"…"})}),P?.isMain&&"stacked"===s&&(0,r.jsx)("span",{className:"project-picker-note",children:j("sidebar.main")}),T&&L.length>1&&(0,r.jsx)("span",{className:"project-picker-note",children:L.length}),(0,r.jsx)(ts.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)(ts.OK,{size:11,className:"project-picker-icon"}),(0,r.jsx)("span",{className:"project-picker-label",children:p.label})]}),(0,r.jsx)(tM,{open:null!==k,anchor:k?.anchor??null,sheet:o,ariaLabel:V,title:V,items:n,filter:Y,cancelLabel:j("sidebar.cancel"),focusCancel:Z?.kind==="remove",onClose:W,returnFocusTo:k?.opener??null,width:k?.width,classic:R,footer:G,focusKey:Z?`${Z.kind}:${"remove"===Z.kind&&Z.dirty}`:"list",children:J})]})}function tW(e){let{open:t,query:n,children:s,selectedSessionId:a,onSelectSession:o,archivedSessionIds:l}=e,{t:d,locale:c}=(0,eW.s)(),[u,p]=(0,i.useState)({query:""}),h=n.trim(),m=u.query===h?u.response:void 0,g=u.query===h&&u.failed;return(0,i.useEffect)(()=>{if(!t||!h)return;let e=new AbortController;p({query:h});let n=setTimeout(async()=>{try{let t=await fetch(`/api/sessions/search?${new URLSearchParams({q:h})}`,{signal:e.signal});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();e.signal.aborted||p({query:h,response:n})}catch{e.signal.aborted||p({query:h,failed:!0})}},300);return()=>{clearTimeout(n),e.abort()}},[t,h]),t&&h?(0,r.jsxs)("div",{className:"min-h-20 flex-1 overflow-y-auto","aria-busy":!m&&!g,children:[(0,r.jsx)("div",{role:"status",className:"px-3 py-2 text-xs text-text-muted",children:g?d("sidebar.sessionSearchFailed"):m?0===m.results.length?d("sidebar.sessionSearchEmpty"):d("sidebar.sessionSearchCount",{count:m.results.length}):d("sidebar.sessionSearching")}),m?.truncated&&(0,r.jsx)("div",{role:"status",className:"px-3 pb-2 text-xs text-text-muted",children:d("sidebar.sessionSearchPartial")}),m?.results.map(e=>{let{session:t,entryId:n,blockIndex:i,titleMatch:s,before:u,match:p,after:h}=e;return(0,r.jsxs)("button",{type:"button",onClick:()=>o(t,n,i),"aria-current":t.id===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 ${t.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:s?(0,r.jsxs)(r.Fragment,{children:[u,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:p}),h]}):t.name||t.firstMessage}),l?.has(t.id)&&(0,r.jsx)("span",{className:"shrink-0 rounded-[4px] border border-border px-1 text-[10px] leading-[14px] text-text-dim",children:d("sidebar.archived")})]}),(0,r.jsxs)("span",{className:"mt-1 flex min-w-0 gap-2 text-[10px] text-text-dim",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate",title:t.cwd,children:t.cwd}),(0,r.jsx)("span",{className:"shrink-0",children:(0,te.fw)(t.modified,c)})]}),!s&&(0,r.jsxs)("span",{className:"mt-1 block text-xs leading-relaxed wrap-anywhere text-text-muted",children:[u,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:p}),h]})]},t.id)})]}):s}function tF(e,t){return`${e}/share/${t}`}function tD(e){return e instanceof Error?e.message:String(e)}function tB(e){let{sessionId:t,origin:n,fetchImpl:s,onCopied:a,onStopped:o}=e,{t:l}=(0,eW.s)(),[d,c]=(0,i.useState)({status:"loading"}),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(!1),[x,b]=(0,i.useState)(null),v=s??fetch,y=n??window.location.origin,j=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!0;return c({status:"loading"}),m(null),f(!1),v(`/api/sessions/${encodeURIComponent(t)}/share`,{cache:"no-store"}).then(async t=>{let n=await t.json().catch(()=>({}));if(e){if(!t.ok)return void c({status:"load-failed",error:n.error??`HTTP ${t.status}`});c(n.share?{status:"shared",share:n.share}:{status:"unshared"})}}).catch(t=>{e&&c({status:"load-failed",error:tD(t)})}),()=>{e=!1}},[v,t]),(0,i.useEffect)(()=>{let e=!0;return v(`/api/sessions/${encodeURIComponent(t)}`,{cache:"no-store"}).then(async t=>{let n=await t.json().catch(()=>({}));e&&t.ok&&"number"==typeof n.info?.messageCount&&b(n.info.messageCount)}).catch(()=>{}),()=>{e=!1}},[v,t]);let k=(0,i.useCallback)(()=>{j.current||(j.current=!0,p("create"),m(null),v(`/api/sessions/${encodeURIComponent(t)}/share`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}).then(async e=>{var t,n;let r=await e.json().catch(()=>({}));if("string"!=typeof(t=r).code||"string"!=typeof t.createdAt||"string"!=typeof t.title){let{key:t,params:i}=(n=e.status,"too_large"===r.code||"too_large"===r.error?{key:"share.tooLarge"}:{key:"share.createError",params:{error:r.error??`HTTP ${n}`}});m(l(t,i));return}c({status:"shared",share:{code:r.code,createdAt:r.createdAt,title:r.title}}),f(!1)}).catch(e=>{m(l("share.createError",{error:tD(e)}))}).finally(()=>{j.current=!1,p(null)}))},[v,t,l]),w=(0,i.useCallback)(()=>{if(!j.current){if(!g)return void f(!0);j.current=!0,p("stop"),m(null),v(`/api/sessions/${encodeURIComponent(t)}/share`,{method:"DELETE"}).then(async e=>{let t=await e.json().catch(()=>({}));e.ok&&!0===t.ok?(c({status:"unshared"}),f(!1),b(null),o()):m(l("share.stopError",{error:t.error??`HTTP ${e.status}`}))}).catch(e=>{m(l("share.stopError",{error:tD(e)}))}).finally(()=>{j.current=!1,p(null)})}},[o,v,t,g,l]),S=(0,i.useCallback)(()=>{c(e=>("shared"===e.status&&(0,e3.D)(tF(y,e.share.code)).then(()=>a(),()=>{}),e))},[a,y]);return(0,r.jsx)(tH,{state:d,messageCount:x,busy:u,error:h,stopArmed:g,origin:y,onCopy:S,onCreate:k,onRefresh:k,onStop:w})}function tH(e){let{state:t,messageCount:n,busy:i,error:s,stopArmed:a,origin:o,onCopy:l,onCreate:d,onRefresh:c,onStop:u}=e,{t:p}=(0,eW.s)();return(0,r.jsxs)("div",{className:"sidebar-share-panel",children:[(0,r.jsx)("div",{className:"sidebar-menu-header",children:p("share.title")}),"loading"===t.status&&(0,r.jsx)("p",{role:"status",className:"sidebar-share-status",children:p("sidebar.loading")}),"load-failed"===t.status&&(0,r.jsx)("div",{role:"alert",className:"sidebar-share-error",children:p("share.loadError",{error:t.error})}),"unshared"===t.status&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"sidebar-share-text",children:p("share.description")}),null!==n&&(0,r.jsx)("p",{className:"sidebar-share-note",children:p("share.summary",{count:n})}),(0,r.jsx)("div",{className:"sidebar-share-buttons",children:(0,r.jsx)("button",{type:"button",className:"sidebar-share-create",disabled:null!==i,"data-sidebar-menu-autofocus":"",onClick:d,children:p("create"===i?"share.creating":"share.create")})})]}),"shared"===t.status&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"sidebar-share-link-label",children:p("share.linkLabel")}),(0,r.jsx)("code",{className:"sidebar-share-link",children:tF(o,t.share.code)}),(0,r.jsxs)("div",{className:"sidebar-share-buttons",children:[(0,r.jsx)("button",{type:"button",className:"sidebar-share-copy","data-sidebar-menu-autofocus":"",onClick:l,children:p("share.copy")}),(0,r.jsx)("button",{type:"button",className:"sidebar-share-refresh",disabled:null!==i,onClick:c,children:p("create"===i?"share.creating":"share.refresh")})]}),(0,r.jsx)("div",{className:"sidebar-share-buttons",children:(0,r.jsx)("button",{type:"button",className:`sidebar-share-stop${a?" is-armed":""}`,disabled:null!==i,onClick:u,children:p(a?"share.confirmStop":"share.stop")})})]}),s&&(0,r.jsx)("div",{role:"alert",className:"sidebar-share-error",children:s})]})}function t_(e){let{toast:t,dismissLabel:n,durationMs:s,onDismissRef:a}=e,o=(0,i.useRef)(null),[l,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(!1),p=l||c;return(0,i.useLayoutEffect)(()=>{let e=o.current;e&&window.matchMedia?.("(hover: hover)").matches&&e.matches(":hover")&&d(!0)},[]),(0,i.useEffect)(()=>{if(p)return;let e=window.setTimeout(()=>a.current(),s);return()=>window.clearTimeout(e)},[p,s,a]),(0,r.jsxs)("div",{ref:o,className:"sidebar-toast",onPointerEnter:e=>{"mouse"===e.pointerType&&d(!0)},onPointerLeave:()=>d(!1),onFocus:()=>u(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||u(!1)},children:[t.tail?(0,r.jsxs)("span",{className:"sidebar-toast-message has-tail",title:t.message+t.tail,children:[(0,r.jsx)("span",{className:"sidebar-toast-message-head",children:t.message}),(0,r.jsx)("span",{className:"sidebar-toast-message-tail",children:t.tail})]}):(0,r.jsx)("span",{className:"sidebar-toast-message",title:t.message,children:t.message}),t.actions.map(e=>(0,r.jsx)("button",{type:"button",className:"sidebar-toast-action",onClick:()=>{a.current(),e.onClick()},children:e.label},e.id)),(0,r.jsx)("button",{type:"button",className:"sidebar-toast-dismiss","aria-label":n,title:n,onClick:()=>a.current(),children:(0,r.jsx)(ts.US,{size:12})})]})}function tU(e){let{toast:t,onDismiss:n,dismissLabel:s,durationMs:a=1e4}=e,o=(0,i.useRef)(n);return o.current=n,(0,r.jsx)("div",{className:"sidebar-toast-region",role:"status","aria-live":"polite",children:t?(0,r.jsx)(t_,{toast:t,dismissLabel:s,durationMs:a,onDismissRef:o},t.id):null})}let tq={remote:"sidebar.openInExplorerRemoteOnly","unsupported-platform":"sidebar.openInExplorerUnsupported"};function tK(e){let{ref:t,onClick:n,title:i,disabled:s,pressed:a,expanded:o,controls:l,done:d,className:c,children:u}=e;return(0,r.jsx)("button",{ref:t,type:"button",onClick:n,disabled:s,title:i,"aria-label":i,"aria-pressed":a,"aria-expanded":o,"aria-controls":l,className:`sidebar-tool-button${a||o?" is-active":""}${d?" is-done":""}${c?` ${c}`:""}`,children:u})}let tZ="pi-web:unread-session-ids",tV="pi-web:last-custom-cwd",tJ={"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 tG(){try{return window.localStorage.getItem(tV)??""}catch{return""}}function tY(e){if(!e)return new Set;try{let t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(e=>"string"==typeof e))}catch{}return new Set}function tX(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 tQ(e,t){return e.length>t?`${e.slice(0,t)}…`:e}function t0(e){let t=document.activeElement;e&&t instanceof HTMLElement&&t!==document.body&&(0===t.getClientRects().length||null!==t.closest("[inert]"))?e.focus({preventScroll:!0}):eC(document,e)}function t1(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 t2(e){var t,n,s;let a,o,c,p,h,m,g,b,{selectedSessionId:y,onSelectSession:j,onNewSession:k,controlRef:w,onNewSessionContextChange:C,initialSessionId:O,initialSessionLinked:_,skipInitialProjectSelection:V,onInitialRestoreDone:ea,refreshKey:ec,onSessionDeleted:eu,selectedCwd:em,onCwdChange:ef,onOpenFile:ex,onOpenTerminal:ey,onOpenGitGraph:eS,explorerRefreshKey:eI,onExplorerRefresh:e$,onAtMention:eE,onAtMentions:eT,onBackgroundTaskDone:eM,hiddenFinishedSessionIds:eR,onRunningSessionIdsChange:eA,onSessionsChange:eL}=e,{t:eP}=(0,eW.s)(),ez=(0,eF.a)(),[e_,eZ]=(0,i.useState)([]),eV=(0,i.useRef)(null),eJ=(0,i.useRef)(0),[eG,eY]=(0,i.useState)(!0),[eX,eQ]=(0,i.useState)(!1),[e0,e1]=(0,i.useState)(null),[e2,e5]=(0,i.useState)(null),[e9,te]=(0,i.useState)(""),[tt,tn]=(0,i.useState)(!1),[tr,ti]=(0,i.useState)(tG),[to,td]=(0,i.useState)(null),[tc,tu]=(0,i.useState)(!1),[tp,th]=(0,i.useState)(null),tm=(0,i.useRef)(null),[tg,tf]=(0,i.useState)(null),[tx,tb]=(0,i.useState)(null),tv=(0,i.useRef)(null);tv.current??=new Set((0,eo.PS)());let[ty,tj]=(0,i.useState)(0),[tk,tw]=(0,i.useState)(!1),[tS,tC]=(0,i.useState)(!1),[tN,tI]=(0,i.useState)(!1),[t$,tE]=(0,i.useState)(""),[tT,tR]=(0,i.useState)(0),[tA,tL]=(0,i.useState)(!0),[tP,tz]=(0,i.useState)(!1),[tF,tD]=(0,i.useState)(!1),[tH,t_]=(0,i.useState)(null),[t2,t4]=(0,i.useState)(null),[t8,t6]=(0,i.useState)(()=>new Set),[t3,t5]=(0,i.useState)(()=>new Set),[t9,t7]=(0,i.useState)(()=>new Set),[ne,nt]=(0,i.useState)(()=>(function(){try{return tY(window.localStorage.getItem(tZ))}catch{return new Set}})()),nn=(0,i.useRef)(new Set),nr=(0,i.useRef)(new Set),ni=(0,i.useRef)(new Set),ns=(0,i.useRef)(new Set),na=(0,i.useRef)(!1),no=(0,i.useRef)(null),nl=(0,i.useRef)(null),nd=(0,i.useRef)(null),nc=eO(),nu=!ez&&"below"===nc,[np,nh]=(0,i.useState)("sessions"),[nm,ng]=(0,i.useState)(!1),nf=(0,i.useRef)(null),nx=(0,i.useRef)(null),nb=(0,i.useRef)(null),nv=(0,i.useRef)(null),ny=(0,i.useRef)(new WeakMap),[nj,nk]=(0,i.useState)({}),[nw,nS]=(0,i.useState)(()=>new Set),[nC,nN]=(0,i.useState)({}),[nI,n$]=(0,i.useState)(!1),[nE,nT]=(0,i.useState)([]),[nM,nR]=(0,i.useState)(!1),{phase:nA,start:nL,end:nP}=eK(),{phase:nz,start:nO,end:nW}=eK(),nF=(0,i.useRef)(nm);nF.current=nm;let nD=(0,i.useRef)(nM);nD.current=nM;let nB=(0,i.useCallback)(e=>{e!==nD.current&&nO(e?"in":"out"),nR(e)},[nO]),nH=(a=nm&&"out"===nA,o=!nm&&"in"===nA,{bodyHidden:nm&&!a,bodyInert:a,moving:a||o,open:!nm&&!o}),n_=(c=nM&&"in"===nz,p=!nM&&"out"===nz,{mainHidden:nM&&!c,mainInert:c,archiveMounted:nM||p,archiveInert:p,archiveClass:c?"is-entering":p?"is-leaving":null}),[nU,nq]=(0,i.useState)(null),[nK,nZ]=(0,i.useState)(null),[nV,nJ]=(0,i.useState)(null),[nG,nY]=(0,i.useState)(null),[nX,nQ]=(0,i.useState)(null),n0=(0,i.useRef)(0),n1=(0,i.useCallback)(e=>{nQ(t=>t?.id===e?null:t)},[]),[n2,n4]=(0,i.useState)(null),n8=(0,i.useCallback)(e=>{n4(t=>t?.id===e?null:t)},[]),n6=(0,i.useRef)(y);n6.current=y;let[n3,n5]=(0,i.useState)(null),n9=(0,i.useRef)(0),n7=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2?arguments[2]:void 0;n9.current+=1,n5({id:n9.current,message:e,...n?{tail:n}:{},actions:t})},[]),[re,rt]=(0,i.useState)(0),rn=(0,i.useRef)(0),rr=(0,i.useRef)(null),[ri,rs]=(0,i.useState)(0),ra=(0,i.useRef)(null),ro=(0,i.useRef)(null),rl=(0,i.useRef)(null),rd=(0,i.useRef)(null),[rc,ru]=(0,i.useState)(0),rp=(0,i.useCallback)(e=>{rd.current=e,ru(e=>e+1)},[]);(0,i.useEffect)(()=>{let e=rd.current;rd.current=null,e&&eC(document,e())},[rc]);let{state:rh,loaded:rm,synced:rg,error:rf,apply:rx,snapshot:rb,noteRevision:rv}=function(){let[e,t]=(0,i.useState)(R),[n,r]=(0,i.useState)(!1),[s,a]=(0,i.useState)(!1),[o,l]=(0,i.useState)(null),d=(0,i.useRef)(e),c=(0,i.useRef)(e),u=(0,i.useRef)([]),p=(0,i.useRef)(Promise.resolve()),h=(0,i.useRef)(0),m=(0,i.useRef)(null),g=(0,i.useCallback)(()=>{let e=d.current;for(let{request:t,now:n}of u.current)e=function(e,t,n){var r,i,s,a;let o=function(e){let t={};for(let[n,r]of Object.entries(e.sessions))t[n]={...r};let n={};for(let[t,r]of Object.entries(e.projects))n[t]={...r};let r={...e,sessions:t,projects:n};return e.projectOrder&&(r.projectOrder=[...e.projectOrder]),e.projectNames&&(r.projectNames={...e.projectNames}),r}(e),l=!1;switch(t.action){case"set":for(let e of t.ids){let r=v(o.sessions,e)?o.sessions[e]:void 0;A(o.sessions,e,function(e,t,n){let r={...e};return"pinned"in t?t.pinned?(void 0===r.pinnedAt||void 0!==r.archivedAt)&&(r.pinnedAt=n,delete r.archivedAt):delete r.pinnedAt:t.archived?(r.archivedAt=n,delete r.pinnedAt):delete r.archivedAt,r}(r,t,n))&&(l=!0)}break;case"restore":for(let e of t.entries){let t={};null!==e.pinnedAt&&(t.pinnedAt=e.pinnedAt),null!==e.archivedAt&&(t.archivedAt=e.archivedAt),A(o.sessions,e.id,t)&&(l=!0)}break;case"pin-project":{let{projectKey:e,root:a}=t,d=v(o.projects,e)?o.projects[e]:void 0;if(t.pinned?d?.root!==a&&(o.projects[e]={pinnedAt:n,root:a},l=!0):d&&(delete o.projects[e],l=!0),(t.pinned?void 0===d:void 0!==d)&&o.projectOrder){let n,a,d=(r=o.projectOrder,i=o.projects,s=t.pinned,a=r.filter(t=>t!==e),s?(n=0,a.forEach((e,t)=>{v(i,e)&&(n=t+1)})):(n=a.findIndex(e=>!v(i,e)))<0&&(n=a.length),a.splice(n,0,e),a);$(d.length,I(d))&&L(o,d)&&(l=!0)}break}case"add-projects":L(o,function(e,t){let n=P(e,t),r=e.length,i=I(e),s=n.length;for(;s>0;){let e=N(n[s-1]);if(!$(r+1,i+e))break;r++,i+=e,s--}return[...n.slice(s),...e]}(o.projectOrder??[],t.keys))&&(l=!0);break;case"move-project":{let e,n,{projectKey:r,anchorKey:i,position:s,add:d}=t,c=o.projectOrder??[];L(o,function(e,t){let n=e.length,r=I(e);if($(n,r))return e;let i=new Set;for(let s=e.length-1;s>=0&&!$(n,r);s--)t.has(e[s])||(i.add(s),n--,r-=N(e[s]));let s=e.filter((e,t)=>!i.has(t));return $(n,r)?s:E(s)}((a=[...P(c,d),...c],(e=a.filter(e=>e!==r)).includes(i)||e.unshift(i),n=e.indexOf(i),e.splice("before"===s?n:n+1,0,r),e),new Set([r,i,...d])))&&(l=!0);break}case"rename-project":{let e=S(t.name);void 0!==e&&function(e,t,n){let r={...e.projectNames};if((v(r,t)?r[t]:void 0)===(n??void 0))return!1;if(null===n)delete r[t];else if(r[t]=n,!M(Object.keys(r).length,function(e){let t=1;for(let[n,r]of Object.entries(e))t+=T(n,r);return t}(r)))return!1;return 0===Object.keys(r).length?delete e.projectNames:e.projectNames=r,!0}(o,t.projectKey,e)&&(l=!0)}}return{state:o,changed:l}}(e,t,n).state;c.current=e,t(e)},[]),f=(0,i.useCallback)(async e=>{let t=++h.current;m.current=t;try{let n=await fetch(eH,{cache:"no-store"}),i=await eq(n);if(t!==h.current)return;d.current=i,g(),e||l(null),r(!0),a(!0)}catch(e){if(t!==h.current)return;l(eU(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]),y=(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(eH,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store"}),i=await eq(t);h.current++,d.current=i,l(null),r(!0),a(!0),n=!0}catch(e){l(eU(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]),j=(0,i.useCallback)(e=>(function(e,t){let n=new Set,r=[];for(let i of t){if(n.has(i))continue;n.add(i);let t=v(e.sessions,i)?e.sessions[i]:void 0;r.push({id:i,pinnedAt:t?.pinnedAt??null,archivedAt:t?.archivedAt??null})}return r})(c.current,e),[]);return(0,i.useEffect)(()=>{x()},[x]),(0,i.useMemo)(()=>({state:e,loaded:n,synced:s,error:o,refresh:x,noteRevision:b,apply:y,snapshot:j}),[e,n,s,o,x,b,y,j])}(),ry=(0,i.useRef)(null),rj=(0,i.useRef)(null);eB(rj);let rk=(0,i.useRef)(null),rw=(0,i.useRef)(null),rS=(0,i.useRef)(320),rC=(0,i.useCallback)(()=>{let e=rw.current,t=ry.current;return e&&t&&0!==e.clientHeight?e.clientHeight-t.offsetHeight:window.innerHeight-36},[]),rN=(0,i.useCallback)(()=>Math.round(.45*rC()),[rC]),rI=(0,i.useCallback)(()=>rC()-120,[rC]),r$=(0,eD.T)({ariaLabel:eP("sidebar.resizeFiles"),axis:"vertical",cssVariable:"--sidebar-files-height",defaultWidth:320,getDefaultWidth:rN,getMaxWidth:rI,growthDirection:"up",maxWidth:2e3,minWidth:220,persistClamp:!1,storageKey:"pi-web:sidebar-files-height",widthRef:rS}),rE=r$.panelRef,rT=(0,i.useCallback)(e=>{rw.current=e,rE.current=e},[rE]),rM=r$.reclampWidth;(0,i.useEffect)(()=>{let e=rw.current;if(!nu||!e||"u"<typeof ResizeObserver)return;let t=new ResizeObserver(()=>rM());return t.observe(e),()=>t.disconnect()},[rM,nu]),(0,i.useEffect)(()=>{let e=(0,eo.K$)();"sessions"!==e&&nh(e);let t=(0,eo.$$)();Object.keys(t).length>0&&nk(t),(0,eo.iw)()&&n$(!0);let n=(0,eo.cA)();n.length>0&&nT(n),(0,eo.bj)()&&ng(!0),(0,eo.hS)()&&tz(!0),(0,eo.vK)()},[]);let rR=(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=++eJ.current;try{e&&eY(!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!==eJ.current)return;eV.current=s.sessionListVersion,eZ(s.sessions),n||eQ(!0),na.current||(ni.current=new Set(s.completionNotificationSuppressedSessionIds??[]),t6(e=>tX(e,s.runningSessionIds??[])),t5(e=>tX(e,s.awaitingInputSessionIds??[])));let a=new Set(s.sessions.filter(e=>!l(e.relation)).map(e=>e.id));nt(e=>{if(0===e.size)return e;let t=new Set([...e].filter(e=>a.has(e)));return t.size===e.size?e:t}),e1(null)}catch(e){r===eJ.current&&e1(String(e))}finally{r===eJ.current&&eY(!1)}},[]),rA=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!rA.current;rA.current=!0;let t=!0;return e?rR(!0,!1,!0).then(()=>{t&&(no.current=setTimeout(()=>{no.current=null,t&&rR(!1,!0)},750))}):rR(),()=>{t=!1,no.current&&(clearTimeout(no.current),no.current=null)}},[rR,ec]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/open-in-explorer").then(e=>e.ok?e.json():null).then(t=>{!e&&t&&t_(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{t4(null)},[e2,em]);let rL=(0,i.useCallback)(async()=>{let e=e2??em;if(!e)return!1;try{let t=await fetch("/api/open-in-explorer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e})});if(t.ok)return t4(null),!1;let n=await t.json().catch(()=>({}));t4(n.error??`HTTP ${t.status}`)}catch(e){t4(e instanceof Error?e.message:String(e))}return!0},[e2,em]),rP=eP(tH?.platform==="darwin"?"sidebar.openInFinder":tH?.platform==="win32"?"sidebar.openInExplorer":"sidebar.openInFileManager"),rz=tH?.supported===!1,rO=t2?eP(tq[t2]??t2):null;(0,i.useEffect)(()=>{try{0===ne.size?window.localStorage.removeItem(tZ):window.localStorage.setItem(tZ,JSON.stringify([...ne]))}catch{}},[ne]),(0,i.useEffect)(()=>{let e=e=>{(null===e.key||e.key===tZ)&&nt(t=>tX(t,[...tY(e.newValue)]))};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[]),(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let s=new AbortController;n?.abort(),n=s;let a=Date.now(),o=null,l="error",d=null;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:s.signal});if(d=t.status,!t.ok)return;l="ok";let r=await t.json();if(o=Date.now(),e||n!==s)return;na.current=!0,ni.current=new Set(r.completionNotificationSuppressedSessionIds??[]),t6(e=>tX(e,r.runningSessionIds??[])),t5(e=>tX(e,r.awaitingInputSessionIds??[])),t7(e=>tX(e,r.subagentsActiveSessionIds??[])),rv(r.sessionUiStateRevision),r.sessionListVersion!==eV.current&&await rR()}catch{l=s.signal.aborted?"aborted":"error"}finally{n===s&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500)),(0,eN.tK)(a,l,d,o)}},s=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",s),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",s)}},[rR,rv]),(0,i.useEffect)(()=>{eA?.(t8)},[eA,t8]),(0,i.useEffect)(()=>{eL?.(e_)},[e_,eL]),(0,i.useEffect)(()=>{!function(e){let t,n;if("u"<typeof document)return;let r=(n=(t=eb(e.awaiting))+eb(e.unread))<=0?null:{kind:t>0?"awaiting":"unread",count:Math.min(n,99)},i=r?`${r.kind}:${r.count}`:"none";if(i!==ev){if(ev=i,!r){for(let[e,t]of ej)e.href=t;return}for(let e of ek())ej.has(e)||ej.set(e,e.href);ew(r,i)}}({awaiting:t3.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}(ne,eR)})},[t3,ne,eR]),(0,i.useEffect)(()=>{let e=nn.current,t=[...e].filter(e=>!t8.has(e)&&e!==y),n=new Set([...t8,...t9]),r=[...nr.current].filter(e=>!n.has(e)&&e!==y),i=new Set(e_.filter(e=>l(e.relation)).map(e=>e.id)),s=r.filter(e=>!ns.current.has(e)&&!i.has(e)),a=[...t8].filter(t=>!e.has(t));(s.length>0||a.length>0)&&nt(e=>{let t=new Set(e);return t8.forEach(e=>t.delete(e)),s.forEach(e=>t.add(e)),t});let o=a.some(e=>!e_.some(t=>t.id===e));(t.length>0||o)&&rR(),s.length>0&&eM?.(),nn.current=t8,nr.current=n;let d=ns.current;ns.current=new Set([...n].filter(e=>ni.current.has(e)||i.has(e)||d.has(e)&&!t8.has(e)))},[t8,t9,y,e_,rR,eM]),(0,i.useEffect)(()=>{y&&nt(e=>{if(!e.has(y))return e;let t=new Set(e);return t.delete(y),t})},[y]),(0,i.useEffect)(()=>{void 0!==eI&&tj(e=>e+1)},[eI]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&te(e.home)}).catch(()=>{})},[]);let rW=(0,i.useRef)(!1),rF=(0,i.useCallback)(e=>e?function(e,t){let{validated:n,listing:r,sessions:i}=t;if(n?.cwd===e)return{root:n.root,key:n.key};if(r?.forCwd===e||r?.isTopLevel&&r.worktrees.some(t=>t.path===e))return{root:r.projectRoot,key:r.projectKey};let s=i.find(t=>t.cwd===e||(t.projectRoot??t.cwd)===e);return s?{root:s.projectRoot??s.cwd,key:f(s)}:{root:e,key:e}}(e,{validated:tp,listing:tg,sessions:e_}):null,[tp,tg,e_]),rD=(0,i.useMemo)(()=>rF(e2),[rF,e2]),rB=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=rF(e2),t=rB.current;(t?.cwd!==e2||t.key!==(e?.key??null))&&(rB.current={cwd:e2,key:e?.key??null},ef?.(e2,e?.root??null,e?.key??null))},[e2,ef,rF]);let rH=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!em){rH.current=null;return}em!==rH.current&&(rH.current=em,e5(em))},[em]);let[r_,rU]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!e2){tf(null),tb(null);return}let e=!1;return tb(e2),fetch(`/api/worktrees?cwd=${encodeURIComponent(e2)}`).then(e=>e.json()).then(t=>{if(!e){if(tb(null),t.error||!t.projectRoot)return void tf(null);t.isGit?tv.current?.delete(e2):tv.current?.add(e2),(0,eo._N)(e2,!!t.isGit),tf({forCwd:e2,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||(tb(null),tf(null))}),()=>{e=!0}},[e2,r_,ec]),(0,i.useEffect)(()=>{if(0!==e_.length&&!V&&null===e2){if(O&&!rW.current){rW.current=!0;let e=e_.find(e=>e.id===O);if(e){e5(e.cwd),j(e,!0);return}ea?.(),_&&n7(eP("sidebar.sessionNotFound"))}let e=x(e_);e.length>0&&e5(e[0].root)}},[e_,e2,O,_,V,j,ea,n7,eP]);let rq=tg?tg.worktrees.find(e=>e.path===e2)??(tg.forCwd===e2&&tg.currentWorktreePath?tg.worktrees.find(e=>e.path===tg.currentWorktreePath):void 0)??tg.worktrees.find(e=>e.isMain):void 0,rK=rq?.path??null,rZ=(0,i.useCallback)(async function(e){let{remember:t=!0,purpose:n=tt}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=(e??tr).trim();if(r&&!tc){tu(!0),td(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 td(s.error??`HTTP ${e.status}`);if(t){var i=s.cwd;try{window.localStorage.setItem(tV,i)}catch{}ti(s.cwd)}if(tn(!1),"new-session"===n){let e=ro.current,t=rl.current;ro.current=null,rl.current=null,e?.({cwd:s.cwd,projectKey:s.projectKey,projectRoot:s.projectRoot}),rp(()=>t?.isConnected?t:null);return}th({cwd:s.cwd,root:s.projectRoot,key:s.projectKey}),e5(s.cwd)}catch(e){td(e instanceof Error?e.message:String(e))}finally{tu(!1)}}},[tt,tr,tc,rp]),rV=(0,i.useCallback)(()=>{tn("files"),td(null)},[]),rJ=(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 rZ(n.cwd,{remember:!1,purpose:e})}catch{}},[rZ]),rG=(0,i.useRef)(rJ);rG.current=rJ;let rY=(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:eP(t.key,{...t.params,path:ed(t.params.path)})}:t}let s=i.path;return tf(n=>n&&n.projectKey===e.key&&!n.worktrees.some(e=>e.path===s)?{...n,worktrees:[...n.worktrees,{path:s,branch:t,isMain:!1}]}:n),rU(e=>e+1),{path:s}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},[eP]),rX=(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 rK===t&&e5(e.root),rU(e=>e+1),"removed"}catch(e){return{error:e instanceof Error?e.message:String(e)}}},[rK]),rQ=(0,i.useCallback)(()=>rU(e=>e+1),[]),r0=(0,i.useCallback)(e=>{let{cwd:t,projectKey:n,projectRoot:r}=e;n&&r&&th({cwd:t,root:r,key:n}),e5(t)},[]),r1=(0,i.useCallback)((e,t,n,r)=>{eZ(t=>t.some(t=>t.id===e.id)?t:[e,...t]),e.cwd&&e5(e.cwd),j(e,!1,t,n,r)},[j]),r2=(0,i.useCallback)(e=>{let{cwd:t,projectKey:n,projectRoot:r,carryComposer:i}=e;n&&r&&th({cwd:t,root:r,key:n}),e5(t),k?.("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)},[k]),r4=(0,i.useRef)(r2);r4.current=r2,(0,i.useImperativeHandle)(w,()=>({startNewSessionIn:e=>r4.current(e),openFolderForNewSession:(e,t)=>{ro.current=e,rl.current=t,td(null),tn("new-session")},openDefaultDirectoryForNewSession:e=>{ro.current=e,rl.current=null,rG.current("new-session")},refreshWorktrees:rQ,createWorktree:rY}),[rY,rQ]);let r8=(0,i.useCallback)(()=>{e2&&r2({cwd:e2})},[e2,r2]),r6=(0,i.useMemo)(()=>x(e_),[e_]),r3=(0,i.useMemo)(()=>d(e_),[e_]),r5=(0,i.useMemo)(()=>new Map(r3.map(e=>[e.root.id,e])),[r3]),r9=(0,i.useMemo)(()=>{let e=new Set,t=new Map;for(let n of r3){if(!U(n,rh,t8))continue;for(let t of H(n))e.add(t);let r=f(n.root);t.set(r,(t.get(r)??0)+1)}return{ids:e,countByProject:t}},[r3,rh,t8]),r7=(0,i.useMemo)(()=>(function(e,t,n){let r=new Map;for(let i of e){let e=f(i);if(!e)continue;let s=r.get(e);s||(s={running:0,unread:0},r.set(e,s)),t.has(i.id)&&s.running++,n.has(i.id)&&s.unread++}return r})(0===r9.ids.size?e_:e_.filter(e=>!r9.ids.has(e.id)),t8,ne),[e_,r9,t8,ne]),ie=!!(tg?.isGit&&tg.isTopLevel&&e2&&rD?.key===tg.projectKey),it=e2&&tg?.isGit&&rD?.key===tg.projectKey&&!ie?{label:eP("sidebar.openRepoRoot"),title:eP("sidebar.openRepoRootTitle")}:null,ir=!!(e2&&tx===e2),ii=it??(!ir||ie||e2&&tv.current?.has(e2)?null:{label:eP("sidebar.worktrees"),title:eP("sidebar.checkingWorktrees")}),is=rD?.key??null,ia=rD?.root??null,io=(0,i.useMemo)(()=>is&&ia?{key:is,root:ia}:null,[is,ia]),il=(0,i.useMemo)(()=>0===nw.size?nj:Object.fromEntries([...[...nw].filter(e=>!Object.hasOwn(nj,e)).map(e=>[e,!0]),...Object.entries(nj)]),[nj,nw]),id=(0,i.useMemo)(()=>(function(e){let{uiState:t,runningIds:n,currentProject:r}=e,i=d(e.sessions),s=Y(t,r),a=0,o=[],l=new Map,c=new Map,u=new Set;for(let e of i){if(U(e,t,n)){a++;continue}s.noteFamily(e);let r=G(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),q(e,t,n)){o.push(e);continue}let d=l.get(r);d?d.push(e):l.set(r,[e])}let p=[{kind:"spacer",key:"top-spacer"}];if(o.length>0){let n=e=>D(F(t,e.root.id)?.pinnedAt)??0,r=o.map((e,t)=>({family:e,index:t})).sort((e,t)=>B(n(e.family),n(t.family))||e.index-t.index).map(e=>{let{family:t}=e;return t}),{running:i,awaiting:a,unread:l}=J(r,e);if(p.push({kind:"pinned-header",key:"pinned-header",count:r.length,collapsed:e.pinnedCollapsed,running:i,awaiting:a,unread:l}),!e.pinnedCollapsed){let{visible:t,revealed:n,nextShown:i}=Q(r,8,ee(e.moreShown,W),e);for(let n of t)p.push(X(n,"pinned",s.get(G(n)),e));let a=en(r.length,t.length,n);a&&p.push({kind:"pinned-more",key:"pinned-more",...a,nextShown:i})}p.push({kind:"spacer",key:"pinned-spacer"})}let h=[...l.keys()],m=new Set(h),g=e=>{m.has(e)||(m.add(e),h.push(e))};for(let e of(r&&g(r.key),Object.keys(t.projects)))g(e);let f=h.map(e=>s.get(e)),x=new Map;(t.projectOrder??[]).forEach((e,t)=>{x.has(e)||x.set(e,t)});let b=e=>e.pinned||u.has(e.key),v=(e,t)=>[...e.filter(e=>{let{project:t}=e;return!x.has(t.key)}).sort((e,n)=>Number(b(e.project))-Number(b(n.project))||t(e,n)),...e.filter(e=>{let{project:t}=e;return x.has(t.key)}).sort((e,t)=>(x.get(e.project.key)??0)-(x.get(t.project.key)??0))].map(e=>{let{project:t}=e;return t}),y=e=>c.get(e.key)??(e.current?1/0:-1/0),j=e=>D(t.projects[e.key]?.pinnedAt)??0,k=f.map((e,t)=>({project:e,index:t})),w=v(k.filter(e=>{let{project:t}=e;return t.pinned}),(e,t)=>B(j(t.project),j(e.project))||e.index-t.index),S=v(k.filter(e=>{let{project:t}=e;return!t.pinned}),(e,t)=>B(y(e.project),y(t.project))||e.index-t.index),C=[...w,...S],N=e=>e.filter(e=>!x.has(e.key)).map(e=>e.key),I={pinned:N(w),other:N(S)},$=C.filter(e=>!x.has(e.key)&&b(e)).map(e=>e.key);for(let[t,n]of C.entries()){t>0&&p.push({kind:"spacer",key:`group-spacer:${n.key}`});let r=l.get(n.key)??[],i=Z(n,e.groupExpansion),{running:s,awaiting:a,unread:o}=J(r,e);if(p.push({kind:"group",key:`group:${n.key}`,project:n,expanded:i,running:s,awaiting:a,unread:o}),i)if(0===r.length)p.push({kind:"group-empty",key:`empty:${n.key}`,project:n});else{let{visible:t,revealed:i,nextShown:s}=Q(r,6,ee(e.moreShown,n.key),e);for(let r of t)p.push(X(r,"group",n,e));let a=en(r.length,t.length,i);a&&p.push({kind:"group-more",key:`more:${n.key}`,projectKey:n.key,...a,nextShown:s})}}return C.length>0&&p.push({kind:"spacer",key:"footer-spacer"}),p.push({kind:"footer-open",key:"footer-open"}),a>0&&p.push({kind:"footer-archived",key:"footer-archived",count:a}),{rows:p,projects:C,archivedCount:a,unorderedKeysByBand:I,projectKeysToRecord:$}})({sessions:e_,uiState:rh,runningIds:t8,awaitingIds:t3,unreadIds:ne,selectedSessionId:y,currentProject:io,groupExpansion:il,moreShown:nC,pinnedCollapsed:nI}),[e_,rh,t8,t3,ne,y,io,il,nC,nI]),ic=n_.archiveMounted,iu=(0,i.useMemo)(()=>new Set(nE),[nE]),ip=(0,i.useMemo)(()=>ic?function(e){let{uiState:t,runningIds:n}=e,r=Y(t,e.currentProject),i=new Map;for(let s of d(e.sessions)){if(!U(s,t,n))continue;r.noteFamily(s);let e=D(F(t,s.root.id)?.archivedAt)??0,a=G(s),o=i.get(a);o?(o.families.push({family:s,archivedAt:e}),o.newest=Math.max(o.newest,e)):i.set(a,{newest:e,families:[{family:s,archivedAt:e}]})}let s=[];for(let{key:t,group:n}of[...i.entries()].map((e,t)=>{let[n,r]=e;return{key:n,group:r,index:t}}).sort((e,t)=>B(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)=>B(e.archivedAt,t.archivedAt)||e.index-t.index))s.push(X(t,"archive",i,e))}return s}({sessions:e_,uiState:rh,runningIds:t8,awaitingIds:t3,unreadIds:ne,selectedSessionId:y,currentProject:io,collapsed:iu}):[],[ic,e_,rh,t8,t3,ne,y,io,iu]),ih=(0,i.useMemo)(()=>ip.flatMap(e=>"archive-group"===e.kind?[e]:[]),[ip]),im=(0,i.useMemo)(()=>new Map(id.projects.map(e=>[e.key,e])),[id.projects]),ig=(0,i.useRef)(new Set),ix=id.projectKeysToRecord,ib=rh.projectOrder?.length??0;(0,i.useEffect)(()=>{if(eG||!rg||!eX||ib>=1e3)return;let e=ig.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)}(ix,e);if(0!==t.length){for(let n of t)e.add(n);rx({action:"add-projects",keys:t})}},[rx,eG,ix,eX,ib,rg]);let iv=rh.projectNames,iy=(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(eg(s,n)));return i})(id.projects,r6,iv),[id.projects,r6,iv]),ij=(0,i.useMemo)(()=>{if(!e2||!rD)return null;let e=ie&&null!==tg;return{cwd:e2,project:eg(rD,iv),worktrees:e?tg.worktrees.map(e=>{let{path:t,branch:n,isMain:r}=e;return{path:t,branch:n,isMain:r}}):null,currentWorktreePath:e?rK:null,projects:iy}},[e2,rD,ie,tg,rK,iy,iv]),ik=(0,i.useRef)(ij);ik.current=ij;let iw=ij?JSON.stringify([ij.cwd,ij.project.key,ij.project.root,ij.project.alias??null,ij.currentWorktreePath,ij.worktrees?.map(e=>[e.path,e.branch,e.isMain])??null,ij.projects.map(e=>[e.key,e.root,e.alias??null])]):"";(0,i.useEffect)(()=>{C?.(ik.current)},[iw,C]);let iS=(0,i.useRef)(is);(0,i.useLayoutEffect)(()=>{let e=iS.current;if(iS.current=is,null===e||e===is)return;let t=im.get(e);nS(e=>!t||t.current||t.pinned||e.has(t.key)||Object.hasOwn(nj,t.key)?e:new Set(e).add(t.key))},[is,nj,im]);let iC=(0,i.useCallback)((e,t)=>{nk(e),(0,eo.wL)(e),nS(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)),nN(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))},[]),iN=(0,i.useCallback)(()=>(nb.current?.hidden?nx:nf).current??rk.current,[]),iI=(0,i.useCallback)(e=>{let t=nb.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 iN()},[iN]),i$=(0,i.useCallback)(e=>{let t=CSS.escape(`group:${e}`),n=nb.current?.querySelector(`[data-row-key="${t}"] .session-tree-group-toggle`);return n&&n.getClientRects().length>0?n:iN()},[iN]),iE=(0,i.useCallback)(async e=>{let t=await rx(e);return t||rt(e=>e+1),t},[rx]);(0,i.useEffect)(()=>{re!==rn.current&&(rn.current=re,n7(eP("sidebar.uiStateFailed",{error:rf??""})))},[re,rf,n7,eP]);let iT=(0,i.useCallback)((e,t,n)=>{let r=im.get(e),i=im.get(t);r&&i&&r!==i&&r.pinned===i.pinned&&(iE({action:"move-project",projectKey:e,anchorKey:t,position:n,add:id.unorderedKeysByBand[r.pinned?"pinned":"other"].slice(-500)}),n0.current+=1,nQ({id:n0.current,at:Date.now(),rowKey:`group:${e}`}))},[iE,id.unorderedKeysByBand,im]),iM=(0,i.useCallback)(e=>{nu||(nh(e),(0,eo.d9)(e))},[nu]),iR=(0,i.useCallback)(e=>{e!==nF.current&&nL(e?"out":"in"),ng(e),(0,eo.oh)(e)},[nL]),iA=(0,i.useCallback)(e=>{let t=e.target;t instanceof Element&&ny.current.set(t,t.scrollTop)},[]);(0,i.useLayoutEffect)(()=>{for(let e of[nb.current,nv.current])if(e&&!e.hidden)for(let t of e.querySelectorAll(".session-tree-scroll, .sidebar-files-scroll")){let e=ny.current.get(t);void 0!==e&&t.scrollTop!==e&&(t.scrollTop=e)}},[np,nM,nu,nm]);let iL=(0,i.useCallback)(e=>{if(nY(null),nB(!0),tI(!1),iM("sessions"),void 0!==e){if(nE.includes(e)){let t=nE.filter(t=>t!==e);nT(t),(0,eo.zY)(t)}n0.current+=1,n4({id:n0.current,at:Date.now(),rowKey:`archive:${e}`,block:"start"})}},[nE,nB,iM]),iP=(0,i.useRef)(null),iz=(0,i.useRef)(nM),iO=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(iz.current===nM)return;if(iz.current=nM,nM)return void t0(iP.current);let e=nb.current?.querySelector('[data-row-key="footer-archived"] button'),t=e&&e.getClientRects().length>0?e:iN();t0(t),t&&document.activeElement===t&&(iO.current=t)},[nM,iN]);let iW=(0,i.useRef)(null),iF=(0,i.useRef)(nu);(0,i.useLayoutEffect)(()=>{if(iF.current===nu)return;iF.current=nu;let e=iW.current;e&&(!e.isConnected||0===e.getClientRects().length)&&t0(iN())},[nu,iN]);let iD=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"===np?"files":"sessions";iM(t),("sessions"===t?nf:nx).current?.focus()},iB=(0,i.useCallback)((e,t)=>{iE({action:"set",ids:[e.root.id],pinned:t})},[iE]),iH=(0,i.useCallback)((e,t)=>{nt(n=>{let r=new Set(n);if(t)for(let t of H(e))r.delete(t);else r.add(e.root.id);return r})},[]),i_=(0,i.useCallback)(e=>{0!==e.length&&nt(t=>{let n=new Set(t);for(let t of e)t!==n6.current&&n.add(t);return n.size===t.size?t:n})},[]),iU=(0,i.useCallback)(e=>{let t=e.filter(e=>!e.root.transient);if(0===t.length)return;let n=rb(t.map(e=>e.root.id)),r=t.flatMap(e=>H(e)),i=r.filter(e=>ne.has(e));for(let e of z(t))iE({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=>H(e)));i_(i.filter(e=>n.has(e)))});i.length>0&&nt(e=>{let t=new Set(e);for(let e of r)t.delete(e);return t}),n7(1===t.length?eP("sidebar.archivedToast",{title:tQ(ta(t[0].root),28)}):eP("sidebar.archivedManyToast",{count:t.length}),[{id:"undo",label:eP("sidebar.undo"),onClick:()=>{for(let e of z(n))iE({action:"restore",entries:e});i_(i),rp(()=>iI(t[0].root.id))}},{id:"view",label:eP("sidebar.viewArchive"),onClick:()=>iL()}])},[iE,rp,iI,iL,i_,n7,rb,eP,ne]),iq=(0,i.useCallback)(e=>{H(e).some(e=>t8.has(e))||iU([e])},[iU,t8]),iK=(0,i.useCallback)(e=>{if(0===e.length)return;let t=e.map(e=>e.root.id),n=rb(t);for(let e of z(t))iE({action:"set",ids:e,archived:!1});n7(1===e.length?eP("sidebar.restoredToast",{title:tQ(ta(e[0].root),28)}):eP("sidebar.restoredManyToast",{count:e.length}),[{id:"undo",label:eP("sidebar.undo"),onClick:()=>{for(let e of z(n))iE({action:"restore",entries:e});rp(()=>iI(e[0].root.id))}}])},[iE,iI,rp,n7,rb,eP]),iZ=(0,i.useCallback)(e=>iK([e]),[iK]),iV=(0,i.useCallback)(e=>{e.root.transient||(nJ(null),nq(e.root.id))},[]),iJ=(0,i.useCallback)(async(e,t)=>{let n=e.root,r=ta(n),i=t.trim();if(nq(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})}),rR()}catch{}},[rR]),iG=(0,i.useCallback)(e=>{nZ(e.key)},[]),iY=(0,i.useCallback)(e=>{nZ(t=>t===e?null:t),rp(()=>i$(e))},[rp,i$]),iX=(0,i.useCallback)((e,t)=>{iY(e.key);let n=function(e,t){let n=t.trim();if(n===e.name)return null;let r=""===n||n===K(e.root);return r&&null===e.customName?null:{action:"rename-project",projectKey:e.key,name:r?null:n}}(e,t);n&&iE(n)},[iE,iY]),iQ=(0,i.useCallback)(async e=>{let t=e.root;if(!t.transient){nJ(e=>e===t.id?null:e);try{await fetch(`/api/sessions/${encodeURIComponent(t.id)}`,{method:"DELETE"}),eu?.(t.id),rR()}catch{}}},[rR,eu]),i0=(0,i.useCallback)((e,t)=>{t?iQ(e):(nq(null),nJ(e.root.id))},[iQ]),i1=(e,t)=>{if(iO.current=null,nM){let e=nb.current?.querySelector(".sidebar-sessions-view .session-tree-scroll");e&&ny.current.delete(e),nB(!1)}let n=f(e);if(Object.hasOwn(il,n)&&!1===il[n]){let e={...nj};delete e[n],e[n]=!0,iC(e,[n])}r1(e,void 0,void 0,{keepSidebarOpen:null!==t}),rR();let r=t?`[data-row-key="${CSS.escape(t)}"]`:null;n0.current+=1,nQ({id:n0.current,at:Date.now(),rowKey:`session:group:${e.id}`,takeFocusFrom:e=>null!==r&&null!==e.closest(r)||e===iO.current})},i2=(0,i.useRef)(i1);i2.current=i1;let i4=(0,i.useRef)(new Set),i8=(0,i.useCallback)(async e=>{let t=e.family.root;if(t.transient||i4.current.has(t.id))return;i4.current.add(t.id);let n=n6.current;try{var r;let i,s,a=await fetch(`/api/sessions/${encodeURIComponent(t.id)}/fork`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),o=await a.json().catch(()=>({}));if(!a.ok||!o.session){let{key:e,params:t}=function(e,t){switch(e){case"not_found":return{key:"sidebar.forkNotFound"};case"unsaved":return{key:"sidebar.forkUnsaved"};case"empty":return{key:"sidebar.forkEmpty"};case"subagent":case"request-denied":return{key:"sidebar.forkUnavailable"};default:return{key:"sidebar.forkFailed",params:{error:t}}}}(o.code,o.error??`HTTP ${a.status}`);n7(eP(e,t)),"not_found"===o.code&&rR();return}let l=o.session,d=ta(l),{head:c,tail:u}=(r=eP("sidebar.forkedToast",{title:d}),((s=(i=ep(d)?.suffix)?r.lastIndexOf(i):-1)>0?{head:r.slice(0,s),tail:r.slice(s)}:null)??{head:eP("sidebar.forkedToast",{title:tQ(d,28)}),tail:void 0});if(n6.current!==n){eZ(e=>e.some(e=>e.id===l.id)?e:[l,...e]),nt(e=>new Set(e).add(l.id)),rR(),n7(c,[{id:"open",label:eP("sidebar.open"),onClick:()=>i2.current(l,null)}],u);return}i2.current(l,e.key),n7(c,[],u)}catch(e){n7(eP("sidebar.forkFailed",{error:e instanceof Error?e.message:String(e)}))}finally{i4.current.delete(t.id)}},[rR,n7,eP]),i6=(0,i.useCallback)(e=>{e.root.transient||window.open(u(e.root.id),"_blank","noopener,noreferrer")},[]),i3=(0,i.useCallback)((e,t,n)=>{e.status.transient||nY({kind:"row",row:e,anchor:t,opener:n})},[]),i5=(0,i.useCallback)((e,t)=>{let n=e.family.root;if(n.id===nU||n.id===nV)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:()=>{rR()}})){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?t1(r,"start"):{kind:"point",x:t.clientX,y:t.clientY},s=document.activeElement,a=s instanceof HTMLElement&&null!==r&&r.contains(s);ra.current=!a&&s instanceof HTMLElement&&s!==document.body?s:null,i3(e,i,a?s:null)},[nV,rR,i3,nU]),i9=(0,i.useMemo)(()=>({sessions:e_,uiState:rh,runningIds:t8,awaitingIds:t3,unreadIds:ne,selectedSessionId:y}),[e_,rh,t8,t3,ne,y]),i7=(0,i.useCallback)((e,t)=>{let n=er(i9,e.key,6048e5,Date.now()).length;nY({kind:"group",project:e,olderCount:n,anchor:t1(t,"end"),opener:t})},[i9]),se=(0,i.useCallback)(e=>{iU(er(i9,e.key,6048e5,Date.now()).flatMap(e=>{let t=r5.get(e);return t?[t]:[]}))},[iU,r5,i9]),st=(0,i.useCallback)((e,t)=>{nY(n=>n?.kind==="group"&&n.project.key===e?{...n,askDelete:t}:n)},[]),sn=(0,i.useRef)(new Set),sr=(0,i.useCallback)(async(e,t,n)=>{if(nY(null),!(0===t.length||sn.current.has(e))){sn.current.add(e),n7(eP("sidebar.deletingSessions"));try{let e=await el(t,fetch);for(let t of e.deleted)eu?.(t);if(rR().then(()=>rp(n)),null!==e.error)return void n7(eP("sidebar.deleteFailed",{error:e.error}));let r=e.deletedRoots.length,i=[1===r?eP("sidebar.deletedOneToast"):eP("sidebar.deletedManyToast",{count:r})];e.running.length>0&&i.push(eP("sidebar.keptRunningToast",{count:e.running.length})),n7(i.join(" \xb7 "))}finally{sn.current.delete(e)}}},[rp,rR,eu,n7,eP]),si=(0,i.useCallback)(e=>{let{ids:t}=ei(i9,e.key);sr(`project:${e.key}`,t,()=>i$(e.key))},[sr,i$,i9]),ss=(0,i.useCallback)(e=>{let t=null===e?null:CSS.escape(`archive:${e}`),n=null===t?null:nb.current?.querySelector(`[data-row-key="${t}"] .session-tree-group-toggle`);if(n&&n.getClientRects().length>0)return n;let r=iP.current;return r&&r.getClientRects().length>0?r:iN()},[iN]),sa=(0,i.useCallback)(e=>e.flatMap(e=>{let t=r5.get(e);return t?[t]:[]}),[r5]),so=(0,i.useCallback)((e,t)=>{nY({kind:"archive-group",project:e,anchor:t1(t,"end"),opener:t})},[]),sl=(0,i.useCallback)(e=>{nY(t=>t?.kind==="archive"?null:{kind:"archive",anchor:t1(e,"end"),opener:e})},[]),sd=(0,i.useCallback)(e=>{nY(t=>t?.kind==="archive"?{...t,askDelete:e}:t?.kind==="archive-group"?{...t,askDelete:void 0!==e}:t)},[]),sc=(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||G(r)===t.projectKey)&&U(r,e.uiState,e.runningIds)){if(void 0!==t.archivedBefore){let n=D(F(e.uiState,r.root.id)?.archivedAt);if(null===n||n>=t.archivedBefore)continue}n.push(r.root.id)}return n})(i9,"all"===e?{}:"old"===e?{archivedBefore:Date.now()-2592e6}:e),[i9]),su=(0,i.useCallback)(e=>{let t=sc(e);sr("string"==typeof e?`archive:${e}`:`archive-project:${e.projectKey}`,t,()=>"string"==typeof e?ss(null):ss(e.projectKey))},[sc,ss,sr]),sp=(0,i.useCallback)(e=>{nT(e),(0,eo.zY)(e)},[]),sh=(0,i.useCallback)(e=>{let t=ih.map(e=>e.project.key),n=nE.filter(e=>!t.includes(e));sp(e?n:[...n,...t])},[nE,ih,sp]),sm=(0,i.useCallback)((e,t)=>{let n=nE.includes(e);if(t)return void sh(n);let r=nE.filter(t=>t!==e);sp(n?r:[...r,e])},[nE,sp,sh]),sg=(0,i.useCallback)(e=>{nY(null),r2(eh(e,e2))},[e2,r2]),sf=(0,i.useCallback)(()=>nY(null),[]);(0,i.useEffect)(()=>{if(null!==nG)return;let e=ra.current;if(ra.current=null,!e?.isConnected)return;let t=document.activeElement;t&&t!==document.body||e.focus({preventScroll:!0})},[nG]);let sx=nM?ip:id.rows;(0,i.useEffect)(()=>{nG?.kind!=="row"||sx.some(e=>e.key===nG.row.key)||nY(null),nG?.kind!=="archive-group"||sx.some(e=>e.key===`archive:${nG.project.key}`)||nY(null)},[nG,sx]);let sb=nG?.kind==="row"?sx.find(e=>"session"===e.kind&&e.key===nG.row.key)??nG.row:null,sv=(0,i.useCallback)(e=>{r1(e.root)},[r1]),sy=(0,i.useCallback)(e=>{let t={...nj};for(let n of id.projects)delete t[n.key],t[n.key]=e(n);iC(t,null)},[nj,id.projects,iC]),sj=(0,i.useCallback)((e,t)=>{let n=im.get(e);if(!n)return;let r=!Z(n,il);if(t)return void sy(()=>r);let i={...nj};delete i[e],i[e]=r,iC(i,[e])},[nj,im,iC,sy,il]),sk=(0,i.useCallback)(e=>{let t=id.rows.find(t=>"group-more"===t.kind&&t.projectKey===e||"pinned-more"===t.kind&&e===W);(t?.kind==="group-more"||t?.kind==="pinned-more")&&nN(n=>{var r;return r=t.nextShown,{...n,[e]:Math.max(ee(n,e),Math.floor(r))}})},[id.rows]),sw=(0,i.useCallback)(e=>{nN(t=>et(t,e))},[]),sS=(0,i.useCallback)(e=>{rr.current=e,rs(e=>e+1),nu?iR(!1):iM("files")},[iR,nu,iM]),sC=nu?nH.open:"files"===np;(0,i.useEffect)(()=>{let e=rr.current;e&&sC&&(rr.current=null,"project-list"===e?tm.current?.openMenu("project"):"file-search"===e?document.getElementById("file-search-input")?.focus({preventScroll:!0}):tm.current?.button("project")?.focus({preventScroll:!0}))},[sC,ri]);let sN=e=>{let{heading:t,headingTitle:n,notes:i,count:s,onConfirm:a,onCancel:o}=e;return(0,r.jsxs)("div",{className:"sidebar-menu-question",children:[(0,r.jsx)("div",{className:"sidebar-menu-header",title:n,children:t}),i.map(e=>(0,r.jsx)("p",{className:"sidebar-menu-question-text",children:e},e)),(0,r.jsxs)("div",{className:"sidebar-menu-question-buttons",children:[(0,r.jsx)("button",{type:"button",className:"sidebar-menu-question-confirm",disabled:0===s,onClick:a,children:eP("sidebar.deleteCount",{count:s})}),!ez&&(0,r.jsx)("button",{type:"button",className:"sidebar-menu-question-cancel","data-sidebar-menu-autofocus":"",onClick:o,children:eP("sidebar.cancel")})]})]})},sI=(e,t)=>sN({heading:t?eP("sidebar.deleteArchivedInProjectHeading",{name:t.name}):eP("old"===e?"sidebar.deleteOldArchivedHeading":"sidebar.deleteAllArchivedHeading"),headingTitle:t?.root,notes:[eP("sidebar.deleteArchivedMessage")],count:sc(e).length,onConfirm:()=>su(e),onCancel:()=>sd(void 0)}),s$="",sE=null;if(nG?.kind==="row"&&sb)m=ta(sb.family.root),s$=eP("sidebar.sessionActions"),b=(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"}]})(sb.context,sb.status).map((e,t)=>{if("separator"===e.kind)return{type:"separator",id:`separator-${t}`};let n=eP(tJ[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)(ts.Gb,{});case"pin":return(0,r.jsx)(ts.ts,{});case"unpin":return(0,r.jsx)(ts.UT,{});case"rename":return(0,r.jsx)(ts.R2,{});case"fork":return(0,r.jsx)(ts.o5,{});case"share":return(0,r.jsx)(ts.li,{});case"copy-session-id":return(0,r.jsx)(ts.Td,{});case"mark-read":return(0,r.jsx)(ts.TA,{});case"mark-unread":return(0,r.jsx)(ts.Zy,{});case"archive":return(0,r.jsx)(ts.kb,{});case"unarchive":return(0,r.jsx)(ts.G2,{});case"delete":return(0,r.jsx)(ts.uc,{})}}(e.id),shortcut:e.shortcut,danger:"delete"===e.id,disabled:void 0!==e.disabledReason,disabledReason:"running"===e.disabledReason?eP("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":i6(i);break;case"pin":iB(i,!0);break;case"unpin":iB(i,!1);break;case"rename":iV(i);break;case"fork":i8(t);break;case"share":r?.(),nY(e=>e?.kind==="row"&&e.row.key===t.key?{...e,share:!0}:e);break;case"copy-session-id":(0,e3.D)(i.root.id).then(()=>n7(eP("sidebar.sessionIdCopied")),()=>{});break;case"mark-read":iH(i,!0);break;case"mark-unread":iH(i,!1);break;case"archive":iq(i);break;case"unarchive":iZ(i);break;case"delete":i0(i,n)}})(e.id,sb,n,r)}}}),nG.share&&(b=void 0,sE=(0,r.jsx)(tB,{sessionId:sb.family.root.id,onCopied:()=>n7(eP("share.copiedToast")),onStopped:()=>n7(eP("share.stoppedToast"))}),g=320);else if(nG?.kind==="group"){let e,t,i,a,o,l=im.get(nG.project.key)??nG.project;m=l.name,s$=eP("sidebar.projectActions",{name:l.name}),n=l,s=nG.olderCount,e=r9.countByProject.get(n.key)??0,t=ei(i9,n.key),i=es(id.projects,n.key,"up"),a=es(id.projects,n.key,"down"),o=(null===n.customName?["rename-project"]:["rename-project","reset-project-name"]).map(e=>"rename-project"===e?{type:"item",id:e,label:eP("sidebar.renameProject"),icon:(0,r.jsx)(ts.R2,{}),onSelect:()=>iG(n)}:{type:"item",id:e,label:eP("sidebar.resetProjectName"),icon:(0,r.jsx)(ts.G2,{}),onSelect:()=>{iE({action:"rename-project",projectKey:n.key,name:null})}}),b=[{type:"item",id:"pin-project",label:eP(n.pinned?"sidebar.unpinProject":"sidebar.pinProject"),icon:n.pinned?(0,r.jsx)(ts.UT,{}):(0,r.jsx)(ts.ts,{}),onSelect:()=>{iE({action:"pin-project",projectKey:n.key,root:n.root,pinned:!n.pinned})}},...o,{type:"item",id:"open-in-files",label:eP("sidebar.openInFilesTab"),icon:(0,r.jsx)(ts.sj,{}),onSelect:()=>{n.current||e5(n.root),sS("project-button")}},{type:"item",id:"open-new-tab",label:eP("sidebar.openInNewTab"),icon:(0,r.jsx)(ts.Gb,{}),shortcut:"T",onSelect:()=>(e=>{let{cwd:t}=eh(e,e2);window.open(`?cwd=${encodeURIComponent(t)}`,"_blank","noopener,noreferrer")})(n)},{type:"separator",id:"separator-layout"},{type:"item",id:"move-up",label:eP("sidebar.moveProjectUp"),icon:(0,r.jsx)(ts.zp,{className:"sidebar-icon-up"}),disabled:null===i,onSelect:()=>{i&&iT(n.key,i.anchorKey,i.position)}},{type:"item",id:"move-down",label:eP("sidebar.moveProjectDown"),icon:(0,r.jsx)(ts.zp,{className:"sidebar-icon-down"}),disabled:null===a,onSelect:()=>{a&&iT(n.key,a.anchorKey,a.position)}},{type:"item",id:"collapse-others",label:eP("sidebar.collapseOtherGroups"),icon:(0,r.jsx)(ts.zp,{}),disabled:id.projects.every(e=>Z(e,il)===(e.key===n.key)),onSelect:()=>sy(e=>e.key===n.key)},{type:"item",id:"expand-all",label:eP("sidebar.expandAllGroups"),icon:(0,r.jsx)(ts.zp,{className:"sidebar-icon-down"}),disabled:id.projects.every(e=>Z(e,il)),onSelect:()=>sy(()=>!0)},{type:"separator",id:"separator-sessions"},{type:"item",id:"archive-older",label:eP("sidebar.archiveOlderThanWeek",{count:s}),icon:(0,r.jsx)(ts.kb,{}),disabled:0===s,onSelect:()=>se(n)},{type:"item",id:"view-archived",label:eP("sidebar.viewArchived",{count:e}),icon:(0,r.jsx)(ts.kb,{}),disabled:0===e,onSelect:()=>iL(n.key)},{type:"item",id:"delete-all",label:eP("sidebar.deleteProjectSessions",{count:t.ids.length}),icon:(0,r.jsx)(ts.uc,{}),danger:!0,disabled:0===t.ids.length,onSelect:e=>{let{keepOpen:t}=e;t(),st(n.key,!0)}}],nG.askDelete&&(sE=(e=>{let{ids:t,running:n}=ei(i9,e.key);return sN({heading:eP("sidebar.deleteProjectSessionsHeading",{name:e.name}),headingTitle:e.root,notes:[eP("sidebar.deleteProjectSessionsMessage"),...n>0?[eP("sidebar.deleteProjectSessionsRunning",{count:n})]:[]],count:t.length,onConfirm:()=>si(e),onCancel:()=>st(e.key,!1)})})(l)),g=264}else if(nG?.kind==="archive-group"){let e,t=ih.find(e=>e.project.key===nG.project.key)?.project??nG.project;m=t.name,s$=eP("sidebar.archivedProjectActions",{name:t.name}),b=[{type:"item",id:"restore-all",label:eP("sidebar.restoreAllArchived",{count:(e=sc({projectKey:t.key})).length}),icon:(0,r.jsx)(ts.G2,{}),disabled:0===e.length,onSelect:()=>iK(sa(e))},{type:"separator",id:"separator-delete"},{type:"item",id:"delete-all",label:eP("sidebar.deleteAllArchived",{count:e.length}),icon:(0,r.jsx)(ts.uc,{}),danger:!0,disabled:0===e.length,onSelect:e=>{let{keepOpen:t}=e;t(),sd("all")}}],nG.askDelete&&(sE=sI({projectKey:t.key},t)),g=248}else if(nG?.kind==="archive"){let e,t,n;m=eP("sidebar.archived"),s$=eP("sidebar.archiveActions"),e=sc("all"),t=sc("old"),n=ih.filter(e=>!e.expanded).length,b=[{type:"item",id:"collapse-all",label:eP("sidebar.collapseAllGroups"),icon:(0,r.jsx)(ts.zp,{}),disabled:n===ih.length,onSelect:()=>sh(!1)},{type:"item",id:"expand-all",label:eP("sidebar.expandAllGroups"),icon:(0,r.jsx)(ts.zp,{className:"sidebar-icon-down"}),disabled:0===n,onSelect:()=>sh(!0)},{type:"separator",id:"separator-sessions"},{type:"item",id:"restore-all",label:eP("sidebar.restoreAllArchived",{count:e.length}),icon:(0,r.jsx)(ts.G2,{}),disabled:0===e.length,onSelect:()=>iK(sa(e))},{type:"item",id:"delete-old",label:eP("sidebar.deleteOldArchived",{count:t.length}),icon:(0,r.jsx)(ts.uc,{}),danger:!0,disabled:0===t.length,onSelect:e=>{let{keepOpen:t}=e;t(),sd("old")}},{type:"item",id:"delete-all",label:eP("sidebar.deleteAllArchived",{count:e.length}),icon:(0,r.jsx)(ts.uc,{}),danger:!0,disabled:0===e.length,onSelect:e=>{let{keepOpen:t}=e;t(),sd("all")}}],nG.askDelete&&(sE=sI(nG.askDelete,null)),g=280}let sT={layout:ez?"mobile":"desktop",loading:eG||!rm,error:e0,renamingRootId:nU,renamingProjectKey:nK,confirmDeleteRootId:nV,activeMenuRowKey:nG?.kind==="row"?nG.row.key:nG?.kind==="group"?`group:${nG.project.key}`:nG?.kind==="archive-group"?`archive:${nG.project.key}`:null,onSelectFamily:sv,onToggleGroup:sj,onShowMore:sk,onShowLess:sw,onTogglePinned:()=>{let e=!nI;n$(e),(0,eo.Lc)(e),e&&nN(e=>et(e,W))},onArchiveFamily:iq,onRestoreFamily:iZ,onOpenRowMenu:i3,onRowContextMenu:i5,onRenameCommit:(e,t)=>{iJ(e,t)},onRenameCancel:()=>nq(null),onRenameProjectCommit:iX,onRenameProjectCancel:()=>{nK&&iY(nK)},onDeleteConfirm:e=>{iQ(e)},onDeleteCancel:()=>{nJ(null),nV&&rp(()=>iI(nV))},onGroupNew:sg,onGroupMenu:i7,onPinEmptyGroup:e=>{iE({action:"pin-project",projectKey:e.key,root:e.root,pinned:!0}),rp(()=>i$(e.key))},onToggleArchiveGroup:sm,onArchiveGroupMenu:so,onOpenOtherProject:()=>{sS("project-list")},onOpenArchive:()=>iL(),onMoveGroup:iT},sM=e2??em??null,sR=sM&&tT>0?eP("sidebar.changedFiles",{count:tT}):void 0,sA=(0,i.useRef)(null),sL=!sM||0===tT;(0,i.useLayoutEffect)(()=>{let e=sA.current;if(sL&&e&&iW.current===e){var t,n;let r;t=document,n=iN(),(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}):eC(t,r)}},[sL,iN]);let sP=nu||"sessions"===np,sz=!nu&&"files"===np&&null!==sM,sO=(t=(nu?["below",eP("sidebar.new")]:["tabs",eP("sidebar.tabSessions"),eP("sidebar.tabFiles"),eP("sidebar.new"),sM&&tT>0?tT:"",np]).join("\n"),h=(0,i.useCallback)(()=>{let e=ry.current;if(e){for(let t of["0","1","2"])if(e.dataset.fit=t,e.scrollWidth<=e.clientWidth)return}},[ry]),(0,i.useLayoutEffect)(()=>{let e=ry.current;if(!e)return;h();let t=new ResizeObserver(h);return t.observe(e),()=>t.disconnect()},[ry,h,t]),h),sW=id.archivedCount,sF=nu?13:14,sD=(0,r.jsx)(tK,{onClick:()=>{sM&&ey?.(sM)},disabled:!sM||!ey,title:eP("terminal.open"),children:(0,r.jsx)(ts.k3,{size:sF})}),sB=(0,r.jsx)(tK,{onClick:()=>{rL().then(e=>{e&&nu&&iR(!1)})},disabled:!sM||rz,title:rz?eP(tH?.reason==="remote"?"sidebar.openInExplorerRemoteOnly":"sidebar.openInExplorerUnsupported"):rP,children:(0,r.jsx)(ts.sj,{size:sF})}),sH=(0,r.jsx)(tK,{onClick:()=>{nu&&nm&&iR(!1),nd.current?.openUploadPicker()},disabled:!sM||tk,title:eP("sidebar.uploadFilesTitle"),children:(0,r.jsx)(ts.JM,{size:sF})}),s_=(0,r.jsx)(tK,{onClick:()=>{e$?e$():tj(e=>e+1),tD(!0),nl.current&&clearTimeout(nl.current),nl.current=setTimeout(()=>tD(!1),2e3)},disabled:!sM,title:eP("sidebar.refreshExplorer"),done:tF,children:tF?(0,r.jsx)(ts.Sr,{size:sF}):(0,r.jsx)(ts.fN,{size:sF})}),sU=e=>(0,r.jsx)(tK,{onClick:()=>{let e=!tP;tz(e),(0,eo.qM)(e)},disabled:!sM,title:eP("sidebar.showIgnoredFiles"),pressed:tP,className:e,children:(0,r.jsx)(ts.bM,{size:sF})}),sq=(0,r.jsx)(tK,{ref:sA,onClick:()=>{if(nu&&nm){iR(!1),tL(!1);return}tL(e=>!e)},disabled:sL,title:eP("sidebar.changedFiles",{count:tT}),pressed:!sL&&!tA,children:(0,r.jsx)(ts.Vz,{size:sF})}),sK=(0,r.jsx)(tK,{onClick:()=>{sM&&eS?.(sM)},disabled:!sM||!eS,title:eP("sidebar.openGitGraph"),children:(0,r.jsx)(ts.WQ,{size:sF})});return(0,r.jsxs)("div",{ref:rT,className:`session-sidebar${nu?" is-files-below":""}${nu&&nm?" is-files-collapsed":""}${nu&&nH.moving?" is-files-folding":""}${n3?" has-toast":""}`,style:{"--sidebar-files-height":`${r$.width}px`},onFocus:e=>{iW.current=e.target},onBlur:e=>{(null!==e.relatedTarget||document.hasFocus())&&(e.currentTarget.contains(e.relatedTarget)||(iW.current=null))},children:[tt&&(0,r.jsx)(e4,{initialPath:tr,busy:tc,error:to,onCancel:()=>{let e="new-session"===tt?rl.current:null;ro.current=null,rl.current=null,tn(!1),td(null),e&&rp(()=>e.isConnected?e:null)},onSelect:e=>void rZ(e)}),(0,r.jsxs)("div",{ref:ry,className:"sidebar-header",children:[nu&&(0,r.jsx)(e7,{onWidthChange:sO}),!nu&&(0,r.jsxs)("div",{className:"sidebar-tabs-list",role:"tablist","aria-label":eP("sidebar.tabsLabel"),children:[(0,r.jsxs)("button",{ref:nf,type:"button",role:"tab",id:"session-sidebar-tab-sessions","aria-selected":"sessions"===np,"aria-controls":"session-sidebar-panel-sessions",tabIndex:"sessions"===np?0:-1,className:`sidebar-tab${"sessions"===np?" is-selected":""}`,onClick:()=>iM("sessions"),onKeyDown:iD,children:[(0,r.jsx)(ts.b1,{size:13,className:"sidebar-tab-icon"}),(0,r.jsx)("span",{className:"sidebar-tab-label",children:eP("sidebar.tabSessions")})]}),(0,r.jsxs)("button",{ref:nx,type:"button",role:"tab",id:"session-sidebar-tab-files","aria-selected":"files"===np,"aria-controls":"session-sidebar-panel-files",tabIndex:"files"===np?0:-1,title:sR,className:`sidebar-tab${"files"===np?" is-selected":""}`,onClick:()=>iM("files"),onKeyDown:iD,children:[(0,r.jsx)(ts.sj,{size:13,className:"sidebar-tab-icon"}),(0,r.jsx)("span",{className:"sidebar-tab-label",children:eP("sidebar.tabFiles")}),sM&&tT>0&&(0,r.jsx)("span",{className:"sidebar-tab-count","aria-hidden":"true",children:tT})]})]}),(0,r.jsx)("span",{className:"sidebar-header-spacer"}),(0,r.jsxs)("button",{type:"button",className:"sidebar-new-button",onClick:r8,disabled:!e2,title:e2?eP("sidebar.newSessionTitle",{path:e2}):eP("sidebar.selectProject"),children:[(0,r.jsx)(ts.c1,{size:12}),(0,r.jsx)("span",{className:"sidebar-new-label",children:eP("sidebar.new")})]}),(0,r.jsx)("button",{ref:rk,type:"button",onClick:()=>{if(sz)return void tC(e=>!e);if(!sP){iM("sessions"),tI(!0);return}tI(e=>!e)},title:sz?eP("sidebar.searchFiles"):eP("sidebar.toggleSessionSearch"),"aria-label":sz?eP("sidebar.searchFiles"):eP("sidebar.toggleSessionSearch"),"aria-expanded":sz?tS:tN,"aria-controls":sz?"file-search-input":"session-search-input",className:`sidebar-search-toggle${(sz?tS:tN)?" is-active":""}`,children:(0,r.jsx)(ts.WI,{size:16})})]}),(0,r.jsxs)("div",{ref:nb,id:"session-sidebar-panel-sessions",role:nu?"region":"tabpanel","aria-label":nu?eP("sidebar.tabSessions"):void 0,"aria-labelledby":nu?void 0:"session-sidebar-tab-sessions",hidden:!nu&&"sessions"!==np,className:"sidebar-panel sidebar-sessions-panel",onScrollCapture:iA,children:[tN&&(0,r.jsx)("div",{className:"sidebar-search",children:(0,r.jsx)("input",{id:"session-search-input",type:"search",autoFocus:!0,value:t$,maxLength:200,"aria-label":eP("sidebar.searchSessions"),placeholder:eP("sidebar.searchSessions"),onChange:e=>tE(e.target.value),onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.stopPropagation(),tE(""))},className:"sidebar-search-input"})}),(0,r.jsx)(tW,{open:tN,query:t$,selectedSessionId:y,onSelectSession:r1,archivedSessionIds:r9.ids,children:(0,r.jsxs)("div",{className:"sidebar-sessions-views",children:[(0,r.jsx)("div",{className:"sidebar-sessions-view",hidden:n_.mainHidden,inert:n_.mainInert,children:(0,r.jsx)(tl,{...sT,rows:id.rows,emptyLabel:eP("sidebar.noSessions"),reveal:nX,onRevealHandled:n1})}),n_.archiveMounted&&(0,r.jsxs)("div",{className:`sidebar-sessions-view sidebar-archive-view${n_.archiveClass?` ${n_.archiveClass}`:""}`,inert:n_.archiveInert,onAnimationEnd:e=>{e.target===e.currentTarget&&nW()},children:[(0,r.jsxs)("div",{className:"sidebar-archive-bar",children:[(0,r.jsxs)("button",{ref:iP,type:"button",className:"sidebar-archive-back",title:eP("sidebar.backToSessions"),"aria-label":`${eP("sidebar.backToSessions")}: ${eP("sidebar.archivedCount",{count:sW})}`,onClick:()=>nB(!1),children:[(0,r.jsx)(ts.zp,{size:13,className:"sidebar-icon-back"}),(0,r.jsx)("span",{children:eP("sidebar.archived")}),(0,r.jsxs)("span",{className:"sidebar-archive-count",children:["\xb7 ",sW]})]}),(0,r.jsx)("button",{type:"button",className:`sidebar-archive-menu-button${nG?.kind==="archive"?" is-active":""}`,title:eP("sidebar.archiveActions"),"aria-label":eP("sidebar.archiveActions"),"aria-haspopup":"menu","aria-expanded":nG?.kind==="archive",disabled:0===ih.length,onClick:e=>sl(e.currentTarget),children:(0,r.jsx)(ts.Z4,{size:13})})]}),(0,r.jsx)(tl,{...sT,rows:ip,emptyLabel:eP("sidebar.noArchived"),reveal:n2,onRevealHandled:n8})]})]})})]}),nu&&nH.open&&(0,r.jsx)("div",{...r$.separatorProps,"aria-controls":"session-sidebar-panel-files",className:`panel-resize-handle sidebar-files-resize-handle${r$.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar-files",title:`${eP("sidebar.resizeFiles")}: ${eP("sidebar.resizeFilesHint")}`}),(0,r.jsxs)("div",{ref:nv,id:"session-sidebar-panel-files",role:nu?"region":"tabpanel","aria-label":nu?eP("sidebar.tabFiles"):void 0,"aria-labelledby":nu?void 0:"session-sidebar-tab-files",hidden:!nu&&"files"!==np,className:"sidebar-panel sidebar-files-panel",onScrollCapture:iA,onTransitionEnd:e=>{e.target===e.currentTarget&&"height"===e.propertyName&&nP()},children:[nu&&(0,r.jsxs)("div",{className:"sidebar-files-section",children:[(0,r.jsxs)("button",{type:"button",className:"sidebar-files-section-toggle","aria-expanded":!nm,"aria-controls":"session-sidebar-files-body",title:sR,onClick:()=>iR(!nm),children:[(0,r.jsx)(ts.zp,{size:12,strokeWidth:3,className:`session-tree-chevron${nm?"":" is-open"}`}),(0,r.jsx)("span",{className:"sidebar-files-section-label",children:eP("sidebar.tabFiles")}),sR&&(0,r.jsxs)("span",{className:"sidebar-files-section-count","aria-hidden":"true",children:["\xb7 ",tT]})]}),(0,r.jsxs)("div",{className:"sidebar-files-keys",role:"group","aria-label":eP("sidebar.fileActions"),children:[sD,sB,sH,s_,sU(),sq,sK,(0,r.jsx)(tK,{onClick:()=>{if(nm){tC(!0),sS("file-search");return}tC(e=>!e)},disabled:!sM,title:eP("sidebar.searchFiles"),expanded:tS,controls:"file-search-input",children:(0,r.jsx)(ts.WI,{size:13})})]})]}),(0,r.jsxs)("div",{id:"session-sidebar-files-body",className:"sidebar-files-body",hidden:nu&&nH.bodyHidden,inert:nu&&nH.bodyInert,children:[(0,r.jsxs)("div",{className:"sidebar-files-head",children:[(0,r.jsx)(tO,{handleRef:tm,layout:nu?"row":"stacked",context:ij??{project:null,worktrees:null,currentWorktreePath:null,projects:iy},mobile:ez,label:eP("sidebar.projectAndWorktree"),placeholder:O&&!rW.current?"":eP("sidebar.selectProject"),homeDir:e9,projectActivity:r7,worktreeHint:ii,newWorktreeTitle:eP("sidebar.createWorktreeTitle"),onPick:r0,onUseDefaultDirectory:()=>{rJ()},onOpenFolder:rV,onRefreshWorktrees:rQ,onCreateWorktree:rY,onRemoveWorktree:rX}),!nu&&sM&&(0,r.jsxs)("div",{className:"sidebar-files-actions",role:"group","aria-label":eP("sidebar.fileActions"),children:[ey&&sD,sB,sH,s_,sU("sidebar-files-views-start"),sq,sK]})]}),sM&&rO&&(0,r.jsxs)("div",{role:"alert",className:"sidebar-files-error",children:[(0,r.jsx)("span",{className:"sidebar-files-error-text",children:rO}),(0,r.jsx)(e8.R,{onClick:()=>t4(null),title:eP("files.dismissError")})]}),(0,r.jsx)("div",{ref:rj,className:"sidebar-files-scroll scrollbar-subtle",children:sM&&(0,r.jsx)(e6.I,{ref:nd,cwd:sM,onOpenFile:ex??(()=>{}),refreshKey:ty,onAtMention:eE,onAtMentions:eT,onUploadBusyChange:tw,changesCollapsed:tA,onChangesCountChange:tR,fileSearchOpen:tS,onFileSearchOpenChange:tC,showHidden:tP})})]})]}),(0,r.jsx)(tM,{open:null!==nG,anchor:nG?.anchor??null,sheet:ez,ariaLabel:s$,title:m,items:b,cancelLabel:eP("sidebar.cancel"),focusCancel:null!==sE,onClose:sf,returnFocusTo:nG?.opener??null,width:g,children:sE}),(0,r.jsx)(tU,{toast:n3,onDismiss:()=>n5(null),dismissLabel:eP("sidebar.dismiss")})]})}var t4=n(5772);let t8=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,t6=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,t3=/\x1B_pi:c\x07/g;function t5(e){return e.replace(t3,"").replace(t8,"")}function t9(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(t6);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 t7(e,t){let n=t9(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function ne(e){return t9(e)[0]?.char}let nt=/[▀-▟]/,nn={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:""},nr={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"};var ni=n(48656),ns=n(19870),na=n(14667);function no(e,t){let n,r=t.shortWithArg??new Set,i=t.longWithArg??new Set,s=t.inPlace??new Set,a=[],o=!1,l=!1,d=e=>{t.targetDir&&(n=e)};for(let c=1;c<e.length;c++){let u=e[c],p=u.text;if(!u.quoted&&"--"===p){for(let t=c+1;t<e.length;t++)a.push(e[t].text);break}if(!u.quoted&&p.startsWith("--")){let r=p.indexOf("=");if(-1!==r){let e=p.slice(0,r);s.has(e)?o=!0:t.expression&&("--expression"===e||"--file"===e)?l=!0:"--target-directory"===e&&t.targetDir&&(n=p.slice(r+1));continue}if(s.has(p)){o=!0;continue}t.expression&&("--expression"===p||"--file"===p)&&(l=!0),i.has(p)&&c+1<e.length&&("--target-directory"===p&&d(e[c+1].text),c+=1);continue}if(!u.quoted&&p.startsWith("-")&&p.length>1&&!/^\d/.test(p.slice(1))){let n=p.slice(1);for(let i=0;i<n.length;i++){let a=`-${n[i]}`;if(s.has(a)&&(o=!0),t.expression&&("-e"===a||"-f"===a)&&(l=!0),r.has(a)){let t=n.slice(i+1);t.length>0?"-t"===a&&d(t):c+1<e.length&&("-t"===a&&d(e[c+1].text),c+=1);break}}continue}a.push(p)}return{operands:a,targetDirectory:n,inPlace:o,expressionSeen:l}}var nl=n(83236),nd=n(67803);function nc(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}function nu(e){return e?e.map(e=>e.newPath).filter(e=>"string"==typeof e&&e.length>0):[]}function np(e,t,n){let r=new Set,i=[],s=e=>{let t=(0,ns.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,na.V4)(a)||(0,na.iG)(a))&&!(0,na.aP)(n.toolName)&&!(0,na.Y2)(n.toolName)&&n.toolName!==nl.sp))continue;let r=t?.get(n.toolCallId);if(r&&!r.isError){if((0,na.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,nd.IN)(e).matchAll(/^\*\*\* Delete File: (.+)$/gm)){let e=(t[1]??"").trim();e&&n.add(e)}return n}(e,n),i=(0,nd.dc)(n);if(i)return i.filter(e=>!r.has(e));if((0,nd.FK)(n))return[];if(n&&"object"==typeof n&&!Array.isArray(n)){let e=nu((0,nd.ND)(n.preview));if(e.length>0)return e}return nu((0,nd.oC)((0,nd.IN)(e)))}(n.input,r);else if((0,na.Y2)(n.toolName)){let t=function(e){if(!e)return null;let t=e.command??e.cmd??e.script;return"string"==typeof t&&t.length>0?t:null}(n.input);e=t?function(e){if("string"!=typeof e||0===e.length||e.length>2e5)return[];let t=new Set,n=[];for(let r of function(e){let t=[],n=[],r="",i=!1,s="",a=()=>{(r.length>0||i)&&n.push({text:r,quoted:i}),r="",i=!1},o=()=>{a(),n.length>0&&t.push(n),n=[]};for(let t=0;t<e.length;t++){let n=e[t];if(s){if("\\"===n&&'"'===s&&e[t+1]){r+=e[t+1],t+=1;continue}if(n===s){s="";continue}r+=n;continue}if("'"===n||'"'===n){s=n,i=!0;continue}if("\\"===n){e[t+1]&&(r+=e[t+1],i=i||/[^\w./-]/.test(e[t+1]),t+=1);continue}if(";"===n||"|"===n||"&"===n||"\n"===n){("|"===e[t+1]||"&"===e[t+1])&&(t+=1),o();continue}if("#"===n&&0===r.length){let n=e.indexOf("\n",t);t=-1===n?e.length-1:n-1,o();continue}if(/\s/.test(n)){a();continue}r+=n}return o(),t}(e)){let e=function(e){let t=function(e){let t=0;for(;t<e.length;){let n=e[t].text,r=n.slice(n.lastIndexOf("/")+1);if("sudo"===r||"nohup"===r||"env"===r||"command"===r||"exec"===r||/^[\w]+=/.test(n)&&t+1<e.length){t+=1;continue}break}return e.slice(t)}(e);if(0===t.length)return null;let n=t[0].text,r=n.slice(n.lastIndexOf("/")+1),i=[];for(let e=0;e<t.length;e++){let n=t[e];if(n.quoted)continue;if(">"===n.text||">>"===n.text||"&>"===n.text||"&>>"===n.text){let n=t[e+1];n&&!n.text.startsWith("&")&&i.push(n.text),e+=1;continue}let r=n.text.match(/^(?:\d*>>|\d*>|&>>|&>|>&)(.+)$/);if(r){let e=r[1];e.startsWith("&")||i.push(e);continue}}let s=[];switch(r){case"tee":s=no(t,{}).operands;break;case"touch":s=no(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]}(no(t,{shortWithArg:new Set(["-t","-S","-Z"]),longWithArg:new Set(["--target-directory","--suffix","--context"]),targetDir:!0}));break;case"sed":{let e=no(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=no(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===nl.sp?function(e){let{calls:t}=(0,nl.or)(e?.details),n=[];for(let e of t){if("ok"!==e.status||!(0,na.V4)(e.name)&&!(0,na.iG)(e.name))continue;let t=function(e){try{let t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return nc(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):[nc(n.input)];for(let t of e)t&&s(t)}}return i}var nh=n(11316),nm=n(6483);function ng(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,nm.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 nf(e,t){let n,r=[],i=null;for(let s=0;s<t;s++){let t=new URLSearchParams({tail:"1000",deferThinking:"",deferMedia:""});n&&t.set("before",n);let s=await fetch(`/api/sessions/${encodeURIComponent(e)}/context?${t}`,{cache:"no-store"});if(!s.ok)throw Error(`context ${s.status}`);let a=await s.json();i??=a.cwd??null;let o=a.context??{},l=Array.isArray(o.messages)?o.messages:[];if(r.unshift(...l),!o.hasMore||!o.oldestEntryId)break;n=o.oldestEntryId}return{messages:r,cwd:i}}let nx=new Map,nb=new Map;function nv(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={...e,content:t};return n.omitUsage&&(r.usage=void 0),r}var ny=n(56038);function nj(e){let t=e.trim().split("\n").map(e=>`> ${e}`).join("\n");return`${t}
3
-
4
- `}function nk(e){return!e.trim()||e.endsWith("\n\n")?"":e.endsWith("\n")?"\n":"\n\n"}var nw=n(2836),nS=n(15855),nC=n(2849);function nN(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 nI=new Map;function n$(e){return`parked-new:${e}`}function nE(e){return{value:e.value,images:e.images.map(e=>({...e}))}}function nT(e){return!e.value&&0===e.images.length}function nM(e){let t=nI.get(e);return t?nE(t):null}function nR(e,t){nT(t)?nI.delete(e):nI.set(e,nE(t))}function nA(e){nI.delete(e)}function nL(e,t){return e.trim()?t.trim()?`${e}
5
-
6
- ${t}`:e:t}function nP(e,t,n,r){let i=[...t??[],...r].filter(nN).slice(0,10).map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});return{value:nL(e,n),images:i}}function nz(e,t,n){let r=nM(e)??{value:"",images:[]},i=nP(t,n,r.value,r.images);return nR(e,i),i}function nO(e,t,n){if(e===t)return n?nE(n):nM(t);let r=nM(e),i=n&&!nT(n)?nE(n):r??(n?nE(n):null),s=nM(t);if(nA(e),!i)return s;let a=s?nP(s.value,s.images,i.value,i.images):i;return nR(t,a),nE(a)}var nW=n(3099);let nF=/^([ \t]*)([-*+])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,nD=/^([ \t]*)(\d{1,9})([.)])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,nB=/^([ \t]*)(\d{1,3})(、)([ \t]*)/,nH=/^[ \t]*([-*_])(?:[ \t]*\1){2,}[ \t]*$/,n_=/^[ \t]{0,3}(`{3,}|~{3,})/;function nU(e){return"mcp"===e.name&&e.sourceInfo?.path==="builtin:mcp"}function nq(e){return"/mcp"===e.trim()}var nK=n(30527),nZ=n(8436);let nV="pi-enter-send-mode",nJ="enter",nG=null,nY=new Set;function nX(){return null===nG&&(nG=function(){try{let e=window.localStorage.getItem(nV);return"ctrlEnter"===e?"ctrlEnter":"enter"}catch{return nJ}}()),nG}function nQ(e){return nY.add(e),()=>{nY.delete(e)}}function n0(e){nG=e;try{window.localStorage.setItem(nV,e)}catch{}nY.forEach(e=>e())}function n1(){return(0,i.useSyncExternalStore)(nQ,nX,()=>nJ)}var n2=n(23584),n4=n(74761);function n8(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 n6(e){let{active:t,onSelect:n,star:s,gutter:a=!!s,children:o}=e,l=(0,eF.a)(),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=!!(s&&!s.isDefault),m=h&&(d||u||l);return(0,r.jsxs)("div",{onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),onFocus:()=>p(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||p(!1)},style:{position:"relative",background:t?"var(--bg-selected)":d?"var(--bg-hover)":"transparent",transition:"background 0.1s"},children:[(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":t,onClick:n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minWidth:0,padding:a?"7px 36px 7px 12px":"7px 12px",border:"none",background:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:t?600:400,textAlign:"left",whiteSpace:"nowrap"},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),o]}),s?.isDefault&&(0,r.jsx)("span",{role:"img","aria-label":s.defaultLabel,title:s.defaultLabel,style:{position:"absolute",top:"50%",right:6,transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,color:"var(--text-dim)"},children:(0,r.jsx)(n8,{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)(n8,{filled:!1,size:12})})]})}function n3(e){var t;let n,s,a,o,l,d,c,u,p,h,m,{options:g,value:f,onChange:x,onReselect:b,onClear:v,emptyLabel:y,selectedLabel:j,disabled:k=!1,busy:w=!1,isAutoSelection:S=!1,ariaLabel:C,variant:N="toolbar",placement:I="up",defaultValue:$,onSetDefault:E,allOptions:T,onShowAll:M}=e,{t:R}=(0,eW.s)(),A=(0,eF.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=k||w,q=H?T:g,K=(t=q??[],(n=D.trim().toLocaleLowerCase())?t.filter(e=>`${e.name} ${e.providerName??""} ${e.modelId} ${e.provider}/${e.modelId}`.toLocaleLowerCase().includes(n)):t),Z=!!M||g.length>8,V=(e,t)=>e?.find(e=>e.modelId===t.modelId&&e.provider===t.provider),J=()=>{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}(K),Y=j??(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,o=window.visualViewport?.width??window.innerWidth,d=(l=Math.min(W.top-6,s+a-8))-s-8,c=s+a-W.bottom-6-8,p=Math.max(120,Math.min((u="up"===I||d>c)?d:c,.6*a)),h=u?{top:l,transform:"translateY(-100%)"}:{top:W.bottom+6},m=A?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:W.left,width:"max-content",minWidth:W.width,maxWidth:Math.max(W.width,o-W.left-8)},(0,r.jsxs)("div",{ref:P,role:"listbox","aria-label":C,style:{position:"fixed",...h,...m,zIndex:500,display:"flex",flexDirection:"column",maxHeight:p,overflow:"hidden",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:u?"0 -4px 16px rgba(0,0,0,0.10)":"0 4px 16px rgba(0,0,0,0.10)"},children:[M&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px 0",fontSize:11},children:[[!1,!0].map(e=>(0,r.jsx)("button",{type:"button","aria-pressed":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)(n6,{active:!f,gutter:!!E,onSelect:()=>{O(!1),B(""),v()},children:(0,r.jsx)(n5,{label:y??R("i18n.default")})}),0===G.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:q?D.trim()?R("chat.noMatchingModels"):R("chat.noAvailableModels"):R("agents.modelsLoading")}):G.map((e,t)=>(0,r.jsxs)("div",{children:[G.length>1&&(0,r.jsx)("div",{title:e.providerName===e.provider?void 0:e.provider,style:{padding:"6px 12px 4px",borderTop:t>0||v?"1px solid var(--border)":"none",color:"var(--text-dim)",fontSize:10,fontWeight:600,letterSpacing:0,textTransform:e.providerName===e.provider?"uppercase":"none"},children:e.providerName}),e.options.map(e=>(0,r.jsx)(n6,{active:e.modelId===f?.modelId&&e.provider===f?.provider,onSelect:()=>{let t;return t=e.modelId===f?.modelId&&e.provider===f?.provider,void(O(!1),B(""),!t||S?x(e.provider,e.modelId):b?.(e.provider,e.modelId))},star:E&&(!H||V(g,e))?{isDefault:e.modelId===$?.modelId&&e.provider===$?.provider,saveLabel:R("chat.saveDefaultModel"),defaultLabel:R("chat.defaultModel"),onSave:()=>{O(!1),B(""),E?.(e.provider,e.modelId)}}:void 0,children:(0,r.jsx)(n5,{label:e.name})},`${e.provider}:${e.modelId}`))]},e.provider))]})]}))]})}function n5(e){let{label:t}=e;return(0,r.jsx)("span",{title:t,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})}let n9=["configured","chat-only","read-only","default","full"],n7={configured:"configured","chat-only":"none","read-only":"read-only",default:"default",full:"full"},re=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function rt(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 rr(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 ri(e){e.style.height="auto",e.style.height=`${e.value?Math.min(e.scrollHeight,200):e.clientHeight}px`,e.style.overflowY=e.value&&e.scrollHeight>e.clientHeight?"auto":"hidden"}function rs(e,t){let n=null,r=()=>{n=null,t(function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8;return Math.max(0,Math.floor(e-t-n))}(e.getBoundingClientRect().bottom,function(e){let t=window.visualViewport?.offsetTop??0;for(let n=e.parentElement;n;n=n.parentElement){let e=window.getComputedStyle(n).overflowY;("auto"===e||"scroll"===e||"hidden"===e||"clip"===e)&&(t=Math.max(t,n.getBoundingClientRect().top+n.clientTop))}return t}(e)))},i=()=>{null!==n&&cancelAnimationFrame(n),n=requestAnimationFrame(r)};r();let s=e.parentElement,a=s?.parentElement,o="u">typeof ResizeObserver&&s?new ResizeObserver(i):null;s&&o?.observe(s),a&&o?.observe(a);let l=window.visualViewport;return l?.addEventListener("resize",i),l?.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("scroll",i,!0),()=>{o?.disconnect(),l?.removeEventListener("resize",i),l?.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("scroll",i,!0),null!==n&&cancelAnimationFrame(n)}}let ra=["auto","off","minimal","low","medium","high","xhigh","max"],ro={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 rl(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let rd=[{name:"compact",description:"chat.commandCompact",source:"builtin"},{name:"auto-compact",description:"chat.commandAutoCompact",source:"builtin"},{name:"reload",description:"chat.commandReload",source:"builtin"},{name:"name",description:"chat.commandName",source:"builtin"},{name:"session",description:"chat.commandSession",source:"builtin",availableWhileStreaming:!0},{name:"copy",description:"chat.commandCopy",source:"builtin",availableWhileStreaming:!0},{name:"clone",description:"chat.commandClone",source:"builtin"},{name:"side",description:"chat.commandSide",source:"builtin",availableWhileStreaming:!0}];function rc(e){return function(e){let t=e.trim().match(/^\/([^\s]+)(?:\s|$)/);if(t)return rd.find(e=>e.name===t[1])}(e)?.availableWhileStreaming===!0}let ru=["builtin","extension","prompt","skill"],rp={builtin:"chat.builtIn",extension:"chat.extensions",prompt:"chat.prompts",skill:"chat.skills"},rh={builtin:0,extension:1,prompt:2,skill:3};function rm(e,t){return"builtin"===e.source?t(e.description):e.description??""}function rg(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function rf(e){return{data:e.data,mimeType:e.mimeType}}function rx(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function rb(e){return(e??[]).filter(nN).slice(0,10).map(rx)}function rv(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function ry(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 rj(e){let{tone:t,title:n,body:i,onClose:s}=e,{t:a}=(0,eW.s)(),o="error"===t?"239,68,68":"234,179,8";return(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid rgba(${o},0.3)`,borderRadius:6,background:`rgba(${o},0.07)`,color:`rgb(${o})`,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:n}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:i})]}),s&&(0,r.jsx)("button",{type:"button",onClick:s,"aria-label":a("sidebar.dismiss"),style:{flexShrink:0,background:"none",border:"none",padding:"0 2px",cursor:"pointer",color:"inherit",opacity:.7,fontSize:13,lineHeight:1},children:"\xd7"})]})}function rk(e){let{cwd:t}=e,{t:n}=(0,eW.s)();return t?(0,r.jsx)(rj,{tone:"error",title:n("chat.cwdMissingTitle"),body:n("chat.cwdMissingBody",{cwd:t})}):null}function rw(e){let{error:t}=e,{t:n}=(0,eW.s)();return t?(0,r.jsx)(rj,{tone:"error",title:n("chat.modelError"),body:t}):null}function rS(e){let{warnings:t}=e,{t:n}=(0,eW.s)();return t&&0!==t.length?(0,r.jsx)(rj,{tone:"warning",title:n(t.length>1?"chat.modelScopeWarnings":"chat.modelScopeWarning"),body:t.join("\n")}):null}let rC=(0,i.memo)((0,i.forwardRef)(function(e,t){let n,s,a,o,l,{onSend:d,onAbort:c,onSteer:u,onSideChat:p,onFollowUp:h,isStreaming:m,model:g,isAutoModelSelection:f,modelNames:x,modelList:b,modelError:v,missingCwd:y,modelScopeWarnings:j,allModelList:k,onLoadAllModels:w,onModelChange:S,modelSwitching:C,defaultModel:N,onSetDefaultModel:I,onCompact:$,onAbortCompaction:E,isCompacting:T,compactError:M,onDismissCompactError:R,compactResult:A,toolPreset:L,onToolPresetChange:P,thinkingLevel:z,isAutoThinkingSelection:O=!1,onThinkingLevelChange:W,availableThinkingLevels:F,thinkingLevelMap:D,savedDefaultThinkingLevel:B,onSetDefaultThinkingLevel:H,retryInfo:_,queuedMessages:U,inputHistory:q=[],onRecallQueue:K,slashCommands:Z,slashCommandsLoading:V,onLoadSlashCommands:J,onBuiltinCommand:G,soundEnabled:Y,onSoundToggle:X,onAudioUnlock:Q,onPromptWithStreamingBehavior:ee,draftKey:et,cwd:en,onAttachFiles:er,compact:ei=!1}=e,{t:es}=(0,eW.s)(),{fontSize:ea}=(0,n2.Uh)(),{ui:eo,uiWeight:el}=(0,n4.VE)(),ed=(0,eF.a)(),ec=ed?44:32,eu=n1(),[ep,eh]=(0,i.useState)(()=>et?nM(et)?.value??"":""),[em,eg]=(0,i.useState)(!1),[ef,ex]=(0,i.useState)(!1),[eb,ev]=(0,i.useState)(!1),[ey,ej]=(0,i.useState)(()=>et?rb(nM(et)?.images):[]),ek=ep.trimStart(),ew=0===ey.length&&ek.startsWith("!"),eS=ew&&ek.startsWith("!!"),[eC,eN]=(0,i.useState)(!1),[eI,e$]=(0,i.useState)(0),[eE,eT]=(0,i.useState)(null),[eM,eR]=(0,i.useState)(null),[eA,eL]=(0,i.useState)(!1),[eP,ez]=(0,i.useState)(null),[eO,eD]=(0,i.useState)(0),[eB,eH]=(0,i.useState)(!1),[e_,eU]=(0,i.useState)(!1),[eq,eK]=(0,i.useState)(0),[eZ,eV]=(0,i.useState)(!1),eJ=(0,i.useRef)(!1),[eG,eY]=(0,i.useState)(null),[eX,eQ]=(0,i.useState)(!1),[e0,e1]=(0,i.useState)(null),[e2,e4]=(0,i.useState)(null),e6=en&&e2?.cwd===en?e2.values:{},e3=(0,i.useRef)(null),e5=(0,i.useRef)(null),e9=(0,i.useRef)(null),e7=(0,i.useRef)(null),te=(0,i.useRef)(null),tt=(0,i.useRef)(null),tn=(0,i.useRef)(!1),tr=(0,i.useRef)(0),ti=(0,i.useRef)(null),ts=(0,i.useRef)(!1),ta=(0,i.useRef)(null),to=(0,i.useRef)([]),tl=(0,i.useRef)(null),td=(0,i.useRef)([]),tc=(0,i.useRef)([]),tu=(0,i.useRef)(null),tp=(0,i.useRef)(null),th=(0,i.useRef)(et),tm=(0,i.useRef)(ep),tg=(0,i.useRef)(ey),tf=(0,i.useRef)(0);tm.current=ep,tg.current=ey,(0,i.useImperativeHandle)(t,()=>({insertIfEmpty(e){let t=e3.current;(t?t.value:ep).trim()||(tm.current=e,eh(e),eR(null),requestAnimationFrame(()=>{t&&(t.focus(),ri(t))}))},replaceMessage(e){var t,n,r;let i=e3.current;if(t=i?i.value:ep,n=tg.current.length,r=tf.current,t.trim()||0!==n||0!==r)return;let s="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),a=rb("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 nN(r)?[r]:[]}));tm.current=s,tg.current=a,eh(s),eR(null),eU(!1),ej(e=>(e.forEach(rv),a)),requestAnimationFrame(()=>{i&&(i.focus(),ri(i))})},prependText(e){if(!e.trim())return;let t=e3.current,n=[e,t?t.value:ep].filter(e=>e.trim()).join("\n\n");tm.current=n,eh(n),eR(null),requestAnimationFrame(()=>{t&&(t.focus(),t.setSelectionRange(n.length,n.length),ri(t))})},rekeyDraft(e,t){if(e===t)return;if(th.current!==e)return void nO(e,t);let n={value:tm.current,images:tg.current.map(rf)},r=nO(e,t,n)??{value:"",images:[]},i=r.value===n.value&&r.images.length===n.images.length&&r.images.every((e,t)=>e.data===n.images[t]?.data&&e.mimeType===n.images[t]?.mimeType);if(th.current=t,i)return;let s=rb(r.images);tm.current=r.value,tg.current=s,eh(r.value),ej(e=>(e.forEach(rv),s)),eR(null),eU(!1)},restoreSubmission(e,t,n){if(!e.trim()&&!t?.length)return;let r=th.current,i=n??r,s=i===r,a=!s&&i?nM(i):null,o=nP(e,t,s?tm.current:a?.value??"",s?tg.current.map(rf):a?.images??[]);if(i&&nR(i,o),!s)return;let l=t?.length?[...rb(t).slice(0,Math.max(0,10-tg.current.length)),...tg.current].slice(0,10):tg.current;tm.current=o.value,tg.current=l,eh(t=>{let n=nL(e,t);return tm.current=n,n}),eR(null),eU(!1),t?.length&&ej(e=>{let n=Math.max(0,10-e.length),r=rb(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tg.current=i,i}),requestAnimationFrame(()=>{let e=e3.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),ri(e))})},focus(){let e=e3.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length))},insertText(e){let t=e3.current;if(!t)return void eh(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n);rr(t,n,r,(i.length>0&&!i.endsWith(" ")?" ":"")+e),eR(null)},insertQuote(e){let t=e3.current;if(!t)return void eh(t=>t+nk(t)+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length;rr(t,n,r,nk(t.value.slice(0,n))+e),eR(null)},addImages(e){tx(e)}}));let tx=(0,i.useCallback)(async e=>{if(ei)return;let t=Math.max(0,10-tg.current.length-tf.current),n=e.filter(e=>e.type.startsWith("image/")&&e.size<=0xa00000).slice(0,t);if(n.length){tf.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)}}));ej(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(rv);let r=[...t,...n];return tg.current=r,r})}finally{tf.current-=n.length}}},[ei]),tb=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",er?er(t):tx(t)},[er,tx]),tv=(0,i.useCallback)(e=>{ej(t=>{let n=[...t],[r]=n.splice(e,1);return r&&rv(r),tg.current=n,n})},[]),ty=(0,i.useCallback)(()=>{tg.current=[],ej(e=>(e.forEach(rv),[]))},[]),tj=(0,i.useCallback)(()=>{tm.current="",eh(""),eR(null),eU(!1),et&&nA(et),th.current&&th.current!==et&&nA(th.current),ty(),e3.current&&(e3.current.style.height="auto")},[ty,et]);(0,i.useEffect)(()=>{et&&th.current===et&&nR(et,{value:ep,images:ey.map(rf)})},[ey,et,ep]),(0,i.useEffect)(()=>{let e=th.current;if(e===et)return;e&&nR(e,{value:tm.current,images:tg.current.map(rf)});let t=et?nM(et):null;th.current=et;let n=t?.value??"",r=rb(t?.images);tm.current=n,tg.current=r,eh(n),eR(null),eU(!1),ej(e=>(e.forEach(rv),r))},[et]);let tk=(0,i.useCallback)(()=>{let e=e3.current;e&&(e.style.height="auto",e.value?ri(e):e.style.overflowY="hidden")},[]);(0,i.useLayoutEffect)(tk,[ep,ea,eo,el,tk]),(0,i.useEffect)(()=>{let e=e3.current;if(!e)return;let t=-1,n=new ResizeObserver(e=>{let[n]=e;n.contentRect.width!==t&&(t=n.contentRect.width,tk())});return n.observe(e),()=>n.disconnect()},[tk]),(0,i.useEffect)(()=>{let e=e3.current;if(!e)return;let t=t=>{if("insertLineBreak"!==t.inputType||t.isComposing)return;let n=function(e,t,n){let r;if(t!==n)return null;let i=e.lastIndexOf("\n",t-1)+1,s=e.indexOf("\n",t),a=-1===s?e.length:s,o=e.slice(i,a),l=function(e){if(nH.test(e))return null;let t=nF.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=nD.exec(e)??nB.exec(e);return n?{indent:n[1],marker:"",number:n[2],delimiter:n[3],spacing:n[4],task:void 0!==n[5],length:n[0].length}:null}(o);return!l||t-i<l.length||function(e){let t=null;for(let n of e.split("\n")){let e=n_.exec(n)?.[1];e&&(null===t?t=e:e[0]===t[0]&&e.length>=t.length&&n.trim()===e&&(t=null))}return null!==t}(e.slice(0,i))?null:""===o.slice(l.length).trim()?{start:i,end:a,text:""}:{start:t,end:t,text:`
7
- ${r=null===l.number?l.marker:`${String(Number(l.number)+1).padStart(l.number.length,"0")}${l.delimiter}`,`${l.indent}${r}${l.spacing}${l.task?"[ ] ":""}`}`}}(e.value,e.selectionStart,e.selectionEnd);n&&(t.preventDefault(),e.setSelectionRange(n.start,n.end),document.execCommand(n.text?"insertText":"delete",!1,n.text))};return e.addEventListener("beforeinput",t),()=>e.removeEventListener("beforeinput",t)},[]),(0,i.useEffect)(()=>()=>{tg.current.forEach(rv)},[]);let tw=(0,i.useCallback)(async e=>{if(ey.length||!e.startsWith("/")||!G)return!1;if(eJ.current)return!0;eJ.current=!0,eV(!0);try{var t,n;let r=await G(e);if(!r.handled)return!1;return r.error||(t=tm.current,n=tg.current.length,0!==n||t.trim()!==e)||tj(),!0}finally{eJ.current=!1,eV(!1)}},[ey.length,tj,G]),tS=(0,i.useCallback)(async()=>{var e;let t=ep.trim();(t||ey.length)&&(Q?.(),(!m||rc(e=t)||nq(e))&&await tw(t)||m||(tj(),d(t,ey.length?ey:void 0)))},[ep,ey,m,tw,d,tj,Q]),tC=!ei&&ep.startsWith("/")&&!/\s/.test(ep.slice(1))?ep.slice(1).toLowerCase():null,tN=(()=>{var e;let t,n;return null===tC?[]:(e=[...m?rd.filter(e=>e.availableWhileStreaming):rd,...Z??[]],((n=(t=e.map(e=>{let t,n;return{command:e,rank:(t=e.name.toLowerCase(),(n="skill"===e.source&&t.startsWith("skill:")?t.slice(6):t)===tC||t===tC?0:n.startsWith(tC)||t.startsWith(tC)?1:t.includes(tC)?2:3)}})).filter(e=>{let{rank:t}=e;return t<3})).length>0?n:t.filter(e=>{let{command:t}=e;return rm(t,es).toLowerCase().includes(tC)})).sort((e,t)=>e.rank-t.rank||rh[e.command.source]-rh[t.command.source]||re.compare(e.command.name,t.command.name)).map(e=>{let{command:t}=e;return t}))})(),{commands:tI,groups:t$}=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",r=0,i=ru.map(i=>{let s=e.filter(e=>e.source===i),a="skill"!==i||n?s:[...s.filter(e=>!rg(e,t)),...s.filter(e=>rg(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}}(tN,e6,tC??""),tE=1===tN.length?es(tC?"chat.match":"chat.command"):es(tC?"chat.matches":"chat.commands",{count:tN.length}),tT=!!ep.trim()||ey.length>0,tM=ei||ed&&m,tR=ey.length>0&&!function(e,t){if(!e)return!0;let n=t?.find(t=>t.provider===e.provider&&t.id===e.modelId);return!n||!n.input||n.input.includes("image")}(g,b)&&!eB;(0,i.useEffect)(()=>{0===ey.length&&eH(!1)},[ey.length]);let tA=(0,i.useCallback)((e,t)=>{if(!en)return void eR(null);let n=t??e.length;eR((0,nW.RO)(e.slice(0,n)))},[en]),tL=eM?.query??null,tP=i.useMemo(()=>null!==tL&&eG&&eG.cwd===en?(0,nW.R7)(eG.entries,tL):[],[tL,eG,en]),tz=!!(tL&&eG?.truncated&&eG.cwd===en);(0,i.useEffect)(()=>{if(!tz||!en||!tL)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(en)}&q=${encodeURIComponent(tL)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>e1({cwd:en,query:tL,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tz,tL,en]);let tO=tz&&null!==e0&&e0.cwd===en&&e0.query===tL,tW=tO?e0.matches:tP,tF=null===eM?null:`${eM.start}:${+!!eM.quoted}:${eM.query}`;(0,i.useEffect)(()=>{if(null===tF){eL(!1),eD(0);return}eL(!0),eD(0)},[tF]);let tD=null!==eM;(0,i.useEffect)(()=>{if(!tD||!en)return;let e=tu.current;e&&e.cwd===en&&Date.now()-e.fetchedAt<1e4||tp.current===en||(tp.current=en,eQ(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(en)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{eY({cwd:en,entries:(0,nW.Yh)(e.files??[]),truncated:!!e.truncated}),tu.current={cwd:en,fetchedAt:Date.now()}}).catch(()=>{tu.current=null}).finally(()=>{tp.current=null,eQ(!1)}))},[tD,en]);let tB=(0,i.useCallback)(e=>{if(!eM)return;let t=e3.current;if(!t)return;let n=t.selectionStart??t.value.length,r=n+(eM.quoted&&'"'===t.value[n]?1:0),i=(0,nW.W)(e.path,e.isDir,eM.quoted),s=eM.start+i.cursorOffset;rr(t,eM.start,r,i.text,i.cursorOffset),eR((0,nW.RO)(t.value.slice(0,s)))},[eM]);(0,i.useEffect)(()=>{eO>=tW.length&&eD(Math.max(0,tW.length-1))},[tW.length,eO]),(0,i.useEffect)(()=>{td.current.length=tW.length},[tW.length]),(0,i.useEffect)(()=>{eA&&td.current[eO]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eO,eA]),(0,i.useEffect)(()=>{eq>=q.length&&eK(Math.max(0,q.length-1))},[q.length,eq]),(0,i.useEffect)(()=>{tc.current.length=q.length},[q.length]),(0,i.useEffect)(()=>{e_&&tc.current[eq]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eq,e_]);let tH=(0,i.useCallback)(e=>{eh(e),eU(!1),eK(0),eR(null),requestAnimationFrame(()=>{let t=e3.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),ri(t))})},[]),t_=(0,i.useCallback)(e=>{let t=`/${e.name} `;eh(t),eN(!1),e$(0),requestAnimationFrame(()=>{let e=e3.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),ri(e))})},[]),tU=(0,i.useCallback)(()=>{let e=ep.trim();e&&!ey.length&&p&&(tj(),p(e))},[ep,ey,p,tj]),tq=(0,i.useCallback)(e=>{let t=ep.trim();if(!t&&!ey.length)return;Q?.();let n=ey.length?ey:void 0,r=()=>{if(t.startsWith("/")&&ee){tj(),ee(t,"steer"===e?"steer":"followUp",n);return}tj(),"steer"===e&&u?u(t,n):"followup"===e&&h&&h(t,n)};!ey.length&&G&&rc(t)?tw(t):!ey.length&&G&&nq(t)?tw(t).then(e=>{e||r()},()=>r()):r()},[ep,ey,G,ee,u,h,tj,Q,tw]),tK=(0,i.useCallback)(e=>{let t=tI.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eI-1);if("right"===e)return Math.min(t,eI+1);let n=to.current[eI];if(!n)return"down"===e?Math.min(t,eI+1):Math.max(0,eI-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,s=r.top+r.height/2,a=-1,o=1/0;for(let n=0;n<=t;n+=1){if(n===eI)continue;let t=to.current[n];if(!t)continue;let r=t.getBoundingClientRect(),l=r.top+r.height/2-s;if("down"===e?l<=4:l>=-4)continue;let d=1e3*Math.abs(l)+Math.abs(r.left+r.width/2-i);d<o&&(a=n,o=d)}return a>=0?a:"down"===e?Math.min(t,eI+1):Math.max(0,eI-1)},[tI.length,eI]),tZ=(0,i.useCallback)(e=>{let t=e.nativeEvent,n="Enter"===e.key&&!e.shiftKey,r=ed||"ctrlEnter"===eu?n&&(e.ctrlKey||e.metaKey):n,i=ed?r:n,s=Date.now()-tr.current<100,a=tn.current||t.isComposing||229===t.keyCode;if(i&&(a||s)){s&&e.preventDefault();return}if(e_&&!a){if("ArrowDown"===e.key){e.preventDefault(),eK(e=>Math.min(Math.max(0,q.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eK(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),eU(!1);return}if(("Tab"===e.key||i)&&q[eq]){e.preventDefault(),tH(q[eq]);return}}if(eC&&null!==tC){if("ArrowDown"===e.key){e.preventDefault(),e$(tK("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e$(tK("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e$(tK("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e$(tK("left"));return}if("Escape"===e.key){e.preventDefault(),eN(!1);return}let t=tI[eI];if("Tab"===e.key&&t){e.preventDefault(),t_(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 nU(t)&&nq(e)}(ep,t,m)?(eN(!1),tS()):t_(t);return}}if(eA&&null!==eM&&!a){if("ArrowDown"===e.key){e.preventDefault(),eD(e=>rt(e,tW.length,1));return}if("ArrowUp"===e.key){e.preventDefault(),eD(e=>rt(e,tW.length,-1));return}if("Escape"===e.key){e.preventDefault(),eL(!1);return}if(("Tab"===e.key||i)&&tW[eO]){e.preventDefault(),tB(tW[eO]);return}}if("ArrowUp"===e.key&&!a&&!m&&q.length>0&&0===ep.trim().length){e.preventDefault(),eN(!1),eL(!1),eK(q.length-1),eU(!0);return}if("Escape"===e.key&&!a&&m&&c){e.preventDefault(),c();return}r&&(e.preventDefault(),m&&(u||h)?tq(e.altKey&&h||!u?"followup":"steer"):tS())},[ed,eu,m,u,h,c,eC,tC,tI,eI,t_,tq,tS,tK,eA,eM,tW,eO,tB,e_,q,eq,tH,ep]),tV=(0,i.useCallback)(()=>{ti.current=null;let e=e3.current;e&&ri(e)},[]),tJ=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!ei&&t.length){e.preventDefault(),tx(t.map(e=>e.getAsFile()).filter(e=>null!==e));return}let n=e.clipboardData.getData("text/html"),r=e.clipboardData.getData("text/plain");if(r){let t=e.currentTarget,n=e.nativeEvent,i=t.selectionStart,s=t.selectionEnd,a={};ti.current=a,setTimeout(()=>{ti.current===a&&(ti.current=null,!n.defaultPrevented&&t.isConnected&&rr(t,i,s,r))},0)}if(!n||!r)return;let i=new DOMParser().parseFromString(n,"text/html"),s=function(e,t){let n="",r=0,i=!1;for(let{label:s,href:a,occurrence:o}of t){if(!s||!a)continue;let t=0;for(let n=0;n<=o&&!((t=e.indexOf(s,n?t+s.length:0))<0);n++);if(t<r)continue;let l=s.replace(/([\\[\]])/g,"\\$1"),d=a.replace(/([\\()])/g,"\\$1");n+=`${e.slice(r,t)}[${l}](${d})`,r=t+s.length,i=!0}return i?n+e.slice(r):null}(r,Array.from(i.querySelectorAll("a[href]"),e=>{let t=e.textContent??"",n=i.createRange();return n.setStart(i.body,0),n.setEndBefore(e),{label:t,href:e.getAttribute("href")?.trim()??"",occurrence:t?n.toString().split(t).length-1:0}}));if(null===s)return;let a=e.currentTarget,o=a.selectionStart,l=a.value.slice(0,o)+s+a.value.slice(a.selectionEnd);e.preventDefault(),tm.current=l,eh(l),eU(!1),tA(l,o+s.length),requestAnimationFrame(()=>{a.focus(),a.setSelectionRange(o+s.length,o+s.length)})},[ei,tx,tA]);(0,i.useEffect)(()=>{if(null===tC){eN(!1),e$(0),ts.current=!1;return}eN(!0),e$(0),!ts.current&&J&&(ts.current=!0,Promise.resolve(J()).catch(()=>{ts.current=!1}))},[tC,J]),(0,i.useEffect)(()=>{if(!eC||!en)return;let e=!1;return e4({cwd:en,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(en)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;e4({cwd:en,values:n})}).catch(()=>{e||e4({cwd:en,values:{}})}),()=>{e=!0}},[eC,en]),(0,i.useEffect)(()=>{eI>=tI.length&&e$(Math.max(0,tI.length-1))},[tI.length,eI]),(0,i.useEffect)(()=>{to.current.length=tI.length},[tI.length]),(0,i.useEffect)(()=>{eC&&to.current[eI]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eI,eC]),(0,i.useLayoutEffect)(()=>{if(!eC||null===tC)return void eT(null);let e=ta.current;if(e)return rs(e,e=>{eT(t=>t===e?t:e)})},[eC,tC]),(0,i.useLayoutEffect)(()=>{if(!eA||null===eM)return void ez(null);let e=tl.current;if(e)return rs(e,e=>{ez(t=>t===e?t:e)})},[eA,eM]);let tG=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}}),tY=A?Math.max(0,A.tokensBefore-A.estimatedTokensAfter):0,tX=A?`${A.reason&&"manual"!==A.reason?`${A.reason[0].toUpperCase()}${A.reason.slice(1)} `:es("chat.compacted")} ${rl(A.tokensBefore)} -> ${rl(A.estimatedTokensAfter)} tokens (${es("chat.tokensSaved",{saved:rl(tY)})})`:null,tQ=z&&"auto"!==z?z:null,t0="auto"!==(n=tQ??"auto")&&D?D[n]??n:n,t1=Object.entries(n7).find(e=>{let[,t]=e;return t===(L??"configured")})?.[0]??"configured",t2="chat-only"===t1?es("chat.chatOnly"):t1;(0,i.useEffect)(()=>{let e=e=>{e5.current&&!e5.current.contains(e.target)&&eg(!1),e9.current&&!e9.current.contains(e.target)&&ex(!1),e7.current&&!e7.current.contains(e.target)&&ev(!1),!te.current||te.current.contains(e.target)||e3.current?.contains(e.target)||eU(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{m&&eg(!1)},[m]);let t4=(0,i.useRef)(-1/0);(0,i.useLayoutEffect)(()=>{if(m)return()=>{t4.current=performance.now()}},[m]);let t8=e=>{var t,n;return t=e.detail,n=performance.now()-t4.current,t>0&&n<600};return(0,i.useEffect)(()=>{ed||ev(!1)},[ed]),(0,r.jsxs)("fieldset",{disabled:eZ,"aria-busy":eZ,className:ei?void 0:"chat-input-shell",style:{...ei?{flexShrink:0}:{display:"flex",flexDirection:"column",minHeight:0},minWidth:0,margin:0,border:0,background:"transparent",padding:ei?0:"0 16px 8px",paddingRight:ei?0:ed?16:52,opacity:eZ?.5:1,transition:"opacity 0.15s"},children:[!ei&&(0,r.jsx)("input",{ref:tt,type:"file",accept:er?void 0:"image/*",multiple:!0,style:{display:"none"},onChange:tb}),(0,r.jsxs)("div",{style:{...ei?void 0:{display:"flex",flexDirection:"column",minHeight:0,width:"100%"},maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(0,r.jsx)(rk,{cwd:y}),(0,r.jsx)(rw,{error:v}),(0,r.jsx)(rS,{warnings:j}),tR&&(s=b?.find(e=>e.provider===g?.provider&&e.id===g?.modelId),(0,r.jsx)(rj,{tone:"warning",title:es("chat.imageNotSupportedTitle"),body:es("chat.imageNotSupportedBody",{model:s?.name||g?.modelId||""}),onClose:()=>eH(!0)})),(U?.steering.length??0)+(U?.followUp.length??0)>0&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:72,marginBottom:8,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:es("chat.queued",{count:(U?.steering.length??0)+(U?.followUp.length??0)})}),K&&(0,r.jsxs)("button",{onClick:K,title:es("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:7,cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),es("chat.recall")]})]}),(0,r.jsxs)("div",{style:{maxHeight:"min(180px, calc(var(--app-viewport-height, 100dvh) * 0.25))",overflowY:"auto",overscrollBehavior:"contain"},children:[U?.steering.map((e,t)=>(0,r.jsx)(ry,{kind:"steer",text:e},`steer-${t}`)),U?.followUp.map((e,t)=>(0,r.jsx)(ry,{kind:"follow-up",text:e},`followup-${t}`))]})]}),_&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"rgba(234,179,8,0.08)",border:"1px solid rgba(234,179,8,0.25)",borderRadius:6,fontSize:12,color:"rgba(180,130,0,0.9)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),es("chat.retrying",{attempt:_.attempt,max:_.maxAttempts}),_.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",_.errorMessage]})]}),tX&&(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"})}),tX]}),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)(e8.R,{onClick:R,title:es("chat.dismissCompactError")})]}),ey.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:ey.map((e,t)=>(0,r.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,r.jsx)(nZ.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:()=>tv(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:[e_&&q.length>0&&(0,r.jsxs)("div",{ref:te,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",maxHeight:"min(44vh, 360px)"},children:[(0,r.jsx)("div",{title:es("chat.inputHistory"),style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:"calc(min(44vh, 360px) - 31px)",overflowY:"auto",padding:4},children:q.map((e,t)=>{let n=t===eq;return(0,r.jsxs)("button",{ref:e=>{tc.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tH(e)},onMouseEnter:()=>eK(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),eC&&null!==tC&&(0,r.jsxs)("div",{ref:ta,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eE?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${eE}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:V?es("chat.loadingCommands"):es("chat.slashCommands",{label:tE})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:es("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:10},children:V||0!==tN.length?t$.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:es(rp[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(e=>{let{command:t,index:n}=e,i=n===eI,s=rg(t,e6);return(0,r.jsxs)("button",{ref:e=>{to.current[n]=e},type:"button",onMouseDown:e=>{e.preventDefault(),t_(t)},onMouseEnter:()=>e$(n),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${i?"var(--accent)":"var(--border)"}`,borderRadius:7,background:i?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:i?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:s?"var(--text-dim)":void 0},children:["/",t.name,s&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:es("chat.dormant")})]}),t.description&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:rm(t,es)})]},`${t.source}:${t.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:es("chat.noCommands")})})]}),eA&&null!==eM&&(a=eX&&(!eG||eG.cwd!==en),o=1===tW.length?es("chat.match"):es("chat.matches",{count:tW.length}),l=eG?.truncated&&!tO?eM.query?es("chat.searchingAll"):es("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:tl,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eP?"min(48vh, 400px)":`min(48vh, 400px, ${eP}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:a?es("chat.loadingFiles"):es("chat.files",{label:o,hint:l})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:es("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:a||0!==tW.length?tW.map((e,t)=>{let n=t===eO,i=e.path.split("/").pop()??e.path,s=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{td.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tB(e)},onMouseEnter:()=>eD(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)(nK.sj,{size:14}):(0,nK.I3)(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[s&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:s}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:tz&&!tO?es("chat.searching"):es("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:tM?void 0:"chat-composer-row",style:{minWidth:0,display:"flex",flexDirection:tM?"column":"row",gap:8,alignItems:tM?"stretch":"center",background:"var(--bg)",border:ei?"none":`1px solid ${ew?"var(--tool-bg)":m&&(u||h)?"rgba(234,179,8,0.4)":"color-mix(in srgb, var(--border) 70%, transparent)"}`,borderRadius:14*!ei,padding:ei?0:ed?"6px 6px 6px 12px":"10px 10px 10px 14px",boxShadow:ei?"none":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("textarea",{ref:e3,className:"chat-input-textarea","aria-label":ei?es("chat.askInSideChat"):void 0,value:ep,onChange:e=>{tm.current=e.target.value,eh(e.target.value),eU(!1),tA(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;tA(t.value,t.selectionStart)},onKeyDown:tZ,onCompositionStart:()=>{tn.current=!0},onCompositionEnd:e=>{tn.current=!1,tr.current=Date.now();let t=e.currentTarget;tA(t.value,t.selectionStart)},onInput:tV,onPaste:tJ,placeholder:T?es("chat.compactingPlaceholder"):m&&(u||h)?es("chat.steerPlaceholder"):m?es("chat.agentPlaceholder"):es("chat.messagePlaceholder"),rows:1,style:{flex:tM?"none":1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:"var(--chat-content-font-size, 14px)",lineHeight:1.6,fontFamily:"inherit",minHeight:ei?96:24,maxHeight:200,overflow:"auto"}}),m?(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:tU,disabled:!ep.trim()||ey.length>0,title:es("chat.sideChatHint"),"aria-label":es("chat.sideChat"),className:`bg-transparent ${ep.trim()&&!ey.length?"cursor-pointer text-text-muted hover:bg-bg-hover hover:text-text":"cursor-not-allowed text-text-dim"}`,style:{width:38,display:"grid",placeItems:"center",padding:0,border:"1px solid var(--border)",borderRadius:8,transition:"background 0.12s"},children:(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"}),(0,r.jsx)("path",{d:"M13 8.5v7M9.5 12h7"})]})}),u&&(0,r.jsxs)("button",{onClick:()=>tq("steer"),disabled:!tT,title:es("chat.steerHint"),"aria-label":es("chat.steer"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tT?"rgba(234,179,8,0.12)":"none",border:"1px solid rgba(234,179,8,0.35)",borderRadius:8,color:tT?"rgba(180,130,0,1)":"var(--text-dim)",cursor:tT?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{className:"chat-composer-run-label",children:es("chat.steer")})]}),h&&(0,r.jsxs)("button",{onClick:()=>tq("followup"),disabled:!tT,title:`${es("chat.followUpHint")} (${ed?"Ctrl/Cmd+":""}Alt/Option+Enter)`,"aria-label":es("chat.followUp"),"aria-keyshortcuts":ed?"Control+Alt+Enter Meta+Alt+Enter":"Alt+Enter",style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tT?"rgba(129,140,248,0.12)":"none",border:"1px solid rgba(129,140,248,0.35)",borderRadius:8,color:tT?"rgba(99,102,241,1)":"var(--text-dim)",cursor:tT?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),(0,r.jsx)("span",{className:"chat-composer-run-label",children:es("chat.followUp")})]})]}):(0,r.jsxs)("button",{onClick:tS,disabled:!ep.trim()&&!ey.length,title:es("chat.send"),"aria-label":es("chat.send"),style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,...ed?{width:36,height:36,padding:0}:{padding:"7px 14px"},background:ep.trim()||ey.length?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:ep.trim()||ey.length?"var(--accent-contrast)":"var(--text-dim)",cursor:ep.trim()||ey.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:ep.trim()||ey.length?"0 1px 3px color-mix(in srgb, var(--accent) 25%, transparent)":"none",transition:"background 0.15s, box-shadow 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),!ed&&es("chat.send")]})]})]}),ew&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eS?"var(--text-muted)":"var(--accent)",marginTop:4},children:[es("chat.shell")," \xb7 ",eS?es("chat.outputLocal"):es("chat.outputModel")]}),!ei&&(0,r.jsxs)("div",{className:"chat-input-controls",style:{marginTop:ed?4:8,display:ed?"grid":"flex",gridTemplateColumns:ed?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:ed?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2},children:[(0,r.jsx)("button",{onClick:()=>tt.current?.click(),title:es("chat.attachFiles"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:ec,height:ec,padding:0,background:"none",border:"none",borderRadius:9,color:ey.length?"var(--accent)":"var(--text-muted)",cursor:"pointer",opacity:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=ey.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=ey.length?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:ed?18:15,height:ed?18:15,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),(tG.length>0||g||v)&&S&&(0,r.jsx)(n3,{options:tG,value:g,onChange:S,onReselect:S,busy:C,isAutoSelection:f,defaultValue:N,onSetDefault:I,allOptions:k?.map(e=>({provider:e.provider,providerName:e.providerName,modelId:e.id,name:e.name})),onShowAll:w})]}),!ed&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsxs)("div",{ref:e7,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:ed?0:"auto"},children:[ed&&(0,r.jsx)("button",{type:"button",title:eb?void 0:es("chat.moreControls"),"aria-label":es("chat.moreControls"),"aria-expanded":eb,"aria-hidden":eb||void 0,tabIndex:eb?-1:void 0,onClick:()=>{ev(!0)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:ec,padding:"8px 10px",background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:eb?"default":"pointer",fontSize:12,fontWeight:500,visibility:eb?"hidden":"visible",pointerEvents:eb?"none":"auto",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{eb||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{eb||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:es("chat.moreControls")}),(0,r.jsxs)("div",{style:{display:ed?eb?"flex":"none":"flex",alignItems:"center",gap:ed?1:2,...ed?{position:"absolute",right:0,bottom:0,zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"nowrap",justifyContent:"flex-end",border:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:10,background:"color-mix(in srgb, var(--bg-panel) 92%, var(--bg))",boxShadow:"0 8px 24px rgba(0,0,0,0.14)",backdropFilter:"blur(10px)"}:null},children:[W&&(0,r.jsxs)("div",{ref:e9,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>ex(e=>!e),title:m?es("chat.currentReasoning",{level:t0}):es("chat.changeReasoning",{level:t0}),"aria-label":es("chat.changeReasoningLabel"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ed?"0 10px":"8px 12px",width:ed?"auto":void 0,height:ec,background:ef?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=ef?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),(!ed||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t0})]}),ef&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",...ed?{left:0}:{right:0},zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:180},children:ra.filter(e=>!F||"auto"===e||F.includes(e)).map(e=>{let t="auto"===e?O:!O&&tQ===e,n=es(ro[e]),i="auto"!==e&&D?D[e]:void 0,s=null!=i&&i!==e?i:e,a=null!=i&&i!==e;return(0,r.jsxs)(n6,{active:t,onSelect:()=>{if(ex(!1),"auto"===e){O||W("auto");return}(!t||O)&&W(e)},gutter:!!H,star:H&&"auto"!==e?{isDefault:B===e,saveLabel:es("chat.saveDefaultThinking"),defaultLabel:es("chat.defaultThinking"),onSave:()=>{ex(!1),H(e)}}:void 0,children:[(0,r.jsxs)("span",{style:{flex:1},children:[s,a&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",e,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:n})]},e)})})]}),!m&&P&&(0,r.jsxs)("div",{ref:e5,style:{position:ed?"static":"relative"},children:[(0,r.jsxs)("button",{onClick:e=>{m||t8(e)||eg(e=>!e)},disabled:m,title:es("chat.changeToolPreset")+`: ${t2}`,"aria-label":es("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ed?"0 10px":"8px 12px",width:ed?"auto":void 0,height:ec,background:em?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:m?"not-allowed":"pointer",fontSize:12,opacity:m?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{m||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=em?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(!ed||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t2})]}),em&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,maxWidth:ed?"calc(100vw - 16px)":void 0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:120},children:n9.map(e=>{let t,n=n7[e],i=(L??"configured")===n;return t="configured"===e?es("chat.configuredTools"):"chat-only"===e?es("chat.chatOnly"):"read-only"===e?es("chat.readOnlyTools",{count:4}):"default"===e?es("chat.builtInTools",{count:4}):es("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{eg(!1),i||P(n)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:t})]},e)})})]}),(!m||T)&&$&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{onClick:T?E:e=>{t8(e)||$()},style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ed?"0 10px":"8px 12px",width:ed?"auto":void 0,height:ec,background:T?"rgba(239,68,68,0.08)":"none",border:"none",borderRadius:9,color:T?"#ef4444":"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=T?"rgba(239,68,68,0.16)":"var(--bg-hover)",e.currentTarget.style.color=T?"#ef4444":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=T?"rgba(239,68,68,0.08)":"none",e.currentTarget.style.color=T?"#ef4444":"var(--text-muted)"},title:T?es("chat.stopCompaction"):es("chat.compactContext"),"aria-label":T?es("chat.stopCompaction"):es("chat.compactContext"),children:T?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(!ed||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:es("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(!ed||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:es("chat.compact")})]})})}),m&&(0,r.jsxs)("button",{onClick:c,title:es("chat.stopAgent"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:ec,background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:9,color:"#ef4444",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.16)"},onMouseLeave:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),es("chat.stop")]}),void 0!==X&&(0,r.jsx)("button",{onClick:X,title:Y?es("chat.disableSound"):es("chat.enableSound"),"aria-label":Y?es("chat.disableSound"):es("chat.enableSound"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:ec,height:ec,padding:0,background:"none",border:"none",borderRadius:9,color:Y?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",opacity:Y?1:.55,transition:"background 0.12s, color 0.12s, opacity 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)",e.currentTarget.style.opacity="1"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=Y?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.opacity=Y?"1":"0.55"},children:Y?(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),(0,r.jsx)("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),(0,r.jsx)("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})}),ed&&eb&&(0,r.jsx)("button",{type:"button",title:es("chat.collapseControls"),"aria-label":es("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eg(!1),ex(!1),ev(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:ed?ec:36,height:ec,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]})]})]})]})}));var rN=n(19109),rI=n(32316),r$=n(88374),rE=n(68925);let rT="pi-web:minimap-preview-locked";function rM(){try{return window.localStorage}catch{return null}}function rR(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:rM();if(!e)return!1;try{return"true"===e.getItem(rT)}catch{return!1}}var rA=n(88576),rL=n.n(rA);function rP(e){let{level:t,children:n,headingIndex:i,onClick:s}=e;return(0,r.jsx)("button",{type:"button",className:rL().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 rz=[...rE.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]:[]}}],rO=[[r$.A,{throwOnError:!1,strict:!1}]];function rW(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 rF=(0,i.memo)(function(e){let{markdown:t,onHeadingClick:n,onAnswerClick:s}=e,a=(0,i.useMemo)(()=>(0,rE.Ep)(t),[t]);return t?(0,r.jsx)("div",{className:rL().outline,children:(0,r.jsx)(rI.oz,{remarkPlugins:rz,rehypePlugins:rO,components:{h1:e=>{let{children:t,node:i}=e;return(0,r.jsx)(rP,{level:1,headingIndex:rW(i),onClick:n,children:t})},h2:e=>{let{children:t,node:i}=e;return(0,r.jsx)(rP,{level:2,headingIndex:rW(i),onClick:n,children:t})},h3:e=>{let{children:t,node:i}=e;return(0,r.jsx)(rP,{level:3,headingIndex:rW(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:rL().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}),rD=(0,i.memo)(function(e){let{messages:t,getStreamingMessage:n,scrollContainer:s,messageRefs:a,onRevealHistory:o,turnsBefore:l}=e,{t:d}=(0,eW.s)(),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)([]),[m,g]=(0,i.useState)(null),[f,x]=(0,i.useState)(600),[b,v]=(0,i.useState)(!1),[y,j]=(0,i.useState)(rR),[k,w]=(0,i.useState)(null),S=(0,i.useRef)(!1),C=(0,i.useRef)(null),N=(0,i.useRef)([]),I=(0,i.useRef)({nodes:[],gap:50,fillsHeight:!1}),$=(0,i.useRef)(null),E=(0,i.useRef)(new Map),T=(0,i.useRef)(null),M=(0,i.useRef)(null),R=(0,i.useRef)(null),A=(0,i.useRef)(t);A.current=t;let L=(0,i.useMemo)(()=>(function(e,t){if(0===e.length)return{nodes:[],gap:50,fillsHeight:!1};let n=Math.max(1,t),r=Math.max(0,n-12-48);if(1===e.length)return{nodes:[{...e[0],topRatio:12/n}],gap:50,fillsHeight:!1};let i=r/(e.length-1),s=Math.min(50,i);return{nodes:e.map((e,t)=>({...e,topRatio:(12+t*s)/n})),gap:s,fillsHeight:i<=50}})(p,f),[p,f]),{nodes:P,gap:z}=L;I.current=L;let O=(0,i.useCallback)(e=>{M.current={index:e,until:Date.now()+1600},g(e)},[]),W=(0,i.useCallback)((e,t)=>{let n=M.current;if(n&&Date.now()<n.until)return void g(n.index);M.current=null;let r=t.filter(e=>null!==e.targetTurn.scrollTop);if(0===r.length)return void g(null);let i=e.scrollTop+.3*e.clientHeight;g(r.reduce((e,t)=>Math.abs((t.targetTurn.scrollTop??0)-i)<Math.abs((e.targetTurn.scrollTop??0)-i)?t:e,r[0]).index)},[]),F=(0,i.useCallback)(()=>{let e=s.current;if(!e)return;let t=e.scrollHeight-e.clientHeight,n=N.current;u(t>20),W(e,n)},[s,W]),D=(0,i.useRef)(null),B=(0,i.useCallback)(()=>{D.current||(D.current=setTimeout(()=>{D.current=null;let e=s.current,t=C.current;if(!e||!t)return;let r=a.current,i=e.getBoundingClientRect(),o=[],l=0,d=null,c=n();for(let t of c?[...A.current,c]:A.current){let n=(0,ni.Y0)(t);if(!n&&"assistant"!==t.role)continue;let s=r?.[l];if(l++,n){d=null;let n=s?.getBoundingClientRect();d={userMessage:t,assistantPreviews:[],scrollTop:n?n.top-i.top+e.scrollTop:null,toolCount:0},o.push(d);continue}if(!d)continue;d.toolCount+="assistant"===t.role&&Array.isArray(t.content)?t.content.reduce((e,t)=>e+ +("toolCall"===t.type),0):0;let a=function(e){if("assistant"!==e.role)return"";let{answerBlocks:t}=(0,ni.dQ)(e);return t.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n").trim()}(t);a&&d.assistantPreviews.push({markdown:a,element:s})}let p=o.map((e,t)=>({topRatio:0,targetTurn:e,index:t}));x(t.clientHeight),N.current=p,h(p),u(e.scrollHeight-e.clientHeight>20),W(e,p);let m=R.current,g=m?p[m.nodeIndex]:null;if(m&&g){let t=void 0===m.assistantIndex?null:g.targetTurn.assistantPreviews[m.assistantIndex],n=g.targetTurn.scrollTop;if("assistant"===m.target){let r=t?.element?.getBoundingClientRect();n=r?r.top-i.top+e.scrollTop:null}else if("heading"===m.target){let r=void 0===m.headingIndex?null:t?.element?.querySelectorAll("h1, h2, h3").item(m.headingIndex),s=r?.getBoundingClientRect();n=s?s.top-i.top+e.scrollTop:null}if(null===n)return;R.current=null,O(g.index);let r=.3*e.clientHeight;e.scrollTo({top:Math.max(0,n-r),behavior:"smooth"})}},150))},[n,O,a,s,W]);(0,i.useEffect)(()=>{let e=s.current;if(e)return e.addEventListener("scroll",F,{passive:!0}),()=>e.removeEventListener("scroll",F)},[s,F]),(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=()=>{B(),F()},n=new ResizeObserver(t);return n.observe(e),e.firstElementChild&&n.observe(e.firstElementChild),t(),()=>{n.disconnect(),D.current&&(clearTimeout(D.current),D.current=null)}},[B,s,F]),(0,i.useEffect)(()=>{let e=setTimeout(()=>{B(),F()},50);return()=>clearTimeout(e)},[t.length,B,F]);let H=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;if(O(e.index),null===e.targetTurn.scrollTop){R.current={nodeIndex:e.index,target:"user"},o();return}let r=Math.max(0,e.targetTurn.scrollTop-.3*n.clientHeight);n.scrollTo({top:r,behavior:t})},[O,o,s]),_=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;let r=e.targetTurn.assistantPreviews[t]?.element;if(!r){R.current={nodeIndex:e.index,target:"assistant",assistantIndex:t},o();return}let i=n.getBoundingClientRect(),a=r.getBoundingClientRect().top-i.top+n.scrollTop-.3*n.clientHeight;O(e.index),n.scrollTo({top:Math.max(0,a),behavior:"smooth"})},[O,o,s]),U=(0,i.useCallback)(e=>{let{nodes:t,gap:n,fillsHeight:r}=I.current,i=C.current?.clientHeight??0;if(0===t.length||i<=0)return null;let s=Math.max(0,Math.min(i,e*i)),a=t[0].topRatio*i,o=n>0?Math.round((s-a)/n):0,l=Math.max(0,Math.min(t.length-1,o)),d=t[l];if(!r&&Math.abs(s-d.topRatio*i)>Math.max(10,n/2))return null;return d},[]),q=(0,i.useCallback)((e,t,n)=>{let r=s.current;if(!r)return;let i=e.targetTurn.assistantPreviews[t]?.element;if(!i){R.current={nodeIndex:e.index,target:"heading",assistantIndex:t,headingIndex:n},o();return}let a=i.querySelectorAll("h1, h2, h3").item(n);if(!a)return;let l=r.getBoundingClientRect(),d=a.getBoundingClientRect().top-l.top+r.scrollTop-.3*r.clientHeight;O(e.index),r.scrollTo({top:Math.max(0,d),behavior:"smooth"})},[O,o,s]),K=(0,i.useCallback)(()=>{T.current&&(clearTimeout(T.current),T.current=null)},[]),Z=(0,i.useCallback)(()=>{y||(K(),v(!0))},[K,y]),V=(0,i.useCallback)(()=>{let e=!y;j(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:rM();if(t)try{t.setItem(rT,String(e))}catch{}}(e),e&&(K(),v(!1),w(null))},[K,y]),J=(0,i.useCallback)(()=>{K(),T.current=setTimeout(()=>{T.current=null,v(!1),w(null)},250)},[K]);(0,i.useEffect)(()=>()=>K(),[K]);let G=(0,i.useCallback)(e=>{if(!c)return;S.current=!0,Z();let t=e.currentTarget.getBoundingClientRect();w(Math.max(0,Math.min(1,(e.clientY-t.top)/t.height)));let n=(e,n)=>{let r=U(Math.max(0,Math.min(1,(e-t.top)/t.height)));r&&H(r,n)};n(e.clientY,"smooth");let r=e=>{S.current&&n(e.clientY,"auto")},i=()=>{S.current=!1,window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",i)};window.addEventListener("mousemove",r),window.addEventListener("mouseup",i)},[U,H,Z,c]),Y=null===k?null:U(k),X=Y?.index??null;if((0,i.useEffect)(()=>{if(!b||null===X)return;let e=$.current,t=E.current.get(X);if(!e||!t)return;let n=t.offsetTop-(e.clientHeight-t.offsetHeight)/2;e.scrollTop=Math.max(0,n)},[p,b,X]),!c)return null;let Q=Math.max(1,(P.length>0?P[P.length-1].topRatio*f:12)-12);return(0,r.jsxs)("div",{ref:C,onMouseDown:G,onMouseEnter:Z,onMouseLeave:J,onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();w((e.clientY-t.top)/t.height)},style:{width:36,flexShrink:0,position:"relative",cursor:"pointer",userSelect:"none",borderLeft:"1px solid var(--border)",background:"var(--bg-panel)",overflow:"visible"},children:[l>0&&(0,r.jsx)("div",{"data-minimap-earlier":"",style:{position:"absolute",left:"50%",top:0,height:12,width:1,background:"repeating-linear-gradient(to bottom, var(--text-dim) 0 2px, transparent 2px 4px)",transform:"translateX(-50%)",zIndex:0}}),(0,r.jsx)("div",{style:{position:"absolute",left:"50%",top:12,height:Q,width:1,background:"var(--border)",transform:"translateX(-50%)",zIndex:0}}),P.map(e=>{let t=b&&Y?.index===e.index,n=m===e.index;return(0,r.jsx)("div",{"data-minimap-node-index":e.index,"data-minimap-node-active":n?"":void 0,style:{position:"absolute",top:`${100*e.topRatio}%`,transform:"translateY(-50%)",left:0,right:0,height:Math.max(1,z),display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none",zIndex:2},children:(0,r.jsx)("div",{style:{width:8,height:8,borderRadius:2,background:n?"rgba(128,128,128,0.42)":"rgba(128,128,128,0.16)",border:`1.5px solid ${n?"rgba(128,128,128,0.95)":"rgba(128,128,128,0.58)"}`,boxShadow:n?"0 0 0 2px var(--bg-panel)":"none",transition:"transform 0.1s, background 0.1s",transform:t?"scale(1.25)":"scale(1)"}})},e.index)}),(0,r.jsx)("button",{type:"button",className:rL().lock,"data-minimap-lock":y?"on":"off","aria-pressed":y,title:d(y?"chatMinimap.unlockPreview":"chatMinimap.lockPreview"),"aria-label":d("chatMinimap.lockPreview"),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),V()},children:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"4",y:"11",width:"16",height:"10",rx:"2"}),y?(0,r.jsx)("path",{d:"M8 11V7a4 4 0 0 1 8 0v4"}):(0,r.jsx)("path",{d:"M8 11V7a4 4 0 0 1 7.9-.9"})]})}),b&&p.length>0&&(0,r.jsxs)("div",{ref:$,className:rL().preview,"data-minimap-preview-box":"",onMouseEnter:Z,onMouseDown:e=>e.stopPropagation(),onMouseMove:e=>e.stopPropagation(),children:[l>0&&(0,r.jsx)("button",{type:"button",className:rL().earlier,"data-minimap-preview-earlier":"",onClick:()=>s.current?.scrollTo({top:0,behavior:"smooth"}),children:d("chatMinimap.earlierTurns",{count:l})}),p.map(e=>{var t;let n=X===e.index;return(0,r.jsxs)("div",{ref:t=>{t?E.current.set(e.index,t):E.current.delete(e.index)},className:rL().turn,"data-minimap-preview-index":e.index,"data-located":n?"true":void 0,children:[(0,r.jsxs)("span",{className:rL().number,children:[(0,r.jsx)("span",{"aria-hidden":"true",children:String(l+e.index+1).padStart(2,"0")}),e.targetTurn.toolCount>0&&(0,r.jsx)("span",{className:rL().toolBadge,role:"img",title:d("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),"aria-label":d("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),children:e.targetTurn.toolCount>99?"99+":e.targetTurn.toolCount})]}),(0,r.jsxs)("div",{className:rL().content,children:[(0,r.jsx)("button",{type:"button",className:rL().user,"data-minimap-preview-user":e.index,onClick:()=>{H(e,"smooth")},children:(0,r.jsx)("span",{className:rL().userText,children:"string"==typeof(t=e.targetTurn.userMessage).content?t.content.trim():t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim()})}),e.targetTurn.assistantPreviews.map((t,n)=>(0,r.jsxs)("div",{className:rL().assistant,children:[(0,r.jsx)("button",{type:"button",className:rL().assistantJump,"data-minimap-preview-assistant":`${e.index}-${n}`,onClick:()=>_(e,n),"aria-label":d("chatMinimap.locateAssistant"),title:d("chatMinimap.locateAssistant"),children:"A"}),(0,r.jsx)(rF,{markdown:t.markdown,onAnswerClick:()=>_(e,n),onHeadingClick:t=>q(e,n,t)})]},n))]})]},e.index)})]})]})});var rB=n(42790);function rH(e){let{text:t}=e,n=(0,i.useMemo)(()=>{let e=new rB.v;return e.use_classes=!0,e.ansi_to_html(t).replaceAll('<a href="','<a target="_blank" rel="noopener noreferrer" href="')},[t]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:n}})}function r_(e){let t,n,s,{widgets:a,children:o}=e,{t:l}=(0,eW.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)(rH,{text:f.lines.join("\n")})})]},f.key))}),(0,r.jsxs)("div",{className:"extension-status-row",children:[(0,r.jsx)("div",{className:"extension-widget-triggers","aria-label":l("chat.extensionWidgets"),children:a.map((e,t)=>{let n=e.lines.length>0,i=n&&e.key===f?.key,s=m.has(e.key),a=l(1===e.lines.length?"chat.extensionWidgetLine":"chat.extensionWidgetLines",{count:e.lines.length}),o=l("belowEditor"===e.placement?"chat.extensionWidgetBelow":"chat.extensionWidgetAbove"),c=`${d}-trigger-${t}`,u=`${d}-panel-${t}`,p=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"extension-widget-update-pulse","aria-hidden":"true"}),(0,r.jsx)("span",{className:"extension-widget-placement","aria-hidden":"true",children:(0,r.jsx)("svg",{className:"extension-widget-placement-icon",viewBox:"0 0 8 6",width:"8",height:"6","data-direction":"belowEditor"===e.placement?"down":"up",focusable:"false",children:(0,r.jsx)("path",{d:"belowEditor"===e.placement?"M0 0h8L4 6z":"M4 0l4 6H0z"})})}),(0,r.jsx)("span",{className:"extension-widget-key",children:e.key})]});return n?(0,r.jsx)("button",{id:c,type:"button",className:`extension-widget-trigger${i?" is-expanded":""}${s?" is-updating":""}`,"aria-controls":u,"aria-expanded":i,"aria-label":`${o}: ${e.key}, ${a}`,title:`${e.key} - ${o} - ${i?l("i18n.collapse"):l("i18n.expand")}`,onClick:()=>{h(t=>{var n;return t===(n=e.key)?null:n})},children:p},e.key):(0,r.jsx)("div",{className:`extension-widget-trigger${s?" is-updating":""}`,"aria-label":`${o}: ${e.key}, ${a}`,title:`${e.key} - ${o}`,children:p},e.key)})}),o]})]})}let rU="command:";function rq(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(rU))return null;let t=e.slice(rU.length).trim();return t.length>1&&t.startsWith("/")?t:null}(n.key);if(r){let n=t5(e).replace(/\s+/g," ").trim();t.push({kind:"command",command:r,label:n||r})}else t5(e).trim()&&t.push({kind:"text",text:e})}return t}(t);if(0===a.length&&0===n.length)return null;let o=a.some(e=>"command"===e.kind),l=a.map(e=>"text"===e.kind?t5(e.text):e.label).join(" "),d=a.length>0?(0,r.jsx)("div",{role:"status",className:"extension-status-line","aria-label":l,title:l,children:(0,r.jsx)("span",{className:"extension-status-text",children:a.map((e,t)=>"text"===e.kind?(0,r.jsx)("span",{className:"extension-status-item",children:(0,r.jsx)(rH,{text:e.text})},t):(0,r.jsx)("button",{type:"button",className:"extension-status-item extension-status-command",disabled:!i||s,title:`${e.label} \xb7 ${e.command}`,"aria-label":`${e.label} (${e.command})`,onClick:()=>i?.(e.command),children:e.label},t))})}):null;return(0,r.jsx)("div",{className:`extension-status-shelf${n.length>0?" has-widgets":""}${a.length>0?" has-status":""}${o?" has-commands":""}`,children:n.length>0?(0,r.jsx)(r_,{widgets:n,children:d}):d})}function rK(e,t){return e?.kind==="running_tools"&&e.tools.length>0?e:t?{kind:"waiting_model"}:{kind:"running_command"}}function rZ(e){switch(e.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==e.closed;default:return!1}}function rV(e,t){return e.every(e=>t.has(e.id))?e:e.filter(e=>t.has(e.id))}function rJ(e,t){return e.some(e=>e.id===t)?e.filter(e=>e.id!==t):e}function rG(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function rY(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(!rG(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=rG(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=rG(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 rX(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 rQ 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 r0(e){return e instanceof rQ&&"prompt_rejected"===e.code&&!1===e.accepted}function r1(e){return`/api/agent/${encodeURIComponent(e)}?systemPrompt=0`}async function r2(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 rQ(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted,rX(r)??void 0);return r.data}let r4={not_found:"sideChat.error.notFound",unsaved:"sideChat.error.unsaved",empty:"sideChat.error.empty",subagent:"sideChat.error.subagent",side:"sideChat.error.side"};async function r8(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 r4?t(r4[i.code]):i?.error??`HTTP ${r.status}`}}async function r6(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 r3(){return globalThis.__piSessionViewCache||(globalThis.__piSessionViewCache=new Map),globalThis.__piSessionViewCache}let r5=new WeakMap;function r9(e){let t,n=r5.get(e);if(void 0!==n)return n;try{t=JSON.stringify(e).length}catch{t=Number.MAX_SAFE_INTEGER}return r5.set(e,t),t}function r7(e){let t=r3().get(e);return t?Date.now()-t.savedAt>6e5?(r3().delete(e),null):(r3().delete(e),r3().set(e,t),t):null}function ie(e){if(!e.sessionId||!e.revision)return!1;let t=r3();t.delete(e.sessionId);let n={...e,savedAt:Date.now()};return!(r9(n)>0x2000000)&&(t.set(n.sessionId,n),!function(){let e=r3();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+=r9(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-=r9(r))}}(),r3().has(n.sessionId))}function it(e){r3().delete(e)}var ir=n(14755);let ii="pi-tool-preset";function is(){try{return window.localStorage}catch{return null}}function ia(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 io(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,ia(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),ia(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function il(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e)}function id(e){return e>0?e>=.01?`$${e.toFixed(2)}`:"<$0.01":null}function ic(e){if(e<=0)return"0s";let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${i}s`:`${i}s`}function 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 ip(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 ih=(e,t)=>`live:${e??""}:${t}`;class im 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 ig{constructor(e){this.options=e,this.current=null,this.retry=null,this.retryGeneration=0,this.opens=0,this.retries=0,this.lastError=null,this.lastClose=null}close(e){let t=null!==this.lastError&&!(this.lastClose&&this.lastClose.at>=this.lastError.at);(this.current||this.retry||t)&&(this.lastClose={reason:e??null,at:Date.now()}),this.stopRetrying(),this.current&&this.discard(this.current,new im("closed"))}snapshot(){let e=this.current,t=this.retry;return{sessionId:e?.sessionId??t?.sessionId??null,state:e?e.attempt.ready?"connected":"connecting":t?"retrying":"idle",readyState:e?e.source.readyState:null,openedAt:e?.openedAt??null,connectedAt:e?.connectedAt??null,lastSeenAt:e?.lastSeenAt??null,lastHeartbeatAt:e?.lastHeartbeatAt??null,events:e?.events??0,opens:this.opens,retries:this.retries,retryDueAt:t?.dueAt??null,watchdogArmed:!!(e&&null!==e.watchdog),staleAfterMs:this.options.staleAfterMs??null,lastError:this.lastError?{...this.lastError}:null,lastClose:this.lastClose?{...this.lastClose}:null}}maintain(e){if(!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof im?"startup_error"===n.status?this.stopRetrying():this.scheduleRetry(e):this.options.onUnexpectedError?.(n))})}async ensureConnected(e){for(;;){let t=this.current;if(t&&t.sessionId===e){if(t.attempt.ready&&1===t.source.readyState)return}else t=this.open(e);if(await t.attempt.promise,this.current!==t){if(this.current?.sessionId===e)continue;throw new im("closed")}if(1===t.source.readyState)return;this.lastClose={reason:"stuck",at:Date.now()},this.discard(t,new im("closed"))}}open(e){let t,n,r;this.current&&(this.lastClose={reason:"replaced",at:Date.now()},this.discard(this.current,new im("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 im("closed",e)}this.opens+=1;let i=!1,s=new Promise((e,t)=>{n=e,r=t}),a=setTimeout(()=>{this.fail(d,new im("ready_timeout"),"ready_timeout")},this.options.readinessTimeoutMs),o={promise:s,ready:!1,succeed(){i||(i=!0,clearTimeout(a),n())},fail(e){i||(i=!0,clearTimeout(a),r(e))}},l=Date.now(),d={sessionId:e,source:t,attempt:o,watchdog:null,openedAt:l,connectedAt:null,lastSeenAt:null,lastHeartbeatAt:null,events:0};return this.current=d,t.onmessage=e=>{let t;if(this.current===d){d.lastSeenAt=Date.now();try{t=JSON.parse(e.data)}catch{return}if("heartbeat"===t.type){d.lastHeartbeatAt=d.lastSeenAt;return}if("connected"===t.type){d.connectedAt??=d.lastSeenAt,o.ready=!0,o.succeed(),this.stopRetrying();let e=this.options.staleAfterMs;e&&null===d.watchdog&&(d.watchdog=setInterval(()=>{Date.now()-(d.lastSeenAt??l)>e&&this.fail(d,new im("closed"),"stale")},Math.max(1e3,Math.floor(e/3))))}else if("startup_error"===t.type){let e="string"==typeof t.errorMessage?t.errorMessage:void 0;this.fail(d,new im("startup_error",e),"startup_error");return}d.events+=1,this.options.onEvent(t)}},t.onerror=()=>{this.fail(d,new im("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 ix(e){return!!e&&"unanswered"!==e&&!!(e.running||e.awaitingInput||e.subagentsActive)}var ib=n(48495);function iv(e){return("tool_execution_start"===e.type||"tool_execution_update"===e.type||"tool_execution_end"===e.type)&&"string"==typeof e.parentToolCallId&&""!==e.parentToolCallId}function iy(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 ij(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var ik=n(89594);function iw(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return e+t>=n-r}let iS={isStreaming:!1,streamingMessage:null};function iC(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 iN(){let e=iS,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=rY(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 iC(e,n.contentIndex,()=>({type:"text",text:""}));case"text_delta":return iC(e,n.contentIndex,e=>e?.type==="text"?{...e,text:e.text+n.delta}:null);case"text_end":return iC(e,n.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:n.content}));case"thinking_start":return iC(e,n.contentIndex,()=>({type:"thinking",thinking:""}));case"thinking_delta":return iC(e,n.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+n.delta}:null);case"thinking_end":return iC(e,n.contentIndex,e=>({...e?.type==="thinking"?e:{},type:"thinking",thinking:n.content}));case"toolcall_start":return iC(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 iC(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 iC(e,n.contentIndex,()=>({type:"toolCall",toolCallId:n.toolCall.id,toolName:n.toolCall.name,input:n.toolCall.arguments}));default:return e}case"end":return iS;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 iI(e,t){let n=e.lastIndexOf(t);return -1===n?e:[...e.slice(0,n),...e.slice(n+1)]}function i$(e,t){return e.reduce((e,n)=>"user"===n.role&&ip(n)===t?e+1:e,0)}function iE(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function iT(e){return e&&"auto"!==e?e:null}let iM=new Map,iR=[2e3,5e3,1e4];function iA(e){return new Promise(t=>setTimeout(t,e))}function iL(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function iP(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:iL(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:iL(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=iL(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function iz(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 iO(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 iW=e=>e.isStreaming,iF=e=>!!e.streamingMessage?.content.length,iD=e=>e.streamingMessage;var iB=n(70843),iH=n(36690);let i_=null,iU=null;function iq(e){let{label:t}=e,[n,s]=(0,i.useState)(()=>iU);if((0,i.useEffect)(()=>{if(iU)return;let e=!1;return(i_??=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=>(iU=e,e)).catch(()=>(i_=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 iK(e){let{messageCount:t,toolCallCount:n,durationMs:s,cacheMisses:a,defaultExpanded:o=!1,reveal:l=!1,children:d,t:c}=e,[u,p]=(0,i.useState)(o);(0,i.useLayoutEffect)(()=>{l&&p(!0)},[l]);let h=[`${t} ${c(1===t?"chat.message":"chat.messages")}`];n>0&&h.push(`${n} ${c(1===n?"chat.toolCall":"chat.toolCalls")}`),void 0!==s&&h.push(c("chat.turnDuration",{time:(0,ny.J)(s)}));let m=a&&!(u||l)?(0,iH.YL)(c,a):void 0;return(0,r.jsxs)("div",{style:{marginBottom:14},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":u||l,"aria-label":[c("chat.processDetails"),...h,...m?[m]:[]].join(" \xb7 "),onClick:()=>p(e=>!e),style:{display:"flex",alignItems:"center",gap:8,width:"auto",maxWidth:"100%",minHeight:24,padding:"2px 0",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},title:c(u?"chat.collapseProcess":"chat.expandProcess"),children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:u?"rotate(90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"4 2.5 7.5 6 4 9.5"})}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[h.join(" \xb7 "),m&&(0,r.jsx)("span",{style:{color:iH.lV},children:` \xb7 ${m}`})]})]}),(u||l)&&(0,r.jsx)("div",{style:{marginTop:8},children:d})]})}function iZ(e){var t;let s,{session:o,searchTarget:d,onSearchTargetHandled:c,initialScrollPosition:u,onScrollPositionChange:p,sessionRunning:h,newSessionCwd:m,newSessionDraftKey:g,newSessionContextBar:f,initialNewSessionChoices:x,onNewSessionChoicesChange:b,onAgentEnd:v,onToolEnd:y,onAttentionNeeded:j,onSessionCreated:k,onSessionForked:w,panel:S=!1,onSideSession:C,modelsRefreshKey:N,chatInputRef:I,onBranchDataChange:$,onSystemPromptChange:E,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:q,playDoneSound:K=()=>{},unlockAudio:Z,holdAudio:V}=e,{t:J}=(0,eW.s)(),G=(0,eF.a)(),Y=!l(o?.relation),X=(0,i.useRef)(K);X.current=K;let Q=(0,i.useRef)(U);Q.current=U;let ee=(0,i.useRef)(!1),et=(0,i.useCallback)(e=>{Y&&Q.current&&!e.aborted&&!e.subagentsActive&&X.current(),v?.(e)},[Y,v]),en=(0,i.useRef)(d?null:u??null),[er,ei]=(0,i.useState)(()=>{let e=en.current;return e&&!e.atBottom?e:null}),[es,ea]=(0,i.useState)(!1),{loading:eo,error:el,messages:ed,activeToolResults:ec,entryIds:eu,messageKeys:ep,historyCursor:eh,hasEarlierMessages:em,earlierTurnCount:eg,streamingStore:ef,agentRunning:ex,bashRunning:eb,pendingBash:ev,modelNames:ey,modelList:ej,modelError:ek,missingCwd:ew,modelScopeWarnings:eS,isModelScopeActive:eC,allModelList:eI,modelThinkingLevels:e$,modelThinkingLevelMaps:eE,toolPreset:eT,thinkingLevel:eM,retryInfo:eR,contextUsage:eA,forkingEntryId:eL,isCompacting:eP,compactError:ez,compactResult:eO,displayModel:eD,modelSwitching:eH,sessionStats:e_,slashCommands:eU,slashCommandsLoading:eq,queuedMessages:eK,notices:eV,extensionDialog:eJ,waitingExtensionDialogCount:eG,extensionCustomUi:eY,waitingExtensionCustomUiCount:eX,extensionStatuses:eQ,extensionWidgets:e0,respondToExtensionUi:e1,sendExtensionCustomInput:e2,setNoticePaused:e4,addNotice:e8,isAutoModelSelection:e6,isAutoThinkingSelection:e3,defaultModel:e5,savedDefaultThinkingLevel:e9,agentPhase:e7,isNew:te,editEntryId:tt,showScrollToBottom:tn,sessionIdRef:tr,scrollContainerRef:ti,lastUserMsgRef:ts,promptAnchorActive:ta,handleSend:to,handleAbort:tl,startSideChat:td,handleFork:tc,handleEditContent:tu,cancelEdit:tp,handleModelChange:th,handleCompact:tm,handleSteer:tg,handleFollowUp:tf,handlePromptWithStreamingBehavior:tx,handleAbortCompaction:tb,dismissCompactError:tv,handleRecallQueue:ty,handleBuiltinSlashCommand:tj,handleToolPresetChange:tk,handleThinkingLevelChange:tw,handleSetDefaultModel:tS,handleSetDefaultThinkingLevel:tC,loadSlashCommands:tN,loadAllModels:tI,scrollUserMsgToTop:t$,loadContext:tE,activeLeafId:tT,scrollToBottom:tM,scrollToMessage:tR}=function(e){let{session:t,newSessionCwd:r,newSessionDraftKey:s,onAgentEnd:a,onToolEnd:o,onAttentionNeeded:l,onSessionCreated:d,onSessionForked:c,onSideSession:u,modelsRefreshKey:p,onBranchDataChange:h,onSystemPromptChange:m,onSystemToolsChange:g,onSystemInfoLoaderChange:f,onSessionStatsPanelOpen:x,onOpenSettings:b,onDebugSnapshotReaderChange:v}=e,y=null===t&&null!==r,j=y?e.initialNewSessionChoices??null:null,[k,w]=(0,i.useState)(null),[S,C]=(0,i.useState)(!y),[N,I]=(0,i.useState)(null),[$,E]=(0,i.useState)(null),[T,M]=(0,i.useState)([]),[R,A]=(0,i.useState)(new Map),[L,P]=(0,i.useState)([]),[z,O]=(0,i.useState)(()=>new Map),[W,F]=(0,i.useState)(null),[D,B]=(0,i.useState)(!1),[H,_]=(0,i.useState)(0),[U]=(0,i.useState)(iN),q=U.dispatch,[K,Z]=(0,i.useState)(!1),[V,J]=(0,i.useState)(!1),[G,Y]=(0,i.useState)(null),[X,Q]=(0,i.useState)({}),[ee,et]=(0,i.useState)([]),[en,er]=(0,i.useState)(null),[ei,es]=(0,i.useState)(null),[ea,eo]=(0,i.useState)(null),[el,ed]=(0,i.useState)([]),[ec,eu]=(0,i.useState)(!1),[ep,eh]=(0,i.useState)(null),em=(0,i.useRef)(null),[eg,ef]=(0,i.useState)({}),[ex,eb]=(0,i.useState)({}),[ev,ey]=(0,i.useState)(()=>j?.model??null),[ej,ek]=(0,i.useState)(null),[ew,eS]=(0,i.useState)(ir.Q8),[eC,eI]=(0,i.useState)(()=>j?.thinkingLevel??null),[e$,eE]=(0,i.useState)(null),[eT,eM]=(0,i.useState)(null),[eR,eA]=(0,i.useState)(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=(0,i.useRef)(0),e_=(0,i.useRef)(0),[eU,eq]=(0,i.useState)(null),[eK,eZ]=(0,i.useState)(null),[eV,eJ]=(0,i.useState)(null),[eG,eY]=(0,i.useState)(null),[eX,eQ]=(0,i.useState)(null),[e0,e1]=(0,i.useState)(!1),[e2,e4]=(0,i.useState)(!1),[e8,e6]=(0,i.useState)(!0),[e3,e5]=(0,i.useState)(null),[e9,e7]=(0,i.useState)(null),[te,tt]=(0,i.useState)(null),[tn,tr]=(0,i.useState)(!1),[ti,ts]=(0,i.useState)(!1),[ta,to]=(0,i.useState)([]),[tl,td]=(0,i.useState)(!1),[tc,tu]=(0,i.useReducer)(iP,{visible:[],pending:[]}),[tp,th]=(0,i.useState)(null),[tm,tg]=(0,i.useState)([]),[tf,tx]=(0,i.useState)([]),[tb,tv]=(0,i.useState)([]),[ty,tj]=(0,i.useState)([]),[tk,tw]=(0,i.useState)({steering:[],followUp:[]}),tS=(0,i.useRef)(null),tC=(0,i.useRef)(null),tN=(0,i.useRef)(0),tI=(0,i.useRef)(!1),t$=(0,i.useRef)(!1),[tE,tT]=(0,i.useState)(0),tM=(0,i.useRef)(null),tR=(0,i.useRef)(()=>{}),tA=(0,i.useRef)({renewStartedAt:null,inFlightSince:null,requests:0,unanswered:0,errors:0,last:null}),tL=(0,i.useRef)({count:0,lastAt:null}),tP=(0,i.useRef)({count:0,lastAt:null,lastReason:null}),tz=(0,i.useRef)(null),tO=(0,i.useRef)(null),tW=(0,i.useRef)(!1),tF=(0,i.useRef)(0),tD=(0,i.useRef)(t?.id??null),tB=(0,i.useRef)(t?.id??null),tH=(0,i.useRef)(!1),t_=(0,i.useRef)(!1),tU=(0,i.useRef)(!1),tq=(0,i.useRef)(!1),tK=(0,i.useRef)(-1),tZ=(0,i.useRef)(!1),tV=(0,i.useRef)(0),tJ=(0,i.useRef)(null),tG=(0,i.useRef)(!!e.deferInitialScroll),tY=(0,i.useRef)(null),tX=(0,i.useRef)(!1),tQ=(0,i.useRef)(!0),t0=(0,i.useRef)(0),t1=(0,i.useRef)(null),t2=(0,i.useRef)(void 0),t4=(0,i.useRef)(void 0),t8=(0,i.useRef)(null),t6=(0,i.useRef)(null),t3=(0,i.useRef)([]),t9=(0,i.useRef)(null),t7=(0,i.useRef)(0),ne=(0,i.useRef)(!1),nt=(0,i.useRef)(j?.model??null),nn=(0,i.useRef)(j?.thinkingLevel??null),nr=(0,i.useRef)({}),ni=(0,i.useRef)(null),ns=(0,i.useRef)(0),na=(0,i.useRef)(null),no=(0,i.useRef)(null),nd=(0,i.useRef)(null),nc=(0,i.useRef)(0),nu=(0,i.useRef)(null),np=(0,i.useCallback)(()=>{no.current=ns.current,nd.current?.runId===ns.current&&(nd.current=null)},[]),nh=(0,i.useRef)(!1),ng=(0,i.useRef)(new Map),nf=(0,i.useRef)(!0),nx=(0,i.useRef)(new Map),nb=(0,i.useRef)(null),nv=(0,i.useRef)([]),ny=(0,i.useRef)([]),nj=(0,i.useRef)(null),nk=(0,i.useRef)(null),nw=(0,i.useRef)(!1),nS=(0,i.useRef)(0);tB.current=t?.id??null,nb.current=k,nv.current=T,ny.current=L,nj.current=$,nk.current=W,nw.current=D,nS.current=H,tW.current=e2,tF.current=tm.length+tf.length;let nC=(0,i.useCallback)(e=>nf.current&&tD.current===e&&(t_.current||tI.current||tB.current===e&&!t$.current),[]);tS.current||(tS.current=new ig({createSource:e=>(0,eN.Lf)("agent",new EventSource(`/api/agent/${encodeURIComponent(e)}/events?holder=${encodeURIComponent((0,eN.nU)())}`),e),onEvent:e=>tJ.current?.(e),shouldMaintain:nC,readinessTimeoutMs:6e4,reconnectDelayMs:1e3,staleAfterMs:75e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let nN=e.setToolPreset??eS,nI=t?.id;(0,i.useLayoutEffect)(()=>{(nI||y&&!tD.current)&&nN(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:is();if(!e)return ir.Q8;try{let t=e.getItem(ii);return(0,ir.sn)(t)?t:ir.Q8}catch{return ir.Q8}}())},[nI,y,nN]);let nE=e.onNewSessionChoicesChange;(0,i.useEffect)(()=>{y&&nE?.({model:ev,thinkingLevel:eC})},[y,ev,eC,nE]);let nT=(0,i.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"smooth",t=t8.current;t&&(t.scrollTo({top:t.scrollHeight,behavior:e}),t0.current=t.scrollTop)},[]),nR=eV??eG??k?.context.model??eX??null,nL=y?ev??ej:nR??(k?.context.messages.length===0?ej:null),nP=iT(k?.context.thinkingLevel&&"off"!==k.context.thinkingLevel?k.context.thinkingLevel:null),nW=y?eC??e$:eR??eL??nP??(k?.context.messages.length===0?e$:null),nF=t?.id??s??void 0,nD=(0,i.useCallback)(e=>{eY(e?.model?{provider:e.model.provider,modelId:e.model.id}:null),e?.thinkingLevel!==void 0&&eP(iT(e.thinkingLevel))},[]),nB=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=ng.current.get(t);if(!e)break;t=e}return t},[]),nH=(0,i.useCallback)((t,n,r)=>{let i=n?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}}),a=nB(r);if(!nf.current&&!ne.current&&r===s)return;let o=e.chatInputRef?.current;o?o.restoreSubmission(t,i,a):a&&nz(a,t,i)},[s,e.chatInputRef,nB]),[n_,nq]=(0,i.useState)(()=>{let e=t?.id;return e&&!nM(e)&&iM.delete(e),e&&iM.get(e)||null}),nK=(0,i.useCallback)(e=>{t?.id&&(e?iM.set(t.id,e):iM.delete(t.id),nq(e))},[t?.id]),nZ=(0,i.useCallback)((n,r)=>{t?.id&&(e.chatInputRef?.current?.replaceMessage(n),nK(r))},[e.chatInputRef,t?.id,nK]),nV=(0,i.useCallback)(()=>nK(null),[nK]),nJ=(0,i.useMemo)(()=>{let e=k?.totalActiveMs,n=eD&&eD.sessionId===k?.sessionId?eD.value:void 0,r=void 0===e&&void 0===n?void 0:Math.max(e??0,n??0);if(tp)return{...tp,totalActiveMs:r,...eW?{contextUsage:eW}:{}};let i=k?.stats,s=function(e,t,n){let r=io(n);if(!e)return r;let i=io(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)}}(i,k?.context.messages??[],T);return 0!==s.tokens.total||0!==T.length||i?{sessionFile:k?.filePath||void 0,sessionId:tD.current??t?.id??"",sessionName:t?.name,...s,totalActiveMs:r,...eW?{contextUsage:eW}:{}}:null},[T,tp,eW,eD,k?.sessionId,k?.context.messages,k?.filePath,k?.totalActiveMs,k?.stats,t?.id,t?.name]),nG=(0,i.useCallback)((e,t,n,r)=>{nf.current&&tD.current===t&&ns.current===n&&!(r<=e_.current)&&(e_.current=r,e?.contextUsage!==void 0&&eF(e.contextUsage??null),"number"==typeof e?.totalActiveMs&&eB({sessionId:t,value:e.totalActiveMs}))},[]),nY=(0,i.useCallback)(async e=>{let t=ns.current,n=++eH.current;try{let r=await fetch(r1(e));if(!r.ok)return;let i=await r.json();nG(i.state,e,t,n)}catch{}},[nG]),nX=(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:nx.current.get(i);if(s)return await s;let a=(async()=>{let i=!1,s=++nc.current;try{t&&C(!0);let a=new URLSearchParams({deferThinking:"1",deferMedia:"1",tree:"summary"});r?.force&&a.set("force","1");let o=await fetch(`/api/sessions/${encodeURIComponent(e)}?${a}`);if(404===o.status)return t&&(w(null),E(null),M([]),P([]),F(null),B(!1),_(0),I(null)),it(e),null;if(!o.ok)throw Error(`HTTP ${o.status}`);let l=await o.json();if(tD.current!==e)return null;(nu.current?.seq??0)<s&&(nu.current={sid:e,seq:s,messages:l.context.messages,entryIds:l.context.entryIds??[]});let d=r7(e),c=!!(l.snapshotRevision&&d?.revision===l.snapshotRevision&&d.entryIds.length>=(l.context.entryIds??[]).length),u=c?nv.current:l.context.messages;if(w(c?{...l,context:{...l.context,messages:nv.current,entryIds:ny.current,oldestEntryId:nk.current,hasMore:nw.current,turnsBefore:nS.current}}:l),E(l.leafId),c)ie({sessionId:e,revision:l.snapshotRevision,messages:nv.current,entryIds:ny.current,leafId:l.leafId,oldestEntryId:nk.current,hasMore:nw.current,turnsBefore:nS.current,summaryTree:l.tree,thinkingLevel:l.context.thinkingLevel,model:l.context.model,stats:l.stats,totalActiveMs:l.totalActiveMs,loadedEntryIds:ny.current});else{let e={messages:nv.current,entryIds:ny.current},t={messages:u,entryIds:l.context.entryIds??[]};O(n=>(function(e,t){let n=new Set(t.entryIds),r=new Map([...e.aliases].filter(e=>{let[t]=e;return n.has(t)})),i=e.entryIds.length,s=e.entryIds[i-1],a=void 0===s?0:t.entryIds.indexOf(s)+1;if(0===a&&void 0!==s)return r;for(let n=0;i+n<e.messages.length;n++){var o,l;let d=t.entryIds[a+n];if(void 0===d||(o=e.messages[i+n],l=t.messages[a+n],o.role!==l.role||("user"===o.role?ip(o)!==ip(l):"custom"===o.role?o.customType!==l.customType:o.timestamp!==l.timestamp)))break;r.set(d,ih(s,n))}return r})({...e,aliases:n},t)),M(t.messages),P(t.entryIds),F(l.context.oldestEntryId),B(l.context.hasMore),_(l.context.turnsBefore??0)}if(tH.current=void 0!==l.toolNames,nN(void 0!==l.toolNames?(0,ir.YO)(l.toolNames):ir.Q8),eJ(e=>nh.current?e:null),eA(null),I(null),"summary"===l.treeFormat&&l.snapshotRevision&&ie({sessionId:e,revision:l.snapshotRevision,messages:u,entryIds:l.context.entryIds??[],leafId:l.leafId,oldestEntryId:l.context.oldestEntryId,hasMore:l.context.hasMore,turnsBefore:l.context.turnsBefore??0,summaryTree:l.tree,thinkingLevel:l.context.thinkingLevel,model:l.context.model,stats:l.stats,totalActiveMs:l.totalActiveMs,loadedEntryIds:l.context.entryIds??[]}),l.wrapperRebuilt&&(tS.current?.close("rebuilt"),tS.current?.maintain(e)),!n&&l.context.thinkingLevel&&"off"!==l.context.thinkingLevel&&eP(iT(l.context.thinkingLevel)),i=!0,t&&C(!1),!n)return null;try{let t=ns.current,n=++eH.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(tD.current!==e)return null;let s=i.state;return nD(s),s?(nG(s,e,t,n),void 0!==s.systemPrompt&&eq(s.systemPrompt??null),void 0!==s.extensionStatuses&&tv(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tj(s.extensionWidgets??[]),void 0!==s.queuedMessages&&tw(iE(s.queuedMessages)),void 0!==s.autoCompactionEnabled&&e6(s.autoCompactionEnabled??!0)):i.running||tw({steering:[],followUp:[]}),i}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return I(String(e)),"error"}finally{t&&!i&&C(!1)}})();return r?.force||nx.current.set(i,a),a.finally(()=>{nx.current.get(i)===a&&nx.current.delete(i)}),await a},[nG,nN,nD]),nQ=(0,i.useCallback)(async(e,t,n,r)=>{try{let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&i.set("leafId",t),n&&i.set("before",n),r?.tail&&i.set("tail",String(r.tail));let s=`/api/sessions/${encodeURIComponent(e)}/context?${i}`,a=await fetch(s,{signal:r?.signal});if(!a.ok)throw Error(`HTTP ${a.status}`);let o=await a.json();if(tD.current!==e||r?.signal?.aborted||!nf.current)return;return F(o.context.oldestEntryId),B(o.context.hasMore),_(o.context.turnsBefore??0),w(t=>{if(!t||t.sessionId!==e)return t;let r=n?{...t.context,messages:[...o.context.messages,...t.context.messages],entryIds:[...o.context.entryIds,...t.context.entryIds],oldestEntryId:o.context.oldestEntryId,hasMore:o.context.hasMore,turnsBefore:o.context.turnsBefore}:o.context;return{...t,context:r}}),n?(M(e=>[...o.context.messages,...e]),P(e=>[...o.context.entryIds,...e])):(M(o.context.messages),P(o.context.entryIds??[])),o.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),n0=(0,i.useCallback)(async e=>{try{let t=await r2(e,{type:"get_tools"});if(!t||!nf.current||tD.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return nN(tH.current?r(t):ir.Q8),g?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[g,nN]),n1=(0,i.useCallback)(function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"(no messages)",i=tD.current;if(y&&r&&i&&!ne.current&&(ne.current=!0,s)){if(s!==i){ng.current.set(s,i);let t=e.chatInputRef?.current;t?t.rekeyDraft(s,i):nO(s,i)}d?.({id:i,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0},s)}},[y,r,s,d,e.chatInputRef]),n2=(0,i.useCallback)(async()=>{if(tD.current||!y||!r)return tD.current;if(t6.current)return t6.current;let e=(async()=>{let e=nt.current,t=nn.current;e&&eQ(e);let n=(0,ir.xG)(ew);tH.current=void 0!==n;let i=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r,type:"ensure_session",...void 0!==n?{toolNames:n}:{},...e?{provider:e.provider,modelId:e.modelId}:{},...t?{thinkingLevel:t}:{}})});if(!i.ok){let e=await i.json().catch(()=>null),t="string"==typeof e?.error?e.error:`HTTP ${i.status}`,n=rX(e);throw n?new rQ(t,i.status,void 0,void 0,n):Error(t)}let s=await i.json(),a=s.sessionId;return tD.current=a,s.model&&nt.current===e&&(eQ(s.model),e||ek(s.model)),s.thinkingLevel&&nn.current===t&&(eP(iT(s.thinkingLevel)),t||eE(iT(s.thinkingLevel))),a})();t6.current=e;try{return await e}finally{t6.current=null}},[y,r,ew]),n4=(0,i.useCallback)(async()=>{let e=tD.current??await n2();if(!e)return;let[t]=await Promise.all([r2(e,{type:"get_state"}),n0(e)]);nf.current&&tD.current===e&&(nD(t),eq(t.systemPrompt??""))},[n2,n0,nD]),n8=(0,i.useCallback)(e=>{t3.current=e,to(e)},[]),n6=(0,i.useCallback)(()=>{t7.current+=1,t9.current=null,n8([])},[n8]),n3=(0,i.useCallback)(()=>{let e=++t7.current,t=(async()=>{let t=tD.current??await n2();if(!t)return t7.current===e&&n8([]),[];td(!0);try{let n=await r2(t,{type:"get_commands"}),r=n?.commands??[];return t7.current===e&&n8(r),r}catch(t){return console.error("Failed to load slash commands:",t),t7.current===e&&n8([]),null}finally{t7.current!==e&&t9.current||td(!1)}})();t9.current=t;let n=()=>{t9.current===t&&(t9.current=null)};return t.then(n,n),t},[n2,n8]),n5=(0,i.useCallback)(async()=>await n3()??[],[n3]),n9=(0,i.useCallback)(async()=>{let e=t9.current,t=t3.current;return!e&&t.length>0?t:await (e??n3()).catch(()=>null)??(t.length>0?t:null)},[n3]),n7=(0,i.useCallback)(()=>{tN.current+=1,tI.current=!1,tO.current=null,tC.current&&(clearTimeout(tC.current),tC.current=null)},[]),re=(0,i.useCallback)(e=>{tS.current?.close(e)},[]),rt=(0,i.useCallback)(e=>tS.current.ensureConnected(e),[]),rn=(0,i.useCallback)(e=>{tS.current.maintain(e)},[]);(0,i.useEffect)(()=>{let e=t?.id;if(e)return nf.current=!0,t$.current=!1,rn(e),()=>{tD.current===e&&tS.current?.close("deselected")}},[rn,t?.id]);let rr=(0,i.useCallback)(e=>{let t=tM.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();tA.current.inFlightSince=a,tA.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),tM.current===i&&(tM.current=null);try{let e=tA.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{}}})(),tM.current=i,i.promise},[]),ri=!K&&!V&&!e2&&0===tm.length&&0===tf.length;(0,i.useEffect)(()=>{let e=t?.id;if(!e||!ri)return;let n=!1,r=null,i=()=>!n&&"hidden"===document.visibilityState&&!t$.current&&tD.current===e&&tB.current===e&&!t_.current&&!tZ.current,s=async()=>{if(r=null,tz.current=null,!i())return;let t=await rr(e);if(i()){if(!("unanswered"===t||t&&!ix(t)))return void a();t$.current=!0,tL.current={count:tL.current.count+1,lastAt:Date.now()},re("released")}},a=()=>{null===r&&(r=setTimeout(()=>void s(),ib.P),tz.current=Date.now()+ib.P)},o=()=>{"hidden"===document.visibilityState?a():r&&(clearTimeout(r),r=null,tz.current=null)};return"hidden"===document.visibilityState&&a(),document.addEventListener("visibilitychange",o),()=>{n=!0,r&&clearTimeout(r),tz.current=null,document.removeEventListener("visibilitychange",o)}},[re,ri,tE,rr,t?.id]);let rs=(0,i.useCallback)(async(e,t)=>{let n=tD.current;if(tg(t=>rJ(t,e.id)),n)try{await r2(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e)}},[]),ra=(0,i.useCallback)(async(e,t)=>{let n=tD.current;if(n)try{await r2(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),ro=(0,i.useCallback)(e=>{let t=e.message.trim();t&&tu({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"}})},[]),rl=(0,i.useRef)(e.t);rl.current=e.t;let rd=(0,i.useCallback)((e,t)=>rl.current(e,t),[]),rc=(0,i.useCallback)(()=>{ro({type:"warning",message:rd("chat.sendUnconfirmed")})},[ro,rd]),ru=(0,i.useCallback)(e=>{nf.current&&M(t=>iI(t,e.bubble));let t=r7(e.sid);t?.messages.includes(e.bubble)&&ie({...t,messages:iI(t.messages,e.bubble)})},[]),rp=(0,i.useCallback)((e,t,n)=>{let r=nd.current;if(!r||r.runId!==t||r.sid!==e)return;nd.current=null;let i=nu.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&&i$(s.messages.slice(a),r.key)>r.sameTextAfterSend||(nH(r.message,r.images,r.draftKey),s&&ru(r),ro(s&&!r.command&&a===s.entryIds.length?{type:"error",message:rd("chat.sendNotReceived")}:{type:"warning",message:rd("chat.sendUnconfirmed")}))},[ro,ru,nH,rd]),rh=(0,i.useCallback)(()=>{let e=nd.current;if(nd.current=null,e){if(e.parkedDraftKey){let t=e.images?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});nz(e.parkedDraftKey,e.message,t)}else nH(e.message,e.images,e.draftKey);ru(e)}},[ru,nH]),rm=(0,i.useRef)(rh);rm.current=rh;let rg=(0,i.useCallback)(t=>{switch(rZ(t)&&l?.(t),t.method){case"select":case"confirm":case"input":case"editor":tg(e=>e.some(e=>e.id===t.id)?e:[...e,t]);break;case"notify":ro({id:t.id,message:t5(t.message),type:t.notifyType??"info"});break;case"setStatus":tv(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":tj(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=t5(t.title));break;case"set_editor_text":e.chatInputRef?.current?.insertText(t5(t.text));break;case"custom":tx(e=>{let n;return t.closed?rJ(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)})}},[ro,l,e.chatInputRef]),rf=(0,i.useCallback)(()=>{let e=t_.current;return t_.current=!1,Z(!1),tt(null),eO(null),A(new Map),q({type:"end"}),e},[q]),rx=(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 tK.current!==e&&(tK.current=e,a?.({aborted:t,...n?{subagentsActive:n}:{}}),!0)},[a]),rb=(0,i.useCallback)(e=>{if(tB.current===e)return void n7();n7(),tI.current=!0;let t=tN.current,n=async()=>{if(t===tN.current&&tD.current===e&&tI.current)try{let r=await fetch(r1(e));if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(t!==tN.current||tD.current!==e||!tI.current)return;let s=i.state;if(nD(s),i.running&&s&&(s.isStreaming||s.isPromptRunning)){tI.current=!1,tC.current=null,tO.current=null,tU.current=!!s?.isStreaming,tq.current=!!s?.isPromptRunning,t_.current=!0,Z(!0),tt(e=>rK(e,!!s?.isStreaming));return}if(i.running&&s?.isCompacting){e4(!0),tC.current=setTimeout(()=>void n(),600),tO.current=Date.now()+600;return}tI.current=!1,tC.current=null,tO.current=null,re("grace_end")}catch{if(t!==tN.current||tD.current!==e||!tI.current)return;tC.current=setTimeout(()=>void n(),600),tO.current=Date.now()+600}};tC.current=setTimeout(()=>void n(),3e4),tO.current=Date.now()+3e4},[n7,re,nD]),rv=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tD.current,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ns.current;if(ns.current!==t)return;let n=nc.current;try{e&&await nX(e)}finally{if(ns.current!==t)return;e&&rp(e,t,n);let r=tq.current,i=tU.current;tq.current=!1,tU.current=!1,na.current=null;let s=rf();r?rx(t):i&&s&&a?.({aborted:!1}),e&&rb(e)}},[nX,rx,a,rb,rf,rp]),ry=(0,i.useCallback)(async(e,t)=>{await iA(800);let n=Date.now();for(;t_.current&&Date.now()-n<2e4;){if(void 0!==t&&ns.current!==t)return;try{let n=await fetch(r1(e));if(n.ok){let r=await n.json(),i=r.state;if(nD(i),!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await rv(e,t)}}catch{}await iA(600)}},[rv,nD]),rj=(0,i.useCallback)(async e=>{let t=tV.current+1;for(tV.current=t;tZ.current&&tV.current===t&&tD.current===e;){await iA(1e3);try{let n=await fetch(r1(e));if(!n.ok)continue;let r=await n.json();if(nD(r.state),r.state?.isBashRunning)continue;if(await nX(e),tV.current!==t||tD.current!==e)return;tZ.current=!1,J(!1),Y(null);return}catch{}}},[nX,nD]),rk=(0,i.useCallback)(async e=>{if(!t_.current||tD.current!==e)return;let t=ns.current,n=++eH.current;try{let r=await fetch(r1(e));if(!r.ok)return;let i=await r.json();if(tD.current!==e||ns.current!==t)return;let s=i.state;if(nG(s,e,t,n),nD(s),e4(s?.isCompacting??!1),e6(s?.autoCompactionEnabled??!0),tw(iE(s?.queuedMessages)),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isCompacting)){tU.current=!!s.isStreaming,tq.current=!!s.isPromptRunning;return}if(!t_.current)return;s&&(void 0!==s.extensionStatuses&&tv(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tj(s.extensionWidgets??[]),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(t=>{t&&nf.current&&tD.current===e&&t.state?.systemPrompt!==void 0&&eq(t.state.systemPrompt??null)}).catch(()=>{})),await rv(e,t)}catch{}},[nG,rv,nD]);(0,i.useEffect)(()=>{if(!K)return;let e=()=>{let e=tD.current;e&&rk(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)}},[K,rk]),(0,i.useEffect)(()=>{t_.current=K},[K]),tJ.current=(0,i.useCallback)(e=>{switch(e.type){case"connected":if(q({type:"end"}),Array.isArray(e.pendingExtensionUiIds)){let t=new Set(e.pendingExtensionUiIds);tg(e=>rV(e,t)),tx(e=>rV(e,t))}!0===e.isStreaming&&(n7(),tU.current=!0,t_.current=!0,Z(!0),tt({kind:"waiting_model"})),tD.current&&nY(tD.current);break;case"agent_start":np(),n7(),tU.current=!0,t_.current=!0,Z(!0),tt({kind:"waiting_model"}),eO(null),q({type:"start"});break;case"agent_end":if(!t_.current)break;if(tt(null),eO(null),q({type:"end"}),tD.current){let e=tD.current,t=ns.current,n=++eH.current;nX(e),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(r=>{r&&nf.current&&tD.current===e&&ns.current===t&&(nD(r.state),nG(r.state,e,t,n),r.state?.systemPrompt!==void 0&&eq(r.state.systemPrompt??null),r.state?.extensionStatuses!==void 0&&tv(r.state.extensionStatuses??[]),r.state?.extensionWidgets!==void 0&&tj(r.state.extensionWidgets??[]),tw(iE(r.state?.queuedMessages)))}).catch(()=>{})}break;case"agent_settled":{let t=tU.current;if(tU.current=!1,!t||tq.current)break;let n=tD.current,r=rf();e4(!1),n&&(nX(n),rb(n)),r&&a?.({aborted:!0===e.aborted,...!0===e.subagentsActive?{subagentsActive:!0}:{}});break}case"prompt_done":{np();let t=ns.current,n=tq.current;tq.current=!1,na.current=null;let r=rx(t,!0===e.aborted,!0===e.subagentsActive);if(!n&&!r)break;let i=tD.current;i&&nX(i),!tU.current&&(rf(),i&&rb(i))}break;case"prompt_error":ro({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":ro({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":if(!t_.current||iy(e))break;if("message_start"===e.type){let t=e.message;if(t?.role==="user")break;t?.role==="assistant"?(q({type:"snapshot",message:t}),t.content.length>0&&tt(null)):t&&tt(null)}else{let t=e.assistantMessageEvent;t&&(q({type:"delta",event:t}),"toolcall_start"!==t.type&&"toolcall_delta"!==t.type&&tt(null))}!tX.current&&tQ.current&&null===t1.current&&(t1.current=requestAnimationFrame(()=>{t1.current=null,tQ.current&&nT("auto")}));break;case"message_end":{if(!t_.current||iy(e))break;let t=e.message;if(t&&"user"===t.role){let e=rY(t),n=ip(e),r=na.current;na.current=null,r&&np(),M(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&ip(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]})}else if(t){let n=Array.isArray(e.transcriptNotices)?e.transcriptNotices:void 0;if(M(e=>[...e,(0,ik.mO)(rY(t),n)]),"assistant"===t.role){let e=tD.current;e&&nY(e)}}q({type:"end"}),tt({kind:"waiting_model"});break}case"tool_execution_start":{if(iv(e))break;let t=e.toolCallId,n=e.toolName;tt(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[];return r.some(e=>e.id===t)||r.push({id:t,name:n}),{kind:"running_tools",tools:r}});break}case"tool_execution_update":{if(iv(e))break;let t=e.toolCallId,n=e.toolName,r=e.partialResult,i=r?.content;Array.isArray(i)&&("bash"===n||"powershell"===n||n===nl.sp||(0,nm.G)(r?.details))&&A(e=>{let s=new Map(e);return s.set(t,{role:"toolResult",toolCallId:t,toolName:n,content:i,isError:r?.isError,details:r?.details}),s});let s=n===nl.sp?(0,nl.ky)(e.partialResult):function(e){if(!ij(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>ij(e)&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n").split(/\r?\n/),r="";for(let e=n.length-1;e>=0&&!(r=n[e].trim());e-=1);if(!r)return null;let i=r.replace(/\s+/g," ");return i.length<=500?i:`...${i.slice(-497)}`}(e.partialResult);tt(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[],i=r.find(e=>e.id===t),a={id:t,name:n||i?.name||"tool",progress:s??i?.progress};return{kind:"running_tools",tools:[...r.filter(e=>e.id!==t),a]}});break}case"tool_execution_end":{if(iv(e))break;let t=e.toolCallId;o?.(e.toolName),A(e=>{if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}),tt(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"queue_update":np(),tw({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":eO({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":eO(null);break;case"auto_compaction_start":case"compaction_start":e4(!0),e5(null),e7(null);break;case"auto_compaction_end":case"compaction_end":e4(!1),e.errorMessage?(e5(e.errorMessage),e7(null)):!e.aborted&&(e7(iz(e.result,e.reason??"auto")),tD.current&&nX(tD.current));break;case"extension_ui_request":rg(e);break;case"extension_ui_closed":tg(t=>rJ(t,e.id))}},[ro,nG,n7,q,rg,nX,np,rx,a,o,nY,rb,nT,rf,nD]);let rw=(0,i.useCallback)(async(e,n)=>{let i=e.trim();if(!i&&!n?.length)return;if(t_.current||tZ.current)return void nH(e,n,nF);if(n_&&(nK(null),!await t4.current?.(n_))){nK(n_),nH(e,n,nF);return}let s=!n?.length&&i.startsWith("/");if(!n?.length&&i.startsWith("!")){let t=i.startsWith("!!"),r=(t?i.slice(2):i.slice(1)).trim();return r?void await t2.current?.(r,t):void nH(e,n,nF)}let a=ns.current+1;n7(),tq.current=!0;let o=n?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),l={role:"user",content:o?.length?[...e.trim()?[{type:"text",text:e}]:[],...o]:e,timestamp:Date.now()},d=ip(l),c=ny.current,u=c.at(-1)??null,p=i$(nv.current.slice(c.length),d);M(e=>[...e,l]),na.current=d,ns.current=a,t_.current=!0,Z(!0),tt(s?{kind:"running_command"}:{kind:"waiting_model"}),q({type:"start"}),tX.current=!0,tr(!0);let h=()=>{M(e=>{let t=e.lastIndexOf(l);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),na.current=null},m=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),g=null,f=!1;try{if(y&&r){let t=tD.current??await t6.current,n=t??await n2();if(!n)throw Error("Unable to create a session for the prompt");g=n,ev&&(eQ(ev),t&&await r2(n,{type:"set_model",provider:ev.provider,modelId:ev.modelId})),nf.current&&await rt(n).catch(e=>{if(nf.current)throw e}),f=!0;let r=await r2(n,{type:"prompt",message:e,...m?.length?{images:m}:{}});r?.queued&&h(),n1(1,e)}else if(t){g=t.id,await rt(t.id),f=!0;let n=await r2(t.id,{type:"prompt",message:e,...m?.length?{images:m}:{}});n?.queued&&h()}else throw Error("No active session for the prompt");eo(null),s&&g&&ry(g,a)}catch(t){if(console.error("Failed to send message:",t),!(!f||r0(t))&&g){no.current!==a&&(nd.current={runId:a,sid:g,message:e,images:n,draftKey:nF,parkedDraftKey:y&&r?n$(r):null,lastEntryIdAtSend:u,sameTextAfterSend:p,bubble:l,key:d,command:s},nf.current||rh()),ry(g,a);return}if(tq.current=!1,M(e=>iI(e,l)),t instanceof rQ&&t.missingCwd?eo(t.missingCwd):ro({type:"error",message:t instanceof Error?t.message:String(t)}),nH(e,n,nF),na.current=null,g)return void rk(g);t_.current=!1,re("send_failed"),Z(!1),tt(null),q({type:"end"})}},[y,r,ev,t,n2,rt,n1,ry,ro,rh,n7,re,nF,q,rk,nH,n_,nK]);t2.current=(0,i.useCallback)(async(e,n)=>{if(t_.current||tZ.current)return;let r=`${n?"!!":"!"}${e}`;tZ.current=!0,Y({command:e,excludeFromContext:n}),J(!0);try{let i=tD.current??t?.id??await n2();if(!i)throw Error("Unable to create a session for the shell command");await r2(i,{type:"bash",command:e,excludeFromContext:n}),await nX(i),n1(1,r)}catch(e){console.error("Failed to execute shell command:",e),ro({type:"error",message:e instanceof Error?e.message:String(e)}),nH(r,void 0,nF)}finally{tZ.current=!1,Y(null),J(!1)}},[ro,nF,n2,nX,n1,nH,t]);let rS=(0,i.useCallback)(t=>{let n=[...t?.steering??[],...t?.followUp??[]].join("\n\n");t?.images?.length?nH(n,t.images,nF):n&&e.chatInputRef?.current?.prependText(n)},[nF,e.chatInputRef,nH]),rC=(0,i.useCallback)(async()=>{let e=tD.current;if(e){if(tZ.current){try{await r2(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{rS(await r2(e,{type:"abort"}))}catch(e){console.error("Failed to abort:",e)}}},[rS]),rN=(0,i.useCallback)(async e=>{if(tZ.current)return;let t=tD.current;if(t){eZ(e);try{let{cancelled:n,newSessionId:r}=await r2(t,{type:"fork",entryId:e})??{};!n&&r&&c?.(r)}catch(e){console.error("Fork failed:",e),ro({type:"error",message:e instanceof Error?e.message:String(e)})}finally{eZ(null)}}},[ro,c]),rI=(0,i.useCallback)(async e=>{if(tZ.current)return!1;let t=tD.current;if(!t)return!1;try{let n=await r2(t,{type:"navigate_tree",targetId:e});if(n?.cancelled||tD.current!==t)return!1;return await nX(t),tD.current===t}catch(e){return console.error("Failed to navigate:",e),!1}},[nX]);t4.current=rI;let r$=(0,i.useCallback)(async e=>{if(tZ.current||t_.current||e2)return;E(e);let t=tD.current;t&&(await nQ(t,e),e&&r2(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[e2,nQ]),rE=(0,i.useCallback)(async(e,t)=>{if(y){let n={provider:e,modelId:t};nt.current=n,ey(n),eQ(n),null===nn.current&&eE(iT(nr.current[`${e}/${t}`])??ni.current);let r=tD.current??await t6.current;if(!r)return;try{await r2(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tD.current;if(!n||nh.current)return;nh.current=!0,eJ({provider:e,modelId:t}),e1(!0);let r=t_.current||tZ.current,i=async()=>{let e=await fetch(r1(n)).catch(()=>null),t=e?.ok?await e.json().catch(()=>null):null;t?.state&&nf.current&&tD.current===n&&nD(t.state)};try{let s=await r2(n,{type:"set_model",provider:e,modelId:t});eY({provider:s.provider,modelId:s.id}),nh.current=!1,r?(eJ(null),await i()):await nX(n)}catch(e){console.error("Failed to set model:",e),nh.current=!1,eJ(eV),ro({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),r?await i():await nX(n,!1,!0)}finally{nh.current=!1,e1(!1)}},[ro,eV,y,nX,ey,nD]),rT=(0,i.useCallback)(async e=>{let t=tD.current;if(!t||e2)return!0;e4(!0),e5(null),e7(null);try{let n=await r2(t,{type:"compact",...e?{customInstructions:e}:{}});return e7(iz(n,"manual")),await nX(t,!0)&&n1(),!0}catch(e){return e5(e instanceof Error?e.message:String(e)),e7(null),!1}finally{e4(!1)}},[e2,nX,n1]),rM=(0,i.useCallback)(()=>e5(null),[]),rR=(0,i.useCallback)(async e=>{let n,i=r??t?.cwd??"",s=i?`/api/models?cwd=${encodeURIComponent(i)}`:"/api/models",a=null;try{let t=await fetch(s,e?{signal:e}:void 0);if(!t.ok){let e="";try{let n=await t.json();n&&"object"==typeof n&&"error"in n&&"string"==typeof n.error&&(e=n.error),a=rX(n)}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw e}throw Error(e||`Failed to load models (HTTP ${t.status})`)}n=await t.json(),e?.throwIfAborted()}catch(t){throw e?.aborted||t instanceof DOMException&&"AbortError"===t.name||(es(a),er(a?null:t instanceof Error?t.message:String(t))),t}es(null),Q(n.models),er(n.modelError??null),ed(n.modelScopeWarnings??[]),eu(!!n.isScoped),eh(null),em.current=null,ef(n.thinkingLevels??{}),eb(n.thinkingLevelMaps??{});let o=n.modelList??[];et(o);let l=n.defaultModel?o.find(e=>e.id===n.defaultModel?.modelId&&e.provider===n.defaultModel?.provider):void 0;if(ek(l?{provider:l.provider,modelId:l.id}:null),nr.current=n.thinkingLevelPins??{},ni.current=iT(n.defaultThinkingLevel),eM(iT(n.savedDefaultThinkingLevel)),y&&!tD.current){let e=nt.current,t=e&&(0===o.length||!!n.isScoped||o.some(t=>t.provider===e.provider&&t.id===e.modelId));e&&!t&&(nt.current=null,ey(null));let r=t?e:l&&{provider:l.provider,modelId:l.id},i=r&&n.thinkingLevelPins?.[`${r.provider}/${r.modelId}`];null===nn.current&&eE(iT(i)??ni.current)}},[y,r,t?.cwd]),rA=(0,i.useCallback)(()=>{if(em.current)return;let e={};em.current=e;let n=r??t?.cwd??"";fetch(`/api/models?scope=all${n?`&cwd=${encodeURIComponent(n)}`:""}`).then(async t=>{if(!t.ok)throw Error(`Failed to load models (HTTP ${t.status})`);let n=await t.json();em.current===e&&(Q(e=>({...n.models,...e})),ef(e=>({...n.thinkingLevels,...e})),eb(e=>({...n.thinkingLevelMaps,...e})),eh(n.modelList??[]))}).catch(t=>{em.current===e&&(em.current=null,ro({type:"error",message:t instanceof Error?t.message:String(t)}))})},[ro,r,t?.cwd]);(0,i.useEffect)(()=>{!ec||!nL||ep||ee.some(e=>e.provider===nL.provider&&e.id===nL.modelId)||rA()},[ep,nL,ec,rA,ee]);let rL=(0,i.useCallback)(async e=>{let n=r??t?.cwd,i=await fetch("/api/models/default",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...n?{cwd:n}:{},...e})});if(i.ok)return;let s="";try{let e=await i.json();e&&"object"==typeof e&&"error"in e&&"string"==typeof e.error&&(s=e.error)}catch{}throw Error(s||`HTTP ${i.status}`)},[r,t?.cwd]),rP=(0,i.useCallback)(()=>{rR().catch(()=>{})},[rR]),rz=(0,i.useCallback)(async(e,t)=>{try{await rL({provider:e,modelId:t})}catch(e){ro({type:"error",message:`Failed to save default model: ${e instanceof Error?e.message:String(e)}`});return}ro({type:"success",message:`Default model: ${e}/${t}`}),ek({provider:e,modelId:t}),(nL?.provider!==e||nL?.modelId!==t)&&await rE(e,t),rP()},[ro,nL,rE,rP,rL]),rO=(0,i.useCallback)(async(t,n)=>{let r=e.session?.relation?.kind;if("side"===r||"subagent"===r)return rd(r4[r]);let i=tD.current;if(!i)return rd("sideChat.error.noSession");let s=await r8(i,rd,n);return"error"in s?s.error:(u?.(s.session,t),null)},[u,e.session?.relation?.kind,rd]),rW=(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=tD.current??await n2(),o=e=>(e.handled&&(e.error?ro({type:"error",message:e.error}):e.action||ro({type:"success",message:e.message??"Command completed"})),e);try{switch(r){case"compact":if(!a||e2)return o({handled:!0,error:"No active session to compact"});return rT(s||void 0).then(t=>{!t&&s&&e.chatInputRef?.current?.prependText(`/compact ${s}`)}),o({handled:!0,action:"compact"});case"auto-compact":{if(!a)return o({handled:!0,error:"No active session"});let e=await r2(a,{type:"get_state"}),t=!(e?.autoCompactionEnabled??!0);return await r2(a,{type:"set_auto_compaction",enabled:t}),e6(t),o({handled:!0,message:t?"Auto-compaction enabled":"Auto-compaction disabled"})}case"reload":if(!a)return o({handled:!0,error:"No active session to reload"});return await r2(a,{type:"reload"}),await Promise.all([nX(a,!1,!0),n0(a),n5(),rR()]),o({handled:!0,message:"Reloaded session resources"});case"name":if(!a)return o({handled:!0,error:"No active session to name"});if(!s)return o({handled:!0,error:"Usage: /name <name>"});return await r2(a,{type:"set_session_name",name:s}),await nX(a)&&n1(),o({handled:!0,message:`Session renamed to ${s}`});case"session":{if(!a)return o({handled:!0,error:"No active session"});if(!x)return o({handled:!0,message:function(e){if(!e)return"No usage yet";let t=id(e.cost);return[`${e.totalMessages} messages`,`${il(e.tokens.total)} tokens`,...t?[t]:[]].join(" \xb7 ")}(nJ)});let e=await r2(a,{type:"get_session_stats"});return e&&th(e),x(),o({handled:!0,action:"openSessionStats"})}case"mcp":{if(s||!b)return{handled:!1};let e=await n9();if(!e||!(e.some(nU)||!e.some(e=>"mcp"===e.name)))return{handled:!1};return b("mcp"),o({handled:!0,action:"openSettings"})}case"copy":{if(!a)return o({handled:!0,error:"No active session"});let e=await r2(a,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return o({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),o({handled:!0,message:"Copied last assistant message"})}case"clone":{if(!a)return o({handled:!0,error:"No active session to clone"});if(t_.current||tZ.current)return o({handled:!0,error:"Cannot clone while the session is running"});let e=await r2(a,{type:"clone",leafId:$});if(e?.cancelled||!e?.newSessionId)return o({handled:!0,error:"Cannot clone an empty or unsaved session"});let t=o({handled:!0,message:"Cloned current session branch"});return c?.(e.newSessionId),t}case"side":{let e=await rO(s||null);return o(e?{handled:!0,error:e}:{handled:!0,action:"openSideChat"})}default:return{handled:!1}}}catch(e){return o({handled:!0,error:e instanceof Error?e.message:String(e)})}},[$,ro,n2,rT,e2,rR,nX,n5,n0,n1,b,c,x,e.chatInputRef,nJ,n9,rO]),rF=(0,i.useCallback)(async(e,t,n)=>{let r=tD.current;if(n_)return void nH(e,n,nF);if(!r){nH(e,n,nF),ro({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 r2(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){if(console.error("Failed to submit streaming prompt:",t),nH(e,n,nF),t instanceof rQ&&t.missingCwd)return void eo(t.missingCwd);r0(t)?ro({type:"error",message:t.message}):rc()}},[ro,rc,nF,n_,nH]),rD=(0,i.useCallback)(async(e,t)=>{await rF(e,"steer",t)},[rF]),rB=(0,i.useCallback)(async(e,t,n)=>{await rF(e,t,n)},[rF]),rH=(0,i.useCallback)(async(e,t)=>{await rF(e,"followUp",t)},[rF]),r_=(0,i.useCallback)(async()=>{let e=tD.current;if(e)try{await r2(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),rU=(0,i.useCallback)(async()=>{let e=tD.current;if(e)try{let t=await r2(e,{type:"clear_queue"});tw({steering:[],followUp:[]}),rS(t)}catch(e){console.error("Failed to recall queued messages:",e),ro({type:"error",message:"Failed to recall queued messages"})}},[ro,rS]),rq=(0,i.useCallback)(async e=>{if("auto"===e){nn.current=null,eI(null),eA(null);return}y?(nn.current=e,eI(e)):eA(e);let t=tD.current??await t6.current;if(t)try{await r2(t,{type:"set_thinking_level",level:e}),nf.current&&tD.current===t&&(eP(e),eA(null))}catch(e){console.error("Failed to set thinking level:",e),eA(null)}},[y]),rG=(0,i.useCallback)(async e=>{try{await rL({thinkingLevel:e})}catch(e){ro({type:"error",message:`Failed to save default reasoning level: ${e instanceof Error?e.message:String(e)}`});return}ro({type:"success",message:`Default reasoning level: ${e}`}),eM(e),nW!==e&&await rq(e),rP()},[ro,nW,rq,rP,rL]),r6=(0,i.useCallback)(async e=>{let t=(0,ir.xG)(e);!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:is();if(t)try{t.setItem(ii,e)}catch{}}(e),nN(e);let n=tD.current??await t6.current;if(!n){tH.current=void 0!==t;return}try{let e=await r2(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});tH.current=void 0!==t;let r=e?.sessionId??n;(r!==n||e?.recreated)&&(n7(),re("set_tools"),tg([]),tx([]),tD.current=r,e?.recreated&&tB.current===r&&rn(r)),n6(),tv([]),tj([]);let[i]=await Promise.all([r2(r,{type:"get_state"}),n0(r)]);nf.current&&tD.current===r&&(eq(i.systemPrompt??""),nD(i))}catch(e){console.error("Failed to set tools:",e)}},[n7,n6,re,n0,rn,nN,nD]),r3=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=t8.current;n&&(null!==t1.current&&(cancelAnimationFrame(t1.current),t1.current=null),tG.current=!0,tX.current=!1,tQ.current=!1,tr(!1),n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),t0.current=n.scrollTop)},[]),r5=(0,i.useCallback)(()=>{let e=t8.current,t=tY.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!==t1.current&&(cancelAnimationFrame(t1.current),t1.current=null),tQ.current=!0,t0.current=n,e.scrollTo({top:n,behavior:"auto"})},[]),r9=(0,i.useCallback)(()=>{let e=t8.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=t_.current,s=tQ.current,a=function(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:96;return!!iw(n,r,i)||!(n<t)&&(!!(!e&&n>t&&iw(n,r,i,s))||e)}(s,t0.current,t,n,r,i?96:8);tQ.current=a,t0.current=t;let o=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return!(n<=t)&&!iw(e,t,n,r)}(t,n,r);ts(e=>e===o?e:o),!s&&a&&i?nT("auto"):a||null===t1.current||(cancelAnimationFrame(t1.current),t1.current=null)}},[nT]),ia=(0,i.useCallback)((e,t)=>{t?.running&&(n0(e),(t.state?.isStreaming||t.state?.isPromptRunning)&&(tU.current=!!t.state.isStreaming,tq.current=!!t.state.isPromptRunning,t_.current=!0,Z(!0),tt(e=>rK(e,t.state?.isStreaming===!0)),q({type:"resume"}),!t.state.isStreaming&&t.state.isPromptRunning&&ry(e)),t.state?.isBashRunning&&(tZ.current=!0,J(!0),rj(e))),t?.state&&(void 0!==t.state.isCompacting&&e4(t.state.isCompacting),void 0!==t.state.systemPrompt&&eq(t.state.systemPrompt??null),void 0!==t.state.extensionStatuses&&tv(t.state.extensionStatuses??[]),void 0!==t.state.extensionWidgets&&tj(t.state.extensionWidgets??[]),void 0!==t.state.queuedMessages&&tw(iE(t.state.queuedMessages)))},[q,n0,rj,ry]);tR.current=(e,t)=>{!t$.current||(t$.current=!1,tP.current={count:tP.current.count+1,lastAt:Date.now(),lastReason:t},tT(e=>e+1),nf.current&&tD.current===e&&tB.current===e&&(rn(e),nX(e,!1,!0).then(t=>{nf.current&&tD.current===e&&ia(e,t)})))},(0,i.useEffect)(()=>{let e=t?.id;if(!e)return;let n=!1,r=tA.current,i=async()=>{let t=await rr(e);!n&&"hidden"===document.visibilityState&&ix(t)&&tR.current(e,"activity")};i();let s=setInterval(()=>void i(),3e4);r.renewStartedAt=Date.now();let a=()=>{"visible"===document.visibilityState&&(tR.current(e,"visible"),i())};return document.addEventListener("visibilitychange",a),()=>{n=!0,clearInterval(s),r.renewStartedAt=null,document.removeEventListener("visibilitychange",a)}},[rr,t?.id]),(0,i.useEffect)(()=>{if(nf.current=!0,e_.current=eH.current,t){tD.current=t.id;let e=r7(t.id);e&&(w({sessionId:t.id,filePath:"",totalActiveMs:e.totalActiveMs??0,tree:e.summaryTree,leafId:e.leafId,context:{messages:e.messages,entryIds:e.entryIds,oldestEntryId:e.oldestEntryId,hasMore:e.hasMore,turnsBefore:e.turnsBefore,thinkingLevel:e.thinkingLevel,model:e.model},stats:e.stats}),E(e.leafId),M(e.messages),P(e.entryIds),F(e.oldestEntryId),B(e.hasMore),_(e.turnsBefore),I(null),C(!1)),nX(t.id,!e,!0,{force:!0}).then(e=>{ia(t.id,e)})}return()=>{nf.current=!1;let e=y?s:null;e&&queueMicrotask(()=>{nf.current||ne.current||nA(e)});let t=tD.current,n=nb.current;if(t&&n&&n.sessionId===t&&n.snapshotRevision){let e=r7(t),r=ny.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)?ie({sessionId:t,revision:n.snapshotRevision,messages:nv.current,entryIds:ny.current,leafId:nj.current,oldestEntryId:nk.current,hasMore:nw.current,turnsBefore:nS.current,summaryTree:n.tree,thinkingLevel:n.context.thinkingLevel,model:n.context.model,stats:n.stats,totalActiveMs:n.totalActiveMs,loadedEntryIds:ny.current}):it(t)}rm.current(),null!==t1.current&&(cancelAnimationFrame(t1.current),t1.current=null),tV.current+=1,n7(),re()}},[]),(0,i.useEffect)(()=>{m?.(eU)},[eU,m]),(0,i.useEffect)(()=>(f?.(n4),()=>f?.(null)),[n4,f]);let ic=(0,i.useCallback)(()=>{let e=null;try{e=tS.current?.snapshot?.()??null}catch{e=null}let t=tD.current,n=tA.current,r=tP.current;return{pageId:(0,eN.kz)(),sessionId:t,selectedSessionId:tB.current,mounted:nf.current,wantsStream:null!==t&&nC(t),connection:e,released:{active:t$.current,...tL.current},reattached:{...r},hiddenReleaseDueAt:tz.current,hiddenGraceMs:ib.P,graceDueAt:tO.current,run:{agentRunning:t_.current,bashRunning:tZ.current,compacting:tW.current,dialogs:tF.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}}}}},[nC]);(0,i.useEffect)(()=>(v?.(ic),()=>v?.(null)),[ic,v]);let iu=K||V||e2;(0,i.useEffect)(()=>{h&&h(k?.tree??[],$,r$,iu)},[k?.tree,$,r$,iu,h]),(0,i.useEffect)(()=>{let e=t8.current;if(e)return t0.current=e.scrollTop,e.addEventListener("scroll",r9,{passive:!0}),()=>{e.removeEventListener("scroll",r9)}},[T.length,S,r9]),(0,i.useEffect)(()=>{K||tr(!1)},[K]),(0,i.useLayoutEffect)(()=>{T.length>0&&(tX.current?(tX.current=!1,tG.current=!0,r5()):tG.current?!t_.current&&tQ.current&&nT("auto"):(tG.current=!0,nT("instant")))},[T.length,K,nT,r5]),(0,i.useEffect)(()=>{let e=new AbortController;return(async()=>{for(let t=0;;t++)try{await rR(e.signal);return}catch(n){if(e.signal.aborted||n instanceof DOMException&&"AbortError"===n.name||t>=iR.length||(await iA(iR[t]),e.signal.aborted))return}})(),()=>e.abort()},[rR,p]),(0,i.useEffect)(()=>{if(!e9)return;let e=setTimeout(()=>e7(null),6e3);return()=>clearTimeout(e)},[e9]);let[im,iS]=(0,i.useState)(null),iC=(0,i.useRef)(5e3),iL=(0,i.useRef)(null),iO=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(0===tc.visible.length){iO.current=null;return}let e=tc.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{tu({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=tc.visible[0];if(!t||(iO.current!==t.id&&(iO.current=t.id,iC.current=5e3),tc.visible.some(e=>e.id===im)))return;iL.current=Date.now();let n=setTimeout(()=>{tu({type:"mark_oldest_exiting"})},iC.current);return()=>{clearTimeout(n),null!==iL.current&&(iC.current=Math.max(0,iC.current-(Date.now()-iL.current)),iL.current=null)}},[tc.visible,im]),(0,i.useEffect)(()=>{th(null)},[T.length,eW?.tokens,eW?.percent,eW?.contextWindow]);let iW=nW??"auto",iF=tm[0]??null,iD=Math.max(0,tm.length-1),iB=tf[0]??null,iH=Math.max(0,tf.length-1),i_=(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?ih(r,s-e.length):n.get(t)??t)}return i})(L,T.length,z),[L,T.length,z]);return{data:k,loading:S,error:N,activeLeafId:$,messages:T,activeToolResults:R,entryIds:L,messageKeys:i_,historyCursor:W,hasEarlierMessages:D,earlierTurnCount:H,streamingStore:U,agentRunning:K,modelNames:X,modelList:ee,modelError:en,missingCwd:ea??ei,modelScopeWarnings:el,isModelScopeActive:ec,allModelList:ep,modelThinkingLevels:eg,modelThinkingLevelMaps:ex,newSessionModel:ev,toolPreset:ew,thinkingLevel:iW,retryInfo:ez,contextUsage:eW,systemPrompt:eU,forkingEntryId:eK,isCompacting:e2,compactError:e3,compactResult:e9,currentModel:nR,displayModel:nL,modelSwitching:e0,sessionStats:nJ,autoCompactionEnabled:e8,slashCommands:ta,slashCommandsLoading:tl,queuedMessages:tk,notices:tc.visible,extensionDialog:iF,waitingExtensionDialogCount:iD,extensionCustomUi:iB,waitingExtensionCustomUiCount:iH,extensionStatuses:tb,extensionWidgets:ty,respondToExtensionUi:rs,sendExtensionCustomInput:ra,isAutoModelSelection:y&&null===ev,isAutoThinkingSelection:y&&null===eC,defaultModel:ej,savedDefaultThinkingLevel:eT,agentPhase:te,isNew:y,editEntryId:n_,promptAnchorActive:tn,showScrollToBottom:ti,sessionIdRef:tD,scrollContainerRef:t8,lastUserMsgRef:tY,pendingScrollToUserRef:tX,initialScrollDoneRef:tG,handleSend:rw,handleAbort:rC,startSideChat:rO,handleFork:rN,handleNavigate:rI,handleModelChange:rE,handleCompact:rT,handleSteer:rD,handleFollowUp:rH,handlePromptWithStreamingBehavior:rB,handleAbortCompaction:r_,dismissCompactError:rM,handleRecallQueue:rU,handleBuiltinSlashCommand:rW,handleEditContent:nZ,cancelEdit:n_?nV:void 0,addNotice:ro,setNoticePaused:iS,handleToolPresetChange:r6,handleThinkingLevelChange:rq,handleSetDefaultModel:rz,handleSetDefaultThinkingLevel:rG,loadTools:n0,loadSlashCommands:n5,loadAllModels:rA,setActiveLeafId:E,setData:w,setMessages:M,loadContext:nQ,scrollToBottom:nT,scrollUserMsgToTop:r5,scrollToMessage:r3,dispatch:q,setAgentRunning:Z,setForkingEntryId:eZ,bashRunning:V,pendingBash:G,handleAgentEventRef:tJ}}({session:o,sessionRunning:h,newSessionCwd:m,newSessionDraftKey:g,initialNewSessionChoices:x,onNewSessionChoicesChange:b,onAgentEnd:et,onToolEnd:y,onAttentionNeeded:j,onSessionCreated:k,onSessionForked:w,onSideSession:C,modelsRefreshKey:N,chatInputRef:I,onBranchDataChange:$,onSystemPromptChange:E,onSystemToolsChange:T,onSystemInfoLoaderChange:M,onSessionStatsPanelOpen:L,onOpenSettings:P,onDebugSnapshotReaderChange:R,t:J,deferInitialScroll:!!er}),tA=iO(ef,iW),tL=iO(ef,iF),tP=(0,i.useCallback)(()=>ef.getState().streamingMessage,[ef]),tz=ex||eb;(0,i.useEffect)(()=>{if(ex&&V)return V()},[ex,V]);let[tO,tW]=(0,i.useState)(null),[tF,tD]=(0,i.useState)(!1),[tB,tH]=(0,i.useState)(!1),[t_,tU]=(0,i.useState)(null),tq=(0,i.useRef)(null),tK=(0,i.useRef)(null),tZ=(0,i.useCallback)(()=>{tW(null),tD(!1),tU(null)},[]);(0,i.useEffect)(()=>{B||tZ()},[B,tZ]);let tV=(0,i.useCallback)(()=>{if(!B||tF)return;let e=window.getSelection(),t=e?.rangeCount?e.getRangeAt(0):null,n=t8.current;if(!e||e.isCollapsed||!t||!n||!n.contains(t.commonAncestorContainer))return void tW(null);let r=e.toString().trim();if(!r)return void tW(null);let i=t.getBoundingClientRect();tW({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,tF]);(0,i.useEffect)(()=>{tF&&tO&&tK.current?.insertIfEmpty(nj(tO.text))},[tF,tO]),(0,i.useLayoutEffect)(()=>{let e=tq.current;if(!e||!tO)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(tO.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(tO.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)}},[tO,tF,t_]),(0,i.useEffect)(()=>{if(!tO)return;let e=e=>{tF||tq.current?.contains(e.target)||tZ()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),tB||tZ())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[tO,tF,tB,tZ]);let tJ=(0,i.useCallback)(()=>{tO&&(I?.current?.insertQuote(nj(tO.text)),tZ())},[I,tO,tZ]),tG=(0,i.useCallback)(async e=>{if(!tB&&e.trim()&&tO){tH(!0),tU(null);try{let t=await td(e,tO.text);if(!t)return void tZ();tK.current?.restoreSubmission(e),tU(t)}catch(t){tK.current?.restoreSubmission(e),tU(t instanceof Error?t.message:String(t))}finally{tH(!1)}}},[tO,tB,tZ,td]),tY=(0,i.useCallback)(async e=>{let t;try{t=await td(e)}catch(e){t=e instanceof Error?e.message:String(e)}t&&(I?.current?.restoreSubmission(e),e8({type:"error",message:t}))},[e8,I,td]),tX=(0,i.useRef)(!1);(0,i.useEffect)(()=>{eo||el||!H||tX.current||(tX.current=!0,_?.(),to(H))},[H,eo,el,to,_]),(0,i.useEffect)(()=>{let e=!!eJ&&!ee.current;ee.current=!!eJ,Y&&e&&X.current()},[Y,eJ]),(0,i.useEffect)(()=>{S||(a=tz?tl:null)},[S,tz,tl]);let[tQ,t0]=(0,i.useState)(50),[t1,t2]=(0,i.useState)(null),t8=(0,i.useRef)(null),t6=(0,i.useRef)(null),t3=(0,i.useRef)(!1),t9=(0,i.useRef)(!1),t7=(0,i.useRef)(er);t7.current=er;let[ne,nt]=(0,i.useState)(null),nn=ed[eu.indexOf(ne?.entryId??"")],nr=nn?.role==="assistant"?ne?.blockIndex===void 0?nn.content.find(e=>"text"===e.type):nn.content[ne.blockIndex]:void 0,ns=(0,i.useRef)({entryIds:eu,historyCursor:eh,hasEarlierMessages:em});ns.current={entryIds:eu,historyCursor:eh,hasEarlierMessages:em};let na=(0,i.useRef)(null),no=(0,i.useCallback)(async(e,t,n)=>{na.current=t;let r=await tE(e,tT,t,n);return r||na.current!==t||(na.current=null),r},[tT,tE]);(0,i.useEffect)(()=>{eh!==na.current&&(na.current=null)},[eh]),(0,i.useLayoutEffect)(()=>{let e=o?.id,t=ti.current,n=t8.current;if(e&&p&&t&&n)return()=>{if(t7.current)return;if(iw(t.scrollTop,t.clientHeight,t.scrollHeight))return void p(e,{atBottom:!0});let r=t.getBoundingClientRect().top,i=function(e,t){let n=e[0];for(let r of e){if(r.top>t)break;n=r}return n?{anchorEntryId:n.entryId,anchorOffset:n.top-t}:null}(Array.from(n.children).flatMap(e=>{if(!(e instanceof HTMLElement)||!e.dataset.entryId)return[];let t=e.getBoundingClientRect();return[{entryId:e.dataset.entryId,top:t.top,bottom:t.bottom}]}),r);i&&p(e,{atBottom:!1,...i,oldestEntryId:ns.current.historyCursor})}},[eo,p,ti,o?.id]),(0,i.useEffect)(()=>{d&&ei(null)},[d]),(0,i.useEffect)(()=>{let e=o?.id;if(!er||!e||eo||d||t9.current)return;t9.current=!0;let t=new AbortController;return(async()=>{let n=ns.current;if(n.entryIds.includes(er.anchorEntryId)){t0(e=>Math.max(e,2*n.entryIds.length)),ea(!0);return}t3.current=!0;let r=n.historyCursor,i=n.hasEarlierMessages;try{for(;i&&r&&!t.signal.aborted;){let n=await no(e,r,{signal:t.signal});if(t.signal.aborted)return;if(!n){tM("instant"),ei(null);return}if(t0(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||(tM("instant"),ei(null))}finally{t3.current=!1}})(),()=>{t.abort(),ei(null)}},[tT,no,eo,er,tM,d,o?.id]),(0,i.useLayoutEffect)(()=>{let e=t8.current;if(!er||!e||d)return;let t=Array.from(e.children).find(e=>e instanceof HTMLElement&&e.dataset.entryId===er.anchorEntryId);if(t instanceof HTMLElement){tR(t,er.anchorOffset),ei(null);return}es&&(tM("instant"),ei(null))},[eu,er,es,tM,tR,d,tQ]),(0,i.useEffect)(()=>{if(!d||eo)return;let e=new AbortController;return(async()=>{let t=ns.current,n=t.entryIds.includes(d.entryId);if(!n&&!tz&&t.hasEarlierMessages&&t.historyCursor&&!t3.current){t3.current=!0;let r=ti.current;r&&(t6.current=r.scrollHeight-r.scrollTop);let i=await no(d.sessionId,t.historyCursor,{tail:200,signal:e.signal});t3.current=!1,n=!!i?.entryIds.includes(d.entryId)}e.signal.aborted||(n?(t6.current=null,t0(e=>Math.max(e,(ns.current.entryIds.length+200)*2)),nt(d)):c?.(d))})(),()=>e.abort()},[d,eo,tz,no,c,ti]),(0,i.useLayoutEffect)(()=>{if(!ne||ne!==d)return;let e=`[data-entry-id="${CSS.escape(ne.entryId)}"]`,t=ti.current?.querySelector(nn?.role==="user"?e:`${e} [data-search-target]`);t&&(tR(t),t.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500})),nt(null),c?.(ne)},[ne,d,nn,ti,tR,c]),(0,i.useEffect)(()=>{let e=ti.current;if(!t1||!e)return;let t=new IntersectionObserver(t=>{if(!t[0]?.isIntersecting||t3.current)return;if(!em){t6.current=e.scrollHeight-e.scrollTop,t0(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50;return e+t})(e));return}if(!eh||eh===na.current)return;let n=o?.id??tr.current;n&&(t3.current=!0,t6.current=e.scrollHeight-e.scrollTop,no(n,eh).finally(()=>{t3.current=!1}))},{root:e,threshold:0});return t.observe(t1),()=>t.disconnect()},[t1,tQ,eh,em,o,no,tr,ti]),(0,i.useEffect)(()=>{t0(e=>Math.max(e,ed.length))},[ed.length]),(0,i.useEffect)(()=>{if(null==t6.current)return;let e=ti.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-t6.current),t6.current=null}},[tQ,ti]);let nd=e_?[e_.sessionId,e_.sessionFile??"",e_.sessionName??"",e_.userMessages,e_.assistantMessages,e_.toolCalls,e_.toolResults,e_.totalMessages,e_.tokens.input,e_.tokens.output,e_.tokens.cacheRead,e_.tokens.cacheWrite,e_.tokens.total,e_.cost??0,e_.totalActiveMs??0].join("|"):null,nc=(0,i.useRef)(e_);nc.current=e_,(0,i.useEffect)(()=>{A?.(nc.current)},[nd,A]),(0,i.useEffect)(()=>()=>{A?.(null)},[A]);let nu=eA?`${eA.percent??"null"}|${eA.contextWindow}|${eA.tokens??"null"}`:null,nk=(0,i.useRef)(eA);nk.current=eA,(0,i.useEffect)(()=>{z?.(nk.current)},[nu,z]),(0,i.useEffect)(()=>()=>{z?.(null)},[z]);let nC=(0,i.useCallback)(async e=>{let t=o?.cwd??m;if(!t)return void e8({type:"warning",message:J("chat.dropNeedsCwd")});try{let{status:n,data:r}=await (0,nw.Zn)(t,e,"skip");if(200!==n&&207!==n)throw Error(r.error??`HTTP ${n}`);let i=r.uploaded??[],s=r.skipped??[],a=(0,nw.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,m,W,o?.cwd,J]),nN=(0,i.useCallback)(e=>{let{images:t,files:n,folders:r}=(0,nw.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&&nC(n)},[e8,I,J,nC]),nI=(0,i.useCallback)(e=>{nN(e.map(e=>({kind:"file",file:e})))},[nN]),{isDragOver:nE,handleDragEnter:nT,handleDragOver:nR,handleDragLeave:nL,handleDrop:nP}=(0,iB.J)(nN),nW=ed.filter(e=>(0,ni.Y0)(e)||"assistant"===e.role),nF=(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]),nD=(0,i.useMemo)(()=>new WeakMap,[]),nB=(0,i.useMemo)(()=>(0,nh.n_)(ed),[ed]),nH=(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]),n_=(t=nW.length,(s=(0,i.useRef)([])).current=Array(t).fill(null).map((e,t)=>s.current[t]??null),s),nq=(0,i.useCallback)(()=>{t0(e=>Math.max(e,2*ed.length))},[ed.length]),nK=te&&0===ed.length&&!tA&&!tz;eB(ti,!!o?.id||!nK);let nZ=o?.cwd??m??void 0,nV=function(e,t,n){let[r,s]=(0,i.useState)(()=>new Map);return(0,i.useEffect)(()=>{let r=ng(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=nx.get(e);if(r)return r;let i=nb.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 nf(e,5),a=new Map;for(let e of i)"toolResult"===e.role&&a.set(e.toolCallId,e);return{files:(r=t??s??n,np(i.flatMap(e=>"assistant"===e.role?e.content??[]:[]),a,r))}}catch{return nb.set(e,Date.now()),null}})();return nx.set(e,s),s.catch(()=>nb.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,nF,nZ),nJ=(0,i.useRef)(null),nG=(0,i.useRef)(0),nY=(0,i.useRef)(null),nX=(0,i.useRef)(!1),nQ=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=nJ.current;if(!ex||!ta){nQ.current=null,nG.current=0,nX.current=!1,e&&(e.style.height="");return}let t=ti.current,n=t8.current,r=ts.current;if(!t||!n||!r||!e)return;let i=!1,s=()=>{var s;let a;if(i||ti.current!==t||t8.current!==n||ts.current!==r||nJ.current!==e)return;let o=t.getBoundingClientRect().top,l=Math.max(0,r.getBoundingClientRect().top-o+t.scrollTop-16),d=e.getBoundingClientRect().top-o+t.scrollTop,c=(s=t.clientHeight,0===(a=Math.max(0,l))?0:Math.max(0,Math.ceil(a+s-Math.max(0,d)))),u=!nX.current;u&&(nX.current=!0),c!==nG.current&&(nG.current=c,e.style.height=c>0?`${c}px`:"",u&&c>0&&t$())};nQ.current=s,s();let a="u"<typeof ResizeObserver?null:new ResizeObserver(()=>{i||null!==nY.current||(nY.current=requestAnimationFrame(()=>{nY.current=null,s()}))});return a?.observe(t),a?.observe(n),a?.observe(r),()=>{i=!0,nQ.current===s&&(nQ.current=null),a?.disconnect(),null!==nY.current&&(cancelAnimationFrame(nY.current),nY.current=null)}},[ex,ts,ed.length,ta,ti,t$]);let n0=(0,i.useCallback)(()=>{nQ.current?.()},[]);(0,i.useLayoutEffect)(n0,[tA,tL,n0]);let n1=eD?e$[`${eD.provider}:${eD.modelId}`]??null:null,n2=eD?eE[`${eD.provider}:${eD.modelId}`]??null:null,n4=(0,r.jsx)(rC,{ref:I,onSend:to,onAbort:tl,onSideChat:C&&!l(o?.relation)?tY:void 0,onSteer:ex?tg:void 0,onFollowUp:ex?tf:void 0,onPromptWithStreamingBehavior:ex?tx:void 0,isStreaming:tz,model:eD,isAutoModelSelection:e6,modelNames:ey,modelList:ej,modelError:ek,missingCwd:ew,modelScopeWarnings:eS,allModelList:eI,onLoadAllModels:eC?tI:void 0,onModelChange:th,modelSwitching:eH,defaultModel:e5,onSetDefaultModel:tS,onCompact:o||te?tm:void 0,onAbortCompaction:tb,isCompacting:eP,compactError:ez,onDismissCompactError:tv,compactResult:eO,toolPreset:eT,onToolPresetChange:o&&!l(o.relation)||te?tk:void 0,thinkingLevel:eM,isAutoThinkingSelection:e3,onThinkingLevelChange:o||te?tw:void 0,availableThinkingLevels:n1,thinkingLevelMap:n2,savedDefaultThinkingLevel:e9,onSetDefaultThinkingLevel:o||te?tC:void 0,retryInfo:eR,queuedMessages:eK,inputHistory:nH,onRecallQueue:ty,slashCommands:eU,slashCommandsLoading:eq,onLoadSlashCommands:tN,onBuiltinCommand:tj,soundEnabled:U,onSoundToggle:q,onAudioUnlock:Z,draftKey:o?.id??g??void 0,cwd:o?.cwd??m,onAttachFiles:nI});return eo?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:J("chat.loadingSession")}):el?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:el}):(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:nT,onDragOver:nR,onDragLeave:nL,onDrop:nP,children:[nE&&(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)(iG,{notices:eV,floating:!0,onPauseChange:e4})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[eJ&&(0,r.jsx)(iQ,{request:eJ,waitingCount:eG,onRespond:e1},eJ.id),eY&&(0,r.jsx)(i0,{request:eY,waitingCount:eX,onInput:e2},eY.id),!nK&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:ti,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:t8,onPointerUp:tV,style:{width:"100%",minWidth:0,maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(()=>{var e;let t,n,s=-1;for(let e=ed.length-1;e>=0;e--)if("user"===ed[e].role){s=e;break}let a=-1;for(let e=ed.length-1;e>=0;e--)if((0,ni.Y0)(ed[e])){a=e;break}let l=new Map,d=0;ed.forEach((e,t)=>{((0,ni.Y0)(e)||"assistant"===e.role)&&l.set(t,d++)});let c=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.messageOverride??ed[e];if("custom"===n.role&&"pi-web:side-boundary"===n.customType)return(0,r.jsx)(iV,{},"side-chat-divider");if((0,ni.zZ)(n))return null;let a=!1===t.withNotices?[]:(0,ik.YQ)(ed[e]),d=(0,ni.Y0)(n)||"assistant"===n.role,c=l.get(e),u=t.keyPrefix??"message",p=ep[e],h=!1;if("assistant"===n.role){h=!0;for(let t=e+1;t<ed.length;t++){let e=ed[t].role;if("user"===e)break;if("assistant"===e){h=!1;break}}h&&tA&&e===ed.length-1&&(h=!1)}void 0!==t.showTimestamp&&(h=t.showTimestamp);let m=(0,r.jsx)(nS.Dx,{message:n,toolResults:nF,modelNames:ey,cwd:nZ,onOpenFile:O,onOpenSubagent:F,onEnterSubagent:D,entryId:eu[e],searchBlock:eu[e]===ne?.entryId?nr:void 0,onFork:eb||te?void 0:tc,forking:eL===eu[e],onEditContent:tz?void 0:tu,onCancelEdit:tp,isEditing:tt===eu[e],showTimestamp:h,prevTimestamp:e>0?ed[e-1].timestamp:void 0,sessionId:o?.id??tr.current??void 0,writtenFiles:t.writtenFiles,turnDurationMs:t.turnDurationMs,onCompact:t.recoverTruncation?tm:void 0,isCompacting:t.recoverTruncation?eP:void 0,compactError:t.recoverTruncation?ez:void 0},`${u}-view-${p}`),g=a.length>0?(0,r.jsx)(iH.yt,{notices:a},`${u}-notices-${p}`):null;return d&&void 0!==c?(0,r.jsxs)("div",{"data-entry-id":eu[e],ref:!1===t.attachRef?void 0:t=>{n_.current[c]=t,e===s&&(ts.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=ed[e],i=(0,ni.Y0)(n);if(!i&&0!==e){u.push(c(e)),e+=1;continue}let s=i?e:-1,o=i?e:0,d=e+1;for(;d<ed.length&&!(0,ni.Y0)(ed[d]);)d+=1;let p=function(e,t,n){for(let i=n-1;i>t;i--){var r;if("assistant"===(r=e[i]).role&&(0,ni.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,s,d);if(-1===p||(tz||tA)&&d===ed.length&&s===a){for(let e=o;e<d;e++)u.push(c(e));e=d;continue}i&&u.push(c(s));let h=i&&eu[s]?(0,ny.G)(ed,s,d):void 0,m=function(e,t){let n=e.get(t);if(n)return n;let{answerBlocks:r}=(0,ni.dQ)(t),i=r.length>0||(0,ni.mc)(t)||(0,ni.PC)(t)?nv(t,r):null,s=t.content.indexOf(r[0]),a={answer:i,process:nv(t,t.content.slice(0,s<0?void 0:s),{omitUsage:!!i})};return e.set(t,a),a}(nD,ed[p]),g=m.answer,f=[],x=0,b=0,v=!1;for(let e=s+1;e<=p;e++){let n=ed[e];if("custom"===n.role){if((0,ni.zZ)(n))continue;v||=!!(ne&&ne.entryId===eu[e]),x+=1,f.push(c(e,{attachRef:!1,keyPrefix:"process"}));continue}if("assistant"!==n.role)continue;let i=e===p?m.process:n,s=e!==p||!g,a=(0,ni.TC)(i);if(0===a.length){let t=s?(0,ik.YQ)(n):[];t.length>0&&f.push((0,r.jsx)(iH.yt,{notices:t},`process-notices-${ep[e]}`));continue}t??=l.get(e),b+=(0,ni._q)(a),x+=1,v||=!!(ne&&eu[e]===ne.entryId&&(!nr||a.includes(nr))),f.push(c(e,{attachRef:!1,keyPrefix:"process",messageOverride:i,showTimestamp:!1,withNotices:s}))}if(0===x)u.push(...f);else if(f.length>0){let e=(0,ni.sE)(g),n=(0,ik.Uv)(ed.slice(s+1,g?p:p+1));u.push((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{n_.current[t]=e},children:(0,r.jsx)(iK,{messageCount:x,toolCallCount:b,durationMs:h,cacheMisses:n,defaultExpanded:!e,reveal:v,t:J,children:f},e?"answered":"unanswered")},`process-group-${ep[o]}`))}if(g){let e=[];for(let t=s+1;t<=p;t++){let n=ed[t];if(n?.role==="assistant")for(let t of n.content??[])e.push(t)}let t=np(e,nF,nZ);for(let e of ng(ed.slice(s+1,p+1),nF))for(let n of nV.get(e.sessionId)??[])t.some(e=>e.filePath===n.filePath)||t.push(n);let n=function(e,t){let n=e.writtenFiles;return n&&n.length===t.length&&n.every((e,n)=>e.filePath===t[n].filePath)?n:(e.writtenFiles=t,t)}(m,t);u.push(c(p,{messageOverride:g,writtenFiles:n,turnDurationMs:0===f.length?h:void 0,recoverTruncation:d===ed.length&&!tA&&!(0,ni.D6)(g)}))}for(let e=p+1;e<d;e++)u.push(c(e));e=d}let{startIndex:p}=(t=Math.min(Math.max(tQ,0),Math.max(e=u.length,0)),{startIndex:n=Math.max(0,e-t),hasMore:n>0}),h=p>0||em;return(0,r.jsxs)(r.Fragment,{children:[h&&(0,r.jsx)("div",{ref:t2,className:"py-3 text-center text-xs text-text-muted",children:J("chat.loadEarlier")}),u.slice(p)]})})(),tA&&tL&&(0,r.jsx)(iJ,{store:ef,onCommit:n0,toolResults:nF,modelNames:ey,cwd:nZ,onOpenFile:O,onOpenSubagent:F,onEnterSubagent:D}),(ex||eP)&&!tL&&(e7||eP)&&(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}(e7,J,eP,(eK?.steering.length??0)+(eK?.followUp.length??0))})}),eb&&!ev&&(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")})}),ev&&(0,r.jsx)(nS.Dx,{message:{role:"bashExecution",command:ev.command,output:"",excludeFromContext:ev.excludeFromContext},sessionId:o?.id??tr.current??void 0,onOpenSubagent:F,onEnterSubagent:D}),(0,r.jsx)("div",{ref:nJ,"aria-hidden":"true"})]})})}),G||er?null:(0,r.jsx)(rD,{messages:ed,getStreamingMessage:tP,scrollContainer:ti,messageRefs:n_,onRevealHistory:nq,turnsBefore:eg})]})]}),B&&tO&&(0,eZ.createPortal)((0,r.jsx)("div",{ref:tq,role:tF?"dialog":"toolbar","aria-label":J(tF?"chat.newQuoteChat":"chat.selectionActions"),style:{position:"fixed",top:tO.top,left:tO.left,zIndex:260,display:"flex",flexWrap:"wrap",gap:3,width:tF?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:tF?12:3,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",boxShadow:"0 2px 10px rgba(0,0,0,0.12)"},children:tF?(0,r.jsxs)("fieldset",{disabled:tB,"aria-busy":tB,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:tB,onClick:tZ,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)(rC,{ref:tK,compact:!0,onSend:tG,onAbort:tZ,isStreaming:!1}),t_&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:t_})]}):(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:tJ,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&&!l(o?.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:()=>{tD(!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:[!nK&&(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${tn&&!er?" is-visible":""}`,title:J("chat.scrollToLatest"),"aria-label":J("chat.scrollToLatest"),onClick:()=>tM("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"})})})}),nK&&(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)(t4.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.15.2"]}),(0,r.jsx)(iq,{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.0"]})]})]})]}),f]})}),(0,r.jsx)(rN.Z,{snapshot:nB}),n4,(0,r.jsx)(rq,{statuses:eQ,widgets:e0,onCommand:to,commandsDisabled:tz})]}),nK&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}function iV(){let{t:e}=(0,eW.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 iJ=(0,i.memo)(function(e){let{store:t,onCommit:n,toolResults:s,modelNames:a,cwd:o,onOpenFile:l,onOpenSubagent:d,onEnterSubagent:c}=e,u=iO(t,iD);return((0,i.useLayoutEffect)(n,[u,n]),u)?(0,r.jsx)(nS.Dx,{message:u,toolResults:s,isStreaming:!0,modelNames:a,cwd:o,onOpenFile:l,onOpenSubagent:d,onEnterSubagent:c}):null});function iG(e){let{notices:t,floating:n=!1,onPauseChange:i}=e;return 0===t.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",marginBottom:10*!n},children:t.map((e,s)=>{var a;let o,l,d,c="error"===e.type?"#ef4444":"warning"===e.type?"#d97706":"success"===e.type?"#10b981":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",onMouseEnter:()=>i?.(e.id),onMouseLeave:e=>{e.currentTarget.contains(document.activeElement)||i?.(null)},onFocus:()=>i?.(e.id),onBlur:e=>{e.currentTarget.matches(":hover")||i?.(null)},style:{display:"flex",alignItems:"flex-start",gap:10,minHeight:60,height:"auto",maxHeight:500,pointerEvents:"auto",marginBottom:6*(s!==t.length-1),overflow:"hidden",borderRadius:14,border:"1px solid color-mix(in srgb, var(--border) 70%, transparent)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:n?"0 1px 2px rgba(15,23,42,0.05), 0 10px 28px -14px rgba(15,23,42,0.24)":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",fontSize:14,lineHeight:1.5,transformOrigin:"top right",animation:e.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out backwards",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:c,flexShrink:0,marginTop:25.5}}),(0,r.jsx)("span",{tabIndex:0,style:{padding:"18.5px 0",minWidth:0,maxWidth:"100%",maxHeight:498,overflowY:"auto",scrollbarWidth:"thin",whiteSpace:"pre-line",wordBreak:"break-word"},children:(a=e.message,o=[],l=(e,t)=>{if(!t)return;let n=o[o.length-1];n?.kind===e?n.text+=t:o.push({kind:e,text:t})},d=!1,a.split("\n").forEach((e,t)=>{let n=nt.test(e);t>0&&l(n&&d?"art":"text","\n"),l(n?"art":"text",e),d=n}),o).map((e,t)=>"art"===e.kind?(0,r.jsx)("span",{style:{display:"inline-block",verticalAlign:"top",maxWidth:"100%",overflowX:"auto",whiteSpace:"pre",fontFamily:"Menlo, Consolas, 'DejaVu Sans Mono', monospace",lineHeight:1,color:"var(--text)"},children:e.text},t):e.text)})]},e.id)})})}function iY(e){let{count:t}=e,{t:n}=(0,eW.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 iX(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 iQ(e){let{request:t,waitingCount:n,onRespond:s}=e,{t:a}=(0,eW.s)(),[o,l]=(0,i.useState)("editor"===t.method?t.prefill??"":""),[d,c]=(0,i.useState)(!1),u=(0,i.useRef)(null),p=(0,i.useRef)(null),[h,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(!1),x=(0,i.useCallback)(()=>f(e=>!e),[]),[b,v]=(0,i.useState)(()=>Date.now()),y=(0,i.useCallback)(e=>e?.focus(),[]),j=function(e){if("select"===e.method&&e.options.length>0)return t5(e.options[0]);if("confirm"===e.method){let t=t5(e.message).split("\n").find(e=>e.trim());return t?.trim()}}(t),k=void 0===t.expiresAt?null:Math.max(0,Math.ceil((t.expiresAt-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!==k&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:a("chat.extensionExpiresIn",{seconds:k})}),S=()=>{"confirm"===t.method?s(t,{confirmed:!0}):s(t,{value:o})};return(0,r.jsx)("div",{onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),e.stopPropagation(),s(t,{cancelled:!0}))},style:{position:"absolute",inset:0,zIndex:90,display:"flex",alignItems:d?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:d?(0,r.jsxs)("button",{type:"button",onClick:()=>c(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(560px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:a("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:t5(t.title)}),j&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:j}),(0,r.jsx)(iY,{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":t5(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:t5(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)(iY,{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)(iX,{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)(nC.m,{children:t5(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":t5(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)(nC.m,{children:t5(e)})})},e))}),"input"===t.method&&(0,r.jsx)("input",{autoFocus:!0,value:o,placeholder:t.placeholder,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||S()},style:{width:"100%",padding:"9px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",fontSize:13}}),"editor"===t.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:o,onChange:e=>l(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&!e.nativeEvent.isComposing&&S()},style:{width:"100%",minHeight:220,padding:10,borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:13,lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 14px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("button",{autoFocus:"confirm"===t.method||"select"===t.method&&0===t.options.length,onClick:()=>s(t,{cancelled:!0}),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"},children:a("chat.cancel")}),"confirm"===t.method?(0,r.jsx)("button",{onClick:S,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:a("chat.confirm")}):"select"!==t.method?(0,r.jsx)("button",{onClick:S,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:a("chat.submit")}):null]})]})})}function i0(e){let{request:t,waitingCount:n,onInput:s}=e,{t:a}=(0,eW.s)(),o=(0,i.useRef)(null),l=(0,i.useRef)(!1),[d,c]=(0,i.useState)(!1),u=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(t3,""),i=t5(e).trimEnd();if(t.test(i))continue;let s=e,a=ne(s);("│"===a||"┃"===a)&&" "===ne(s=t7(s,0))&&(s=t7(s,0));let o=function(e){let t=t9(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(s),l=o>=0?t9(s)[o]?.char:void 0;("│"===l||"┃"===l)&&(s=t7(s,o)),n.push(function(e){let t=e;for(;;){let e=t9(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&&""===t5(n[0]).trim();)n.shift();for(;n.length>0&&""===t5(n[n.length-1]).trim();)n.pop();return n.length?n:e}(t.lines),p=u.map(t5).find(e=>e.trim())?.trim();return(0,i.useEffect)(()=>{d||o.current?.focus()},[d]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:d?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:d?(0,r.jsxs)("button",{type:"button",onClick:()=>c(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(920px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:a("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:a("chat.extensionPanel")}),p&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:p}),(0,r.jsx)(iY,{count:n}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:a("chat.extensionExpand")})]}):(0,r.jsxs)("div",{role:"dialog",onClick:e=>{e.target.closest("button")||o.current?.focus()},style:{pointerEvents:"auto",position:"relative",width:"max-content",minWidth:"min(920px, 100%)",maxWidth:"100%",maxHeight:"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:o,"aria-label":a("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:e=>{if(l.current||e.nativeEvent.isComposing)return;let n=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=nr[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":" ":nn[e.key]??null}(e);n&&(e.preventDefault(),e.stopPropagation(),s(t,n))},onInput:e=>{if(l.current||e.nativeEvent.isComposing)return;let n=e.currentTarget.value;e.currentTarget.value="",n&&s(t,n)},onCompositionStart:()=>{l.current=!0},onCompositionEnd:e=>{l.current=!1;let n=e.currentTarget;queueMicrotask(()=>{let e=n.value;n.value="",e&&s(t,e)})},onPaste:e=>{e.preventDefault();let n=e.clipboardData.getData("text");n&&s(t,`\x1b[200~${n}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:a("chat.extensionPanel")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)(iY,{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)(rH,{text:u.join("\n")})})]})})}let i1=null,i2="";function i4(e){let{context:t,mobile:n,initialFocus:s,onInitialFocusDone:a,onPick:o,onUseDefaultDirectory:l,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u}=e,{t:p}=(0,eW.s)(),[h,m]=(0,i.useState)(()=>i2),g=(0,i.useRef)(null),f=(0,i.useRef)(s),x=(0,i.useRef)(a);return x.current=a,(0,i.useEffect)(()=>{if(i2)return;let e=!1;return(i1??=fetch("/api/home").then(e=>e.json()).then(e=>i2=e.home??"").catch(()=>(i1=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;eC(document,("worktree"===e?t?.button("worktree"):null)??t?.button("project")??null)},[]),(0,r.jsx)("div",{className:"new-session-context",children:(0,r.jsx)(tO,{handleRef:g,layout:"inline",context:t,mobile:n,label:p("workspace.newSessionContext"),homeDir:h,newWorktreeTitle:p("sidebar.newWorktreeForSession"),onPick:o,onUseDefaultDirectory:l,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u})})}var i8=n(30392),i6=n(90137),i3=n(88545),i5=n(96793),i9=n(68929);let i7=["general","models","skills","agents","plugins","mcp","channels","automations","usage"],se="pi-web:settings-navigation",st=new Set(["skills","agents","plugins"]);function sn(e){return st.has(e)}function sr(){try{return window.localStorage}catch{return null}}function si(e){let t=e.getItem(se);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 ss(e,t){return"models"===e?e:t?JSON.stringify([e,t]):"mcp"===e||"channels"===e||"automations"===e?e:null}function sa(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr();if(t)try{let n=si(t);n.section=e,t.setItem(se,JSON.stringify(n))}catch{}}function so(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:sr();if(!n)return null;let r=ss(e,t);if(!r)return null;try{let e=si(n).selections?.[r];return"string"==typeof e&&e.length>0?e:null}catch{return null}}function sl(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:sr();if(!r||!t)return;let i=ss(e,n);if(i)try{let e=si(r);e.selections={...e.selections,[i]:t},r.setItem(se,JSON.stringify(e))}catch{}}var sd=n(61958);function sc(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}class su extends Error{constructor(e){super(`Context window of ${e} must be a positive number of tokens`),this.name="ContextWindowError",this.model=e}}function sp(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 sh={empty:e=>`Provider ${e} needs a Base URL or at least one model`,baseUrl:e=>`Provider ${e} needs a Base URL`};class sm extends Error{constructor(e,t){super(sh[t](e)),this.name="ProviderEntryError",this.provider=e,this.problem=t}}function sg(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sf(e){return!sg(e)||"string"!=typeof e.id||e.id.trim().length>0}function sx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sb(e){let t=sx(e.inputLimits)?e.inputLimits.images:void 0,n=sx(t)?t.resize:void 0;return sx(n)?n.maxBytes:void 0}function sv(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 sy(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 sj 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 sk=["input","output","cacheRead","cacheWrite"];function sw(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 sS(e){if(!sC(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 sC(e){return sk.some(t=>""!==e[t].trim())}function sN(e,t,n){return{...e,compat:{...e.compat??{},[t]:n}}}function sI(e){return new Map(Object.entries(e.providers??{}).map(e=>{let[t,n]=e;return[t,(n.models??[]).map(e=>e.id)]}))}function s$(e,t,n){if(n<=0)return;let r=e.get(t)??[];e.set(t,[...r,...Array.from({length:n},()=>null)])}function sE(e,t,n,r){let i=e.providers??{},s=i[n],a=s?.models;if(!a||r.every((e,t)=>e===t))return null;let o=t.get(n);return o&&t.set(n,r.map(e=>o[e]??null)),{config:{...e,providers:{...i,[n]:{...s,models:r.map(e=>a[e])}}},providerName:n,order:r}}function sT(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 sM(e,t,n){let r=e.trim().toLowerCase();return!r||n.toLowerCase().includes(r)||t.toLowerCase().includes(r)}function sR(e){return e.name?.trim()||e.id}function sA(e){let{embedded:t,title:n,subtitle:i,closeLabel:s="Close",onClose:a,children:o,width:l=900,height:d="78vh"}=e,c=t?void 0:{"--config-panel-width":`${l}px`,"--config-panel-height":d};return(0,r.jsx)("div",{role:t?void 0:"dialog","aria-modal":t?void 0:"true","aria-label":n,className:`config-panel-root ${t?"is-embedded":"is-modal"}`,onClick:e=>{t||e.target!==e.currentTarget||a()},children:(0,r.jsxs)("div",{className:"config-panel-surface",style:c,children:[!t&&(0,r.jsxs)("div",{className:"config-panel-header",children:[(0,r.jsx)("strong",{className:"config-panel-title",children:n}),i&&(0,r.jsx)("code",{className:"config-panel-subtitle",title:i,children:i}),(0,r.jsx)("button",{type:"button",className:"config-close-button",onClick:a,title:s,"aria-label":s,children:"\xd7"})]}),o]})})}let sL=(0,i.createContext)(null);function sP(){return(0,i.useContext)(sL)??sz}let sz={detailOpen:!1,openDetail:()=>{},closeDetail:()=>{},reportDetailTitle:()=>{}};function sO(e,t){let{detailOpen:n,reportDetailTitle:r}=sP(),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 sW(e){let{children:t}=e,n=(0,i.useContext)(sL);return(0,r.jsx)("div",{className:"config-split-view","data-pane":n?n.detailOpen?"detail":"list":void 0,children:t})}function sF(e){let{children:t}=e;return(0,r.jsx)("aside",{className:"config-sidebar",children:t})}function sD(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-sidebar-list",children:t})}function sB(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 sH(e){let{enabled:t,total:n,checked:i,label:s,disabled:a=!1,loading:o=!1,describedBy:l,onChange:d}=e;return(0,r.jsxs)("span",{className:"config-sidebar-group-switch",children:[(0,r.jsxs)("span",{className:"config-sidebar-group-count",children:[t,"/",n]}),(0,r.jsx)(ar,{checked:i??(n>0&&t===n),disabled:a,loading:o,label:s,describedBy:l,onChange:d})]})}function s_(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 sU(e){let{active:t=!1,className:n,children:i,onClick:s,ref:a,...o}=e,{openDetail:l}=sP(),d=sO(t,a);return(0,r.jsx)("button",{type:"button",...o,ref:d,onClick:e=>{s?.(e),e.defaultPrevented||l()},"aria-current":t?"page":void 0,className:["config-sidebar-item",n].filter(Boolean).join(" "),children:i})}function sq(e){let{className:t,...n}=e;return(0,r.jsx)("span",{...n,className:["config-sidebar-text",t].filter(Boolean).join(" ")})}function sK(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-stack",t].filter(Boolean).join(" ")})}function sZ(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header",t].filter(Boolean).join(" ")})}function sV(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header-info",t].filter(Boolean).join(" ")})}function sJ(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-actions",t].filter(Boolean).join(" ")})}function sG(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-title",children:t})}function sY(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-section-title",children:t})}function sX(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 sQ(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-grid",children:t})}function s0(e){let{label:t,tone:n="muted",mono:i=!1,className:s,style:a,children:o}=e;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-detail-grid-label",children:t}),(0,r.jsx)("div",{className:["config-detail-grid-value","plain"===n?null:`is-${n}`,i?"is-mono":null,s].filter(Boolean).join(" "),style:a,children:o})]})}function s1(e){let{scope:t,children:n}=e;return(0,r.jsx)("span",{className:`config-scope-tag${"project"===t?" is-project":""}`,children:n})}function s2(e){let{value:t,options:n,label:s,disabledReason:a,size:o="default",onChange:l,children:d}=e,c=(0,i.useId)(),u=a&&n.some(e=>e.disabled)?a:null;return(0,r.jsxs)("div",{className:"config-scope-switch-field",children:[(0,r.jsxs)("div",{className:"config-scope-switch-row",children:[(0,r.jsx)("div",{role:"group","aria-label":s,className:`config-scope-switch${"small"===o?" is-small":""}`,children:n.map(e=>(0,r.jsx)("button",{type:"button","aria-pressed":e.value===t,"aria-describedby":e.disabled&&u?c:void 0,disabled:e.disabled,className:"config-scope-switch-option",onClick:()=>{e.disabled||l(e.value)},children:e.label},e.value))}),d]}),u&&(0,r.jsx)("span",{id:c,className:"config-scope-switch-reason",children:u})]})}function s4(e){let{value:t,options:n,label:s,path:a,disabledReason:o,onChange:l,children:d}=e;return(0,r.jsxs)("div",{className:"config-save-target",children:[(0,r.jsx)(s2,{value:t,options:n,label:s,disabledReason:o,size:"small",onChange:l,children:(0,r.jsx)("span",{className:"config-save-target-path",children:"string"==typeof a?a.split(/([\\/])/).map((e,t)=>"/"===e||"\\"===e?(0,r.jsxs)(i.Fragment,{children:[e,(0,r.jsx)("wbr",{})]},t):e):a})}),d]})}function s8(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)(sG,{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 s6(e){let{title:t,catalogs:n,target:s,inputLabel:a,inputId:o,placeholder:l,value:d,canSubmit:c,normalizeValue:u,onValueChange:p,onSubmit:h,examplesLabel:m,examples:g,error:f,multiline:x=!1,children:b}=e,v=(0,i.useRef)(null),y=(0,i.useRef)(null);(0,i.useEffect)(()=>{x?window.matchMedia?.("(pointer: coarse)").matches||y.current?.focus():v.current?.focus()},[x]);let j=e=>{if(!u)return;let t=e.clipboardData.getData("text"),n=u(t);n!==t&&(e.preventDefault(),p(n))};return(0,r.jsxs)(sK,{className:"is-fill",children:[(0,r.jsx)(s8,{title:t,catalogs:n,target:s}),(0,r.jsx)(sX,{label:a,children:x?(0,r.jsx)("textarea",{id:o,ref:y,value:d,"aria-label":a,className:"config-add-source-input is-multiline",placeholder:l,rows:5,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>p(e.target.value),onPaste:j,onBlur:e=>{u&&p(u(e.currentTarget.value))},onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&e.nativeEvent?.isComposing!==!0&&229!==e.keyCode&&(e.preventDefault(),c&&h())}}):(0,r.jsx)("input",{id:o,ref:v,value:d,"aria-label":a,className:"config-add-source-input",placeholder:l,onChange:e=>p(e.target.value),onPaste:j,onBlur:e=>{u&&p(u(e.currentTarget.value))},onKeyDown:e=>{"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 s3(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 s5(e){let{id:t,message:n,trustLabel:i,trusting:s=!1,onTrust:a}=e;return(0,r.jsx)(s3,{id:t,action:a&&i?(0,r.jsx)(an,{size:"small",onClick:a,disabled:s,children:i}):void 0,children:n})}function s9(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-empty-state",children:t})}function s7(e){let{children:t,style:n}=e;return(0,r.jsx)("div",{className:"config-detail",style:n,children:t})}function ae(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 at(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 an(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 ar(e){let{checked:t,disabled:n=!1,loading:i=!1,size:s="default",label:a,describedBy:o,onChange:l}=e,d=n||i;return(0,r.jsx)("button",{type:"button",role:"switch","aria-checked":t,"aria-busy":i||void 0,"aria-label":a,"aria-describedby":o,title:a,disabled:d,className:`config-switch${"small"===s?" is-small":""}${i?" is-loading":""}`,onClick:()=>l(!t),children:(0,r.jsx)("span",{className:"config-switch-knob","aria-hidden":"true"})})}function ai(e){let{active:t=!1,children:n,className:i,onClick:s,ref:a,...o}=e,{openDetail:l}=sP(),d=sO(t,a);return(0,r.jsx)("div",{className:"config-list-action",children:(0,r.jsxs)("button",{type:"button",...o,ref:d,onClick:e=>{s?.(e),e.defaultPrevented||l()},"aria-current":t?"page":void 0,className:["config-list-action-button",i].filter(Boolean).join(" "),children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})}),n]})})}function as(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 aa(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 ao(e,t){let n=aa(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 al(e,t){return t.enabled&&(e?.enabledTotal??0)<=1}function ad(e,t){return e?.providers.find(e=>e.id===t)}function ac(e){let{modelName:t,effective:n,value:i,onChange:s,disabled:a=!1,describedBy:o}=e,{t:l}=(0,eW.s)(),d=void 0!==i&&void 0===sp(i);return(0,r.jsx)("input",{type:"text",inputMode:"numeric",className:"model-context-input",value:void 0===i?"":String(i),placeholder:void 0===n?void 0:String(n),title:l("models.contextWindow"),"aria-label":l("models.contextForModel",{model:t}),"aria-invalid":d||void 0,"aria-describedby":o,disabled:a,onChange:e=>s(""===e.target.value.trim()?void 0:e.target.value)})}let au={"last-model":"models.enabledLastModel","project-scope":"models.enabledProjectScope"};function ap(e){let{controller:t}=e,{t:n}=(0,eW.s)(),{view:i,pending:s}=t;if(!i)return null;let a=!i.allEnabled,o=i.stalePatterns.length;return a||0!==o?(0,r.jsxs)("div",{className:"enabled-models-banner",children:[(0,r.jsxs)("span",{className:"enabled-models-banner-text",...o>0?{title:n("models.enabledStaleHint")}:{},children:[(0,r.jsx)("code",{className:"enabled-models-banner-key",title:i.settingsPath,children:i.settingsPath}),(0,r.jsxs)("code",{className:"enabled-models-banner-facts",children:[`\xb7 enabledModels ${i.enabledTotal}/${i.availableTotal}`,o>0&&` \xb7 ${n("models.enabledStale",{count:o})}`]})]}),i.editable&&o>0&&(0,r.jsx)(an,{size:"small",onClick:t.pruneStale,disabled:null!==s,title:n("models.enabledPruneHint"),children:n("models.enabledPrune")}),i.editable&&a&&(0,r.jsx)(an,{size:"small",onClick:t.clearScope,disabled:null!==s,title:n("models.enabledClearHint"),children:n("models.enabledClear")})]}):null}function ah(e){let{providerId:t,controller:n,noteId:i}=e,{t:s}=(0,eW.s)(),{view:a,loading:o,pending:l,failure:d}=n,c=ad(a,t),u=d?d.messageKey?s(d.messageKey):d.message:null,p=am(n,t)?i:void 0;if(o&&!a)return null;if(!c)return(0,r.jsx)(ar,{checked:!1,disabled:!0,label:s("models.enabledProviderToggle",{provider:t}),describedBy:p,onChange:()=>{}});let h=ao(a,c);return(0,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("span",{className:"enabled-models-switch-error",children:u}),(0,r.jsx)(ar,{checked:h.checked,loading:l===`provider:${c.id}`,disabled:null!==l||h.blocked,label:s("models.enabledProviderToggle",{provider:c.name}),describedBy:p,onChange:e=>n.setProvider(c.id,e)})]})}function am(e,t){let{view:n,loading:r}=e;if(r&&!n)return null;let i=ad(n,t);if(!i)return"models.enabledCustomEmpty";let{reason:s}=ao(n,i);return s?au[s]:null}function ag(e){let{providerId:t,controller:n,id:i}=e,{t:s}=(0,eW.s)(),a=am(n,t);return a?(0,r.jsx)("div",{id:i,className:"config-detail-heading-note",children:s(a)}):null}function af(e){var t;let n,{providerId:s,controller:a,contextSettings:o}=e,{t:l}=(0,eW.s)(),[d,c]=(0,i.useState)(""),{view:u,loading:p,pending:h,failure:m}=a,g=ad(u,s),f=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),x=(0,i.useId)();if((0,i.useEffect)(()=>c(""),[s]),p&&!u)return(0,r.jsx)("div",{className:"enabled-models-empty",children:l("agents.modelsLoading")});if(!g)return m?.message?(0,r.jsx)("div",{className:"enabled-models-error",children:m.message}):(0,r.jsx)("div",{className:"enabled-models-empty",children:l("models.enabledUnavailable")});let b=(t=g.models,(n=d.trim().toLowerCase())?t.filter(e=>e.id.toLowerCase().includes(n)||e.name.toLowerCase().includes(n)):[...t]),v=aa(u,b),y=b.length!==g.models.length,j=null!==h,k=`provider:${g.id}`,w=u?.editable===!0,S=`${x}-scope`,C=`${x}-last`,N=`${x}-context`,I=w&&!v.canDisable&&v.disableRefs.length>0,$=I||w&&b.some(e=>al(u,e)),E=(e,t)=>{y?a.setModels(k,t,e):a.setProvider(g.id,e)};return(0,r.jsxs)("div",{className:"enabled-models-section",children:[(0,r.jsxs)("div",{className:"enabled-models-header",children:[(0,r.jsx)("span",{className:"enabled-models-title",children:l("models.enabledSection")}),(0,r.jsx)("span",{className:"enabled-models-count",children:l("models.enabledCount",{enabled:g.enabledCount,total:g.models.length})}),(0,r.jsx)(an,{size:"small",disabled:j||!v.canEnable,"aria-describedby":w?void 0:S,onClick:()=>E(!0,v.enableRefs),children:y?l("models.enableShown"):l("models.enableAll")}),(0,r.jsx)(an,{size:"small",disabled:j||!v.canDisable,"aria-describedby":w?I?C:void 0:S,onClick:()=>E(!1,v.disableRefs),children:y?l("models.disableShown"):l("models.disableAll")}),(0,r.jsx)(an,{size:"small",disabled:j||f.refreshing,title:l("models.refreshCatalogHint"),onClick:f.refresh,children:f.refreshing?l("models.refreshingCatalog"):l("models.refreshCatalog")})]}),f.note&&(0,r.jsx)("div",{className:"enabled-models-note",children:l(f.note)}),!w&&(0,r.jsx)("div",{id:S,className:"enabled-models-note",children:l("models.enabledProjectScope")}),$&&(0,r.jsx)("div",{id:C,className:"enabled-models-note",children:l("models.enabledLastModel")}),m&&(0,r.jsx)("div",{className:"enabled-models-error",children:m.messageKey?l(m.messageKey):m.message}),g.models.length>8&&(0,r.jsx)("input",{value:d,onChange:e=>c(e.target.value),placeholder:l("models.enabledFilterPlaceholder",{count:g.models.length}),"aria-label":l("models.enabledFilter"),className:"enabled-models-filter"}),o&&(0,r.jsx)("div",{id:N,className:"enabled-models-note",children:l("models.contextOverrideHelp")}),(0,r.jsx)("div",{className:"enabled-models-list",children:0===b.length?(0,r.jsx)("div",{className:"enabled-models-empty",children:l("models.enabledNoMatches")}):b.map(e=>{let t=al(u,e),n=o?.overrides?.[e.id],i=n&&"object"==typeof n&&!Array.isArray(n)?n.contextWindow:void 0;return(0,r.jsxs)("div",{className:"enabled-models-row",children:[(0,r.jsxs)("span",{className:"enabled-models-row-text",children:[(0,r.jsx)("span",{className:"enabled-models-row-name",children:e.name}),(0,r.jsx)("code",{className:"enabled-models-row-id",children:e.id})]}),e.thinkingPin&&(0,r.jsx)("span",{className:"enabled-models-pin",title:l("models.enabledPinHint"),children:e.thinkingPin}),o&&(0,r.jsx)(ac,{modelName:e.name,effective:e.contextWindow,value:i,disabled:o.disabled,describedBy:N,onChange:t=>o.onChange(e.id,t)}),(0,r.jsx)(ar,{checked:e.enabled,loading:h===e.ref,disabled:j||!u?.editable||t,label:l("models.enabledToggle",{model:e.name}),describedBy:w?t?C:void 0:S,onChange:t=>a.setModels(e.ref,[e.ref],t)})]},e.ref)})})]})}function ax(e){let{message:t,hint:n,value:i,placeholder:s,submitLabel:a,inputLabel:o,disabled:l=!1,plainEnterSubmits:d=!0,inputRef:c,onValueChange:u,onSubmit:p}=e,h=!l&&i.trim().length>0;return(0,r.jsxs)("div",{className:"oauth-paste-panel",children:[(0,r.jsx)("p",{className:"oauth-paste-message",children:t}),n&&(0,r.jsx)("p",{className:"oauth-paste-hint",children:n}),(0,r.jsxs)("div",{className:"oauth-paste-row",children:[(0,r.jsx)("input",{ref:c,value:i,className:"oauth-paste-input",placeholder:s,"aria-label":o,disabled:l||void 0,onChange:e=>u(e.target.value),onKeyDown:e=>{var t;t={key:e.key,metaKey:e.metaKey,ctrlKey:e.ctrlKey,isComposing:e.nativeEvent.isComposing,keyCode:e.keyCode},"Enter"===t.key&&!t.isComposing&&229!==t.keyCode&&(d||t.metaKey||t.ctrlKey)&&h&&p()}}),(0,r.jsx)("button",{type:"button",className:"oauth-paste-submit",onClick:p,disabled:!h,children:a})]})]})}let ab={anthropic:{symbol:"anthropic",color:!1},openai:{symbol:"openai",color:!1},"openai-codex":{symbol:"openai",color:!1},google:{symbol:"google",color:!0},"google-vertex":{symbol:"google",color:!0},"ant-ling":{symbol:"antgroup",color:!0},deepseek:{symbol:"deepseek",color:!0},groq:{symbol:"groq",color:!1},mistral:{symbol:"mistral",color:!0},moonshotai:{symbol:"moonshot",color:!1},"moonshotai-cn":{symbol:"moonshot",color:!1},moonshot:{symbol:"moonshot",color:!1},minimax:{symbol:"minimax",color:!0},"minimax-cn":{symbol:"minimax",color:!0},fireworks:{symbol:"fireworks",color:!0},huggingface:{symbol:"huggingface",color:!0},cerebras:{symbol:"cerebras",color:!0},openrouter:{symbol:"openrouter",color:!1},xai:{symbol:"xai",color:!1},"cloudflare-ai-gateway":{symbol:"cloudflare",color:!0},"cloudflare-workers-ai":{symbol:"cloudflare",color:!0},"vercel-ai-gateway":{symbol:"vercel",color:!1},"github-copilot":{symbol:"githubcopilot",color:!1},"amazon-bedrock":{symbol:"aws",color:!0},azure:{symbol:"azure",color:!0},"azure-openai-responses":{symbol:"azure",color:!0},"kimi-coding":{symbol:"kimi",color:!0},nvidia:{symbol:"nvidia",color:!0},opencode:{symbol:"opencode",color:!1},"opencode-go":{symbol:"opencode",color:!1},qwen:{symbol:"qwen",color:!0},xiaomi:{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-ams":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-cn":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-sgp":{symbol:"xiaomimimo",color:!1},zai:{symbol:"zai",color:!1},"zai-coding-cn":{symbol:"zai",color:!1},zhipu:{symbol:"zhipu",color:!0},cohere:{symbol:"cohere",color:!0},perplexity:{symbol:"perplexity",color:!0},together:{symbol:"together",color:!0},grok:{symbol:"grok",color:!1}};function av(e){let{id:t,size:n}=e,i=ab[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 ay=["openai-codex","deepseek","openrouter","moonshotai","moonshotai-cn","minimax","minimax-cn","vercel-ai-gateway","opencode-go","kimi-coding"],aj="pi-web:provider-usage:";function ak(e){let{providerId:t,enabled:n}=e;return ay.includes(t)?(0,r.jsx)(aw,{providerId:t,enabled:n}):null}function aw(e){let{providerId:t,enabled:n}=e,[s,a]=(0,i.useState)(null),[o,l]=(0,i.useState)(!1),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),h=(0,i.useRef)(null),{locale:m,t:g}=(0,eW.s)();(0,i.useEffect)(()=>{h.current&&clearTimeout(h.current),p(!1),a(null);try{let e=localStorage.getItem(`${aj}${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(`${aj}${t}`)}catch{}}return c(null),()=>{h.current&&clearTimeout(h.current)}},[t]);let f=(0,i.useCallback)(async()=>{l(!0),c(null);try{let e=await fetch("/api/provider-usage/query",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:t})}),n=await e.json();if(!e.ok)throw Error(n.error??`HTTP ${e.status}`);if("ready"===n.status){a(n);try{localStorage.setItem(`${aj}${t}`,JSON.stringify(n))}catch{}p(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>p(!1),2e3)}else c(n.message??g("providerUsage.queryFailed"))}catch(e){c(e instanceof Error?e.message:g("providerUsage.queryFailed"))}finally{l(!1)}},[t,g]),x=s?.status==="ready"?s.report:void 0;return(0,r.jsxs)("section",{style:{paddingTop:10,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:13,color:"var(--text)",fontWeight:600,lineHeight:1.35},children:g("providerUsage.usage")}),(0,r.jsx)("button",{type:"button",onClick:f,disabled:!n||o,title:g(o?"providerUsage.refreshing":"providerUsage.refresh"),"aria-label":g(o?"providerUsage.refreshing":"providerUsage.refresh"),style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:32,height:30,padding:0,background:"none",border:"none",color:u?"#4ade80":"var(--text-dim)",cursor:n&&!o?"pointer":"default",borderRadius:5,flexShrink:0,opacity:n?1:.6,transition:"color 0.3s"},children:u?(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:o?{animation:"spin 0.8s linear infinite"}:void 0,"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}),x&&(0,r.jsx)("span",{title:new Date(x.capturedAt).toLocaleString(m),style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap"},children:g("providerUsage.updated",{time:(0,te.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 ":"$"}${aS(e.remaining??e.limit)}`:void 0!==e.remaining&&void 0!==e.limit?`${aS(e.remaining)} / ${aS(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 aS(e){return void 0===e?"-":Number.isInteger(e)?String(e):e.toFixed(2)}function aC(){let e=so("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 aN(e){return 1===Object.keys(e).length&&Object.keys(e.modelOverrides??{}).length>0}let aI=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],a$={empty:"models.providerIncomplete",baseUrl:"models.providerNeedsBaseUrl"};function aE(e){let{label:t,children:n}=e;return(0,r.jsx)(sX,{label:t,children:n})}let aT={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 aM(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:{...aT,fontFamily:s?"var(--font-mono)":"inherit"}})}function aR(e){let{value:t,onChange:n,placeholder:s,mono:a,onKeyDown:o,autoComplete:l="off",spellCheck:d=!1,style:c}=e,[u,p]=(0,i.useState)(!1),{t:h}=(0,eW.s)();return(0,i.useEffect)(()=>{t||p(!1)},[t]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...c},children:[(0,r.jsx)("input",{type:u?"text":"password",value:t,onChange:e=>n(e.target.value),onKeyDown:o,placeholder:s,style:{...aT,paddingRight:34,fontFamily:a?"var(--font-mono)":"inherit"},autoComplete:l,spellCheck:d}),(0,r.jsx)("button",{type:"button",onClick:()=>p(e=>!e),"aria-label":h(u?"i18n.hideDetails":"i18n.showDetails"),title:h(u?"i18n.hideDetails":"i18n.showDetails"),style:{position:"absolute",right:5,top:"50%",transform:"translateY(-50%)",width:24,height:24,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:u?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C7 20 2.73 16.89 1 12a18.45 18.45 0 0 1 5.06-6.94"}),(0,r.jsx)("path",{d:"M9.9 4.24A10.94 10.94 0 0 1 12 4c5 0 9.27 3.11 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,r.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,r.jsx)("path",{d:"M1 1l22 22"})]}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function aA(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?{...aT,borderColor:"#ef4444"}:aT})}function aL(e){let{value:t,onChange:n,options:i,required:s}=e,{t:a}=(0,eW.s)();return(0,r.jsxs)("select",{value:t,onChange:e=>n(e.target.value),style:{...aT,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 aP(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 az(e){let{children:t}=e;return(0,r.jsx)(sY,{children:t})}function aO(e){let{name:t,editingName:n,provider:s,onChange:a,onEditingNameChange:o,onRename:l,onDelete:d,onAddModels:c,enabledModels:u}=e,{t:p}=(0,eW.s)(),[h,m]=(0,i.useState)({phase:"idle"}),[g,f]=(0,i.useState)(""),[x,b]=(0,i.useState)([]),v=(0,i.useRef)(0),y=(0,i.useRef)(null),j=(0,i.useId)(),k=(e,t)=>a({...s,[e]:t});(0,i.useEffect)(()=>{v.current+=1,m({phase:"idle"}),f(""),b([])},[t,s.baseUrl,s.api,s.apiKey]);let w=(0,i.useCallback)(async()=>{if("loading"===h.phase)return;let e=++v.current;m({phase:"loading"}),b([]);try{let n=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:t,provider:{...s,models:void 0}})}),r=await n.json();if(e!==v.current)return;if(!n.ok||r.error||!r.models)return void m({phase:"error",message:r.error??`HTTP ${n.status}`});m({phase:"success",models:r.models,endpoint:r.endpoint??s.baseUrl??""})}catch(t){if(e!==v.current)return;m({phase:"error",message:t instanceof Error?t.message:String(t)})}},[h.phase,t,s]),S=new Set((s.models??[]).map(e=>e.id)),C="success"===h.phase?h.models:[],N=g.trim().toLocaleLowerCase(),I=C.filter(e=>!N||e.id.toLocaleLowerCase().includes(N)||e.name?.toLocaleLowerCase().includes(N)),$=I.slice(0,300),E=$.filter(e=>!S.has(e.id)).map(e=>e.id),T=x.filter(e=>!S.has(e)).length,M=E.length>0&&E.every(e=>x.includes(e)),R=!M&&E.some(e=>x.includes(e));return(0,i.useEffect)(()=>{y.current&&(y.current.indeterminate=R)},[R]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(sZ,{children:[(0,r.jsx)(sV,{children:(0,r.jsx)(az,{children:p("i18n.provider")})}),(0,r.jsxs)(sJ,{children:[(0,r.jsx)(ah,{providerId:t,controller:u,noteId:j}),(0,r.jsx)(an,{variant:"danger",size:"small",onClick:d,children:p("i18n.delete")})]})]}),(0,r.jsx)(ag,{providerId:t,controller:u,id:j})]}),(0,r.jsxs)(aE,{label:p("i18n.providerName"),children:[(0,r.jsx)(aM,{value:n,onChange:o,placeholder:"provider-name",mono:!0}),n!==t&&n.trim()&&(0,r.jsx)("button",{onClick:()=>l(n.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--accent)",border:"none",borderRadius:4,color:"var(--accent-contrast)",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:p("i18n.rename")})]}),(0,r.jsx)(aE,{label:"Base URL",children:(0,r.jsx)(aM,{value:s.baseUrl??"",onChange:e=>k("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsx)(aE,{label:"API Key",children:(0,r.jsx)(aR,{value:s.apiKey??"",onChange:e=>k("apiKey",e||void 0),placeholder:p("models.apiKeyPlaceholder"),mono:!0})}),(0,r.jsx)(aE,{label:"API",children:(0,r.jsx)(aL,{value:s.api??"",onChange:e=>k("api",e||void 0),options:aI})}),(0,r.jsx)(aE,{label:"Headers",children:(0,r.jsx)(aU,{headers:s.headers,onChange:e=>k("headers",e)})}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==h.phase&&(0,r.jsx)("button",{onClick:w,disabled:"loading"===h.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:"loading"===h.phase?"var(--text-dim)":"var(--text-muted)",cursor:"loading"===h.phase?"not-allowed":"pointer",fontSize:11},children:"loading"===h.phase?p("models.discoveryFetching"):p("models.discoveryFetch")}),"error"===h.phase&&(0,r.jsx)("div",{style:{padding:"7px 9px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",fontSize:11,lineHeight:1.4},children:h.message}),"success"===h.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:g,onChange:e=>f(e.target.value),placeholder:p("models.discoveryFilterPlaceholder",{count:h.models.length}),"aria-label":p("models.discoveryFilter"),style:{...aT,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:E.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:y,type:"checkbox",checked:M,disabled:0===E.length,onChange:()=>{let e=new Set(E);b(t=>M?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...E])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),p("models.discoverySelectShown")]}),0===$.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:p("models.discoveryNoMatches")}):$.map((e,t)=>{let n=S.has(e.id),i=x.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:i||n,disabled:n,onChange:()=>{var t;return t=e.id,void b(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),n&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:p("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:h.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:I.length>$.length?p("models.discoveryShowing",{shown:$.length,total:I.length}):p("models.discoveryFetched",{count:h.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==h.phase)return;let e=new Set(x),t=h.models.filter(t=>e.has(t.id)&&!S.has(t.id));0!==t.length&&(c(t),b([]))},disabled:0===T,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:T?"var(--accent)":"var(--bg-panel)",color:T?"var(--accent-contrast)":"var(--text-dim)",cursor:T?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:T?p("models.discoveryAddSelectedCount",{count:T}):p("models.discoveryAddSelected")})]})]})]})]})}let aW=["off","minimal","low","medium","high","xhigh","max"],aF={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function aD(e){let{value:t,onChange:n}=e,{t:i}=(0,eW.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:aW.map(e=>{let t=s[e],n=e in s?null===t?"null":"string":"omit",o="string"==typeof t?t:"",l=aF[e],d={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},c={background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600};return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:l,flexShrink:0,opacity:"null"===n?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===n?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===n?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>a(e,"omit"),style:{...d,..."omit"===n?c:{}},children:i("i18n.default")}),(0,r.jsx)("button",{onClick:()=>a(e,null),style:{...d,borderLeft:"1px solid var(--border)",..."null"===n?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:i("i18n.disabled")})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===n?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>a(e,o||e),style:{...d,..."string"===n?c:{},borderRight:"1px solid var(--border)",flexShrink:0},children:i("i18n.custom")}),(0,r.jsx)("input",{value:o,onChange:t=>a(e,t.target.value),onFocus:()=>{"string"!==n&&a(e,o||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===n?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===n?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let aB={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function aH(e){return e.compat?.thinkingFormat==="deepseek"}function a_(e,t){return{...e.compat??{},...t.compat??{}}}function aU(e){let{headers:t,onChange:n}=e,{t:s}=(0,eW.s)(),[a,o]=(0,i.useState)(()=>Object.entries(t??{}).map((e,t)=>{let[n,r]=e;return{id:t,name:n,value:r}})),l=(0,i.useRef)(a.length),d=e=>{o(e),n(function(e){let t={};for(let n of e){let e=n.name.trim();e&&(t[e]=n.value)}return Object.keys(t).length?t:void 0}(e))},c=(e,t)=>{d(a.map(n=>n.id===e?{...n,...t}:n))},u={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[a.map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{value:e.name,onChange:t=>c(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...aT,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>c(e.id,{value:t.target.value}),placeholder:"value",style:{...aT,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void d(a.filter(e=>e.id!==t))},style:u,children:"✕"})]},e.id)),(0,r.jsxs)("button",{onClick:()=>o(e=>[...e,{id:l.current++,name:"",value:""}]),style:{padding:"5px 9px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,alignSelf:"flex-start"},children:["+ ",s("models.addHeader")]})]})}function aq(e){let{providerName:t,provider:n,model:s,onChange:a,onDelete:o}=e,[l,d]=(0,i.useState)({phase:"idle"}),{t:c}=(0,eW.s)(),[u,p]=(0,i.useState)({phase:"idle"}),[h,m]=(0,i.useState)(!1),[g,f]=(0,i.useState)(()=>sw(s.cost)),x=(0,i.useRef)(g),[b,v]=(0,i.useState)(!1),y=(0,i.useRef)(0),j=s.baseUrl??n.baseUrl,k=(0,i.useRef)(0),w=(0,i.useRef)(null),S=(0,i.useRef)(s.cost),C=(e,t)=>a({...s,[e]:t}),N=(()=>{if("idle"===l.phase)return null;if("testing"===l.phase)return c("i18n.testingModel");let e=[void 0!==l.latencyMs?`${l.latencyMs}ms`:null,void 0!==l.status?`HTTP ${l.status}`:null].filter(Boolean);return"success"===l.phase?[c("i18n.connected"),...e,l.responseText||null].filter(Boolean).join(" \xb7 "):[c("i18n.failed"),...e,l.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>(y.current+=1,d({phase:"idle"}),()=>{y.current+=1}),[t,n,s]),(0,i.useEffect)(()=>{k.current+=1,p({phase:"idle"}),w.current=null},[t,j,s.id]);let I=(0,i.useCallback)(async()=>{if(!s.id.trim()||"testing"===l.phase)return;let e=++y.current;d({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:t,provider:n,model:s})}),i=await r.json();if(e!==y.current)return;if(!r.ok||!i.ok)return void d({phase:"error",message:i.error??`HTTP ${r.status}`,latencyMs:i.latencyMs,status:i.status});d({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(t){if(e!==y.current)return;d({phase:"error",message:t instanceof Error?t.message:String(t)})}},[s,n,t,l.phase]),$=(0,i.useCallback)(async()=>{let e=s.id.trim();if(!e||"loading"===u.phase)return;let n=++k.current;p({phase:"loading"});try{let r=new URLSearchParams({q:e,provider:t,limit:"50"});j?.trim()&&r.set("baseUrl",j.trim());let i=await fetch(`/api/models-config/catalog?${r}`),o=await i.json();if(n!==k.current)return;if(!i.ok||o.error||!o.recommendation)return void p({phase:"error",message:o.error??`HTTP ${i.status}`});let l=function(e,t){let n={...e},r=0;if(!e.name?.trim()&&t.name&&(n.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(n.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(n.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(n.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(n.maxTokens=t.maxTokens,r+=1),t.cost){let i={...e.cost??{}},s=0;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],s+=1);let a=sS(sw(i));s>0&&a&&(n.cost={...i,...a},r+=s)}return{model:n,appliedCount:r}}(s,o.recommendation.preset);l.appliedCount>0&&(w.current=s,a(l.model)),m(!1),p({phase:"success",recommendation:o.recommendation,appliedCount:l.appliedCount})}catch(e){if(n!==k.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,s,a,j,t]),E=(()=>{if("success"!==u.phase)return null;let{recommendation:e,appliedCount:n}=u,r=n>0?c("models.catalogFilled",{count:n}):c("models.catalogNoEmptyFields");if("unreliable"===e.price.status){let t="no-exact-match"===e.price.reason?c("models.catalogNoExactMatch"):c("models.catalogPriceUnreliable");return`${r} \xb7 ${t}`}let i="provider"===e.price.method?c("models.catalogPriceProvider",{provider:e.price.providerName??e.price.providerId??t}):"base-url"===e.price.method?c("models.catalogPriceBaseUrl",{provider:e.price.providerName??e.price.providerId??t}):c("models.catalogPriceConsensus",{support:e.price.support,total:e.price.total});return`${r} \xb7 ${i}`})(),T="error"===u.phase?u.message:E,M="error"===u.phase?"#ef4444":"success"===u.phase&&"unreliable"===u.recommendation.price.status?"#d97706":"var(--text-dim)",R=[{key:"input",label:c("models.costInput")},{key:"output",label:c("models.costOutput")},{key:"cacheRead",label:c("models.costCacheRead")},{key:"cacheWrite",label:c("models.costCacheWrite")}],A=new Set(Object.keys(s.compat??{})),L=0;aH(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=sb(s),z=sv(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:sy(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)(sZ,{children:[(0,r.jsx)(sV,{children:(0,r.jsx)(az,{children:c("i18n.model")})}),(0,r.jsxs)(sJ,{children:[N&&(0,r.jsx)("span",{title:N,style:{maxWidth:260,height:28,padding:"0 8px",border:`1px solid ${"error"===l.phase?"#fecaca":"success"===l.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===l.phase?"#fee2e2":"success"===l.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:N}),(0,r.jsxs)(an,{size:"small",variant:"success"===l.phase?"primary":"secondary",onClick:"success"===l.phase?()=>d({phase:"idle"}):I,disabled:!s.id.trim()||"testing"===l.phase,title:c("i18n.testConnection"),className:"success"===l.phase?"is-success":void 0,children:["success"===l.phase&&(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===l.phase?c("i18n.checking"):"success"===l.phase?c("common.ok"):c("i18n.test")]}),(0,r.jsx)(an,{variant:"danger",size:"small",onClick:o,children:c("i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(aE,{label:"ID *",children:(0,r.jsx)(aM,{value:s.id,onChange:e=>C("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(aE,{label:"Name",children:(0,r.jsx)(aM,{value:s.name??"",onChange:e=>C("name",e||void 0),placeholder:c("models.displayNamePlaceholder")})})]}),(0,r.jsxs)("div",{style:{padding:"2px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>void $(),disabled:!s.id.trim()||"loading"===u.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:s.id.trim()&&"loading"!==u.phase?"var(--text-muted)":"var(--text-dim)",cursor:s.id.trim()&&"loading"!==u.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===u.phase?c("models.catalogFilling"):c("models.catalogFill")}),(0,r.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:c("models.catalogSource")})]}),T&&(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:8,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:M,fontSize:10},children:[(0,r.jsx)("span",{title:T,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:T}),w.current&&(0,r.jsx)("button",{onClick:()=>{let e=w.current;e&&(w.current=null,a(e),p({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:c("models.catalogUndo")})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(az,{children:c("models.capabilities")}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginTop:8},children:[(0,r.jsx)(aP,{label:c("models.reasoning"),checked:s.reasoning??!1,onChange:e=>C("reasoning",e||void 0)}),(0,r.jsx)(aP,{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)(az,{children:c("models.modelSpecs")}),(0,r.jsx)("button",{type:"button",onClick:()=>{if(h)return void m(!1);S.current=s.cost;let e=sw(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)(aE,{label:c("models.contextWindow"),children:(0,r.jsx)(aA,{value:void 0!==s.contextWindow?String(s.contextWindow):"",onChange:e=>C("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(aE,{label:c("models.maxOutputTokens"),children:(0,r.jsx)(aA,{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)(aE,{label:n,children:(0,r.jsx)(aA,{value:g[t],onChange:e=>{let n,r,i;return r=sS(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)}),sC(g)&&!sS(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)(aE,{label:c("models.baseUrlOverride"),children:(0,r.jsx)(aM,{value:s.baseUrl??"",onChange:e=>C("baseUrl",e.trim()||void 0),placeholder:n.baseUrl??c("models.providerDefaults"),mono:!0})}),(0,r.jsx)(aE,{label:c("models.apiOverride"),children:(0,r.jsx)(aL,{value:s.api??"",onChange:e=>C("api",e||void 0),options:aI})}),(0,r.jsxs)(aE,{label:c("models.headers"),children:[(0,r.jsx)(aU,{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)(aE,{label:c("models.imageMaxBytes"),children:[(0,r.jsx)(aA,{value:void 0===P?"":String(P),onChange:e=>{var t;let n,r,i,o;return a((t=e.trim()||void 0,n={...sx(s.inputLimits)?s.inputLimits:{}},r={...sx(n.images)?n.images:{}},i={...sx(r.resize)?r.resize:{}},void 0===t?delete i.maxBytes:i.maxBytes=sv(t)??t,Object.keys(i).length?r.resize=i:delete r.resize,Object.keys(r).length?n.images=r:delete n.images,o={...s},Object.keys(n).length?o.inputLimits=n:delete o.inputLimits,o))},placeholder:String(4718592),invalid:void 0===z&&void 0!==P}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[void 0!==z&&`${sy(z)} \xb7 `,c("models.imageMaxBytesHelp",{size:sy(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)(az,{children:c("models.compatibility")}),(0,r.jsx)(aP,{label:c("models.deepSeekThinkingCompat"),checked:aH(s),onChange:e=>a(function(e,t){if(t)return{...e,compat:{...e.compat??{},...aB}};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)(aP,{label:c("models.developerRole"),checked:!1!==a_(n,s).supportsDeveloperRole,onChange:e=>a(sN(s,"supportsDeveloperRole",e))}),(s.api??n.api)==="anthropic-messages"&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[(0,r.jsx)(aP,{label:c("models.adaptiveThinking"),checked:!0===a_(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 sN(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)(az,{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)(aD,{value:s.thinkingLevelMap,onChange:e=>C("thinkingLevelMap",e)})]})]})]})]})]})}function aK(e){let{provider:t,onRefresh:n,enabledModels:s,contextSettings:a}=e,[o,l]=(0,i.useState)({phase:"idle"}),{t:d}=(0,eW.s)(),[c,u]=(0,i.useState)(""),p=(0,i.useRef)(null),h=(0,i.useRef)(null);(0,i.useEffect)(()=>{("auth"===o.phase||"prompt"===o.phase)&&setTimeout(()=>h.current?.focus(),50)},[o.phase]),(0,i.useEffect)(()=>{l({phase:"idle"}),u(""),p.current?.close(),p.current=null},[t.id]),(0,i.useEffect)(()=>()=>{p.current?.close()},[]);let m=(0,i.useCallback)(()=>{p.current?.close(),l({phase:"connecting"}),u("");let e=new EventSource(`/api/auth/login/${encodeURIComponent(t.id)}`);p.current=e,e.onmessage=t=>{let r=JSON.parse(t.data);"auth"===r.type?(l({phase:"auth",url:r.url,instructions:r.instructions??null,token:r.token}),window.open(r.url,"_blank","noopener,noreferrer")):"device_code"===r.type?(l({phase:"device_code",userCode:r.userCode,verificationUri:r.verificationUri,intervalSeconds:r.intervalSeconds??null,expiresInSeconds:r.expiresInSeconds??null}),window.open(r.verificationUri,"_blank","noopener,noreferrer")):"prompt_request"===r.type?l({phase:"prompt",message:r.message,placeholder:r.placeholder??null,token:r.token}):"select_request"===r.type?l({phase:"select",message:r.message,options:r.options??[],token:r.token}):"progress"===r.type?l({phase:"progress",message:r.message}):"success"===r.type?(e.close(),l({phase:"success"}),n()):"error"===r.type?(e.close(),l({phase:"error",message:r.message})):"cancelled"===r.type&&(e.close(),l({phase:"idle"}))},e.onerror=()=>{e.close(),l(e=>"success"===e.phase?e:{phase:"error",message:d("models.connectionLost")})}},[t.id,n,d]),g=(0,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(t.id)}`,{method:"POST"}),l({phase:"idle"}),n()},[t.id,n]),f=(0,i.useCallback)(async(e,n)=>{if(n.trim()){l({phase:"progress",message:d("models.verifying")});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,code:n.trim()})});if(!r.ok){let e=await r.json().catch(()=>({}));l({phase:"error",message:e.error??d("models.serverError",{status:r.status})});return}u("")}catch(e){l({phase:"error",message:e instanceof Error?e.message:d("i18n.networkError")})}}},[t.id,d]),x=(0,i.useCallback)(async(e,n)=>{l({phase:"progress",message:d("i18n.continuing")});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,code:n})});if(!r.ok){let e=await r.json().catch(()=>({}));l({phase:"error",message:e.error??d("models.serverError",{status:r.status})})}}catch(e){l({phase:"error",message:e instanceof Error?e.message:d("i18n.networkError")})}},[t.id,d]),b="connecting"===o.phase||"progress"===o.phase||"auth"===o.phase||"device_code"===o.phase||"prompt"===o.phase||"select"===o.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:t.loggedIn&&"idle"===o.phase?0:16},children:[(0,r.jsxs)(sZ,{children:[(0,r.jsx)(sV,{children:(0,r.jsx)(az,{children:d("i18n.subscription")})}),(0,r.jsxs)(sJ,{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)(an,{size:"small",onClick:()=>{p.current?.close(),l({phase:"idle"})},children:d("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(an,{variant:"primary",size:"small",onClick:m,children:t.loggedIn?d("i18n.relogin"):d("i18n.login")}),t.loggedIn&&(0,r.jsx)(an,{variant:"danger",size:"small",onClick:g,children:d("i18n.disconnect")})]})]})]}),(0,r.jsxs)("div",{style:{minHeight:t.loggedIn&&"idle"===o.phase?0:48},children:["idle"===o.phase&&!t.loggedIn&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:d("models.oauthConnect",{provider:t.name})}),"connecting"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:d("i18n.openingBrowser")}),"select"===o.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:o.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:o.options.map(e=>(0,r.jsx)("button",{onClick:()=>x(o.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),("auth"===o.phase||"prompt"===o.phase)&&(0,r.jsx)(ax,{message:"auth"===o.phase?d("models.oauthPasteRedirect"):o.message,hint:"auth"===o.phase?(0,r.jsxs)(r.Fragment,{children:[d("models.oauthNoBrowser")," ",(0,r.jsx)("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",children:d("models.oauthOpenLoginPage")}),d("models.oauthOpenLoginPageEnd")]}):void 0,value:c,placeholder:"auth"===o.phase?"http://localhost:1455/auth/callback?code=…":o.placeholder??d("models.oauthValuePlaceholder"),submitLabel:d("i18n.submit"),inputRef:h,onValueChange:u,onSubmit:()=>void f(o.token,c)}),"device_code"===o.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:d("models.oauthDeviceCode")}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:o.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:o.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:o.verificationUri}),o.expiresInSeconds?` ${d("models.deviceCodeExpires",{minutes:Math.ceil(o.expiresInSeconds/60)})}`:""]})]}),"progress"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:o.message}),"success"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:d("i18n.connectedSuccessfully")}),"error"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:o.message})]}),(0,r.jsx)(ak,{providerId:t.id,enabled:t.loggedIn}),t.loggedIn&&(0,r.jsx)(af,{providerId:t.id,controller:s,contextSettings:a})]})}function aZ(e){let{provider:t,onRefresh:n,enabledModels:s,contextSettings:a}=e,[o,l]=(0,i.useState)(""),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(!1),{t:x}=(0,eW.s)();(0,i.useEffect)(()=>{l(""),m(null),f(!1)},[t.id]);let b=(0,i.useCallback)(async()=>{if(o.trim()){c(!0),m(null),f(!1);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:o.trim()})}),r=await e.json();!e.ok||r.error?m(r.error??`HTTP ${e.status}`):(l(""),f(!0),setTimeout(()=>f(!1),2e3),n())}catch(e){m(String(e))}finally{c(!1)}}},[o,t.id,n]),v=(0,i.useCallback)(async()=>{p(!0),m(null);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"DELETE"}),r=await e.json();!e.ok||r.error?m(r.error??`HTTP ${e.status}`):n()}catch(e){m(String(e))}finally{p(!1)}},[t.id,n]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(sZ,{children:[(0,r.jsx)(sV,{children:(0,r.jsx)(az,{children:"API Key"})}),(0,r.jsxs)(sJ,{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:t.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:t.configured?"#4ade80":"var(--text-dim)"},children:x(t.configured?"i18n.configured":"i18n.notConfigured")})]}),t.configured&&(0,r.jsx)(an,{variant:"danger",size:"small",onClick:v,disabled:u,children:x(u?"i18n.removing":"i18n.disconnect")})]})]}),!t.configured&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:1===t.modelCount?x("models.apiKeyEnableOne",{provider:t.displayName}):x("models.apiKeyEnable",{provider:t.displayName,count:t.modelCount})}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(aR,{value:o,onChange:l,onKeyDown:e=>{"Enter"===e.key&&o.trim()&&b()},placeholder:t.configured?x("models.replaceApiKey"):"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:b,disabled:d||!o.trim()||g,style:{padding:"6px 12px",background:g?"#16a34a":o.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:g?"#fff":o.trim()?"var(--accent-contrast)":"var(--text-dim)",cursor:d||!o.trim()||g?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[g&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),x(g?"i18n.saved":d?"i18n.saving":"i18n.save")]})]}),h&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:h}),(0,r.jsx)(ak,{providerId:t.id,enabled:t.configured}),t.configured&&(0,r.jsx)(af,{providerId:t.id,controller:s,contextSettings:a})]})}function aV(e){let{oauthProviders:t,apiKeyProviders:n,onSelectOAuth:s,onSelectApiKey:a,onAddCustom:o,onClose:l}=e,[d,c]=(0,i.useState)(""),{t:u}=(0,eW.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&&sM(h,e.id,e.name)),g=n.filter(e=>!e.configured&&sM(h,e.id,e.displayName)),f=!h||"custom".includes(h)||"openai-compatible".includes(h)||"anthropic-compatible".includes(h),x=m.length+g.length+ +!!f,b={display:"flex",flexDirection:"row",alignItems:"center",gap:8,padding:"10px 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:7,boxSizing:"border-box",cursor:"pointer",minWidth:0,textAlign:"left",transition:"border-color 0.12s, background 0.12s",width:"100%"};return(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&l()},onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.preventDefault(),e.stopPropagation(),l())},children:(0,r.jsxs)("div",{style:{width:820,maxWidth:"calc(100vw - 32px)",maxHeight:"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{ref:p,value:d,onChange:e=>c(e.target.value),placeholder:u("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===x?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:u("i18n.noProviders")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[f&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:u("i18n.custom")}),f&&(0,r.jsxs)("button",{onClick:()=>{o(),l()},style:b,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:u("i18n.customEndpoint")})]}),(0,r.jsx)("span",{style:{width:26,height:26,borderRadius:5,background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),m.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!f,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:u("i18n.subscriptions")}),m.map(e=>(0,r.jsxs)("button",{onClick:()=>{s(e.id),l()},style:b,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(av,{id:e.id,size:28})]},e.id)),g.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(m.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),g.map(e=>(0,r.jsxs)("button",{onClick:()=>{a(e.id),l()},style:b,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:1===e.modelCount?u("models.modelCountOne"):u("models.modelCount",{count:e.modelCount})})]}),(0,r.jsx)(av,{id:e.id,size:28})]},e.id))]})})]})})}function aJ(e){let{onClose:t,embedded:n=!1,cwd:s=null}=e,{t:a}=(0,eW.s)(),{openDetail:o,closeDetail:l}=sP(),d=function(e){let[t,n]=(0,i.useState)(null),[r,s]=(0,i.useState)(!0),[a,o]=(0,i.useState)(null),[l,d]=(0,i.useState)(null),c=(0,i.useRef)(null),u=(0,i.useRef)(null),p=(0,i.useRef)(null),[h,m]=(0,i.useState)(0);(0,i.useEffect)(()=>{let t=new AbortController;s(!0);let r=e?`?cwd=${encodeURIComponent(e)}`:"";return fetch(`/api/models/enabled${r}`,{signal:t.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);n(t),d(null)}).catch(e=>{t.signal.aborted||d({message:e instanceof Error?e.message:String(e)})}).finally(()=>{t.signal.aborted||s(!1)}),()=>t.abort()},[e,h]);let g=(0,i.useCallback)((t,r)=>{if(c.current){u.current={key:t,body:r};return}c.current=t,o(t),d(null),(async()=>{try{let t=await fetch("/api/models/enabled",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...e?{cwd:e}:{}})}),i=await t.json();if(!t.ok||i.error){let e=i.reason?au[i.reason]:void 0;d(e?{messageKey:e}:{message:i.error??`HTTP ${t.status}`});return}n(i)}catch(e){d({message:e instanceof Error?e.message:String(e)})}finally{c.current=null,o(null);let e=u.current;u.current=null,e&&p.current?.(e.key,e.body)}})()},[e]);p.current=g;let f=(0,i.useCallback)((e,t,n)=>{g(e,{op:"models",refs:t,enabled:n})},[g]),x=(0,i.useCallback)((e,t)=>{g(`provider:${e}`,{op:"provider",provider:e,enabled:t})},[g]),b=(0,i.useCallback)(()=>g("clear",{op:"clear"}),[g]),v=(0,i.useCallback)(()=>g("prune",{op:"prune"}),[g]),y=(0,i.useCallback)(()=>m(e=>e+1),[]),j=(0,i.useCallback)((e,n)=>{g("resync",{op:"resync",renames:e,modelRenames:n,fullyEnabled:(t?.providers??[]).filter(e=>e.models.length>0&&e.enabledCount===e.models.length).map(e=>e.id)})},[g,t]);return{view:t,loading:r,pending:a,failure:l,setModels:f,setProvider:x,clearScope:b,pruneStale:v,refresh:y,resync:j}}(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,j]=(0,i.useState)(!1),[k,w]=(0,i.useState)(aC),[S,C]=(0,i.useState)([]),[N,I]=(0,i.useState)([]),[$,E]=(0,i.useState)({}),[T,M]=(0,i.useState)(!1),[R,A]=(0,i.useState)(!1),L=(0,i.useRef)(new Set),P=(0,i.useRef)(new Map),z=(0,i.useRef)(new Map),O=(0,i.useRef)(new WeakMap),W=(0,i.useRef)(0),F=(0,i.useRef)(null),[D,B]=(0,i.useState)(null),[H,_]=(0,i.useState)(null),U=(0,i.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>{Array.isArray(e.oauthProviders)&&C(e.oauthProviders),Array.isArray(e.apiKeyProviders)&&I(e.apiKeyProviders),E(e.providerNames??{})}).catch(()=>{}).finally(()=>M(!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),L.current=new Set(Object.keys(t.providers??{})),z.current=sI(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)),U()},[U]),(0,i.useEffect)(()=>{k&&sl("models",JSON.stringify(k))},[k]),(0,i.useEffect)(()=>{if(k?.type!=="provider")return;let e=c.providers?.[k.name];e&&aN(e)&&(S.some(e=>e.id===k.name)?w({type:"oauth",providerId:k.name}):N.some(e=>e.id===k.name)&&w({type:"apikey",providerId:k.name}))},[N,c.providers,S,k]);let q=e=>({overrides:c.providers?.[e]?.modelOverrides,disabled:p||m||null!==b,onChange:(t,n)=>{try{u(function(e,t,n,r){let i={...e.providers},s={...Object.hasOwn(i,t)?i[t]:{}},a={...s.modelOverrides},o=Object.hasOwn(a,n)?a[n]:void 0;if(void 0!==o&&!sc(o))throw Error("Model override must be an object");let l={...o};return void 0===r?delete l.contextWindow:l.contextWindow=r,Object.keys(l).length?Object.defineProperty(a,n,{value:l,enumerable:!0,configurable:!0}):delete a[n],Object.keys(a).length?s.modelOverrides=a:delete s.modelOverrides,Object.keys(s).length?Object.defineProperty(i,t,{value:s,enumerable:!0,configurable:!0}):delete i[t],{...e,providers:i}}(c,e,t,n)),j(!1),x(null)}catch(e){x(String(e))}}}),K=(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]),Z=(0,i.useCallback)((e,t)=>{u(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),V=(0,i.useCallback)((e,t,n)=>{let r=function(e,t,n,r){let i=e.providers??{};if(!Object.hasOwn(i,n))return null;if(n===r)return e;if(Object.hasOwn(i,r))return null;let{renames:s,slots:a}=t,o=sT(t,n);o===r?s.delete(o):null!==o&&s.set(o,r);let l=a.get(n);l&&(a.delete(n),a.set(r,l));let d=Object.entries(i),c=d.findIndex(e=>{let[t]=e;return t===n});return d[c]=[r,d[c][1]],{...e,providers:Object.fromEntries(d)}}(e,{savedProviders:L.current,renames:P.current,slots:z.current},t,n);return r?(u(r),_(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},[]),J=(0,i.useCallback)((e,t)=>{V(c,e,t)?x(null):x(a("models.providerNameTaken",{name:t}))},[V,c,a]),G=(0,i.useCallback)(e=>{var t;let n,r,i=(null!==(n=sT(t={savedProviders:L.current,renames:P.current,slots:z.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??{});_(t=>t?.provider===e?null:t),u(i),w(s.length>0?{type:"provider",name:s[0]}:null),l()},[c,l]),Y=(0,i.useCallback)(e=>{s$(z.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})},[]),X=(0,i.useCallback)((e,t)=>{u(n=>{let r=new Set((n.providers?.[e]?.models??[]).map(e=>e.id));s$(z.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}}}})},[]),Q=(0,i.useCallback)((e,t,n)=>{u(r=>{let i=r.providers?.[e]??{},s=[...i.models??[]],a=O.current.get(s[t]);return a&&O.current.set(n,a),s[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:s}}}})},[]),ee=(0,i.useCallback)(e=>{e&&(u(e.config),j(!1),x(null),w(t=>t?.type==="model"&&t.providerName===e.providerName?{...t,index:e.order.indexOf(t.index)}:t))},[]),et=(0,i.useCallback)((e,t,n)=>{m||b||ee(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),sE(e,t,n,a)}(c,z.current,e,t,n))},[ee,c,b,m]),en=(0,i.useCallback)(e=>{if(!m&&!b){var t;let n,r;ee((t=z.current,n=c.providers?.[e]?.models??[],r=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),sE(c,t,e,[...n.keys()].sort((e,t)=>r.compare(sR(n[e]),sR(n[t]))))))}},[ee,c,b,m]),er=(0,i.useCallback)((e,t)=>{z.current.get(e)?.splice(t,1),u(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]];return i.splice(t,1),{...n,providers:{...n.providers??{},[e]:{...r,models:i.length?i:void 0}}}}),w({type:"provider",name:e}),l()},[l]),ei=(0,i.useCallback)(async()=>{if(b)return;g(!0),x(null),j(!1);let e=c,t=H?.name.trim();if(H&&t&&c.providers?.[H.provider]){let n=V(c,H.provider,t);if(!n){x(a("models.providerNameTaken",{name:t})),g(!1);return}e=n}try{var n=e=function(e){let t=structuredClone(e);if(!sc(t.providers))return t;for(let[e,n]of Object.entries(t.providers))if(sc(n)&&sc(n.modelOverrides))for(let[t,r]of Object.entries(n.modelOverrides)){if(!sc(r)||!Object.hasOwn(r,"contextWindow"))continue;let n=sp(r.contextWindow);if(void 0===n)throw new su(`${e}/${t}`);r.contextWindow=n}return t}(e);if(sg(n.providers))for(let[e,t]of Object.entries(n.providers)){if(!sg(t))continue;if(t.oauth&&!t.baseUrl)throw new sm(e,"baseUrl");let n=Array.isArray(t.models)&&t.models.some(sf),r=sg(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 sm(e,"empty")}var r=e;if(sx(r.providers)){for(let[e,t]of Object.entries(r.providers))if(sx(t)&&Array.isArray(t.models))for(let n of t.models){if(!sx(n)||"string"==typeof n.id&&!n.id.trim())continue;let t=sb(n);if(void 0!==t&&void 0===sv(t))throw new sj(`${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{j(!0),setTimeout(()=>j(!1),2e3);let t=[...P.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,z.current,P.current);L.current=new Set(Object.keys(e.providers??{})),z.current=sI(e),P.current.clear(),d.resync(t,n)}}catch(e){e instanceof sm?(x(a(a$[e.problem],{provider:e.provider})),w({type:"provider",name:e.provider})):e instanceof su?x(a("models.contextInvalid",{model:e.model})):x(e instanceof sj?a("models.imageMaxBytesInvalid",{model:e.model}):String(e))}finally{g(!1)}},[V,c,d,b,H,a]),es=Object.entries(c.providers??{}).filter(e=>{let[t,n]=e;if(!aN(n))return!0;let r=S.some(e=>e.id===t)||N.some(e=>e.id===t);return T&&!r}),ea=e=>{let t=function(e,t){if(!e||e.allEnabled)return null;let n=ad(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},eo=S.filter(e=>e.loggedIn),el=N.filter(e=>e.configured),ed=(()=>{if(!k)return null;if("oauth"===k.type){let e=S.find(e=>e.id===k.providerId);return e?(0,r.jsx)(aK,{provider:e,onRefresh:U,enabledModels:d,contextSettings:q(e.id)},e.id):null}if("apikey"===k.type){let e=N.find(e=>e.id===k.providerId);return e?(0,r.jsx)(aZ,{provider:e,onRefresh:U,enabledModels:d,contextSettings:q(e.id)},e.id):null}if("provider"===k.type){let e=c.providers?.[k.name];return e&&es.some(e=>{let[t]=e;return t===k.name})?(0,r.jsx)(aO,{name:k.name,editingName:H?.provider===k.name?H.name:k.name,provider:e,onChange:e=>Z(k.name,e),onEditingNameChange:e=>_(e===k.name?null:{provider:k.name,name:e}),onRename:e=>J(k.name,e),onDelete:()=>G(k.name),onAddModels:e=>X(k.name,e),enabledModels:d},k.name):null}let e=c.providers?.[k.providerName],t=e?.models?.[k.index];return t?(0,r.jsx)(aq,{providerName:k.providerName,provider:e,model:t,onChange:e=>Q(k.providerName,k.index,e),onDelete:()=>er(k.providerName,k.index)},`${k.providerName}-${k.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(sA,{embedded:n,title:a("common.models"),subtitle:"~/.pi/agent/models.json",closeLabel:a("i18n.close"),onClose:t,children:[(0,r.jsx)(ap,{controller:d}),(0,r.jsxs)(sW,{children:[(0,r.jsxs)(sF,{children:[(0,r.jsxs)(sD,{children:[eo.map(e=>{let t=k?.type==="oauth"&&k.providerId===e.id;return(0,r.jsxs)(sU,{active:t,onClick:()=>w({type:"oauth",providerId:e.id}),children:[(0,r.jsx)(av,{id:e.id,size:16}),(0,r.jsx)(sq,{className:"is-grow",children:e.name}),ea(e.id)]},e.id)}),el.map(e=>{let t=k?.type==="apikey"&&k.providerId===e.id;return(0,r.jsxs)(sU,{active:t,onClick:()=>w({type:"apikey",providerId:e.id}),children:[(0,r.jsx)(av,{id:e.id,size:16}),(0,r.jsx)(sq,{className:"is-grow",children:e.displayName}),ea(e.id)]},e.id)}),(eo.length>0||el.length>0)&&es.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")}):es.map(e=>{var t;let[n,i]=e,s=k?.type==="provider"&&k.name===n,o=i.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)(sU,{onClick:()=>w({type:"provider",name:n}),active:s,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)(sq,{className:"is-grow",children:(t=$[n]??d.view?.providers.find(e=>e.id===n)?.name,i.name?.trim()||t?.trim()||n)}),ea(n)]}),o.map((e,t)=>{var i;let s,o,l=k?.type==="model"&&k.providerName===n&&k.index===t,d=O.current.get(e);d||(d=`model-${++W.current}`,O.current.set(e,d));let c=D?.providerName===n&&D.index===t?D:null;return(0,r.jsxs)(sU,{active:l,className:"models-sidebar-indented-item",style:c?{boxShadow:`inset 0 ${c.after?"-2px":"2px"} 0 var(--accent)`}:void 0,"aria-keyshortcuts":"Alt+ArrowUp Alt+ArrowDown",onClick:()=>w({type:"model",providerName:n,index:t}),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(),et(n,t,t+r))},...(i=e.id,s=e=>{var r;let i,s=F.current;if(s?.providerName!==n)return null;let a=e.currentTarget.getBoundingClientRect(),o=e.clientY>=a.top+a.height/2;return{from:s.index,to:(r=s.index,r<(i=o?t+1:t)?i-1:i),after:o}},{draggable:!m&&!b,onDragStart:e=>{F.current={providerName:n,index:t},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:n,index:t,after:r.after};B(e=>e?.providerName===i?.providerName&&e?.index===i?.index&&e?.after===i?.after?e:i)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||B(e=>e?.providerName===n&&e.index===t?null:e)},onDrop:e=>{let t=s(e);t&&(e.preventDefault(),et(n,t.from,t.to),o())},onDragEnd:o=()=>{F.current=null,B(null)}}),children:[(0,r.jsx)(sq,{className:"is-grow",style:{color:e.id?"var(--text-muted)":"var(--text-dim)"},children:sR(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)(sU,{className:"models-sidebar-indented-item models-sidebar-add-item",onClick:e=>{e.stopPropagation(),Y(n)},children:(0,r.jsxs)(sq,{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||o.length<2,onClick:()=>en(n),children:"A–Z"})]})]},n)})]}),(0,r.jsx)(ai,{onClick:e=>{e.preventDefault(),A(!0)},children:a("i18n.addProvider")})]}),(0,r.jsx)(s7,{children:(0,r.jsx)(sK,{className:"is-fill",children:p?null:ed??(0,r.jsx)(s9,{children:a("i18n.selectProviderModel")})})})]}),(0,r.jsxs)(ae,{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)(an,{onClick:t,children:a("i18n.cancel")}),(0,r.jsxs)(an,{variant:"primary",onClick:ei,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")})]})]})]}),R&&(0,r.jsx)(aV,{oauthProviders:S,apiKeyProviders:N,onSelectOAuth:e=>{w({type:"oauth",providerId:e}),o()},onSelectApiKey:e=>{w({type:"apikey",providerId:e}),o()},onAddCustom:()=>{K(),o()},onClose:()=>A(!1)})]})}let aG=null;async function aY(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(aG)return aG;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 aG=null,!1}})();return aG=t,t.then(e=>{e||aG!==t||(aG=null)}),t}var aX=n(9258);function aQ(e,t,n,r){return e.filter(e=>n(e)!==t&&(t||!r?.(e)))}function a0(e){return e?JSON.stringify([e.requiresTrust,e.trusted,e.decision,e.decisionPath??null,e.inherited]):""}function a1(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function a2(e,t){return t("project"===e?"skills.scope.project":"global"===e?"skills.scope.global":"skills.scope.path")}function a4(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function a8(e,t){return e?e.slice(0,8):t}function a6(e){let{skill:t,cwd:n,onToggle:s,toggling:a,saveError:o,updateStatus:l,checkingUpdate:d,updating:c,updateError:u,onCheckUpdate:p,onUpdate:h}=e,{t:m}=(0,eW.s)(),g=a1(t),f=!t.disableModelInvocation,[x,b]=(0,i.useState)(null),[v,y]=(0,i.useState)(null),j=t.filePath.split(/[\\/]/).pop(),[k,w]=(0,i.useState)([]),S=k.at(-1)??j,C=(0,i.useRef)(null),N=(0,i.useRef)(null),[I,$]=(0,i.useState)(0),E=(0,i.useCallback)(e=>{let t=function(e,t){let n=e.indexOf("#"),[r,i]=[n<0?e:e.slice(0,n),n<0?"":e.slice(n+1)].map(e=>{try{return decodeURIComponent(e)}catch{return e}});if(!r)return{document:t,anchor:i};if(r.startsWith("/"))return{document:r,anchor:i};let s=t.split("/").slice(0,-1);for(let e of r.split("/"))".."===e&&s.length&&".."!==s[s.length-1]?s.pop():e&&"."!==e&&s.push(e);return{document:s.join("/"),anchor:i}}(e,S);N.current=t.anchor,t.document===S?$(e=>e+1):w(e=>[...e,t.document])},[S]);return(0,i.useLayoutEffect)(()=>{let e=N.current,t=C.current;null!==e&&(null!==x||v)&&t&&(N.current=null,((e?t.querySelector(`[data-heading-anchor="${CSS.escape(e)}"]`):null)??t).scrollIntoView({block:"start"}))},[x,v,I]),(0,i.useEffect)(()=>{let e=new AbortController;return b(null),y(null),(async()=>{try{var r;let i=new URLSearchParams({cwd:n,filePath:t.filePath});S!==j&&i.set("document",S);let s=await fetch(`/api/skills/content?${i}`,{signal:e.signal}),a=await s.json();if(!s.ok||a.error||"string"!=typeof a.content)throw Error(a.error??`HTTP ${s.status}`);b((r=a.content,(0,aX.yv)(r).rest.trim()))}catch(t){if(e.signal.aborted)return;y(t instanceof Error?t.message:String(t))}})(),()=>e.abort()},[n,t.filePath,S,j]),(0,r.jsxs)(sK,{children:[(0,r.jsxs)("div",{className:"skill-detail-heading",children:[(0,r.jsxs)(sZ,{children:[(0,r.jsxs)(sV,{children:[(0,r.jsx)(s1,{scope:g,children:a2(g,m)}),(0,r.jsx)("span",{className:"config-detail-path",children:"project"===g?ec(t.filePath,n):ed(t.filePath)})]}),(0,r.jsx)(sJ,{children:(0,r.jsx)(ar,{checked:f,loading:a,label:m(f?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),onChange:()=>s(t)})})]}),(0,r.jsxs)("div",{className:"skill-detail-status-row",children:[!f&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:m("i18n.hiddenButInvocable")}),o&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:o})]})]}),t.install?.skillsShUrl&&(0,r.jsx)(sX,{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)(sX,{label:m("i18n.version"),children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:a8(l?.currentVersion??t.install.versionHash,m("i18n.unknown"))}),t.install.canCheckForUpdates&&(0,r.jsx)(an,{size:"small",onClick:p,disabled:d||c,children:m("i18n.check")}),l?.state==="update-available"&&(0,r.jsx)("span",{className:"skill-version-value is-update",children:a8(l.latestVersion,m("i18n.unknown"))}),(d||l&&"update-available"!==l.state)&&(0,r.jsx)("span",{className:`skill-update-status ${d?"is-checking":l?.state==="up-to-date"?"is-success":l?.state==="error"?"is-error":"is-muted"}`,children:d?m("i18n.checking"):l?.state==="up-to-date"?m("i18n.upToDate"):l?.state==="unsupported"?m("i18n.automaticChecksUnavailable"):l?.message||m("i18n.checkFailed")}),l?.state==="update-available"&&(0,r.jsx)(an,{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)(sX,{label:m("config.name"),children:(0,r.jsx)("span",{className:"skill-name-value",children:t.name})}),(0,r.jsx)(sX,{label:m("i18n.description"),children:(0,r.jsx)("span",{className:"skill-description",children:t.description})}),(0,r.jsxs)(sX,{label:m("skills.instructions"),ref:C,children:[k.length>0&&(0,r.jsx)(sZ,{children:(0,r.jsxs)(sV,{children:[(0,r.jsx)(an,{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)(nC.m,{className:"skill-instructions",cwd:[t.baseDir,...S.split("/").slice(0,-1)].join("/"),onNavigateLink:E,children:x}):(0,r.jsx)("span",{className:"skill-instructions-status",children:m("skills.noInstructions")})]})]})}function a3(e){let{cwd:t,installedPackages:n,projectResourcesLoaded:s,onInstalled:a}=e,{t:o}=(0,eW.s)(),[l,d]=(0,i.useState)(""),[c,u]=(0,i.useState)([]),[p,h]=(0,i.useState)(!1),[m,g]=(0,i.useState)(null),[f,x]=(0,i.useState)(null),[b,v]=(0,i.useState)(null),[y,j]=(0,i.useState)(new Set),[k,w]=(0,i.useState)("global"),S=(0,i.useRef)(null);(0,i.useEffect)(()=>{S.current?.focus()},[]);let C=(0,i.useCallback)(async e=>{if(e.trim()){h(!0),g(null),u([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),n=await t.json();if(n.error)return void g(n.error);u(n.results??[]),0===(n.results??[]).length&&g(o("i18n.noSkills"))}catch(e){g(String(e))}finally{h(!1)}}},[o]),N=(0,i.useCallback)(async e=>{x(e),v(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:e,scope:k,cwd:t})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);j(t=>new Set(t).add(`${k}:${e}`)),a()}catch(e){v(String(e))}finally{x(null)}},[a,k,t]),I="global"===k?"~/.pi/agent/skills/":`${ed(t)}/.pi/skills/`;return(0,r.jsxs)(sK,{className:"is-full-height",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)(s8,{title:o("i18n.addSkill"),catalogs:[{href:"https://skills.sh",label:"skills.sh"}],target:(0,r.jsx)(s4,{value:k,label:o("config.saveTo"),options:[{value:"global",label:a2("global",o)},{value:"project",label:a2("project",o),disabled:!s}],path:I,disabledReason:o("trust.projectScopeUnavailable"),onChange:w})}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:S,value:l,onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&C(l)},placeholder:o("i18n.skillSearchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:12,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",outline:"none"}}),(0,r.jsx)(an,{variant:"primary",onClick:()=>C(l),disabled:p||!l.trim(),children:p?o("i18n.searching"):o("i18n.search")})]}),m&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:m}),b&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:b})]}),c.length>0&&(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:c.map(e=>{let t=n[k].has(e.package)||y.has(`${k}:${e.package}`),i=f===e.package,s=e.package.indexOf("@"),a=s>-1?e.package.slice(0,s):e.package,l=s>-1?e.package.slice(s+1):null;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:l??a}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:a}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,r.jsx)(an,{size:"small",onClick:()=>!t&&!i&&N(e.package),disabled:t||i||null!==f,style:{flexShrink:0,background:t?"rgba(34,197,94,0.1)":"none",color:t?"#16a34a":i?"var(--accent)":"var(--text-muted)"},children:t?`✓ ${o("i18n.installed")}`:i?o("i18n.installing"):o("i18n.install")})]},e.package)})})]})}function a5(e){let{cwd:t,onClose:n,embedded:s=!1,trust:a}=e,{t:o}=(0,eW.s)(),[l,d]=(0,i.useState)([]),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(null),[m,g]=(0,i.useState)(()=>so("skills",t)),[f,x]=(0,i.useState)(new Set),[b,v]=(0,i.useState)(null),[y,j]=(0,i.useState)(null),[k,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=a0(a),D=(0,i.useRef)(F);(0,i.useEffect)(()=>{D.current!==F&&(D.current=F,W())},[F,W]),(0,i.useEffect)(()=>{m&&sl("skills",m,t)},[t,m]);let B=(0,i.useCallback)(async e=>{let n=(e?[e]:l.filter(e=>!!e.install)).map(a4).filter(e=>!!e);if(0!==n.length){P(null),E(e=>new Set([...e,...n])),e||M(!0);try{let n=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,package:e?.install?.package,scope:e?.install?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);I(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){P(e instanceof Error?e.message:String(e))}finally{E(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),e||M(!1)}}},[t,l]),H=(0,i.useCallback)(async e=>{if(!e.install)return;let n=a4(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=aQ(t,n,e=>!e.disableModelInvocation);if(0===r.length)return;let i=r.map(e=>e.filePath),s=!n;x(e=>new Set([...e,...i])),j(e),v(null),w(null);try{let t=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePaths:i,disableModelInvocation:s})}),n=await t.json();if(!t.ok||n.error||!n.results)throw Error(n.error??`HTTP ${t.status}`);let a=n.results;d(e=>{let t;return t=new Set(a.filter(e=>!e.error).map(e=>e.filePath)),e.map(e=>t.has(e.filePath)?{...e,disableModelInvocation:s}:e)});let l=a.filter(e=>e.error);if(l.length>0){let t=new Map(r.map(e=>[e.filePath,e.name]));w({group:e,error:[o("skills.bulkFailed",{count:l.length,total:a.length}),...l.map(e=>`${t.get(e.filePath)??e.filePath}: ${e.error}`)].join("\n")})}}catch(t){w({group:e,error:t instanceof Error?t.message:String(t)})}finally{j(null),x(e=>{let t=new Set(e);for(let e of i)t.delete(e);return t})}},[o]),q=l.find(e=>e.filePath===m)??null,K=c||f.size>0||null!==R;return(0,r.jsxs)(sA,{embedded:s,title:o("common.skills"),subtitle:ed(t),closeLabel:o("i18n.close"),onClose:n,children:[!z&&(0,r.jsx)(s5,{message:o("trust.skillsNotLoaded")}),(0,r.jsxs)(sW,{children:[(0,r.jsxs)(sF,{children:[(0,r.jsx)(sD,{children:c?(0,r.jsx)("div",{className:"config-sidebar-message",children:o("i18n.loading")}):p?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:p}):0===l.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:o("i18n.noSkills")}):(()=>{let e=[],t={project:o("skills.scope.project"),global:o("skills.scope.global"),path:o("skills.scope.path")};for(let{label:n,matches:r}of[{label:`${t.project} / skills.sh`,matches:e=>"project"===a1(e)&&!!e.install?.skillsShUrl},{label:t.project,matches:e=>"project"===a1(e)&&!e.install?.skillsShUrl},{label:`${t.global} / skills.sh`,matches:e=>"global"===a1(e)&&!!e.install?.skillsShUrl},{label:t.global,matches:e=>"global"===a1(e)&&!e.install?.skillsShUrl},{label:t.path,matches:e=>"path"===a1(e)}]){let t=l.filter(r);t.length>0&&e.push({label:n,skills:t})}let n=e=>{let t,n,i=!S&&m===e.filePath,s=e.disableModelInvocation;return(0,r.jsxs)(sU,{active:i,onClick:()=>{g(e.filePath),C(!1)},children:[(0,r.jsx)(as,{active:!s}),(0,r.jsx)(sq,{className:`is-grow${s?" is-muted":""}`,children:e.name}),(n=(t=a4(e))?N[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:o("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"}))]},e.filePath)};return e.map(e=>{let{label:t,skills:i}=e,s=i.filter(e=>!e.disableModelInvocation).length,a=s===i.length;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(sB,{aside:(0,r.jsx)(sH,{enabled:s,total:i.length,disabled:K,loading:y===t,label:o(a?"skills.groupSwitchOn":"skills.groupSwitchOff",{group:t}),onChange:e=>void U(t,i,e)}),children:t}),k?.group===t&&(0,r.jsx)(s_,{error:k.error}),[...i.filter(e=>!e.disableModelInvocation),...i.filter(e=>e.disableModelInvocation)].map(n)]},t)})})()}),(0,r.jsx)(ai,{onClick:()=>C(!0),active:S,children:o("i18n.addSkill")})]}),(0,r.jsx)(s7,{children:(0,r.jsx)(sK,{className:"is-fill",children:S?(0,r.jsx)(a3,{cwd:t,projectResourcesLoaded:z,installedPackages:{global:new Set(l.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(l.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{W()}}):c?null:q?(0,r.jsx)(a6,{skill:q,cwd:t,onToggle:_,toggling:f.has(q.filePath),saveError:b,updateStatus:a4(q)?N[a4(q)]:void 0,checkingUpdate:!!a4(q)&&$.has(a4(q)),updating:R===a4(q),updateError:L,onCheckUpdate:()=>void B(q),onUpdate:()=>void H(q)},q.filePath):(0,r.jsx)(s9,{children:o("i18n.selectSkill")})})})]}),(0,r.jsxs)(ae,{status:Object.values(N).filter(e=>"update-available"===e.state).length>0&&(0,r.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(N).filter(e=>"update-available"===e.state).length," ",1===Object.values(N).filter(e=>"update-available"===e.state).length?o("i18n.update"):o("i18n.updates")]}),children:[!s&&(0,r.jsx)(an,{onClick:n,children:o("i18n.close")}),l.some(e=>!!e.install)&&(0,r.jsx)(an,{variant:"secondary",onClick:()=>void B(),disabled:T||null!==R,children:T?o("i18n.checking"):o("i18n.checkUpdates")})]})]})}let a9={builtin:0,global:1,workspace:2,project:3},a7=["read","bash","edit","write","grep","find","ls"],oe=["","off","minimal","low","medium","high","xhigh","max"],ot={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},on={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"},or={background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"default"};function oi(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 os(e){return`${e.scope}:${e.name}`}function oa(e){return"global"===e||"project"===e}function oo(e){return oa(e)||"builtin"===e}function ol(e){let{label:t,children:n}=e;return(0,r.jsx)(sX,{label:t,children:n})}function od(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 oc(e){let{cwd:t,sessionId:n=null,onClose:s,onReloaded:a,embedded:o=!1,trust:l}=e,d=(0,eF.a)(),{t:c}=(0,eW.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)(()=>so("agents",t)),[j,k]=(0,i.useState)(ot),[w,S]=(0,i.useState)("view"),[C,N]=(0,i.useState)("global"),[I,$]=(0,i.useState)(!0),[E,T]=(0,i.useState)(!1),[M,R]=(0,i.useState)(!1),[A,L]=(0,i.useState)(!1),[P,z]=(0,i.useState)(null),[O,W]=(0,i.useState)(!1),[F,D]=(0,i.useState)(10),[B,H]=(0,i.useState)(!0),[_,U]=(0,i.useState)(!1),[q,K]=(0,i.useState)(null),[Z,V]=(0,i.useState)(!1),[J,G]=(0,i.useState)(!1),Y=(0,i.useMemo)(()=>u.find(e=>os(e)===v)??null,[u,v]),X=(0,i.useMemo)(()=>h.map(e=>({provider:e.provider,providerName:e.providerName,modelId:e.id,name:e.name})),[h]),Q=(0,i.useCallback)(async e=>{$(!0),z(null);try{let n=await fetch(`/api/subagents/profiles?cwd=${encodeURIComponent(t)}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);let i=r.profiles??[];p(i);let s=e??so("agents",t),a=i.find(e=>os(e)===s)??i.find(e=>"project"===e.scope)??i.find(e=>"global"===e.scope)??i[0]??null;y(a?os(a):null),a&&(k(oi(a)),S(oa(a.scope)?"edit":"view"),oa(a.scope)&&N(a.scope))}catch(e){z(e instanceof Error?e.message:String(e))}finally{$(!1)}},[t]);(0,i.useEffect)(()=>{Q()},[Q]),(0,i.useEffect)(()=>{let e=new AbortController;return H(!0),K(null),(async()=>{try{let t=await fetch("/api/subagents/settings",{cache:"no-store",signal:e.signal}),n=await t.json();if(!t.ok||n.error||"boolean"!=typeof n.enabled)throw Error(n.error??`HTTP ${t.status}`);W(n.enabled),"number"==typeof n.maxConcurrent&&D(n.maxConcurrent)}catch(t){if(e.signal.aborted)return;K(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||H(!1)}})(),()=>e.abort()},[]),(0,i.useEffect)(()=>{v&&sl("agents",v,t)},[t,v]);let ee=a0(l);(0,i.useEffect)(()=>{let e=new AbortController;return f(!0),b(null),(async()=>{try{let n=await fetch(`/api/models?cwd=${encodeURIComponent(t)}`,{signal:e.signal}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);m(r.modelList??[]),b(r.modelError??null)}catch(t){if(e.signal.aborted)return;b(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||f(!1)}})(),()=>e.abort()},[t,ee]);let et=async()=>{T(!0),z(null),R(!1);try{let e=await fetch("/api/subagents/profiles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:C,profile:j})}),n=await e.json();if(!e.ok||n.error||!n.profile)throw Error(n.error??`HTTP ${e.status}`);await Q(os(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&&oa(Y.scope)&&window.confirm(c("agents.deleteConfirm",{name:Y.displayName}))){T(!0),z(null);try{let e=await fetch("/api/subagents/profiles",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:Y.scope,name:Y.name})}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);await Q()}catch(e){z(e instanceof Error?e.message:String(e))}finally{T(!1)}}},er="view"!==w,ei="create"===w,es=!er||E||A,ea=ei?C:Y?.scope,eo=ei?"global"===C?`~/.pi/agent/agents/${j.name||"..."}.md`:`./.pi/agents/${j.name||"..."}.md`:Y?(Y.filePath?"project"===Y.scope||"workspace"===Y.scope?ec(Y.filePath,t):ed(Y.filePath):null)??c("agents.builtinPath"):"",el=ei?eo:Y?.filePath??eo,eu=e=>h.some(t=>`${t.provider}/${t.id}`===e),ep=j.model&&function(e,t){if(t(e))return e;let n=e.lastIndexOf(":"),r=e.slice(n+1);return n>0&&r&&oe.includes(r)?e.slice(0,n):e}(j.model,eu),eh=!ep||eu(ep),em=(()=>{if(!ep)return null;let e=ep.indexOf("/");return e<0?{provider:"",modelId:ep}:{provider:ep.slice(0,e),modelId:ep.slice(e+1)}})(),eg=es?{...on,...or}:on,ef=ei?es:!Y||!oo(Y.scope)||E||A,ex=(e,t)=>{k(n=>({...n,[e]:t}))},eb=0===j.tools.length&&!j.loadSkills&&!j.loadExtensions,ev=async e=>{if(ei)return void ex("enabled",e);if(Y&&oo(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=>os(e)===os(i)?i:e)),k(e=>({...e,enabled:i.enabled}))}catch(e){z(e instanceof Error?e.message:String(e))}finally{L(!1)}}},ey=async e=>{U(!0),K(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),r=await t.json();if(!t.ok||r.error||"boolean"!=typeof r.enabled)throw Error(r.error??`HTTP ${t.status}`);W(r.enabled),V(!!n)}catch(e){K(e instanceof Error?e.message:String(e))}finally{U(!1)}},ej=async e=>{D(e),K(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxConcurrent:e})}),n=await t.json();if(!t.ok||n.error||"number"!=typeof n.maxConcurrent)throw Error(n.error??`HTTP ${t.status}`);D(n.maxConcurrent)}catch(e){K(e instanceof Error?e.message:String(e))}},ek=async()=>{if(n){G(!0),K(null);try{await r2(n,{type:"reload"}),V(!1),a?.()}catch(e){K(e instanceof Error?e.message:String(e))}finally{G(!1)}}};return(0,r.jsxs)(sA,{embedded:o,title:c("common.agents"),subtitle:ed(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)(an,{size:"small",onClick:()=>void ek(),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 ej(F)})]}),(0,r.jsx)(ar,{checked:O,disabled:B||J,loading:_,label:c("agents.builtInTitle"),onChange:e=>void ey(e)})]})]}),(0,r.jsxs)(sW,{children:[(0,r.jsxs)(sF,{children:[(0,r.jsx)(sD,{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)(sB,{children:c(`agents.scope.${e}`)}),t.map(e=>{let t,n,i=(t=e.name.toLowerCase(),n=a9[e.scope],u.some(e=>e.name.toLowerCase()===t&&a9[e.scope]>n));return(0,r.jsxs)(sU,{active:v===os(e)&&!ei,onClick:()=>{y(os(e)),k(oi(e)),S(oa(e.scope)?"edit":"view"),oa(e.scope)&&N(e.scope),z(null)},children:[(0,r.jsx)(as,{active:e.enabled}),(0,r.jsx)(sq,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.displayName}),i&&(0,r.jsx)("span",{className:"agents-overridden-label",children:c("agents.overridden")})]},os(e))})]},e)})}),(0,r.jsx)(ai,{active:ei,onClick:()=>{let e="custom-agent",t=2;for(;u.some(t=>t.name===e);)e=`custom-agent-${t++}`;y(null),k({...ot,name:e,displayName:e}),S("create"),N("global"),z(null)},children:c("agents.new")})]}),(0,r.jsx)(s7,{children:(0,r.jsx)(sK,{className:"is-fill",children:Y||ei?(0,r.jsxs)(sK,{children:[(0,r.jsxs)(sZ,{children:[(0,r.jsx)(sV,{children:ei?(0,r.jsx)(s4,{value:C,label:c("config.saveTo"),options:["global","project"].map(e=>({value:e,label:c(`agents.scope.${e}`),disabled:E})),path:eo,onChange:N}):(0,r.jsxs)(r.Fragment,{children:[ea&&(0,r.jsx)(s1,{scope:ea,children:c(`agents.scope.${ea}`)}),(0,r.jsx)("span",{title:el,className:"config-detail-path",children:eo})]})}),(0,r.jsxs)(sJ,{children:[Y&&("view"===w||"edit"===w)&&(0,r.jsx)(an,{size:"small",onClick:()=>{if(!Y)return;let e=function(e,t){let n=new Set(t.map(e=>e.name.toLowerCase())),r=`${e}-copy`,i=r,s=2;for(;n.has(i.toLowerCase());)i=`${r}-${s++}`;return i}(Y.name,u);y(null),k({...oi(Y),name:e,displayName:c("agents.copyName",{name:Y.displayName})}),S("create"),N(oa(Y.scope)?Y.scope:"global"),z(null)},disabled:E||A,children:c("agents.duplicate")}),Y&&oa(Y.scope)&&"edit"===w&&(0,r.jsx)(an,{variant:"danger",size:"small",onClick:()=>void en(),disabled:E||A,children:c("agents.delete")}),(0,r.jsx)(ar,{checked:j.enabled,disabled:ef,label:j.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)(ol,{label:c("agents.name"),children:ei?(0,r.jsx)("input",{"aria-label":c("agents.name"),value:j.name,disabled:es,onChange:e=>ex("name",e.target.value),style:on}):(0,r.jsx)("code",{style:{minHeight:34,display:"flex",alignItems:"center",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:j.name})}),(0,r.jsx)(ol,{label:c("agents.displayName"),children:(0,r.jsx)("input",{"aria-label":c("agents.displayName"),value:j.displayName,disabled:es,onChange:e=>ex("displayName",e.target.value),style:eg})})]}),(0,r.jsx)(ol,{label:c("agents.description"),children:(0,r.jsx)("input",{"aria-label":c("agents.description"),value:j.description,disabled:es,onChange:e=>ex("description",e.target.value),style:eg})}),(0,r.jsx)(ol,{label:c("agents.prompt"),children:(0,r.jsx)("textarea",{className:"agents-system-prompt","aria-label":c("agents.prompt"),value:j.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)(ol,{label:c("agents.tools"),children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 16px"},children:a7.map(e=>(0,r.jsx)(od,{label:e,disabled:es,checked:j.tools.includes(e),onChange:t=>ex("tools",t?[...j.tools,e]:j.tools.filter(t=>t!==e))},e))})}),(0,r.jsxs)(ol,{label:c("agents.resources"),children:[(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 20px"},children:[(0,r.jsx)(od,{label:c("agents.loadSkills"),disabled:es,checked:j.loadSkills,onChange:e=>ex("loadSkills",e)}),(0,r.jsx)(od,{label:c("agents.loadExtensions"),disabled:es,checked:j.loadExtensions,onChange:e=>ex("loadExtensions",e)}),(0,r.jsx)(od,{label:c("agents.mcp"),disabled:es||eb&&"on"!==j.mcp,checked:"on"===j.mcp,onChange:e=>ex("mcp",e?"on":"off")})]}),j.loadSkills&&void 0!==j.skills&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:j.skills.length>0?c("agents.skillsOnly",{skills:j.skills.join(", ")}):c("agents.skillsNone")}),j.loadExtensions&&void 0!==j.extensions&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:j.extensions.length>0?c("agents.extensionsOnly",{extensions:j.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"===j.mcp&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:c("agents.mcpHint")})]}),(0,r.jsx)(ol,{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:j.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)(ol,{label:c("agents.model"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(n3,{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:j.model&&!eh?c("agents.modelUnavailable",{model:j.model}):j.model!==ep?j.model:void 0,disabled:es||g||0===h.length&&!j.model,ariaLabel:c("agents.model"),variant:"field",placement:"auto"}),x&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:10},children:x})]})}),(0,r.jsx)(ol,{label:c("agents.thinking"),children:(0,r.jsx)("select",{"aria-label":c("agents.thinking"),value:j.thinking??"",disabled:es,onChange:e=>ex("thinking",e.target.value||void 0),style:eg,children:oe.map(e=>(0,r.jsx)("option",{value:e,children:e||c("agents.inherit")},e||"default"))})}),(0,r.jsx)(ol,{label:c("agents.maxTurns"),children:(0,r.jsx)("input",{"aria-label":c("agents.maxTurns"),type:"number",min:1,value:j.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)(od,{label:c("agents.inheritContext"),disabled:es,checked:j.inheritContext,onChange:e=>ex("inheritContext",e)}),(0,r.jsx)(od,{label:c("agents.background"),disabled:es,checked:j.runInBackground,onChange:e=>ex("runInBackground",e)})]})]}):(0,r.jsx)(s9,{children:c("agents.empty")})})})]}),(0,r.jsx)(ae,{status:(q||P)&&(0,r.jsx)("span",{role:"alert",style:{color:"#ef4444"},children:q||P}),children:er&&(0,r.jsxs)(an,{variant:"primary",onClick:()=>void et(),disabled:E||M||A||!j.name.trim(),className:M?"is-success":void 0,children:[M&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:M?c("i18n.saved"):E?c("agents.saving"):c("agents.save")})]})})]})}let ou=["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"];function op(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function oh(e){return`${e.scope}\0${e.source}`}function om(e){return`extension\0${e.path}`}function og(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function of(e,t){return t(`plugins.status.${e}`)}function ox(e){return`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`}function ob(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function ov(e){let{pkg:t}=e,{t:n}=(0,eW.s)(),i=[["extension",n("i18n.extensions")],["skill",n("i18n.skills")],["prompt",n("i18n.prompts")],["theme",n("i18n.themes")]].map(e=>{let[n,r]=e;return{kind:n,label:r,resources:t.resources.filter(e=>e.kind===n)}}).filter(e=>e.resources.length>0);return 0===i.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:n(t.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:i.map((e,t)=>(0,r.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function oy(e){let{cwd:t,source:n,scope:i,projectResourcesLoaded:s,busy:a,actionError:o,onSourceChange:l,onScopeChange:d,onInstall:c}=e,{t:u}=(0,eW.s)();return(0,r.jsx)(s6,{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)(s4,{value:i,label:u("config.saveTo"),options:[{value:"global",label:og("global",u)},{value:"project",label:og("project",u),disabled:!s}],path:"project"===i?`${ed(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:op,onValueChange:l,onSubmit:c,examplesLabel:u("config.examples"),examples:ou,error:o,children:(0,r.jsx)(an,{variant:"primary",onClick:c,disabled:a||!n.trim(),className:"is-pushed-right",children:u(a?"i18n.installing":"i18n.install")})})}function oj(e){let t,{pkg:n,cwd:s,busyKey:a,actionError:o,actionMessage:l,sessionId:d,updateStatus:c,checkingUpdate:u,updateError:p,onAction:h,onCheckUpdate:m,onReloadSession:g}=e,{t:f}=(0,eW.s)(),x=oh(n),b=(a?.endsWith(x)||a?.startsWith("bulk:"))??!1,v="reload"===a,y=!n.disabled,j=n.canCheckForUpdates,k=c?.state==="update-available",w=n.description?.trim(),S=(0,i.useId)();return(0,r.jsxs)(sK,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(sZ,{className:"is-top-aligned",children:[(0,r.jsxs)(sV,{children:[(0,r.jsx)(s1,{scope:n.scope,children:og(n.scope,f)}),n.disabled?(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:f("i18n.disabled")}):n.filtered&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:f("i18n.filtered")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.source})]}),(0,r.jsxs)(sJ,{children:[(0,r.jsx)(an,{size:"small",variant:k?"primary":void 0,onClick:k||!j?()=>h("update",n):m,disabled:b||v||u,title:k?f("i18n.updateAvailable"):void 0,children:f(a===`update:${x}`?"i18n.updating":u?"i18n.checking":k||!j?"i18n.update":"i18n.check")}),(0,r.jsx)(an,{size:"small",onClick:g,disabled:!d||v||b,"aria-describedby":d?void 0:S,children:f(v?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)(an,{variant:"danger",size:"small",onClick:()=>h("remove",n),disabled:b||v,children:f(a===`remove:${x}`?"i18n.removing":"i18n.remove")}),(0,r.jsx)(ar,{checked:y,loading:b||v,onChange:()=>h(n.disabled?"enable":"disable",n),label:f(n.disabled?"i18n.enablePackage":"i18n.disablePackage")})]})]}),!d&&(0,r.jsx)("div",{id:S,className:"config-detail-heading-note",children:f("i18n.openSessionToReload")})]}),(0,r.jsxs)(sQ,{children:[w&&(0,r.jsx)(s0,{label:f("i18n.description"),children:w}),(0,r.jsx)(s0,{label:f("i18n.status"),tone:"plain",style:{color:ob(n.status),textTransform:"capitalize"},children:of(n.status,f)}),(0,r.jsxs)(s0,{label:f("i18n.version"),tone:"plain",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:(t=[],n.version&&t.push(f("i18n.installedVersion",{version:n.version})),n.configuredVersion&&t.push(f("i18n.configuredVersion",{version:n.configuredVersion})),t.length?t.join(" \xb7 "):f("i18n.unknown"))}),k&&(0,r.jsx)("span",{className:"skill-version-value is-update",title:c.displayName,children:f("i18n.updateAvailable")}),j&&(u||c&&!k)&&(0,r.jsx)("span",{className:`skill-update-status ${u?"is-checking":c?.state==="up-to-date"?"is-success":c?.state==="error"?"is-error":"is-muted"}`,children:u?f("i18n.checking"):c?.state==="up-to-date"?f("i18n.upToDate"):c?.state==="unsupported"?f("i18n.automaticChecksUnavailable"):c?.message||f("i18n.checkFailed")})]}),p&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:p})]}),(0,r.jsx)(s0,{label:f("i18n.package"),mono:!0,children:n.packageName??f("i18n.unknown")}),(0,r.jsx)(s0,{label:f("i18n.resources"),children:function(e,t){if(e.disabled)return t("i18n.disabled");let n=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t("i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t("i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t("i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t("i18n.themeShort")}):""].filter(Boolean);return n.length?n.join(" \xb7 "):t("i18n.noResources")}(n,f)}),(0,r.jsx)(s0,{label:f("i18n.installedPath"),tone:n.installedPath?"muted":"error",mono:!0,children:n.installedPath?ed(n.installedPath):f("i18n.notFound")}),(0,r.jsx)(s0,{label:f("i18n.cwd"),tone:"dim",mono:!0,children:ed(s)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)(sY,{children:f("i18n.resolvedResources")}),(0,r.jsx)(ov,{pkg:n})]}),l&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:l}),o&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:o})]})}function ok(e){let{extension:t}=e,{t:n}=(0,eW.s)(),i=t.enabled?"loaded":"disabled";return(0,r.jsxs)(sK,{children:[(0,r.jsx)(sZ,{children:(0,r.jsxs)(sV,{children:[(0,r.jsx)(s1,{scope:t.scope,children:og(t.scope,n)}),(0,r.jsx)(sG,{children:t.name})]})}),(0,r.jsxs)(sQ,{children:[(0,r.jsx)(s0,{label:n("i18n.status"),tone:"plain",style:{color:t.enabled?"var(--accent)":"var(--text-dim)"},children:of(i,n)}),(0,r.jsx)(s0,{label:n("i18n.installedPath"),mono:!0,children:ed(t.path)})]})]})}function ow(e){var t;let{cwd:n,sessionId:s,onClose:a,onReloaded:o,embedded:l=!1,trust:d}=e,{t:c}=(0,eW.s)(),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(!0),[g,f]=(0,i.useState)(null),[x,b]=(0,i.useState)(()=>so("plugins",n)),[v,y]=(0,i.useState)(!1),[j,k]=(0,i.useState)(""),[w,S]=(0,i.useState)("global"),[C,N]=(0,i.useState)(null),[I,$]=(0,i.useState)(null),[E,T]=(0,i.useState)(null),[M,R]=(0,i.useState)(null),[A,L]=(0,i.useState)({}),[P,z]=(0,i.useState)(new Set),[O,W]=(0,i.useState)(!1),[F,D]=(0,i.useState)(null),[B,H]=(0,i.useState)(!1),_=(0,i.useMemo)(()=>u?.packages??[],[u?.packages]),U=(0,i.useMemo)(()=>u?.standaloneExtensions??[],[u?.standaloneExtensions]),q=_.find(e=>oh(e)===x)??null,K=U.find(e=>om(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=>oh(t)===e)||t.standaloneExtensions.some(t=>om(t)===e))?e:t.packages[0]?oh(t.packages[0]):t.standaloneExtensions[0]?om(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=a0(d),Y=(0,i.useRef)(G);(0,i.useEffect)(()=>{Y.current!==G&&(Y.current=G,J())},[G,J]),(0,i.useEffect)(()=>{x&&sl("plugins",x,n)},[n,x]);let X=(0,i.useCallback)(async e=>{let t=(e?[e]:_.filter(e=>e.canCheckForUpdates)).map(oh);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[oh(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),$(null),T(null),D(null);try{let e=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"update",cwd:n})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);p(t),L({}),T(c("i18n.packagesUpdated")),s&&T(`${c("i18n.packagesUpdated")} ${c("agents.reloadRequired")}`)}catch(e){$(e instanceof Error?e.message:String(e))}finally{H(!1)}},[n,s,c]),ee=(0,i.useCallback)(async(e,t)=>{let r=oh(t);N(`${e}:${r}`),$(null),T(null),R(null);try{let i=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,source:t.source,scope:t.scope,cwd:n})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);if(p(s),"remove"===e)b(s.packages[0]?oh(s.packages[0]):s.standaloneExtensions[0]?om(s.standaloneExtensions[0]):null),0===s.packages.length&&0===s.standaloneExtensions.length&&y(!0),T(c("i18n.packageRemoved")),L(e=>{let t={...e};return delete t[r],t});else{let t={install:c("i18n.packageInstalled"),update:c("i18n.packageUpdated"),disable:c("i18n.packageDisabled"),enable:c("i18n.packageEnabled")};T(t[e]),"update"===e&&L(e=>{let t={...e};return delete t[r],t})}}catch(e){$(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,c]),et=(0,i.useCallback)(async(e,t,r)=>{let i=aQ(t,r,e=>!e.disabled,e=>e.filtered),a=r?0:t.filter(e=>!e.disabled&&e.filtered).length,o=a>0?c("plugins.bulkKeptFiltered",{count:a}):void 0;if($(null),T(null),R(o?{scope:e,note:o}:null),0===i.length)return;let l=r?"enable":"disable";N(`bulk:${e}`);try{let t=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:l,cwd:n,packages:i.map(t=>{let{source:n}=t;return{source:n,scope:e}})})}),a=await t.json();if(!t.ok||a.error||!a.results)throw Error(a.error??`HTTP ${t.status}`);let{results:d,...u}=a;p(u);let h=d.filter(e=>e.error);if(h.length<d.length){let e=r?c("plugins.bulkEnabled"):c("plugins.bulkDisabled");T(s?`${e} ${c("agents.reloadRequired")}`:e)}h.length>0&&R({scope:e,note:o,error:[c("plugins.bulkFailed",{count:h.length,total:d.length}),...h.map(e=>`${e.source}: ${e.error}`)].join("\n")})}catch(t){R({scope:e,note:o,error:t instanceof Error?t.message:String(t)})}finally{N(null)}},[n,s,c]),en=(0,i.useCallback)(async()=>{let e=op(j).trim();if(!e)return;k(e);let t=`${w}\0${e}`;N(`install:${t}`),$(null),T(null),R(null);try{var r;let i,s,a=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:e,scope:w,cwd:n})}),o=await a.json();if(!a.ok||o.error)throw Error(o.error??`HTTP ${a.status}`);p(o);let l=(r=o.packages,s=(i=e.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===w&&e.source===i)??r.find(e=>e.scope===w&&e.source===`npm:${s}`)??r.find(e=>e.scope===w&&e.source.endsWith(i)));b(l?oh(l):t),y(!1),k(""),T(c("i18n.packageInstalled"))}catch(e){$(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,w,j,c]),er=(0,i.useCallback)(async()=>{if(s){N("reload"),$(null),T(null),R(null);try{await r2(s,{type:"reload"}),o?.(),await J(),T(c("i18n.sessionReloaded"))}catch(e){$(e instanceof Error?e.message:String(e))}finally{N(null)}}},[J,o,s,c]),ei=C?.startsWith("install:")??!1,es=Object.values(A).filter(e=>"update-available"===e.state).length,ea=_.some(e=>e.canCheckForUpdates),eo=h||null!==C||P.size>0||B;return(0,r.jsxs)(sA,{embedded:l,title:c("common.plugins"),subtitle:ed(n),closeLabel:c("i18n.close"),onClose:a,children:[!Z&&(0,r.jsx)(s5,{message:c("trust.pluginsNotLoaded")}),(0,r.jsxs)(sW,{children:[(0,r.jsxs)(sF,{children:[(0,r.jsx)(sD,{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)(sB,{children:c("i18n.extensions")}),U.map(e=>{let t=om(e);return(0,r.jsxs)(sU,{active:!v&&x===t,title:e.path,onClick:()=>{b(t),y(!1),$(null),T(null)},children:[(0,r.jsx)(as,{active:e.enabled}),(0,r.jsx)(sq,{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)(sB,{aside:(0,r.jsx)(sH,{enabled:t,total:e.packages.length,disabled:eo,loading:C===`bulk:${e.scope}`,label:c(n?"plugins.groupSwitchOn":"plugins.groupSwitchOff",{group:og(e.scope,c)}),onChange:t=>void et(e.scope,e.packages,t)}),children:og(e.scope,c)}),M?.scope===e.scope&&(0,r.jsx)(s_,{error:M.error,note:M.note}),e.packages.map(e=>{let t=oh(e),n=!v&&x===t;return(0,r.jsxs)(sU,{active:n,title:e.description??e.source,onClick:()=>{b(t),y(!1),$(null),T(null)},children:[(0,r.jsx)(as,{active:!e.disabled,color:ob(e.status)}),(0,r.jsx)(sq,{className:`is-grow${e.disabled?" is-muted":""}`,children:e.source}),A[oh(e)]?.state==="update-available"&&(0,r.jsx)("span",{title:c("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"})]},t)})]},e.scope)})]})}),(0,r.jsx)(ai,{active:v,onClick:()=>{y(!0),$(null),T(null)},children:c("i18n.addPlugin")})]}),(0,r.jsx)(s7,{children:(0,r.jsx)(sK,{className:"is-fill",children:v?(0,r.jsx)(oy,{cwd:n,source:j,scope:w,projectResourcesLoaded:Z,busy:ei,actionError:I,onSourceChange:k,onScopeChange:S,onInstall:en}):h?null:K?(0,r.jsx)(ok,{extension:K}):q?(0,r.jsx)(oj,{pkg:q,cwd:n,busyKey:C,actionError:I,actionMessage:E,sessionId:s,updateStatus:A[oh(q)],checkingUpdate:P.has(oh(q)),updateError:F,onAction:ee,onCheckUpdate:()=>void X(q),onReloadSession:er},oh(q)):(0,r.jsx)(s9,{children:c("i18n.selectPackage")})})})]}),(0,r.jsxs)(ae,{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)(at,{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(ox)}):(0,r.jsx)(at,{summary:u?[c("i18n.resourceCount",{count:(t=u.totals).extensions,label:c("i18n.extensionShort")}),c("i18n.resourceCount",{count:t.skills,label:c("i18n.skillShort")}),c("i18n.resourceCount",{count:t.prompts,label:c("i18n.promptShort")}),c("i18n.resourceCount",{count:t.themes,label:c("i18n.themeShort")})].join(" \xb7 "):""}),children:[!l&&(0,r.jsx)(an,{onClick:a,children:c("i18n.close")}),ea&&(0,r.jsx)(an,{variant:es>0?"primary":"secondary",onClick:()=>void(es>0?Q():X()),disabled:eo,title:es>0?c("i18n.updateAllPluginsHint"):void 0,children:B?c("i18n.updating"):O?c("i18n.checking"):es>0?`${c("i18n.updateAllPlugins")} (${es})`:c("i18n.checkUpdates")}),(0,r.jsx)(an,{variant:"secondary",onClick:()=>void J(),disabled:eo,children:c("i18n.refresh")})]})]})}let oS="\\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",oC=RegExp(`[${oS}]`,"gu"),oN=RegExp(`[${oS}]`,"u");function oI(e){return e.replace(oC,e=>{let t=e.codePointAt(0)??0;return`\\u{${t.toString(16).toUpperCase().padStart(4,"0")}}`})}let o$=/[\s"'`$|&;<>()*?#~]/;function oE(e){let t=oN.test(e),n=oI(e);return""===n||t||o$.test(n)?`"${n.replace(/"/g,'\\"')}"`:n}function oT(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return[e,...t].map(oE).join(" ")}function oM(e){let t=void 0!==e.command?oT(e.command,e.args):void 0,n=void 0!==e.url?oI(e.url):void 0;return"http"===e.transport?n:"stdio"===e.transport?t:n??t}function oR(e){return[e.name,e.command,e.cwd,e.url,...e.args??[],...e.envNames,...e.headerNames].some(e=>void 0!==e&&oN.test(e))}function oA(e){return"oauth-client-secret"===e.kind?{key:"mcp.field.oauthClientSecret"}:{key:"env"===e.kind?"mcp.field.env":"mcp.field.header",params:{name:oI(e.name??"")}}}function oL(e){return"http"===e.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables"}function oP(e){return e.length>0?{key:"mcp.server.overridesGlobal",params:{keys:e.join(", ")}}:{key:"mcp.server.overridesGlobalNothing"}}function oz(e){return e.flatMap(e=>{let{variables:t,...n}=e;return t.map(e=>({variable:e,field:n}))})}function oO(e,t){return"unparsable"===e.reason||"unreadable"===e.reason?oI(e.error):"link-outside"===e.reason?void 0===t?void 0:oI(t):void 0}let oW="codemode";function oF(e){return`${e.scope}\0${e.name}`}function oD(e){return e?.trust?.decision===!0}function oB(e){return"test"===e.origin?e.state:void 0!==e.closedAt||"not-trusted"===e.state?"on":e.state}function oH(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?oB(e.status):"on":"mcp-off":"not-trusted":"disabled"}let o_={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"},oU={connected:"mcp.state.session.connected",failed:"mcp.state.session.failed"};function oq(e,t){return(t?.origin==="session"?oU[e]:void 0)??o_[e]}let oK={disconnected:"mcp.stateDetail.disconnected",conflict:"mcp.stateDetail.conflict"},oZ={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 oV(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 oJ(e){return"on"===e?{active:!0}:"off"===e?{active:!1}:{color:"error"===e?"#ef4444":"#f59e0b"}}function oG(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 oY={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"},oX={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"},oQ={connecting:"off",connected:"on","needs-auth":"warning",failed:"error",disconnected:"warning",conflict:"error","not-trusted":"warning"},o0={codemode:"mcp.exposure.codemode",deferred:"mcp.exposure.deferred",direct:"mcp.exposure.direct",hidden:"mcp.exposure.hidden"},o1=["codemode","deferred","direct","hidden"],o2={codemode:"mcp.exposureShort.codemode",deferred:"mcp.exposureShort.deferred",direct:"mcp.exposureShort.direct",hidden:"mcp.exposureShort.hidden"};function o4(e){return"auto-enable-codemode-invalid"!==e.reason}function o8(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 o6(e){return{enabled:e.filter(e=>e.enabled).length,total:e.length}}function o3(e,t){let n=e.flatMap(e=>e.servers.map(oF));return t===oW||null!==t&&n.includes(t)?t:n[0]??null}function o5(e){let t=e?.trust;return void 0!==t&&t.requiresTrust&&!t.trusted}function o9(e){return e.projectOverride?.preference??e.preference}let o7={always:"mcp.codemode.projectOverride.always",automatic:"mcp.codemode.projectOverride.automatic"},le={on:"mcp.codemode.toolMode.onDescription",only:"mcp.codemode.toolMode.onlyDescription"},lt={on:"mcp.codemode.toolMode.projectOverride.on",only:"mcp.codemode.toolMode.projectOverride.only"},ln={automatic:"mcp.codemode.automatic",always:"mcp.codemode.always",unavailable:"mcp.codemode.unavailable",unknown:"i18n.unknown"};function lr(e){return"unavailable"===e?"error":"unknown"===e?"off":"on"}let li=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e);function ls(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}:{},...li(n.names)?{names:n.names}:{},...li(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 la(e,t,n,r){let i,{abortAtDeadline:s=!0}=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},a=new AbortController,o=()=>a.abort();r?.aborted?a.abort():r?.addEventListener("abort",o,{once:!0});let l=new Promise(e=>{i=setTimeout(()=>{e(t()),s&&a.abort()},n)});try{return await Promise.race([e(a.signal),l])}finally{clearTimeout(i),r?.removeEventListener("abort",o)}}function lo(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 ll(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&&lo(i)?{ok:!0,data:i}:{ok:!1,error:ls(i,r.status)}}let ld=new Set(["cwd-invalid","cwd-denied","cwd-not-directory"]);async function lc(e,t,n){let r=await ll(e,t,n);if(r.ok||!e||!r.error.reason||!ld.has(r.error.reason))return r;let i=await ll(null,t,n);return i.ok?{...i,projectError:r.error}:i}async function lu(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 la(n=>lc(e,t,n),()=>({ok:!1,error:{error:`GET /api/mcp did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function lp(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:ls(s,i.status)}}async function lh(e,t,n){let r=await lp({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 lm(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 la(n=>lh(e,t,n),()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function lg(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 la(async n=>{let r=await lp({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 lf(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 la(async n=>{let r=await lp({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 lx(e){return!e.available&&"builtin-disabled"!==e.reason}function lb(e,t){if(lx(t.mcp))return"mcp-off";if("project"===e){if(!t.project?.trust)return"trust-unreadable";if(!oD(t.project))return"project-untrusted"}}let lv={"mcp-off":"mcp.readOnly.mcp-off","project-untrusted":"mcp.readOnly.project-untrusted","trust-unreadable":"mcp.readOnly.trust-unreadable"};function ly(e){return!0!==e.notAnObject}function lj(e){return ly(e)&&void 0===e.webPasswordField}async function lk(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&&lo(i)?{ok:!0,data:i}:{ok:!1,error:ls(i,r.status)}}async function lw(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 la(e=>lk(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp did not answer within ${i} ms`,timedOut:!0}}),i,r)}let lS={"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 lC(e,t){let n=lb(e.scope,t);return n||(void 0===e.invalidError&&e.validated?e.webPasswordField?"web-password":void 0:"invalid")}let lN={"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"},lI={connected:"mcp.test.state.connected","needs-auth":"mcp.test.state.needs-auth",failed:"mcp.test.state.failed",timedOut:"mcp.test.state.timedOut"},l$={connected:"mcp.test.summary.connected","needs-auth":"mcp.test.summary.needs-auth",failed:"mcp.test.summary.failed",timedOut:"mcp.test.summary.timedOut"},lE={connected:"mcp.signIn.summary.connected","needs-auth":"mcp.signIn.summary.needs-auth",failed:"mcp.signIn.summary.failed",timedOut:"mcp.signIn.summary.timedOut"};function lT(e){return(Math.max(0,e)/1e3).toFixed(1)}async function lM(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:ls(i,r.status)}}async function lR(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 la(e=>lM(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp/test did not answer within ${i} ms`,timedOut:!0}}),i,r,{abortAtDeadline:!1})}let lA="•••",lL=new Set(["key","apikey","token","secret","password","passwd","passphrase","pwd","pass","credential","credentials","authorization","bearer","jwt","cookie","signature","pat"]),lP=new Set([...lL,"auth","sig","code","pw"]),lz=["token","secret","password","passwd","apikey"],lO=new Set(["file","path","dir","url","uri","endpoint","id","name","type","header","env","var","length","ttl","expiry","expires","timeout","mode","format"]),lW=new Set(["-k"]);function lF(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 lD(e,t){let n=lF(e);return!(n.length>1&&lO.has(n[n.length-1]))&&n.some(e=>t.has(e)||lz.some(t=>e.length>t.length&&e.endsWith(t)))}function lB(e){return lD(e,lL)}let lH=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,})"),l_=/^eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*$/,lU=/^[A-Za-z0-9_\-+/=.~]+$/;function lq(e){return!(/\s/.test(e)||lG(e))&&(!!(lH.test(e)||l_.test(e))||!(e.length<24||!lU.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 lK=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Za-z_][A-Za-z0-9_]*/,lZ=RegExp(lK.source,"g"),lV=/^(?:bearer|basic|token)\s+/i;function lJ(e,t,n){let r=e.replace(lV,"");return t.test(r)&&/^[^A-Za-z0-9]*$/.test(r.replace(n,""))}function lG(e){return lJ(e.replace(/\$[$!]/g,"_x"),lK,lZ)}let lY=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Z_][A-Z0-9_]*(?![A-Za-z0-9_])/,lX=RegExp(lY.source,"g");function lQ(e){return lJ(e,lY,lX)}function l0(e,t){if(!e||""===t)return;e.push(t);let n=l4(t);n!==t&&e.push(n)}let l1=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#]*)/;function l2(e,t,n){let r=!1,i=e,s="",a=l1.exec(e);if(a){let[o,l,d]=a,c=d.lastIndexOf("@");if(c>=0&&!t(l4(d.slice(0,c)))){s=`${l}${lA}${d.slice(c)}`,r=!0;let e=d.slice(0,c);l0(n,e);let t=e.indexOf(":");t>=0&&l0(n,e.slice(t+1))}else s=o;i=e.slice(o.length)}let o=i.search(/[?#]/),l=o<0?i:i.slice(0,o),d=o<0?"":i.slice(o),c=l.split("/").map(e=>lq(l4(e))?(r=!0,l0(n,e),lA):e).join("/");return d=d.replace(/([?&#;])([^&#;]*)/g,(e,i,s)=>{let a=s.indexOf("=");if(a<0){let a=l4(s);return!lq(a)||t(a)?e:(r=!0,l0(n,s),`${i}${lA}`)}let o=s.slice(0,a),l=l4(s.slice(a+1));return""===l||t(l)||!function(e){let t=e;try{t=decodeURIComponent(e)}catch{}return lD(t,lP)}(o)&&!lq(l)?e:(r=!0,l0(n,s.slice(a+1)),`${i}${o}=${lA}`)}),{value:`${s}${c}${d}`,masked:r}}function l4(e){try{return decodeURIComponent(e)}catch{return e}}let l8=/^(\s*[A-Za-z][A-Za-z0-9 _.-]*=)([\s\S]*)$/;function l6(e,t,n){let r=/^([A-Za-z0-9_-]+):(\s*)([\s\S]*)$/.exec(e);if(r&&""!==r[3]&&!r[3].startsWith("//")&&lB(r[1])){let[,i,s,a]=r;return t(a)?{value:e,masked:!1}:(l0(n,a.trim()),{value:`${i}:${s}${lA}`,masked:!0})}let i=e.includes(";")?function(e,t,n){let r=e.split(";");if(r.length<2||!r.every(e=>""===e.trim()||l8.test(e)))return;let i=!1;return{value:r.map(e=>{let r=l8.exec(e);if(!r)return e;let[,s,a]=r;if(""===a.trim()||t(a))return e;if(lB(s.slice(0,-1).trim()))return i=!0,l0(n,a.trim()),`${s}${lA}`;let o=l6(a,t,n);return i||=o.masked,`${s}${o.value}`}).join(";"),masked:i}}(e,t,n):void 0;if(i)return i;let s=/^([A-Za-z_][A-Za-z0-9_]*)=([\s\S]*)$/.exec(e);if(s&&""!==s[2]&&lB(s[1]))return t(s[2])?{value:e,masked:!1}:(l0(n,s[2]),{value:`${s[1]}=${lA}`,masked:!0});if(/\s/.test(e)){var a,o,l;let r,i;return a=e,o=t,l=n,i=l9((r=a.split(/(\s+)/)).filter((e,t)=>t%2==0),o,!0,l),{value:r.map((e,t)=>t%2==0?i.values[t/2]:e).join(""),masked:i.masked}}if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(e))return l2(e,t,n);if(s&&""!==s[2]){let e=l6(s[2],t,n);return{value:`${s[1]}=${e.value}`,masked:e.masked}}return lq(e)&&!t(e)?(l0(n,e),{value:lA,masked:!0}):{value:e,masked:!1}}function l3(e){if(lW.has(e))return!0;if(!/^--?[A-Za-z]/.test(e))return!1;let t=e.replace(/^-+/,"");return lB(t)||"auth"===lF(t).at(-1)}let l5=/^(?:bearer|basic|token)$/i;function l9(e,t,n,r){let i=!1,s=!1;return{values:e.map(e=>{if(""===e)return e;if(s){if(n&&l5.test(e))return e;if(s=!1,!/^-[A-Za-z-]/.test(e))return t(e)?e:(i=!0,l0(r,e),lA)}let a=/^(--?[A-Za-z][A-Za-z0-9_.-]*)=([\s\S]*)$/.exec(e);if(a){let[,e,n]=a;if(""!==n&&l3(e)&&!t(n))return i=!0,l0(r,n),`${e}=${lA}`;let s=l6(n,t,r);return i||=s.masked,`${e}=${s.value}`}if(/^--?[A-Za-z][A-Za-z0-9_.-]*$/.test(e))return s=l3(e),e;if(n){let t=/^([A-Za-z0-9_-]+):$/.exec(e);if(l5.test(e)||t&&lB(t[1]))return s=!0,e}let o=l6(e,t,r);return i||=o.masked,o.value}),masked:i}}function l7(e){let{values:t,masked:n}=l9(e,lQ,!1);return{args:t,masked:n}}function de(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function dt(e){return!e.startsWith("!")&&!lG(e)}function dn(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 dr={"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(dr);let di={dollarBrace:!1,bareDollar:!1,percent:!1,braceEnv:!1},ds={dollarBrace:!0,bareDollar:!1,percent:!0,braceEnv:!0},da={...ds,bareDollar:!0},dl={...di,braceEnv:!0},dd=/^[A-Za-z_][A-Za-z0-9_]*$/,dc=/\$\{([^{}]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)|%([A-Za-z_][A-Za-z0-9_]*)%|\{(env|file):([^{}]*)\}/g;function du(e,t){if(!t)return;let n=e[e.length-1];n?.kind==="text"?n.text+=t:e.push({kind:"text",text:t})}function dp(e,t,n){let r=[],i=0;dc.lastIndex=0;for(let s=dc.exec(e);s;s=dc.exec(e)){let[a,o,l,d,c,u]=s,p=a;if(void 0!==o&&t.dollarBrace)p=function(e,t){let n=/^env:([A-Za-z_][A-Za-z0-9_]*)$/.exec(e);if(n)return{kind:"env",name:n[1],from:t};let r=/^input:(.+)$/.exec(e);if(r)return{kind:"input",id:r[1],from:t};if("userHome"===e)return{kind:"home",from:t};if("workspaceFolder"===e||"workspaceRoot"===e||"CLAUDE_PROJECT_DIR"===e)return{kind:"workspace",from:t};if("workspaceFolderBasename"===e)return{kind:"workspace-basename",from:t};if("pathSeparator"===e||"/"===e)return"/";if("CLAUDE_PLUGIN_ROOT"===e||"CLAUDE_PLUGIN_DATA"===e)return{kind:"unsupported",from:t};if(dd.test(e))return{kind:"env",name:e,from:t};let i=/^([A-Za-z_][A-Za-z0-9_]*):?-([\s\S]*)$/.exec(e);return i?{kind:"env",name:i[1],from:t,fallback:i[2]}:/^[A-Za-z]+:/.test(e)?{kind:"unsupported",from:t}:t}(o,a);else if(void 0!==l&&t.bareDollar)p={kind:"env",name:l,from:a};else if(void 0!==d&&t.percent&&n)p={kind:"env",name:d,from:a};else if(void 0!==c&&t.braceEnv)p="env"===c&&dd.test(u)?{kind:"env",name:u,from:a}:{kind:"unsupported",from:a};else if(void 0!==d||void 0!==c){du(r,e.slice(i,s.index+1)),i=s.index+1,dc.lastIndex=s.index+1;continue}du(r,e.slice(i,s.index)),"string"==typeof p?du(r,p):r.push(p),i=s.index+a.length}return du(r,e.slice(i)),r}function dh(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 dm(e){return e.startsWith("!")}function dg(e){if(dm(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);dd.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 df=/<[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,dx=/^(?:\.\.\.|…|\*{3,}|x{3,}|TODO|FIXME|changeme|change[-_]me|replace[-_]?me|placeholder|redacted|\[[^\]]+\])$/i,db=/(?:^|[\\/])(?:path[\\/]to(?:[\\/]|$)|Users[\\/](?:username|yourname|your[-_][A-Za-z_-]+|user[-_]?name|<[^>]+>)(?:[\\/]|$)|home[\\/](?:username|yourname|your[-_][A-Za-z_-]+|<[^>]+>)(?:[\\/]|$))/i,dv=/^(Bearer|Basic|Token|Bot|ApiKey|Api-Key)\s+(.+)$/i;function dy(e){return e.join("\0")}function dj(e){return"args"===e[0]?`args[${e[1]}]`:e.join(".")}function dk(e){return"env"===e[0]||"headers"===e[0]||"oauth"===e[0]&&"clientSecret"===e[1]}function dw(e){return"command"===e[0]||"args"===e[0]||"cwd"===e[0]}let dS=new Set(["HOME","USERPROFILE"]);class dC{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 dN(e){return e.map(e=>"text"in e?e.text:e.from).join("")}let dI=/\$\{[^{}]*\}/g,d$=new Set(["variable","home","workspace-basename","unsupported-variable","input"]);class dE{constructor(e){this.draft=e,this.fields=new Map,this.argTexts=e.args.map(dN),this.urlText=dN(e.url??[])}encode(e,t){let n,r=dk(e),i=dj(e),s=dN(t),a=[],o=!1,l=()=>a.every(e=>""===e),d=e=>{if(!r)return void a.push(e);let t=/\$([A-Za-z_][A-Za-z0-9_]*)/.exec(e);t&&this.draft.note("bare-dollar-literal",{field:i,name:t[1]});let n=dh(e,{atStart:l()});n!==e&&(o=!0),a.push(n)},c=e=>a.push(e),u=e=>a.push({field:e});if(!r&&dw(e)&&1===t.length&&"text"in t[0]&&db.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(db.test(n))return t&&c(t),u(this.field(e,"placeholder-path",n,n,"text")),this.target(e,a,void 0)}let p=0;return t.forEach((a,o)=>{let h=t[o+1],m=void 0===h||"text"in h&&/^[\\/]/.test(h.text),g=(t,r,i)=>{let a=0;for(let[d,c]of function(e){let t=e.trim();if(dx.test(t)){let n=e.indexOf(t);return[[n,n+t.length]]}let n=dv.exec(t);if(n&&dx.test(n[2].trim())){let t=e.lastIndexOf(n[2].trim());return[[t,t+n[2].trim().length]]}let r=[];df.lastIndex=0;for(let t=df.exec(e);t;t=df.exec(e))/^your[-_]/.test(t[0])&&/[@/]/.test(e[t.index-1]??"")||r.push([t.index,t.index+t[0].length]);return r}(t)){var o,l;if(i.some(e=>{let[t,n]=e;return d<n&&c>t}))continue;d>a&&r(t.slice(a,d)),"url"===e[0]&&dT(s,p+d)&&(n="uri-component");let h=t.slice(d,c);u(this.field(e,"placeholder",(o=e,l=h,"env"===o[0]||"headers"===o[0]?o[1]:l.replace(/^[<{\s]+|[>}\s]+$/g,"")||dj(o)),h)),a=c}a<t.length&&r(t.slice(a))};switch(a.kind){case"text":g(a.text,d,[]);break;case"pi":{var f;let e=h?(f=a.text,(/\$+$/.exec(f)?.[0].length??0)%2==1?`${f}$`:f):a.text;if(r&&l()&&dm(e)){this.draft.note("shell-command-value",{field:i}),c(e);break}let t=[...e.matchAll(dI)].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}}`})):dw(e)&&l()&&dS.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}"})):dw(e)&&l()&&m?(c("~"),this.draft.note("home-translated",{field:i,from:a.from})):u(this.field(e,"home","userHome",a.from,"text"));break;case"workspace":"url"===e[0]||"oauth"===e[0]?u(this.field(e,"variable","workspaceFolder",a.from,"text")):(c("."),this.draft.note("workspace-folder-relative",{field:i,from:a.from}));break;case"workspace-basename":u(this.field(e,"workspace-basename","workspaceFolderBasename",a.from,"text"));break;case"unsupported":u(this.field(e,"unsupported-variable",a.from,a.from)),this.draft.note("unsupported-variable",{field:i,variable:a.from});break;case"prompt":"url"===e[0]&&dT(s,p)&&(n="uri-component"),u(this.promptField(e,a))}p+=("text"in a?a.text:a.from).length}),o&&this.draft.note("escaped-value",{field:i}),this.target(e,a,n)}target(e,t,n){let r=t.filter(e=>""!==e);for(let t of new Set(r.flatMap(e=>"string"==typeof e?[]:[e.field]))){let i=this.fields.get(t);i.targets.some(t=>dy(t.path)===dy(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=d$.has(t)?`${t}.${n}`:dj(e);if(d$.has(t)){if(this.fields.has(a))return a}else for(let t=2;this.fields.has(a);t++)a=`${dj(e)}#${t}`;let o=this.isSecretContext(e,r)||lB(n),l="headers"===e[0]&&"authorization"===e[1].toLowerCase();return this.fields.set(a,{id:a,kind:i??(o?"password":"text"),reason:t,label:n,placeholder:r,...void 0!==s?{defaultValue:s}:{},..."placeholder"===t&&l?{optional:!0}:{},targets:[]}),a}inputField(e,t){let n=`input.${t.id}`;if(this.fields.has(n))return n;let r=this.draft.inputs?.get(t.id);r?"command"===r.type&&this.draft.note("input-command-unsupported",{id:t.id}):this.draft.note("input-undefined",{id:t.id});let i=r?.type==="pickString"&&r.options&&r.options.length>0?r.options:void 0,s=r?.password===!0||this.isSecretContext(e,t.from);return this.fields.set(n,{id:n,kind:i?"select":s?"password":"text",reason:"input",label:t.id,placeholder:t.from,...r?.description?{description:r.description}:{},...r?.default!==void 0?{defaultValue:r.default}:{},...i?{options:i}:{},targets:[]}),n}promptField(e,t){return this.fields.has(t.id)||this.fields.set(t.id,{id:t.id,kind:t.options?"select":t.secret||this.isSecretContext(e,t.from)?"password":"text",reason:t.reason,label:t.label,placeholder:t.from,...t.description?{description:t.description}:{},...void 0!==t.defaultValue?{defaultValue:t.defaultValue}:{},...t.options?{options:t.options}:{},...t.optional?{optional:!0}:{},targets:[]}),t.id}isSecretContext(e,t){switch(e[0]){case"env":case"headers":return lB(e[1]);case"oauth":return"clientSecret"===e[1];case"args":{if(l7([this.argTexts[e[1]]??""]).masked)return!0;let t=this.argTexts[e[1]-1];return void 0!==t&&l7([t,"x"]).args[1]===lA}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,l2(`https://host.invalid/?${n}=x`,lQ).masked)}default:return!1}}}function dT(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 dM(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 dR=/^[A-Za-z0-9_-]+$/;function dA(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 dL=new Set(["mcp","server","mcp-server","mcpserver","cli","index","main","app","src","dist","build","bin","lib"]);function dP(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=dO(t);return s&&!dL.has(s.toLowerCase())?s:dO(r)||r||s||t}let dz=[/^mcp[-_]server[-_]/i,/^server[-_]/i,/^mcp[-_]/i,/[-_]mcp[-_]server$/i,/[-_]mcp$/i,/[-_]server$/i];function dO(e){let t=e;for(let e=!0;e;)for(let n of(e=!1,dz)){let r=t.replace(n,"");r!==t&&r&&(t=r,e=!0)}return t}let dW=new Set(["mcp","www","api","app","server","servers","remote","gateway"]);function dF(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=>!dW.has(e.toLowerCase()));return r[r.length-1]??n[n.length-1]??""}let dD=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 dB(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 dH(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(!dL.has(n.toLowerCase())&&"."!==n&&".."!==n)return dO(n.replace(/_/g,"-"))||n}return""}function d_(e,t){dU(e,t)&&dq(e,Math.ceil(t/1e3),t)}function dU(e,t){return!!("number"==typeof t&&Number.isFinite(t))&&t>0||(void 0!==t&&e.note("timeout-dropped",{value:String(t)}),!1)}function dq(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 dK=["codemode","deferred","direct","hidden"],dZ={"codemode-deferred":"codemode"},dV=["localhost","127.0.0.1","[::1]"];function dJ(e){return"string"==typeof e&&dK.includes(e)?e:"string"==typeof e&&Object.hasOwn(dZ,e)?dZ[e]:void 0}function dG(e){try{return new URL(e)}catch{return}}function dY(e){let t=dG(e);return void 0!==t&&"http:"===t.protocol&&dV.includes(t.hostname)&&""===t.search&&""===t.hash}function dX(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function dQ(e){return dX(e)&&Object.values(e).every(e=>"string"==typeof e)}function d0(e,t){if(!dR.test(e))return{problem:"name",name:e};if(!dX(t))return{problem:"not-an-object"};let{type:n,exposure:r,enabled:i,timeout:s,toolExposure:a,description:o}=t;if(void 0!==r&&!dJ(r))return{problem:"exposure",value:String(r)};if(void 0!==a){if(!dX(a))return{problem:"tool-exposure"};for(let[e,t]of Object.entries(a))if(!dJ(t))return{problem:"tool-exposure",tool:e}}if(void 0!==i&&"boolean"!=typeof i)return{problem:"enabled"};if(void 0!==o&&"string"!=typeof o)return{problem:"description"};if(void 0!==s&&("number"!=typeof s||!(s>0)))return{problem:"timeout",value:String(s)};if("sse"===n)return{problem:"sse"};if("string"==typeof t.url&&(void 0===n||"http"===n||"streamable-http"===n)){let e=dG(t.url);if(!e||!/^https?:$/.test(e.protocol))return{problem:"url",url:t.url};if(void 0!==t.headers&&!dQ(t.headers))return{problem:"headers"};let n=function(e){var t;let n;if(void 0===e)return;if(!dX(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||!dY(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?dG(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)?dG(t):void 0)&&("https:"===n.protocol||"http:"===n.protocol&&dV.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(!dX(r)||"string"!=typeof r.provider||!r.provider)return{problem:"auth"};if("https:"!==e.protocol&&!dV.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||dQ(t.env)?void 0!==t.cwd&&"string"!=typeof t.cwd?{problem:"cwd"}:void 0:{problem:"env"}:{problem:"args"}:{problem:"no-command-or-url"}}let d1=/[A-Za-z_]/,d2=/[A-Za-z0-9_]/,d4=/^[A-Za-z_][A-Za-z0-9_]*$/,d8=new Set([..." \n'\"\\$`|&;<>()#*?[]{}!~="]),d6=new Set([..."|&;<>()"]),d3=/[0-9@*#?$!-]/,d5={n:"\n",t:" ",r:"\r",a:"\x07",b:"\b",e:"\x1b",E:"\x1b",f:"\f",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function d9(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 d7(e,t){return/^(?:[A-Za-z]:\\|\\\\[A-Za-z0-9.$_-])/.test(e.slice(t,t+4))}class ce{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 ct)return{ok:!1,error:e.detail};throw e}return{ok:!0,words:this.words}}fail(e){throw new ct(e)}startWord(){return this.parts||(this.lineBreak&&this.fail({code:"multiple-commands"}),this.parts=[],this.windowsWord=d7(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)&&d9(e,this.index)>0)this.index+=d9(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:"`"}):d6.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||!d8.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=d7(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 d5?(t+=d5[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&&d1.test(n)){let n=this.index+1;for(;n<t.length&&d2.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&&d3.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}),d4.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 ct extends Error{constructor(e){super(e.code),this.detail=e}}function cn(e){return new ce(e).run()}function cr(e){return e.parts.every(e=>"text"===e.type)?e.text:void 0}function ci(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let cs=["httpUrl","trust","includeTools","excludeTools","authProviderType","targetAudience","targetServiceAccount","tcp"];function ca(e){if(cs.some(t=>t in e))return!0;let t=e.oauth;return ci(t)&&["redirectUri","authorizationUrl","tokenUrl","audiences","tokenParamName"].some(e=>e in t)}function co(e){if(!ci(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]||ci(t)&&"string"==typeof t.path||"string"==typeof n||"string"==typeof r||"string"==typeof i}function cl(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 cd(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 cc(e,t){let n=t?cd(t):void 0;return{code:"sse-transport",params:{...e?{server:e}:{},...t?{url:t}:{},...n?{suggestedUrl:n}:{}}}}function cu(e){return e?{server:e}:{}}function cp(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?String(e):void 0}function ch(e,t,n){let r;if(!ci(t))return{note:{code:"no-command-or-url",params:cu(e)}};let i=new Set,s=e=>(i.add(e),t[e]),a=n.rawPi,o=function(e,t){switch(e.flavor){case"zed":return di;case"opencode":return dl;case"vscode":return ds;default:return ca(t)?da:ds}}(n,t),l=s("name"),d=e??("string"==typeof l?l:void 0),c=new dC(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"),dp(e,o,t)};c.name=d,c.inputs=n.inputs;let p=s("inputs");Array.isArray(p)&&(c.inputs=new Map([...n.inputs??[],...cf(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:cu(d)}};if(void 0!==h&&"unknown"===(r="string"==typeof h?cl(h):"unknown"))return{note:{code:"unsupported-transport",params:{...cu(d),type:String(h)}}};let f="string"==typeof m&&""!==m||Array.isArray(m)||ci(m),x=void 0!==g;if("sse"===r)return{note:cc(d,g)};if("ws"===r)return{note:{code:"websocket-transport",params:{...cu(d),...g?{url:g}:{}}}};if(void 0===r){if(f&&x)return{note:{code:"ambiguous-command-and-url",params:cu(d)}};if(x){if(void 0!==cd(g))return{note:cc(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:cu(d)}};r="stdio"}}if("stdio"!==r&&"http"!==r)return{note:{code:"unsupported-transport",params:{...cu(d),type:String(h)}}};if("stdio"===r&&!f||"http"===r&&!x)return{note:{code:"no-command-or-url",params:cu(d)}};if(c.transport=r,"stdio"===r){let e=function(e,t,n,r,i,s){let a,o=r("args"),l=r("opencode"===s.flavor?"environment":"env");if("opencode"===s.flavor&&void 0===l&&(l=r("env")),Array.isArray(n)){if(!n.every(e=>"string"==typeof e)||0===n.length)return{code:"invalid-config",params:{...cu(e.name),problem:"args"}};a=n[0],o=[...n.slice(1),...Array.isArray(o)?o:[]]}else if(ci(n))for(let t of(a="string"==typeof n.path?n.path:void 0,void 0===o&&(o=n.args),void 0===l&&(l=n.env),Object.keys(n)))["path","args","env"].includes(t)||e.note("dropped-key",{key:`command.${t}`});else"string"==typeof n&&(a=n);if(!a)return{code:"no-command-or-url",params:cu(e.name)};let d=Array.isArray(o)?[...o]:[];if(void 0!==o&&!Array.isArray(o))return{code:"invalid-config",params:{...cu(e.name),problem:"args"}};if(0===d.length&&/\s/.test(a.trim())&&!/^(?:[A-Za-z]:[\\/]|[\\/]|~[\\/]|\.{1,2}[\\/])/.test(a.trim())){let t=cn(a.trim()),n=t.ok?t.words.map(cr):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=cp(n);if(void 0===r)return{code:"invalid-config",params:{...cu(e.name),problem:"args",index:t}};e.args.push(i(r,!1))}if(void 0!==l){if(!ci(l))return{code:"invalid-config",params:{...cu(e.name),problem:"env"}};for(let[t,n]of Object.entries(l)){if(null===n){e.note("env-null-dropped",{name:t});continue}let r=cp(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&&lB(t)){e.env.push([t,[{kind:"prompt",id:`env.${t}`,reason:"empty",label:t,from:"",secret:!0}]]);continue}e.env.push([t,i(r,!0)])}}let c=r("cwd");for(let n of("string"==typeof c&&""!==c?e.cwd=i(c,!1):void 0!==c&&""!==c&&e.note("dropped-key",{key:"cwd"}),["headers","oauth","auth","url","httpUrl","serverUrl"]))n in t&&(r(n),e.note("dropped-key",{key:n}))}(c,t,m,s,u,n);if(e)return{note:e}}else!function(e,t,n,r,i){let s=r("headers"),a=i(n,!1),o=ci(s)&&Object.keys(s).some(e=>"authorization"===e.toLowerCase());if(1===a.length&&"text"in a[0]?dM(e,n,o):e.url=a,ci(s))for(let[t,n]of Object.entries(s)){let r=cp(n);if(void 0===r){e.note("dropped-key",{key:`headers.${t}`});continue}if(""===r.trim()){"authorization"===t.toLowerCase()?e.note("empty-authorization-dropped"):lB(t)?e.headers.push([t,[{kind:"prompt",id:`headers.${t}`,reason:"empty",label:t,from:"",secret:!0,optional:!0}]]):e.headers.push([t,[]]);continue}e.headers.push([t,i(r,!0)])}else void 0!==s&&e.note("dropped-key",{key:"headers"});let l=r("oauth"),d=r("auth");if(!1===l?e.note("oauth-disable-unsupported"):ci(l)?cm(e,l,i):void 0!==l&&e.note("dropped-key",{key:"oauth"}),ci(d))for(let t of(cm(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(ca(t))d_(c,b);else["autoApprove","alwaysAllow","transportType"].some(e=>e in t)||"streamableHttp"===t.type?dU(c,b)&&dq(c,Math.ceil(b),void 0):!function(e,t){if(!dU(e,t))return;let n=t>=1e3;e.note("timeout-unit-guessed",{value:t,unit:n?"milliseconds":"seconds"}),n?dq(e,Math.ceil(t/1e3),t):dq(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 j=s("exposure");if(void 0!==j){let e=dJ(j);e?c.exposure=e:c.note("invalid-exposure-dropped",{value:String(j)})}let k=s("toolExposure");if(void 0!==k){let e=ci(k)?Object.entries(k).map(e=>{let[t,n]=e;return[t,dJ(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===j&&void 0===k||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(cg(c,s("includeTools"),s("excludeTools")),Object.keys(t)))i.has(e)||c.note("dropped-key",{key:e});return{draft:c}}function cm(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&&dY(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 cg(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 cf(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e)ci(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=>ci(e)?e.value:e).filter(e=>"string"==typeof e)}:{}});return t}function cx(e,t,n,r){let i=[],s=0;for(let a of e.matchAll(/\{([A-Za-z_][A-Za-z0-9_-]*)\}/g)){a.index>s&&i.push({kind:"text",text:e.slice(s,a.index)});let o=ci(t)&&ci(t[a[1]])?t[a[1]]:{};i.push(cb(`${n}${a[1]}`,a[1],a[0],o,r)),s=a.index+a[0].length}return s<e.length&&i.push({kind:"text",text:e.slice(s)}),i}function cb(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 cv(e,t,n){let r=[],i="",s=()=>{i&&("pi"===t?r.push({kind:"pi",text:i}):r.push(...dp(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 cy(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 cj=/^https?:\/\//i,ck=/^wss?:\/\//i,cw={"@earendil-works/pi-coding-agent":"pi","@anthropic-ai/claude-code":"claude","@openai/codex":"codex","@google/gemini-cli":"gemini"},cS=new Set(["pi","claude","codex","gemini"]),cC=new Set(["install","remove","uninstall","update","list","config"]);function cN(e){return"error"in e?{error:e.error}:{entries:[e],notes:[]}}let cI={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"},c$=new Map([["-l","--local"]]),cE=["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name","oauth-client-registration"],cT=["env","cwd"];function cM(e,t,n,r){let i={positional:[],afterDashDash:[],values:new Map,lists:new Map,seen:new Map};for(let s=0;s<t.length;s++){let a=t[s],o=a.text;if("--"===o){i.afterDashDash.push(...t.slice(s+1));break}if(void 0!==r.stopAfter&&i.positional.length>=r.stopAfter){i.positional.push(...t.slice(s));break}if(!o.startsWith("-")||"-"===o){i.positional.push(a);continue}let l=o.startsWith("--")?o.indexOf("="):-1,d=l>0?o.slice(0,l):o,c=n[d];if(!c){if(i.positional.length>=r.asArgAfter){i.positional.push(a),i.seen.set(`as-arg:${d}`,d);continue}return{error:{code:"cli-unknown-option",params:{cli:e,option:d}}}}if(i.seen.set(c.name,d),"flag"===c.kind){i.values.set(c.name,!0);continue}let u=l>0?cR(a,l+1):void 0;if("value"===c.kind||"list"===c.kind){let n=u??t[++s];if(void 0===n)return{error:{code:"cli-option-needs-value",params:{cli:e,option:d}}};"value"===c.kind?i.values.set(c.name,n):i.lists.set(c.name,[...i.lists.get(c.name)??[],n]);continue}let p=u?[u]:[];if(!u)for(;s+1<t.length&&r.variadic(c.name,t[s+1]);)p.push(t[++s]);if(0===p.length)return{error:{code:"cli-option-needs-value",params:{cli:e,option:d}}};i.lists.set(c.name,[...i.lists.get(c.name)??[],...p])}return i}function cR(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 cA=/^[A-Za-z_][A-Za-z0-9_]*=/,cL=/^[^\s:]+:/;function cP(e,t,n,r){for(let i of t??[]){let t=cy(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],cv(t[1],n,!0)])}}function cz(e,t,n,r){for(let i of t??[]){let t=cy(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,cv(a,n,!0)])}}function cO(e){if(void 0!==e&&!0!==e){if("user"===e.text)return"global";if("project"===e.text)return"project"}}function cW(e,t,n,r,i){let s,[a,o,...l]=r;if(!a||!o)return{code:"cli-usage",params:{cli:t}};e.name=a.text;let d=void 0===n||!0===n?void 0:n.text.toLowerCase();if(void 0===d){if("http"==(s=cj.test(o.text)?"http":ck.test(o.text)?"ws":"stdio")&&void 0!==cd(o.text))return cc(a.text,o.text);"http"===s&&"gemini"===t&&e.note("transport-assumed-http")}else s="streamable-http"===d?"http":d;return"sse"===s?cc(a.text,o.text):"ws"===s?{code:"websocket-transport",params:{server:a.text,url:o.text}}:"http"===s?(e.transport="http",e.url=cv(o.parts,i,!1),l.length>0&&e.note("cli-extra-arguments",{cli:t,arguments:l.map(e=>e.text).join(" ")}),"http"):"stdio"!==s?{code:"unsupported-transport",params:{server:a.text,type:s}}:(e.transport="stdio",e.command=cv(o.parts,i,!1),e.args=l.map(e=>cv(e.parts,i,!1)),"stdio")}let cF={"-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 cD(e,t){return"env"===e?cA.test(t.text):cL.test(t.text)&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(t.text)}function cB(e){e.oauth.clientSecret=[{kind:"prompt",id:"oauth.clientSecret",reason:"client-secret",label:"clientSecret",from:"",secret:!0}],e.note("client-secret-prompt")}let cH={"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"--client-secret":{name:"client-secret",kind:"flag"}};function c_(e){let t,n=cr(e)??e.text;try{t=dn(n)}catch(e){return{error:{code:"invalid-json",params:{detail:e instanceof Error?e.message:String(e)}}}}return ci(t)?{value:t}:{error:{code:"no-servers-found"}}}let cU={"--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"}},cq={"-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 cK(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(cZ(r),cZ(i))}return t}function cZ(e){try{return decodeURIComponent(e)}catch{return e}}function cV(e){let t=e.trim();for(let e=0;e<4;e++)try{return dn(t)}catch{let e=cZ(t);if(e===t)break;t=e.trim()}}function cJ(e){return{error:{code:"install-link-invalid",params:{detail:e}}}}function cG(e){let t=e.get("config");if(!t)return cJ("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:cV(n);return ci(r)?{entries:[ch(e.get("name")||void 0,r,{source:"cursor-install-link",flavor:"mcp-servers",rawPi:!1})],notes:[]}:cJ("config")}function cY(e,t,n,r){return ci(e)?{entries:[ch(n,e,{source:t,flavor:"vscode",rawPi:!1,inputs:cf(r)})],notes:[]}:cJ("config")}function cX(e){return{error:{code:"by-name-link",params:{name:e}}}}function cQ(e){let t=e.indexOf("?");return t<0?"":e.slice(t+1)}function c0(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:[c2(void 0,r)],notes:[]};return{error:{code:"unrecognized-input"}}}if(n>3)return cJ("nesting");let i=t.protocol.replace(/:$/,"").toLowerCase();switch(i){case"cursor":if(/\/mcp\/install\/?$/.test(t.pathname))return cG(cK(t.search));return cJ("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 cX(cZ(t[1]));if(/^mcp\/api\.mcp\.github\.com\//.test(e))return cX(e.replace(/^mcp\//,""));if(/^mcp\/install\?/.test(e))return cY(cV(cQ(r)),"vscode-install-link");return cJ(i)}case"vsweb+mcp":return cY(cV(cQ(r)),"visual-studio-install-link");case"ghapp":if(/^\/\/mcp\/install/.test(r.slice(r.indexOf(":")+1)))return cY(cV(cQ(r)),"copilot-app-install-link");return cJ(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 cG(cK(e.search));if("vscode.dev"===r||"insiders.vscode.dev"===r){let t=cK(e.search);if(/^\/redirect\/?$/.test(i)&&t.get("url"))return c0(t.get("url"),n+1);if(/^\/redirect\/mcp\/install\/?$/.test(i)){let e=t.get("config");return e?cY(cV(e),"vscode-install-link",t.get("name")||void 0,cV(t.get("inputs")??"[]")):cJ("config")}}if("aka.ms"===r&&/^\/vs\/mcp-install\/?$/i.test(i))return cY(cV(e.search.slice(1)),"visual-studio-install-link");if("github.com"===r&&/^\/copilot\/app\/launch\/?$/.test(i)){let t=cK(e.search).get("open");return t?c0(t,n+1):cJ("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:[c2(e,t)],notes:[]}}(t,r,n);default:return{error:{code:"unsupported-url-scheme",params:{scheme:i}}}}}let c1=new Set(["localhost","127.0.0.1","[::1]"]);function c2(e,t){let n=dF(t)||void 0;if(void 0!==cd(t))return{note:cc(n,t)};let r=new dC("url",!1);return r.transport="http",dM(r,t,!1),e?.protocol!=="http:"||c1.has(e.hostname)||r.note("insecure-http",{host:e.hostname}),{draft:r}}let c4=/[\u200B-\u200D\u2060\uFEFF]/g,c8=/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]\S*)?$/i,c6={"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 c3(e){return new Set(e.fields.flatMap(e=>e.targets.map(e=>dy(e.path))))}function c5(e){var t;let n,r,i,s,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=(n=e.replace(c4,"").replace(/\u00A0/g," ").trim(),(r=/```[^\n]*\n([\s\S]*?)(?:```|$)/.exec(n))?n=r[1].trim():/^`[^`\n]+`$/.test(n)&&(n=n.slice(1,-1).trim()),(i=n.startsWith("[")?/\]\(([^()\s]+)\)\s*$/.exec(n):null)&&(n=i[1]),/^<\S+>$/.test(n)&&(n=n.slice(1,-1)),n);if(!o)return{ok:!1,notes:[{code:"empty-input"}]};if(o.startsWith("{")||o.startsWith("[")||/^"[^"\n]+"\s*:/.test(o))s=function(e,t){let n;try{n=dn(e)}catch(t){try{n=dn(`{${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 ch(n,r,t)});if(Array.isArray(e)){let r=e.filter(co);return 0===r.length?{error:{code:"no-servers-found"}}:{entries:r.map(e=>ch(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})),notes:n}}if(!ci(e))return{error:{code:"no-servers-found"}};let i=ci(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?dP(t.split("/").pop()??t):void 0,r=Array.isArray(e.remotes)?e.remotes.filter(ci):[],i=r.filter(e=>"string"==typeof e.type&&"http"===cl(e.type)&&"string"==typeof e.url);if(0===i.length){let e=r.find(e=>"sse"===e.type);return e?[{note:cc(n,"string"==typeof e.url?e.url:void 0)}]:[{note:{code:"registry-packages-unsupported",params:cu(n)}}]}return i.map(e=>{let r=new dC("registry-server-json",!1);for(let i of(r.name=n,t&&n!==t&&(r.originalName=t),r.transport="http",r.url=cx(e.url,e.variables,"url.","registry-variable"),Array.isArray(e.headers)?e.headers.filter(ci):[])){if("string"!=typeof i.name||""===i.name)continue;let e=i.name;"string"==typeof i.value&&""!==i.value?r.headers.push([e,cx(i.value,i.variables,`headers.${e}.`,"registry-header")]):r.headers.push([e,[cb(`headers.${e}`,e,"",i,"registry-header")]])}return{draft:r}})}(i),notes:n};if(ci(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(ci(e.servers)){let t=cf(e.inputs);return{entries:r(e.servers,{source:"vscode-json",flavor:"vscode",rawPi:!1,inputs:t}),notes:n}}if(ci(e.mcp)){let t=e.mcp;if(ci(t.servers)){let e=cf(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(ci(e.context_servers))return{entries:Object.entries(e.context_servers).map(e=>{let t,[n,r]=e;return ci(r)&&("extension"===r.source||!co(r))?{note:{code:"zed-extension-server",params:{server:n}}}:ch(n,ci(r)?(t={...r},delete t.source,t):r,{source:"zed-json",flavor:"zed",rawPi:!1})}),notes:n};if(co(e))return{entries:[ch(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})],notes:n};let s=Object.values(e);return s.length>0&&s.every(ci)&&s.some(co)?{entries:r(e,{source:"server-map",flavor:"mcp-servers",rawPi:t}),notes:n}:{error:{code:"no-servers-found"}}}(n,t)}(o,!0===a.rawPi);else if(c8.test(o)){if(!("error"in(s=c0(`http://${o}`))))for(let e of s.entries)"draft"in e&&e.draft.note("scheme-assumed",{url:`http://${o}`})}else{let e;s=!/\s/.test(o)&&/^[A-Za-z][A-Za-z0-9+.-]+:/.test(o)?c0(o):(e=cn(o.replace(/^(?:\$|%|>|❯|PS [^\n>]*>)[ \t]+/,"").replace(/[\u201C\u201D\u201E\u201F\u2033]/g,'"').replace(/[\u2018\u2019\u201A\u201B\u2032]/g,"'").replace(/(^|\s)[\u2013\u2014](?=\S)/g,"$1--").replace(/(^|\s)[\u2013\u2014](?=\s|$)/g,"$1--"))).ok?0===e.words.length?{error:{code:"empty-input"}}:function(e){var t;let n=0,r=(t=e[0],(t?.text.split(/[\\/]/).pop()??"").replace(/\.(?:cmd|exe|ps1)$/i,"").toLowerCase());if(["npx","bunx","pnpx"].includes(r)){let t=1;for(;e[t]?.text.startsWith("-");)t++;let i=e[t]?.text.replace(/^(@?[^@]+)@.*$/,"$1");i&&cw[i]&&e[t+1]?.text==="mcp"&&(n=t,r=cw[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 cN(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=c$.get(e[t].text)??e[t].text;if("--"===s||n.length>=2){n.push(...e.slice("--"===s?t+1:t));break}if(!s.startsWith("--")){n.push(e[t]);continue}let a=s.slice(2),o=cI[a];if(!o)return{error:{code:"cli-unknown-option",params:{cli:"pi",option:s}}};if("flag"===o){r.set(a,!0);continue}let l=e[++t];if(void 0===l)return{error:{code:"cli-option-needs-value",params:{cli:"pi",option:s}}};"list"===o?i.set(a,[...i.get(a)??[],l]):r.set(a,l)}let[s,...a]=n,o=r.get("url");if(!s||""===s.text||void 0===o==(0===a.length))return{error:{code:"cli-usage",params:{cli:"pi"}}};let l=e=>{let t=r.get(e);return!0===t?void 0:t},d=(void 0===o?cE:cT).find(e=>r.has(e)||i.has(e));if(d)return{error:{code:"cli-option-wrong-transport",params:{cli:"pi",option:`--${d}`,transport:void 0===o?"stdio":"http"}}};let c=new dC("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=cy(r.parts,t);if(!i||""===i[0])return{error:{code:"cli-invalid-pair",params:{cli:"pi",option:`--${e}`,value:r.text}}};let s=n.findIndex(e=>{let[t]=e;return t===i[0]});s>=0?n[s]=i:n.push(i)}return n},p={};if(void 0!==o&&!0!==o){c.transport="http",c.url=cv(o.parts,"pi",!1);let e=u("header");if("error"in e)return e;for(let[t,n]of e)c.headers.push([t,cv(n,"pi",!0)]);let t=l("bearer-token-env-var");if(void 0!==t){let e=["Authorization",[{kind:"pi",text:`Bearer $\{${t.text}}`}]],n=c.headers.findIndex(e=>{let[t]=e;return"Authorization"===t});n>=0?c.headers[n]=e:c.headers.push(e)}let n=l("oauth-client-id"),r=l("oauth-client-secret"),i=l("oauth-callback-port"),s=l("oauth-client-name"),a=l("oauth-client-registration");n&&(c.oauth.clientId=cv(n.parts,"pi",!1)),r&&(c.oauth.clientSecret=cv(r.parts,"pi",!0)),i&&(c.oauth.callbackPort=Number(i.text)),s&&(c.oauth.clientName=cv(s.parts,"pi",!1)),a&&(c.oauth.clientRegistration=a.text),p.url=o.parts.some(e=>"variable"===e.type)?"https://placeholder.invalid/":o.text,(i||s||a)&&(p.oauth={...n?{clientId:n.text}:{},...i?{callbackPort:Number(i.text)}:{},...s?{clientName:s.text}:{},...a?{clientRegistration:a.text}:{}})}else{c.transport="stdio";let e=u("env");if("error"in e)return e;for(let[t,n]of e)c.env.push([t,cv(n,"pi",!0)]);let[t,...n]=a;c.command=cv(t.parts,"pi",!1),c.args=n.map(e=>cv(e.parts,"pi",!1));let r=l("cwd");r&&(c.cwd=cv(r.parts,"pi",!1)),p.command=t.text}let h=l("exposure");void 0!==h&&(p.exposure=h.text,c.exposure=dJ(h.text)??h.text);let m=l("description");void 0!==m&&(p.description=m.text,c.description=m.text);let g=d0("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 cN(function(e){let t=cM("claude",e,cF,{asArgAfter:2,variadic:cD});if("error"in t)return{error:t.error};let n=new dC("claude-mcp-add",!1),r=cW(n,"claude",t.values.get("transport"),[...t.positional,...t.afterDashDash],ds);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=cO(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=cz(n,t.lists.get("header"),ds,"claude");if(r)return{error:r};let a=t.values.get("client-id");a&&!0!==a&&(n.oauth.clientId=cv(a.parts,ds,!1)),t.values.has("client-secret")&&cB(n);let o=t.values.get("callback-port");o&&!0!==o&&(i=n,Number.isInteger(e=Number(s=o.text))&&e>=1&&e<=65535?i.oauth.callbackPort=e:i.note("callback-port-dropped",{value:s}))}else{for(let e of["header","client-id","client-secret","callback-port"])(t.lists.has(e)||t.values.has(e))&&n.note("cli-option-wrong-transport",{cli:"claude",option:t.seen.get(e)??`--${e}`,transport:"stdio"});let e=cP(n,t.lists.get("env"),ds,"claude");if(e)return{error:e}}return{draft:n}}(t));if("claude"===r&&"add-json"===e)return cN(function(e){let t=cM("claude",e,cH,{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=c_(r);if("error"in s)return s;let a=ch(n.text,s.value,{source:"claude-mcp-add-json",flavor:"mcp-servers",rawPi:!1});return"note"in a||(a.draft.scopeHint=cO(t.values.get("scope")),t.values.has("client-secret")&&"http"===a.draft.transport&&!a.draft.oauth.clientSecret&&cB(a.draft)),a}(t));if("claude"===r&&"add-from-claude-desktop"===e)return{error:{code:"claude-desktop-import"}};if("codex"===r&&"add"===e)return cN(function(e){let t=cM("codex",e,cU,{asArgAfter:1/0,stopAfter:2});if("error"in t)return{error:t.error};let n=t.afterDashDash,r=t.lists.get("env")??[],[i,...s]=t.positional,a=n.length>0?n:s,o=t.values.get("url");if(!i||void 0===o==(0===a.length)||n.length>0&&s.length>0)return{error:{code:"cli-usage",params:{cli:"codex"}}};let l=new dC("codex-mcp-add",!1);for(let e of(l.name=i.text,["config","enable","disable"]))t.values.has(e)&&l.note("cli-option-ignored",{cli:"codex",option:t.seen.get(e)});if(t.values.has("oauth-resource")&&l.note("oauth-option-dropped",{key:"--oauth-resource"}),void 0!==o&&!0!==o){if(r.length>0)return{error:{code:"cli-option-wrong-transport",params:{cli:"codex",option:"--env",transport:"http"}}};if(void 0!==cd(o.text))return{note:cc(i.text,o.text)};l.transport="http",l.url=cv(o.parts,di,!1);let e=t.values.get("bearer-token-env-var");e&&!0!==e&&l.headers.push(["Authorization",[{kind:"text",text:"Bearer "},{kind:"env",name:e.text,from:`$\{${e.text}}`}]]);let n=t.values.get("oauth-client-id");n&&!0!==n&&(l.oauth.clientId=cv(n.parts,di,!1))}else{for(let e of["bearer-token-env-var","oauth-client-id","oauth-resource"])if(t.values.has(e))return{error:{code:"cli-option-wrong-transport",params:{cli:"codex",option:`--${e}`,transport:"stdio"}}};l.transport="stdio";let e=cP(l,r,di,"codex");if(e)return{error:e};l.command=cv(a[0].parts,di,!1),l.args=a.slice(1).map(e=>cv(e.parts,di,!1))}return{draft:l}}(t));if("gemini"===r&&"add"===e)return cN(function(e){let t=cM("gemini",e,cq,{asArgAfter:2});if("error"in t)return{error:t.error};let n=new dC("gemini-mcp-add",!1),r=cW(n,"gemini",t.values.get("transport"),[...t.positional,...t.afterDashDash],da);if("string"!=typeof r)return"cli-usage"===r.code?{error:r}:{note:r};if(n.scopeHint=cO(t.values.get("scope")),"http"===r){t.lists.has("env")&&n.note("cli-option-wrong-transport",{cli:"gemini",option:"--env",transport:"http"});let e=cz(n,t.lists.get("header"),da,"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=cP(n,t.lists.get("env"),da,"gemini");if(e)return{error:e}}let i=t.values.get("timeout");for(let e of(i&&!0!==i&&d_(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 cg(n,s("include-tools"),s("exclude-tools")),{draft:n}}(t));if("add"===e||"install"===e)return{error:{code:"cli-unsupported",params:{cli:r}}};if(cS.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]&&cC.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=cR(e[n],10)}if(!r)return{error:{code:"cli-option-needs-value",params:{cli:"code",option:"--add-mcp"}}};let s=c_(r);if("error"in s)return s;t.push(ch(void 0,s.value,{source:"vscode-add-mcp",flavor:"vscode",rawPi:!1}))}return{entries:t,notes:[]}}(e.slice(1)):cN(function(e){let t=new dC("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,cv(r.value,di,!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=cv(i.parts,di,!1),t.args=e.slice(n+1).map(e=>cv(e.parts,di,!1));let s=e.slice(n+1).map(e=>e.text),a=s.some(e=>/^mcp-remote(?:@|$)/.test(e))?s.find(e=>cj.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:c6[t],params:n}:{code:c6[t]}}(e.error)}}if("error"in s)return{ok:!1,notes:[s.error]};let l=[...s.notes],d=[],c=[...a.takenNames??[]],u=new Set;for(let e of s.entries){if("note"in e){l.push(e.note);continue}let n=function(e){let t,n=new dE(e);if("stdio"===e.transport&&e.command&&""!==dN(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||""===dN(e.url))return{note:{code:"no-command-or-url",...e.name?{params:{server:e.name}}:{}}};let r=n.encode(["url"],e.url),i={};for(let[t,r]of e.headers)i[t]=n.encode(["headers",t],r);let s={},{clientId:a,clientSecret:o,callbackPort:l,clientName:d,clientRegistration:c,callbackUrl:u,scope:p,authServerMetadataUrl:h}=e.oauth;a&&(s.clientId=n.encode(["oauth","clientId"],a)),o&&(s.clientSecret=n.encode(["oauth","clientSecret"],o)),void 0!==l&&(s.callbackPort=l),d&&(s.clientName=n.encode(["oauth","clientName"],d)),c&&(s.clientRegistration=c),u&&(s.callbackUrl=n.encode(["oauth","callbackUrl"],u)),p&&(s.scope=n.encode(["oauth","scope"],p)),h&&(s.authServerMetadataUrl=n.encode(["oauth","authServerMetadataUrl"],h)),t={url:r,...Object.keys(i).length>0?{headers:i}:{},...Object.keys(s).length>0?{oauth:s}:{}}}return void 0!==e.exposure&&(t.exposure=e.exposure),void 0!==e.toolExposure&&(t.toolExposure=e.toolExposure),!1===e.enabled&&(t.enabled=!1),void 0!==e.timeout&&(t.timeout=e.timeout),void 0!==e.description&&(t.description=e.description),{server:{name:e.name??"",...void 0!==e.originalName?{originalName:e.originalName}:{},config:t,fields:[...n.fields.values()],notes:e.notes,source:e.source,rawPi:e.rawPi,...e.scopeHint?{scopeHint:e.scopeHint}:{}}}}(e.draft);if("note"in n){l.push(n.note);continue}let r=n.server,i=r.name,s=!i;s&&(i=function(e){if("url"in e)return dF(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&&dF(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=dB(t,new Set(["-p","--package","-c","--call"]));return e?dP(e):""}case"pnpm":case"yarn":case"bun":case"npm":{let e=t.findIndex(e=>"dlx"===e||"exec"===e||"x"===e),n=e>=0?dB(t.slice(e+1),new Set(["-p","--package"])):void 0;return n?dP(n):""}case"uvx":case"pipx":{let e=dB("pipx"===n&&"run"===t[0]?t.slice(1):t,new Set(["--from","--with","--python","-p","--index-url","--spec"]));return e?dP(e):""}case"uv":{let e=t.indexOf("run"),n=e>=0?dB(t.slice(e+1),new Set(["--with","--directory","--python","-p","--from","--project"])):void 0;return n?dH(n):""}case"docker":case"podman":{let e=t.indexOf("run"),n=e>=0?dB(t.slice(e+1),dD):void 0;if(!n)return"";let r=n.split("/").pop().replace(/[:@].*$/,"");return dO(r)||r}case"python":case"python3":case"py":{let e=t.indexOf("-m");if(e>=0&&t[e+1])return dP(t[e+1].replace(/_/g,"-"));let n=dB(t,new Set(["-X","-W"]));return n?dH(n):""}case"node":case"deno":case"tsx":case"ts-node":{let e=dB("deno"===n&&"run"===t[0]?t.slice(1):t,new Set(["-r","--require","--import","--loader"]));return e?dH(e):""}default:return dO(n.replace(/_/g,"-"))||n}}(e.command,t)}(r.config))&&r.notes.push({code:"name-derived",params:{name:i}});let a=(t=i,dR.test(t))?i:i.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/-{2,}/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,48).replace(/[-_]+$/g,"")||"server";a!==i&&i&&(r.originalName=r.originalName??i,r.notes.push({code:"name-sanitized",params:{original:i,name:a}}));let o=dA(a,s?[...c,...u]:u);o!==a&&(r.notes.push({code:"name-deduplicated",params:{original:a,name:o}}),a=o),!s&&c.includes(a)&&r.notes.push({code:"name-taken",params:{name:a,suggestedName:dA(a,[...c,...u])}}),r.name=a;let p=d0(a,function(e){let t=c3(e),n=JSON.parse(JSON.stringify(e.config));t.has(dy(["url"]))&&(n.url="https://placeholder.invalid/");let r=n.oauth;return r&&t.has(dy(["oauth","callbackUrl"]))&&delete r.callbackUrl,n}(r));if(p){l.push({code:"invalid-config",params:{server:a,...p}});continue}!function(e){let t=c3(e);for(let n of us(e.config))t.has(dy(n))||e.notes.push({code:"literal-secret",params:{field:dj(n)}});let n=e.config;if("url"in n){for(let[t,r]of Object.entries(n.headers??{})){let n=dg(r);n.length>0&&e.notes.push({code:"header-env-reference",params:{header:t,names:n.join(", ")}})}let t=dg(n.oauth?.clientSecret??"");t.length>0&&e.notes.push({code:"client-secret-env-reference",params:{names:t.join(", ")}})}}(r),u.add(a),d.push(r)}return 0===d.length?{ok:!1,notes:l.length>0?l:[{code:"no-servers-found"}]}:{ok:!0,servers:d,notes:l}}let c9=/^[A-Za-z_][A-Za-z0-9_]*$/;function c7(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 ue(e){let t=c3(e);return us(e.config).filter(e=>dk(e)&&!t.has(dy(e)))}function ut(e){return"string"==typeof e&&""===e.trim()?"missing":"name"}let un=/^(?:bearer|basic|token)\s+/i;function ur(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(ue(e).map(e=>[dj(e),e])),o=[];for(let[e,t]of Object.entries(n)){let n="string"==typeof t?t.trim():"",r=a.get(e);r?c9.test(n)?o.push([r,n]):s.push({code:"field-reference-invalid",params:{field:e,problem:ut(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():"";c9.test(r)?"select"!==n.kind&&n.targets.every(e=>dk(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:ut(t)}});continue}let r=("string"==typeof e?e:n.defaultValue??"").trim();""===r?n.optional?i.set(n.id,void 0):s.push({code:"field-required",params:{field:n.id}}):"select"===n.kind&&n.options&&!n.options.includes(r)?s.push({code:"field-invalid-option",params:{field:n.id}}):i.set(n.id,{text:r})}if(s.length>0)return{ok:!1,notes:s};let l=new Set,d=new Set;for(let t of e.fields)for(let e of t.targets){let n=i.get(t.id);"password"===t.kind&&void 0!==n&&"text"in n&&l.add(dj(e.path));let s=dy(e.path);if(d.has(s))continue;if(d.add(s),e.parts.some(e=>"string"!=typeof e&&void 0===i.get(e.field))){c7(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):dk(u)?dh(c.text,{atStart:p}):c.text)}c7(r,e.path,a)}for(let[e,t]of o){let n=function(e,t){let[n,r]=t,i=e[n];return void 0===r||"object"!=typeof i||null===i?void 0===r?i:void 0:i[r]}(r,e),i="headers"===e[0]&&"string"==typeof n?n.match(un)?.[0]??"":"";c7(r,e,`${i}$\{${t}}`)}for(let e of us(r))l.add(dj(e));return{ok:!0,config:r,secretPaths:[...l]}}let ui=["command","args","env","cwd","url","headers","oauth"];function us(e){let t=[];for(let n of function(e){if(!de(e))return[];let t=[];for(let n of["env","headers"]){let r=e[n];if(de(r))for(let[e,i]of Object.entries(r))"string"==typeof i&&dt(i)&&""!==i&&(lB(e)||/^(?:bearer|basic|token)\s+\S/i.test(i)||l6(i,lG).masked)&&t.push({kind:"env"===n?"env":"header",name:e})}let n=de(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&""!==n&&dt(n)&&t.push({kind:"oauth-client-secret"}),"string"==typeof e.url&&l2(e.url,lQ).masked&&t.push({kind:"url"}),"string"==typeof e.command&&l6(e.command,lQ).masked&&t.push({kind:"command"}),Array.isArray(e.args)&&l7(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:""):[];l7(n).args.forEach((e,r)=>{e!==n[r]&&t.push(["args",r])})}}return t.sort((e,t)=>ui.indexOf(e[0])-ui.indexOf(t[0]))}let ua="PI_WEB_PASSWORD";function uo(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ul(e){return uo(e)?Object.entries(e).filter(e=>"string"==typeof e[1]):[]}function ud(e){if(!uo(e))return[];if(!("url"in e))return ul(e.env).map(e=>{let[t,n]=e;return{kind:"env",name:t,value:n}});let t=ul(e.headers).map(e=>{let[t,n]=e;return{kind:"header",name:t,value:n}}),n=uo(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&t.push({kind:"oauth-client-secret",value:n}),t}let uc={text:"",rawPi:!1,server:0,values:{},references:{},secretReferences:{}};function uu(e,t,n){let r=c5(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 up(e,t){let n={...e,...t},r=uu(e.text,e.rawPi,e.server);if(void 0!==r&&r===uu(n.text,n.rawPi,e.server))return n;let i={...n,server:0,values:{},references:{},secretReferences:{}};return delete i.name,i}function uh(e){return dr[e.code]??"warning"}function um(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?oI(t):t;if("string"==typeof i.field&&e.code.startsWith("field-")){let e=r.find(e=>e.id===i.field);e&&(s.field=oI(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 ug={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"},uf={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"},ux=JSON.stringify({command:"uvx",args:["mcp-server-fetch"]}),ub=JSON.stringify({name:"fetch",command:"uvx",args:["mcp-server-fetch"]}),uv=[{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 '${ub}'`},{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(ux)}`},{source:"vscode-install-link",text:`vscode:mcp/install?${encodeURIComponent(ub)}`},{source:"visual-studio-install-link",text:`vsweb+mcp:/install?${encodeURIComponent(ub)}`},{source:"copilot-app-install-link",text:`ghapp://mcp/install?${encodeURIComponent(ub)}`}];function uy(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?oI(r):r.field===e.id?n:`‹${oI(t.find(e=>{let{id:t}=e;return t===r.field})?.label??r.field)}›`).join("")}))].join(", ")}function uj(e){return"select"!==e.kind&&e.targets.every(e=>dk(e.path)&&void 0===e.encoding)}let uk=/^[A-Za-z_][A-Za-z0-9_]*$/;function uw(){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 uk.test(r)?r:void 0}let uS=/^(?:proxy-)?authorization$/i;function uC(e,t){let n=function(e,t){if(e.startsWith("env.")){let t=e.slice(4);return uk.test(t)?t:uw(t)}let n=function(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];return uw(t,...n)??uw(...n)};if(e.startsWith("headers.")){let t=e.slice(8);return n(uS.test(t)?"TOKEN":t.replace(/^x-/i,""))}if("oauth.clientSecret"===e)return n("CLIENT_SECRET")}(e,t);return n===ua?void 0:n}function uN(e){return e.startsWith("env.")||e.startsWith("headers.")||"oauth.clientSecret"===e}function uI(e,t){let n=e;for(let e of t)n=n.split(e).join(lA);return{text:n,masked:n!==e}}function u$(e){let{kind:t,name:n}=e;return void 0===n?{kind:t}:{kind:t,name:n}}function uE(e,t){let n=t.files.find(t=>t.scope===e),r=n?.problems.find(o4);return n&&r?{kind:"file-problem",path:n.path,reason:r.reason}:void 0}function uT(e,t){return e.servers.filter(e=>e.scope===t).map(e=>e.name)}function uM(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 uR(e,t,n){switch(e.kind){case"trust-too-broad":return t(uL[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(uA[e.kind])}}let uA={"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"},uL={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 uP(e){return oI(ed(e))}function uz(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}let uO=[{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"}],uW=new Set(["name-derived","name-sanitized","name-deduplicated","name-taken"]);function uF(e){let{notes:t,fields:n=[]}=e,{t:i}=(0,eW.s)();if(0===t.length)return null;let s={error:0,warning:1,info:2},a=[...t].sort((e,t)=>s[uh(e)]-s[uh(t)]);return(0,r.jsx)("ul",{className:"mcp-add-notes",children:a.map((e,t)=>(0,r.jsx)("li",{className:`mcp-add-note is-${uh(e)}`,children:um(e,i,n)},`${t}\0${e.code}`))})}let uD={"server-invalid":"mcp.add.refused.server-invalid","web-password":"mcp.add.blocked.web-password"};function uB(e){let{data:t,cwd:n,draft:s,busy:a,controlsBusy:o,failure:l,onDraftChange:d,onSubmit:c,onTrustProject:u}=e,{t:p}=(0,eW.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:o5(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=>c5(t.text,{rawPi:t.rawPi,takenNames:uT(n,e)}),o=a(t.scope??"global"),l=o.ok?o.servers[Math.min(t.server,o.servers.length-1)]:void 0,d=t.scope??(l?.scopeHint==="project"&&"write"===s.kind?"project":"global");d!==(t.scope??"global")&&(l=(o=a(d)).ok?o.servers[Math.min(t.server,o.servers.length-1)]:void 0);let c={parsed:o,name:t.name??"",scope:d,projectMode:s,..."blocked"===s.kind?{projectBlock:s.block}:{},values:{},pasteSecrets:[],secretReferences:{},fieldProblems:{},secretPaths:[],trustFolder:!1},u=lx(n.mcp);if(!l)return{...c,submitBlock:{kind:u?"mcp-off":"nothing"}};let p=t.name??l.name,h=function(e,t){let n={};for(let r of e.fields){let e=t.references[r.id];void 0!==e&&uj(r)?n[r.id]={reference:e}:void 0!==t.values[r.id]&&(n[r.id]=t.values[r.id])}return n}(l,t),m=ue(l).map(dj),g=Object.fromEntries(m.flatMap(e=>{let n=t.secretReferences[e];return void 0===n?[]:[[e,n]]})),f=ur(l,h,g),x={};if(!f.ok)for(let e of f.notes){let t=e.params?.field;"field-required"===e.code||"string"!=typeof t||t in x||(x[t]=e)}let b=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={};for(let n of e.fields){let e=t[n.id];"object"==typeof e?r[n.id]=uk.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=ur(e,r,Object.fromEntries(Object.entries(n).map(e=>{let[t,n]=e;return[t,uk.test(n.trim())?n:"VALUE"]})));return i.ok?i.secretPaths:[]}(l,h,g),v=function(e,t,n){let r=n?.ok?n.config:e.config,i=n?.ok?function(e,t){let n=new Set;for(let r of e.fields){let e=t[r.id];if("password"!==r.kind||"string"!=typeof e||""===e.trim())continue;let i=e.trim();n.add(i),n.add(i.replace(/\$/g,"$$$$")),n.add(encodeURIComponent(i))}return[...n].filter(e=>""!==e).sort((e,t)=>t.length-e.length)}(e,t):[],s=!1!==r.enabled,a={source:e.source,commandFields:ud(r).filter(e=>{let{value:t}=e;return dm(t)}).map(u$),variableReferences:ud(r).map(e=>({...u$(e),variables:dg(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=uI(r.url,i);return{...a,transport:"http",target:oI(e.text),envNames:[],headerNames:Object.keys(r.headers??{}),masked:e.masked}}let o=uI(oT(r.command,r.args??[]),i);return{...a,transport:"stdio",target:o.text,...void 0!==r.cwd?{cwd:oI(r.cwd)}:{},envNames:Object.keys(r.env??{}),headerNames:[],masked:o.masked}}(l,h,f),y=f.ok?d0(p,f.config):void 0,j="blocked"===s.kind?s.block:b.length>0?{kind:"secret",fields:b,fixed:!b.every(uN)}:uE("project",n),k=uT(n,d),w=n.files.find(e=>e.scope===d);if(u)i={kind:"mcp-off"};else if(dR.test(p))if(k.includes(p))i={kind:"name-taken",name:p,suggestedName:dA(p,k),...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 ud(e))if(t.isCommandConfigValue(n)?n.toUpperCase().includes(ua):t.getConfigValueEnvVarNames(n).some(e=>e.toUpperCase()===ua))return r}(f.config,{isCommandConfigValue:dm,getConfigValueEnvVarNames:dg}))i={kind:"web-password"};else if("project"===d&&j)i={kind:"scope",block:j};else{let e=uE(d,n);e&&(i={kind:"scope",block:e})}else{let e=e=>{let t=String(e.params?.field??"");return l.fields.find(e=>e.id===t)?.label??t},t=f.notes.filter(e=>"field-required"===e.code||"field-reference-invalid"===e.code&&e.params?.problem==="missing");i=t.length>0?{kind:"fields",fields:[...new Set(t.map(e))]}:{kind:"field-invalid",fields:[...new Set(f.notes.map(e))]}}else i={kind:"name-invalid"};return void 0===t.scope&&"project"===d&&j?e({...t,scope:"global"},n,r):{parsed:o,server:l,name:p,scope:d,projectMode:s,...j?{projectBlock:j}:{},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=c5(e,{rawPi:!0});if(!t.ok)return!1;let n=c5(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:j}=g,k=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?[]:k.filter(e=>uW.has(e.code)),S=k.filter(e=>!uW.has(e.code)),C=!a&&!o&&void 0===j,N=()=>{C&&c(uM(s,g))},I=e=>d({...s,...e}),$=t.files.find(e=>e.scope===g.scope)?.path??("project"===g.scope&&n?`${n.replace(/[\\/]+$/,"")}/.pi/mcp.json`:"mcp.json"),E=j&&(""!==s.text.trim()||"mcp-off"===j.kind)?function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];switch(e.kind){case"mcp-off":return t("mcp.reason.mcp-off");case"nothing":return t("mcp.add.blocked.nothing");case"name-invalid":return t("mcp.add.nameInvalid");case"name-taken":return t("mcp.add.nameTaken",{name:oI(e.name),path:e.path?uP(e.path):"mcp.json"});case"fields":return t("mcp.add.blocked.fields",{fields:e.fields.map(oI).join(", ")});case"field-invalid":return t("mcp.add.blocked.fieldsInvalid",{fields:e.fields.map(oI).join(", ")});case"config-invalid":return um(e.note,t,n);case"web-password":return t("mcp.add.blocked.web-password");case"scope":return uR(e.block,t,uP)}}(j,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)(s6,{title:p("mcp.add.title"),catalogs:uO,target:(0,r.jsxs)(s4,{value:g.scope,label:p("config.saveTo"),options:[{value:"global",label:uz("global",p)},{value:"project",label:uz("project",p),disabled:void 0!==y&&"project"!==g.scope}],path:uP($),disabledReason:y?uR(y,p,uP):null,onChange:e=>I({scope:e}),children:[T&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(an,{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:uP(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(up(s,{text:e})),onSubmit:N,examplesLabel:p("mcp.add.examples"),examples:""===s.text.trim()?uv.map(e=>{let{source:t,text:n}=e;return{label:p(uf[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(up(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)(uF,{notes:x.notes}),x.ok&&x.servers.length>1&&(0,r.jsxs)(sX,{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:oI(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)(sX,{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)(uF,{notes:w,fields:b.fields}),j?.kind==="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(an,{size:"small",onClick:()=>I({name:j.suggestedName}),children:p("mcp.add.useName",{name:oI(j.suggestedName)})})})]}),b&&v&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(sY,{children:p("mcp.add.preview")}),(0,r.jsxs)(sQ,{children:[(0,r.jsx)(s0,{label:p("mcp.add.readAs"),children:p(uf[v.source])}),(0,r.jsx)(s0,{label:p("mcp.detail.transport"),children:p(`mcp.transport.${v.transport}`)}),(0,r.jsx)(s0,{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)(s0,{label:p("mcp.detail.cwd"),mono:!0,children:v.cwd}),M.length>0&&(0,r.jsx)(s0,{label:"http"===v.transport?p("mcp.detail.headers"):p("mcp.detail.env"),children:(0,r.jsx)(uH,{names:M})}),v.commandFields.length>0&&(0,r.jsx)(s0,{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=oA(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)(s0,{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:oz(v.variableReferences).map(e=>{let{variable:t,field:n}=e,i=oA(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p("mcp.server.variableIn",{variable:oI(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)(uF,{notes:S,fields:b.fields}),b.fields.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(sY,{children:p("mcp.add.fields")}),b.fields.map(e=>{var t;let n;return(0,r.jsx)(u_,{field:e,fields:b.fields,draft:s,suggestedName:(t=g.name,(n=e.targets[0])?uC(dj(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)(sY,{children:p("mcp.add.secrets")}),g.pasteSecrets.map(e=>{var t,n;let i;return(0,r.jsx)(uU,{label:e,draft:s,suggestedName:uC(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)&&lG(i)?i:void 0):void 0,problem:g.fieldProblems[e],onDraftChange:d},e)})]})]}),(0,r.jsx)(an,{variant:"primary",className:"is-pushed-right",disabled:!C,"aria-busy":a||void 0,"aria-describedby":E?h:void 0,onClick:N,children:a?p("mcp.add.adding"):g.trustFolder?p("mcp.add.buttonTrust"):p("mcp.add.button")}),E&&(0,r.jsx)("p",{id:h,className:`mcp-config-line ${j?.kind==="scope"?"is-warning":"is-dim"}`,children:E}),b&&!j&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:p("mcp.add.afterAdd")}),l&&(0,r.jsxs)("div",{role:"alert",className:"mcp-add-failure",children:[(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[p("mcp.add.failed")," ",function(e,t){if(e.timedOut)return t("mcp.actionTimedOut");if("trust-too-broad"===e.reason&&e.breadth)return t(uL[e.breadth.kind],{path:uP(e.breadth.path)});if("secret-global-only"===e.reason&&e.fields)return t(e.fields.every(uN)?"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:oI(e.name),path:e.path?uP(e.path):"mcp.json"});let n=e.reason?uD[e.reason]:void 0;return n?t(n,{error:oI(e.error)}):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):oI(e.error)}(l,p)]}),l.trustKept&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.trustKept",{folder:uP(l.trust?.decisionPath??n??"")})}),l.notes&&l.notes.length>0&&(0,r.jsx)(uF,{notes:l.notes,fields:b?.fields}),"name-taken"===l.reason&&l.suggestedName&&j?.kind!=="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(an,{size:"small",onClick:()=>I({name:l.suggestedName}),children:p("mcp.add.useName",{name:oI(l.suggestedName)})})}),"host-env-confirm"===l.reason&&l.names&&l.names.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.hostEnv.body",{names:l.names.map(oI).join(", ")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(an,{variant:"danger",size:"small",disabled:a||o||void 0!==j,onClick:()=>c(uM(s,g,l.names)),children:p("mcp.add.hostEnv.confirm")})})]})]})]})}function uH(e){let{names:t}=e,{t:n}=(0,eW.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:oI(e)},e))}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.detail.valuesHidden")})]})}function u_(e){let t,{field:n,fields:s,draft:a,suggestedName:o,problem:l,onDraftChange:d}=e,{t:c}=(0,eW.s)(),u=(0,i.useId)(),p=l?{"aria-invalid":!0,"aria-describedby":u}:{},h=uj(n),m=h?a.references[n.id]:void 0,g=void 0!==m,f=oI(n.label),x=a.values[n.id]??n.defaultValue??"",b=ug[n.reason],v=n.optional&&1===(t=new Set(n.targets.map(e=>{let{path:t}=e;return"headers"===t[0]?t[1]:void 0}))).size?[...t][0]:void 0,y=g?m&&!l?uy(n,s,"${"+m+"}",!0):void 0:uy(n,s,`‹${c("mcp.add.field.slot")}›`),j=e=>d({...a,values:{...a.values,[n.id]:e}}),k=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)(sX,{label:f,children:g?(0,r.jsx)("input",{className:"mcp-add-input","aria-label":c("mcp.add.field.variableName",{field:f}),value:m,placeholder:o??"GITHUB_TOKEN",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...p,onChange:e=>k(e.target.value)}):"select"===n.kind?(0,r.jsxs)("select",{className:"mcp-add-input","aria-label":f,value:x,...p,onChange:e=>j(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:oI(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?oI(n.placeholder):void 0,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...p,onChange:e=>j(e.target.value)})}),l&&(0,r.jsx)("span",{id:u,className:"mcp-config-line is-error",children:um(l,c,[n])}),(0,r.jsxs)("span",{className:"mcp-config-lines",children:[n.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:oI(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:oI(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=>k(e.target.checked?o??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:c("mcp.add.field.useVariable")})]})]})}function uU(e){let{label:t,draft:n,suggestedName:s,stored:a,problem:o,onDraftChange:l}=e,{t:d}=(0,eW.s)(),c=(0,i.useId)(),u=n.secretReferences[t],p=void 0!==u,h=oI(t),m=e=>{let r={...n.secretReferences};void 0===e?delete r[t]:r[t]=e,l({...n,secretReferences:r})};return(0,r.jsxs)("div",{className:"mcp-add-field",children:[(0,r.jsx)("span",{className:"mcp-config-lines",children:(0,r.jsxs)("span",{className:"mcp-config-line",children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:h})," ",d("mcp.add.secret.holds")]})}),(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:p,onChange:e=>m(e.target.checked?s??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("mcp.add.field.useVariable")})]}),p&&(0,r.jsx)(sX,{label:d("mcp.add.field.variableName",{field:h}),children:(0,r.jsx)("input",{className:"mcp-add-input","aria-label":d("mcp.add.field.variableName",{field:h}),value:u,placeholder:s??"API_TOKEN",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...o?{"aria-invalid":!0,"aria-describedby":c}:{},onChange:e=>m(e.target.value)})}),o&&(0,r.jsx)("span",{id:c,className:"mcp-config-line is-error",children:um(o,d)}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p?void 0!==a?d("mcp.add.secret.storedAs",{value:oI(a)}):d("mcp.add.field.variableHint"):d("mcp.add.secret.asPasted")})]})}let uq=new Set(["done","failed","cancelled","expired"]);function uK(e){var t;return e?.flow!==void 0&&!e.gone&&(t=e.flow.phase,!uq.has(t))}let uZ={"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"},uV={"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"},uJ={connecting:"mcp.signIn.phase.connecting",starting:"mcp.signIn.phase.starting",finishing:"mcp.signIn.phase.finishing"},uG={"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 uY(e,t,n){var r;let i={...e,flow:t,deadlineAt:n+t.expiresInMs,gone:!1};return r=t.phase,uq.has(r)&&(delete i.pasteError,delete i.cancelError,i.pasting&&(i.pasting=!1),i.cancelling&&(i.cancelling=!1)),i}function uX(e){return"sign-in-unknown"===e.reason}async function uQ(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:ls(a,s.status)}}function u0(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},a=t.method??"GET";return la(r=>uQ(e,t,n,r),()=>({ok:!1,error:{error:`${a} ${e} did not answer within ${i} ms`,timedOut:!0}}),i,r,s)}function u1(e){return`/api/mcp/sign-in/${encodeURIComponent(e)}`}function u2(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?uV[e.reason]:void 0;return r?t(r):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function u4(e){let{server:t,run:n,block:s,signOutBlock:a,controlsBusy:o,signingOut:l,onSignIn:d,onSignOut:c,onPaste:u,onCancel:p}=e,{t:h}=(0,eW.s)(),m=(0,i.useId)(),g=(0,i.useId)(),f=(0,i.useId)(),x=(0,i.useRef)(null),b=(0,i.useRef)(null),v=uK(n),y=(0,i.useRef)(v);if((0,i.useEffect)(()=>{let e=y.current;y.current=v,!e&&v?eC(document,b.current):e&&!v&&eC(document,x.current)},[v]),!t.usesOAuth)return void 0===t.authProvider&&t.headerNames.some(e=>"authorization"===e.toLowerCase())?null:(0,r.jsx)(s0,{label:h("mcp.detail.signIn"),children:void 0!==t.authProvider?h("mcp.signIn.provider",{provider:oI(t.authProvider)}):h("mcp.signIn.header")});let j=n?.flow,k=n?.starting===!0,w=void 0!==j&&(j.scope!==t.scope||j.name!==t.name),S=(t.oauthStateStored??t.signedIn)!==!1,C=k||l||void 0!==s,N=o||k||void 0!==a,I=j?.phase==="finishing";return(0,r.jsx)(s0,{label:h("mcp.detail.signIn"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line",children:h(!0===t.signedIn?"mcp.signIn.signedIn":!1===t.signedIn?t.oauthStateStored?"mcp.signIn.registrationOnly":"mcp.signIn.notSignedIn":"mcp.signIn.unknown")}),j&&v&&w&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.shared",{name:oI(j.name)})}),j&&v&&("authorize"===j.phase?(0,r.jsx)(u8,{flow:j,pasting:n?.pasting===!0,pasteError:n?.pasteError,onPaste:e=>u(t,j.flowId,e)},j.flowId):(0,r.jsx)("span",{role:"status",className:"mcp-config-line",children:h(uJ[j.phase]??"mcp.signIn.phase.connecting")})),j&&v&&I&&(0,r.jsx)("span",{id:f,className:"mcp-config-line is-dim",children:h("mcp.signIn.phase.noCancel")}),j&&!v&&!n?.gone&&(0,r.jsx)(u6,{flow:j,shared:w}),n?.gone&&(0,r.jsx)("span",{role:"alert",className:"mcp-config-line is-warning",children:h("mcp.signIn.gone")}),n?.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.requestFailed")," ",u2(n.error,h)]}),v&&n?.cancelError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.cancelFailed")," ",u2(n.cancelError,h,"mcp.signIn.cancelTimedOut")]}),n?.signOutError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.signOutFailed")," ",u2(n.signOutError,h,"mcp.actionTimedOut")]}),n?.signedOut&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line",children:h(n.signedOut.removed?"mcp.signIn.signedOutDone":"mcp.signIn.signedOutNothing")}),s&&(0,r.jsx)("span",{id:m,className:"mcp-config-line is-dim",children:h(uZ[s])}),!s&&a&&S&&!v&&(0,r.jsx)("span",{id:g,className:"mcp-config-line is-dim",children:h(uZ[a])}),(0,r.jsxs)("div",{className:"mcp-sign-in-actions",children:[v&&j?(0,r.jsx)(an,{ref:b,size:"small",disabled:n?.cancelling===!0||I,"aria-busy":n?.cancelling===!0||void 0,"aria-describedby":I?f:void 0,onClick:()=>p(t,j.flowId),children:h(n?.cancelling?"mcp.signIn.cancelling":"mcp.signIn.cancel")}):(0,r.jsx)(an,{ref:x,size:"small",variant:"primary",disabled:C,"aria-busy":k||void 0,"aria-describedby":s?m:void 0,onClick:()=>d(t),children:h(k?"mcp.signIn.starting":"mcp.signIn.button")}),S&&!v&&(0,r.jsx)(an,{size:"small",disabled:N,"aria-busy":l||void 0,"aria-describedby":a?s?m:g:void 0,onClick:()=>c(t),children:h(l?"mcp.signIn.signingOut":"mcp.signIn.signOut")})]}),!s&&!v&&S&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.replaces")}),S&&!a&&!v&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.signOutExplain")})]})})}function u8(e){let{flow:t,pasting:n,pasteError:s,onPaste:a}=e,{t:o}=(0,eW.s)(),[l,d]=(0,i.useState)(""),c=(0,i.useRef)(null),u=(0,i.useRef)(n);(0,i.useEffect)(()=>{let e=u.current;u.current=n,e&&!n&&eC(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)(ax,{message:o("mcp.signIn.authorize.message"),hint:p?(0,r.jsxs)(r.Fragment,{children:[o("mcp.signIn.authorize.link")," ",(0,r.jsx)("a",{href:p,target:"_blank",rel:"noopener noreferrer",children:oI(p)})]}):(0,r.jsxs)(r.Fragment,{children:[o("mcp.signIn.authorize.notALink")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:oI(t.authorizationUrl??"")})]}),value:l,placeholder:o("mcp.signIn.paste.placeholder"),inputLabel:o("mcp.signIn.paste.label"),submitLabel:o(n?"mcp.signIn.paste.checking":"mcp.signIn.paste.submit"),disabled:n,plainEnterSubmits:!1,inputRef:c,onValueChange:d,onSubmit:()=>a(l)}),s&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[o("mcp.signIn.paste.refused")," ",u2(s,o,"mcp.signIn.paste.timedOut"),"redirect-denied"===s.reason&&s.error&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:oI(s.error)})]})]}),t.redirectUrl&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.signIn.authorize.redirect",{url:oI(t.redirectUrl)})}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.signIn.authorize.wait")})]})}function u6(e){let{flow:t,shared:n}=e,{t:i}=(0,eW.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 uG[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:oI(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:oI(t.error)})]})]})}function u3(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function u5(e){return oI(ed(e))}function u9(e,t){let{key:n,params:r}=e;return r?t(n,void 0===r.path?r:{...r,path:u5(r.path)}):t(n)}function u7(e,t){return e.timedOut?t("mcp.loadTimedOut"):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function pe(e,t){return e.timedOut?t("mcp.actionTimedOut"):u7(e,t)}function pt(){if("u"<typeof document)return null;let e=document.activeElement;return e instanceof HTMLButtonElement||e instanceof HTMLSelectElement?e:null}function pn(e){let{cwd:t,onClose:n,embedded:s=!1,trust:a,onTrustProject:o,onProjectTrustChanged:l}=e,[d,c]=(0,i.useState)({state:"loading"}),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(()=>so("mcp",t)),[g,f]=(0,i.useState)({saving:!1,error:null}),[x,b]=(0,i.useState)(null),[v,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(null),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),[I,$]=(0,i.useState)({}),E=(0,i.useRef)(0),T=(0,i.useRef)(null),M=(0,i.useRef)(null),R=(0,i.useRef)(null),A=(0,i.useRef)(new Map),[L,P]=(0,i.useState)({}),z=(0,i.useRef)(L);z.current=L;let[O,W]=(0,i.useState)(0),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)(uc),_=(0,i.useRef)(B);_.current=B;let[U,q]=(0,i.useState)(null),[K,Z]=(0,i.useState)(null),V=(0,i.useRef)(!0),J=(0,i.useRef)(d);J.current=d;let G=(0,i.useCallback)(async()=>{let e=++E.current;T.current?.abort();let n=new AbortController;T.current=n,p(!0);let r=await lu(t,void 0,n.signal);if(e===E.current){if(p(!1),!r.ok)return void c({state:"failed",error:r.error});c({state:"loaded",data:r.data,...r.projectError?{projectError:r.projectError}:{}}),m(e=>o3(o8(r.data,!!t),e))}},[t]),Y=a0(a);(0,i.useEffect)(()=>(G(),()=>{E.current+=1,T.current?.abort()}),[G,Y]);let X=(0,i.useCallback)(async e=>{let t=new AbortController;M.current=t,f({saving:!0,error:null,target:"preference"});let n=await lm(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 lg(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 lf(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=oF(e);if(A.current.has(n))return;let r={};A.current.set(n,r),$(e=>({...e,[n]:{...e[n],running:!0,startedAt:Date.now(),error:void 0,queueTimedOut:void 0,configKey:void 0}}));let i=J.current,s="loaded"===i.state&&i.data.project?t:null,a=await lR({scope:e.scope,name:e.name},s);if(A.current.get(n)!==r)return;A.current.delete(n),$(t=>({...t,[n]:function(e,t,n){let r=e?.signedOutAt,i={...e?.startedAt!==void 0?{startedAt:e.startedAt}:{},...void 0!==r?{signedOutAt:r}:{}};if(void 0!==r&&(e?.startedAt??0)<=r)return{running:!1,...i};let s=e?.response?{response:e.response}:{};return t.ok?t.data.result.queueTimedOut?{running:!1,...i,...s,queueTimedOut:!0,configKey:t.data.configKey}:{running:!1,...i,response:t.data}:{running:!1,...i,...s,error:t.error,...void 0!==n?{configKey:n}:{}}}(t[n],a,e.configKey)}));let o=J.current,l="loaded"===o.state?o.data.servers.find(e=>oF(e)===n):void 0;(a.ok?l?.configKey===a.data.configKey:void 0===a.error.reason||a.error.timedOut)||G()},[t,G]),en=(0,i.useCallback)((e,n)=>{E.current+=1,T.current?.abort(),p(!1),c(t=>({state:"loaded",data:e,..."loaded"===t.state&&t.projectError?{projectError:t.projectError}:{}})),m(r=>o3(o8(e,!!t),n??r))},[t]),er=(0,i.useCallback)(async e=>{let n=oF(e),r=z.current[n];if(r?.starting||uK(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 u0("/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?uY({},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=oF(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 u0(u1(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?{...uY(i,n.data,r),pasteError:void 0}:uX(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=oF(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 u0(u1(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?uY(i,n.data,r):uX(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 uK(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 u0(u1(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?uY(e,n.data,r):uX(n.error)||void 0!==e.deadlineAt&&r>e.deadlineAt+5e3?{...e,gone:!0}:e:e}(e[n],r,s,Date.now(),i);return void 0===t||t===e[n]?e:{...e,[n]:t}})}W(e=>e+1)},1e3);return()=>{clearTimeout(t),e.abort()}},[ea,O]);let eo=(0,i.useRef)(L);(0,i.useEffect)(()=>{let e=eo.current;eo.current=L,Object.keys(L).some(t=>{var n,r;return n=e[t],r=L[t],uK(n)&&!uK(r)})&&G()},[L,G]);let el=(0,i.useCallback)(async(e,n,r)=>{R.current?.abort();let i=new AbortController;R.current=i,b(n);let s=J.current,a="loaded"===s.state&&s.data.project?t:null,o=await lw(e,a,void 0,i.signal);if(R.current===i)return R.current=null,b(null),o.ok?en(o.data,r?.(o.data)):G(),o},[en,t,G]),ed=(0,i.useCallback)(async(e,t)=>{let n=oF(e),r=pt();y(null),k(null);let i=await el({action:t?"enable":"disable",scope:e.scope,name:e.name},`switch:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[el]),ec=(0,i.useCallback)(async(e,t)=>{let n=oF(e),r=pt();y(null),k(null);let i=await el({action:"set-in-project",name:e.name,enabled:t},`in-project:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[el]),eu=(0,i.useCallback)(async(e,t)=>{let n=oF(e),r=pt();y(null),k(null);let i=await el({action:"set-exposure",scope:e.scope,name:e.name,exposure:t},`exposure:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[el]),ep=(0,i.useCallback)(async e=>{let t=oF(e),n=pt();y(null),k(null);let r=await el({action:"remove",scope:e.scope,name:e.name},`remove:${t}`);if(!r)return;if(!r.ok){y({key:t,failure:r.error}),N({control:n});return}let i=r.data.undo;i&&S({...i,undoing:!1})},[el]),eh=(0,i.useCallback)(async()=>{if(!w)return;let e=pt();y(null),k(null),S({...w,undoing:!0,error:void 0});let t=await el({action:"undo",token:w.token},"undo",e=>e.restored?oF(e.restored):void 0);t&&(S(e=>e?.token!==w.token?e:t.ok?null:{...e,undoing:!1,error:t.error}),t.ok||N({control:e}))},[el,w]),em=(0,i.useCallback)(async e=>{let t=oF(e),n=pt();y(null),k(null),P(e=>({...e,[t]:{...e[t],signOutError:void 0,signedOut:void 0}}));let r=await el({action:"sign-out",scope:e.scope,name:e.name},`sign-out:${t}`);if(r){if(P(e=>({...e,[t]:r.ok?{signedOut:{removed:r.data.signedOut?.removed===!0}}:{...e[t],signOutError:r.error}})),r.ok){let e=Date.now();$(n=>{let r=function(e,t){if(e)return{running:e.running,...void 0!==e.startedAt?{startedAt:e.startedAt}:{},signedOutAt:t}}(n[t],e);return r?{...n,[t]:r}:n})}N({control:n})}},[el]),eg=(0,i.useCallback)(async e=>{let n=pt(),r=_.current;y(null),k(null),q(null);let i=await el(e,"add",e=>e.added?oF(e.added):void 0);if(!i)return;let s=_.current!==r;if(!i.ok){s||q(i.error),i.error.trust&&t&&l?.(t,i.error.trust),N({control:n});return}let{added:a,trust:o,trustedFolder:d}=i.data;if(D(!1),s||H(uc),N({control:null,toSelectedRow:!0}),!a)return;Z({...a,key:oF(a),...d&&t?{trustedFolder:t}:{}}),o&&t&&l?.(t,o);let c=i.data.servers.find(e=>oF(e)===oF(a));c&&!lC(c,i.data)&&et(c)},[t,l,el,et]),ef=w?.token,ex=w?.expiresInMs;(0,i.useEffect)(()=>{if(void 0===ef||void 0===ex)return;let e=setTimeout(()=>S(e=>e?.token===ef?null:e),ex);return()=>clearTimeout(e)},[ef,ex]);let eb=(0,i.useCallback)(async(e,t,n)=>{let{targets:r,keptOff:i}={targets:aQ(t,n,e=>e.enabled).filter(n?lj:ly),keptOff:n?t.filter(e=>!e.enabled&&ly(e)&&!lj(e)).length:0},s=pt();if(y(null),k(i>0?{scope:e,keptOff:i,failures:[],total:0}:null),0===r.length)return;let a=await el({action:"set-enabled",enabled:n,servers:r.map(e=>{let{scope:t,name:n}=e;return{scope:t,name:n}})},`group:${e}`);if(!a)return;if(N({control:s}),!a.ok)return void k({scope:e,keptOff:i,failures:[],total:r.length,error:a.error});let o=a.data.results??[],l=o.filter(e=>void 0!==e.reason).map(e=>({name:e.name,failure:{error:e.error??"",reason:e.reason}}));k(l.length>0||i>0?{scope:e,keptOff:i,failures:l,total:o.length}:null)},[el]);return(0,i.useEffect)(()=>{h&&sl("mcp",h,t)},[t,h]),(0,r.jsx)(pr,{cwd:t,load:d,selected:h,refreshing:u,embedded:s,codemodeSave:g,busy:x,actionError:v,groupStatus:j,undo:w,focusBack:C,tests:I,signIns:L,adding:F,addDraft:B,addFailure:U,added:K,onAddOpen:()=>{D(!0),Z(null),y(null)},onAddDraftChange:e=>{_.current=e,H(e),q(null)},onAddSubmit:e=>void eg(e),onTest:e=>void et(e),onSignIn:e=>void er(e),onSignOut:e=>void em(e),onSignInPaste:(e,t,n)=>void ei(e,t,n),onSignInCancel:(e,t)=>void es(e,t),onSelect:e=>{m(e),y(null),D(!1),Z(t=>t?.key===e?t:null)},onRefresh:()=>void G(),onCodemodeChange:e=>void X(e),onCodemodeModeChange:e=>void Q(e),onCodemodeInlineBudgetSave:e=>void ee(e),onServerSwitch:(e,t)=>void ed(e,t),onServerSwitchInProject:(e,t)=>void ec(e,t),onExposureChange:(e,t)=>void eu(e,t),onGroupSwitch:(e,t,n)=>void eb(e,t,n),onRemove:e=>void ep(e),onUndo:()=>void eh(),onTrustProject:o,onClose:n})}function pr(e){var t,n,s,a;let o,l,d,{cwd:c,load:u,selected:p,refreshing:h,embedded:m,codemodeSave:g={saving:!1,error:null},busy:f=null,actionError:x=null,groupStatus:b=null,undo:v=null,focusBack:y=null,tests:j={},signIns:k={},adding:w=!1,addDraft:S=uc,addFailure:C=null,added:N=null,onAddOpen:I=()=>{},onAddDraftChange:$=()=>{},onAddSubmit:E=()=>{},onSelect:T,onRefresh:M,onCodemodeChange:R,onCodemodeModeChange:A=()=>{},onCodemodeInlineBudgetSave:L=()=>{},onServerSwitch:P=()=>{},onServerSwitchInProject:z=()=>{},onExposureChange:O=()=>{},onGroupSwitch:W=()=>{},onRemove:F=()=>{},onUndo:D=()=>{},onTest:B=()=>{},onSignIn:H=()=>{},onSignOut:_=()=>{},onSignInPaste:U=()=>{},onSignInCancel:q=()=>{},onTrustProject:K,onClose:Z}=e,{t:V}=(0,eW.s)(),J=(0,i.useId)(),G=(0,i.useId)(),Y="loaded"===u.state?(t=u.data,o=!1,l=t.servers.map(e=>{var t;let n=j[oF(e)]?.response;if(!n||n.configKey!==e.configKey||e.status&&("test"===(t=e.status).origin?t.testedAt:t.closedAt??t.updatedAt)>=n.result.testedAt)return e;o=!0;let r={...n.result,origin:"test"};return{...e,status:r}}),o?{...t,servers:l}:t):void 0,X=Y?o8(Y,!!c):[],Q=Y?{mcpAvailable:Y.mcp.available,projectServersLoad:oD(Y.project)}:void 0,ee=X.flatMap(e=>e.servers),et=ee.find(e=>oF(e)===p),en=N?ee.find(e=>oF(e)===N.key):void 0,er=Y?function(e){if(!e.available)return"builtin-disabled"===e.reason?e.settingsPath?{key:"mcp.unavailable.builtin-disabled",params:{path:e.settingsPath}}:{key:"mcp.unavailable.builtin-disabled-unknown"}:{key:"operator-disabled"===e.reason?"mcp.unavailable.operator-disabled":"mcp.unavailable.internals-unavailable"}}(Y.mcp):void 0,ei=er?void 0:Y?.hostInactive,es=Y?.files.find(e=>"project"===e.scope),ea=Y?function(e,t){if(!e||!t||!t.exists&&0===t.problems.length)return;let{trust:n}=e;return n?n.requiresTrust||!1===n.decision?!0===n.decision?n.inherited&&n.decisionPath?{kind:"inherited",key:"mcp.trust.trustedThrough",params:{path:n.decisionPath}}:void 0:!1===n.decision&&n.inherited&&n.decisionPath?{kind:"untrusted",key:"mcp.trust.untrustedThrough",params:{path:n.decisionPath}}:{kind:"untrusted",key:"mcp.trust.untrusted"}:void 0:{kind:"untrusted",key:"mcp.trust.unreadable"}}(Y.project,es):void 0,eo=K&&o5(Y?.project)?K:void 0,el=ea?.kind==="untrusted"&&void 0!==eo,ec=(0,i.useRef)(null),eu=(0,i.useRef)(null),ep=(0,i.useRef)(el);(0,i.useEffect)(()=>{let e=ep.current;ep.current=el,e&&!el&&eC(document,ec.current??eu.current)},[el]);let eh=(0,i.useRef)(null),em=v?.token,eg=(0,i.useRef)(em);(0,i.useEffect)(()=>{let e=eg.current;eg.current=em,void 0!==em&&em!==e?eC(document,eh.current):void 0!==e&&void 0===em&&eC(document,ec.current??eu.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=o6(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&&oD(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(o4))?"mcp.emptyFileProblem":"mcp.empty"):void 0,ej=null!==f||h||g.saving,ek=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(y&&!ej&&ek.current!==y)if(ek.current=y,y.toSelectedRow)eC(document,ec.current??eu.current);else{var e,t,n;e=document,t=y.control,n=ec.current??eu.current,t&&eC(e,t.isConnected&&!t.disabled?t:n)}},[y,ej]);let ew=e=>Y?lb(e,Y):void 0,eS=!!Y&&lx(Y.mcp),eN=X.find(e=>"project"===e.scope)?.servers??[],eI=ew("project"),e$=ea?.kind==="untrusted"?[u9(ea,V),eI&&"mcp-off"!==eI&&eN.length>0?V(lv[eI]):null].filter(Boolean).join(" "):"";return(0,r.jsxs)(sA,{embedded:m,title:V("settings.mcp"),subtitle:c?ed(c):void 0,closeLabel:V("i18n.close"),onClose:Z,children:[(0,r.jsxs)("div",{className:"mcp-config-notices",children:[er&&(0,r.jsxs)(s3,{id:J,children:[u9(er,V),eS&&(0,r.jsxs)(r.Fragment,{children:[" ",V(lv["mcp-off"])]}),Y&&!Y.mcp.available&&Y.mcp.detail&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:oI(Y.mcp.detail)})]})]}),ei&&(0,r.jsx)(s3,{children:V("mcp.hostInactive",{path:u5(ei.cwd),owner:u5(ei.owner)})}),"loaded"===u.state&&u.projectError&&(0,r.jsx)(s3,{children:V("mcp.projectNotListed",{reason:u7(u.projectError,V)})}),ea?.kind==="untrusted"&&(0,r.jsx)(s5,{id:G,message:e$,trustLabel:V("mcp.trust.trustButton"),onTrust:eo}),ea?.kind==="inherited"&&(0,r.jsx)(s3,{children:u9(ea,V)}),v&&(0,r.jsxs)(s3,{action:v.error?.reason==="undo-unavailable"?void 0:(0,r.jsx)(an,{ref:eh,size:"small",onClick:D,disabled:v.undoing||ej,children:v.undoing?V("mcp.undoing"):V("mcp.undo")}),children:[V("mcp.removed",{name:oI(v.name),path:u5(v.path)}),v.error&&(0,r.jsxs)(r.Fragment,{children:[" ",V("mcp.undoFailed")," ",pe(v.error,V)]})]}),N&&Y&&en&&(0,r.jsx)(pi,{added:N,cwd:c,server:en,testing:j[N.key]?.running===!0,signIn:k[N.key],signingOut:f===`sign-out:${N.key}`,signInBlock:en?lC(en,Y):void 0,onSignIn:H})]}),(0,r.jsxs)(sW,{children:[(0,r.jsxs)(sF,{children:[(0,r.jsx)(sD,{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")," ",u7(u.error,V)]}):Y&&Q?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-sidebar-group",children:(0,r.jsx)(ps,{codemode:Y.codemode,active:!w&&p===oW,rowRef:ec,onSelect:T})}),X.map(e=>{let t=ew(e.scope);return(0,r.jsx)(pa,{group:e,context:Q,selected:w?null:p,selectedRowRef:ec,block:t,blockNoticeId:"mcp-off"===t?er?J:void 0:t&&ea?.kind==="untrusted"?G:void 0,busy:f,controlsBusy:ej,status:b?.scope===e.scope?b:null,onSelect:T,onGroupSwitch:W},e.scope)})]}):null}),Y&&(0,r.jsx)(ai,{ref:eu,active:w,onClick:I,children:V("mcp.add.action")})]}),(0,r.jsx)(s7,{children:(0,r.jsx)(sK,{className:"is-fill",children:Y&&Q&&ev&&ey?w?(0,r.jsx)(uB,{data:Y,cwd:c,draft:S,busy:"add"===f,controlsBusy:ej,failure:C,onDraftChange:$,onSubmit:E,onTrustProject:eo}):p===oW?(0,r.jsx)(pb,{codemode:Y.codemode,autoEnable:ev,save:g,serverBusy:null!==f,onChange:R,onModeChange:A,onInlineBudgetSave:L}):et?(0,r.jsx)(pd,{server:et,context:Q,codemode:Y.codemode,toolSearchDisabled:Y.toolSearchDisabled,autoEnable:ev,block:ew(et.scope),inProject:function(e,t){if("global"!==e.scope||void 0!==e.invalidError||e.notAnObject||!oD(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:oF(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:ej,actionError:x?.key===oF(et)?x.failure:null,test:(a=j[oF(et)],a&&void 0!==a.configKey&&a.configKey!==et.configKey?{running:a.running,...a.response?{response:a.response}:{}}:a),testBlock:lC(et,Y),signIn:k[oF(et)],signInBlock:lC(et,Y),signOutBlock:(d=lb(et.scope,Y))||(void 0===et.invalidError&&et.validated?void 0:"invalid"),onSwitch:P,onSwitchInProject:z,onShowServer:e=>{T(e),requestAnimationFrame(()=>eC(document,ec.current??eu.current))},onExposureChange:O,onRemove:F,onTest:B,onSignIn:H,onSignOut:_,onSignInPaste:U,onSignInCancel:q},oF(et)):(0,r.jsx)(s9,{children:"mcp.empty"===ey?V(ey,{globalPath:u5(eb?.path??"~/.pi/agent/mcp.json")}):V(ey)}):null})})]}),(0,r.jsxs)(ae,{status:ef.length>0?(0,r.jsx)(at,{tone:ef.some(e=>{let{problem:t}=e;return o4(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=oO(n,t.realPath);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:u5(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)(at,{summary:ex.total>0?V("mcp.serverCount",{enabled:ex.enabled,total:ex.total}):""}),children:[!m&&(0,r.jsx)(an,{onClick:Z,children:V("i18n.close")}),(0,r.jsx)(an,{variant:"secondary",onClick:M,disabled:ej,children:V("i18n.refresh")})]})]})}function pi(e){let{added:t,cwd:n,server:i,testing:s,signIn:a,signingOut:o,signInBlock:l,onSignIn:d}=e,{t:c}=(0,eW.s)(),u=oI(t.name),p="project"===t.scope&&n?oI(ec(t.path,n)):u5(t.path),h=i.status,m=!s&&h?.origin==="test"&&"needs-auth"===h.state&&i.usesOAuth,g=a?.starting===!0||uK(a);return(0,r.jsxs)(s3,{action:!m||g||o||l?void 0:(0,r.jsx)(an,{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:u5(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 ps(e){let{codemode:t,active:n,rowRef:i,onSelect:s}=e,{t:a}=(0,eW.s)(),o=t.builtinDisabled||"unavailable"===t.sandbox.state?"unavailable":t.preference??"unknown",l=a(ln[o]);return(0,r.jsxs)(sU,{ref:n?i:void 0,active:n,"aria-label":a("mcp.codemode.rowLabel",{state:l}),onClick:()=>s(oW),children:[(0,r.jsx)(as,{...oJ(lr(o))}),(0,r.jsx)(sq,{className:"is-grow",children:a("mcp.codemode.title")}),(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${lr(o)}`,children:l})]})}function pa(e){var t;let n,i,{group:s,context:a,selected:o,selectedRowRef:l,block:d,blockNoticeId:c,busy:u,controlsBusy:p,status:h,onSelect:m,onGroupSwitch:g}=e,{t:f}=(0,eW.s)(),{enabled:x,total:b}=o6(s.servers),v=(t=s.servers).some(e=>e.enabled&&ly(e))&&t.every(e=>e.enabled||!lj(e)),y=function(e){if(!(e.servers.length>0))return e.file?e.file.problems.some(o4)?"mcp.group.fileProblem":"mcp.group.empty":"mcp.group.notListed"}(s),j=h?(n=h.keptOff>0?f("mcp.groupKeptOff",{count:h.keptOff}):void 0,i=h.error?`${f("mcp.actionFailed")} ${pe(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`${oI(t)}: ${pe(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)(sB,{aside:b>0?(0,r.jsx)(sH,{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:u3(s.scope,f)}),onChange:e=>g(s.scope,s.servers,e)}):void 0,children:u3(s.scope,f)}),j&&(0,r.jsx)(s_,{note:j.note,error:j.error}),y&&(0,r.jsx)("div",{className:"mcp-sidebar-group-empty",children:f(y)}),s.servers.map(e=>{let t=oF(e),n=oH(e,a),i=oV(n),s=oZ[n],d=oI(e.name);return(0,r.jsxs)(sU,{ref:o===t?l:void 0,active:o===t,"aria-label":f("mcp.rowLabel",{name:d,state:f(oq(n,e.status))}),onClick:()=>m(t),children:[(0,r.jsx)(as,{...oJ(i)}),(0,r.jsx)(sq,{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 po(e){let{fields:t}=e,{t:n}=(0,eW.s)();return(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>{let t=oA(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function pl(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:oI(e)},e))})}function pd(e){let{server:t,context:n,codemode:s,toolSearchDisabled:a,autoEnable:o,block:l,inProject:d,inProjectBlock:c,savedWhileOff:u,busy:p,controlsBusy:h,actionError:m,test:g,testBlock:f,signIn:x,signInBlock:b,signOutBlock:v,onSwitch:y,onSwitchInProject:j,onShowServer:k,onExposureChange:w,onRemove:S,onTest:C,onSignIn:N,onSignOut:I,onSignInPaste:$,onSignInCancel:E}=e,{t:T}=(0,eW.s)(),M=(0,i.useId)(),R=(0,i.useId)(),A=oH(t,n),L=oM(t),P=t.status,z=P?.origin==="test"&&"connected"===P.state&&P.toolCount>0?P:void 0,O=void 0===t.invalidError,W="http"===t.transport||void 0===t.transport&&void 0!==t.url,F=!W&&("stdio"===t.transport||void 0!==t.command),D=t.exposure?function(e,t,n){if("codemode"===e){var r;return r=t.codemode,"unavailable"===r.sandbox.state?{key:"mcp.exposure.sandboxUnavailable"}:r.builtinDisabled?{key:"mcp.exposure.builtinDisabled"}:n.value||"always"===o9(r)?void 0:{key:"mcp.exposure.autoEnableOff",params:{path:n.path}}}if("deferred"!==e||!t.toolSearchDisabled)return;let i=t.toolSearchDisabled.settingsPath;return i?{key:"mcp.exposure.toolSearchDisabled",params:{path:i}}:{key:"mcp.exposure.toolSearchDisabledUnknown"}}(t.exposure,{codemode:s,toolSearchDisabled:a},o):void 0,B=(0,i.useId)(),H=(0,i.useId)(),_=oF(t),U=oI(t.name),q=!t.enabled&&void 0!==t.webPasswordField,K=!0===t.notAnObject,Z=l?T(`mcp.reason.${l}`):K?T("mcp.reason.entry-not-object"):q?T("mcp.reason.web-password"):u?T("mcp.write.savedWhileOff"):void 0;return(0,r.jsxs)(sK,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(sZ,{children:[(0,r.jsxs)(sV,{children:[(0,r.jsx)(s1,{scope:t.scope,children:u3(t.scope,T)}),(0,r.jsx)(sG,{children:U})]}),(0,r.jsxs)(sJ,{children:[(0,r.jsx)(pf,{server:t,test:g,testBlock:f,describedBy:R,onTest:C}),(0,r.jsx)(an,{variant:"danger",size:"small",disabled:h||void 0!==l,"aria-describedby":l?M:void 0,onClick:()=>S(t),children:p===`remove:${_}`?T("i18n.removing"):T("i18n.remove")}),(0,r.jsx)(ar,{checked:t.enabled,disabled:h||void 0!==l||K||q,loading:p===`switch:${_}`,describedBy:Z?M:void 0,label:T(t.enabled?"mcp.server.switchOff":"mcp.server.switchOn",{name:U}),onChange:e=>y(t,e)})]})]}),Z&&(0,r.jsx)("div",{id:M,className:"config-detail-heading-note",children:Z})]}),m&&(0,r.jsxs)("p",{role:"alert",className:"mcp-config-line is-error",children:[T("mcp.actionFailed")," ",pe(m,T)]}),(0,r.jsxs)(sQ,{children:[(0,r.jsx)(px,{server:t,state:A,test:g,testBlock:f,testBlockId:R}),void 0!==t.description&&(0,r.jsx)(s0,{label:T("mcp.detail.description"),tone:"plain",children:oI(t.description)}),void 0!==L?(0,r.jsx)(s0,{label:W?T("mcp.detail.url"):T("mcp.detail.command"),tone:"plain",mono:!0,className:"mcp-config-code",children:L}):t.transport&&(0,r.jsx)(s0,{label:T("mcp.detail.transport"),children:T(`mcp.transport.${t.transport}`)}),F&&void 0!==t.cwd&&(0,r.jsx)(s0,{label:T("mcp.detail.cwd"),mono:!0,className:"mcp-config-code",children:oI(t.cwd)}),F&&t.envNames.length>0&&(0,r.jsx)(s0,{label:T("mcp.detail.env"),children:(0,r.jsx)(pl,{names:t.envNames})}),W&&t.headerNames.length>0&&(0,r.jsx)(s0,{label:T("mcp.detail.headers"),children:(0,r.jsx)(pl,{names:t.headerNames})}),O&&t.commandFields.length>0&&(0,r.jsx)(s0,{label:T("mcp.detail.shellCommands"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:T("mcp.server.commandFields")}),(0,r.jsx)(po,{fields:t.commandFields})]})}),O&&t.variableReferences.length>0&&(0,r.jsx)(s0,{label:T("mcp.detail.variables"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:T(oL(t))}),(0,r.jsx)("span",{className:"mcp-config-chips",children:oz(t.variableReferences).map(e=>{let{variable:t,field:n}=e,i=oA(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:T("mcp.server.variableIn",{variable:t,field:T(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})}),W&&O&&(0,r.jsx)(u4,{server:t,run:x,block:b,signOutBlock:v,controlsBusy:h,signingOut:p===`sign-out:${_}`,onSignIn:N,onSignOut:I,onPaste:$,onCancel:E}),(t.exposure||z)&&(0,r.jsx)(s0,{label:T("mcp.detail.exposure"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[t.exposure&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-exposure-choice",children:[(0,r.jsx)("select",{className:"mcp-add-input mcp-exposure-select","aria-label":T("mcp.exposure.label",{name:U}),"aria-describedby":[B,l?M:null].filter(Boolean).join(" "),value:t.exposure,disabled:h||void 0!==l,onChange:e=>{let n=e.target.value;n!==t.exposure&&w(t,n)},children:o1.map(e=>(0,r.jsx)("option",{value:e,children:"codemode"===e?T("mcp.exposure.optionDefault",{label:T(o2[e])}):T(o2[e])},e))}),p===`exposure:${_}`&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:T("i18n.saving")})]}),(0,r.jsx)("span",{id:B,className:"mcp-config-line",children:T(o0[t.exposure])}),void 0!==t.toolExposureCount&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:T("mcp.exposure.toolOverrides",{count:t.toolExposureCount})}),D&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:u9(D,T)})]}),z&&(0,r.jsx)(pg,{status:z,serverExposure:t.exposure})]})}),d&&(0,r.jsx)(s0,{label:T("mcp.detail.inProject"),tone:"plain",children:(0,r.jsx)("span",{className:"mcp-config-lines",children:"override"===d.kind?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"mcp-config-line",children:d.applies?T("mcp.inProject.overridden",{keys:d.keys.join(", ")}):T("mcp.inProject.refused")}),(0,r.jsx)("span",{children:(0,r.jsx)(an,{size:"small",onClick:()=>k(d.key),children:T("mcp.inProject.show")})})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:(0,r.jsx)(an,{size:"small",disabled:h||void 0!==c||q,"aria-describedby":[H,c||q?M:null].filter(Boolean).join(" "),onClick:()=>j(t,!t.enabled),children:p===`in-project:${_}`?T("i18n.saving"):T(t.enabled?"mcp.inProject.turnOff":"mcp.inProject.turnOn")})}),(0,r.jsx)("span",{id:H,className:"mcp-config-line is-dim",children:T("mcp.inProject.saved")})]})})}),(0,r.jsx)(s0,{label:T("mcp.detail.file"),tone:"dim",mono:!0,className:"mcp-config-code",children:u5(t.sourcePath)})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[oR(t)&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:T("mcp.server.hiddenCharacters")}),!t.validated&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:T("mcp.server.unchecked")}),t.replacesGlobal&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:T("mcp.server.replacesGlobal")}),t.override&&(0,r.jsx)("p",{className:"mcp-config-line",children:u9(oP(t.override.keys),T)}),t.shadowedByProject&&"replaced"!==A&&(0,r.jsx)("p",{className:"mcp-config-line",children:T("mcp.server.shadowedByProject")}),t.overriddenByProject&&"overridden"!==A&&(0,r.jsx)("p",{className:"mcp-config-line",children:T("mcp.server.overriddenByProject")}),t.masked&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:T("mcp.server.masked")})]})]})}function pc(e){let{error:t,stderr:n}=e,{t:i}=(0,eW.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:oI(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(oI).join("\n")})]})]})}function pu(e){let{status:t,showState:n,entryCwd:i}=e;return"session"===t.origin?(0,r.jsx)(pm,{status:t,showState:n}):(0,r.jsx)(ph,{status:t,showState:n,entryCwd:i})}function pp(e){let{view:t}=e,{t:n}=(0,eW.s)();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:`mcp-config-state is-${t.tone}`,children:n(t.key)})," "]})}function ph(e){let{status:t,showState:n,entryCwd:i}=e,{t:s,locale:a}=(0,eW.s)(),o=oG(t.testedAt,a),l=t.serverInfo;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,r.jsx)(pp,{view:t.timedOut?{key:lI.timedOut,tone:"error"}:{key:lI[t.state],tone:oV(t.state)}}),s((t.afterSignIn?lE:l$)[t.timedOut?"timedOut":t.state],{count:t.toolCount,seconds:lT(t.durationMs),time:o})]}),(0,r.jsx)(pc,{error:t.error,stderr:t.stderr}),l&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.serverInfo",{name:oI(l.title??l.name),version:oI(l.version)})}),t.resources&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.resources")}),void 0!==t.cwd&&t.cwd!==i&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.ranIn",{path:u5(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:lT(t.queuedMs)})})]})}function pm(e){let{status:t,showState:n}=e,{t:i,locale:s}=(0,eW.s)(),a=oG(t.updatedAt,s),o=void 0===t.closedAt?void 0:oG(t.closedAt,s);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,r.jsx)(pp,{view:void 0!==t.closedAt?{key:"mcp.session.state.closed",tone:"off"}:{key:oY[t.state],tone:oQ[t.state]}}),i(void 0!==t.closedAt?"mcp.session.summary.closed":oX[t.state],{path:u5(t.cwd),time:a,...void 0===o?{}:{closedTime:o}})]}),void 0!==t.conflict&&(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[i("mcp.session.conflictOwner")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:u5(t.conflict)})]}),(0,r.jsx)(pc,{error:t.error,stderr:t.stderr})]})}function pg(e){let{status:t,serverExposure:n}=e,{t:i}=(0,eW.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:oI(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(o2[e.exposure])})]}),e.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:oI(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 pf(e){let{server:t,test:n,testBlock:s,describedBy:a,onTest:o}=e,{t:l}=(0,eW.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&&eC(document,d.current)},[c]),(0,r.jsx)(an,{ref:d,size:"small",disabled:c||void 0!==s,"aria-busy":c||void 0,"aria-describedby":s?a:void 0,onClick:()=>o(t),children:l(c?"mcp.test.testing":"mcp.test.button")})}function px(e){let{server:t,state:n,test:i,testBlock:s,testBlockId:a}=e,{t:o}=(0,eW.s)(),l=t.status,d=oK[n],c="invalid"===s&&"invalid"===n?"state":"web-password"===s&&void 0!==t.webPasswordField?"password":void 0;return(0,r.jsx)(s0,{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-${oV(n)}`,children:o(oq(n,l))}),"invalid"===n&&(0,r.jsxs)("span",{id:"state"===c?a:void 0,className:"mcp-config-line is-warning",children:[o("mcp.server.invalid")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:oI(t.invalidError??"")})]}),t.webPasswordField&&(0,r.jsxs)("span",{id:"password"===c?a:void 0,className:"mcp-config-line is-warning",children:[o("mcp.server.webPassword")," ",(0,r.jsx)(po,{fields:[t.webPasswordField]})]}),l?(0,r.jsx)(pu,{status:l,showState:oB(l)!==n,entryCwd:t.cwd}):!s&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.test.never")}),d&&(0,r.jsx)("span",{className:"mcp-config-line",children:o(d)}),i?.queueTimedOut&&(0,r.jsx)("span",{role:"alert",className:"mcp-config-line is-error",children:o("mcp.test.queueTimedOut")}),i?.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[o("mcp.test.requestFailed")," ",function(e,t){if(e.timedOut)return t("mcp.test.requestTimedOut");let n=e.reason?lN[e.reason]:void 0;return n?t(n):u7(e,t)}(i.error,o)]}),s&&!c&&(0,r.jsx)("span",{id:a,className:"mcp-config-line is-dim",children:o(lS[s])}),!s&&t.commandFields.length>0&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.test.serial")})]})})}function pb(e){let{codemode:t,autoEnable:n,save:i,serverBusy:s,onChange:a,onModeChange:o,onInlineBudgetSave:l}=e,{t:d}=(0,eW.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"===o9(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:o7[t.preference],params:{path:t.settingsPath}}}(t);return(0,r.jsxs)(sK,{children:[(0,r.jsx)(sZ,{children:(0,r.jsx)(sV,{children:(0,r.jsx)(sG,{children:d("mcp.codemode.title")})})}),(0,r.jsx)("p",{className:"mcp-config-line",children:d("mcp.codemode.intro")}),(0,r.jsxs)(sQ,{children:[(0,r.jsx)(s0,{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)(s2,{value:u,label:d("mcp.codemode.title"),options:[{value:"automatic",label:d(ln.automatic),disabled:p},{value:"always",label:d(ln.always),disabled:p||void 0!==g}],disabledReason:g?u9(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:oI(t.preferenceError??"")})]}),h.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[d("mcp.codemode.saveFailed")," ",(0,r.jsx)(pv,{error:h.error})]}),x&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:u9(x,d)}),m&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:u9(m,d)})]})}),t.mode?(0,r.jsx)(py,{mode:t.mode,codemode:t,save:i,waiting:p,onChange:o}):void 0!==t.modeError&&(0,r.jsx)(s0,{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:oI(t.modeError)})]})}),t.inlineBudget?(0,r.jsx)(pj,{budget:t.inlineBudget,save:i,waiting:p,onSave:l}):void 0!==t.inlineBudgetError&&(0,r.jsx)(s0,{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:oI(t.inlineBudgetError)})]})}),(0,r.jsx)(s0,{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:oI(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)(s0,{label:d("mcp.codemode.builtin"),tone:"error",children:u9(f,d)})]})]})}function pv(e){let{error:t}=e,{t:n}=(0,eW.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:oI(t.error)})}function py(e){let{mode:t,codemode:n,save:i,waiting:s,onChange:a}=e,{t:o}=(0,eW.s)(),l="mode"===i.target,d=function(e){let t=e.mode;if(!t)return[];let n=[];void 0!==t.invalid&&n.push({key:"mcp.codemode.toolMode.invalid",params:{path:t.settingsPath,value:t.invalid}});let r=t.projectOverride;return r&&n.push({key:lt[r.value],params:{path:r.settingsPath}}),"only"===(r??t).value&&"automatic"===o9(e)&&n.push({key:"mcp.codemode.toolMode.automaticNote"}),n}(n);return(0,r.jsx)(s0,{label:o("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)(s2,{value:t.value,label:o("mcp.codemode.toolMode"),options:[{value:"on",label:o("mcp.codemode.toolMode.on"),disabled:s},{value:"only",label:o("mcp.codemode.toolMode.only"),disabled:s}],onChange:e=>{(e!==t.value||void 0!==t.invalid)&&a(e)},children:l&&i.saving&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:o("i18n.saving")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:o(le[t.value])}),d.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:u9(e,o)},e.key)),l&&i.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[o("mcp.codemode.toolMode.saveFailed")," ",(0,r.jsx)(pv,{error:i.error})]})]})})}function pj(e){let t,n,{budget:s,save:a,waiting:o,onSave:l}=e,{t:d}=(0,eW.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&&eC(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)(s0,{label:d("mcp.codemode.inlineBudget"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsxs)("form",{className:"mcp-codemode-budget",onSubmit:e=>{e.preventDefault(),g.ok&&f&&!o&&l(g.value)},children:[(0,r.jsx)("input",{ref:c,className:"mcp-add-input mcp-codemode-budget-input",inputMode:"numeric","aria-label":d("mcp.codemode.inlineBudget"),"aria-describedby":u,"aria-invalid":!g.ok||void 0,value:h,placeholder:String(s.default),readOnly:o,autoComplete:"off",spellCheck:!1,onChange:e=>m(e.target.value)}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("mcp.codemode.inlineBudget.unit")}),(0,r.jsx)(an,{type:"submit",size:"small",disabled:!f||o,children:d("mcp.codemode.inlineBudget.save")}),b&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:d("i18n.saving")})]}),!g.ok&&(0,r.jsx)("span",{className:"mcp-config-line is-error",children:d("mcp.codemode.inlineBudget.invalidDraft",{max:String(s.max)})}),(0,r.jsx)("span",{id:u,className:"mcp-config-line",children:d("mcp.codemode.inlineBudget.description",{default:String(s.default)})}),y.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:u9(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)(pv,{error:a.error})]})]})})}async function pk(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 pw(e){var t;let n,{embedded:s=!0,onClose:a}=e,{t:o}=(0,eW.s)(),[l,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(""),[m,g]=(0,i.useState)(""),[f,x]=(0,i.useState)(null),[b,v]=(0,i.useState)(null),y=(0,i.useRef)(!1),j=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/channels",{cache:"no-store"}),t=await e.json();if(!e.ok||t.error)return void u(t.error??`HTTP ${e.status}`);d(t),u(null),y.current||g(t.config.defaultCwd??"")}catch(e){u(e instanceof Error?e.message:String(e))}},[]);(0,i.useEffect)(()=>{j();let e=setInterval(()=>void j(),5e3);return()=>clearInterval(e)},[j]);let k=(0,i.useCallback)(async(e,t,n)=>{x(e),v(null);let r=await pk(t);if(x(null),!r.ok)return void v({kind:"error",message:r.error??o("telegram.actionFailed")});let i=n();i&&v(i),await j()},[j,o]),{config:w}=l??{};return(0,r.jsxs)(sA,{embedded:s,title:o("settings.channels"),closeLabel:o("i18n.close"),onClose:()=>a?.(),children:[(0,r.jsxs)(sW,{children:[(0,r.jsx)(sF,{children:(0,r.jsx)(sD,{children:c&&!l?(0,r.jsx)("div",{role:"alert",className:"config-sidebar-message is-error",children:o("channels.loadFailed",{error:c})}):l?(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(sB,{children:o("channels.group")}),(n=l.config.tokenSet?l.config.enabled?l.lastError?{tone:"error",badge:"channels.badge.error"}:{tone:"on",badge:"channels.badge.on"}:{tone:"off",badge:"channels.badge.off"}:{tone:"off",badge:"channels.badge.unconfigured"},(0,r.jsxs)(sU,{active:!0,"aria-label":`Telegram — ${o(n.badge)}`,children:[(0,r.jsx)(as,{..."on"===(t=n.tone)?{active:!0}:"off"===t?{active:!1}:{color:"#ef4444"}}),(0,r.jsx)(sq,{className:"is-grow",children:"Telegram"}),(0,r.jsx)("span",{className:`mcp-sidebar-badge${"error"===n.tone?" is-error":""}`,children:o(n.badge)})]}))]}):(0,r.jsx)("div",{className:"config-sidebar-message",children:o("i18n.loading")})})}),(0,r.jsx)(s7,{children:(0,r.jsx)(sK,{className:"is-fill",children:l&&w?(0,r.jsxs)(r.Fragment,{children:[b&&(0,r.jsx)(s3,{children:b.message}),l.lastError&&(0,r.jsx)(s3,{children:o("telegram.loopError",{error:l.lastError})}),(0,r.jsxs)(sZ,{children:[(0,r.jsx)(sV,{children:(0,r.jsx)(sG,{children:"Telegram"})}),(0,r.jsx)(sJ,{children:(0,r.jsx)(ar,{checked:w.enabled,disabled:!w.tokenSet||null!==f,label:o("telegram.enabledLabel"),onChange:e=>void k("enabled",{action:"set-enabled",enabled:e},()=>null)})})]}),!w.tokenSet&&(0,r.jsx)(s3,{children:o("telegram.setupHint")}),(0,r.jsxs)(sQ,{children:[(0,r.jsx)(s0,{label:o("telegram.botStatus"),children:l.running?o("telegram.connected",{bot:l.botUsername??""}):o("telegram.notConnected")}),(0,r.jsx)(s0,{label:o("telegram.tokenLabel"),children:(0,r.jsx)("input",{type:"password",autoComplete:"off",spellCheck:!1,className:"mcp-add-input",placeholder:w.tokenSet?o("telegram.tokenPlaceholder",{hint:w.tokenHint??""}):"1234567890:AA…","aria-label":o("telegram.tokenLabel"),value:p,onChange:e=>h(e.target.value)})})]}),(0,r.jsxs)(sJ,{children:[(0,r.jsx)(an,{size:"small",disabled:""===p.trim()||null!==f,onClick:()=>void k("token",{action:"set-token",token:p.trim()},()=>(h(""),{kind:"ok",message:o("telegram.tokenSaved")})),children:o("telegram.tokenSave")}),w.tokenSet&&(0,r.jsx)(an,{size:"small",variant:"secondary",disabled:null!==f,onClick:()=>void k("remove-token",{action:"remove-token"},()=>({kind:"info",message:o("telegram.tokenRemoved")})),children:o("telegram.tokenRemove")})]}),(0,r.jsx)(sY,{children:o("telegram.chatsHeading")}),(0,r.jsx)(sV,{children:o("telegram.chatsDescription")}),l.lastUnknownChat&&(0,r.jsx)(s3,{action:(0,r.jsx)(an,{size:"small",disabled:null!==f||w.allowedChats.some(e=>e.id===l.lastUnknownChat?.id),onClick:()=>void k("allow",{action:"allow-chat",chatId:l.lastUnknownChat?.id,title:l.lastUnknownChat?.title},()=>({kind:"ok",message:o("telegram.chatAllowed")})),children:o("telegram.allowChat")}),children:o("telegram.unknownChatPrompt",{title:l.lastUnknownChat.title??o("telegram.unnamedChat"),id:String(l.lastUnknownChat.id)})}),0===w.allowedChats.length?(0,r.jsx)(s9,{children:o("telegram.noChats")}):(0,r.jsx)(r.Fragment,{children:w.allowedChats.map(e=>(0,r.jsx)("div",{className:"channels-chat",children:(0,r.jsxs)(sQ,{children:[(0,r.jsxs)(s0,{label:e.title??o("telegram.unnamedChat"),mono:!0,children:[e.id,(0,r.jsxs)(sJ,{children:[(0,r.jsx)(an,{size:"small",variant:"secondary",disabled:null!==f,onClick:()=>void k(`test-${e.id}`,{action:"test-send",chatId:e.id},()=>({kind:"ok",message:o("telegram.testSent")})),children:o("telegram.testSend")}),(0,r.jsx)(an,{size:"small",variant:"secondary",disabled:null!==f,onClick:()=>void k(`remove-${e.id}`,{action:"remove-chat",chatId:e.id},()=>({kind:"info",message:o("telegram.chatRemoved")})),children:o("telegram.chatRemove")})]})]}),(0,r.jsx)(s0,{label:o("telegram.chatCwdLabel"),children:(0,r.jsx)("input",{type:"text",spellCheck:!1,className:"mcp-add-input",placeholder:o("telegram.defaultCwdPlaceholder"),"aria-label":o("telegram.chatCwdLabel"),defaultValue:e.cwd??"",onBlur:t=>{let n=t.target.value.trim();n!==(e.cwd??"")&&k(`cwd-${e.id}`,{action:"set-chat-cwd",chatId:e.id,cwd:n},()=>({kind:"ok",message:o("telegram.chatCwdSaved")}))}},`${e.id}:${e.cwd??""}`)})]})},e.id))}),(0,r.jsx)(sY,{children:o("telegram.defaultCwdLabel")}),(0,r.jsx)(sQ,{children:(0,r.jsx)(s0,{label:o("telegram.defaultCwdLabel"),children:(0,r.jsx)("input",{type:"text",spellCheck:!1,className:"mcp-add-input",placeholder:o("telegram.defaultCwdPlaceholder"),"aria-label":o("telegram.defaultCwdLabel"),value:m,onChange:e=>{y.current=!0,g(e.target.value)}})})}),(0,r.jsx)(sJ,{children:(0,r.jsx)(an,{size:"small",disabled:null!==f,onClick:()=>void k("cwd",{action:"set-default-cwd",cwd:m.trim()},()=>({kind:"ok",message:o("telegram.defaultCwdSaved")})),children:o("telegram.defaultCwdSave")})})]}):null})})]}),(0,r.jsx)(ae,{status:l?(0,r.jsx)(at,{tone:l.lastError?"warning":void 0,summary:l.running?o("telegram.connected",{bot:l.botUsername??""}):o("telegram.notConnected")}):void 0,children:!s&&a&&(0,r.jsx)(an,{onClick:a,children:o("i18n.close")})})]})}let pS={minutes:6e4,hours:36e5,days:864e5};function pC(e){return String(e).padStart(2,"0")}function pN(e){let t=new Date(e);return`${t.getFullYear()}-${pC(t.getMonth()+1)}-${pC(t.getDate())}T${pC(t.getHours())}:${pC(t.getMinutes())}`}function pI(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)*pS[e.everyUnit];return Number.isFinite(t)&&e.everyValue>0?{kind:"every",everyMs:t}:null}function p$(e){if(!e)return{name:"",kind:"every",cronExpr:"0 9 * * *",cronTz:Intl.DateTimeFormat().resolvedOptions().timeZone,atLocal:pN(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?pN(t.atMs):pN(Date.now()+36e5),everyValue:"every"===t.kind?t.everyMs/pS.hours>=1&&t.everyMs%pS.hours==0?t.everyMs/pS.hours:Math.max(1,Math.round(t.everyMs/pS.minutes)):1,everyUnit:"every"===t.kind&&(t.everyMs%pS.hours!=0||t.everyMs<pS.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 pE(e,t){if(null===e)return t("automations.neverAgain");let n=new Date(e),r=new Date().toDateString()===n.toDateString(),i=`${pC(n.getHours())}:${pC(n.getMinutes())}`;return r?i:`${pC(n.getMonth()+1)}-${pC(n.getDate())} ${i}`}async function pT(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 pM(e){let{embedded:t=!0,onClose:n}=e,{t:s}=(0,eW.s)(),[a,o]=(0,i.useState)(null),[l,d]=(0,i.useState)([]),[c,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(()=>p$(null)),[x,b]=(0,i.useState)(null),[v,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(null),w=(0,i.useRef)("ok"),S=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/automations",{cache:"no-store"}),t=await e.json();if(!e.ok||t.error)return;o(t.automations??[]),d(t.runs??[]),t.telegram&&p(t.telegram)}catch{}},[]);(0,i.useEffect)(()=>{S();let e=setInterval(()=>void S(),5e3);return()=>clearInterval(e)},[S]);let C=(0,i.useMemo)(()=>a?.find(e=>e.id===h)??null,[a,h]),N=(0,i.useCallback)(e=>{m(e),b(null),k(null),f(p$(a?.find(t=>t.id===e)??null))},[a]),I=(0,i.useCallback)(()=>{m("new"),b(null),k(null),f(p$(null))},[]);(0,i.useEffect)(()=>{let e=pI(g);if(!e)return;let t=setTimeout(()=>{pT({action:"preview",schedule:e}).then(e=>{e.ok?b({dueAt:"number"==typeof e.payload?.dueAt?e.payload.dueAt:null,problem:"string"==typeof e.payload?.problem?e.payload.problem:null}):b({dueAt:null,problem:e.error??s("automations.actionFailed")})})},400);return()=>clearTimeout(t)},[g,s]);let $=(0,i.useCallback)(async(e,t,n)=>{y(e),k(null);let r=await pT(t);return(y(null),r.ok)?(null!==n&&(w.current="ok",k(n)),await S(),!0):(w.current="error",k(r.error??s("automations.actionFailed")),!1)},[S,s]),E=()=>n?.(),T=null!==C,M=pI(g),R=""!==g.name.trim()&&""!==g.cwd.trim()&&""!==g.prompt.trim()&&null!==M&&x?.problem==null;return(0,r.jsxs)(sA,{embedded:t,title:s("settings.automations"),closeLabel:s("i18n.close"),onClose:E,children:[(0,r.jsxs)(sW,{children:[(0,r.jsxs)(sF,{children:[(0,r.jsx)(sD,{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)(sB,{children:s("automations.group")}),a.map(e=>(0,r.jsxs)(sU,{active:h===e.id,onClick:()=>N(e.id),children:[(0,r.jsx)(as,{active:e.enabled&&null!==e.nextDueAt}),(0,r.jsx)(sq,{className:"is-grow",children:e.name}),(0,r.jsx)("span",{className:"mcp-sidebar-badge",children:e.enabled?null!==e.nextDueAt?pE(e.nextDueAt,s):"…":s("channels.badge.off")})]},e.id))]})}),(0,r.jsx)(ai,{active:"new"===h,onClick:I,children:s("automations.newAction")})]}),(0,r.jsx)(s7,{children:(0,r.jsxs)(sK,{className:"is-fill",children:[(null===h||"new"===h||T)&&(0,r.jsxs)(r.Fragment,{children:[j&&(0,r.jsx)(s3,{children:j}),null!==h&&"new"!==h&&T&&(0,r.jsxs)(sZ,{children:[(0,r.jsx)(sV,{children:(0,r.jsx)(sG,{children:C.name})}),(0,r.jsxs)(sJ,{children:[(0,r.jsx)(ar,{checked:C.enabled,disabled:null!==v,label:s("automations.enabledLabel"),onChange:e=>void $(`enabled-${C.id}`,{action:"set-enabled",id:C.id,enabled:e},null)}),(0,r.jsx)(an,{size:"small",variant:"secondary",disabled:null!==v,onClick:()=>void $(`run-${C.id}`,{action:"run-now",id:C.id},s("automations.runStarted")),children:s("automations.runNow")}),(0,r.jsx)(an,{size:"small",variant:"danger",disabled:null!==v,onClick:()=>{$(`delete-${C.id}`,{action:"delete",id:C.id},s("automations.deleted")).then(e=>{e&&N(null)})},children:s("automations.delete")})]})]}),(0,r.jsxs)(sQ,{children:[(0,r.jsx)(s0,{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)(s0,{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)(s0,{label:s("automations.nextRun"),children:null===x?"…":null!==x.problem?`⚠️ ${x.problem}`:`${pE(x.dueAt,s)}`}),(0,r.jsx)(s0,{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)(s0,{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)(ar,{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)(sX,{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)(s3,{children:s("automations.disclosure")}),(0,r.jsx)(sJ,{children:(0,r.jsx)(an,{disabled:!R||null!==v,onClick:()=>{$("save",{action:T?"update":"create",...T?{id:C.id}:{},name:g.name.trim(),schedule:pI(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)(sY,{children:s("automations.historyTitle")}),0===l.length?(0,r.jsx)(s9,{children:s("automations.noRuns")}):(0,r.jsx)(sQ,{children:l.slice(0,12).map(e=>{let t=a?.find(t=>t.id===e.automationId),n=null!==e.finishedAt?Math.max(1,Math.round((e.finishedAt-e.startedAt)/1e3)):null;return(0,r.jsxs)(s0,{label:t?.name??s("automations.deletedAutomation"),mono:!0,children:[(0,r.jsx)(as,{..."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)(an,{size:"small",variant:"secondary",onClick:()=>window.open(u(e.sessionId),"_blank"),children:s("automations.openSession")})]},e.id)})})]})})]}),(0,r.jsx)(ae,{status:null!==a?(0,r.jsx)(at,{summary:s("automations.footerCount",{count:a.length})}):void 0,children:!t&&E&&(0,r.jsx)(an,{onClick:E,children:s("i18n.close")})})]})}let pR=[7,30,90,"all"];function pA(e){let{daily:t,formatCount:n,title:i}=e;if(0===t.length)return null;let s=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.map(e=>e.total),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.total/i*(n-2*r)}))}(t,720,150),a=s.map(e=>`${e.x.toFixed(1)},${e.y.toFixed(1)}`).join(" "),o=`8,148 ${a} 718,148`,l=Math.max(...t.map(e=>e.total),1),d=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),c=t.length<=400?t.map((e,i)=>(0,r.jsx)("rect",{x:s[i].x-720/t.length/2,y:0,width:720/t.length+1,height:150,fill:"transparent",children:(0,r.jsx)("title",{children:`${e.date} \xb7 ${n(e.total)} \xb7 ${e.messages}`})},e.date)):null;return(0,r.jsxs)("svg",{viewBox:"0 0 720 150",className:"usage-trend-chart",role:"img","aria-label":i,preserveAspectRatio:"none",children:[(0,r.jsx)("polygon",{points:o,className:"usage-trend-area"}),(0,r.jsx)("polyline",{points:a,className:"usage-trend-line",fill:"none"}),(0,r.jsx)("text",{x:4,y:12,className:"usage-trend-max",children:n(l)}),d.map(e=>(0,r.jsx)("text",{x:s[e].x,y:148,textAnchor:0===e?"start":e===t.length-1?"end":"middle",className:"usage-trend-label",children:t[e].date.slice(5)},e)),c]})}function pL(e){let{daily:t,formatCount:n}=e;if(0===t.length)return null;let i=new Map(t.map(e=>[e.date,e])),s=t[0].date,a=t[t.length-1].date,o=Math.max(...t.map(e=>e.total),1),l=s;for(let e=0;e<function(e){let[t,n,r]=e.split("-").map(Number);return(new Date(t,n-1,r).getDay()+6)%7}(s);e++)l=function(e){let[t,n,r]=e.split("-").map(Number),i=new Date(t,n-1,r-1),s=e=>e<10?`0${e}`:String(e);return`${i.getFullYear()}-${s(i.getMonth()+1)}-${s(i.getDate())}`}(l);let d=[],c=0;for(;l<=a;)l>=s&&d.push({date:l,day:i.get(l),offset:c}),l=function(e){let[t,n,r]=e.split("-").map(Number),i=new Date(t,n-1,r+1),s=e=>e<10?`0${e}`:String(e);return`${i.getFullYear()}-${s(i.getMonth()+1)}-${s(i.getDate())}`}(l),c+=1;return(0,r.jsx)("div",{className:"usage-heatmap",role:"img","aria-hidden":"true",children:d.map(e=>(0,r.jsx)("span",{className:"usage-heat-cell","data-level":e.day?function(e,t){if(e<=0||t<=0)return 0;let n=e/t;return n<=.25?1:n<=.5?2:n<=.75?3:4}(e.day.total,o):0,title:e.day?`${e.date} \xb7 ${n(e.day.total)}`:e.date},e.date))})}function pP(e){let{items:t,formatValue:n}=e;if(0===t.length)return null;let i=Math.max(...t.map(e=>e.value),1);return(0,r.jsx)("ul",{className:"usage-bar-list",children:t.map(e=>{var t;return(0,r.jsxs)("li",{className:"usage-bar-row",children:[(0,r.jsx)("span",{className:"usage-bar-label",title:e.label,children:e.label}),(0,r.jsx)("span",{className:"usage-bar-track","aria-hidden":"true",children:(0,r.jsx)("span",{className:"usage-bar-fill",style:{width:`${(t=e.value,t<=0||i<=0?0:Math.max(2,Math.round(t/i*100)))}%`}})}),(0,r.jsxs)("span",{className:"usage-bar-value",children:[n(e.value),e.hint?` \xb7 ${e.hint}`:""]})]},e.key)})})}function pz(e){return null===e?"—":`${Math.round(100*e)}%`}function pO(){let{t:e}=(0,eW.s)(),[t,n]=(0,i.useState)("all"),[s,a]=(0,i.useState)(null),[o,l]=(0,i.useState)(!1),[d,c]=(0,i.useState)(!0),[u,p]=(0,i.useState)(!1),h=(0,i.useRef)(0),m=(0,i.useCallback)(async(e,t)=>{let n=++h.current;t&&p(!0),l(!1);try{let r=new URLSearchParams({range:String(e),...t?{force:"1"}:{}}),i=await fetch(`/api/usage?${r.toString()}`,{cache:"no-store"});if(!i.ok)throw Error(String(i.status));let s=await i.json();if(h.current!==n)return;a(s),c(!1)}catch{if(h.current!==n)return;l(!0),c(!1)}finally{h.current===n&&p(!1)}},[]);(0,i.useEffect)(()=>{m(t,!1)},[t,m]);let g=null!==s&&0===s.overview.messages&&s.daily.every(e=>0===e.total),f=7!==t&&null!==s&&s.daily.length>7;return(0,r.jsxs)("div",{className:"settings-usage",children:[(0,r.jsxs)("div",{className:"usage-header",children:[(0,r.jsx)(sY,{children:e("settings.usage.sectionTitle")}),(0,r.jsxs)("div",{className:"usage-controls",children:[(0,r.jsx)("div",{className:"usage-range-group",role:"group","aria-label":e("settings.usage.rangeLabel"),children:pR.map(i=>(0,r.jsx)(an,{variant:"ghost","aria-pressed":t===i,onClick:()=>n(i),children:"all"===i?e("settings.usage.rangeAll"):e(`settings.usage.range${i}`)},String(i)))}),(0,r.jsx)(an,{variant:"ghost",onClick:()=>void m(t,!0),disabled:u,children:e("settings.usage.refresh")})]})]}),(0,r.jsx)("p",{className:"settings-general-description",children:e("settings.usage.sectionDescription")}),d&&(0,r.jsx)("div",{className:"usage-loading",children:e("i18n.loading")}),!d&&o&&(0,r.jsx)(s3,{action:(0,r.jsx)(an,{variant:"ghost",onClick:()=>void m(t,!0),children:e("settings.usage.retry")}),children:e("settings.usage.error")}),!d&&!o&&g&&(0,r.jsxs)(s9,{children:[(0,r.jsx)("strong",{children:e("settings.usage.empty")}),e("settings.usage.emptyHint")]}),!d&&!o&&null!==s&&!g&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsxs)("div",{className:"usage-cards",children:[(0,r.jsxs)("div",{className:"usage-card",children:[(0,r.jsx)("span",{className:"usage-card-label",children:e("settings.usage.totalTokens")}),(0,r.jsx)("strong",{className:"usage-card-value",children:il(s.overview.tokens.total)}),(0,r.jsx)("span",{className:"usage-card-detail",children:`${e("settings.usage.input")} ${il(s.overview.tokens.input)} \xb7 ${e("settings.usage.output")} ${il(s.overview.tokens.output)} \xb7 ${e("settings.usage.cacheRead")} ${il(s.overview.tokens.cacheRead)} \xb7 ${e("settings.usage.cacheWrite")} ${il(s.overview.tokens.cacheWrite)}`})]}),(0,r.jsxs)("div",{className:"usage-card",children:[(0,r.jsx)("span",{className:"usage-card-label",children:e("settings.usage.cost")}),(0,r.jsx)("strong",{className:"usage-card-value",children:id(s.overview.cost)??"$0"})]}),(0,r.jsxs)("div",{className:"usage-card",children:[(0,r.jsx)("span",{className:"usage-card-label",children:e("settings.usage.sessions")}),(0,r.jsx)("strong",{className:"usage-card-value",children:il(s.overview.sessions)}),(0,r.jsx)("span",{className:"usage-card-detail",children:`${il(s.overview.messages)} ${e("settings.usage.messages").toLowerCase()}`})]}),(0,r.jsxs)("div",{className:"usage-card",children:[(0,r.jsx)("span",{className:"usage-card-label",children:e("settings.usage.activeDays")}),(0,r.jsx)("strong",{className:"usage-card-value",children:s.overview.activeDays})]}),(0,r.jsxs)("div",{className:"usage-card",children:[(0,r.jsx)("span",{className:"usage-card-label",children:e("settings.usage.activeTime")}),(0,r.jsx)("strong",{className:"usage-card-value",children:ic(s.overview.totalActiveMs)})]}),(0,r.jsxs)("div",{className:"usage-card",children:[(0,r.jsx)("span",{className:"usage-card-label",children:e("settings.usage.topModel")}),(0,r.jsx)("strong",{className:"usage-card-value usage-card-model",title:s.overview.topModel?.model??void 0,children:s.overview.topModel?s.overview.topModel.model:"—"}),s.overview.topModel&&(0,r.jsx)("span",{className:"usage-card-detail",children:`${e("settings.usage.favoriteModelShare")} ${pz(s.overview.topModel.share)}`})]})]}),(0,r.jsxs)("div",{className:"usage-metrics",children:[(0,r.jsx)("span",{children:`${e("settings.usage.currentStreak")} ${s.activity.currentStreakDays} ${e("settings.usage.daysUnit")}`}),(0,r.jsx)("span",{children:`${e("settings.usage.longestStreak")} ${s.activity.longestStreakDays} ${e("settings.usage.daysUnit")}`}),(0,r.jsx)("span",{children:`${e("settings.usage.cacheHitRate")} ${pz(s.activity.cacheHitRate)}`}),null!==s.activity.peakHour&&(0,r.jsx)("span",{children:`${e("settings.usage.peakHour")} ${s.activity.peakHour}:00–${s.activity.peakHour}:59`})]})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)(sY,{children:e("settings.usage.dailyTrend")}),(0,r.jsx)(pA,{daily:s.daily,formatCount:il,title:e("settings.usage.dailyTrend")}),f&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(sY,{children:e("settings.usage.heatmap")}),(0,r.jsx)(pL,{daily:s.daily,formatCount:il})]})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)(sY,{children:e("settings.usage.models")}),(0,r.jsx)(pP,{items:s.models.map(t=>({key:t.model,label:"unknown"===t.model?e("settings.usage.unknownModel"):t.model,value:t.total,hint:id(t.cost)??void 0})),formatValue:il})]}),s.tools.length>0&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)(sY,{children:e("settings.usage.tools")}),(0,r.jsx)(pP,{items:s.tools.map(e=>({key:e.name,label:e.name,value:e.count})),formatValue:t=>`${il(t)} ${e("settings.usage.timesUnit")}`})]}),s.projects.length>0&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)(sY,{children:e("settings.usage.projects")}),(0,r.jsx)(pP,{items:s.projects.map(t=>({key:t.cwd,label:ed(t.cwd),value:t.total,hint:`${t.sessions} ${e("settings.usage.sessions").toLowerCase()}`})),formatValue:il})]}),(0,r.jsx)("p",{className:"usage-footnote",children:e("settings.usage.subagentsIncluded")})]})]})}var pW=n(75702);let pF=[{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 pD(){let{t:e}=(0,eW.s)(),t=(0,n4.VE)();return(0,r.jsx)("div",{className:"settings-font-rows",children:pF.map(n=>{let{kind:i,label:s,placeholder:a,reset:o,weightLabel:l}=n,d=t[`${i}Weight`],c=pW.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:pW.zx,"aria-describedby":"settings-typography-description",autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,onChange:e=>t.setFontPreference(i,e.target.value)}),(0,r.jsx)("output",{htmlFor:`settings-font-${i}-weight`,title:`${e(l)}: ${d}`,children:e(pW.qI[c].label)}),(0,r.jsx)(an,{variant:"ghost",size:"small",className:"settings-chat-reset",title:e(o),"aria-label":e(o),disabled:!t[i]&&d===pW.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:pW.qI[0].value,max:pW.qI[pW.qI.length-1].value,step:100,value:d,"aria-label":e(l),"aria-valuetext":`${d} ${e(pW.qI[c].label)}`,onChange:e=>t.setFontWeight(i,Number(e.target.value))})]},i)})})}function pB(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"})]}):"usage"===t?(0,r.jsx)("svg",{...s,children:(0,r.jsx)("path",{d:"M5 20V10M12 20V4M19 20v-7"})}):(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 pH(e){let{sessionId:t,onSessionReloaded:n,quoteSelectionEnabled:s,onQuoteSelectionChange:a}=e,{locale:o,setLocale:l,supportedLocales:d,t:c}=(0,eW.s)(),{preference:u,setThemePreference:p}=(0,i5.D)(),{width:h,setWidth:m,fontSize:g,setFontSize:f}=(0,n2.Uh)(),x=n1(),b=eO(),[v,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(!1),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(!1),[I,$]=(0,i.useState)(null),[E,T]=(0,i.useState)(!1),[M,R]=(0,i.useState)(null),[A,L]=(0,i.useState)(!1),[P,z]=(0,i.useState)(null),[O,W]=(0,i.useState)(!1),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)("");(0,i.useEffect)(()=>{N((0,sd.ql)()),fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>W(e?.enabled===!0)).catch(()=>{})},[]);let _=async()=>{D(!0),H("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.replace("/login")}catch{H(c("auth.logoutFailed"))}finally{D(!1)}};(0,i.useEffect)(()=>{let e=!1;return fetch("/api/tools/settings").then(async t=>{let n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);e||y(n)}).catch(t=>{e||S(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/cache-miss-notices").then(async t=>{let n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);e||$(!0===n.enabled)}).catch(t=>{e||R(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]);let U=async e=>{T(!0),R(null);try{let r=await fetch("/api/cache-miss-notices",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);$(!0===i.enabled),t&&n()}catch(e){R(e instanceof Error?e.message:String(e))}finally{T(!1)}},q=async e=>{k(!0),S(null);try{let r=await fetch("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);y(i),t&&(await r2(t,{type:"reload"}),n())}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(!1)}},K=async()=>{if(!A){L(!0),z(null);try{if(!("Notification"in window))throw Error("unsupported or not permitted");let e="default"===Notification.permission?await Notification.requestPermission():Notification.permission;if("granted"!==e||!await aY(o))throw Error("unsupported or not permitted");z({kind:"ok",message:c("settings.pushRegistered")})}catch(e){z({kind:"error",message:`${c("settings.pushRegisterFailed")} ${e instanceof Error?e.message:String(e)}`})}finally{L(!1)}}};return(0,r.jsxs)("div",{className:"settings-general",children:[(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.appearance")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":c("settings.appearance"),className:"settings-theme-options",children:i9.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)(pD,{}),(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)(an,{variant:"ghost",size:"small",className:"settings-chat-reset",title:c("settings.resetChatContentFontSize"),"aria-label":c("settings.resetChatContentFontSize"),disabled:g===n2.NN,onClick:()=>f(n2.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:n2.WH,max:n2.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)(an,{variant:"ghost",size:"small",className:"settings-chat-reset",title:c("settings.resetChatContentWidth"),"aria-label":c("settings.resetChatContentWidth"),disabled:h===n2.mi,onClick:()=>m(n2.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:n2.lg,max:n2.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)(ar,{checked:C,label:c("settings.thinkingExpandedDefault"),onChange:e=>{(0,sd.kF)(e),N(e)}})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:c("settings.quoteSelection")}),(0,r.jsx)(ar,{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:()=>n0("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:()=>n0("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)(ar,{checked:!0===I,loading:null===I&&!M||E,label:c("settings.cacheMissNotices"),describedBy:"settings-cache-miss-notices-description",onChange:e=>void U(e)})]})]}),(0,r.jsx)("p",{id:"settings-cache-miss-notices-description",className:"settings-general-description",children:c("settings.cacheMissNoticesDescription")}),M&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:M})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children: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:()=>ez("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:()=>ez("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?.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)(ar,{checked:v.powerShellEnabled,loading:j,label:c("settings.usePowerShell"),onChange:e=>void q(e)})]}),w&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:w})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.pushPermission")}),(0,r.jsx)("p",{className:"settings-general-description",children:c("settings.pushPermissionDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:c("settings.pushPermission")}),(0,r.jsx)("button",{type:"button",className:"config-button config-button-small config-button-secondary",disabled:A,onClick:()=>void K(),children:A?c("settings.pushRegisterLoading"):c("settings.pushRegister")})]}),P&&(0,r.jsx)("p",{role:"status",className:"settings-general-error",style:"ok"===P.kind?{color:"var(--accent)"}:void 0,children:P.message})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("common.language")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":c("common.language"),className:"settings-language-options",children:d.map(e=>{let t=o===e.id;return(0,r.jsxs)("button",{type:"button",role:"radio","aria-checked":t,onClick:()=>l(e.id),className:"settings-language-option",children:[(0,r.jsx)("span",{className:"settings-language-radio",children:t&&(0,r.jsx)("span",{className:"settings-language-radio-dot"})}),(0,r.jsx)("span",{className:"settings-language-label",children:e.label}),(0,r.jsx)("span",{className:"settings-language-code",children:e.id})]},e.id)})})]}),O&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsxs)(an,{variant:"secondary",disabled:F,onClick:()=>void _(),children:[(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M10 17l5-5-5-5M15 12H3M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"})}),F?c("auth.loggingOut"):c("auth.logOut")]}),B&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:B})]})]})}let p_={home:"home",section:"home",detail:"section"},pU={home:0,section:1,detail:2},pq="cubic-bezier(0.2, 0.8, 0.2, 1)";function pK(e){let t,{cwd:n,sessionId:s,initialSection:a,openAtHome:o=!1,onClose:l,onSessionReloaded:d,quoteSelectionEnabled:c,onQuoteSelectionChange:u,projectTrust:p,onOpenTrustDialog:h,onProjectTrustChanged:m}=e,{t:g}=(0,eW.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:"usage",label:g("settings.usage")}].map(e=>({...e,requiresProject:sn(e.id)})),j=sn(f),k=(0,eF.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=>p_[e]))};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[e]);let o=(0,i.useCallback)(t=>{e&&(window.history.pushState(window.history.state,""),a.current+=1,r(t))},[e]);return{level:n,levelRef:s,enter:o,goUp:(0,i.useCallback)(()=>{a.current>0?window.history.back():r(e=>p_[e])},[]),dropHistory:(0,i.useCallback)(()=>{let e=a.current;a.current=0,e>0&&window.history.go(-e)},[])}}(k,o),{dropHistory:S,enter:C,goUp:N,levelRef:I}=w,$=(0,i.useRef)(null),E=(0,i.useRef)(null),T=(0,i.useRef)(w.level);(0,i.useLayoutEffect)(()=>{let e=T.current;T.current=w.level,k&&e!==w.level&&function(e,t,n,r){if(!e||"function"!=typeof e.animate||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;let i=pU[r]>pU[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:pq}),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:pq})})}(E.current,$.current,e,w.level)},[k,w.level]);let M=(0,i.useCallback)(()=>{S(),l()},[l,S]),R=y.find(e=>e.id===f)?.label??g("settings.title"),[A,L]=(0,i.useState)(null),P=(0,i.useMemo)(()=>({detailOpen:"detail"===w.level,openDetail:()=>{"section"===I.current&&(L(null),C("detail"))},closeDetail:()=>{"detail"===I.current&&N()},reportDetailTitle:L}),[C,N,w.level,I]);(0,i.useEffect)(()=>sa(a),[a]),(0,i.useEffect)(()=>{var e;let t;return e=document,t=e=>{"Escape"!==e.key||e.defaultPrevented||eS(e)||(e.preventDefault(),M())},e.addEventListener("keydown",t,!1),()=>e.removeEventListener("keydown",t,!1)},[M]);let z=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>(function(e,t){let{restoreTextEntry:n=!0}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=e.activeElement,i=!!(r&&t&&t.contains(r)),s=r&&r!==e.body&&!i?r:null;return t&&!i&&t.focus({preventScroll:!0}),()=>{if(!s||!s.isConnected||!n&&function(e){if(e.isContentEditable)return!0;let t=e.tagName?.toUpperCase();return"TEXTAREA"===t||"INPUT"===t&&!["button","checkbox","color","file","hidden","image","radio","range","reset","submit"].includes((e.type??"text").toLowerCase())}(s))return;let r=e.activeElement;r&&r!==e.body&&!(t&&t.contains(r))||"function"==typeof s.focus&&s.focus({preventScroll:!0})}})(document,z.current,{restoreTextEntry:!window.matchMedia?.("(pointer: coarse)").matches}),[]),(0,i.useEffect)(()=>{!n&&j&&(x("general"),v(e=>new Set(e).add("general")),sa("general"))},[n,j]);let O=e=>{v(t=>new Set(t).add(e)),x(e),sa(e)},W=(e,t)=>b.has(e)?(0,r.jsx)("div",{hidden:f!==e||"home"===w.level,"data-phone-level":k?w.level:void 0,className:"settings-section-host",children:t},e):null;return(0,r.jsx)("div",{ref:z,role:"dialog","aria-modal":"true","aria-label":g("settings.title"),tabIndex:-1,onClick:e=>{e.target===e.currentTarget&&M()},className:"settings-dialog-backdrop",children:(0,r.jsxs)("div",{className:"settings-dialog-surface",children:[(0,r.jsxs)("div",{ref:$,className:"settings-dialog-header",children:[k&&"home"!==w.level&&(t="detail"===w.level?R:g("settings.title"),(0,r.jsxs)("button",{type:"button",className:"settings-phone-back",onClick:N,"aria-label":g("settings.backTo",{name:t}),children:[(0,r.jsx)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m15 18-6-6 6-6"})}),(0,r.jsx)("span",{children:t})]})),(0,r.jsx)("strong",{className:"settings-dialog-title",children:k&&"home"!==w.level?"section"===w.level?R:A:g("settings.title")}),(0,r.jsx)("nav",{"aria-label":g("settings.title"),className:"settings-section-tabs",children:y.map(e=>{let t=f===e.id,i=e.requiresProject&&!n;return(0,r.jsxs)("button",{type:"button",className:"settings-section-tab",disabled:i,title:i?g("settings.projectRequired"):e.label,"aria-current":t?"page":void 0,onClick:()=>O(e.id),children:[(0,r.jsx)(pB,{section:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id)})}),(0,r.jsx)("button",{type:"button",onClick:M,title:g("i18n.close"),"aria-label":g("i18n.close"),className:"config-close-button settings-dialog-close",children:"\xd7"})]}),(0,r.jsxs)("main",{ref:E,className:"settings-dialog-main",children:[k&&"home"===w.level&&(0,r.jsx)("nav",{"aria-label":g("settings.title"),className:"settings-phone-home",children:y.map(e=>{let t=e.requiresProject&&!n;return(0,r.jsxs)("button",{type:"button",className:"settings-phone-home-item",disabled:t,"aria-describedby":t?`settings-phone-home-${e.id}-note`:void 0,onClick:()=>{O(e.id),C("section")},children:[(0,r.jsx)(pB,{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)(sL.Provider,{value:P,children:[W("general",(0,r.jsx)(pH,{sessionId:s,onSessionReloaded:d,quoteSelectionEnabled:c,onQuoteSelectionChange:u})),W("models",(0,r.jsx)(aJ,{embedded:!0,cwd:n,onClose:M})),n&&W("skills",(0,r.jsx)(a5,{embedded:!0,cwd:n,trust:p,onClose:M},n)),n&&W("agents",(0,r.jsx)(oc,{embedded:!0,cwd:n,sessionId:s,trust:p,onClose:M,onReloaded:d},n)),n&&W("plugins",(0,r.jsx)(ow,{embedded:!0,cwd:n,sessionId:s,trust:p,onClose:M,onReloaded:d},n)),W("mcp",(0,r.jsx)(pn,{embedded:!0,cwd:n,trust:p,onTrustProject:h,onProjectTrustChanged:m,onClose:M},n??"")),W("channels",(0,r.jsx)(pw,{})),W("automations",(0,r.jsx)(pM,{})),W("usage",(0,r.jsx)(pO,{}))]})]})]})})}let pZ="project-trust-mcp-status";function pV(e){let{cwd:t,busy:n,error:s,onCancel:a,onConfirm:o,onStatus:l}=e,[d,c]=(0,i.useState)({state:"loading"}),u=(0,i.useRef)(l);return(0,i.useEffect)(()=>{u.current=l},[l]),(0,i.useEffect)(()=>{let e=!0,n=!1;c({state:"loading"});let r=new AbortController,i=window.setTimeout(()=>{n=!0,r.abort()},1e4);return fetch(`/api/project-trust?cwd=${encodeURIComponent(t)}`,{signal:r.signal,cache:"no-store"}).then(async t=>{let n=await t.json();if(!e)return;let r=function(e,t,n){let r=Array.isArray(n.mcpServers)?{mcpServers:n.mcpServers,...n.mcpFile?{mcpFile:n.mcpFile}:{},...void 0!==n.mcpError?{mcpError:n.mcpError}:{}}:void 0;if(e&&!n.error&&r&&"boolean"==typeof n.requiresTrust){let e;return{state:"loaded",listing:r,status:(e={requiresTrust:n.requiresTrust,trusted:n.trusted,decision:n.decision,inherited:n.inherited},void 0!==n.decisionPath&&(e.decisionPath=n.decisionPath),void 0!==n.decisionError&&(e.decisionError=n.decisionError),e)}}return"trust-unreadable"===n.reason&&r?{state:"loaded",listing:r,statusError:n.error??`HTTP ${t}`}:{state:"failed",error:n.error??`HTTP ${t}`,reason:n.reason}}(t.ok,t.status,n);c(r),"loaded"===r.state&&r.status&&u.current?.(r.status)}).catch(t=>{e&&c(n?{state:"failed",timedOut:!0}:{state:"failed",error:t instanceof Error?t.message:String(t)})}).finally(()=>window.clearTimeout(i)),()=>{e=!1,window.clearTimeout(i),r.abort()}},[t]),(0,r.jsx)(pJ,{cwd:t,busy:n,error:s,listing:d,onCancel:a,onConfirm:o})}function pJ(e){let{cwd:t,busy:n,error:s,listing:a,onCancel:o,onConfirm:l}=e,{t:d}=(0,eW.s)(),c="loading"===a.state,u="loaded"===a.state?function(e){if(e){if(!e.requiresTrust)return"mcp.reason.trust-not-required";if(e.trusted)return"trust.alreadyTrusted"}}(a.status):void 0,p=(0,i.useRef)(null),h=(0,i.useRef)(n),m=(0,i.useRef)(o);return(0,i.useEffect)(()=>{h.current=n,m.current=o},[n,o]),(0,i.useEffect)(()=>{var e,t,n;let r,i,s;return e=document,t=p.current,n=()=>{h.current||m.current()},r=e.activeElement,t?.focus({preventScroll:!0}),i=e=>{"Escape"!==e.key||(e.stopPropagation(),eS(e)||(e.preventDefault(),n()))},e.addEventListener("keydown",i,!0),s=()=>e.removeEventListener("keydown",i,!0),()=>{s(),r&&r.isConnected&&"function"==typeof r.focus&&r.focus({preventScroll:!0})}},[]),(0,r.jsx)("div",{role:"presentation",className:"project-trust-backdrop",onClick:e=>{n||e.target!==e.currentTarget||o()},children:(0,r.jsxs)("div",{ref:p,role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title","aria-describedby":"project-trust-description",tabIndex:-1,className:"project-trust-dialog",children:[(0,r.jsxs)("div",{className:"project-trust-body",children:[(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"project-trust-icon",children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,r.jsxs)("div",{className:"project-trust-content",children:[(0,r.jsx)("div",{id:"project-trust-title",className:"project-trust-title",children:d("trust.dialogTitle")}),(0,r.jsx)("div",{id:"project-trust-description",className:"project-trust-text",children:d("trust.dialogBody")}),(0,r.jsx)("code",{className:"project-trust-path",children:oI(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:oI(a.statusError)})]}),(0,r.jsx)(pY,{listing:a})]})]}),s&&(0,r.jsx)(pG,{error:s}),(0,r.jsxs)("div",{className:"project-trust-footer",children:[(0,r.jsx)("button",{type:"button",className:"project-trust-button",onClick:o,disabled:n,children:d(u?"trust.close":"trust.cancel")}),!u&&(0,r.jsx)("button",{type:"button",className:"project-trust-button is-primary",onClick:l,disabled:n||c,"aria-busy":n||void 0,"aria-describedby":c?pZ:void 0,children:d(n?"trust.trusting":"trust.trustProject")})]})]})})}function pG(e){let{error:t}=e,{t:n}=(0,eW.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:oI(t.error)})]})}function pY(e){let{listing:t}=e,{t:n}=(0,eW.s)();if("loading"===t.state)return(0,r.jsx)("p",{id:pZ,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:oI(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)(pX,{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)(p1,{server:e},e.name))})]}):null}function pX(e){let{file:t}=e,{t:n}=(0,eW.s)();return(0,r.jsx)(r.Fragment,{children:t.problems.map(e=>{let i=oO(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 pQ(e){let{fields:t}=e,{t:n}=(0,eW.s)();return(0,r.jsx)(r.Fragment,{children:t.map(e=>{let t=oA(e);return(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function p0(e){let{server:t}=e,{t:n}=(0,eW.s)();return(0,r.jsx)(r.Fragment,{children:oz(t.variableReferences).map(e=>{let{variable:t,field:i}=e,s=oA(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 p1(e){let t,{server:n}=e,{t:i}=(0,eW.s)(),s=oM(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:oI(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:oI(n.cwd)})}),oR(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:oI(n.invalidError)})]}),n.webPasswordField&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.webPassword")," ",(0,r.jsx)(pQ,{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)(pQ,{fields:n.commandFields})]}),a&&n.variableReferences.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i(oL(n))," ",(0,r.jsx)(p0,{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=oP(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 p2(e){return"message"===e.type&&"message"in e&&"system"!==e.message.role}function p4(e){let t=e,n=t.branchPreview,r=p2(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&p2(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function p8(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 p6(e){let{node:t,activePathIds:n,depth:i,isLast:s,parentLines:a,onSelect:o}=e,{node:l,skipped:d,branchPreview:c,labelEntry:u}=p4(t),p=n.has(l.entry.id),h=n.has(t.entry.id)||n.has(l.entry.id),m=c?.text??function(e){if("message"===e.type&&p2(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:p2(u)?u.message.role:null;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:o?"pointer":"default"},onClick:o?()=>o(l.entry.id):void 0,children:[a.map((e,t)=>(0,r.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,r.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:s?"50%":0,width:1,background:"var(--border)"}}),(0,r.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,r.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:p?"var(--accent)":h?"var(--text-muted)":"var(--border)",border:p?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),g&&(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===g?"var(--accent)":"var(--text-dim)",background:"user"===g?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===g?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===g?"U":"A"}),d>0&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",d]}),(0,r.jsx)("span",{style:{fontSize:11,color:p?"var(--text)":h?"var(--text-muted)":"var(--text-dim)",fontWeight:p?500:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:m})]}),l.children.map((e,t)=>(0,r.jsx)(p6,{node:e,activePathIds:n,depth:i+1,isLast:t===l.children.length-1,parentLines:[...a,!s],onSelect:o},e.entry.id))]})}function p3(e){let{tree:t,activeLeafId:n,onLeafChange:s,inline:a,containerRef:o,open:l,onToggle:d,hasSession:c,compact:u,hideInlineButton:p,locked:h=!1}=e,{t:m}=(0,eW.s)(),[g,f]=(0,i.useState)(!1),x=void 0!==l?l:g,b=(0,i.useRef)(null),[v,y]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!x||!a)return;let e=o?.current??b.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();y({top:t.bottom,left:t.left,width:t.width})};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[x,a,o]);let j=(0,i.useMemo)(()=>(function(e,t){if(!t)return new Set;let n=e.map(e=>({node:e,path:[e.entry.id]}));for(;n.length>0;){let{node:e,path:r}=n.pop();if(e.entry.id===t||e.compressedEntryIds?.includes(t))return new Set(r);for(let t of e.children)n.push({node:t,path:[...r,t.entry.id]})}return new Set})(t,n),[t,n]),k=(0,i.useCallback)(e=>{s(e)},[s]),w=h?void 0:k,S=h&&(0,r.jsx)("div",{style:{padding:"2px 0 4px",fontSize:11,color:"var(--text-dim)",fontStyle:"italic"},children:m("i18n.branchesLockedWhileRunning")}),C=c?p8(t)?null:m("i18n.noBranches"):m("i18n.noActiveSession"),N=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=p4(e[0]).node;return t.children.length>1?t.children:[]}(t),I=!C&&N.length>0,$=(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:I?"var(--accent)":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),E=(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{marginLeft:2,transform:x?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})});return a?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"stretch"},children:[(0,r.jsxs)("button",{ref:b,onClick:()=>d?d():f(e=>!e),style:{display:p?"none":"flex",alignItems:"center",gap:6,height:"100%",padding:"0 12px",background:x?"var(--bg-selected)":"none",border:"none",borderTop:x?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:"pointer",color:x?"var(--text)":"var(--text-muted)",fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color=x?"var(--text)":"var(--text-muted)"},title:m("i18n.branches"),"aria-label":m("i18n.branches"),"aria-pressed":x,children:[$,!u&&(0,r.jsx)("span",{children:m("i18n.branches")})]}),x&&v&&(0,r.jsx)("div",{style:{position:"fixed",top:v.top,left:v.left,width:v.width,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",zIndex:500},children:I?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(p6,{node:e,activePathIds:j,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:w},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C})})]}):(0,r.jsxs)("div",{style:{borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>f(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"5px 12px",background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",fontSize:11,textAlign:"left"},children:[$,(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:m("i18n.branches")}),E]}),x&&(0,r.jsx)("div",{style:{position:"absolute",top:"100%",left:0,right:0,background:"var(--bg)",borderBottom:"1px solid var(--border)",boxShadow:"0 4px 12px rgba(0,0,0,0.1)",zIndex:100},children:I?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(p6,{node:e,activePathIds:j,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:w},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C??m("i18n.noBranches")})})]})}function p5(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 p9(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e)}catch{return String(e)}}function p7(e){let{children:t}=e;return(0,r.jsx)("div",{className:"tool-definitions-empty",children:t})}function he(e){let{loading:t,tools:n,translate:s}=e,a=(0,i.useMemo)(()=>n?.filter(e=>e.active&&!e.declarationHidden)??null,[n]),[o,l]=(0,i.useState)(null);(0,i.useEffect)(()=>{l(e=>a?.some(t=>t.name===e)?e:a?.[0]?.name??null)},[a]);let d=a?.find(e=>e.name===o)??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 p9(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(p9).join(", "):void 0,defaultValue:void 0===i.default?void 0:p9(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:()=>l(e.name),children:(0,r.jsx)("code",{children:e.name})},e.name)}):a?(0,r.jsx)(p7,{children:s("tools.noTools")}):(0,r.jsx)(p7,{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)(p7,{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
- `})]})}function ht(e){let{usage:t,style:n}=e,{locale:i,t:s}=(0,eW.s)(),a=id(t.cost);return(0,r.jsxs)("span",{title:function(e,t,n){let{tokens:r}=e;return[`${t("session.totalActive")}: ${ic(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"})]}),ic(t.totalActiveMs)]}),t.tokens.total>0&&(0,r.jsx)("span",{children:s("agentSwitcher.tokens",{count:il(t.tokens.total)})}),a&&(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:a})]})}function hn(e){return!!(e&&(e.tokens.total>0||e.totalActiveMs>0))}function hr(e){return e.name||e.firstMessage||e.id.slice(0,12)}function hi(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 hs(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 ha(e){let{session:t,main:n,sideTitle:s,selected:a,running:o,usage:l,onSelect:d,tabShown:c,onToggleTab:u,onNewSideChat:p,newSideChatPending:h,onDelete:m,confirming:g,onDeleteConfirm:f,onDeleteCancel:x}=e,{locale:b,t:v}=(0,eW.s)(),y=t.relation?.kind==="subagent"?t.relation:null,j=t.relation?.kind==="side",k=o?"running":y?.status??"completed",w=n?v("agentSwitcher.main"):j?s??v("agentSwitcher.sideChat"):y?.description||hr(t),S=j?v("agentSwitcher.sideChat"):y?.profile??v("agentSwitcher.subagent"),C=l?.model?.modelId,N=l?.thinkingLevel&&"off"!==l.thinkingLevel?l.thinkingLevel:void 0,I=n?hr(t):j?hi(t.modified,b):S,$=n?I:[S,l?.model?`${l.model.provider}/${l.model.modelId}`:void 0,N,hi(t.modified,b)].filter(Boolean).join(" \xb7 "),E=(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)(tp,{label:v("sidebar.deleteSession",{title:w}),deleteLabel:v("sidebar.delete"),cancelLabel:v("sidebar.cancel"),onConfirm:f,onCancel:x})}):(0,r.jsxs)("div",{ref:E,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:n?(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"8",r:"4"}),(0,r.jsx)("path",{d:"M4 21a8 8 0 0 1 16 0"})]}):j?(0,r.jsx)("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.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]})}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12,fontWeight: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:$,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]})]}),hn(l)&&(0,r.jsx)(ht,{usage:l,style:{marginTop:3}})]}),(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",gap:6,color:(n||j)&&!o?"var(--text-dim)":"running"===k||"starting"===k?"var(--accent)":"completed"===k?"#16a34a":"failed"===k?"#dc2626":"aborted"===k?"#d97706":"var(--text-dim)",fontSize:11,whiteSpace:"nowrap"},children:(n||j)&&!o?a?v("agentSwitcher.current"):null:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(hs,{status:k}),(0,r.jsx)("span",{children:v(`agentSwitcher.status.${k}`)})]})})]}),p&&(0,r.jsx)(ho,{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)(ho,{title:v(a?"agentSwitcher.openInMainChat":c?j?"sideChat.closeTab":"subagent.closeTab":j?"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)(ho,{title:v("sidebar.delete"),danger:!0,onClick:()=>{M(E.current?.offsetHeight),m()},children:(0,r.jsx)(ts.uc,{size:14})})]})}function ho(e){let{title:t,pressed:n,danger:i,disabled:s,onClick:a,children:o}=e,l=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 ${l}`,style:{width:36,display:"grid",placeItems:"center",border:"none",borderLeft:"1px solid var(--border)",flexShrink:0},children:o})}function hl(e){let{rootSession:t,subagents:n,selectedSessionId:s,runningSessionIds:a,onSelectSession:l,openSubagentTabIds:d,onToggleSubagentTab:u,onNewSideChat:p,onDeleteSideChat:h}=e,{t:m}=(0,eW.s)(),[g,f]=(0,i.useState)(""),[x,b]=(0,i.useState)(!1),[v,y]=(0,i.useState)(null),[j,k]=(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;k(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]),$=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($))}):I,T=c(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 o=setInterval(()=>{"visible"===document.visibilityState&&a()},3e3);return()=>{clearInterval(o),n.abort()}},[s,t]),n}(M,R),L=(0,i.useMemo)(()=>{let e=M.map(e=>A[e]).filter(hn);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)",borderLeft:"1px solid var(--border)",borderRight:"1px solid var(--border)",borderBottom:"1px solid var(--border)",borderRadius:"0 0 6px 6px",boxShadow:"0 10px 28px rgba(0,0,0,0.10)",overflow:"hidden"},children:(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{minHeight:44,display:"flex",alignItems:"center",gap:8,padding:"7px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("strong",{style:{fontSize:12,fontWeight:600},children: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)(ht,{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)(ha,{session:t,main:!0,selected:t.id===s,running:a.has(t.id),usage:A[t.id],onSelect:()=>l(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}),E.map(e=>(0,r.jsx)(ha,{session:e,sideTitle:e.relation?.kind==="side"?o(e,m("agentSwitcher.sideChat"),n):void 0,selected:e.id===s,running:a.has(e.id),usage:A[e.id],onSelect:()=>l(e),tabShown:d.has(e.id),onToggleTab:()=>{let t=e.relation?.kind==="subagent"?e.relation:null;e.relation?.kind==="side"?u(e.id,m("sideChat.title"),!0):u(e.id,t?.description||t?.profile||hr(e))},onDelete:e.relation?.kind==="side"?()=>k(e.id):void 0,confirming:j===e.id,onDeleteConfirm:()=>{N(e.id)},onDeleteCancel:()=>k(null)},e.id)),n.length>0&&0===E.length&&(0,r.jsx)("div",{style:{padding:"22px 12px",color:"var(--text-dim)",fontSize:12,textAlign:"center"},children:m("agentSwitcher.noMatches")})]})]})})}let hd={idle:"debug.stream.state.idle",connecting:"debug.stream.state.connecting",connected:"debug.stream.state.connected",retrying:"debug.stream.state.retrying"},hc={ready_timeout:"debug.stream.error.readyTimeout",startup_error:"debug.stream.error.startup",error:"debug.stream.error.error",stale:"debug.stream.error.stale"},hu={visible:"debug.stream.reattach.visible",activity:"debug.stream.reattach.activity"},hp={agent:"debug.page.source.agent","file-watch":"debug.page.source.fileWatch",terminal:"debug.page.source.terminal"},hh={connecting:"debug.page.source.connecting",open:"debug.page.source.open"},hm={reply:"debug.lease.outcome.reply",unanswered:"debug.lease.outcome.unanswered",error:"debug.lease.outcome.error"},hg={alive:"debug.state.alive",closing:"debug.state.closing",none:"debug.state.none"},hf={timeout:"debug.poll.timeout",http:"debug.poll.http",network:"debug.poll.network",invalid:"debug.poll.invalid"},hx={starting:"agentSwitcher.status.starting",queued:"debug.run.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"},hb={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 hv(e,t,n){return Object.prototype.hasOwnProperty.call(t,e)?n(t[e]):e}function hy(e){return Number.isFinite(e)?Math.max(0,e):0}function hj(e){return String(e).padStart(2,"0")}function hk(e,t){let n=hy(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:hj(Math.floor(n%6e4/1e3))}):n<864e5?t("debug.duration.hoursMinutes",{hours:Math.floor(n/36e5),minutes:hj(Math.floor(n%36e5/6e4))}):t("debug.duration.daysHours",{days:Math.floor(n/864e5),hours:Math.floor(n%864e5/36e5)})}function hw(e,t){return t("debug.time.ago",{time:hk(e,t)})}function hS(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"floor",r=Math[n](hy(e)/1e3);return r<60?t("debug.duration.seconds",{count:r}):hk(1e3*r,t)}function hC(e,t){return e>0?t("debug.time.in",{time:hS(e,t,"ceil")}):t("debug.time.due")}function hN(e,t){return e>0?t("debug.time.in",{time:hk(e,t)}):t("debug.time.due")}function hI(e){return e.length>8?e.slice(0,8):e}function h$(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function hE(e){return"number"==typeof e&&Number.isFinite(e)}function hT(e){var t;return h$(e)&&"string"==typeof e.sessionId&&"string"==typeof e.state&&hE(e.eventStreams)&&(null===(t=e.nextIdleCheckAt)||hE(t))}function hM(e,t){try{return e()}catch{return t}}function hR(e){if(!e)return{client:null,failed:!1};try{return{client:e()??null,failed:!1}}catch{return{client:null,failed:!0}}}function hA(e,t){return e?.sessionId??t}let hL={sessionId:null,reply:null,receivedAt:null,roundTripMs:null,failure:null,requests:0,failures:0,consecutiveFailures:0},hP=e=>e.filter(Boolean).join(" \xb7 ");function hz(e,t,n){return null===e?n("debug.holder.none"):`${n(e===t?"debug.holder.thisPage":"debug.holder.otherPage")} ${hI(e)}`}function hO(e,t){let n=e.filter(e=>null!==e.holder&&e.holder===t);return[...n,...e.filter(e=>!n.includes(e))]}let hW={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 hF(e){return e.awaitingInput?"awaiting":e.running?"running":e.state}function hD(e,t){return null===e.label?"—":"agent"===e.kind?t?.(e.label)??hI(e.label):K(e.label)}function hB(e,t){if(!(t>0))return null;let n=e/t;return Number.isFinite(n)?Math.min(1,Math.max(0,n)):0}function hH(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 h_(e,t){return t>0?e>=t?"error":e>=t/2?"warning":"dim":"dim"}let hU={poll:[],running:[]};function hq(e){let t=hy(e);return{ms:t,tone:t>=2e3?"warning":"dim",failed:!1}}function hK(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 hZ(e){let t=Date.parse(e.modified);return Number.isFinite(t)?t:-1/0}function hV(e,t){return e===t?0:t>e?1:-1}class hJ 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 hG(e){let{readerRef:t,selectedSessionId:n,sessions:s,onClose:a}=e,{t:o}=(0,eW.s)(),l=(0,i.useRef)(n);l.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)(hL),[v,y]=(0,i.useState)(hU),[j,k]=(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,o,d,h,g;u.current=!1;let x=(r=(e={fetch:(e,t)=>fetch(e,t),sessionId:()=>hA(hR(t.current).client,l.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:hq(e.roundTripMs)}(e);t&&y(e=>({...e,poll:hK(e.poll,t)}))}}).now??(()=>Date.now()),i=e.setTimeout??((e,t)=>setTimeout(e,t)),s=e.clearTimeout??(e=>clearTimeout(e)),a=!1,o=null,d=hL,h=async t=>{let l=new AbortController,c={sessionId:t,controller:l,startedAt:r()};o=c,n=t;let u=!1,p=i(()=>{u=!0,l.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:l.signal});if(n.ok){let e=null;try{e=await n.json()}catch(e){if(l.signal.aborted)throw e}(g=e,h$(g)&&hE(g.now)&&h$(f=g.server)&&hE(f.startedAt)&&h$(f.wrappers)&&h$(f.eventStreams)&&hE(f.sseTotal)&&Array.isArray(f.pages)&&h$(f.terminals)&&Array.isArray(g.sessions)&&g.sessions.every(hT)&&(null===g.session||function(e){if(!h$(e)||"string"!=typeof e.sessionId)return!1;let t=e.wrapper,n=e.subagents,r=e.mcp;return(null===t||h$(t)&&"string"==typeof t.state&&h$(t.run)&&h$(t.idle))&&(null===e.lifecycle||h$(e.lifecycle))&&(null===e.providers||Array.isArray(e.providers))&&Array.isArray(e.eventStreams)&&h$(n)&&Array.isArray(n.runs)&&Array.isArray(n.notifications)&&(null===r||h$(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),o===c&&(o=null)}if(a||l.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(o){if(o.sessionId===t)return;o.controller.abort()}h(t)},sync(){a||(o?o.sessionId:n)!==e.sessionId()&&g()},inFlightSince:()=>o?.startedAt??null,dispose(){a=!0,o?.controller.abort(),o=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}=hR(e);return{at:n,client:r,clientFailed:i,sources:hM(eN.X6,[]),visibility:hM(eN._L,null),protocol:hM(eN.rv,null),runningPoll:hM(eN.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:hy(n.durationMs),tone:"error",failed:!0}:hq(n.durationMs):null;e&&y(t=>({...t,running:hK(t.running,e)}))}};v(),x.poll();let j=window.setInterval(()=>{"visible"===document.visibilityState&&(v(),x.sync())},1e3),k=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(j),window.clearInterval(k),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)(hY,{page:N.page,server:N.server,samples:N.samples,selectedSessionId:n,sessions:s,copied:j,onCopy:()=>{let e={client:g,server:x.reply};(0,e3.D)(JSON.stringify(e,null,2)).then(()=>{u.current||(p.current&&clearTimeout(p.current),k(!0),p.current=setTimeout(()=>k(!1),1400))},()=>{})},t:o,sectionRef:h})}function hY(e){var t;let n,{page:s,server:a,samples:o=hU,selectedSessionId:l,sessions:d,copied:c,onCopy:u,t:p,sectionRef:h}=e,m=s?.at??a.receivedAt??0,g=s?.client??null,x=hA(g,l),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===x?b.session:null,j=g?.pageId??null,k=(0,i.useMemo)(()=>new Map(d.map(e=>[e.id,e])),[d]),w=(0,i.useMemo)(()=>e=>{let t=k.get(e);return t?ta(t):null},[k]),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),o=i.get(a.id);o||(o={root:a,summary:null,subagents:[]},i.set(a.id,o)),a.id===e.id?o.summary=n:o.subagents.push({info:e,summary:n})}let a=null===n?void 0:t.get(n),o=a?r(a).id:null,l=(e,t)=>hV(hZ(e.root),hZ(t.root)),d=(e,t)=>Number(t.root.id===o)-Number(e.root.id===o),c=new Map;for(let e of i.values()){let t=f(e.root),n=c.get(t);n||(n={key:t,name:K(e.root.projectRoot??e.root.cwd),families:[]},c.set(t,n)),n.families.push(e)}let u=e=>Math.max(...e.families.map(e=>hZ(e.root))),p=e=>e.families.some(e=>e.root.id===o),h=[...c.values()].sort((e,t)=>Number(p(t))-Number(p(e))||hV(u(e),u(t))).map(e=>{let t=[];for(let r of[...e.families].sort(l).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)=>hV(hZ(e.info),hZ(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(hI(e.sessionId),hI(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,k,x):null,[b,k,x]),C=s?function(e){let{page:t,server:n,detail:r,t:i,titleOf:s}=e,a=t.at,o=[],l=(e,t,n)=>{o.push({id:e,tone:t,text:hP(n)})},d=n.failure;d?l("poll","timeout"===d.kind?"warning":"error",[i(hf[d.kind],{status:d.status??"?"}),hw(a-d.at,i)]):null!==t.pollInFlightSince&&a-t.pollInFlightSince>=2e3&&l("poll","warning",[i("debug.poll.inFlight",{time:hk(a-t.pollInFlightSince,i)})]),t.clientFailed&&l("reader","error",[i("debug.stream.readerFailed")]);let c=t.runningPoll?.last??null;c?.outcome==="error"&&l("runningPoll","warning",[i("debug.page.runningPoll"),i("debug.page.poll.error"),null!==c.httpStatus&&`HTTP ${c.httpStatus}`,hw(a-c.at,i)]);let u=t.sources.filter(e=>"open"===e.state).length;"http/1.1"===t.protocol&&u>=5&&l("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)&&l("source","warning",[i(hp[e.kind]),hD(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:hN(h.retryDueAt-a,i)}),t=h.lastError;t&&"connected"!==h.state&&!(h.lastClose&&h.lastClose.at>=t.at)?l("stream","error",[hv(t.reason,hc,i),t.message,hw(a-t.at,i),e]):"retrying"===h.state&&l("stream","warning",[i(hd.retrying),e]);let n=hH(h,a),r=n?h_(n.ageMs,n.staleAfterMs):"dim";n&&"dim"!==r&&l("streamSilent",r,[`${i("debug.stream.lastData")} ${hw(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)&&l("noServerStream","warning",[i("debug.issue.noServerStream")]),r?.eventStreams??[]))e.droppedEvents>0&&l("dropped","warning",[hz(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?l("lease","warning",[i("debug.section.lease"),i("debug.lease.inFlight",{time:hk(a-x.inFlightSince,i)})]):e?.outcome==="error"?l("lease","error",[i("debug.section.lease"),i(hm.error),null!==e.httpStatus&&`HTTP ${e.httpStatus}`,hw(a-e.at,i)]):e?.outcome==="unanswered"&&l("lease","warning",[i("debug.section.lease"),i(hm.unanswered),hw(a-e.at,i)])}let b=r?.wrapper??null;for(let e of(b&&!b.stale&&"failed"===b.extensions&&l("extensions","error",[i("debug.server.extensions"),i("debug.server.extensions.failed")]),r?.providers??[]))"error"===e.active&&l("provider","error",[e.name,i("debug.server.providerError")]);for(let e of r?.mcp?.servers??[])(e.hasError||"failed"===e.state||"conflict"===e.state)&&l("mcp","error",[`MCP ${e.name}`,hv(e.state,oY,i)]);return o.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:j,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)(h7,{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)(me,{issues:C}),(0,r.jsxs)("div",{className:"debug-cols",children:[(0,r.jsx)(mr,{page:s,samples:o,reply:b,ctx:I}),(0,r.jsxs)("div",{className:"debug-col debug-col-server",children:[(0,r.jsx)(mu,{reply:b,ctx:I}),(0,r.jsx)(mp,{reply:b,ctx:I})]}),(0,r.jsx)("div",{className:"debug-col debug-col-sessions",children:(0,r.jsx)(mh,{reply:b,detail:y,groups:S,targetSessionId:x,sources:s.sources,ctx:I})})]})]}),(0,r.jsx)("style",{children:mN})]})}function hX(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 hQ(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 h0(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:hQ(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 h1={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)(h2,{}),iOS:(0,r.jsx)(h2,{}),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 h2(){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 h4(e){let{client:t}=e,n=t?t.split(" \xb7 ").filter(e=>e in h1):[];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:h1[e]},e))})}function h8(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 h6(e){let{tone:t,children:n,title:i}=e;return(0,r.jsx)("span",{className:`debug-chip is-${t}`,title:i,children:n})}function h3(e){let{fraction:t,tone:n,width:i,height:s=4,notches:a,title:o,className:l}=e;return(0,r.jsxs)("span",{className:`debug-bar is-${n}${l?` ${l}`:""}`,style:{width:i,height:s},title:o,"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 h5(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(hy(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 h9(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)(ts.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 h7(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)(hX,{kind:"error"===t.tone?"error":"warning"}),"ok"===t.kind&&(0,r.jsx)(h8,{tone:"ok"}),("hidden"===t.kind||"waiting"===t.kind)&&(0,r.jsx)(h8,{tone:"dim",ring:!0}),(0,r.jsx)("span",{className:"debug-panel-status-text",children:i})]})}function me(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)(hX,{kind:e.tone}),(0,r.jsx)("span",{className:"debug-issue-text",children:e.text})]},`${e.id}:${t}`))})}function mt(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:hk(n.median,t),max:hk(n.max,t)})}function mn(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?"—":hk(i.ms,n)}):(0,r.jsx)("span",{className:"debug-value is-dim",children:"—"})}function mr(e){let{page:t,samples:n,reply:i,ctx:s}=e,{t:a}=s,o=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,o={agent:0,"file-watch":0,terminal:0};for(let e of r)o[e.kind]=(o[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:o,tone:null===i?"dim":a>=i?"error":a>=i-1?"warning":"dim"}}(t.sources,t.protocol,t.client?.connection?.sessionId??null),l=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)(mi,{pool:o,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)(h5,{samples:n.poll,label:mt(n.poll,a)}),(0,r.jsx)(mn,{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)(h5,{samples:n.running,label:hP([l&&a("debug.page.pollCounts",{count:l.count,failures:l.failures}),mt(n.running,a)])}),(0,r.jsx)(mn,{samples:n.running,t:a}),(0,r.jsx)(ml,{page:t,reply:i,ctx:s}),(0,r.jsx)(mc,{page:t,ctx:s})]})]})}function mi(e){let{pool:t,ctx:n}=e,{t:i,now:s,titleOf:a}=n,o=Object.keys(hp).filter(e=>t.kinds[e]>0).map(e=>`${i(hp[e])} ${t.kinds[e]}`),l=null!==t.cap?hP([`${i("debug.page.http1",{protocol:t.protocol??""})} \xb7 ${t.mine}/${t.cap}`,...o]):hP([i("debug.section.page"),...o,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":l,title:l,children:[d.map((e,t)=>e?(0,r.jsx)("span",{className:hQ({tone:e.connecting?"warning":e.chat?"accent":"muted",filled:e.chat,dashed:e.connecting},"debug-slot"),title:hP([i(hp[e.kind]),hD(e,a),i(hh[e.connecting?"connecting":"open"]),i("debug.page.sourceCounts",{opens:e.opens,errors:e.errors}),hw(s-e.createdAt,i)]),children:"agent"===e.kind?"SSE":i(ms[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)(h6,{tone:"dim",children:t.protocol})]})}let ms={"file-watch":"debug.box.file",terminal:"debug.box.terminal"},ma={connected:{tone:"ok",ring:!1},connecting:{tone:"warning",ring:!0},retrying:{tone:"warning",ring:!1},idle:{tone:"dim",ring:!0}};function mo(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")} ${hw(i-t.openedAt,r)}`,null!==t.connectedAt&&`${r("debug.stream.connected")} ${hw(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")} ${hP([hv(t.lastError.reason,hc,r),t.lastError.message,hw(i-t.lastError.at,r)])}`,null!==t.lastClose&&`${r("debug.stream.lastClose")} ${hP([t.lastClose.reason?hv(t.lastClose.reason,hb,r):"—",hw(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(hP([r("debug.page.hiddenCount",{count:a.hiddenCount}),null!==a.lastHiddenAt&&r("debug.page.lastHidden",{time:hw(i-a.lastHiddenAt,r)})])),e.released.count>0&&s.push(`${r("debug.stream.released")} ${hP([r("debug.times",{count:e.released.count}),null!==e.released.lastAt&&hw(i-e.released.lastAt,r)])}`),e.reattached.count>0&&s.push(`${r("debug.stream.reattached")} ${hP([r("debug.times",{count:e.reattached.count}),null!==e.reattached.lastAt&&hw(i-e.reattached.lastAt,r),e.reattached.lastReason&&r(hu[e.reattached.lastReason])])}`),s.filter(Boolean).join("\n")}function ml(e){let{page:t,reply:n,ctx:i}=e,{t:s,now:a}=i,o=t.client,l=o?.connection??null,d=(0,r.jsx)("span",{className:"debug-measure-name",title:o&&l?mo(o,l,t,s):void 0,children:(0,r.jsx)("span",{className:"debug-label",children:s("debug.section.stream")})});if(!o||!l)return(0,r.jsxs)(r.Fragment,{children:[d,(0,r.jsx)("span",{className:"debug-measure-empty",children:o?s("debug.stream.noConnection"):t.clientFailed?"—":s("debug.stream.noChat")})]});let c=hH(l,a),u=ma[l.state];return(0,r.jsxs)(r.Fragment,{children:[d,c?(0,r.jsx)(md,{connection:l,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:mo(o,l,t,s),children:[(0,r.jsx)(h8,{tone:u?.tone??"dim",ring:u?.ring??!0}),hP([s(hd[l.state]??"debug.unknown"),`${s("debug.stream.events")} ${l.events}`,l.retries>0&&`${s("debug.stream.opens")} ${s("debug.stream.opensRetries",{opens:l.opens,retries:l.retries})}`])]}),(o.released.active||null!==o.graceDueAt)&&(0,r.jsxs)("span",{className:"debug-measure-sub debug-chips",children:[o.released.active&&(0,r.jsx)(h6,{tone:"accent",children:s("debug.stream.close.released")}),null!==o.graceDueAt&&(0,r.jsx)(h6,{tone:"accent",children:`${s("debug.stream.grace")} ${hC(o.graceDueAt-a,s)}`})]})]})}function md(e){let{connection:t,freshness:n,heartbeatMs:i,ctx:s}=e,{t:a,now:o}=s,{ageMs:l,staleAfterMs:d}=n,c=h_(l,d),u=[];if(i>0)for(let e=i;e<d&&u.length<12;e+=i)u.push(e/d);let p=hP([`${a("debug.stream.lastData")} ${hw(l,a)}`,null!==t.lastHeartbeatAt&&a("debug.stream.heartbeat",{time:hw(o-t.lastHeartbeatAt,a)}),a("debug.stream.watchdogArmed",{time:hk(d,a)})]);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(h3,{fraction:hB(l,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:hS(l,a)})})]})}function mc(e){let{page:t,ctx:n}=e,{t:i,now:s}=n,a=t.client?.lease??null,o=t.client?.pageId??null,l=(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:[l,(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=hP([null!==c&&`${i("debug.lease.next")} ${hC(c-s,i)}`,i("debug.lease.every",{time:hk(a.renewIntervalMs,i)}),h,null!==o&&`${i("debug.holder.thisPage")} ${hI(o)}`]);return(0,r.jsxs)(r.Fragment,{children:[l,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)(h3,{fraction:u?1:1-(hB(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:hS(c-s,i,"ceil")}):i("debug.lease.renewing")})]}),(0,r.jsx)("span",{className:"debug-measure-sub",children:`${i("debug.lease.last")} ${d?hP([i(hm[d.outcome]??"debug.unknown"),hk(d.durationMs,i),"error"===d.outcome&&null!==d.httpStatus&&`HTTP ${d.httpStatus}`,i("debug.time.ago",{time:hS(s-d.at,i)})]):i("debug.notYet")}`}),(a.unanswered>0||a.errors>0)&&(0,r.jsx)("span",{className:"debug-measure-sub",children:h})]})}function mu(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 o=t.server,l=i("debug.global.wrappersValue",{...o.wrappers}),d=`${i("debug.global.timers")}: ${i("debug.global.timersValue",{idle:o.idleTimeoutMs>0?hk(o.idleTimeoutMs,i):i("debug.server.idleDisabled"),heartbeat:hk(o.heartbeatMs,i)})}
200
- ${l}`,c=o.terminals,u=hP([`${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:hN(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")}: ${o.fileWatches}`,m=o.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)(hX,{kind:"server"}),(0,r.jsx)("span",{children:`${i("debug.global.uptime")} ${hk(s.age(o.startedAt),i)}`})]}),m>0&&(0,r.jsxs)("span",{className:"debug-run",role:"img","aria-label":l,title:l,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)(h0,{text:i("debug.box.file"),items:Array.from({length:o.fileWatches},()=>({tone:"muted",title:h})),cap:4,label:h}),(0,r.jsx)(h0,{text:i("debug.box.terminal"),items:p,cap:4,label:u})]})}function mp(e){let{reply:t,ctx:n}=e,{t:i,myHolder:s}=n;if(!t)return null;let{pages:a,sseTotal:o}=t.server;if(0===o&&0===a.length)return null;let l=hO(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")} ${l.length}`}),(0,r.jsx)("span",{className:"debug-page-count",children:`SSE ${i("debug.global.streamTotal",{count:o})}`})]}),l.map((e,t)=>{let n=null!==e.holder&&e.holder===s,a=hz(e.holder,s,i),o=e.agent+e.terminal+e.fileWatch,l=hP([e.agent>0&&`${i(hp.agent)} ${e.agent}`,e.terminal>0&&`${i(hp.terminal)} ${e.terminal}`,e.fileWatch>0&&`${i(hp["file-watch"])} ${e.fileWatch}`]);return(0,r.jsxs)("div",{className:`debug-page-row${n?" is-current":""}`,title:hP([a,e.client,e.address,`SSE ${o}`,l]),children:[(0,r.jsx)("span",{className:"debug-page-icons",children:(0,r.jsx)(h4,{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?hI(e.holder):i("debug.holder.none")}),(0,r.jsx)("span",{className:"debug-page-count",children:o})]},`${e.holder??""}:${t}`)})]})}function mh(e){let{reply:t,detail:n,groups:s,targetSessionId:a,sources:o,ctx:l}=e,{t:d,clock:c}=l;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)(mg,{detail:n,clock:c,ctx:l})):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)(ts.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)(mS,{row:e,sources:o,idleTimeoutMs:t.server.idleTimeoutMs,clock:c,ctx:l,current:s?function(e,t,n){let{t:i}=n,s=e=>hw(t.age(e),i),a=e.wrapper?.idle??null,o=e.lifecycle;return{badges:(0,r.jsx)(mb,{detail:e,clock:t,ctx:n}),idleTitle:a&&null!==a.nextCheckAt?hP([`${i("debug.server.idle")} ${hk(t.remaining(a.nextCheckAt),i)}`,a.timeoutMs>0&&i("debug.server.idleTimeout",{time:hk(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:o&&o.starts>1?mm(o,s,i):void 0}}(s,c,l):void 0}),s&&(0,r.jsx)(mf,{detail:s,clock:c,ctx:l})]},e.id)})]},e.key))]})}function mm(e,t,n){return hP([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 mg(e){var t;let n,{detail:i,clock:s,ctx:a}=e,{t:o,titleOf:l}=a,d=l(i.sessionId)??hI(i.sessionId),c=(n=(t=i).wrapper)?hF({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:o("debug.sessions.current"),children:[(0,r.jsx)("span",{className:"debug-row-status",children:(0,r.jsx)(h9,{state:c,label:o(hW[c])})}),(0,r.jsx)("span",{className:"debug-row-title",children:(0,r.jsx)("span",{className:"debug-row-name",children:d})})]}),(0,r.jsx)(mf,{detail:i,clock:s,ctx:a,unlisted:!0})]})}function mf(e){let{detail:t,clock:n,ctx:i,unlisted:s=!1}=e,{t:a,titleOf:o}=i,l=t.wrapper,d=t.lifecycle,c=e=>hw(n.age(e),a),u=null!==l&&!l.stale,p=l?.state==="closing"?null!==l.closingAt?a("debug.server.closingSince",{time:c(l.closingAt)}):a("debug.state.closing"):null,h=l&&hP([null!=l.startedAt&&`${a("debug.server.started")} ${c(l.startedAt)}`,u&&l.lastEvent&&`${a("debug.server.lastEvent")} ${l.lastEvent.type} ${c(l.lastEvent.at)}`,u&&l.lastCommand&&`${a("debug.server.lastCommand")} ${l.lastCommand.type} ${c(l.lastCommand.at)}`]);return(0,r.jsxs)("div",{className:"debug-detail",children:[(0,r.jsxs)("div",{className:"debug-detail-line",children:[null!==o(t.sessionId)&&(0,r.jsx)("span",{className:"debug-detail-id",children:hI(t.sessionId)}),!l&&(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:mm(d,c,a),children:`↻${d.starts}`}),p&&(0,r.jsx)(h6,{tone:"warning",children:p}),l?.chatOnly&&(0,r.jsx)(h6,{tone:"dim",children:a("debug.server.chatOnly")}),l?.subagent&&(0,r.jsx)(h6,{tone:"dim",children:a("debug.server.subagent")}),l?.stale&&(0,r.jsx)(h6,{tone:"warning",children:a("debug.server.stale")}),(0,r.jsx)(mx,{detail:t,t:a}),u&&(0,r.jsx)(mv,{detail:t,t:a}),h&&(0,r.jsx)("span",{className:"debug-line",children:h})]}),u&&(0,r.jsx)(mk,{detail:t,clock:n,ctx:i}),u&&(0,r.jsx)(mw,{detail:t,clock:n,ctx:i})]})}function mx(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)(h6,{tone:"warning",children:`${n("debug.server.listeners")} ${i.eventListeners}`}):null}function mb(e){var t;let n,{detail:i,clock:s,ctx:a}=e,{t:o,myHolder:l}=a,d=e=>hw(s.age(e),o),c=hO([...i.eventStreams].sort((e,t)=>e.openedAt-t.openedAt),l),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===l?"accent":"muted"),filled:null!==e.holder&&e.holder===l,dashed:r,title:hP([hz(e.holder,l,o),e.client,e.address,null!==e.connectedAt?o("debug.server.streamConnected",{time:d(e.connectedAt)}):o("debug.server.streamStarting"),null!==e.lastWriteAt&&o("debug.server.lastWrite",{time:d(e.lastWriteAt)}),e.droppedEvents>0&&o("debug.server.dropped",{count:e.droppedEvents}),e.queuedBytes>0&&o("debug.server.queued",{size:(n=hy(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:o("debug.server.providersUnknown")}]:p.map(e=>({tone:"error"===e.active?"error":e.active?"muted":"dim",faded:!1===e.active,text:e.name,title:hP([e.name,o("error"===e.active?"debug.server.providerError":e.active?"debug.server.providerActive":"debug.server.providerInactive"),e.byFile&&o("debug.server.byFile")])}));return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(h0,{text:"SSE",items:u,cap:3,label:(t=c.map(e=>e.holder),n=t.filter(e=>null!==e&&e===l).length,`SSE: ${t.length} (${o("debug.holder.thisPage")} ${n}, ${o("debug.holder.otherPage")} ${t.length-n})`)}),(0,r.jsx)(h0,{text:o("debug.box.provider"),items:h,cap:1,label:`${o("debug.server.providers")}: ${null===p?o("debug.server.providersUnknown"):p.length}`})]})}function mv(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),o=[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)(h6,{tone:"dim",children:e},e)),o.map(e=>(0,r.jsx)(h6,{tone:"warning",children:e},e))]})}let my={completed:"ok",failed:"error",aborted:"warning",interrupted:"warning"};function mj(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)(ts.Nl,{size:12})});let n=my[t];return n?(0,r.jsx)("span",{className:`debug-run-icon is-${n}`,children:(0,r.jsx)(hs,{status:t})}):(0,r.jsx)("span",{className:"debug-run-icon",children:(0,r.jsx)("span",{className:"debug-status-ring is-alive"})})}function mk(e){let{detail:t,clock:n,ctx:i}=e,{t:s,titleOf:a}=i,o=t.subagents;if(!o.active&&0===o.runs.length&&0===o.notifications.length)return null;let l=e=>hw(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")}),o.active&&(0,r.jsx)(h6,{tone:"accent",children:s("debug.server.subagentsActive")})]}),o.runs.map((e,t)=>(0,r.jsxs)("div",{className:"debug-run-line",children:[(0,r.jsx)(mj,{status:e.status}),(0,r.jsx)("span",{className:"debug-run-name",children:a(e.sessionId)??e.profile??hI(e.sessionId)}),(0,r.jsx)("span",{className:"debug-line",children:hP([hv(e.status,hx,s),e.background&&s("debug.server.background"),e.resumed&&s("debug.server.resumed"),null!==e.dispatchedAt&&l(e.dispatchedAt)])}),e.abortRequested&&(0,r.jsx)(h6,{tone:"warning",children:s("debug.server.abortRequested")}),e.mcpWaiting&&(0,r.jsx)(h6,{tone:"warning",children:s("debug.run.waitingForMcp")})]},`${e.sessionId}:${t}`)),o.notifications.map((e,t)=>(0,r.jsx)("div",{className:"debug-line is-warning",children:hP([s("debug.server.notifying",{parent:hI(e.parentSessionId)}),null!==e.since&&l(e.since)])},`${e.sessionId}:${t}`))]})}function mw(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 o=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=hv(e.state,oY,s),o=hP([`${e.name} (${e.scope})`,a,e.released&&s("debug.server.mcpReleased"),e.hasError&&s("debug.server.mcpError")]),l="connected"!==e.state?a:e.hasError?s("debug.server.mcpError"):null;return(0,r.jsxs)("span",{className:"debug-pill",role:"img","aria-label":o,title:o,children:[(0,r.jsx)(h8,{tone:n,ring:!i}),(0,r.jsx)("span",{className:e.released?"is-dim":void 0,children:e.name}),l&&(0,r.jsx)("span",{className:"debug-pill-state",children:`\xb7 ${l}`})]},`${e.scope}:${e.name}:${t}`)}),a.problems>0&&(0,r.jsx)(h6,{tone:"warning",children:s("debug.server.mcpProblems",{count:a.problems})}),a.disposed&&(0,r.jsx)(h6,{tone:"dim",children:s("debug.server.mcpDisposed")})]}),null!==o&&(0,r.jsxs)("div",{className:"debug-idle-row",children:[(0,r.jsx)(h3,{fraction:hB(o,a.idleMs)??0,tone:"dim",width:80}),(0,r.jsx)("span",{className:"debug-value is-muted",children:s("debug.server.mcpRelease",{time:hN(o,s)})})]})]})}function mS(e){var t;let n,i,{row:s,sources:a,idleTimeoutMs:o,clock:l,ctx:d,current:c}=e,{t:u}=d,p=s.summary,h=s.info?ta(s.info):hI(s.id),m=p&&null!==p.nextIdleCheckAt?l.remaining(p.nextIdleCheckAt):null,g=p?hF(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:hP([s.current&&u("debug.sessions.current"),p?(n=[p.subagent?u("debug.overlay.subagentId",{id:hI(p.sessionId)}):hI(p.sessionId),u(hg[p.state]??hg.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=hy(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)(h9,{state:g,label:u(hW[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)(mC,{summary:p,mine:(t=s.id,a.filter(e=>"agent"===e.kind&&e.label===t).length),remaining:m,idleTimeoutMs:o,t:u,badges:c?.badges,idleTitle:c?.idleTitle})]})}function mC(e){let{summary:t,mine:n,remaining:i,idleTimeoutMs:s,t:a,badges:o,idleTitle:l}=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:hS(i,a)}):void 0;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"debug-row-badges",children:o??(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(h0,{text:"SSE",items:u,cap:3,label:d}),(0,r.jsx)(h0,{text:a("debug.box.provider"),items:h,cap:1,label:p})]})}),(0,r.jsx)("span",{className:`debug-row-idle is-${g}`,title:l,children:m&&null!==i&&(0,r.jsxs)(r.Fragment,{children:[s>0&&(0,r.jsx)(h3,{fraction:hB(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:hS(i,a)})]})})]})}let mN=`
201
- .debug-panel {
202
- --dbg-ok: #16a34a;
203
- --dbg-warn: #d97706;
204
- --dbg-err: #ef4444;
205
- container-type: inline-size;
206
- container-name: debug-panel;
207
- display: flex;
208
- max-height: min(720px, 80dvh);
209
- flex-direction: column;
210
- background: var(--bg-panel);
211
- border-bottom: 1px solid var(--border);
212
- box-shadow: 0 10px 28px rgba(0,0,0,0.10);
213
- color: var(--text);
214
- }
215
- .debug-panel .is-ok { color: var(--dbg-ok); }
216
- .debug-panel .is-warning { color: var(--dbg-warn); }
217
- .debug-panel .is-error { color: var(--dbg-err); }
218
- .debug-panel .is-accent { color: var(--accent); }
219
- .debug-panel .is-muted { color: var(--text-muted); }
220
- .debug-panel .is-dim { color: var(--text-dim); }
221
- .debug-panel-header {
222
- display: flex;
223
- flex-shrink: 0;
224
- align-items: center;
225
- gap: 12px;
226
- min-width: 0;
227
- padding: 8px 16px;
228
- border-bottom: 1px solid var(--border);
229
- font-size: 12px;
230
- }
231
- .debug-panel-heading {
232
- flex-shrink: 0;
233
- color: var(--text);
234
- cursor: help;
235
- font-weight: 700;
236
- }
237
- .debug-panel-status {
238
- display: inline-flex;
239
- min-width: 0;
240
- align-items: center;
241
- gap: 6px;
242
- font-variant-numeric: tabular-nums;
243
- }
244
- .debug-panel-status svg {
245
- flex-shrink: 0;
246
- }
247
- .debug-panel-status-text {
248
- min-width: 0;
249
- overflow: hidden;
250
- text-overflow: ellipsis;
251
- white-space: nowrap;
252
- }
253
- .debug-panel-copy {
254
- flex-shrink: 0;
255
- margin-left: auto;
256
- padding: 2px 8px;
257
- border: 1px solid var(--border);
258
- border-radius: 4px;
259
- background: transparent;
260
- color: var(--text-muted);
261
- cursor: pointer;
262
- font-size: 11px;
263
- }
264
- .debug-panel-copy:hover {
265
- background: var(--bg-hover);
266
- color: var(--text);
267
- }
268
- .debug-panel-scroll {
269
- display: flex;
270
- min-height: 0;
271
- flex: 1;
272
- flex-direction: column;
273
- gap: 12px;
274
- overflow: auto;
275
- padding: 10px 16px 12px;
276
- font-size: 12px;
277
- line-height: 1.5;
278
- }
279
- .debug-section-title {
280
- color: var(--text);
281
- font-size: 11px;
282
- font-weight: 700;
283
- }
284
- .debug-empty,
285
- .debug-note {
286
- color: var(--text-dim);
287
- font-size: 12px;
288
- }
289
- .debug-label {
290
- color: var(--text-dim);
291
- font-size: 11px;
292
- white-space: nowrap;
293
- }
294
- .debug-value {
295
- font-family: var(--font-mono);
296
- font-size: 11px;
297
- font-variant-numeric: tabular-nums;
298
- white-space: nowrap;
299
- }
300
- .debug-line {
301
- color: var(--text-dim);
302
- font-family: var(--font-mono);
303
- font-size: 11px;
304
- font-variant-numeric: tabular-nums;
305
- overflow-wrap: anywhere;
306
- }
307
- .debug-panel .debug-line.is-warning {
308
- color: var(--dbg-warn);
309
- }
310
-
311
- .debug-issues {
312
- display: flex;
313
- flex-direction: column;
314
- gap: 4px;
315
- margin: 0;
316
- padding: 0;
317
- list-style: none;
318
- }
319
- .debug-issue {
320
- display: flex;
321
- align-items: flex-start;
322
- gap: 6px;
323
- padding: 4px 8px;
324
- border-left: 2px solid currentColor;
325
- border-radius: 4px;
326
- background: color-mix(in srgb, currentColor 8%, var(--bg-panel));
327
- }
328
- .debug-issue > svg {
329
- flex-shrink: 0;
330
- margin-top: 3px;
331
- }
332
- .debug-issue-text {
333
- min-width: 0;
334
- color: var(--text);
335
- font-size: 12px;
336
- overflow-wrap: anywhere;
337
- }
338
-
339
- /* Three columns when the panel is wide: the page's as wide as its table, the server's and the
340
- sessions' each capped, so names never stretch and push the badges to the far edge. */
341
- .debug-cols {
342
- display: grid;
343
- grid-template-areas: "page server sessions";
344
- grid-template-columns: minmax(320px, max-content) minmax(340px, 480px) minmax(360px, 560px);
345
- gap: 0;
346
- }
347
- .debug-col {
348
- display: flex;
349
- min-width: 0;
350
- flex-direction: column;
351
- gap: 8px;
352
- }
353
- .debug-col-page {
354
- grid-area: page;
355
- }
356
- .debug-col-server {
357
- grid-area: server;
358
- }
359
- .debug-col-sessions {
360
- grid-area: sessions;
361
- }
362
- .debug-col-server,
363
- .debug-col-sessions {
364
- margin-left: 20px;
365
- padding-left: 20px;
366
- border-left: 1px solid var(--border);
367
- }
368
- .debug-list,
369
- .debug-block {
370
- display: flex;
371
- min-width: 0;
372
- flex-direction: column;
373
- gap: 6px;
374
- }
375
- .debug-block {
376
- gap: 4px;
377
- }
378
- .debug-col-head {
379
- display: flex;
380
- min-height: 18px;
381
- align-items: center;
382
- gap: 8px;
383
- }
384
- /* Name, scale, value; a measure's details span the row below it. */
385
- /* As wide as the column (the details get the room), never so wide a value drifts off its bar. */
386
- .debug-measures {
387
- display: grid;
388
- max-width: 400px;
389
- grid-template-columns: max-content minmax(max-content, 1fr) max-content;
390
- align-items: center;
391
- gap: 4px 10px;
392
- }
393
- /* Numbers line up on the right, as the count in the column's head does. */
394
- .debug-measures > .debug-value {
395
- justify-self: end;
396
- text-align: right;
397
- }
398
- .debug-measure-name {
399
- display: inline-flex;
400
- align-items: center;
401
- gap: 6px;
402
- }
403
- .debug-measure-name[title] {
404
- cursor: help;
405
- }
406
- /* Wrapped to the table's width rather than widening it (a percentage min-width adds nothing to
407
- the columns' sizes). */
408
- .debug-measure-sub,
409
- .debug-measure-empty {
410
- grid-column: 2 / -1;
411
- width: 0;
412
- min-width: 100%;
413
- color: var(--text-dim);
414
- font-family: var(--font-mono);
415
- font-size: 11px;
416
- font-variant-numeric: tabular-nums;
417
- overflow-wrap: anywhere;
418
- }
419
- .debug-measure-sub {
420
- margin-top: -4px;
421
- }
422
- .debug-measure-sub > .debug-dot {
423
- margin-right: 6px;
424
- vertical-align: 0;
425
- }
426
- .debug-measure-empty {
427
- font-family: inherit;
428
- font-size: 12px;
429
- }
430
- .debug-chips {
431
- display: flex;
432
- flex-wrap: wrap;
433
- gap: 4px;
434
- }
435
- .debug-chip {
436
- display: inline-flex;
437
- align-items: center;
438
- padding: 0 6px;
439
- border: 1px solid color-mix(in srgb, currentColor 35%, transparent);
440
- border-radius: 9px;
441
- font-family: var(--font-mono);
442
- font-size: 11px;
443
- line-height: 16px;
444
- white-space: nowrap;
445
- }
446
-
447
- /* A boxed word: "SSE", a provider's name, File, Term. Filled is this page's own. */
448
- .debug-badge {
449
- display: inline-flex;
450
- height: 16px;
451
- box-sizing: border-box;
452
- flex-shrink: 0;
453
- align-items: center;
454
- padding: 0 4px;
455
- border: 1px solid currentColor;
456
- border-radius: 3px;
457
- background-clip: padding-box;
458
- font: 600 10px/14px var(--font-mono);
459
- white-space: nowrap;
460
- }
461
- .debug-panel .debug-badge.is-filled {
462
- border-color: var(--accent);
463
- background-color: var(--accent);
464
- color: var(--accent-contrast);
465
- }
466
- /* This page's, amber: a stream of its own still starting or dropping events. */
467
- .debug-panel .debug-badge.is-filled.is-warning {
468
- border-color: var(--dbg-warn);
469
- background-color: var(--dbg-warn);
470
- color: var(--bg-panel);
471
- }
472
- .debug-badge.is-dashed {
473
- border-style: dashed;
474
- }
475
- .debug-badge.is-faded {
476
- opacity: 0.45;
477
- }
478
- /* A provider's name: twelve characters, then an ellipsis (a block, so the ellipsis applies). */
479
- .debug-badge.is-name {
480
- display: inline-block;
481
- max-width: calc(12ch + 10px);
482
- overflow: hidden;
483
- text-overflow: ellipsis;
484
- }
485
- /* A page's browser and system marks. */
486
- .debug-client {
487
- display: inline-flex;
488
- align-items: center;
489
- gap: 3px;
490
- }
491
- .debug-client svg {
492
- display: block;
493
- flex-shrink: 0;
494
- }
495
-
496
- /* The connected pages: marks, browser and system, address, page, its stream count. */
497
- .debug-pages {
498
- display: flex;
499
- flex-direction: column;
500
- }
501
- .debug-page-row {
502
- position: relative;
503
- display: grid;
504
- min-height: 22px;
505
- grid-template-columns: 30px minmax(0, 1.2fr) minmax(0, 1fr) minmax(0, 1fr) 32px;
506
- align-items: center;
507
- column-gap: 8px;
508
- padding: 0 4px;
509
- border-radius: 4px;
510
- font-size: 11px;
511
- }
512
- .debug-page-row.debug-list-head {
513
- min-height: 18px;
514
- grid-template-columns: minmax(0, 1fr) auto;
515
- color: var(--text-dim);
516
- font-size: 10px;
517
- }
518
- .debug-page-row.is-current {
519
- background: var(--bg-selected);
520
- }
521
- .debug-page-row.is-current::before {
522
- content: "";
523
- position: absolute;
524
- top: 4px;
525
- left: 0;
526
- width: 3px;
527
- height: 14px;
528
- border-radius: 0 2px 2px 0;
529
- background: var(--accent);
530
- }
531
- .debug-page-icons {
532
- display: inline-flex;
533
- padding-left: 4px;
534
- color: var(--text-muted);
535
- }
536
- .debug-page-icons svg {
537
- width: 12px;
538
- height: 12px;
539
- }
540
- .debug-page-client,
541
- .debug-page-address,
542
- .debug-page-holder {
543
- min-width: 0;
544
- overflow: hidden;
545
- text-overflow: ellipsis;
546
- white-space: nowrap;
547
- }
548
- .debug-page-client {
549
- color: var(--text);
550
- }
551
- .debug-page-address {
552
- color: var(--text-muted);
553
- font-family: var(--font-mono);
554
- }
555
- .debug-page-holder {
556
- color: var(--text-dim);
557
- }
558
- .debug-page-count {
559
- justify-self: end;
560
- color: var(--text-muted);
561
- font-family: var(--font-mono);
562
- font-variant-numeric: tabular-nums;
563
- white-space: nowrap;
564
- }
565
- .debug-list-head .debug-page-count {
566
- color: var(--text-dim);
567
- }
568
- .debug-run {
569
- display: inline-flex;
570
- flex-wrap: wrap;
571
- align-items: flex-start;
572
- gap: 3px;
573
- vertical-align: middle;
574
- }
575
- .debug-run-more {
576
- color: var(--text-dim);
577
- font-family: var(--font-mono);
578
- font-size: 10px;
579
- line-height: 16px;
580
- }
581
-
582
- .debug-meter-row {
583
- display: flex;
584
- flex-wrap: wrap;
585
- align-items: center;
586
- gap: 8px;
587
- }
588
- .debug-meter {
589
- display: flex;
590
- min-height: 18px;
591
- flex-wrap: wrap;
592
- align-items: center;
593
- gap: 3px;
594
- }
595
- .debug-slot {
596
- display: inline-flex;
597
- min-width: 32px;
598
- height: 18px;
599
- box-sizing: border-box;
600
- align-items: center;
601
- justify-content: center;
602
- border-radius: 3px;
603
- }
604
- .debug-slot.is-empty {
605
- border: 1px dotted var(--border);
606
- }
607
- .debug-meter.is-inline .debug-slot {
608
- min-width: 0;
609
- height: 16px;
610
- }
611
- .debug-meter-overflow {
612
- margin-left: 2px;
613
- font-family: var(--font-mono);
614
- font-size: 11px;
615
- }
616
-
617
- .debug-spark {
618
- display: inline-flex;
619
- width: 120px;
620
- height: 15px;
621
- }
622
- .debug-spark svg {
623
- display: block;
624
- }
625
- .debug-bar {
626
- position: relative;
627
- display: inline-block;
628
- flex-shrink: 0;
629
- overflow: hidden;
630
- border-radius: 2px;
631
- background: var(--border);
632
- vertical-align: middle;
633
- }
634
- .debug-bar-fill {
635
- position: absolute;
636
- top: 0;
637
- bottom: 0;
638
- left: 0;
639
- background: currentColor;
640
- }
641
- .debug-bar-notch {
642
- position: absolute;
643
- top: 0;
644
- bottom: 0;
645
- width: 1px;
646
- background: var(--bg-panel);
647
- }
648
- .debug-dot {
649
- display: inline-block;
650
- width: 8px;
651
- height: 8px;
652
- flex-shrink: 0;
653
- border-radius: 50%;
654
- background: currentColor;
655
- }
656
- .debug-dot.is-ring {
657
- background: transparent;
658
- box-shadow: inset 0 0 0 1.5px currentColor;
659
- }
660
-
661
- .debug-status {
662
- display: inline-flex;
663
- width: 14px;
664
- height: 14px;
665
- flex-shrink: 0;
666
- align-items: center;
667
- justify-content: center;
668
- }
669
- .debug-status-ring {
670
- width: 7px;
671
- height: 7px;
672
- box-sizing: border-box;
673
- border: 1.5px solid var(--text-dim);
674
- border-radius: 50%;
675
- }
676
- .debug-status-ring.is-closing {
677
- border-style: dashed;
678
- border-color: var(--dbg-warn);
679
- }
680
- .debug-status-ring.is-none {
681
- border-style: dotted;
682
- border-color: var(--text-dim);
683
- }
684
- .debug-status-ring.is-starting {
685
- border-style: dashed;
686
- }
687
-
688
- /* The chat's details under its row, from the title's edge; the row's tint carried down. */
689
- .debug-detail {
690
- display: flex;
691
- min-width: 0;
692
- flex-direction: column;
693
- gap: 4px;
694
- margin-bottom: 2px;
695
- padding: 0 4px 5px 24px;
696
- border-radius: 0 0 4px 4px;
697
- background: var(--bg-selected);
698
- }
699
- .debug-detail-line {
700
- display: flex;
701
- min-width: 0;
702
- flex-wrap: wrap;
703
- align-items: center;
704
- gap: 2px 6px;
705
- }
706
- .debug-detail-id,
707
- .debug-starts {
708
- color: var(--text-dim);
709
- font-family: var(--font-mono);
710
- font-size: 11px;
711
- }
712
- .debug-idle-row {
713
- display: flex;
714
- flex-wrap: wrap;
715
- align-items: center;
716
- gap: 4px 8px;
717
- }
718
- .debug-subhead {
719
- display: flex;
720
- align-items: center;
721
- gap: 6px;
722
- color: var(--text);
723
- font-size: 11px;
724
- font-weight: 700;
725
- }
726
- .debug-panel .debug-subhead.is-dim {
727
- color: var(--text-dim);
728
- }
729
- .debug-run-line {
730
- display: flex;
731
- flex-wrap: wrap;
732
- align-items: center;
733
- gap: 2px 6px;
734
- }
735
- .debug-run-icon {
736
- display: inline-flex;
737
- width: 12px;
738
- height: 12px;
739
- flex-shrink: 0;
740
- align-items: center;
741
- justify-content: center;
742
- }
743
- .debug-run-icon svg {
744
- width: 12px;
745
- height: 12px;
746
- }
747
- .debug-run-name {
748
- min-width: 0;
749
- overflow: hidden;
750
- color: var(--text);
751
- font-size: 12px;
752
- text-overflow: ellipsis;
753
- white-space: nowrap;
754
- }
755
- .debug-pills {
756
- display: flex;
757
- flex-wrap: wrap;
758
- align-items: center;
759
- gap: 4px 10px;
760
- }
761
- .debug-pill {
762
- display: inline-flex;
763
- align-items: center;
764
- gap: 4px;
765
- font-size: 11px;
766
- }
767
- .debug-pill-state {
768
- color: var(--text-dim);
769
- white-space: nowrap;
770
- }
771
-
772
- .debug-group {
773
- display: flex;
774
- flex-direction: column;
775
- }
776
- .debug-group-head {
777
- display: flex;
778
- min-height: 22px;
779
- align-items: center;
780
- gap: 5px;
781
- color: var(--text-dim);
782
- font-size: 11px;
783
- }
784
- .debug-group-head svg {
785
- flex-shrink: 0;
786
- }
787
- .debug-group-name {
788
- min-width: 0;
789
- overflow: hidden;
790
- font-weight: 600;
791
- text-overflow: ellipsis;
792
- white-space: nowrap;
793
- }
794
- .debug-group-count {
795
- font-family: var(--font-mono);
796
- font-size: 10px;
797
- font-variant-numeric: tabular-nums;
798
- }
799
- .debug-row {
800
- display: grid;
801
- min-height: 24px;
802
- /* The title keeps room for a few characters; the badges wrap before they take it all. */
803
- grid-template-columns: 14px minmax(96px, 1fr) auto 104px;
804
- align-items: center;
805
- column-gap: 6px;
806
- padding: 0 4px;
807
- border-radius: 4px;
808
- }
809
- .debug-row.debug-list-head {
810
- min-height: 18px;
811
- color: var(--text-dim);
812
- font-size: 10px;
813
- }
814
- /* At the end of their columns, spilling left rather than out of the row when wider. */
815
- .debug-list-head-holders,
816
- .debug-list-head-idle {
817
- justify-self: end;
818
- white-space: nowrap;
819
- }
820
- .debug-row.is-current {
821
- position: relative;
822
- background: var(--bg-selected);
823
- }
824
- .debug-row.has-detail {
825
- border-radius: 4px 4px 0 0;
826
- }
827
- /* The sidebar's mark of the selected session (app/sidebar.css): a short bar on the left edge,
828
- on the first line however many lines the row takes. */
829
- .debug-row.is-current::before {
830
- content: "";
831
- position: absolute;
832
- top: 5px;
833
- left: 0;
834
- width: 3px;
835
- height: 14px;
836
- border-radius: 0 2px 2px 0;
837
- background: var(--accent);
838
- }
839
- .debug-row-status {
840
- display: inline-flex;
841
- width: 14px;
842
- justify-content: center;
843
- }
844
- .debug-row-title {
845
- position: relative;
846
- display: flex;
847
- min-width: 0;
848
- align-items: center;
849
- gap: 4px;
850
- }
851
- .debug-row.is-sub .debug-row-title {
852
- padding-left: 16px;
853
- }
854
- .debug-row-branch {
855
- position: absolute;
856
- top: calc(50% - 8px);
857
- left: 4px;
858
- width: 8px;
859
- height: 8px;
860
- border-bottom: 1px solid var(--border);
861
- border-left: 1px solid var(--border);
862
- }
863
- .debug-row-name {
864
- min-width: 0;
865
- overflow: hidden;
866
- color: var(--text);
867
- font-size: 12px;
868
- text-overflow: ellipsis;
869
- white-space: nowrap;
870
- }
871
- .debug-row.is-sub .debug-row-name {
872
- color: var(--text-muted);
873
- }
874
- .debug-row.is-current .debug-row-name {
875
- font-weight: 600;
876
- }
877
- .debug-row.is-placeholder .debug-row-name {
878
- color: var(--text-dim);
879
- }
880
- .debug-row-starts {
881
- flex-shrink: 0;
882
- color: var(--text-dim);
883
- font-family: var(--font-mono);
884
- font-size: 10px;
885
- }
886
- .debug-row-badges {
887
- display: flex;
888
- min-width: 0;
889
- flex-wrap: wrap;
890
- justify-content: flex-end;
891
- align-items: center;
892
- gap: 3px 8px;
893
- }
894
- .debug-row-idle {
895
- display: flex;
896
- align-items: center;
897
- justify-content: flex-end;
898
- gap: 4px;
899
- }
900
- .debug-row-forced {
901
- width: 6px;
902
- height: 6px;
903
- flex-shrink: 0;
904
- border-radius: 1px;
905
- background: currentColor;
906
- }
907
- .debug-row-idle-text {
908
- min-width: 3ch;
909
- font-family: var(--font-mono);
910
- font-size: 11px;
911
- font-variant-numeric: tabular-nums;
912
- text-align: right;
913
- }
914
-
915
- /* The server's totals beside its title. */
916
- .debug-server-head {
917
- flex-wrap: wrap;
918
- gap: 4px 14px;
919
- color: var(--text-dim);
920
- font-size: 11px;
921
- }
922
- .debug-server-item {
923
- display: inline-flex;
924
- flex-wrap: wrap;
925
- align-items: center;
926
- gap: 3px 4px;
927
- }
928
-
929
- /* Narrower: the sessions under the server's pages, one border down both; the page's column
930
- beside them, its height going to the sessions' row rather than opening a gap under the pages. */
931
- @container debug-panel (max-width: 1239px) {
932
- .debug-cols {
933
- grid-template-areas: "page server" "page sessions";
934
- grid-template-columns: minmax(320px, max-content) minmax(0, 560px);
935
- grid-template-rows: auto 1fr;
936
- }
937
- .debug-col-sessions {
938
- padding-top: 10px;
939
- }
940
- }
941
- @container debug-panel (max-width: 760px) {
942
- .debug-cols {
943
- grid-template-areas: "page" "server" "sessions";
944
- grid-template-columns: minmax(0, 1fr);
945
- grid-template-rows: none;
946
- }
947
- .debug-col-server {
948
- margin-top: 10px;
949
- padding-top: 10px;
950
- border-top: 1px solid var(--border);
951
- }
952
- .debug-col-server,
953
- .debug-col-sessions {
954
- margin-left: 0;
955
- padding-left: 0;
956
- border-left: 0;
957
- }
958
- }
959
- @container debug-panel (max-width: 520px) {
960
- .debug-detail-id {
961
- display: none;
962
- }
963
- .debug-row {
964
- grid-template-columns: 14px minmax(0, 1fr) 64px;
965
- }
966
- /* The badges take a line of their own under the title, which keeps its width. */
967
- .debug-row-badges {
968
- grid-column: 2 / -1;
969
- grid-row: 2;
970
- flex-wrap: wrap;
971
- justify-content: flex-start;
972
- padding-bottom: 4px;
973
- }
974
- .debug-row.is-sub .debug-row-badges {
975
- padding-left: 16px;
976
- }
977
- .debug-row-badges:empty,
978
- .debug-list-head-holders,
979
- .debug-page-holder {
980
- display: none;
981
- }
982
- .debug-page-row {
983
- grid-template-columns: 30px minmax(0, 1fr) minmax(0, 1fr) 24px;
984
- }
985
- .debug-row-idle-bar {
986
- display: none;
987
- }
988
- .debug-server-head .debug-section-title {
989
- flex-basis: 100%;
990
- }
991
- }
992
- `;function mI(e){let{sessionId:t,running:n,...s}=e,{t:a}=(0,eW.s)(),[o,l]=(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?l(a.info):c("error")}catch(e){e instanceof Error&&"AbortError"===e.name||c("error")}};return i(),()=>{r.abort(),clearTimeout(e)}},[t,n]),o)?(0,r.jsx)(iZ,{...s,session:o,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 m$=n(60956);class mE{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 mT{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 mM=new mE(-1,"__missing_parent__"),mR=["#4f8cff","#f59e0b","#10b981","#ef4444","#a855f7","#d9a814"];function mA(e){return e.slice(0,7)}function mL(e){let{cwd:t,refreshKey:n=0}=e,{t:s,locale:a}=(0,eW.s)(),[o,l]=(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),j=(0,i.useRef)(!1),k=(0,i.useRef)(0),w=(0,i.useCallback)(async e=>{let n=new URLSearchParams({cwd:t,skip:String(e),maxCount:String(50)}),r=++k.current,i=await fetch(`/api/git/graph?${n.toString()}`);if(!i.ok){let e=await i.json().catch(()=>null);throw Error(e?.error??`HTTP ${i.status}`)}let s=await i.json();return r===k.current?s:null},[t]);(0,i.useEffect)(()=>{let e=!1;return(async()=>{c(!0),f(null);try{let t=await w(0);!e&&t&&(l(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&&(l(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(!j.current&&o.hasMore){j.current=!0,p(!0),f(null);try{let e=await w(o.commits.length);e&&l(t=>({commits:[...t.commits,...e.commits],hasMore:e.hasMore}))}catch(e){f(e instanceof Error?e.message:String(e))}finally{j.current=!1,p(!1)}}},[w,o.commits.length,o.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,o=function(e){let t=e.map((e,t)=>new mE(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)??mM);return t}(e),l=[],d=[];for(let e=0;e<o.length;){let t=o[e],n=t.nextParent();if(null===n&&t.isOnBranch()){e++;continue}if(n===mM){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],o=a.connectionTo(t,r),l=null!==o,d=o??a.nextPoint();if(r.addLine(i,d,e.hash,t.hash,l||i.laneIndex<d.laneIndex),a.reservePoint(d.laneIndex,t,r),i=d,l){e.markParentProcessed();break}}}(t,n,o):function(e,t,n,r){let i,s=t[e],a=s.nextParent(),o=s.isOnBranch()?s.point():s.nextPoint(),l=new mT((i=r.findIndex(t=>t<e))>=0?i:(r.push(0),r.length-1));s.joinBranch(l,o.laneIndex),s.reservePoint(o.laneIndex,s,l);let d=e+1;for(;d<t.length&&null!==a&&a!==mM;d++){let e=t[d],n=a===e&&e.isOnBranch()?e.point():e.nextPoint();if(l.addLine(o,n,s.hash,a.hash,o.laneIndex<n.laneIndex),e.reservePoint(n.laneIndex,a,l),o=n,a===e){s.markParentProcessed();let t=e.isOnBranch();if(e.joinBranch(l,n.laneIndex),(a=(s=e).nextParent())===mM){s.markParentProcessed();break}if(null===a||t)break}}l.endRowIndex=Math.min(d,t.length),n.push(l),r[l.colorIndex]=l.endRowIndex}(e,o,l,d)}let c=e=>i+e*r,u=e=>s+e*n,p=o.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 o)m=Math.max(m,e.widestLaneIndex());for(let e of l)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}})(o.commits),[o.commits]),I=(0,i.useMemo)(()=>new Intl.DateTimeFormat(a,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}),[a]),$=(0,i.useMemo)(()=>o.commits.find(e=>e.hash===x)??null,[o.commits,x]),E=Math.max(N.width+12,56),T=`${E}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")}),o.commits.length>0&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s(o.hasMore?"gitGraph.subtitlePartial":"gitGraph.subtitle",{count:o.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===o.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:E,height:N.height+N.rowHeight,viewBox:`0 0 ${E} ${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:mR[e.colorIndex%mR.length],strokeWidth:2,opacity:n?.25:t?1:.6},e.id)}),N.rows.map(e=>{let t=e.commit.hash===x,n=mR[e.laneIndex%mR.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":`${mA(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)(mP,{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||mA(t.hash)}),t.parents.length>1&&(0,r.jsx)(mz,{})]}),(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:mA(t.hash)})]},t.hash)})]}),o.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")})})]}),$&&(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:$.subject||mA($.hash)}),$.refs.length>0&&(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:3,marginTop:4},children:$.refs.map(e=>(0,r.jsx)(mP,{gitRef: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:mA($.hash)})]}),(0,r.jsxs)("span",{children:[s("gitGraph.detailAuthor"),": ",(0,r.jsx)("span",{style:{color:"var(--text)"},children:$.authorName??"—"})]}),(0,r.jsxs)("span",{children:[s("gitGraph.detailDate"),":"," ",(0,r.jsx)("span",{style:{color:"var(--text)"},children:$.authoredAtMs?new Intl.DateTimeFormat(a,{dateStyle:"medium",timeStyle:"short"}).format(new Date($.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:$.parents.length>0?$.parents.map(mA).join(", "):"—"})]})]})]})]})}function mP(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 mz(){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 mO=n(50335);let mW=e=>`pi-web:side-tabs:${e}`;function mF(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let mD=[48,120,240,420,720];var mB=n(28999);function mH(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document;return"visible"!==e.visibilityState||!e.hasFocus()}async function m_(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 mU="pi-web:tab-open-session";function mq(){try{return window.sessionStorage}catch{return null}}function mK(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 mZ(e,t){t.setItem(mU,JSON.stringify(e))}var mV=n(82831);let mJ="var(--top-bar-height)",mG=new Set(ir.kU);function mY(e){let t=e.at(-1);return t?`agent:${t.sessionId}`:null}function mX(){var e;let t,n,u,x,b,v,y,j,k,w,S,C,N,I=(0,s.useRouter)(),$=(0,s.useSearchParams)(),[E,T]=(0,i.useState)(()=>{let e;return{requestedCwd:e=$.get("cwd")?.trim()||null,sessionId:e?null:$.get("session")||null,sidebarCollapsed:"collapsed"===$.get("sidebar")}});(0,i5.D)(),(0,n4.VE)();let{locale:M,t:R}=(0,eW.s)(),A=(0,eF.a)(),L=(0,eF.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:mF(),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>=mD.length){i=!1;return}let n=mD[e++],a=window.setTimeout(()=>{r.delete(a),s(),t()},n);r.add(a)};t()})()},o=()=>{mF()&&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",o),document.addEventListener("compositionupdate",o),document.addEventListener("compositionend",o),document.addEventListener("input",o),document.addEventListener("keyup",o),()=>{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",o),document.removeEventListener("compositionupdate",o),document.removeEventListener("compositionend",o),document.removeEventListener("input",o),document.removeEventListener("keyup",o),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&&aY(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),o=(0,i.useRef)(0),l=(0,i.useRef)(void 0),d=(0,i.useCallback)(e=>{clearTimeout(l.current),l.current=setTimeout(()=>{0===a.current&&0===o.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(o.current++,clearTimeout(l.current),n.current){let e=s();e&&"running"!==e.state&&c(e,()=>{})}let e=!1;return()=>{!e&&(e=!0,o.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),[q,K]=(0,i.useState)(new Set),Z=(0,i.useCallback)(()=>{D.current&&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)(()=>{var e;return(e=V?.id)?d(en).find(t=>t.root.id===e||t.subagents.some(t=>t.id===e))??null:null},[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)},[]),eo=er?(t=c(e=er.subagents,ei))>0?{count:t,running:!0}:{count:e.length,running:!1}:null,el=eo?.running?R("agentSwitcher.titleRunning",{count:eo.count}):R("agentSwitcher.title"),[ed,ec]=(0,i.useState)(null),[eu,ep]=(0,i.useState)("initial"),eh=(0,i.useRef)(null),em=(0,i.useRef)(null),[eg,ef]=(0,i.useState)(null),ex=(0,i.useRef)(null),eb=(0,i.useCallback)(e=>{e&&e.cwd===ex.current?.cwd&&(ex.current=null),ef(e)},[]),ev=(0,i.useRef)(null),ey=(0,i.useRef)(null),[ej,ek]=(0,i.useState)(null),ew=(0,i.useCallback)(e=>{ey.current=e,ek(null)},[]),[eS,eI]=(0,i.useState)(()=>E.requestedCwd?"validating":"idle"),[e$,eE]=(0,i.useState)(null),[eT,eM]=(0,i.useState)(0),[eR,eA]=(0,i.useState)(0),eL=(0,i.useRef)(new Map),eP=(0,i.useCallback)((e,t)=>{eL.current.set(e,t)},[]),[ez,eO]=(0,i.useState)(null),eB=(0,i.useCallback)(e=>{eO(t=>t===e?null:t)},[]),[eH,e_]=(0,i.useState)(0),[eU,eq]=(0,i.useState)(null),[eK,eZ]=(0,i.useState)(!1),[eV,eJ]=(0,i.useState)(0),[eG,eY]=(0,i.useState)(null),[eX,eQ]=(0,i.useState)(!1),[e0,e1]=(0,i.useState)(!1),[e2,e4]=(0,i.useState)(null),[e8,e6]=(0,i.useState)(()=>!E.sidebarCollapsed),e5=(0,i.useRef)(!E.sidebarCollapsed),[e9,e7]=(0,i.useState)(!1),[te,tt]=(0,i.useState)(!1),tn=e9&&te&&!A;(0,i.useEffect)(()=>{(!e9||A)&&tt(!1)},[e9,A]);let[tr,ti]=(0,i.useState)(!1),ts=tr?R("chat.close"):R("chat.moreControls"),[ta,to]=(0,i.useState)(!1),tl=(0,i.useRef)(mV.Qw),td=(0,i.useRef)(mV.MH),tc=(0,i.useCallback)(()=>(0,mV.YZ)(window.innerWidth),[]),tu=(0,i.useCallback)(()=>(0,mV.VX)({viewportWidth:window.innerWidth,rightPanelOpen:e9,rightPanelWidth:td.current}),[e9]),tp=(0,i.useCallback)(()=>(0,mV.NC)({viewportWidth:window.innerWidth,sidebarOpen:e8,sidebarWidth:tl.current}),[e8]),th=(0,eD.T)({ariaLabel:R("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:mV.Qw,getMaxWidth:tu,growthDirection:"right",maxWidth:mV.vd,minWidth:mV.hh,storageKey:"pi-sidebar-width",widthRef:tl}),tm=(0,eD.T)({ariaLabel:R("layout.resizeFilePanel"),cssVariable:"--right-panel-width",defaultWidth:mV.MH,getDefaultWidth:tc,getMaxWidth:tp,growthDirection:"left",maxWidth:mV.QA,minWidth:mV.I9,storageKey:"pi-right-panel-width",widthRef:td}),tg=th.reclampWidth,tf=tm.reclampWidth;(0,i.useEffect)(()=>{e6(!A&&e5.current)},[A]),(0,i.useEffect)(()=>{to(!0)},[]),(0,i.useEffect)(()=>{e9&&(tg(),tf())},[tf,tg,e9]);let tx=(0,i.useRef)(null),[tb,tv]=(0,i.useState)({}),ty=(0,i.useRef)(null),tj=(0,i.useRef)(null),[tk,tw]=(0,i.useState)([]),[tS,tC]=(0,i.useState)(null),[tN,tI]=(0,i.useState)(!1),t$=(0,i.useRef)(null),tE=p8(tk),tT=(0,i.useCallback)((e,t,n,r)=>{tw(e),tC(t),tI(r),t$.current=n},[]),tM=(0,i.useCallback)(e=>{t$.current?.(e)},[]),[tR,tA]=(0,i.useState)(null),[tL,tP]=(0,i.useState)(null),[tz,tO]=(0,i.useState)(!1),tW=(0,i.useRef)(null),tF=(0,i.useRef)(0),tD=(0,i.useRef)(null),tB=(0,i.useCallback)(e=>{tA(e),tO(!1)},[]),tH=(0,i.useCallback)(e=>{tP(e)},[]),t_=(0,i.useCallback)(e=>{tF.current+=1,tW.current=e,tO(!1)},[]),tU=(0,i.useRef)(null),tq=(0,i.useCallback)(e=>{tU.current=e},[]);(0,i.useEffect)(()=>{(0,eN.t0)()},[]);let[tK,tZ]=(0,i.useState)(null),[tV,tJ]=(0,i.useState)({kind:"idle"}),tG=(0,i.useRef)(null),tY=(0,i.useRef)(V?.id??null);tY.current=V?.id??null;let tX=(0,i.useCallback)(e=>{tZ(e)},[]),[tQ,t0]=(0,i.useState)(null),t1=(0,i.useRef)(null),t4=(0,i.useCallback)((e,t)=>{(0,e3.D)(t).then(()=>{t1.current&&clearTimeout(t1.current),t0(e),t1.current=setTimeout(()=>t0(null),1400)})},[]);(0,i.useEffect)(()=>()=>{t1.current&&clearTimeout(t1.current),tG.current&&clearTimeout(tG.current)},[]);let[t8,t6]=(0,i.useState)(null),t3=(0,i.useCallback)(e=>{t6(e)},[]),[t5,t9]=(0,i.useState)(null),[t7,ne]=(0,i.useState)(null);(0,i.useEffect)(()=>{tE||t9(e=>"branches"===e?null:e)},[tE]),(0,i.useEffect)(()=>{er||t9(e=>"agents"===e?null:e)},[er]),(0,i.useEffect)(()=>{tn&&t9(null)},[tn]);let nt=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];A&&e6(!1),t9(t=>t===e?null:e),A&&L&&t&&ti(!0)},[A,L]),nn=(0,i.useRef)(null),nr=(0,i.useCallback)(e=>{t9(e=>"debug"===e?null:e),e&&requestAnimationFrame(()=>eC(document,nn.current))},[]),ni=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=t5!==e;if(nt(e,t),!n||tz)return;let r=tW.current;if(!r)return;let i=++tF.current;tO(!0),r().catch(e=>{console.error("Failed to load system information:",e)}).finally(()=>{tF.current===i&&tO(!1)})},[t5,tz,nt]),ns=(0,i.useCallback)(()=>{A&&e6(!1),ti(!1),t9("session")},[A]),na=(0,i.useCallback)(e=>{eZ(!1),eq(e)},[]),no=(0,i.useCallback)(()=>{A&&(t9(null),ti(!1)),e6(e=>{let t=!e;return A||(e5.current=t),t})},[A]),nl=(0,i.useCallback)(()=>{e6(!1),t9(null),ti(e=>!e)},[]),nd=(0,i.useCallback)(()=>{A&&(e6(!1),t9(null),ti(!1)),e7(e=>!e)},[A]),nc=(0,i.useCallback)(()=>{t9(null),tt(e=>!e)},[]);(0,i.useEffect)(()=>{if(!tr)return;let e=e=>{let t=tj.current;t&&e.composedPath().includes(t)||ti(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),ti(!1))};return document.addEventListener("pointerdown",e,!0),document.addEventListener("keydown",t,!0),()=>{document.removeEventListener("pointerdown",e,!0),document.removeEventListener("keydown",t,!0)}},[tr]),(0,i.useEffect)(()=>{ti(!1)},[A,L,V?.id,eu]),(0,i.useEffect)(()=>{if(!t5||!ty.current)return;let e=()=>{let e=ty.current.getBoundingClientRect();"agents"===t5?ne({top:e.bottom,left:e.left,width:Math.min(420,e.width)}):ne({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(ty.current),()=>t.disconnect()},[t5,A]);let[nu,np]=(0,i.useState)([]),[nh,nm]=(0,i.useState)(null),ng=(0,i.useRef)(new Map),[nf,nx]=(0,i.useState)(0),nb=(0,i.useRef)(0),[nv,ny]=(0,i.useState)([]),[nj,nk]=(0,i.useState)([]),[nw,nS]=(0,i.useState)(!1),[nC,nN]=(0,i.useState)([]),nI=(0,i.useRef)(null),nE=(0,i.useRef)(!1),nT=(0,i.useRef)(!1),[nR,nA]=(0,i.useState)(null),nL=(0,i.useRef)(null),[nP,nz]=(0,i.useState)([]),nF=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()]}([...nu,...nv.map(e=>({id:e.id,label:(0,mB.WP)(e.cwd)||e.cwd,filePath:e.cwd,kind:"terminal",closing:!!e.closing})),...nj.map(e=>({id:`git-graph:${e}`,label:(0,mB.WP)(e)||e,filePath:e,kind:"git-graph"})),...nC.map(e=>{let t=e.side?Y.find(t=>t.id===e.sessionId):void 0,n=t?o(t,R("agentSwitcher.sideChat"),er?.subagents??[]):e.label;return{id:`agent:${e.sessionId}`,label:n,filePath:n,kind:e.side?"side":"agent"}})],nP),nD=nF.map(e=>e.id).join("\n");(0,i.useEffect)(()=>{let e=new Set(nD.split("\n"));nz(t=>t.every(t=>e.has(t))?t:t.filter(t=>e.has(t)))},[nD]),(0,i.useEffect)(()=>{try{let e=(0,mO.PT)(window.sessionStorage.getItem(mO.WT));ny(e.tabs),e.activeId&&(nm(e.activeId),e7(e.open))}catch{}nS(!0)},[]),(0,i.useEffect)(()=>{if(nw)try{window.sessionStorage.setItem(mO.WT,JSON.stringify({tabs:nv.map(e=>{let{id:t,cwd:n}=e;return{id:t,cwd:n}}),activeId:nh,open:e9}))}catch{}},[nv,nh,e9,nw]);let nB=(0,i.useCallback)(e=>{try{let t=nC.filter(e=>e.side);if(!t.length)return void window.sessionStorage.removeItem(mW(e));window.sessionStorage.setItem(mW(e),JSON.stringify({tabs:t,activeId:t.some(e=>`agent:${e.sessionId}`===nh)?nh:null,open:e9}))}catch{}},[nC,nh,e9]),nH=(0,i.useCallback)((e,t,n,r)=>{e!==nb.current?(0,i3.K1)(ng.current,e,t,n,r):np(e=>(0,i3.ZS)(e,t,n,r))},[]),n_=(0,i.useCallback)((e,t)=>{if(e===t)return;let n=nh?.startsWith("file:")?nh:null,r=(0,i3.G_)(ng.current,e,t,{tabs:nu,activeTabId:n,open:e9&&!!n},nb.current);nb.current+=1,nx(nb.current),np(r.tabs),nN(e=>e.filter(e=>e.side)),nE.current&&nI.current&&(nB(nI.current),nT.current=!0),nk([]),(!nh||n||nh.startsWith("agent:")||nh.startsWith("git-graph:"))&&(nm(r.activeTabId),e7(r.open))},[nh,nu,nB,e9]),nU=(0,i.useCallback)((e,t)=>{tx.current?.insertText((0,nW.$C)(e,t)),A&&(e7(!1),e6(!1))},[A]),nq=(0,i.useCallback)(e=>{let t=(0,nW.SO)(e);t&&tx.current?.insertText(t),A&&(e7(!1),e6(!1))},[A]),nK=(0,i.useCallback)((e,t,n)=>{tx.current?.insertText((0,nW.sn)(e,t,n)),A&&(e7(!1),e6(!1))},[A]),nZ=E.sessionId,nV=E.sessionFromTab?null:E.sessionId,[nJ,nG]=(0,i.useState)(()=>!nZ),nY=er?.root.id??null;(0,i.useEffect)(()=>{if(!Q||!nJ)return;let e=nI.current;if(!nE.current||e!==nY){nE.current&&e&&!nT.current&&nB(e),nT.current=!1,nE.current=!0,nI.current=nY;let t={tabs:[],activeId:null,open:!1};if(nY)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(mW(nY)),nY,Y)}catch{}nN(e=>[...e.filter(e=>!e.side),...t.tabs]);let n=t.activeId===`agent:${V?.id}`?null:t.activeId;(n||nh?.startsWith("agent:")||!nh)&&(nm(n??nu.at(-1)?.id??nv.at(-1)?.id??null),e7(n?t.open:!!(nu.length||nv.length)&&e9));return}nY&&nB(nY),nT.current=!1},[nh,Q,nu,nJ,nB,e9,V?.id,Y,nY,nv]),(0,i.useLayoutEffect)(()=>{var e;let t=(e=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:mq();if(!e)return null;try{return mK(e.getItem(mU))}catch{return null}}(),E.requestedCwd||E.sessionId||!e?E:"session"===e.kind?{...E,sessionId:e.sessionId,sessionFromTab:!0}:{...E,requestedCwd:e.cwd});t!==E&&(T(t),t.sessionId&&nG(!1))},[E]);let nX=(0,i.useRef)(!1),nQ=(0,i.useRef)(!1),n0=(0,i.useRef)(0),n1=(0,i.useCallback)(()=>{n0.current+=1},[]);(0,i.useEffect)(()=>{if(V){!function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:h();if(n)try{let r=m(n);r[e]=t,n.setItem(p,JSON.stringify(r))}catch{}}(V.projectKey??nL.current??f(V),V.id),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mq();if(t&&e)try{mZ({kind:"session",sessionId:e},t)}catch{}}(V.id);return}ed&&function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mq(),n=e.trim();if(t&&n)try{mZ({kind:"new",cwd:n},t)}catch{}}(ed)},[ed,V]),(0,i.useEffect)(()=>{let e=E.requestedCwd;if(!e)return;let t=new AbortController;return eI("validating"),eE(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}`);nX.current=!0;let r=`initial:${e}`;ep(r),eh.current=`new:${r}:${n.cwd}`,ec(n.cwd),eI("ready"),new URLSearchParams(window.location.search).get("cwd")||I.replace(`?cwd=${encodeURIComponent(n.cwd)}`,{scroll:!1})}).catch(e=>{t.signal.aborted||(eE(e instanceof Error?e.message:String(e)),eI("error"))}),()=>t.abort()},[E,I]);let n2=(0,i.useCallback)((e,t)=>{let n=++n0.current,r=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:h();if(!t)return null;try{let n=m(t)[e];return"string"==typeof n&&n.length>0?n:null}catch{return null}}(e);if(!r)return;let i=i=>{if(n!==n0.current)return;let s=i?.sessions.find(e=>e.id===r);if(!s){i&&g(e);return}if(f(s)!==e)return void g(e);let a=eh.current;a&&nO(a,n$(t)),eh.current=null,J(s),eA(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]),n8=(0,i.useCallback)((e,t,n)=>{n1();let r=ed??nR;if(nA(e),!e)return;let i=nQ.current;nQ.current=!1;let s=n??t??e,a=nL.current??(V?f(V):null);if(nL.current=s,nX.current){nX.current=!1;return}if(r===e&&a!==s||a===s&&(null!==V||r===e))return;let o=eh.current;o&&r&&nO(o,n$(r));let l="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,d=`new:${l}:${e}`;nO(n$(e),d),ep(l),eh.current=d,J(null),ec(t=>t&&t!==e?null:t),eA(e=>e+1),tw([]),tC(null),tI(!1),tA(null),tP(null),tO(!1),t9(e=>"debug"===e?e:null),a!==s&&(n_(a,s),i||n2(s,e)),I.replace(window.location.pathname,{scroll:!1})},[nR,n_,n1,ed,I,V,n2]),n6=(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;eO(n?{sessionId:e.id,entryId:n,blockIndex:r}:null),n1();let s=eh.current,a=ed??(null===V?nR:null);s&&a&&nO(s,n$(a)),eh.current=null;let o=f(e);if(nL.current!==o&&(n_(nL.current,o),t9(e=>"debug"===e?e:null)),nL.current=o,!t&&V){let t=f(V)===f(e);if(V.id===e.id&&t){A&&e6(!1);return}}ec(null),J(e),eA(e=>e+1),tw([]),tC(null),tI(!1),t$.current=null,tA(null),tP(null),tO(!1),nG(!0),!A||t||i?.keepSidebarOpen||e6(!1),t&&(nX.current=!0),t&&new URLSearchParams(window.location.search).get("session")===e.id||I.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[nR,n_,n1,I,A,ed,V]),n3=(0,i.useCallback)((e,t,n,r)=>{n1();let i=`new:${e}:${t}`,s=eh.current,a=ed??(null===V?nR:null);if(r?.carryComposer&&null===V&&s){let e=tx.current;e?e.rekeyDraft(s,i):nO(s,i),ek(ey.current)}else s&&a&&a!==t&&nO(s,n$(a));let o=n??(t===nR?nL.current:null)??t;nL.current!==o&&n_(nL.current,o),nL.current=o,nM(i)||nO(n$(t),i),eh.current=i,ep(e),J(null),ec(t),eA(e=>e+1),tw([]),tC(null),tI(!1),tA(null),tP(null),tO(!1),t9(e=>"debug"===e?e:null),A&&e6(!1),I.replace(`?cwd=${encodeURIComponent(t)}`,{scroll:!1}),A||ev.current||requestAnimationFrame(()=>{document.activeElement?.closest("[aria-modal='true']")||tx.current?.focus()})},[nR,n_,n1,A,ed,I,V]);!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:e=>n3(`kb-${Date.now()}`,e),activeCwd:nR});let n5=(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(()=>{})},[]),n9=(0,i.useCallback)((e,t)=>{eM(e=>e+1),eh.current===t&&(n1(),eh.current=null,ec(null),J(e),n5(e.id),I.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1}))},[n1,I,n5]),n7=(0,i.useCallback)(e=>{let{targetSession:t,title:n,body:r,tag:i}=e;if(!("Notification"in window))return;let s=()=>{m_({title:n,body:r,sessionUrl:t?`/?session=${encodeURIComponent(t.id)}`:"/",tag:i,onClick:()=>{window.focus(),t&&n6(t)}})};"granted"===Notification.permission?(s(),aY(M)):"default"===Notification.permission&&Notification.requestPermission().then(e=>{"granted"===e&&(s(),aY(M))})},[n6,M]),re=(0,i.useCallback)(e=>{eM(e=>e+1),e_(e=>e+1),e.aborted||e.subagentsActive||l(V?.relation)||!mH()||(V&&K(e=>{if(e.has(V.id))return e;let t=new Set(e);return t.add(V.id),t}),n7({targetSession:V,title:V?.name??R("i18n.sessionComplete"),body:R("i18n.taskFinished"),tag:V?`pi-session-complete:${V.id}`:"pi-session-complete"}))},[n7,V,R]);(0,i.useEffect)(()=>{let e=()=>{"visible"===document.visibilityState&&document.hasFocus()&&K(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 rt=(0,i.useCallback)(e=>{var t;!l(V?.relation)&&mH()&&(t=U.current,!(!rZ(e)||t.has(e.id))&&(t.add(e.id),1)&&n7({targetSession:V,title:R("i18n.attentionNeeded"),body:"custom"===e.method?R("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[n7,V,R]),rn=(0,i.useCallback)(async()=>{let e=V?.id;if(e&&"naming"!==tV.kind){tG.current&&clearTimeout(tG.current),t9(null),tJ({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(eM(e=>e+1),tY.current!==e)return;J(t=>t?.id===e?{...t,name:r}:t),tZ(t=>t?.sessionId===e?{...t,sessionName:r}:t),tJ({kind:"success"}),tG.current=setTimeout(()=>tJ({kind:"idle"}),1800)}catch(t){if(tY.current!==e)return;tJ({kind:"error",message:t instanceof Error?t.message:String(t)}),tG.current=setTimeout(()=>tJ({kind:"idle"}),5e3)}}},[tV.kind,V?.id]);(0,i.useEffect)(()=>{tG.current&&clearTimeout(tG.current),tJ({kind:"idle"})},[V?.id]);let rr=(0,i.useCallback)(()=>{e_(e=>e+1)},[]),ri=(0,i.useRef)(null),rs=(0,i.useCallback)(e=>{mG.has(e)||ri.current||(ri.current=setTimeout(()=>{ri.current=null,e_(e=>e+1)},1e3))},[]);(0,i.useEffect)(()=>()=>{ri.current&&clearTimeout(ri.current)},[]);let ra=(0,i.useCallback)(e=>{n1(),eh.current=null,eM(e=>e+1),eA(e=>e+1),ec(null),J(t=>({...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1})),n5(e),I.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1})},[n1,I,n5]),ro=(0,i.useCallback)(()=>{nG(!0),nV&&(nQ.current=!0)},[nV]),rl=(0,i.useCallback)(e=>{n1(),eM(e=>e+1);let t=G.current;if(t?.id===e){!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mq();if(t&&e)try{let n=mK(t.getItem(mU));if(n?.kind!=="session"||n.sessionId!==e)return;t.removeItem(mU)}catch{}}(e);let n=t.cwd,r="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;ep(r),eh.current=n?`new:${r}:${n}`:null,J(null),ec(n??null),eA(e=>e+1),tw([]),tC(null),tI(!1),tA(null),tP(null),tO(!1),t9(e=>"debug"===e?e:null),I.replace(n?`?cwd=${encodeURIComponent(n)}`:window.location.pathname,{scroll:!1})}},[n1,I]),rd=(0,i.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,i=n?.modeHint,s=n?.page,a=`file:${e}`;np(n=>(0,i3.cG)(n,{fileName:t,filePath:e,modeHint:i,page:s,sourceSessionId:r,tabId:a})),nm(a),e7(!0),A&&e6(!1)},[A]),rc=(0,i.useCallback)((e,t)=>{rd(e,(0,mB.WP)(e),{sourceSessionId:V?.id??null,page:t})},[rd,V?.id]),ru=(0,i.useCallback)(()=>{let e=new URLSearchParams;nR&&e.set("cwd",nR);let t=nu.find(e=>e.id===nh);t?.filePath&&e.set("path",t.filePath);let n=""!==e.toString()?`?${e.toString()}`:"";window.open(`/files${n}`,"_blank","noopener")},[nR,nh,nu]),rp=(0,i.useCallback)(e=>{let t=nv.find(t=>t.cwd===e),n=t??(0,mO.Wg)(e);t||ny(e=>[...e,n]),nm(n.id),e7(!0),A&&e6(!1)},[nv,A]),rh=(0,i.useCallback)(e=>{nk(t=>t.includes(e)?t:[...t,e]),nm(`git-graph:${e}`),e7(!0),A&&e6(!1)},[A]),rm=(0,i.useCallback)((e,t,n)=>{nN(r=>r.some(t=>t.sessionId===e)?r:[...r,{sessionId:e,label:t,...n?{side:!0}:{}}]),nm(`agent:${e}`),e7(!0),A&&e6(!1)},[A]),rg=(0,i.useMemo)(()=>new Set(e9?nC.map(e=>e.sessionId):[]),[nC,e9]),rf=(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?n6(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}`);n6(n.info)}catch{rm(e,t)}})()},[er,n6,rm]),rx=(0,i.useCallback)((e,t)=>{t&&tv(n=>({...n,[e.id]:t})),X(t=>[e,...t.filter(t=>t.id!==e.id)]);let n=R("agentSwitcher.sideChat"),r=e.relation?.kind==="side"?e.relation.parentSessionId:null;if(r&&r!==nI.current)try{let t=mW(r);window.sessionStorage.setItem(t,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(t),e.id,n))}catch{}else rm(e.id,n,!0);eM(e=>e+1)},[rm,R]),rb=(0,i.useCallback)(async e=>{let t=await r8(e,R);return"error"in t?t.error:(A&&t9(null),rx(t.session,null),null)},[rx,A,R]),rv=nC.filter(e=>e.side&&ei.has(e.sessionId)).map(e=>e.sessionId).join();(0,i.useEffect)(()=>{rv&&eM(e=>e+1)},[rv]);let ry=(0,i.useCallback)(e=>{if(nv.some(t=>t.id===e))return void ny(t=>t.map(t=>t.id!==e||t.closing?t:{...t,closing:"close"}));if(e.startsWith("git-graph:")){let t=nj.filter(t=>`git-graph:${t}`!==e);nk(t),nm(n=>{if(n!==e)return n;let r=t.at(-1);return nu.at(-1)?.id??nv.at(-1)?.id??(void 0!==r?`git-graph:${r}`:null)??mY(nC)}),0===nu.length&&0===nv.length&&0===t.length&&0===nC.length&&e7(!1);return}if(e.startsWith("agent:")){let t=nC.filter(t=>`agent:${t.sessionId}`!==e);nN(t),nm(n=>{if(n!==e)return n;let r=nj.at(-1);return nu.at(-1)?.id??nv.at(-1)?.id??(void 0!==r?`git-graph:${r}`:null)??mY(t)}),0===nu.length&&0===nv.length&&0===nj.length&&0===t.length&&e7(!1);return}np(t=>{let n=t.filter(t=>t.id!==e);return 0===n.length&&0===nv.length&&0===nj.length&&0===nC.length&&e7(!1),n}),nm(t=>{if(t!==e)return t;let n=nu.filter(t=>t.id!==e),r=nj.at(-1);return n.at(-1)?.id??nv.at(-1)?.id??(void 0!==r?`git-graph:${r}`:null)??mY(nC)})},[nu,nv,nj,nC]),rj=(0,i.useCallback)(async(e,t)=>{let n=await r6(e);return n?n.error:(ry(`agent:${e}`),G.current?.id===e?(n6(t),eM(e=>e+1)):rl(e),null)},[ry,n6,rl]),rk=V?.id;(0,i.useEffect)(()=>{nC.some(e=>e.sessionId===rk)&&ry(`agent:${rk}`)},[nC,ry,rk]);let rw=(0,i.useCallback)(()=>{V&&window.open(`/api/sessions/${encodeURIComponent(V.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[V]),rS=ed??(null===V&&nR?nR:null),rC=null===V&&rS?`new:${eu}:${rS}`:null;(0,i.useLayoutEffect)(()=>{eh.current=rC},[rC]);let rN=(0,i.useCallback)((e,t)=>{null===V&&rS&&e.cwd!==rS&&(ev.current=t,e.projectKey&&e.projectRoot&&ex.current?.cwd!==e.cwd&&(ex.current={cwd:e.cwd,project:{key:e.projectKey,root:e.projectRoot},branch:null}),em.current?.startNewSessionIn({...e,carryComposer:!0}))},[rS,V]),rI=(0,i.useRef)(rN);rI.current=rN;let r$=(0,i.useCallback)(e=>{em.current?.openFolderForNewSession(e=>rI.current(e,"project"),e)},[]),rE=(0,i.useCallback)(()=>{em.current?.openDefaultDirectoryForNewSession(e=>rI.current(e,"project"))},[]),rT=(0,i.useCallback)(()=>{em.current?.refreshWorktrees()},[]),rM=(0,i.useCallback)(async(e,t)=>{let n=em.current;if(!n)throw Error("The session sidebar is not mounted");let r=await n.createWorktree(e,t);return"path"in r&&(ex.current={cwd:r.path,project:e,branch:t}),r},[]),rR=(0,i.useCallback)(()=>{ev.current=null},[]),rA=null===V&&rS?(0,r.jsx)(i4,{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}}(eg,rS,ex.current),mobile:A,initialFocus:ev.current,onInitialFocusDone:rR,onPick:rN,onUseDefaultDirectory:rE,onOpenFolder:r$,onRefreshWorktrees:rT,onCreateWorktree:rM}):null,rL=null!==V||null!==rS,rP=V?.cwd??rS,rz=nJ&&!rL;(0,i.useEffect)(()=>{rL||t9(e=>"debug"===e?null:e)},[rL]),(0,i.useEffect)(()=>{if(eY(null),eQ(!1),e4(null),!rP)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(rP)}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);eY(t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[rP]);let rO=(0,i.useCallback)(async()=>{if(rP&&!e0){e1(!0),e4(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:rP})}),t=await e.json();if(!e.ok||t.error)return void e4({error:t.error??`HTTP ${e.status}`,...t.reason?{reason:t.reason}:{}});eY(t),eQ(!1),eJ(e=>e+1),eA(e=>e+1)}catch(e){e4({error:e instanceof Error?e.message:String(e)})}finally{e1(!1)}}},[e0,rP]),rW=(0,i.useCallback)(()=>{e4(null),eQ(!0)},[]),rF=(0,i.useCallback)((e,t)=>{e===rP&&eY(t)},[rP]),rD=nu.find(e=>e.id===nh)??null,rB=nC.find(e=>`agent:${e.sessionId}`===nh)??null,rH=nh?.startsWith("git-graph:")?nj.find(e=>`git-graph:${e}`===nh)??null:null,r_=nR?(0,mB.WP)(nR)||nR:null,rU=r_?`${r_} - Pi Web`:"Pi Web";(0,i.useEffect)(()=>{let e=()=>{document.title!==rU&&(document.title=rU)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[rU]);let rq=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(t2,{selectedSessionId:V?.id??null,onSelectSession:n6,onNewSession:n3,controlRef:em,onNewSessionContextChange:eb,initialSessionId:nZ,initialSessionLinked:null!==nV,skipInitialProjectSelection:null!==E.requestedCwd,onInitialRestoreDone:ro,refreshKey:eT,onSessionDeleted:rl,selectedCwd:V?.cwd??ed??null,onCwdChange:n8,onOpenFile:rd,onOpenTerminal:rp,onOpenGitGraph:rh,explorerRefreshKey:eH,onExplorerRefresh:rr,onAtMention:nU,onAtMentions:nq,onBackgroundTaskDone:Z,hiddenFinishedSessionIds:q,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=sn(t)&&!rP;return(0,r.jsxs)("button",{type:"button",onClick:()=>na(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)(pB,{section:t,size:14,strokeWidth:2}),(0,r.jsx)("span",{children:n})]},t)}),(0,r.jsxs)("button",{type:"button",onClick:()=>{eZ(!0),eq(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr();if(!t)return"general";try{let n=si(t).section;if(!("string"==typeof n&&i7.includes(n)))return"general";return sn(n)&&!e?"general":n}catch{return"general"}}(rP))},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)(pB,{section:"general",size:14,strokeWidth:2}),(0,r.jsx)("span",{children:R("common.settings")})]})]})]}),rK=e=>rL&&eG?.requiresTrust&&!eG.trusted?(0,r.jsxs)("button",{type:"button",onClick:rW,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,rV=e=>(0,r.jsxs)("button",{type:"button",onClick:()=>nt("agents",e&&!L),disabled:!er,title:el,"aria-label":el,"aria-pressed":"agents"===t5,style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?mJ:void 0,height:"100%",padding:e?0:"0 12px",background:"agents"===t5?"var(--bg-selected)":"none",border:"none",borderTop:"agents"===t5?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"agents"===t5?"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")}),eo&&eo.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:eo.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:eo.running?600:void 0,...e?{position:"absolute",top:3,right:3,minWidth:13,height:13,padding:"0 3px",fontSize:9}:{}},children:[eo.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"})]}),eo.count]})]}),rJ=e=>{let t,n,i,s,a,o;return e||rL?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",height:"100%"},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>{rw(),e&&L&&ti(!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?mJ: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&&((tK?.userMessages??0)>0||V.messageCount>0)),n=!V||V.transient||!t||"naming"===tV.kind,i="success"===tV.kind,s="error"===tV.kind,a="naming"===tV.kind?R("title.generating"):i?R("title.updated"):s?R("title.failed"):R("title.generate"),o=!V||V.transient?R("title.unsaved"):t?s?tV.message:R("title.generateSession"):R("title.noMessages"),(0,r.jsxs)("button",{type:"button",onClick:()=>{rn(),e&&L&&ti(!0)},disabled:n,title:o,"aria-label":a,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?mJ: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"!==tV.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"===tV.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)&&rV(e),tE&&(e?(0,r.jsx)("button",{type:"button",onClick:()=>nt("branches",!0),title:R("i18n.branches"),"aria-label":R("i18n.branches"),"aria-pressed":"branches"===t5,style:{display:"flex",alignItems:"center",justifyContent:"center",width:mJ,height:"100%",padding:0,background:"branches"===t5?"var(--bg-selected)":"none",border:"none",borderTop:"branches"===t5?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"branches"===t5?"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:tk.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)(p3,{tree:tk,activeLeafId:tS,onLeafChange:tM,locked:tN,inline:!0,containerRef:ty,open:"branches"===t5,onToggle:()=>nt("branches"),hasSession:!0})),(0,r.jsxs)("button",{ref:tD,type:"button",onClick:()=>ni("system",e),disabled:e&&!rL,title:R("system.prompt"),"aria-label":R("system.prompt"),"aria-pressed":"system"===t5,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?mJ:void 0,height:"100%",padding:e?0:"0 12px",background:"system"===t5?"var(--bg-selected)":"none",border:"none",borderTop:"system"===t5?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:e&&!rL?"not-allowed":"pointer",color:"system"===t5?"var(--text)":"var(--text-muted)",opacity:e&&!rL?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||rL)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="system"===t5?"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:tR?"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:()=>ni("tools",e),disabled:e&&!rL,title:R("tools.title"),"aria-label":R("tools.title"),"aria-pressed":"tools"===t5,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?mJ:void 0,height:"100%",padding:e?0:"0 12px",background:"tools"===t5?"var(--bg-selected)":"none",border:"none",borderTop:"tools"===t5?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:e&&!rL?"not-allowed":"pointer",color:"tools"===t5?"var(--text)":"var(--text-muted)",opacity:e&&!rL?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||rL)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="tools"===t5?"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:tL?.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},rG=e=>{if(!e&&(!rL||!tK&&!t8))return null;let t=tK?.tokens,n=tK?.cost??0,i=id(n),s="var(--text-muted)",a=null,o=null;if(t8?.contextWindow){let e=t8.percent;null!==e&&e>90?s="#ef4444":null!==e&&e>70&&(s="rgba(234,179,8,0.95)"),a=null!==e?`${e.toFixed(0)}% / ${il(t8.contextWindow)}`:`? / ${il(t8.contextWindow)}`,o=null!==e?`${e.toFixed(0)}%`:null}let l=[];if(t&&(l.push(`${R("session.input")}: ${t.input.toLocaleString(M)}`),l.push(`${R("session.output")}: ${t.output.toLocaleString(M)}`),l.push(`${R("session.cacheRead")}: ${t.cacheRead.toLocaleString(M)}`),l.push(`${R("session.cacheWrite")}: ${t.cacheWrite.toLocaleString(M)}`),n>0&&l.push(`${R("session.cost")}: $${n.toFixed(4)}`)),t8?.contextWindow){let e=t8.percent;l.push(`${R("session.context")}: ${null!==e?`${e.toFixed(1)}%`:"?"} / ${t8.contextWindow.toLocaleString(M)}`)}let d=l.join(" | "),c=e&&L&&tr,u=!!(t&&(t.input>0||t.output>0)||i||o);return(0,r.jsx)("button",{type:"button",onClick:()=>nt("session"),disabled:!rL||c,tabIndex:c?-1:void 0,title:d||R("session.title"),"aria-label":R("session.title"),"aria-pressed":"session"===t5,"aria-hidden":!!c||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:c?"hidden":"visible",pointerEvents:c?"none":"auto",background:"session"===t5?"var(--bg-selected)":"none",border:"none",borderTop:"session"===t5?"2px solid var(--accent)":"2px solid transparent",fontSize:11,color:"var(--text-muted)",whiteSpace:"nowrap",cursor:rL?"pointer":"default",fontVariantNumeric:"tabular-nums",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{rL&&!c&&(e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="session"===t5?"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"})]}),il(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"})]}),il(t.output)]}),i&&(0,r.jsx)("span",{className:"mobile-session-stat-cost",style:{color:"var(--text)",fontWeight:500,flexShrink:0},children:i}),o&&(0,r.jsx)("span",{style:{color:s,flexShrink:0},children:o}),!u&&rL&&(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"})]}),il(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"})]}),il(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"})]}),il(t.cacheRead)]}),i&&(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",color:"var(--text)",fontWeight:500},children:i}),a&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4,color:s},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M1 9 L1 5 Q1 1 5 1 Q9 1 9 5 L9 9"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"9",y2:"9"})]}),a]})]})})},rY=e=>{if(!rL)return null;let t="debug"===t5;return(0,r.jsx)("button",{ref:nn,type:"button",onClick:()=>nt("debug",e),title:R("debug.title"),"aria-label":R("debug.title"),"aria-pressed":t,style:{marginLeft:e?0:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:mJ,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"})]})})},rX=e=>{let t=e&&L&&tr;return(0,r.jsx)("button",{type:"button",onClick:nd,disabled:t,tabIndex:t?-1:void 0,"aria-controls":"file-panel","aria-expanded":e9,"aria-hidden":!!t||void 0,title:e9?R("files.hidePanel"):R("files.showPanel"),"aria-label":e9?R("files.hidePanel"):R("files.showPanel"),"data-mobile-toolbar-file":e?"true":void 0,style:{marginLeft:e||rL?0:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:mJ,height:mJ,padding:0,visibility:t?"hidden":"visible",pointerEvents:t?"none":"auto",background:e9?"var(--bg-selected)":"none",border:"none",borderLeft:"1px solid var(--border)",color:e9?"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=e9?"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:`
993
- @keyframes session-info-pop {
994
- 0% {
995
- opacity: 0;
996
- transform: translateY(-24px);
997
- filter: blur(6px);
998
- box-shadow: 0 2px 8px rgba(0,0,0,0);
999
- }
1000
- 55% {
1001
- opacity: 1;
1002
- transform: translateY(0);
1003
- filter: blur(0);
1004
- background: color-mix(in srgb, var(--accent) 8%, var(--bg-panel));
1005
- box-shadow: 0 18px 44px rgba(37,99,235,0.16);
1006
- }
1007
- 100% {
1008
- opacity: 1;
1009
- transform: translateY(0);
1010
- filter: blur(0);
1011
- background: var(--bg-panel);
1012
- box-shadow: 0 10px 28px rgba(0,0,0,0.10);
1013
- }
1014
- }
1015
- @keyframes session-info-light-wash {
1016
- 0% {
1017
- opacity: 0;
1018
- transform: translateX(-110%) skewX(-16deg);
1019
- }
1020
- 24% {
1021
- opacity: 0.42;
1022
- }
1023
- 100% {
1024
- opacity: 0;
1025
- transform: translateX(115%) skewX(-16deg);
1026
- }
1027
- }
1028
- .session-info-popover {
1029
- position: relative;
1030
- overflow: hidden;
1031
- transform-origin: top right;
1032
- animation: session-info-pop 360ms ease-out both;
1033
- will-change: transform, opacity, filter, background, box-shadow;
1034
- }
1035
- .session-info-popover::after {
1036
- content: "";
1037
- position: absolute;
1038
- top: 0;
1039
- bottom: 0;
1040
- left: 0;
1041
- width: 44%;
1042
- pointer-events: none;
1043
- background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--accent) 24%, transparent), transparent);
1044
- animation: session-info-light-wash 620ms ease-out both;
1045
- }
1046
- @media (prefers-reduced-motion: reduce) {
1047
- .session-info-popover,
1048
- .session-info-popover::after {
1049
- animation: none;
1050
- }
1051
- }
1052
- .mobile-session-stats {
1053
- container-type: inline-size;
1054
- }
1055
- @container (max-width: 158px) {
1056
- .mobile-session-stat-io {
1057
- display: none !important;
1058
- }
1059
- }
1060
- @container (max-width: 88px) {
1061
- .mobile-session-stat-cost {
1062
- display: none !important;
1063
- }
1064
- }
1065
- @media (max-width: 640px) {
1066
- .sidebar-overlay-backdrop.sidebar-mobile-pending {
1067
- opacity: 0 !important;
1068
- pointer-events: none !important;
1069
- }
1070
- .sidebar-container.sidebar-mobile-pending.sidebar-open {
1071
- transform: translateX(calc(-100% - env(safe-area-inset-left)));
1072
- box-shadow: none;
1073
- }
1074
- }
1075
- `}),(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${ta?"":" sidebar-mobile-pending"}`,onClick:()=>e6(!1),style:{position:"fixed",inset:0,zIndex:199,background:"rgba(0,0,0,0.4)",opacity:+!!e8,pointerEvents:e8?"auto":"none",transition:"opacity 0.25s ease"}}),(0,r.jsx)("div",{ref:th.panelRef,id:"session-sidebar",inert:tn,className:`sidebar-container${e8?" sidebar-open":" sidebar-closed"}${ta?"":" sidebar-mobile-pending"}${th.isResizing?" sidebar-resizing":""}`,style:{"--sidebar-width":`${th.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:rq}),e8&&(0,r.jsx)("div",{...th.separatorProps,inert:tn,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${th.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${R("layout.resizeSidebar")}: ${R("layout.resizeHint")}`}),(0,r.jsxs)("div",{inert:tn,style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:[(0,r.jsxs)("div",{ref:ty,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:no,title:e8?R("sidebar.hide"):R("sidebar.show"),"aria-label":e8?R("sidebar.hide"):R("sidebar.show"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:mJ,height:mJ,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:e8?(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"})]})}),A&&(0,r.jsxs)("div",{ref:tj,"data-mobile-toolbar":"true",style:{position:"relative",display:"flex",alignItems:"stretch",flex:1,minWidth:0,height:"100%"},children:[L&&rV(!0),L&&(0,r.jsx)("button",{type:"button",onClick:nl,title:ts,"aria-label":ts,"aria-controls":"mobile-toolbar-actions","aria-expanded":tr,"data-mobile-toolbar-more":"true",style:{position:"relative",zIndex:tr?21:void 0,display:"flex",alignItems:"center",justifyContent:"center",width:mJ,height:mJ,padding:0,background:tr?"var(--bg-selected)":"none",border:"none",borderRight:"1px solid var(--border)",color:tr?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s, background 0.12s"},children:tr?(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&&rJ(!0),!L&&rY(!0),rG(!0),rX(!0),L&&tr&&(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 * ${mJ})`,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:[rJ(!0),rY(!0)]})]}),!A&&(0,r.jsxs)(r.Fragment,{children:[rK(!1),rJ(!1),rY(!1),rG(!1)]}),!A&&rX(!1),A&&tE&&(0,r.jsx)(p3,{tree:tk,activeLeafId:tS,onLeafChange:tM,locked:tN,inline:!0,compact:!0,containerRef:ty,open:"branches"===t5,onToggle:()=>nt("branches"),hasSession:rL,hideInlineButton:!0}),t5&&t7&&(0,r.jsxs)("div",{style:{position:"fixed",top:t7.top,left:t7.left,width:t7.width,maxHeight:`calc(100dvh - ${t7.top}px)`,overflowY:"auto",zIndex:500},children:["agents"===t5&&er&&V&&(0,r.jsx)(hl,{rootSession:er.root,subagents:er.subagents,selectedSessionId:V.id,runningSessionIds:ei,onSelectSession:n6,openSubagentTabIds:rg,onToggleSubagentTab:(e,t,n)=>{rg.has(e)?ry(`agent:${e}`):(A&&t9(null),rm(e,t,n))},onNewSideChat:()=>rb(er.root.id),onDeleteSideChat:e=>rj(e,er.root)}),"system"===t5&&(0,r.jsx)(p5,{loading:tz,prompt:tR,translate:R}),"tools"===t5&&(0,r.jsx)(he,{loading:tz,tools:tL,translate:R}),"session"===t5&&(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:tK?(n=tK.totalActiveMs??0,u=[...tK.sessionName?[{label:R("session.name"),value:tK.sessionName,copyField:null}]:[],{label:R("session.file"),value:tK.sessionFile??R("session.inMemory"),copyField:"file"},{label:R("session.id"),value:tK.sessionId,copyField:"id"},...n>0?[{label:R("session.totalActive"),value:ic(n),copyField:null}]:[]],x=[...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"),tK.userMessages.toLocaleString(M)],[R("session.assistant"),tK.assistantMessages.toLocaleString(M)],[R("session.toolCalls"),tK.toolCalls.toLocaleString(M)],[R("session.toolResults"),tK.toolResults.toLocaleString(M)],[R("session.total"),tK.totalMessages.toLocaleString(M)]],v=[[R("session.input"),tK.tokens.input.toLocaleString(M)],[R("session.output"),tK.tokens.output.toLocaleString(M)],...tK.tokens.cacheRead>0?[[R("session.cacheRead"),tK.tokens.cacheRead.toLocaleString(M)]]:[],...tK.tokens.cacheWrite>0?[[R("session.cacheWrite"),tK.tokens.cacheWrite.toLocaleString(M)]]:[],[R("session.total"),tK.tokens.total.toLocaleString(M)]],y=t8??tK.contextUsage,j=[...tK.cost>0?[[R("session.cost"),`$${tK.cost.toFixed(4)}`]]:[],...y?.contextWindow?[[R("session.context"),`${null!==y.percent?`${y.percent.toFixed(1)}%`:"?"} / ${il(y.contextWindow)}`]]:[],...tK.tokens.cacheRead+tK.tokens.cacheWrite>0&&tK.tokens.cacheRead+tK.tokens.cacheWrite+tK.tokens.input>0?[[R("session.cacheHitRate"),`${(tK.tokens.cacheRead/(tK.tokens.cacheRead+tK.tokens.cacheWrite+tK.tokens.input)*100).toFixed(1)}%`]]:[]],k=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=tQ===e;return(0,r.jsx)("button",{type:"button",title:n?R("session.copied"):R(w[e]),onClick:()=>t4(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:u.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=x.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:x.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]}),k(R("session.messages"),b),k(R("session.tokens"),[...v,...j],"right",!0)]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:R("session.load")})}),"debug"===t5&&(0,r.jsx)(hJ,{fallback:R("debug.failed"),children:(0,r.jsx)(hG,{readerRef:tU,selectedSessionId:V?.id??null,sessions:en,onClose:nr})})]})]}),A&&rK(!0)]}),(0,r.jsx)("div",{style:{flex:1,overflow:"hidden",position:"relative"},children:rL?(0,r.jsx)(iZ,{session:V,searchTarget:ez?.sessionId===V?.id?ez:null,onSearchTargetHandled:eB,initialScrollPosition:V?eL.current.get(V.id)??null:null,onScrollPositionChange:eP,sessionRunning:!!(V&&ei.has(V.id)),newSessionCwd:rS,newSessionDraftKey:rC,newSessionContextBar:rA,initialNewSessionChoices:null===V?ej:null,onNewSessionChoicesChange:ew,onAgentEnd:re,onToolEnd:rs,onAttentionNeeded:rt,onSessionCreated:n9,onSessionForked:ra,onSideSession:rx,modelsRefreshKey:eV,chatInputRef:tx,onBranchDataChange:tT,onSystemPromptChange:tB,onSystemToolsChange:tH,onSystemInfoLoaderChange:t_,onDebugSnapshotReaderChange:tq,onSessionStatsChange:tX,onSessionStatsPanelOpen:ns,onOpenSettings:na,onContextUsageChange:t3,onOpenFile:rc,onFilesUploaded:rr,onOpenSubagent:rm,onEnterSubagent:rf,quoteSelectionEnabled:B,soundEnabled:P,onSoundToggle:z,playDoneSound:O,unlockAudio:W,holdAudio:F},eR):"validating"===eS?(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:E.requestedCwd})]}):"error"===eS?(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:E.requestedCwd}),(0,r.jsx)("div",{style:{maxWidth:720,fontSize:12},children:e$})]}):rz?nR?(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${e9?" is-open":""}`,onClick:()=>e7(!1)}),e9&&(0,r.jsx)("div",{...tm.separatorProps,inert:tn,"aria-controls":"file-panel",className:`panel-resize-handle right-panel-resize-handle${tm.isResizing?" is-resizing":""}`,"data-resize-handle":"right-panel",title:`${R("layout.resizeFilePanel")}: ${R("layout.resizeHint")}`}),(0,r.jsxs)("div",{ref:tm.panelRef,id:"file-panel",className:`right-panel-container${e9?" right-panel-open":" right-panel-closed"}${tn?" right-panel-full-width":""}${tm.isResizing?" right-panel-resizing":""}`,style:{"--right-panel-width":`${tm.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)(i6.V,{tabs:nF,activeTabId:nh??"",onSelectTab:nm,onCloseTab:ry,onReorderTab:(e,t,n)=>nz(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}(nF.map(e=>e.id),e,t,n))})}),(0,r.jsx)("button",{type:"button",className:"file-panel-expand-button",onClick:ru,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:nc,"aria-controls":"file-panel","aria-pressed":tn,title:R(tn?"files.restorePanelWidth":"files.expandPanel"),"aria-label":R(tn?"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:tn?"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:()=>e7(!1),"aria-controls":"file-panel","aria-expanded":e9,title:R("files.hidePanel"),"aria-label":R("files.hidePanel"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:mJ,height:mJ,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:[rD?.filePath?(0,r.jsx)(i8.h,{filePath:rD.filePath,cwd:nR??void 0,sourceSessionId:rD.sourceSessionId,gitRefreshKey:eH,initialDisplayMode:rD.initialDisplayMode,initialPage:rD.page,initialState:rD.viewerState,watchEnabled:e9,onStateChange:e=>nH(nf,rD.id,rD.viewerRevision??0,e),onMentionLines:e9?nK:void 0,onAtMention:nU,onOpenFile:(e,t)=>rd(e,(0,mB.WP)(e),{sourceSessionId:rD.sourceSessionId,page:t})},`${nf}:${rD.id}:${rD.viewerRevision??0}`):nv.some(e=>e.id===nh)||rB||rH?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!==rH&&(0,r.jsx)(mL,{cwd:rH,refreshKey:eH},`git-graph:${rH}`),nv.map(e=>(0,r.jsx)("div",{hidden:e.id!==nh,style:{width:"100%",height:"100%"},children:(0,r.jsx)(m$.z,{tab:e,active:e9&&e.id===nh,onRestart:()=>ny(t=>t.map(t=>t.id===e.id?{...t,closing:"restart"}:t)),onClosed:()=>{let t,n;return t="restart"===e.closing?(0,mO.Wg)(e.cwd):null,n=nv.filter(t=>t.id!==e.id),void(ny(n=>n.flatMap(n=>n.id!==e.id?[n]:t?[t]:[])),nm(r=>r!==e.id?r:t?.id??n.at(-1)?.id??nu.at(-1)?.id??mY(nC)),!t&&!n.length&&!nu.length&&!nj.length&&!nC.length&&e7(!1))},onCloseError:()=>ny(t=>t.map(t=>t.id===e.id?{...t,closing:void 0}:t))})},e.id)),rB&&(0,r.jsx)(mI,{sessionId:rB.sessionId,running:ei.has(rB.sessionId),initialPrompt:tb[rB.sessionId],onInitialPromptConsumed:()=>tv(e=>{if(!(rB.sessionId in e))return e;let t={...e};return delete t[rB.sessionId],t}),modelsRefreshKey:eV,quoteSelectionEnabled:B,onOpenFile:rc,onOpenSubagent:rm,onSessionForked:e=>{A&&e7(!1),ra(e)},onOpenSettings:na,onToolEnd:rs,onFilesUploaded:rr,soundEnabled:P,onSoundToggle:z,playDoneSound:O,unlockAudio:W,holdAudio:F},rB.sessionId)]})]})]}),eU&&(0,r.jsx)(pK,{cwd:rP,sessionId:V?.id??null,initialSection:eU,openAtHome:eK,quoteSelectionEnabled:B,onQuoteSelectionChange:_,onClose:()=>{eq(null),eJ(e=>e+1)},onSessionReloaded:()=>eA(e=>e+1),projectTrust:eG,onOpenTrustDialog:rW,onProjectTrustChanged:rF}),eX&&rP&&(0,r.jsx)(pV,{cwd:rP,busy:e0,error:e2,onCancel:()=>{e0||eQ(!1)},onConfirm:()=>void rO(),onStatus:eY})]})}},76853:(e,t,n)=>{Promise.resolve().then(n.bind(n,68470)),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,[7523,7330,3888,1449,8986,5772,9242,1278,6219,9176,8646,8441,3794,7358],()=>e(e.s=76853)),_N_E=e.O()}]);