@pricening/pi-web 0.12.11 → 0.12.12

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 (88) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +9 -9
  3. package/.next/build-manifest.json +3 -3
  4. package/.next/diagnostics/framework.json +1 -1
  5. package/.next/prerender-manifest.json +3 -3
  6. package/.next/required-server-files.js +1 -1
  7. package/.next/required-server-files.json +1 -1
  8. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  9. package/.next/server/app/_global-error.html +1 -1
  10. package/.next/server/app/_global-error.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  13. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  14. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  15. package/.next/server/app/_not-found.html +1 -1
  16. package/.next/server/app/_not-found.rsc +2 -2
  17. package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  18. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
  19. package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  20. package/.next/server/app/api/agent/[id]/events/route.js +1 -1
  21. package/.next/server/app/api/app-update/route.js +1 -1
  22. package/.next/server/app/api/auth/login/[provider]/route.js +1 -1
  23. package/.next/server/app/api/auth/logout/[provider]/route.js +1 -1
  24. package/.next/server/app/api/auth/providers/route.js +1 -1
  25. package/.next/server/app/api/cwd/validate/route.js +1 -1
  26. package/.next/server/app/api/file-index/route.js +1 -1
  27. package/.next/server/app/api/files/[...path]/route.js +2 -2
  28. package/.next/server/app/api/git/diff/route.js +2 -2
  29. package/.next/server/app/api/git/status/route.js +2 -2
  30. package/.next/server/app/api/mcp/sign-in/[flowId]/route.js +1 -1
  31. package/.next/server/app/api/models/refresh/route.js +1 -1
  32. package/.next/server/app/api/models/route.js +1 -1
  33. package/.next/server/app/api/models-config/discover/route.js +1 -1
  34. package/.next/server/app/api/plugins/check/route.js +1 -1
  35. package/.next/server/app/api/plugins/route.js +1 -1
  36. package/.next/server/app/api/push/config/route.js +1 -1
  37. package/.next/server/app/api/push/subscribe/route.js +1 -1
  38. package/.next/server/app/api/sessions/[id]/fork/route.js +1 -1
  39. package/.next/server/app/api/sessions/[id]/route.js +1 -1
  40. package/.next/server/app/api/sessions/route.js +1 -1
  41. package/.next/server/app/api/sessions/search/route.js +1 -1
  42. package/.next/server/app/api/sessions/stats/route.js +1 -1
  43. package/.next/server/app/api/skills/install/route.js +1 -1
  44. package/.next/server/app/api/skills/update/route.js +1 -1
  45. package/.next/server/app/api/terminal/[id]/events/route.js +1 -1
  46. package/.next/server/app/api/worktrees/route.js +1 -1
  47. package/.next/server/app/index.html +1 -1
  48. package/.next/server/app/index.rsc +5 -5
  49. package/.next/server/app/index.segments/__PAGE__.segment.rsc +5 -5
  50. package/.next/server/app/index.segments/_full.segment.rsc +5 -5
  51. package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  52. package/.next/server/app/login/page_client-reference-manifest.js +1 -1
  53. package/.next/server/app/login.html +1 -1
  54. package/.next/server/app/login.rsc +3 -3
  55. package/.next/server/app/login.segments/_full.segment.rsc +3 -3
  56. package/.next/server/app/login.segments/_tree.segment.rsc +1 -1
  57. package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +3 -3
  58. package/.next/server/app/manifest.webmanifest/route.js +1 -1
  59. package/.next/server/app/page.js +12 -12
  60. package/.next/server/app/page_client-reference-manifest.js +1 -1
  61. package/.next/server/app-paths-manifest.json +9 -9
  62. package/.next/server/chunks/1813.js +1 -1
  63. package/.next/server/chunks/2243.js +1 -1
  64. package/.next/server/chunks/2430.js +1 -1
  65. package/.next/server/chunks/2686.js +1 -1
  66. package/.next/server/chunks/2970.js +3 -3
  67. package/.next/server/chunks/3757.js +1 -1
  68. package/.next/server/chunks/5582.js +2 -2
  69. package/.next/server/chunks/5799.js +1 -1
  70. package/.next/server/chunks/6429.js +7 -7
  71. package/.next/server/middleware-build-manifest.js +1 -1
  72. package/.next/server/middleware.js +3 -3
  73. package/.next/server/pages/404.html +1 -1
  74. package/.next/server/pages/500.html +1 -1
  75. package/.next/server/preview-props.json +3 -3
  76. package/.next/server/server-reference-manifest.json +1 -1
  77. package/.next/static/chunks/1278-7db73a3610c0f169.js +1 -0
  78. package/.next/static/chunks/{3794-dcdba95a4976cf7e.js → 3794-de8718559825292f.js} +1 -1
  79. package/.next/static/chunks/app/{layout-0167bf731eae39a8.js → layout-14b710b4e68ea96e.js} +1 -1
  80. package/.next/static/chunks/app/page-f26ef30ec2bddae0.js +1152 -0
  81. package/.next/static/chunks/{main-b84543b54475a56e.js → main-286cf099c5558b34.js} +1 -1
  82. package/.next/trace +189 -189
  83. package/.next/trace-build +1 -1
  84. package/package.json +4 -4
  85. package/.next/static/chunks/1278-f32fcb3a7820a55a.js +0 -1
  86. package/.next/static/chunks/app/page-ded4452630a01fcf.js +0 -1152
  87. /package/.next/static/{DfSgiNdr4Vzdiiky41qD7 → ji0IgjD84idWH6suabe3a}/_buildManifest.js +0 -0
  88. /package/.next/static/{DfSgiNdr4Vzdiiky41qD7 → ji0IgjD84idWH6suabe3a}/_ssgManifest.js +0 -0
@@ -0,0 +1,1152 @@
1
+ (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{5284:e=>{e.exports={lock:"LockToggle_lock__hI4qs"}},14755:(e,t,n)=>{"use strict";n.d(t,{Q8:()=>r,YO:()=>h,getPresetFromTools:()=>p,kU:()=>l,kt:()=>d,sn:()=>u,xG:()=>f});let r="configured",i=["configured","none","read-only","default","full"],s=[],l=["read","grep","find","ls"],o=["read","bash","edit","write"],a=["bash","read","edit","write","grep","find","ls"],d=["read","grep","find","ls","edit","write","bash"],c=new Set([...a,"powershell"]);function u(e){return"string"==typeof e&&i.includes(e)}function p(e){return h(e.filter(e=>e.active).map(e=>e.name))}function h(e){if(0===e.length)return"none";let t=e.map(e=>"powershell"===e?"bash":e).filter(e=>c.has(e)).sort().join(",");return t===[...l].sort().join(",")?"read-only":t===[...o].sort().join(",")?"default":t===[...a].sort().join(",")?"full":"default"}function f(e){if(e!==r)return"none"===e?[...s]:"read-only"===e?[...l]:"full"===e?[...a]:[...o]}},42927:(e,t,n)=>{Promise.resolve().then(n.bind(n,60066)),Promise.resolve().then(n.bind(n,21278))},60066:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>w4});var r=n(95155),i=n(12115),s=n(73321);let l=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 a(e){return e?.kind==="subagent"||e?.kind==="side"}function d(e,t){let n=function(e){let t=new Map(e.map(e=>[e.id,e])),n=new Map;for(let r of e){if(n.has(r.id))continue;let e=[],i=new Set,s=r.id,l=null;for(;;){if(n.has(s)){l=n.get(s)??null;break}if(i.has(s))break;i.add(s),e.push(s);let r=t.get(s);if(!r)break;if(!a(r.relation)){l=r.id;break}s=r.relation.parentSessionId}for(let t of e)n.set(t,l)}return n}(e),r=new Map;for(let t of e)a(t.relation)||r.set(t.id,{root:t,subagents:[],latestModified:t.modified});for(let t of e){if(!a(t.relation))continue;let e=n.get(t.id),i=e?r.get(e):void 0;i&&(i.subagents.push(t),t.modified>i.latestModified&&(i.latestModified=t.modified))}return[...r.values()].sort((e,n)=>{var r;return r=!!t?.has(e.root.id),(r===!!t?.has(n.root.id)?0:r?-1:1)||n.latestModified.localeCompare(e.latestModified)})}function c(e,t){return t?d(e).find(e=>e.root.id===t||e.subagents.some(e=>e.id===t))??null:null}function u(e,t){return e.filter(e=>t.has(e.id)).length}function p(e){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 h=new Map,f="parked-new:";function m(e){return`${f}${e}`}let g="pi-web:draft:",x=new Set,v=new Set,b=new Map,y=null,w=!1;function k(){try{return window.localStorage??null}catch{return null}}function j(e){return!e.startsWith("new:")&&!e.startsWith(f)}function S(e){let t=[];for(let n=0;n<e.length;n++){let r=e.key(n);r?.startsWith(g)&&t.push(r)}return t}function C(){null!==y&&clearTimeout(y),y=null;let e=[...v];v.clear();let t=k();if(t)for(let n of e)!function(e,t){let n=g+t,r=h.get(t)?.value??"";try{let t;if(!r||r.length>2e4)return void e.removeItem(n);let i=null===e.getItem(n);e.setItem(n,JSON.stringify({text:r,at:Date.now()})),i&&((t=S(e)).length<=50||t.map(t=>({key:t,at:function(e,t){try{let n=JSON.parse(e.getItem(t)??"")?.at;return"number"==typeof n&&Number.isFinite(n)?n:0}catch{return 0}}(e,t)})).sort((e,t)=>t.at-e.at).slice(50).forEach(t=>{let{key:n}=t;return e.removeItem(n)}))}catch{try{e.removeItem(n)}catch{}}}(t,n)}function N(){"hidden"===document.visibilityState&&C()}function E(e){!(!j(e)||b.has(e))&&k()&&(v.add(e),!w&&(w=!0,window.addEventListener("pagehide",C),"u">typeof document&&document.addEventListener("visibilitychange",N)),null===y&&(y=setTimeout(C,300)))}function $(e){if(v.delete(e),!j(e))return;let t=k();if(t)try{t.removeItem(g+e)}catch{}}function I(e){b.set(e,(b.get(e)??0)+1),$(e);let t=!1;return()=>{if(t)return;t=!0;let n=(b.get(e)??1)-1;n>0?b.set(e,n):(b.delete(e),h.get(e)?.value&&E(e))}}function M(e){return{value:e.value,images:e.images.map(e=>({...e}))}}function T(e){return!e.value&&0===e.images.length}function R(e){let t=h.get(e)??function(e){if(x.has(e)||!j(e))return null;x.add(e);let t=k();if(!t)return null;try{let n=t.getItem(g+e);if(!n)return null;let r=JSON.parse(n),i=r&&"object"==typeof r?r.text:null;if("string"!=typeof i||!i||i.length>2e4)return null;let s={value:i,images:[]};return h.set(e,s),s}catch{return null}}(e);return t?M(t):null}function A(e,t){if(T(t))return void L(e);x.add(e);let n=h.get(e);h.set(e,M(t)),t.value?n?.value!==t.value&&E(e):$(e)}function L(e){x.add(e),h.delete(e),$(e)}function z(e,t){return e.trim()?t.trim()?`${e}
2
+
3
+ ${t}`:e:t}function P(e,t,n,r){let i=[...t??[],...r].filter(p).slice(0,10).map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});return{value:z(e,n),images:i}}function W(e,t,n){let r=R(e)??{value:"",images:[]},i=P(t,n,r.value,r.images);return A(e,i),i}function O(e,t,n){if(e===t)return n?M(n):R(t);let r=R(e),i=n&&!T(n)?M(n):r??(n?M(n):null),s=R(t);if(L(e),!i)return s;let l=s?P(s.value,s.images,i.value,i.images):i;return A(t,l),M(l)}function F(e){return`?session=${encodeURIComponent(e)}`}let D="pi-web:last-open-by-workspace";function B(){try{return window.localStorage}catch{return null}}function H(e){let t=e.getItem(D);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function _(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:B();if(t)try{let n=H(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(D):t.setItem(D,JSON.stringify(n))}catch{}}function U(e){return e.projectKey??e.projectRoot??e.cwd}function K(e,t,n){let r=new Map;for(let t of e){let e=t.projectRoot??t.cwd;if(!e)continue;let i=U(t);if(n?.has(i))continue;let s=r.get(i);(!s||t.modified>s.modified)&&r.set(i,{root:e,modified:t.modified})}return[...r.entries()].sort((e,n)=>{var r;return r=!!t?.has(e[0]),(r===!!t?.has(n[0])?0:r?-1:1)||n[1].modified.localeCompare(e[1].modified)}).map(e=>{let[t,{root:n}]=e;return{key:t,root:n}})}let q=/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/,V=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function Z(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function J(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function Y(e){return"string"==typeof e&&q.test(e)}function G(e){return"string"==typeof e&&e.length>0&&e.length<=4096&&"__proto__"!==e}let X=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;function Q(e){if(null===e)return null;if("string"!=typeof e)return;let t=e.trim();return t?X.test(t)||[...t].length>80?void 0:t:null}let ee=new TextEncoder;function et(e){return ee.encode(JSON.stringify(e)).length+1}function en(e){let t=1;for(let n of e)t+=et(n);return t}function er(e,t){return e<=1e3&&t<=262144}function ei(e){let t=[],n=1;for(let r of e){if(t.length>=1e3)break;let e=et(r);n+e>262144||(t.push(r),n+=e)}return t}function es(e,t){return ee.encode(JSON.stringify(e)).length+ee.encode(JSON.stringify(t)).length+2}function el(e,t){return e<=1e3&&t<=262144}function eo(){return{version:1,revision:0,sessions:{},projects:{}}}function ea(e){let t=Object.entries(e);return t.length<=2e3?e:(t.sort((e,t)=>t[1]-e[1]),Object.fromEntries(t.slice(0,2e3)))}function ed(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 ec(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 eu(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 ep(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 eh={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}},ef="pinned";function em(e,t){return Object.hasOwn(e.sessions,t)?e.sessions[t]:void 0}function eg(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function ex(e,t){return e===t?0:e>t?-1:1}function ev(e){return[e.root.id,...e.subagents.map(e=>e.id)]}function eb(e,t){return 0!==t.size&&(t.has(e.root.id)||e.subagents.some(e=>t.has(e.id)))}function ey(e,t,n){let r=eg(em(t,e.root.id)?.archivedAt);if(null===r||eb(e,n))return!1;if(e.root.detailsPending)return!0;let i=Date.parse(e.root.modified);return Number.isNaN(i)||r>=i}function ew(e,t,n){return null!==eg(em(t,e.root.id)?.pinnedAt)&&!ey(e,t,n)}function ek(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 ej(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 eS(e,t){var n;return{running:eb(e,t.runningIds),awaiting:!!t.awaitingIds&&eb(e,t.awaitingIds),unread:eb(e,t.unreadIds),selected:!!(n=t.selectedSessionId)&&(e.root.id===n||e.subagents.some(e=>e.id===n)),transient:!0===e.root.transient}}function eC(e,t){let n=0,r=0,i=0;for(let s of e)t.awaitingIds&&eb(s,t.awaitingIds)?r++:eb(s,t.runningIds)&&n++,eb(s,t.unreadIds)&&i++;return{running:n,awaiting:r,unread:i}}function eN(e){return U(e.root)}function eE(e,t){let n=new Map,r=new Map;return{noteFamily(e){let t=eN(e);n.has(t)||n.set(t,e.root.projectRoot??e.root.cwd)},get(i){let s,l=r.get(i);if(l)return l;let o=Object.hasOwn(e.projects,i)?e.projects[i]:void 0,a=null!==t&&t.key===i,d=n.get(i)??(a?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??ek(d),customName:c,pinned:void 0!==o,current:a};return r.set(i,u),u}}}function e$(e,t,n,r){return{kind:"session",key:`session:${t}:${e.root.id}`,family:e,context:t,project:n,status:eS(e,r)}}function eI(e,t,n,r){let i=e.map((e,n)=>{if(n<t)return!1;let i=eS(e,r);return i.running||i.unread||i.selected}),s=t+n,l=0,o=e.filter((e,n)=>n<t||!!i[n]||n<s&&(l++,!0)),a=Math.max(t,Math.min(s,e.length));for(let t=0;a<e.length&&t<20;a++)!i[a]&&t++;return{visible:o,revealed:l,nextShown:a-t}}function eM(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 eR(e,t,n){let r=e-t,i=n>0;return r>0||i?{hidden:r,canShowLess:i}:null}function eA(e,t,n,r){let i=r-n,s=[];for(let n of d(e.sessions)){if(eN(n)!==t||ey(n,e.uiState,e.runningIds)||ew(n,e.uiState,e.runningIds))continue;let r=eS(n,e);if(r.running||r.unread||r.selected||r.transient)continue;let l=Date.parse(n.latestModified);Number.isNaN(l)||l>=i||s.push(n.root.id)}return s}function eL(e,t){let n=[],r=0;for(let i of d(e.sessions))if(eN(i)===t&&!i.root.transient){if(eb(i,e.runningIds)||e.awaitingIds&&eb(i,e.awaitingIds)){r++;continue}n.push(i.root.id)}return{ids:n,running:r}}function ez(e,t,n){let r=e.find(e=>e.key===t);if(!r)return null;let i=e.filter(e=>e.pinned===r.pinned),s=i.indexOf(r),l=i["up"===n?s-1:s+1];return l?{anchorKey:l.key,position:"up"===n?"before":"after"}:null}function eP(e,t,n,r,i){if(!Number.isInteger(t)||t<0||t>=e.length-1)return null;let s=e[t],l=e[t+1];return"start"===i?s===n?null:s:s>=n&&l<=n+r?null:"nearest"===i&&l>n&&s<n+r?s<n||l-s>r?s:l-r:Math.max(0,s-Math.max(0,(r-(l-s))/2))}let eW="pi-web:sidebar-tab",eO="pi-web:sidebar-groups-v2",eF="pi-web:sidebar-groups",eD="pi-web:sidebar-archive-collapsed",eB="pi-web:sidebar-pins-collapsed",eH="pi-web:sidebar-files-show-ignored",e_="pi-web:sidebar-files-collapsed",eU="pi-web:sidebar-changes-view-mode",eK="pi-web:sidebar-non-git-cwds",eq=["pi-web:file-explorer:open","pi-web:sidebar-session-pane-height",eF];function eV(){try{return window.localStorage}catch{return null}}function eZ(e){let t={};if(null===e||"object"!=typeof e||Array.isArray(e))return t;for(let[n,r]of Object.entries(e))"__proto__"!==n&&"boolean"==typeof r&&(t[n]=r);return t}function eJ(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eV();if(t)try{let n=Object.entries(eZ(e)),r=n.length>300?n.slice(n.length-300):n;t.setItem(eO,JSON.stringify(Object.fromEntries(r)))}catch{}}function eY(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eV();if(t)try{t.setItem(eD,JSON.stringify([...new Set(e)].slice(-300)))}catch{}}function eG(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eV();if(t)try{t.setItem(eB,String(e))}catch{}}function eX(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:eV();if(!e)return[];try{let t=e.getItem(eK),n=null===t?[]:JSON.parse(t);if(!Array.isArray(n))return[];return n.filter(e=>"string"==typeof e&&""!==e).slice(-50)}catch{return[]}}function eQ(e,t){switch(e){case"not_found":return{key:"sidebar.forkNotFound"};case"unsaved":return{key:"sidebar.forkUnsaved"};case"empty":return{key:"sidebar.forkEmpty"};case"subagent":case"request-denied":return{key:"sidebar.forkUnavailable"};default:return{key:"sidebar.forkFailed",params:{error:t}}}}async function e0(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 e1(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function e2(e,t){let n=t.replace(/[/\\]+$/,"");return n&&(e===n||e.startsWith(`${n}/`)||e.startsWith(`${n}\\`))?`./${e.slice(n.length).replace(/^[/\\]/,"")}`:e1(e)}let e4=/ · [0-9a-f]{4}$/;function e8(e){let t=e4.exec(e);return t&&0!==t.index?{base:e.slice(0,t.index),suffix:t[0]}:null}function e3(e,t){return{cwd:e.current&&t?t:e.root,projectKey:e.key,projectRoot:e.root}}function e5(e){let t=e.project;return!t||e.projects.some(e=>e.key===t.key)?[...e.projects]:[t,...e.projects]}function e6(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 e9(e){let t=e.map(e=>({choice:e,name:e.alias??ek(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?ek(t.slice(0,r)):null}})}let e7={awaiting:"#d97706",unread:"#0891b2"};function te(e){return Number.isFinite(e)?Math.max(0,Math.floor(e)):0}let tt=null,tn=null,tr=new Map;function ti(){return[...document.querySelectorAll('link[rel="icon"]')]}async function ts(e,t){let n=await (!tn&&(tn=new Promise(e=>{let t=new Image;t.onload=()=>e(t),t.onerror=()=>e(null),t.src="/icons/icon-192.png"})),tn);if(!n||tt!==t)return;let r=document.createElement("canvas");r.width=192,r.height=192;let i=r.getContext("2d");if(!i)return;i.clearRect(0,0,192,192),i.drawImage(n,0,0,192,192);let s=e.count>1,l=s?56:42,o=192-l-10,a=l+10;if(i.beginPath(),i.arc(o,a,l,0,2*Math.PI),i.fillStyle=e7[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,a+4)),tt!==t)return;let d=r.toDataURL("image/png");for(let e of ti())e.href=d}function tl(e){return e.isComposing||229===e.keyCode}function to(e,t){let n=e.activeElement;return!!t&&(!n||n===e.body)&&(t.focus({preventScroll:!0}),!0)}let ta=Symbol.for("pi-web:page-id");function td(){let e=globalThis,t=e[ta];if("string"==typeof t)return t;let n=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return e[ta]=n,n}let tc=new Set,tu=1;function tp(e){let t=e.source.deref();return t&&2!==t.readyState?t:void 0}function th(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;for(let e of tc)tp(e)||tc.delete(e);let r={id:tu++,kind:e,label:n,source:new WeakRef(t),createdAt:Date.now(),opens:0,errors:0,lastOpenAt:null,lastErrorAt:null};return tc.add(r),"function"==typeof t.addEventListener&&(t.addEventListener("open",()=>{r.opens+=1,r.lastOpenAt=Date.now()}),t.addEventListener("error",()=>{r.errors+=1,r.lastErrorAt=Date.now()})),t}function tf(){let e=[];for(let t of tc){let n=tp(t);if(!n){tc.delete(t);continue}e.push({id:t.id,kind:t.kind,label:t.label,state:1===n.readyState?"open":"connecting",createdAt:t.createdAt,opens:t.opens,errors:t.errors,lastOpenAt:t.lastOpenAt,lastErrorAt:t.lastErrorAt})}return e}let tm={trackingSince:null,lastHiddenAt:null,lastVisibleAt:null,hiddenCount:0};function tg(){"u">typeof document&&("hidden"===document.visibilityState?(tm.lastHiddenAt=Date.now(),tm.hiddenCount+=1):tm.lastVisibleAt=Date.now())}function tx(){return{state:"u">typeof document&&"hidden"===document.visibilityState?"hidden":"visible",trackingSince:tm.trackingSince,lastHiddenAt:tm.lastHiddenAt,lastVisibleAt:tm.lastVisibleAt,hiddenCount:tm.hiddenCount}}let tv={count:0,failures:0,last:null};function tb(){return{...tv,last:tv.last?{...tv.last}:null}}function ty(){if("u"<typeof performance||"function"!=typeof performance.getEntriesByType)return null;let e=performance.getEntriesByType("navigation")[0],t=e?.nextHopProtocol;return t||("u">typeof location&&"http:"===location.protocol?"http/1.1":null)}let tw="pi-web:unread-session-ids";function tk(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function tj(e){let t,n=new Map;if(!e)return n;try{t=JSON.parse(e)}catch{return n}if(Array.isArray(t))for(let e of t)"string"==typeof e&&n.set(e,0);else if("object"==typeof t&&null!==t)for(let[e,r]of Object.entries(t))tk(r)&&n.set(e,r);return n}function tS(e,t){if(!t||0===e.size)return e;let n=null;for(let[i,s]of e){var r;void 0!==(r=Object.prototype.hasOwnProperty.call(t,i)?t[i]:void 0)&&r>=s&&(n??=new Map(e)).delete(i)}return n??e}let tC=["pointerdown","keydown","wheel","touchstart"],tN=null,tE=0,t$=null;function tI(){return"u">typeof document&&"visible"===document.visibilityState&&document.hasFocus()}function tM(){return tN??=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:12e4,r=null,i=!1,s=new Set,l=e=>null!==r&&e-r<n,o=t=>{let n=e()&&l(t),r=n&&!i;if(i=n,r)for(let e of[...s])try{e()}catch(e){console.error(e)}};return{noteInput(){let e=t();l(e)||(i=!1),r=e,o(e)},notePageChange(){let e=t();l(e)||(i=!1),o(e)},isAttended:()=>e()&&l(t()),onAttended:e=>(s.add(e),()=>s.delete(e))}}(tI,()=>performance.now())}function tT(){return 0!==tE&&tM().isAttended()}let tR="pi-web:sidebar-files-placement",tA="below";function tL(){try{var e;return e=window.localStorage.getItem(tR),"tab"===e?"tab":tA}catch{return tA}}let tz=null,tP=new Set;function tW(){return null===tz&&(tz=tL()),tz}function tO(){tP.forEach(e=>e())}function tF(e){if(null!==e.key&&e.key!==tR)return;let t=tL();t!==tz&&(tz=t,tO())}function tD(e){return 0===tP.size&&(window.addEventListener("storage",tF),tz=tL()),tP.add(e),()=>{tP.delete(e),0===tP.size&&window.removeEventListener("storage",tF)}}function tB(e){if(e!==tW()){tz=e;try{window.localStorage.setItem(tR,e)}catch{}tO()}}function tH(){return(0,i.useSyncExternalStore)(tD,tW,()=>tA)}var t_=n(21278);let tU="(max-width: 640px)",tK="(max-width: 480px)";function tq(e,t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)}function tV(e){return!!window.matchMedia&&window.matchMedia(e).matches}let tZ=e=>tq(tU,e),tJ=()=>tV(tU),tY=e=>tq(tK,e),tG=()=>tV(tK);function tX(){return!1}function tQ(){return(0,i.useSyncExternalStore)(tZ,tJ,tX)}function t0(e,t,n){let r=Number.isFinite(e)?e:t,i=Math.max(t,n);return Math.round(Math.max(t,Math.min(i,r)))}function t1(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function t2(e){let{ariaLabel:t,axis:n="horizontal",cssVariable:r,defaultWidth:s,getDefaultWidth:l,getMaxWidth:o,growthDirection:a,maxWidth:d,minWidth:c,persistClamp:u=!0,storageKey:p,widthRef:h}=e,f=(0,i.useRef)(null),m=(0,i.useRef)(null),g=(0,i.useRef)(!1),x=(0,i.useRef)(s),[v,b]=(0,i.useState)(s),[y,w]=(0,i.useState)(!1),[k,j]=(0,i.useState)(!1);(0,i.useEffect)(()=>{j(!0)},[]);let S=(0,i.useCallback)(()=>Math.min(d,Math.max(c,o())),[o,d,c]),C=(0,i.useCallback)(e=>t0(e,c,S()),[S,c]),N=(0,i.useCallback)(e=>{h.current=e,f.current?.style.setProperty(r,`${e}px`)},[r,h]),E=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{forcePersist:n=!1,persist:r=!0}=t,i=C(e),s=i!==h.current;return N(i),b(i),u?r&&(s||n)&&t1(p,i):n&&(x.current=t0(e,c,d),t1(p,x.current)),i},[N,C,d,c,u,p,h]),$=(0,i.useCallback)(()=>{E(u||m.current?h.current:x.current)},[E,u,h]),I=(0,i.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),M=(0,i.useCallback)(e=>{let t=m.current;if(t&&t.pointerId===e){m.current=null,I(t),w(!1),E(h.current,{forcePersist:u||h.current!==t.startWidth});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[E,u,I,h]),T=(0,i.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=m.current;t&&M(t.pointerId);let r=e.currentTarget;r.focus({preventScroll:!0}),r.setPointerCapture(e.pointerId),m.current={pointerId:e.pointerId,startPosition:"vertical"===n?e.clientY:e.clientX,startWidth:h.current,target:r,previousCursor:document.body.style.cursor,previousUserSelect:document.body.style.userSelect},document.body.style.cursor="vertical"===n?"row-resize":"col-resize",document.body.style.userSelect="none",w(!0)},[n,M,h]),R=(0,i.useCallback)(e=>{let t=m.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void M(e.pointerId);e.preventDefault();let r="right"===a||"down"===a?1:-1,i="vertical"===n?e.clientY:e.clientX,s=C(t.startWidth+(i-t.startPosition)*r);N(s),e.currentTarget.setAttribute("aria-valuenow",String(s)),e.currentTarget.setAttribute("aria-valuetext",`${s} px`)},[N,n,C,M,a]),A=(0,i.useCallback)(e=>{M(e.pointerId)},[M]),L=(0,i.useCallback)(e=>{M(e.pointerId)},[M]),z=(0,i.useCallback)(e=>{M(e.pointerId)},[M]),P=(0,i.useCallback)(()=>{E(l?.()??s,{forcePersist:!0})},[E,s,l]),W=(0,i.useCallback)(e=>{let t=e.shiftKey?32:12,r="right"===a||"down"===a,i="vertical"===n?"ArrowDown":"ArrowRight",s="vertical"===n?"ArrowUp":"ArrowLeft",l=u?h.current:Math.max(h.current,x.current);e.key===(r?i:s)?(e.preventDefault(),E(l+t,{forcePersist:!0})):e.key===(r?s:i)?(e.preventDefault(),E(h.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),E(c,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),E(Math.max(l,S()),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),P())},[n,E,S,a,c,u,P,h]);return(0,i.useEffect)(()=>{if(g.current)return;g.current=!0;let e=function(e){try{let t=window.localStorage.getItem(e);if(null===t)return null;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:null}catch{return null}}(p),t=e??l?.()??s;if(!u){x.current=t0(t,c,d),E(x.current,{persist:!1});return}let n=E(t,{persist:!1});null!==e&&e!==n&&t1(p,n)},[E,s,l,d,c,u,p]),(0,i.useEffect)(()=>{if(!g.current)return;$();let e=()=>{$()};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[$]),(0,i.useEffect)(()=>{if(!y)return;let e=()=>{let e=m.current;e&&M(e.pointerId)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[M,y]),(0,i.useEffect)(()=>()=>{let e=m.current;e&&(m.current=null,I(e))},[I]),{isResizing:y,panelRef:f,reclampWidth:$,resetWidth:P,separatorProps:{"aria-label":t,"aria-orientation":"vertical"===n?"horizontal":"vertical","aria-valuemax":k?S():d,"aria-valuemin":c,"aria-valuenow":v,"aria-valuetext":`${v} px`,onDoubleClick:P,onKeyDown:W,onLostPointerCapture:z,onPointerCancel:L,onPointerDown:T,onPointerMove:R,onPointerUp:A,role:"separator",tabIndex:0},width:v}}function t4(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,l=()=>{null!==s&&(clearTimeout(s),s=null)},o=()=>{n&&(l(),n.classList.add("scrollbar-visible"))},a=()=>{n&&(l(),s=setTimeout(()=>{s=null,n?.classList.remove("scrollbar-visible")},500))},d=()=>{o(),a()},c=()=>{if(!i){if(!(n=e.current)){r=requestAnimationFrame(c);return}n.addEventListener("pointerenter",o),n.addEventListener("pointerleave",a),n.addEventListener("scroll",d)}};return c(),()=>{i=!0,null!==r&&cancelAnimationFrame(r),n?.removeEventListener("pointerenter",o),n?.removeEventListener("pointerleave",a),n?.removeEventListener("scroll",d),l(),n?.classList.remove("scrollbar-visible")}},[t,e])}let t8="/api/sessions/ui-state";async function t3(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 t5(e){return e instanceof Error?e.message:String(e)}async function t6(e){if(!e.ok)throw Error(await t3(e));let t=await e.json(),n=t&&"object"==typeof t?function(e){if(!Z(e)||void 0!==e.version&&1!==e.version||void 0!==e.sessions&&!Z(e.sessions)||void 0!==e.projects&&!Z(e.projects))return null;let t=eo(),n=e.revision;for(let[r,i]of("number"==typeof n&&Number.isSafeInteger(n)&&n>=0&&(t.revision=n),Object.entries(e.sessions??{}))){if(!Y(r))continue;let e=function(e){if(!Z(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(!G(n))continue;let e=Z(r)&&J(r.pinnedAt)&&G(r.root)?{pinnedAt:r.pinnedAt,root:r.root}:null;e&&(t.projects[n]=e)}if(Array.isArray(e.projectOrder)){let n=new Set,r=ei(e.projectOrder.filter(e=>!(!G(e)||n.has(e))&&(n.add(e),!0)));r.length>0&&(t.projectOrder=r)}if(Z(e.projectNames)){let n={},r=0,i=1;for(let[t,s]of Object.entries(e.projectNames)){let e=Q(s);if(!G(t)||"string"!=typeof e)continue;let l=es(t,e);el(r+1,i+l)&&(n[t]=e,r++,i+=l)}r>0&&(t.projectNames=n)}if(Z(e.readAt)){let n={};for(let[t,r]of Object.entries(e.readAt))Y(t)&&J(r)&&(n[t]=r);let r=ea(n);Object.keys(r).length>0&&(t.readAt=r)}return t}(t.state):null;if(!n)throw Error("Invalid session UI state response");return n}function t9(){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]),l=(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:l,end:s}}var t7=n(47650);let ne={overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},nt={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},nn={padding:"6px 16px",borderRadius:6,fontSize:13},nr={...nn,border:0,background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600},ni={...nn,border:"1px solid var(--border)",background:"none",color:"var(--text-muted)"};async function ns(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 nl(e,t){let n=await fetch("/api/cwd/browse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e,name:t})}),r=await n.json();if(!n.ok||r.error||!r.path)throw Error(r.error??`HTTP ${n.status}`);return r.path}function no(){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 na(){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 nd(e){let{onCancel:t,onSelect:n,initialPath:s,busy:l=!1,error:o}=e,{t:a}=(0,t_.s)(),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(""),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(s??""),[x,v]=(0,i.useState)([]),[b,y]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!0),[C,N]=(0,i.useState)(!1),[E,$]=(0,i.useState)(""),[I,M]=(0,i.useState)(null),[T,R]=(0,i.useState)(!1),A=(0,i.useRef)(!1),L=(0,i.useRef)(!1),z=(0,i.useRef)(null),P=(0,i.useRef)(!1),W=(0,i.useCallback)(async e=>{S(!0),k(null);try{let t=await ns(e),n=t.path??e??"/";return p(n),f(t.parentPath??null),g(n),v(t.directories??[]),y(t.drives??null),n}catch(e){return k(e instanceof Error?e.message:String(e)),null}finally{S(!1)}},[]);(0,i.useEffect)(()=>{c(document.body),W(s||void 0)},[s,W]),(0,i.useEffect)(()=>(P.current=!0,()=>{P.current=!1}),[]),(0,i.useEffect)(()=>{(w||o)&&z.current?.focus()},[w,o]);let O=()=>{T||(N(!1),$(""),M(null))},F=async()=>{let e=E.trim();if(u&&e&&!T){R(!0),M(null);try{let t=await nl(u,e);N(!1),$(""),await W(t)}catch(e){M(e instanceof Error?e.message:String(e))}finally{R(!1)}}},D=m.trim(),B=D!==u,H=!!D&&!l&&!j,_=!!u&&!B&&!l&&!j,U=!!h||/^[a-zA-Z]:[\\/]?$/.test(u),K=async()=>{let e=B?await W(D):u;e&&P.current&&n(e)};return d?(0,t7.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":a("directoryPicker.selectDirectory"),onPointerDown:e=>{A.current=e.target===e.currentTarget},onClick:e=>{let n=A.current;A.current=!1,n&&e.target===e.currentTarget&&!l&&t()},onPointerCancel:()=>{A.current=!1},onKeyDown:e=>{!e.nativeEvent.isComposing&&229!==e.keyCode&&("Escape"!==e.key||l||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:{...ne,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:a("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:t,disabled:l,title:a("i18n.close"),"aria-label":a("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:l?"default":"pointer",opacity:l?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=m.trim();t&&W(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 W(h??void 0),disabled:j||!U,title:a("directoryPicker.goToParent"),"aria-label":a("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:U?"pointer":"default",opacity:U?1:.45},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:a("directoryPicker.directoryPath")}),(0,r.jsx)("input",{ref:z,className:"directory-picker-path",id:"directory-path",type:"text",value:m,placeholder:a("directoryPicker.pathPlaceholder"),autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),k(null)},style:{...nt,minWidth:0,flex:1}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:j||!m.trim(),title:a("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:j||!m.trim()?"default":"pointer",opacity:j||!m.trim()?.6:1},children:a("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[j?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.loadingDirectories")}):null!==b?(0,r.jsx)(r.Fragment,{children:b.length>0?b.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void W(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(na,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void W(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(no,{}),(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:a("directoryPicker.noSubdirectories")}),(w||o)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??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),M(null)},disabled:!_,style:{...ni,marginRight:"auto",opacity:_?1:.6,cursor:_?"pointer":"default"},children:a("directoryPicker.newDirectory")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:t,disabled:l,style:{...ni,cursor:l?"default":"pointer"},children:a("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>void K(),disabled:!H,title:B&&D?a("directoryPicker.selectTypedPath",{path:D}):a("directoryPicker.selectCurrentDirectory"),style:{...nr,opacity:H?1:.6,cursor:H?"pointer":"default"},children:a(l?"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&&O()},onPointerCancel:()=>{L.current=!1},onKeyDown:e=>{e.stopPropagation(),e.nativeEvent.isComposing||229===e.keyCode||"Escape"===e.key&&O()},children:(0,r.jsxs)("form",{role:"dialog","aria-modal":"true","aria-label":a("directoryPicker.createDirectory"),onSubmit:e=>{e.preventDefault(),F()},style:{...ne,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:a("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:a("directoryPicker.directoryName")}),(0,r.jsx)("input",{id:"new-directory-name",value:E,autoFocus:!0,autoComplete:"off",spellCheck:!1,placeholder:a("directoryPicker.directoryNamePlaceholder"),onChange:e=>{$(e.target.value),M(null)},disabled:T,className:"directory-picker-path",style:{...nt,width:"100%",boxSizing:"border-box"}}),I&&(0,r.jsx)("div",{style:{marginTop:7,color:"#dc2626",fontSize:11,lineHeight:1.35},children:I}),(0,r.jsxs)("div",{style:{display:"flex",gap:6,marginTop:10},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:T||!E.trim(),style:{...nr,flex:1,opacity:T?.65:1,cursor:T||!E.trim()?"default":"pointer"},children:a(T?"directoryPicker.creating":"directoryPicker.create")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:O,disabled:T,style:{...ni,flex:1,cursor:T?"default":"pointer"},children:a("i18n.cancel")})]})]})]})})]})}),d):null}function nc(e){let{onClick:t,title:n}=e;return(0,r.jsx)("button",{type:"button",onClick:t,title:n,"aria-label":n,style:{width:24,height:24,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"none",borderRadius:4,background:"none",color:"var(--text-dim)",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m6 6 12 12"}),(0,r.jsx)("path",{d:"m18 6-12 12"})]})})}let nu="/icons/catppuccin";function np(e){let{name:t,size:n=14}=e,i={width:n,height:n,"--catppuccin-icon-light":`url(${nu}/latte/${t}.svg)`,"--catppuccin-icon-dark":`url(${nu}/mocha/${t}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:i})}function nh(e){let{size:t=14,open:n=!1}=e;return(0,r.jsx)(np,{name:n?"_folder_open":"_folder",size:t})}function nf(e){let{size:t=14}=e;return(0,r.jsx)(np,{name:"_file",size:t})}let nm={ts:"typescript",tsx:"typescript-react",js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"javascript-react",py:"python",json:"json",jsonl:"json",css:"css",less:"css",scss:"sass",html:"html",htm:"html",md:"markdown",mdx:"markdown",yaml:"yaml",yml:"yaml",toml:"toml",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",rs:"rust",go:"go",sql:"database",graphql:"graphql",gql:"graphql",tf:"terraform",hcl:"terraform",docx:"ms-word",pdf:"pdf",lock:"lock"};function ng(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:14,n=e.toLowerCase(),i="dockerfile"===n||n.startsWith("dockerfile.")?"docker":".env"===n||n.startsWith(".env.")?"env":[".gitignore",".gitattributes",".gitmodules"].includes(n)?"git":"package-lock.json"===n?"npm-lock":"bun.lock"===n?"bun-lock":["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"].includes(n)?"next":[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(n)?"eslint":["yarn.lock","pnpm-lock.yaml","cargo.lock"].includes(n)?"lock":n.endsWith(".config.ts")||n.endsWith(".config.js")||n.endsWith(".config.mjs")||n.endsWith(".config.cjs")?"config":void 0;if(i)return(0,r.jsx)(np,{name:i,size:t});let s=nm[n.split(".").pop()??""];return s?(0,r.jsx)(np,{name:s,size:t}):(0,r.jsx)(nf,{size:t})}function nx(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function nv(e){let t=nx(e),n=t.split("/").filter(Boolean);return t.startsWith("//")&&n.length>0&&(n[0]=`//${n[0]}`),n.map(encodeURIComponent).join("/")}function nb(e){let t=nx(e).replace(/\/+$/,"");return t.split("/").pop()??t}function ny(e){let t=nx(e).replace(/\/+$/,""),n=t.lastIndexOf("/");return n<0?"":0===n?"/":2===n&&/^[a-zA-Z]:\//.test(t)?t.slice(0,3):t.slice(0,n)}function nw(e,t){if(!t)return e;let n=nx(e),r=nx(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}function nk(e,t){return`${nx(e).replace(/\/$/,"")}/${t}`}function nj(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let n=/(?:^|\s)@([^\s"]*)$/.exec(e);return n?{start:e.length-(n[1].length+1),query:n[1],quoted:!1}:null}function nS(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function nC(e,t){if(!e)return!0;let n=0;for(let r=0;r<t.length&&n<e.length;r++)t[r]===e[n]&&n++;return n===e.length}function nN(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function nE(e,t,n,r){return new Promise((i,s)=>{let l=new FormData;t.forEach(e=>l.append("files",e,e.name));let o=new XMLHttpRequest;o.open("POST",`/api/files/${nv(e)}?type=upload&conflict=${n}`),o.upload.onprogress=e=>{r&&e.lengthComputable&&e.total>0&&r(Math.round(e.loaded/e.total*100))},o.onerror=()=>s(Error("Network error while uploading files")),o.onabort=()=>s(Error("Upload cancelled")),o.onload=()=>{let e={};try{e=JSON.parse(o.responseText)}catch{o.responseText&&(e.error=o.responseText)}i({status:o.status,data:e})},o.send(l)})}function n$(e){let t=[],n=new Map;for(let r of e){let e=r.split("/"),i=t,s="";for(let t=0;t<e.length;t++){s=s?`${s}/${e[t]}`:e[t];let r=n.get(s);r||(r={name:e[t],path:s,isDir:t<e.length-1,children:[]},n.set(s,r),i.push(r)),i=r.children}}let r=e=>{e.sort((e,t)=>e.isDir!==t.isDir?e.isDir?-1:1:e.name.localeCompare(t.name)),e.forEach(e=>r(e.children))};return r(t),t}function nI(e){return Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)}function nM(e){let t=[];for(let n of Array.from(e.items)){if("file"!==n.kind)continue;let e=n.webkitGetAsEntry?.();if(e?.isDirectory){t.push({kind:"folder",name:e.name});continue}let r=n.getAsFile();r&&t.push({kind:"file",file:r})}return t.length>0?t:Array.from(e.files).map(e=>({kind:"file",file:e}))}let nT=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:20,t=new Map;return{save(n,r){if(t.delete(n),0!==r.size)for(let i of(t.set(n,new Set(r)),t.keys())){if(t.size<=e)break;t.delete(i)}},restore:e=>new Set(t.get(e))}}();async function nR(e,t){let n=`${t} (HTTP ${e.status})`;try{let t=await e.json();t.error&&(n=t.error)}catch{}return Error(n)}async function nA(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=nv(e),r=await fetch(`/api/files/${n}?type=list${t?"&hidden=1":""}`);if(!r.ok)throw await nR(r,"Failed to load files");return((await r.json()).entries??[]).map(t=>({name:t.name,fullPath:nk(e,t.name),isDir:t.isDir,size:t.size,children:t.isDir?[]:void 0,loaded:!t.isDir,outsideLinkTarget:t.outsideLinkTarget,outsideLinkEncloses:t.outsideLinkEncloses,hidden:t.hidden}))}async function nL(e,t){let n=await fetch(`/api/files/${nv(e)}?type=allow-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:t})});if(!n.ok)throw await nR(n,"Failed to allow the linked folder")}async function nz(e,t){let n=new URLSearchParams({cwd:e}),r=await fetch(`/api/git/status?${n.toString()}`,{signal:t});if(!r.ok)throw Error(`Failed to load Git status (HTTP ${r.status})`);return r.json()}let nP={modified:"files.modified",added:"files.added",deleted:"files.deleted",renamed:"files.renamed",untracked:"files.untracked",conflict:"files.conflict"},nW={modified:"#d6a84b",added:"#4ade80",deleted:"#f87171",renamed:"#60a5fa",untracked:"#4ade80",conflict:"#f87171"};function nO(e){let{status:t,t:n}=e;return(0,r.jsx)("span",{title:n(nP[t.status]),"aria-label":n(nP[t.status]),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:nW[t.status],fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600},children:t.code})}function nF(e){let{size:t=11}=e;return(0,r.jsxs)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function nD(e){let{size:t=11}=e;return(0,r.jsxs)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M15 3h6v6"}),(0,r.jsx)("path",{d:"M10 14 21 3"}),(0,r.jsx)("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]})}let nB={ignored:"files.hiddenIgnored",excluded:"files.hiddenExcluded"};function nH(e){let{node:t,depth:n,cwd:s,onOpenFile:l,onAtMention:o,expandedPaths:a,onToggleExpanded:d,refreshToken:c,highlightedPaths:u,gitStatusByPath:p,changedDirectoryPaths:h,showHidden:f=!1,parentHidden:m,dropTargetPath:g,onDropFiles:x,onDropTargetChange:v,t:b}=e,y=a.has(t.fullPath),w=t.hidden??m,k=t.isDir&&g===t.fullPath,j=u.has(t.fullPath),S=nx(t.fullPath),C=p.get(S),N=t.isDir&&(void 0!==C||h.has(S)),[E,$]=(0,i.useState)(t.children??[]),[I,M]=(0,i.useState)(t.loaded??!1),[T,R]=(0,i.useState)(!1),[A,L]=(0,i.useState)(null),[z,P]=(0,i.useState)(!1),[W,O]=(0,i.useState)(null),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)(null),_=t.outsideLinkTarget&&t.outsideLinkTarget!==W?t.outsideLinkTarget:null;(0,i.useEffect)(()=>{O(null),H(null)},[t.outsideLinkTarget]);let U=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!I||e){R(!0),L(null);try{let e=await nA(t.fullPath,f);$(e),M(!0)}catch(e){L(e instanceof Error?e.message:String(e))}finally{R(!1)}}},[I,t.fullPath,f]),K=(0,i.useRef)(f);(0,i.useEffect)(()=>{K.current===f||(K.current=f,I&&(y&&!_?U(!0):M(!1)))},[f]),(0,i.useEffect)(()=>{t.isDir&&y&&!I&&!_&&U()},[]),(0,i.useEffect)(()=>{void 0!==c&&I&&!_&&(y?U(!0):M(!1))},[c]);let q=(0,i.useCallback)(()=>{if(t.isDir){let e=!y;d(t.fullPath,e),!e||I||_||U()}else l(t.fullPath,t.name)},[t.isDir,t.fullPath,t.name,I,y,_,U,l,d]),V=(0,i.useCallback)(async e=>{if((e.stopPropagation(),_)&&(!t.outsideLinkEncloses||window.confirm(b("files.allowEnclosingLinkConfirm",{target:_})))){D(!0),H(null);try{await nL(t.fullPath,_),O(_),await U(!0)}catch(e){H(e instanceof Error?e.message:String(e))}finally{D(!1)}}},[t.fullPath,t.outsideLinkEncloses,_,U,b]);return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{onClick:q,onMouseEnter:()=>P(!0),onMouseLeave:()=>P(!1),onDragOver:t.isDir?e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect="copy",v?.(t.fullPath))}:void 0,onDrop:t.isDir?e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.stopPropagation(),v?.(null),x?.(t.fullPath,nM(e.dataTransfer)))}:void 0,style:{position:"relative",display:"flex",alignItems:"center",gap:4,paddingLeft:8+14*n,paddingRight:8,height:"var(--file-row-height)",cursor:"pointer",background:k?"color-mix(in srgb, var(--accent) 16%, transparent)":z?"var(--bg-hover)":"transparent",outline:k?"1px dashed var(--accent)":"none",outlineOffset:-1,borderRadius:4,userSelect:"none"},children:[t.isDir&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:y?"rotate(90deg)":"none",transition:"transform 0.1s"},children:(0,r.jsx)("polyline",{points:"3 2 7 5 3 8"})}),!t.isDir&&(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",opacity:w?.55:1},children:t.isDir?(0,r.jsx)(nh,{size:14,open:y}):ng(t.name,14)}),(0,r.jsx)("span",{"data-hidden-reason":w,style:{fontSize:12,color:w?"var(--text-muted)":"var(--text)",opacity:w?.55:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},title:w?`${t.fullPath}
4
+ ${b(nB[w])}`:t.fullPath,children:t.name}),!z&&_&&(0,r.jsx)("span",{title:b("files.outsideLink",{target:_}),"aria-label":b("files.outsideLink",{target:_}),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)"},children:(0,r.jsx)(nD,{})}),j&&(0,r.jsx)("span",{title:b("files.newlyUploaded"),"aria-label":b("files.newlyUploaded"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#3b82f6"}})}),!z&&!t.isDir&&C&&(0,r.jsx)(nO,{status:C,t:b}),!z&&N&&(0,r.jsx)("span",{title:b("files.containsChangedFiles"),"aria-label":b("files.containsChangedFiles"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#d6a84b"}})}),T&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",children:(0,r.jsx)("path",{d:"M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4"})}),o&&z&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),o(nw(t.fullPath,s),t.isDir)},title:b("files.insertPath"),style:{position:"absolute",right:t.isDir?4:28,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:"calc(var(--file-row-height) - 4px)",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(nF,{}),b("files.mention")]}),z&&!t.isDir&&(0,r.jsx)("a",{href:`/api/files/${nv(t.fullPath)}?type=download`,download:!0,onClick:e=>e.stopPropagation(),title:b("files.download"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 5px",height:"calc(var(--file-row-height) - 4px)",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap",textDecoration:"none"},children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})]}),t.isDir&&y&&_&&(0,r.jsxs)("div",{style:{paddingLeft:8+(n+1)*14,paddingRight:8,paddingTop:3,paddingBottom:5,display:"flex",flexDirection:"column",alignItems:"flex-start",gap:4,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{wordBreak:"break-all"},children:b("files.outsideLink",{target:_})}),t.outsideLinkEncloses&&(0,r.jsx)("span",{style:{color:"#f59e0b"},children:b("files.outsideLinkEncloses")}),(0,r.jsx)("button",{type:"button",onClick:V,disabled:F,title:b("files.allowOutsideLinkTitle",{target:_}),style:{height:"calc(var(--file-row-height) - 4px)",padding:"0 8px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:F?"default":"pointer",opacity:F?.6:1,fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:b("files.allowOutsideLink")}),B&&(0,r.jsx)("span",{role:"alert",style:{color:"#f87171",wordBreak:"break-word"},children:B})]}),t.isDir&&y&&!_&&(0,r.jsxs)("div",{children:[E.map(e=>(0,r.jsx)(nH,{node:e,depth:n+1,cwd:s,onOpenFile:l,onAtMention:o,expandedPaths:a,onToggleExpanded:d,refreshToken:c,highlightedPaths:u,gitStatusByPath:p,changedDirectoryPaths:h,showHidden:f,parentHidden:w,dropTargetPath:g,onDropFiles:x,onDropTargetChange:v,t:b},e.fullPath)),0===E.length&&I&&!A&&(0,r.jsx)("div",{style:{paddingLeft:8+(n+1)*14,fontSize:11,color:"var(--text-dim)",height:22,display:"flex",alignItems:"center"},children:"empty"}),A&&(0,r.jsx)("div",{role:"alert",style:{paddingLeft:8+(n+1)*14,paddingRight:8,paddingTop:3,paddingBottom:3,fontSize:11,color:"#f87171",wordBreak:"break-word"},children:A})]})]})}function n_(e){let{status:t,cwd:n,onOpenFile:s,onAtMention:l,t:o,depth:a=0,treeMode:d=!1}=e,[c,u]=(0,i.useState)(!1),p=nb(t.filePath),h=nw(t.filePath,n),f=h.lastIndexOf("/"),m=!d&&f>=0?h.slice(0,f+1):"",g=d?p:f>=0?h.slice(f+1):h;return(0,r.jsxs)("div",{onClick:()=>s(t.filePath,p,{modeHint:"diff"}),onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),title:t.filePath,style:{display:"flex",alignItems:"center",gap:d?4:6,paddingLeft:d?8+14*a:10,paddingRight:8,height:"var(--file-row-height)",cursor:"pointer",background:c?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none",position:"relative"},children:[(0,r.jsx)(nO,{status:t,t:o}),d&&(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",opacity:.85},children:ng(p,13)}),(0,r.jsxs)("span",{title:t.filePath,style:{fontSize:12,color:"var(--text)",display:"flex",alignItems:"center",minWidth:0,flex:1},children:[m&&(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:"0 1 auto",minWidth:0,color:"var(--text-dim)"},children:m}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:+!!d,maxWidth:"100%"},children:g})]}),l&&c&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),l(h,!1)},title:o("files.insertPath"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:"calc(var(--file-row-height) - 4px)",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(nF,{}),o("files.mention")]})]})}function nU(e){let{node:t,depth:n,open:s,onToggle:l}=e,[o,a]=(0,i.useState)(!1);return(0,r.jsxs)("div",{onClick:()=>l(t.path,!s),onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),title:t.path,style:{display:"flex",alignItems:"center",gap:4,paddingLeft:8+14*n,paddingRight:8,height:"var(--file-row-height)",cursor:"pointer",background:o?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:s?"rotate(90deg)":"none",transition:"transform 0.1s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"3 2 7 5 3 8"})}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:(0,r.jsx)(nh,{size:14,open:s})}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:t.name})]})}function nK(e){let{nodes:t,depth:n,cwd:i,statusByPath:s,collapsedPaths:l,onToggleExpanded:o,onOpenFile:a,onAtMention:d,t:c}=e;return(0,r.jsx)(r.Fragment,{children:t.map(e=>{if(e.isDir){let t=!l.has(e.path);return(0,r.jsxs)("div",{children:[(0,r.jsx)(nU,{node:e,depth:n,open:t,onToggle:o}),t&&(0,r.jsx)(nK,{nodes:e.children,depth:n+1,cwd:i,statusByPath:s,collapsedPaths:l,onToggleExpanded:o,onOpenFile:a,onAtMention:d,t:c})]},`dir:${e.path}`)}let t=s.get(e.path);return t?(0,r.jsx)(n_,{status:t,cwd:i,onOpenFile:a,onAtMention:d,t:c,depth:n,treeMode:!0},t.filePath):null})})}function nq(e){let{mode:t}=e;return"tree"===t?(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M8 6h13"}),(0,r.jsx)("path",{d:"M8 12h13"}),(0,r.jsx)("path",{d:"M8 18h13"}),(0,r.jsx)("path",{d:"M3 6h.01"}),(0,r.jsx)("path",{d:"M3 12h.01"}),(0,r.jsx)("path",{d:"M3 18h.01"})]}):(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M6 3v12"}),(0,r.jsx)("path",{d:"M18 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"}),(0,r.jsx)("path",{d:"M6 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"}),(0,r.jsx)("path",{d:"M18 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"}),(0,r.jsx)("path",{d:"M9 12h6"}),(0,r.jsx)("path",{d:"M12 12v3"})]})}let nV=(0,i.forwardRef)(function(e,t){let{cwd:n,onOpenFile:s,refreshKey:l,onAtMention:o,onAtMentions:a,onUploadBusyChange:d,changesCollapsed:c,onChangesCountChange:u,fileSearchOpen:p=!1,onFileSearchOpenChange:h,showHidden:f=!1}=e,{t:m}=(0,t_.s)(),[g,x]=(0,i.useState)([]),[v,b]=(0,i.useState)(!0),[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(new Set),[S,C]=(0,i.useState)(0),[N,E]=(0,i.useState)(new Set),[$,I]=(0,i.useState)([]),[M,T]=(0,i.useState)({additions:0,deletions:0}),[R,A]=(0,i.useState)("list"),[L,z]=(0,i.useState)(()=>new Set),[P,W]=(0,i.useState)("idle"),[O,F]=(0,i.useState)(0),[D,B]=(0,i.useState)(null),[H,_]=(0,i.useState)(null),[U,K]=(0,i.useState)(null),[q,V]=(0,i.useState)(""),[Z,J]=(0,i.useState)([]),[Y,G]=(0,i.useState)(!1),[X,Q]=(0,i.useState)(!1),[ee,et]=(0,i.useState)(new Set),en=(0,i.useRef)(null),[er,ei]=(0,i.useState)(!1),[es,el]=(0,i.useState)(null),eo=(0,i.useRef)(0),ea=(0,i.useRef)(null),ed=(0,i.useRef)(k),ec=(0,i.useRef)(null),eu=`${l??0}:${S}`,ep="idle"!==P,eh=q.trim().length>0;(0,i.useEffect)(()=>{if(!p)return;let e=q.trim();if(!e){J([]),G(!1),Q(!1);return}let t=new AbortController;G(!0),Q(!1);let r=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(n)}&q=${encodeURIComponent(e)}`,{signal:t.signal}).then(e=>e.ok?e.json():Promise.reject(Error("Search failed"))).then(e=>J((e.matches??[]).filter(e=>!e.isDir).map(e=>e.path))).catch(()=>{t.signal.aborted||(J([]),Q(!0))}).finally(()=>{t.signal.aborted||G(!1)})},150);return()=>{clearTimeout(r),t.abort()}},[n,p,q]),(0,i.useEffect)(()=>{p&&en.current?.focus()},[p]),(0,i.useEffect)(()=>{if(0===Z.length)return;let e=new Set;for(let t of Z){let r=t.split("/"),i="";for(let t=0;t<r.length-1;t++)i=i?`${i}/${r[t]}`:r[t],e.add(nk(n,i))}et(t=>{let n=!1,r=new Set(t);for(let t of e)r.has(t)||(r.add(t),n=!0);return n?r:t})},[n,Z]);let ef=(0,i.useMemo)(()=>{let e=t=>({name:t.name,fullPath:nk(n,t.path),isDir:t.isDir,size:0,children:t.children.map(e),loaded:!0});return n$(Z).map(e)},[n,Z]),em=(0,i.useMemo)(()=>new Map($.map(e=>[nx(e.filePath),e])),[$]),eg=(0,i.useMemo)(()=>{let e=new Set,t=nx(n).replace(/\/$/,"");for(let n of $){let r=ny(nx(n.filePath));for(;(r===t||r.startsWith(`${t}/`))&&(e.add(r),r!==t);){let e=ny(r);if(e===r)break;r=e}}return e},[n,$]),ex=(0,i.useMemo)(()=>new Map($.map(e=>[nx(nw(e.filePath,n)).replace(/^\/+/,""),e])),[n,$]),ev=(0,i.useMemo)(()=>n$([...ex.keys()]),[ex]),eb=(0,i.useCallback)((e,t)=>{j(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},[]),ey=(0,i.useCallback)((e,t)=>{let n=e.uploaded??[];_({directory:t,uploaded:n,skipped:e.skipped??[],errors:e.errors??[]}),n.length>0&&(E(new Set(n.map(e=>nk(t,e)))),C(e=>e+1))},[]),ew=(0,i.useCallback)(async(e,t,n)=>{K(null),B(null),F(0),W("uploading");try{let{status:r,data:i}=await nE(n,e,t,F);if(409===r&&i.conflicts?.length)return void K({directory:n,files:e,conflicts:i.conflicts,nonReplaceable:i.nonReplaceable??[]});if(r<200||r>=300)throw Error(i.error??`Upload failed (HTTP ${r})`);F(100),ey(i,n)}catch(e){B(e instanceof Error?e.message:String(e))}finally{W("idle")}},[ey]),ek=(0,i.useCallback)(async(e,t)=>{if(0!==e.length&&!ep){_(null),E(new Set),K(null),B(null),F(0),W("checking");try{let n=await fetch(`/api/files/${nv(t)}?type=upload-check`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileNames:e.map(e=>e.name)})}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error??`Upload check failed (HTTP ${n.status})`);if(r.conflicts?.length)return void K({directory:t,files:e,conflicts:r.conflicts,nonReplaceable:r.nonReplaceable??[]});await ew(e,"error",t)}catch(e){B(e instanceof Error?e.message:String(e))}finally{W("idle")}}},[ew,ep]),ej=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",ek(t,n)},[n,ek]);(0,i.useImperativeHandle)(t,()=>({openUploadPicker(){ep||ec.current?.click()}}),[ep]);let eS=(0,i.useCallback)(()=>{eo.current=0,ei(!1),el(null)},[]),eC=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),eo.current+=1,ei(!0))},[]),eN=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.dataTransfer.dropEffect="copy",el(e=>null===e?e:null))},[]),eE=(0,i.useCallback)(()=>{eo.current<=0||(eo.current-=1,0===eo.current&&(eo.current=0,ei(!1),el(null)))},[]),e$=(0,i.useCallback)((e,t)=>{eS();let n=t.flatMap(e=>"file"===e.kind?[e.file]:[]),r=t.flatMap(e=>"folder"===e.kind?[e.name]:[]);ek(n,e).then(()=>{if(0===r.length)return;let e=m("chat.dropFoldersUnsupported",{names:r.join(", ")});B(t=>t&&n.length>0?t:e)})},[ek,eS,m]),eI=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.stopPropagation(),e$(es??n,nM(e.dataTransfer)))},[n,es,e$]),eM=(0,i.useCallback)(e=>{el(t=>t===e?t:e)},[]);(0,i.useEffect)(()=>{d?.(ep)},[d,ep]),(0,i.useEffect)(()=>()=>d?.(!1),[d]),(0,i.useEffect)(()=>{ed.current=k},[k]),(0,i.useEffect)(()=>()=>{null!==ea.current&&nT.save(ea.current,ed.current)},[]),(0,i.useEffect)(()=>{let e=ea.current,t=e!==n;if(ea.current=n,t){null!==e&&nT.save(e,ed.current);let t=nT.restore(n);ed.current=t,j(t),E(new Set),_(null),K(null),B(null)}b(t),w(null);let r=!1;return nA(n,f).then(e=>{r||x(e)}).catch(e=>{r||w(e instanceof Error?e.message:String(e))}).finally(()=>{r||b(!1)}),()=>{r=!0}},[n,l,S,f]),(0,i.useEffect)(()=>{let e=()=>C(e=>e+1);return window.addEventListener("focus",e),()=>window.removeEventListener("focus",e)},[]),(0,i.useEffect)(()=>{let e=!1,t=new AbortController;return nz(n,t.signal).then(t=>{e||(I(t.isGitRepository?t.files:[]),T(t.isGitRepository?{additions:t.additions,deletions:t.deletions}:{additions:0,deletions:0}))}).catch(()=>{e||(I([]),T({additions:0,deletions:0}))}),()=>{e=!0,t.abort()}},[n,l,S]),(0,i.useEffect)(()=>{u?.($.length)},[$,u]),(0,i.useEffect)(()=>{A(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:eV();if(!e)return"list";try{return"tree"===e.getItem(eU)?"tree":"list"}catch{return"list"}}())},[]);let eT=(0,i.useCallback)((e,t)=>{z(n=>{let r=new Set(n);return t?r.delete(e):r.add(e),r})},[]),eR=(0,i.useCallback)(()=>{A(e=>{let t="list"===e?"tree":"list";return!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eV();if(t)try{t.setItem(eU,e)}catch{}}(t),t})},[]),eA=ep||null!==U||null!==D||null!==H,eL=(0,i.useCallback)(()=>{H&&0!==H.uploaded.length&&a?.(H.uploaded.map(e=>nw(nk(H.directory,e),n)))},[n,a,H]);return(0,r.jsxs)("div",{style:{minHeight:"100%"},onDragEnter:eC,onDragOver:eN,onDragLeave:eE,onDrop:eI,children:[(0,r.jsx)("input",{ref:ec,type:"file",multiple:!0,hidden:!0,onChange:ej}),eA&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[ep&&(0,r.jsxs)("div",{role:"status","aria-live":"polite","aria-label":"checking"===P?m("files.checking"):m("files.uploading",{progress:O}),children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,minHeight:14,color:"var(--text-muted)"},children:["checking"===P?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite"},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-5.7-8.4"})}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 16V4"}),(0,r.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,r.jsx)("path",{d:"M5 20h14"})]}),"uploading"===P&&(0,r.jsxs)("span",{style:{fontSize:10},children:[O,"%"]})]}),"uploading"===P&&(0,r.jsx)("div",{style:{height:3,marginTop:4,overflow:"hidden",borderRadius:2,background:"var(--border)"},children:(0,r.jsx)("div",{style:{width:`${O}%`,height:"100%",background:"var(--text-muted)",transition:"width 120ms ease"}})})]}),U&&(0,r.jsxs)("div",{role:"alert",style:{padding:7,border:"1px solid color-mix(in srgb, #f59e0b 55%, var(--border))",borderRadius:4,background:"color-mix(in srgb, #f59e0b 9%, var(--bg-panel))"},children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text)",lineHeight:1.35,overflowWrap:"anywhere"},children:m("files.conflictSummary",{count:U.conflicts.length,countSuffix:1===U.conflicts.length?"":"s",files:U.conflicts.join(", ")})}),U.nonReplaceable.length>0&&(0,r.jsx)("div",{style:{marginTop:3,fontSize:10,color:"#f59e0b",lineHeight:1.35,overflowWrap:"anywhere"},children:m("files.cannotReplace",{files:U.nonReplaceable.join(", ")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:7},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void ew(U.files,"overwrite",U.directory),style:{height:22,padding:"0 7px",border:"1px solid #ef4444",borderRadius:4,background:"transparent",color:"#ef4444",cursor:"pointer",fontSize:10},children:m("files.replace")}),(0,r.jsx)("button",{type:"button",onClick:()=>void ew(U.files,"skip",U.directory),style:{height:22,padding:"0 7px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",fontSize:10},children:m("files.skipExisting")}),(0,r.jsx)("button",{type:"button",onClick:()=>K(null),style:{height:22,padding:"0 7px",border:"none",borderRadius:4,background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:10},children:m("files.cancel")})]})]}),D&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,fontSize:11,lineHeight:1.35,color:"#f87171"},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflowWrap:"anywhere"},children:D}),(0,r.jsx)(nc,{onClick:()=>B(null),title:m("files.dismissError")})]}),H&&(0,r.jsxs)("div",{"aria-live":"polite",children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:22,fontSize:11},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1,display:"flex",alignItems:"center",gap:8},children:[H.uploaded.length>0&&(0,r.jsxs)("span",{title:m("files.uploadedCount",{count:H.uploaded.length}),"aria-label":m("files.uploadedCount",{count:H.uploaded.length}),style:{display:"flex",alignItems:"center",gap:3,color:"#22c55e"},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m5 12 4 4L19 6"})}),(0,r.jsx)("span",{children:H.uploaded.length})]}),H.skipped.length>0&&(0,r.jsxs)("span",{title:m("files.skippedCount",{count:H.skipped.length}),"aria-label":m("files.skippedCount",{count:H.skipped.length}),style:{display:"flex",alignItems:"center",gap:3,color:"var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M8 12h8"})]}),(0,r.jsx)("span",{children:H.skipped.length})]}),H.errors.length>0&&(0,r.jsxs)("span",{title:m("files.failedCount",{count:H.errors.length}),"aria-label":m("files.failedCount",{count:H.errors.length}),style:{display:"flex",alignItems:"center",gap:3,color:"#f87171"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 3 2.5 20h19L12 3Z"}),(0,r.jsx)("path",{d:"M12 9v4"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{children:H.errors.length})]})]}),H.uploaded.length>0&&a&&(0,r.jsxs)("button",{type:"button",onClick:eL,title:1===H.uploaded.length?m("files.addUploadedFile"):m("files.addAllUploadedFiles"),"aria-label":1===H.uploaded.length?m("files.addUploadedFile"):m("files.addAllUploadedFiles"),style:{height:22,padding:"0 7px",display:"flex",alignItems:"center",justifyContent:"center",gap:4,flexShrink:0,border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(nF,{}),m("files.mention")]}),(0,r.jsx)(nc,{onClick:()=>_(null),title:m("files.dismissUploadResults")})]}),H.errors.map(e=>(0,r.jsxs)("div",{title:e.error,style:{display:"flex",alignItems:"center",gap:4,marginTop:3,minWidth:0,fontSize:10,color:"#f87171"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 8v5"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.name))]})]}),p&&(0,r.jsxs)("div",{style:{padding:"2px 8px 6px"},children:[(0,r.jsxs)("div",{style:{position:"relative"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]}),(0,r.jsx)("input",{ref:en,id:"file-search-input",value:q,onChange:e=>V(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),h?.(!1))},placeholder:m("sidebar.searchFilesPlaceholder"),"aria-label":m("sidebar.searchFiles"),style:{width:"100%",boxSizing:"border-box",padding:"6px 24px",border:"1px solid var(--border)",borderRadius:8,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}}),q&&(0,r.jsx)("button",{type:"button",onClick:()=>V(""),title:m("sidebar.clearSearch"),"aria-label":m("sidebar.clearSearch"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:18,height:18,padding:0,border:"none",borderRadius:4,background:"none",color:"var(--text-dim)",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]}),eh&&(0,r.jsxs)("div",{style:{paddingTop:3},children:[Y&&(0,r.jsx)("div",{role:"status",style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:m("sidebar.searchingFiles")}),!Y&&X&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 2px",fontSize:10,color:"#f87171"},children:m("i18n.networkError")}),!Y&&!X&&0===Z.length&&(0,r.jsx)("div",{style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:m("sidebar.noMatchingFiles")}),!Y&&!X&&Z.length>0&&(0,r.jsx)("div",{children:ef.map(e=>(0,r.jsx)(nH,{node:e,depth:0,cwd:n,onOpenFile:s,onAtMention:o,expandedPaths:ee,onToggleExpanded:(e,t)=>{et(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},highlightedPaths:N,gitStatusByPath:em,changedDirectoryPaths:eg,dropTargetPath:es,onDropFiles:e$,onDropTargetChange:eM,t:m},`${q}:${e.fullPath}`))})]})]}),!c&&$.length>0&&(0,r.jsxs)("div",{style:{padding:"0 4px 2px"},children:[(0,r.jsxs)("div",{"aria-label":m("files.changeStats",{count:$.length,additions:M.additions,deletions:M.deletions}),style:{display:"flex",alignItems:"center",gap:6,height:24,padding:"0 6px 0 10px",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:m("files.changedCount",{count:$.length})}),(0,r.jsxs)("span",{style:{color:nW.added,fontFamily:"var(--font-mono)"},children:["+",M.additions]}),(0,r.jsxs)("span",{style:{color:nW.deleted,fontFamily:"var(--font-mono)"},children:["-",M.deletions]}),(0,r.jsx)("span",{style:{flex:1}}),(0,r.jsx)("button",{type:"button",onClick:eR,title:"list"===R?m("files.viewAsTree"):m("files.viewAsList"),"aria-label":"list"===R?m("files.viewAsTree"):m("files.viewAsList"),"aria-pressed":"tree"===R,style:{display:"flex",alignItems:"center",justifyContent:"center",width:22,height:22,padding:0,border:"none",borderRadius:4,background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsx)(nq,{mode:R})})]}),"tree"===R?(0,r.jsx)(nK,{nodes:ev,depth:0,cwd:n,statusByPath:ex,collapsedPaths:L,onToggleExpanded:eT,onOpenFile:s,onAtMention:o,t:m}):$.map(e=>(0,r.jsx)(n_,{status:e,cwd:n,onOpenFile:s,onAtMention:o,t:m},e.filePath))]}),(c||0===$.length)&&(!p||!eh)&&(0,r.jsxs)("div",{style:{padding:"2px 4px"},children:[v?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:m("files.loading")}):y?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"#f87171"},children:y}):g.map(e=>(0,r.jsx)(nH,{node:e,depth:0,cwd:n,onOpenFile:s,onAtMention:o,expandedPaths:k,onToggleExpanded:eb,refreshToken:eu,highlightedPaths:N,gitStatusByPath:em,changedDirectoryPaths:eg,showHidden:f,dropTargetPath:es,onDropFiles:e$,onDropTargetChange:eM,t:m},e.fullPath)),!v&&!y&&0===g.length&&(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:m("files.noFiles")})]}),er&&(0,r.jsxs)("div",{role:"status","aria-live":"polite",style:{position:"sticky",bottom:0,zIndex:1,display:"flex",alignItems:"center",gap:6,padding:"6px 8px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)",fontSize:11,color:"var(--accent)",userSelect:"none",pointerEvents:"none"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M12 16V4"}),(0,r.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,r.jsx)("path",{d:"M5 20h14"})]}),m("files.dropToUpload",{directory:es?nw(es,n)||es:nb(n)||n})]})]})}),nZ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function nJ(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:nZ[Math.floor(n()*nZ.length)]}return s}function nY(e){let{onWidthChange:t}=e,{t:n}=(0,t_.s)(),[s,l]=(0,i.useState)(!1),o=(0,i.useRef)(null),a="0.12.12",d="1.5.2",c=function(e){let[t,n]=(0,i.useState)(e),r=(0,i.useRef)(e);return(0,i.useEffect)(()=>{if(r.current===e)return;if(r.current=e,window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return void n(e);let t=4*e.length,i=0,s=0,l=()=>{n(nJ(e,i+=1)),i<t&&(s=requestAnimationFrame(l))};return n(nJ(e,0)),s=requestAnimationFrame(l),()=>cancelAnimationFrame(s)},[e]),t}(s?`${a??"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:a??"0.0.0",pi:d??"0.0.0"}),onClick:()=>{(o.current&&clearTimeout(o.current),o.current=null,s)?l(!1):(l(!0),o.current=setTimeout(()=>{o.current=null,l(!1)},3e3))},children:c})}var nG=n(2730);let nX=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function nQ(e){let t=e.match(nX);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}let n0={desktop:32,mobile:48};function n1(e,t,n,r){return Math.hypot(n-e,r-t)}function n2(e){return e.getClientRects().length>0}function n4(e){let{size:t=13,className:n,label:i,strokeWidth:s=2,children:l}=e;return(0,r.jsx)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:s,strokeLinecap:"round",strokeLinejoin:"round",className:n,...i?{role:"img","aria-label":i}:{"aria-hidden":!0},children:l})}function n8(e){return(0,r.jsx)(n4,{...e,children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})}function n3(e){return(0,r.jsxs)(n4,{...e,children:[(0,r.jsx)("circle",{cx:"5",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"}),(0,r.jsx)("circle",{cx:"19",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"})]})}function n5(e){return(0,r.jsxs)(n4,{...e,children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"5",rx:"1"}),(0,r.jsx)("path",{d:"M5 9v9a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V9"}),(0,r.jsx)("path",{d:"M10 13h4"})]})}function n6(e){return(0,r.jsxs)(n4,{...e,children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}function n9(e){return(0,r.jsxs)(n4,{...e,children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M9 10.8a2 2 0 0 1-1.1 1.8l-1.8.9A2 2 0 0 0 5 15.2V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.8a2 2 0 0 0-1.1-1.8l-1.8-.9a2 2 0 0 1-1.1-1.8V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z"})]})}function n7(e){return(0,r.jsxs)(n4,{...e,children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M15 9.3V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8.5"}),(0,r.jsx)("path",{d:"m2 2 20 20"}),(0,r.jsx)("path",{d:"M9 9v1.8a2 2 0 0 1-1.1 1.8l-1.8.9A2 2 0 0 0 5 15.2V16a1 1 0 0 0 1 1h11"})]})}function re(e){let{strokeWidth:t,...n}=e;return(0,r.jsx)(n4,{...n,strokeWidth:t,children:(0,r.jsx)("path",{d:"m9 6 6 6-6 6"})})}function rt(e){return(0,r.jsxs)(n4,{...e,children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function rn(e){return(0,r.jsxs)(n4,{...e,children:[(0,r.jsx)("circle",{cx:"6",cy:"5",r:"2.5"}),(0,r.jsx)("circle",{cx:"18",cy:"5",r:"2.5"}),(0,r.jsx)("circle",{cx:"12",cy:"19",r:"2.5"}),(0,r.jsx)("path",{d:"M6 7.5v1.5a3 3 0 0 0 3 3h6a3 3 0 0 0 3-3V7.5"}),(0,r.jsx)("path",{d:"M12 12v4.5"})]})}function rr(e){return(0,r.jsxs)(n4,{...e,children:[(0,r.jsx)("path",{d:"M14 4h6v6"}),(0,r.jsx)("path",{d:"M20 4 11 13"}),(0,r.jsx)("path",{d:"M18 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4"})]})}function ri(e){return(0,r.jsxs)(n4,{...e,children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})}function rs(e){return(0,r.jsx)(n4,{...e,children:(0,r.jsx)("path",{d:"M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"})})}function rl(e){return(0,r.jsx)(n4,{...e,children:(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4.5",fill:"currentColor",stroke:"none"})})}function ro(e){return(0,r.jsx)(n4,{...e,children:(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4.5"})})}function ra(e){return(0,r.jsx)(n4,{...e,children:(0,r.jsx)("path",{d:"M20 6 9 17l-5-5"})})}function rd(e){return(0,r.jsx)(n4,{...e,children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})}function rc(e){return(0,r.jsx)(n4,{...e,children:(0,r.jsx)("path",{d:"M3 8a2 2 0 0 1 2-2h3.4l1.9 1.9H19a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"})})}function ru(e){return(0,r.jsxs)(n4,{...e,children:[(0,r.jsx)("path",{d:"M3 8a2 2 0 0 1 2-2h3.4l1.9 1.9H19a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"}),(0,r.jsx)("path",{d:"M12 11v5M9.5 13.5h5"})]})}function rp(e){return(0,r.jsxs)(n4,{...e,children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function rh(e){return(0,r.jsxs)(n4,{...e,children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]})}function rf(e){return(0,r.jsxs)(n4,{...e,children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("path",{d:"m17 8-5-5-5 5"}),(0,r.jsx)("path",{d:"M12 3v12"})]})}function rm(e){return(0,r.jsxs)(n4,{...e,children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}function rg(e){return(0,r.jsxs)(n4,{...e,children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,r.jsx)("path",{d:"M3 12h6M15 12h6"})]})}function rx(e){return(0,r.jsxs)(n4,{...e,children:[(0,r.jsx)("path",{d:"M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})}function rv(e){return(0,r.jsx)(n4,{...e,children:(0,r.jsx)("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function rb(e){let{className:t,...n}=e;return(0,r.jsx)(n4,{...n,strokeWidth:2.8,className:t?`sidebar-spin ${t}`:"sidebar-spin",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4"})})}function ry(e){let t=nQ(e.firstMessage)??e.firstMessage;return e.name||t.slice(0,50)||e.id.slice(0,12)}function rw(e){return e.nativeEvent.isComposing||229===e.keyCode}function rk(e){let{rows:t,layout:n,emptyLabel:s,loading:l,error:o,renamingRootId:a,renamingProjectKey:d,confirmDeleteRootId:c,activeMenuRowKey:u,reveal:p}=e,{t:h}=(0,t_.s)(),f=(0,i.useRef)(e);f.current=e;let m=(0,i.useRef)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(null);t4(g);let[b,y]=(0,i.useState)(0),[w,k]=(0,i.useState)(0),[j,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(()=>Date.now()),E=(0,i.useRef)(null),$=(0,i.useCallback)(()=>{null===E.current&&(E.current=requestAnimationFrame(()=>{E.current=null;let e=g.current;e&&y(e.scrollTop)}))},[]);(0,i.useLayoutEffect)(()=>{let e=g.current;if(!e)return;let t=()=>{let t=`${Math.max(0,e.offsetWidth-e.clientWidth)}px`;e.style.setProperty("--session-tree-scrollbar",t),e.offsetWidth>0&&e.closest(".session-sidebar")?.style.setProperty("--session-tree-scrollbar",t)};if(t(),k(e.clientHeight),y(e.scrollTop),"u"<typeof ResizeObserver)return;let n=new ResizeObserver(()=>{t(),k(e.clientHeight),y(e.scrollTop)});return n.observe(e),()=>n.disconnect()},[]),(0,i.useEffect)(()=>()=>{null!==E.current&&cancelAnimationFrame(E.current)},[]),(0,i.useEffect)(()=>{let e=window.setInterval(()=>N(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let I=(0,i.useCallback)(e=>{let t=e.target instanceof Element?e.target.closest("[data-row-key]"):null;S(t?.getAttribute("data-row-key")??null)},[]),M=(0,i.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||S(null)},[]),T=(0,i.useMemo)(()=>(function(e,t){let n=eh[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 l=(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 l=r;for(;l>0&&"spacer"===e[l-1].kind;)l--;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 a=o;for(;a<e.length&&"spacer"===e[a].kind;)a++;n.push({key:s.project.key,pinned:s.project.pinned,top:t[r],bottom:t[o],gapAbove:t[r]-t[l],gapBelow:t[a]-t[o]}),r=o}return n})(t,n),[t,n]),o=(0,i.useRef)(l);o.current=l;let a=(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),l=i.filter(e=>e!==r);if(0===l.length)return null;let o=l.filter(e=>(e.top+e.bottom)/2<n).length;if(o===s)return null;let a=l[l.length-1],d=Math.max(3,o<l.length?l[o].top-l[o].gapAbove/2:a.bottom+a.gapBelow/2);return o>0?{anchorKey:l[o-1].key,position:"after",lineY:d}:{anchorKey:l[0].key,position:"before",lineY:d}}(o.current,e.projectKey,e.clientY-t.getBoundingClientRect().top):null},n=()=>{let e=a.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 l=n.getBoundingClientRect().top,o=i.getBoundingClientRect(),d=t.offsetHeight,c=function(e){let{pointerY:t,lineY:n,ghostHeight:r,pointerGap:i,lineGap:s,minTop:l,maxTop:o}=e,a=Math.max(l,o),d=t-i-r,c=null!==n&&n>=l&&n<=a+r?n:null,u=e=>e>=l&&e<=a,p=e=>null!==c&&e>c-s-r&&e<c+s,h=null===c?[d,l,t+i,a]:[d,c-s-r,l,t+i,c+s,a],f=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 f(e=>u(e)&&!(e>d&&e<t+i)&&!p(e))??f(e=>u(e)&&!p(e))??Math.min(a,Math.max(l,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-l}px`,t.style.left=`${e.ghost.left}px`},r=e=>{null!==e.timer&&window.clearTimeout(e.timer),null!==e.frame&&cancelAnimationFrame(e.frame),e.timer=null,e.frame=null,s.current.scrollRef.current?.removeEventListener("scroll",p);try{e.element.hasPointerCapture(e.pointerId)&&e.element.releasePointerCapture(e.pointerId)}catch{}},i=()=>{let e=a.current;e&&(a.current=null,r(e),window.removeEventListener("pointermove",g,!0),window.removeEventListener("pointerup",x,!0),window.removeEventListener("pointercancel",v,!0),window.removeEventListener("pointerdown",b,!0),window.removeEventListener("keydown",y,!0),window.removeEventListener("contextmenu",w,!0),window.removeEventListener("blur",k),document.removeEventListener("visibilitychange",j),u(null))},l=()=>{let e=a.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=a.current;if(!o||"dragging"!==o.phase)return;let d=s.current.scrollRef.current;if(!d||!n2(d))return void l();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=a.current;if(!e||"dragging"!==e.phase)return;e.frame=null;let t=s.current.scrollRef.current;if(!t||!n2(t))return void l();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,n0[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())}a.current===e&&"dragging"===e.phase&&(e.frame=requestAnimationFrame(h))},f=e=>{let t=s.current.scrollRef.current,n=s.current.treeRef.current;if(!t||!n||!n2(t)||!e.element.isConnected)return void l();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)},m=()=>{let t=a.current;t&&"pending"===t.phase&&(t.timer=null,t.phase="armed",t.armX=t.clientX,t.armY=t.clientY,t.expectedScrollTop=s.current.scrollRef.current?.scrollTop??0,e(t))};function g(e){let t=a.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=n1(t.startX,t.startY,e.clientX,e.clientY);switch(t.phase){case"pending":"mouse"===t.pointerType?n>=4&&f(t):n>8&&i();break;case"armed":n1(t.armX,t.armY,e.clientX,e.clientY)>=4&&f(t);break;case"dragging":c()}}function x(e){let n=a.current;if(n&&e.pointerId===n.pointerId){if("dragging"===n.phase){n.clientX=e.clientX,n.clientY=e.clientY;let r=t(n);r&&s.current.onMove(n.projectKey,r.anchorKey,r.position)}"pending"!==n.phase&&(d.current=e.timeStamp+600),i()}}function v(e){a.current&&e.pointerId===a.current.pointerId&&i()}function b(e){a.current&&e.pointerId!==a.current.pointerId&&l()}function y(e){let t=a.current;t&&"Escape"===e.key&&("armed"===t.phase||"dragging"===t.phase)&&(e.preventDefault(),e.stopPropagation(),l())}function w(e){let t=a.current;if(t){if("pending"===t.phase)return void i();e.preventDefault(),e.stopPropagation()}}function k(){i()}function j(){"hidden"===document.visibilityState&&i()}return{handlers:{onPointerDown(e,t){if(!s.current.enabled||a.current||!e.isPrimary||0!==e.button||e.ctrlKey||e.target instanceof Element&&e.target.closest(".session-tree-group-actions"))return;let n=e.currentTarget,r={pointerId:e.pointerId,pointerType:e.pointerType,projectKey:t,element:n,startX:e.clientX,startY:e.clientY,armX:e.clientX,armY:e.clientY,clientX:e.clientX,clientY:e.clientY,phase:"pending",timer:null,frame:null,expectedScrollTop:0,drop:null,ghost:null};a.current=r,window.addEventListener("pointermove",g,!0),window.addEventListener("pointerup",x,!0),window.addEventListener("pointercancel",v,!0),window.addEventListener("pointerdown",b,!0),window.addEventListener("keydown",y,!0),window.addEventListener("contextmenu",w,!0),window.addEventListener("blur",k),document.addEventListener("visibilitychange",j),"mouse"!==e.pointerType&&(r.timer=window.setTimeout(m,350))},onTouchMove(e){let t=a.current;if(!t||"armed"!==t.phase&&"dragging"!==t.phase)return;if(e.cancelable)return void e.preventDefault();let n=s.current.scrollRef.current;n&&n.scrollTop!==t.expectedScrollTop&&i()}},cancel:l,teardown:i,updateDrag:c,placeGhost:n}},[]);(0,i.useLayoutEffect)(()=>{let e=a.current;e&&("armed"===e.phase||"dragging"===e.phase)&&(t.some(t=>"group"===t.kind&&t.project.key===e.projectKey)?p.updateDrag():p.cancel())},[t,n,p]),(0,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 f=(0,i.useCallback)(e=>{let t=d.current;0===t||(d.current=0,e.timeStamp>t||(e.preventDefault(),e.stopPropagation()))},[]),m=(0,i.useCallback)(()=>{d.current=0},[]);return{view:(0,i.useMemo)(()=>{if(!c)return null;let e="dragging"===c.phase?l.find(e=>e.key===c.projectKey)??null:null;return{...c,source:e}},[c,l]),handlers:p.handlers,onClickCapture:f,onPointerDownCapture:m}}({rows:t,offsets:T,layout:n,enabled:R&&!l,scrollRef:g,innerRef:x,treeRef:m,ghostRef:v,onMove:(e,t,n)=>f.current.onMoveGroup?.(e,t,n)}),z=L.view,P=z?`group:${z.projectKey}`:null,[W,O]=(0,i.useState)(null),F=p&&p.id!==W?p:null,D=F?.rowKey??null,B=(0,i.useMemo)(()=>{let e=[];return t.forEach((t,n)=>{t.key===j||t.key===u||t.key===D||t.key===P||"session"===t.kind&&(t.family.root.id===a||t.family.root.id===c)?e.push(n):"group"===t.kind&&t.project.key===d&&e.push(n)}),e},[t,j,u,D,P,a,d,c]),H=(0,i.useMemo)(()=>l?[]:function(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],s=Math.max(0,e.length-1),l=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)&&n>0?n:600,a=Number.isFinite(r)&&r>0?r:0,d=l-a,c=l+o+a,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 f=u,m=[];for(let e=h;e<f;e++)m.push(e);if(0===i.length)return m;let g=i.filter(e=>Number.isInteger(e)&&e>=0&&e<s&&(e<h||e>=f));return 0===g.length?m:[...new Set([...m,...g])].sort((e,t)=>e-t)}(T,b,w,240,B),[l,T,b,w,B]),_=(0,i.useRef)(null),U=(0,i.useRef)(null),K=(0,i.useCallback)((e,t,n,r)=>{let i=document.activeElement===r,s=i&&r.matches(":focus-visible");_.current={rowKey:e,fallbackKey:t===ef?"pinned-header":`group:${t}`,focus:i,scroll:"less"===n||s},"more"===n?f.current.onShowMore(t):f.current.onShowLess(t)},[]);(0,i.useLayoutEffect)(()=>{let e=_.current;if(!e)return;_.current=null;let n=g.current,r=t.findIndex(t=>t.key===e.rowKey);if(r<0&&(r=t.findIndex(t=>t.key===e.fallbackKey)),e.scroll&&n&&r>=0){let e=eP(T,r,n.scrollTop,n.clientHeight);null!==e&&(n.scrollTop=e),y(n.scrollTop)}e.focus&&(U.current={rowKey:e.rowKey,fallbackKey:e.fallbackKey,tries:0})},[t,T]);let q=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{if(!F)return;let e=t.findIndex(e=>e.key===F.rowKey),n=function(e,t,n,r){let i=e?.id===t.id?e:{id:t.id,misses:0};if(!(r-t.at<=3e3))return{misses:i,action:"drop"};if(n)return{misses:i,action:"reveal"};let s={id:t.id,misses:i.misses+1};return{misses:s,action:s.misses>=3?"drop":"wait"}}(q.current,F,e>=0,Date.now());if(q.current=n.misses,"wait"!==n.action){if("reveal"===n.action){let t=g.current;if(t&&t.getClientRects().length>0){let n=eP(T,e,t.scrollTop,t.clientHeight,F.block);null!==n&&(t.scrollTop=n),y(t.scrollTop)}F.takeFocusFrom&&(U.current={rowKey:F.rowKey,fallbackKey:F.rowKey,tries:0,takeFocusFrom:F.takeFocusFrom})}O(F.id),f.current.onRevealHandled?.(F.id)}},[F,t,T]),(0,i.useLayoutEffect)(()=>{let e=U.current;if(!e)return;let t=document.activeElement;if(t&&t!==document.body&&document.contains(t)&&!e.takeFocusFrom?.(t)){U.current=null;return}let n=g.current,r=e=>n?.querySelector(`[data-row-key="${CSS.escape(e)}"]`)??null,i=r(e.rowKey),s=i?.querySelector('[data-more-action="more"]')??i?.querySelector("a[href], button")??r(e.fallbackKey)?.querySelector("a[href], button");s?(s.focus({preventScroll:!0}),U.current=null):++e.tries>2&&(U.current=null)},[H]);let V=t.some(e=>"session"===e.kind||"group"===e.kind||"archive-group"===e.kind),Z=!l&&!o&&null!==s&&!V,J=z?.source??null,Y=z?.drop?.lineY??null,G=z?.phase==="dragging"?t.find(e=>"group"===e.kind&&e.project.key===z.projectKey)?.project??null:null;return(0,r.jsxs)("div",{ref:m,className:`session-tree${"mobile"===n?" is-mobile":""}${G?" is-group-dragging":""}`,children:[l&&(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}),Z&&(0,r.jsx)("div",{className:"session-tree-message",children:s}),(0,r.jsx)("div",{ref:g,className:"session-tree-scroll scrollbar-subtle",onScroll:$,onFocus:I,onBlur:M,onPointerDownCapture:L.onPointerDownCapture,onClickCapture:L.onClickCapture,children:!l&&(0,r.jsxs)("div",{ref:x,className:"session-tree-inner",style:{height:T[t.length]},children:[H.map(e=>{let i=t[e];if("spacer"===i.kind)return null;let s=T[e],l=T[e+1]-s,o=i.key===u;if("session"===i.kind)return(0,r.jsx)(rS,{row:i,layout:n,top:s,height:l,now:C,renaming:i.family.root.id===a,confirming:i.family.root.id===c,menuOpen:o,handlers:f},i.key);if("archive-group"===i.kind)return(0,r.jsx)(rM,{row:i,top:s,height:l,menuOpen:o,handlers:f},i.key);if("group"===i.kind){let e=i.project.key===d;return(0,r.jsx)(r$,{row:i,top:s,height:l,menuOpen:o,renaming:e,canDrag:R&&!e&&A[i.project.pinned?"pinned":"other"]>1,dragPhase:z?.projectKey===i.project.key?z.phase:null,drag:L.handlers,handlers:f},i.key)}return(0,r.jsx)(rI,{row:i,top:s,height:l,handlers:f,onMoreAction:K},i.key)}),J&&(0,r.jsx)("div",{className:"session-tree-drag-source","aria-hidden":"true",style:{top:J.top,height:J.bottom-J.top}}),null!==Y&&(0,r.jsx)("div",{className:"session-tree-drop-line","aria-hidden":"true",style:{top:Y}})]})}),G&&(0,r.jsx)("div",{ref:v,className:"session-tree-drag-ghost","aria-hidden":"true",children:(0,r.jsx)("span",{className:"session-tree-group-name",children:G.name})})]})}function rj(e,t){return{top:e,height:t}}let rS=(0,i.memo)(function(e){let t,n,{row:i,layout:s,top:l,height:o,now:a,renaming:d,confirming:c,menuOpen:u,handlers:p}=e,{locale:h,t:f}=(0,t_.s)(),{family:m,context:g,status:x}=i,v=m.root,b=ry(v),y=new Date(a),w=["session-tree-row session-tree-session",x.selected?"is-selected":"",x.running?"is-running":"","archive"===g?"is-archived":"",u?"is-menu-open":"",c?"is-confirming":"",d?"is-renaming":""].filter(Boolean).join(" ");if(c){let e=b.slice(0,22)+(b.length>22?"…":"");return(0,r.jsx)("div",{className:w,style:rj(l,o),"data-row-key":i.key,onKeyDown:e=>{"Escape"!==e.key||rw(e)||(e.preventDefault(),e.stopPropagation(),p.current.onDeleteCancel())},children:(0,r.jsx)(rN,{label:f("sidebar.deleteSession",{title:e}),deleteLabel:f("sidebar.delete"),cancelLabel:f("sidebar.cancel"),onConfirm:e=>{e.stopPropagation(),p.current.onDeleteConfirm(m,e)},onCancel:e=>{e.stopPropagation(),p.current.onDeleteCancel()}})})}if(d)return(0,r.jsx)("div",{className:w,style:rj(l,o),"data-row-key":i.key,children:(0,r.jsx)(rC,{initialValue:b,label:f("sidebar.rename"),onCommit:e=>p.current.onRenameCommit(m,e),onCancel:()=>p.current.onRenameCancel()})});let k=v.isWorktree&&v.branch?v.branch:null,j=v.name&&v.relation?.kind==="fork"?e8(v.name):null,S=v.detailsPending?"…":f("sidebar.messagesCount",{count:v.messageCount}),C=`${b}
5
+ ${S} \xb7 ${(0,nG.fw)(v.modified,h,y)}${k?` \xb7 ⑂ ${k}`:""}`,N="";x.awaiting?(t=(0,r.jsx)("span",{className:"session-tree-awaiting",role:"img","aria-label":f("sidebar.agentAwaitingInput")}),N=" is-awaiting",n=f("sidebar.agentAwaitingInput")):x.running?(t=(0,r.jsx)(rb,{size:12,label:f("sidebar.agentRunning")}),N=" is-running",n=f("sidebar.agentRunning")):x.unread?(t=(0,r.jsx)("span",{className:"session-tree-unread",role:"img","aria-label":f("sidebar.newSessionActivity")}),N=" is-unread",n=f("sidebar.newActivity")):t="pinned"===g?(0,r.jsx)("span",{className:"session-tree-project",children:i.project.name}):(0,nG.Rg)(m.latestModified,h,y);let E="desktop"===s&&("archive"===g||!x.running),$=(0,r.jsxs)(r.Fragment,{children:[j?(0,r.jsxs)("span",{className:"session-tree-title has-fork-suffix",children:[(0,r.jsx)("span",{className:"session-tree-title-base",children:j.base}),(0,r.jsx)("span",{className:"session-tree-title-suffix",children:j.suffix})]}):(0,r.jsx)("span",{className:"session-tree-title",children:b}),k&&(0,r.jsxs)("span",{className:"session-tree-branch",children:[(0,r.jsx)(rt,{size:10,className:"session-tree-branch-icon"}),k]}),(0,r.jsx)("span",{className:`session-tree-meta${N}`,title:n,children:t})]});return(0,r.jsxs)("div",{className:w,style:rj(l,o),"data-row-key":i.key,onClick:()=>p.current.onSelectFamily(m),onContextMenu:e=>p.current.onRowContextMenu(i,e),children:[x.transient?(0,r.jsx)("button",{type:"button",className:"session-tree-main",title:C,"aria-current":x.selected?"true":void 0,children:$}):(0,r.jsx)("a",{className:"session-tree-main",href:F(v.id),title:C,"aria-current":x.selected?"true":void 0,onClick:e=>{e.stopPropagation(),e.defaultPrevented||0!==e.button||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||(e.preventDefault(),p.current.onSelectFamily(m))},children:$}),!x.transient&&(0,r.jsxs)("span",{className:"session-tree-actions",children:[E&&("archive"===g?(0,r.jsx)("button",{type:"button",className:"session-tree-action session-tree-quick-action","aria-label":f("sidebar.restore"),title:f("sidebar.restore"),onClick:e=>{e.stopPropagation(),p.current.onRestoreFamily(m)},children:(0,r.jsx)(n6,{size:13})}):(0,r.jsx)("button",{type:"button",className:"session-tree-action session-tree-quick-action","aria-label":f("sidebar.archive"),title:f("sidebar.archive"),onClick:e=>{e.stopPropagation(),p.current.onArchiveFamily(m)},children:(0,r.jsx)(n5,{size:13})})),(0,r.jsx)("button",{type:"button",className:`session-tree-action session-tree-more-action${u?" is-active":""}`,"aria-label":f("sidebar.moreActions"),title:f("sidebar.moreActions"),"aria-haspopup":"menu","aria-expanded":u,onClick:e=>{let t;e.stopPropagation();let n=e.currentTarget;p.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)(n3,{size:14})})]})]})});function rC(e){let{initialValue:t,label:n,maxLength:s,onCommit:l,onCancel:o}=e,[a,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,l(e))};return(0,r.jsx)("input",{ref:c,className:"session-tree-rename",value:a,"aria-label":n,maxLength:s,onChange:e=>d(e.target.value),onBlur:e=>p(e.currentTarget.value),onKeyDown:e=>{if(!rw(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 rN(e){let{label:t,deleteLabel:n,cancelLabel:s,onConfirm:l,onCancel:o}=e,a=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=document.activeElement;e&&e!==document.body||a.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:l,children:[(0,r.jsx)(ri,{size:12}),n]}),(0,r.jsx)("button",{ref:a,type:"button",className:"session-tree-confirm-cancel",onClick:o,children:s})]})}function rE(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)(rb,{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 r$=(0,i.memo)(function(e){let{row:t,top:n,height:s,menuOpen:l,renaming:o,canDrag:a,dragPhase:d,drag:c,handlers:u}=e,{t:p}=(0,t_.s)(),{project:h,expanded:f}=t,m=(0,i.useRef)(null),g=["session-tree-row session-tree-group",h.current?"is-current":"",l?"is-active":"","armed"===d?"is-drag-armed":""].filter(Boolean).join(" ");return((0,i.useEffect)(()=>{let e=m.current;if(!a||!e)return;let t=e=>c.onTouchMove(e);return e.addEventListener("touchmove",t,{passive:!1}),()=>e.removeEventListener("touchmove",t)},[a,c]),o)?(0,r.jsx)("div",{ref:m,className:`${g} is-renaming`,style:rj(n,s),"data-row-key":t.key,children:(0,r.jsx)(rC,{initialValue:h.name,label:p("sidebar.projectName"),maxLength:80,onCommit:e=>u.current.onRenameProjectCommit(h,e),onCancel:()=>u.current.onRenameProjectCancel()})}):(0,r.jsxs)("div",{ref:m,className:g,style:rj(n,s),"data-row-key":t.key,onPointerDown:a?e=>c.onPointerDown(e,h.key):void 0,children:[(0,r.jsxs)("button",{type:"button",className:"session-tree-group-toggle","aria-expanded":f,title:h.root,onClick:e=>u.current.onToggleGroup(h.key,e.altKey),children:[(0,r.jsx)(re,{size:12,strokeWidth:3,className:`session-tree-chevron${f?" is-open":""}`}),(0,r.jsx)("span",{className:"session-tree-group-name",children:h.name}),h.pinned&&(0,r.jsx)(n9,{size:10,className:"session-tree-group-pin",label:p("sidebar.pinnedProject")}),!f&&(0,r.jsx)(rE,{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)(n8,{size:13})}),(0,r.jsx)("button",{type:"button",className:`session-tree-group-action${l?" is-active":""}`,"aria-label":p("sidebar.projectActions",{name:h.name}),title:p("sidebar.projectActions",{name:h.name}),"aria-haspopup":"menu","aria-expanded":l,onClick:e=>{e.stopPropagation(),u.current.onGroupMenu(h,e.currentTarget)},children:(0,r.jsx)(n3,{size:13})})]})]})}),rI=(0,i.memo)(function(e){let{row:t,top:n,height:i,handlers:s,onMoreAction:l}=e,{t:o}=(0,t_.s)(),a=rj(n,i);switch(t.kind){case"pinned-header":return(0,r.jsx)("div",{className:"session-tree-row session-tree-pinned-header",style:a,"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)(re,{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?ef:t.projectKey;return(0,r.jsxs)("div",{className:"session-tree-row session-tree-more",style:a,"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=>l(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=>l(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:a,"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:a,"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)(ru,{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:a,"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)(n5,{size:12}),(0,r.jsx)("span",{className:"session-tree-footer-label",children:o("sidebar.archivedCount",{count:t.count})}),(0,r.jsx)(re,{size:10,className:"session-tree-footer-chevron"})]})})}}),rM=(0,i.memo)(function(e){let{row:t,top:n,height:i,menuOpen:s,handlers:l}=e,{t:o}=(0,t_.s)(),{project:a,expanded:d}=t,c=["session-tree-row session-tree-group session-tree-archive-group",a.current?"is-current":"",s?"is-active":""].filter(Boolean).join(" ");return(0,r.jsxs)("div",{className:c,style:rj(n,i),"data-row-key":t.key,children:[(0,r.jsxs)("button",{type:"button",className:"session-tree-group-toggle","aria-expanded":d,title:a.root,onClick:e=>l.current.onToggleArchiveGroup?.(a.key,e.altKey),children:[(0,r.jsx)(re,{size:12,strokeWidth:3,className:`session-tree-chevron${d?" is-open":""}`}),(0,r.jsx)("span",{className:"session-tree-group-name",children:a.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:a.name}),title:o("sidebar.archivedProjectActions",{name:a.name}),"aria-haspopup":"menu","aria-expanded":s,onClick:e=>{e.stopPropagation(),l.current.onArchiveGroupMenu?.(a,e.currentTarget)},children:(0,r.jsx)(n3,{size:13})})})]})}),rT="[data-sidebar-menu-filter]",rR="[data-sidebar-menu-autofocus]",rA="button, input, textarea, select, a[href], [tabindex]";function rL(e){return i.Children.toArray(e).length>0}function rz(e){return"item"===e.type&&void 0!==e.checked}function rP(e){return e.getClientRects().length>0}function rW(e){return!e.disabled&&"true"!==e.getAttribute("aria-disabled")&&rP(e)}function rO(e){return Array.from(e.querySelectorAll("[data-sidebar-menu-item]")).filter(rW)}function rF(e){let t=Array.from(e.querySelectorAll(rR)).find(rW);if(t)return t;let n=rO(e);return n.length>0?n[0]:Array.from(e.querySelectorAll(rA)).filter(e=>e.tabIndex>=0&&rW(e))[0]??null}function rD(e){e.stopPropagation()}let rB={onClick:rD,onDoubleClick:rD,onMouseDown:rD,onMouseUp:rD,onPointerDown:rD,onPointerUp:rD,onKeyDown:rD,onKeyUp:rD,onFocus:rD,onBlur:rD,onContextMenu:function(e){e.preventDefault(),e.stopPropagation()}};function rH(e,t){return n=>{"Enter"!==n.key||n.nativeEvent.isComposing||229===n.keyCode||(n.preventDefault(),t(e,n.shiftKey))}}function r_(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(" "),l=["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 a=(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:rH(t,n),children:[(0,r.jsx)("span",{className:"sidebar-menu-icon",children:i?t.checked?(0,r.jsx)(ra,{size:13}):null:t.icon}),(0,r.jsx)("span",{className:l,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:[a,(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:rH(d,n),children:d.icon})]}):a}function rU(e){var t;let n,{sheet:i,ariaLabel:s,title:l,items:o,filter:a,filterQuery:d="",onFilterQueryChange:c,children:u,cancelLabel:p,focusCancel:h=!1,width:f=208,classic:m=!1,footer:g,surfaceRef:x,onActivate:v,onClose:b}=e,y=rL(u),w=!y&&rL(g),k=void 0!==a&&!y&&function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;return(e??[]).filter(rz).length>=t}(o,a.minChoices),j=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=j.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)(r_,{item:e,onActivate:v},e.id)),C=y?u:k||w?(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:a.placeholder,"aria-label":a.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()&&!j.some(rz)&&(0,r.jsx)("div",{className:"sidebar-menu-empty",children:a.emptyLabel})}),(0,r.jsx)("div",{role:"menu","aria-label":s,children:S}),w&&g]}):S,N=y||k||w?void 0:"menu";return i?(0,r.jsxs)("div",{className:"sidebar-sheet-layer",...rB,children:[(0,r.jsx)("div",{className:"sidebar-sheet-backdrop","aria-hidden":"true",onClick:()=>b("outside")}),(0,r.jsxs)("div",{ref:x,className:"sidebar-sheet",role:"dialog","aria-modal":"true","aria-label":s,children:[l?(0,r.jsx)("div",{className:"sidebar-sheet-title",children:l}):null,(0,r.jsx)("div",{className:"sidebar-sheet-body",role:N,"aria-label":N?s:void 0,children:C}),(0,r.jsx)("button",{type:"button",className:"sidebar-sheet-cancel","data-sidebar-menu-autofocus":h?"":void 0,onClick:()=>b("cancel"),children:p})]})]}):(0,r.jsx)("div",{ref:x,className:m?"sidebar-menu is-classic":"sidebar-menu",role:N??"dialog","aria-label":s,style:{width:f},...rB,children:C})}function rK(e){let{open:t,anchor:n,sheet:s,ariaLabel:l,title:o,items:a,filter:d,children:c,cancelLabel:u,focusCancel:p,onClose:h,returnFocusTo:f,width:m,classic:g=!1,footer:x,focusKey:v=""}=e,[b,y]=(0,i.useState)(null),[w,k]=(0,i.useState)(""),j=(0,i.useRef)(w);j.current=w;let S=(0,i.useRef)(null),C=(0,i.useRef)(h);C.current=h;let N=(0,i.useRef)(a);N.current=a;let E=(0,i.useRef)(f??null);E.current=f??null;let $=(0,i.useRef)(n);$.current=n,(0,i.useEffect)(()=>{y(document.body)},[]);let I=t&&null!==b&&(s||null!==n),M=rL(c),T=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(!I||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,l=n.left+s,o=n.top+s,a=n.left+n.width-s,d=n.top+n.height-s;if("point"===e.kind)r=e.x+t.width>a&&e.x-t.width>=l?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,l=n.top-4-t.height;i=s+t.height>d&&l>=o?l:s}return{left:Math.max(l,Math.min(r,a-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)}},[I,s,T,M]),(0,i.useEffect)(()=>{k("")},[I,M]);let L=(0,i.useRef)(!1);return((0,i.useLayoutEffect)(()=>{let e=S.current;if(!I||!e){L.current=!1;return}let t=!L.current;L.current=!0,(t?rF(e):Array.from(e.querySelectorAll(rR)).filter(e=>!e.matches(rT)&&rW(e))[0]??rF(e))?.focus({preventScroll:!0})},[I,s,M,v]),(0,i.useLayoutEffect)(()=>{let e=S.current;if(!I||!e)return;let t=E.current;return()=>{let n=document.activeElement;if(n&&n!==document.body&&!e.contains(n))return;let r=function(e){if(!e||!e.isConnected)return null;if(rP(e))return e;let t=e.closest("[data-row-key]");if(!t)return null;for(let e of Array.from(t.querySelectorAll(rA)))if(e.tabIndex>=0&&rW(e))return e;return null}(t);r&&(r.focus({preventScroll:!0}),t&&r!==t&&rP(t)&&t.focus({preventScroll:!0}))}},[I,s]),(0,i.useEffect)(()=>{if(!I)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(rT);if(n&&j.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,l;r&&(s=e.shiftKey,i=Array.from(t.querySelectorAll(rA)).filter(e=>e!==n&&e.tabIndex>=0&&rW(e)),l=s?Node.DOCUMENT_POSITION_PRECEDING:Node.DOCUMENT_POSITION_FOLLOWING,i.some(e=>(n.compareDocumentPosition(e)&l)!=0))||C.current("outside");return}let l=("ArrowDown"===e.key||"ArrowUp"===e.key)&&n?.matches(rT);if(r&&function(e){if(!e)return!1;if(e.isContentEditable)return!0;let t=e.tagName;return"TEXTAREA"===t||"SELECT"===t||"INPUT"===t&&!["button","checkbox","radio","range","reset","submit","image","color","file"].includes((e.type||"text").toLowerCase())}(n)&&!l)return;if("ArrowDown"===e.key||"ArrowUp"===e.key||"Home"===e.key||"End"===e.key){let r,i=rO(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&&!M&&(e.preventDefault(),e.stopPropagation(),A.current(o,e.shiftKey))};return document.addEventListener("keydown",e,!0),()=>document.removeEventListener("keydown",e,!0)},[I,M]),(0,i.useEffect)(()=>{if(!I||s)return;let e=e=>{let t=S.current,n=e.target instanceof Node?e.target:null;if(!t||n&&t.contains(n))return;let r=E.current;r&&n&&0===e.button&&r.contains(n)&&function(e){let t=e.ownerDocument,n=t.defaultView;if(!n)return;let r=0,i=()=>{t.removeEventListener("click",s,!0),n.clearTimeout(r)};function s(t){i(),t.target instanceof Node&&e.contains(t.target)&&(t.preventDefault(),t.stopPropagation())}t.addEventListener("click",s,!0),r=n.setTimeout(i,1e3)}(r),C.current("outside")};return document.addEventListener("pointerdown",e,!0),()=>document.removeEventListener("pointerdown",e,!0)},[I,s]),I&&b)?(0,t7.createPortal)((0,r.jsx)(rU,{sheet:s,ariaLabel:l,title:o,items:a,filter:d,filterQuery:w,onFilterQueryChange:k,cancelLabel:u,focusCancel:p,width:m,classic:g,footer:x,surfaceRef:S,onActivate:(e,t)=>A.current(e,t),onClose:e=>C.current(e),children:c}),b):null}function rq(e){let{heading:t,busy:n,error:s,showCancel:l,onCreate:o,onCancel:a}=e,{t:d}=(0,t_.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")}),l&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-cancel",onClick:a,children:d("sidebar.cancel")})]}),s&&(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:s})]})}function rV(e,t){return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function rZ(e){return e.branch??ek(e.path)}function rJ(e){let{heading:t,dirty:n,busy:i,error:s,showCancel:l,onForce:o,onCancel:a}=e,{t:d}=(0,t_.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||l)&&(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")}),l&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-cancel","data-sidebar-menu-autofocus":"",onClick:a,children:d("sidebar.cancel")})]}),s&&(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:s})]})}function rY(e){let{busy:t,onForce:n,onCancel:s}=e,{t:l}=(0,t_.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:l("sidebar.forceRemoveCheckout"),children:l("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:l("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:l("sidebar.cancel")})]})}function rG(e){let t,n,{layout:s,context:l,mobile:o,label:a,placeholder:d="",homeDir:c,projectActivity:u,worktreeHint:p=null,newWorktreeTitle:h,handleRef:f,onPick:m,onUseDefaultDirectory:g,onOpenFolder:x,onRefreshWorktrees:v,onCreateWorktree:b,onRemoveWorktree:y}=e,{t:w}=(0,t_.s)(),[k,j]=(0,i.useState)(null),S=(0,i.useRef)(k);S.current=k;let C=(0,i.useRef)(0),N=(0,i.useRef)(null),E=(0,i.useRef)(null),$=(0,i.useRef)(!1),I=(0,i.useRef)(m);I.current=m;let M="inline"!==s,T=!M,R=!o,{project:A,worktrees:L}=l,z=(t=l.worktrees??[]).find(e=>e.path===l.currentWorktreePath)??t.find(e=>e.isMain)??null,P=T&&A?e9(e5(l)).find(e=>{let{choice:t}=e;return t.key===A.key}):void 0;(0,i.useEffect)(()=>($.current=!0,()=>{$.current=!1}),[]);let W=()=>(C.current+=1,C.current),O=()=>j(null),F=(e,t)=>{let n=t.getBoundingClientRect(),r=Math.max(M?220:"project"===e?260:240,Math.round(n.width));j({id:W(),kind:e,anchor:{kind:"rect",rect:{left:n.left,top:n.top,right:n.right,bottom:n.bottom},align:"row"===s&&"worktree"===e?"end":"start"},opener:t,width:r,body:null,removing:!1}),"worktree"===e&&v()},D=(0,i.useRef)(F);D.current=F,(0,i.useImperativeHandle)(f,()=>({button:e=>("worktree"===e?E:N).current,openMenu:e=>{let t=("worktree"===e?E:N).current;t&&D.current(e,t)}}),[]);let B=(e,t)=>{j(n=>n?.id===e?t(n):n)},H=e=>{let t=W();j(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 b(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&&(j(null),I.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}}})},K=()=>[...(L??[]).map(e=>R&&q?.kind==="remove"&&q.dirty&&q.worktree.path===e.path?{type:"custom",id:`worktree:${e.path}`,content:(0,r.jsx)(rY,{busy:q.busy,onForce:()=>{U(e,!0)},onCancel:()=>H(null)})}:{type:"item",id:`worktree:${e.path}`,label:R?e.branch??rV(e.path,c):rZ(e),mono:R,path:R,note:e.isMain?w("sidebar.main"):void 0,title:e.path,checked:e.path===z?.path,secondary:y&&!e.isMain?{label:w("sidebar.removeWorktreeTitle",{path:e.path}),icon:(0,r.jsx)(ri,{size:12}),danger:!0,disabled:k?.removing,onSelect:t=>{let{keepOpen:n}=t;n(),U(e,!1)}}:void 0,onSelect:()=>{A&&e.path!==z?.path&&m({cwd:e.path,projectKey:A.key,projectRoot:A.root},"worktree")}}),...R?[]:[{type:"separator",id:"separator"}],...R&&q?.kind==="create"?[]:[{type:"item",id:"new-worktree",label:w("sidebar.newWorktree"),icon:(0,r.jsx)(n8,{size:13}),onSelect:e=>{let{keepOpen:t}=e;t(),H({kind:"create",busy:!1,error:null})}}]],q=k?.kind==="worktree"?k.body:null,V="",Z=null,J=null;if(R&&k?.kind==="worktree")V=w("sidebar.switchWorktree"),n=K(),q?.kind==="create"?J=(0,r.jsx)(rq,{heading:null,busy:q.busy,error:q.error,showCancel:!0,onCreate:e=>{_(e)},onCancel:()=>H(null)}):q?.kind==="remove"&&q.error&&(J=(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:q.error}));else if(q?.kind==="create")V=h,Z=(0,r.jsx)(rq,{heading:o?null:V,busy:q.busy,error:q.error,showCancel:!o,onCreate:e=>{_(e)},onCancel:O});else if(q?.kind==="remove")V=w("sidebar.removeWorktreeHeading",{name:rZ(q.worktree)}),Z=(0,r.jsx)(rJ,{heading:o?null:V,dirty:q.dirty,busy:q.busy,error:q.error,showCancel:!o,onForce:()=>{U(q.worktree,!0)},onCancel:O});else if(k?.kind==="project"){let e,t;V=w("workspace.project"),t=(e=e9(e5(l)).map(e=>{let{choice:t,name:n,note:i}=e,s=u?.get(t.key),l=R&&void 0===t.alias;return{type:"item",id:`project:${t.key}`,label:l?rV(t.root,c):n,note:l?void 0:i??void 0,mono:R,path:l,title:t.root,checked:t.key===A?.key,badge:s?(0,r.jsx)(rE,{running:s.running,unread:s.unread,t:w}):void 0,onSelect:()=>{t.key===A?.key&&L||m({cwd:t.root,projectKey:t.key,projectRoot:t.root},"project")}}})).length>0?[{type:"separator",id:"separator"}]:[],n=[...e,...t,{type:"item",id:"default-directory",label:w("sidebar.useDefaultDirectory"),icon:(0,r.jsx)(rc,{size:13}),onSelect:()=>g()},{type:"item",id:"open-folder",label:w(R?"sidebar.customPath":"sidebar.openOtherProject"),icon:R?(0,r.jsx)(n8,{size:13}):(0,r.jsx)(ru,{size:13}),onSelect:()=>x(k?.opener??null)}]}else k?.kind==="worktree"&&(V=w("sidebar.switchWorktree"),n=K());let Y=k?.kind==="project"?{placeholder:w("sidebar.filterProjects"),emptyLabel:w("sidebar.noMatchingProjects"),minChoices:R?9:void 0}:{placeholder:w("sidebar.filterWorktrees"),emptyLabel:w("sidebar.noMatchingWorktrees")},G=M&&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":a,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:[T&&(0,r.jsx)(rc,{size:12,className:"project-picker-icon"}),T&&A?(0,r.jsxs)("span",{className:"project-picker-name",children:[void 0===A.alias&&P?.note&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"project-picker-parent",children:P.note}),"/"]}),(0,r.jsx)("span",{className:"project-picker-leaf",children:A.alias??P?.name??ek(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:rV(A.root,c)})}):(0,r.jsx)("span",{className:"project-picker-label",children:d}),G&&(0,r.jsx)("span",{className:"project-picker-activity",role:"img",title:w("sidebar.newActivity"),"aria-label":w("sidebar.newActivity")}),T&&(0,r.jsx)(re,{size:9,className:"project-picker-chevron sidebar-icon-down"})]}),L&&(0,r.jsxs)("button",{ref:E,type:"button",className:"project-picker-button",title:z?w("sidebar.worktreePath",{path:z.path}):w("sidebar.switchWorktree"),"aria-haspopup":"menu","aria-expanded":k?.kind==="worktree",onClick:e=>F("worktree",e.currentTarget),children:[(0,r.jsx)(rt,{size:11,className:z&&!z.isMain?"project-picker-icon is-linked":"project-picker-icon"}),(0,r.jsx)("span",{className:"project-picker-path",children:(0,r.jsx)("span",{children:z?z.branch??rV(z.path,c):"…"})}),z?.isMain&&"stacked"===s&&(0,r.jsx)("span",{className:"project-picker-note",children:w("sidebar.main")}),M&&L.length>1&&(0,r.jsx)("span",{className:"project-picker-note",children:L.length}),(0,r.jsx)(re,{size:9,className:"project-picker-chevron sidebar-icon-down"})]}),!L&&M&&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)(rt,{size:11,className:"project-picker-icon"}),(0,r.jsx)("span",{className:"project-picker-label",children:p.label})]}),(0,r.jsx)(rK,{open:null!==k,anchor:k?.anchor??null,sheet:o,ariaLabel:V,title:V,items:n,filter:Y,cancelLabel:w("sidebar.cancel"),focusCancel:q?.kind==="remove",onClose:O,returnFocusTo:k?.opener??null,width:k?.width,classic:R,footer:J,focusKey:q?`${q.kind}:${"remove"===q.kind&&q.dirty}`:"list",children:Z})]})}function rX(e,t,n){if(e.relation?.kind!=="side")return null;let r=e.relation.parentSessionId,i=t.find(e=>e.id===r),s=i?.name||i?.firstMessage||void 0,l=t.filter(e=>e.relation?.kind==="side"&&e.relation.parentSessionId===r),a=l.some(t=>t.id===e.id)?l:[...l,e];return{parentSessionId:r,...s?{parentTitle:s}:{},label:o(e,n,a)}}function rQ(e){let{open:t,query:n,children:s,selectedSessionId:l,onSelectSession:o,onSelectSideChat:a,sessions:d,archivedSessionIds:c,projectNames:u}=e,{t:p,locale:h}=(0,t_.s)(),[f,m]=(0,i.useState)({query:""}),g=n.trim(),x=f.query===g?f.response:void 0,v=f.query===g&&f.failed;return(0,i.useEffect)(()=>{if(!t||!g)return;let e=new AbortController;m({query:g});let n=setTimeout(async()=>{try{let t=await fetch(`/api/sessions/search?${new URLSearchParams({q:g})}`,{signal:e.signal});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();e.signal.aborted||m({query:g,response:n})}catch{e.signal.aborted||m({query:g,failed:!0})}},300);return()=>{clearTimeout(n),e.abort()}},[t,g]),t&&g?(0,r.jsxs)("div",{className:"min-h-20 flex-1 overflow-y-auto","aria-busy":!x&&!v,children:[(0,r.jsx)("div",{role:"status",className:"px-3 py-2 text-xs text-text-muted",children:v?p("sidebar.sessionSearchFailed"):x?0===x.results.length?p("sidebar.sessionSearchEmpty"):p("sidebar.sessionSearchCount",{count:x.results.length}):p("sidebar.sessionSearching")}),x?.truncated&&(0,r.jsx)("div",{role:"status",className:"px-3 pb-2 text-xs text-text-muted",children:p("sidebar.sessionSearchPartial")}),x?.results.map(e=>{let t,n,{session:i,entryId:s,blockIndex:f,titleMatch:m,before:g,match:x,after:v}=e,b=i.relation?.kind==="side"?i.relation:null,y=b?rX(i,d,p("agentSwitcher.sideChat")):null,w=y?y.label:i.name||i.firstMessage;return(0,r.jsxs)("button",{type:"button",onClick:()=>{b&&i.id!==l?a(i):o(i,s,f)},"aria-current":i.id===l?"true":void 0,className:`block w-full cursor-pointer border-b border-border px-3 py-2 text-left hover:bg-bg-hover focus-visible:outline-2 focus-visible:outline-accent ${i.id===l?"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:m?(0,r.jsxs)(r.Fragment,{children:[g,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:x}),v]}):w}),c?.has(i.id)&&(0,r.jsx)("span",{className:"shrink-0 rounded-[4px] border border-border px-1 text-[10px] leading-[14px] text-text-dim",children:p("sidebar.archived")})]}),y&&(0,r.jsx)("span",{className:"mt-1 block truncate text-[10px] text-text-dim",title:y.parentTitle,children:y.parentTitle?p("sidebar.sideChatOf",{name:y.parentTitle}):p("agentSwitcher.sideChat")}),(0,r.jsxs)("span",{className:"mt-1 flex min-w-0 gap-2 text-[10px] text-text-dim",children:[(0,r.jsxs)("span",{className:"min-w-0 flex-1 truncate",title:i.cwd,children:[(0,r.jsx)("span",{className:"font-medium text-text-muted",children:(t=U(i),n=i.projectRoot??i.cwd,u&&Object.hasOwn(u,t)?u[t]:ek(n))}),i.cwd!==(i.projectRoot??i.cwd)&&` \xb7 ${i.cwd}`]}),(0,r.jsx)("span",{className:"shrink-0",children:(0,nG.fw)(i.modified,h)})]}),!m&&(0,r.jsxs)("span",{className:"mt-1 block text-xs leading-relaxed wrap-anywhere text-text-muted",children:[g,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:x}),v]})]},i.id)})]}):s}function r0(e){let{toast:t,dismissLabel:n,durationMs:s,onDismissRef:l}=e,o=(0,i.useRef)(null),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(!1),p=a||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(()=>l.current(),s);return()=>window.clearTimeout(e)},[p,s,l]),(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:()=>{l.current(),e.onClick()},children:e.label},e.id)),(0,r.jsx)("button",{type:"button",className:"sidebar-toast-dismiss","aria-label":n,title:n,onClick:()=>l.current(),children:(0,r.jsx)(rd,{size:12})})]})}function r1(e){let{toast:t,onDismiss:n,dismissLabel:s,durationMs:l=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)(r0,{toast:t,dismissLabel:s,durationMs:l,onDismissRef:o},t.id):null})}let r2={remote:"sidebar.openInExplorerRemoteOnly","unsupported-platform":"sidebar.openInExplorerUnsupported"};function r4(e){let{ref:t,onClick:n,title:i,disabled:s,pressed:l,expanded:o,controls:a,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":l,"aria-expanded":o,"aria-controls":a,className:`sidebar-tool-button${l||o?" is-active":""}${d?" is-done":""}${c?` ${c}`:""}`,children:u})}let r8="pi-web:last-custom-cwd",r3={"open-new-tab":"sidebar.openInNewTab",pin:"sidebar.pin",unpin:"sidebar.unpin",rename:"sidebar.rename",fork:"sidebar.fork","mark-read":"sidebar.markRead","mark-unread":"sidebar.markUnread",archive:"sidebar.archive",unarchive:"sidebar.unarchive",delete:"sidebar.delete"};function r5(){try{return window.localStorage.getItem(r8)??""}catch{return""}}function r6(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 r9(e,t){return e.length>t?`${e.slice(0,t)}…`:e}function r7(e){let t=document.activeElement;e&&t instanceof HTMLElement&&t!==document.body&&(0===t.getClientRects().length||null!==t.closest("[inert]"))?e.focus({preventScroll:!0}):to(document,e)}function ie(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 it(e){var t,n,s;let l,o,u,p,h,f,m,g,{selectedSessionId:x,onSelectSession:v,onSelectSideChat:b,onNewSession:y,controlRef:w,onNewSessionContextChange:k,initialSessionId:j,initialSessionLinked:S,skipInitialProjectSelection:C,onInitialRestoreDone:N,refreshKey:E,onSessionDeleted:$,selectedCwd:I,onCwdChange:M,onOpenFile:T,onOpenTerminal:R,explorerRefreshKey:A,onExplorerRefresh:z,onAtMention:P,onAtMentions:W,onBackgroundTaskDone:O,hiddenFinishedSessionIds:D,onRunningSessionIdsChange:B,onSessionsChange:H}=e,{t:_}=(0,t_.s)(),q=tQ(),[Z,J]=(0,i.useState)([]),Y=(0,i.useRef)(null),G=(0,i.useRef)(0),[X,ee]=(0,i.useState)(!0),[eh,eb]=(0,i.useState)(!1),[eS,eP]=(0,i.useState)(null),[eU,e2]=(0,i.useState)(null),[e4,e5]=(0,i.useState)(""),[e9,e7]=(0,i.useState)(!1),[tn,tl]=(0,i.useState)(r5),[ta,td]=(0,i.useState)(null),[tc,tu]=(0,i.useState)(!1),[tp,th]=(0,i.useState)(null),tf=(0,i.useRef)(null),[tm,tg]=(0,i.useState)(null),[tx,tb]=(0,i.useState)(null),ty=(0,i.useRef)(null);ty.current??=new Set(eX());let[tN,tI]=(0,i.useState)(0),[tR,tA]=(0,i.useState)(!1),[tL,tz]=(0,i.useState)(!1),[tP,tW]=(0,i.useState)(!1),[tO,tF]=(0,i.useState)(""),[tD,tB]=(0,i.useState)(0),[tU,tK]=(0,i.useState)(!0),[tq,tV]=(0,i.useState)(!1),[tZ,tJ]=(0,i.useState)(!1),[tY,tG]=(0,i.useState)(null),[tX,t0]=(0,i.useState)(null),[t1,t3]=(0,i.useState)(()=>new Set),[t7,ne]=(0,i.useState)(()=>new Set),[nt,nn]=(0,i.useState)(()=>new Set),[nr,ni]=(0,i.useState)(()=>(function(){try{return tj(window.localStorage.getItem(tw))}catch{return new Map}})()),ns=(0,i.useRef)(new Set),nl=(0,i.useRef)(new Set),no=(0,i.useRef)({latest:null,before:null}),na=(0,i.useRef)(null);na.current??=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Date.now,t=0;return{note(e,n,r){tk(e)&&Number.isFinite(n)&&Number.isFinite(r)&&(t=e-(n+r)/2)},toServer(){let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:e();return n+t}}}();let nu=(0,i.useRef)(new Set),np=(0,i.useRef)(new Set),nh=(0,i.useRef)(new Set),nf=(0,i.useRef)(new Set),nm=(0,i.useRef)(!1),ng=(0,i.useRef)(null),nx=(0,i.useRef)(null),nv=(0,i.useRef)(null),nb=tH(),ny=!q&&"below"===nb,[nw,nk]=(0,i.useState)("sessions"),[nj,nS]=(0,i.useState)(!1),nC=(0,i.useRef)(null),nN=(0,i.useRef)(null),nE=(0,i.useRef)(null),n$=(0,i.useRef)(null),nI=(0,i.useRef)(new WeakMap),[nM,nT]=(0,i.useState)({}),[nR,nA]=(0,i.useState)(()=>new Set),[nL,nz]=(0,i.useState)({}),[nP,nW]=(0,i.useState)(!1),[nO,nF]=(0,i.useState)(!1),[nD,nB]=(0,i.useState)([]),[nH,n_]=(0,i.useState)(!1),{phase:nU,start:nK,end:nq}=t9(),{phase:nZ,start:nJ,end:nG}=t9(),nX=(0,i.useRef)(nj);nX.current=nj;let nQ=(0,i.useRef)(nH);nQ.current=nH;let n0=(0,i.useCallback)(e=>{e!==nQ.current&&nJ(e?"in":"out"),n_(e)},[nJ]),n1=(l=nj&&"out"===nU,o=!nj&&"in"===nU,{bodyHidden:nj&&!l,bodyInert:l,moving:l||o,open:!nj&&!o}),n2=(u=nH&&"in"===nZ,p=!nH&&"out"===nZ,{mainHidden:nH&&!u,mainInert:u,archiveMounted:nH||p,archiveInert:p,archiveClass:u?"is-entering":p?"is-leaving":null}),[n4,rt]=(0,i.useState)(null),[rd,ru]=(0,i.useState)(null),[rb,rw]=(0,i.useState)(null),[rj,rS]=(0,i.useState)(null),[rC,rN]=(0,i.useState)(null),rE=(0,i.useRef)(0),r$=(0,i.useCallback)(e=>{rN(t=>t?.id===e?null:t)},[]),[rI,rM]=(0,i.useState)(null),rT=(0,i.useCallback)(e=>{rM(t=>t?.id===e?null:t)},[]),rR=(0,i.useRef)(x);rR.current=x;let[rA,rL]=(0,i.useState)(null),rz=(0,i.useRef)(0),rP=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2?arguments[2]:void 0;rz.current+=1,rL({id:rz.current,message:e,...n?{tail:n}:{},actions:t})},[]),[rW,rO]=(0,i.useState)(0),rF=(0,i.useRef)(0),rD=(0,i.useRef)(null),[rB,rH]=(0,i.useState)(0),r_=(0,i.useRef)(null),rU=(0,i.useRef)(null),rq=(0,i.useRef)(null),rV=(0,i.useRef)(null),[rZ,rJ]=(0,i.useState)(0),rY=(0,i.useCallback)(e=>{rV.current=e,rJ(e=>e+1)},[]);(0,i.useEffect)(()=>{let e=rV.current;rV.current=null,e&&to(document,e())},[rZ]);let{state:rX,loaded:r0,synced:it,error:ir,apply:ii,snapshot:is,noteRevision:il}=function(){let[e,t]=(0,i.useState)(eo),[n,r]=(0,i.useState)(!1),[s,l]=(0,i.useState)(!1),[o,a]=(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),f=(0,i.useRef)(null),m=(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,l;let o=function(e){let t={};for(let[n,r]of Object.entries(e.sessions))t[n]={...r};let n={};for(let[t,r]of Object.entries(e.projects))n[t]={...r};let r={...e,sessions:t,projects:n};return e.projectOrder&&(r.projectOrder=[...e.projectOrder]),e.projectNames&&(r.projectNames={...e.projectNames}),e.readAt&&(r.readAt={...e.readAt}),r}(e),a=!1;switch(t.action){case"set":for(let e of t.ids){let r=V(o.sessions,e)?o.sessions[e]:void 0;ed(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))&&(a=!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),ed(o.sessions,e.id,t)&&(a=!0)}break;case"pin-project":{let{projectKey:e,root:l}=t,d=V(o.projects,e)?o.projects[e]:void 0;if(t.pinned?d?.root!==l&&(o.projects[e]={pinnedAt:n,root:l},a=!0):d&&(delete o.projects[e],a=!0),(t.pinned?void 0===d:void 0!==d)&&o.projectOrder){let n,l,d=(r=o.projectOrder,i=o.projects,s=t.pinned,l=r.filter(t=>t!==e),s?(n=0,l.forEach((e,t)=>{V(i,e)&&(n=t+1)})):(n=l.findIndex(e=>!V(i,e)))<0&&(n=l.length),l.splice(n,0,e),l);er(d.length,en(d))&&ec(o,d)&&(a=!0)}break}case"add-projects":ec(o,function(e,t){let n=eu(e,t),r=e.length,i=en(e),s=n.length;for(;s>0;){let e=et(n[s-1]);if(!er(r+1,i+e))break;r++,i+=e,s--}return[...n.slice(s),...e]}(o.projectOrder??[],t.keys))&&(a=!0);break;case"move-project":{let e,n,{projectKey:r,anchorKey:i,position:s,add:d}=t,c=o.projectOrder??[];ec(o,function(e,t){let n=e.length,r=en(e);if(er(n,r))return e;let i=new Set;for(let s=e.length-1;s>=0&&!er(n,r);s--)t.has(e[s])||(i.add(s),n--,r-=et(e[s]));let s=e.filter((e,t)=>!i.has(t));return er(n,r)?s:ei(s)}((l=[...eu(c,d),...c],(e=l.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])))&&(a=!0);break}case"rename-project":{let e=Q(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,!el(Object.keys(r).length,function(e){let t=1;for(let[n,r]of Object.entries(e))t+=es(n,r);return t}(r)))return!1;return 0===Object.keys(r).length?delete e.projectNames:e.projectNames=r,!0}(o,t.projectKey,e)&&(a=!0);break}case"read":{let e={...o.readAt};for(let r of t.ids){let t=V(e,r)?e[r]:void 0;void 0!==t&&t>=n||(e[r]=n,a=!0)}a&&(o.readAt=ea(e))}}return{state:o,changed:a}}(e,t,n).state;c.current=e,t(e)},[]),g=(0,i.useCallback)(async e=>{let t=++h.current;f.current=t;try{let n=await fetch(t8,{cache:"no-store"}),i=await t6(n);if(t!==h.current)return;d.current=i,m(),e||a(null),r(!0),l(!0)}catch(e){if(t!==h.current)return;a(t5(e)),r(!0)}finally{f.current===t&&(f.current=null)}},[m]),x=(0,i.useCallback)(()=>g(!1),[g]),v=(0,i.useCallback)(e=>{"number"!=typeof e||!Number.isFinite(e)||u.current.length>0||e===d.current.revision||(null===f.current||f.current!==h.current)&&x()},[x]),b=(0,i.useCallback)(e=>{let t={request:e,now:Date.now()};u.current=[...u.current,t],m();let n=async()=>{let n=!1;try{let t=await fetch(t8,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store"}),i=await t6(t);h.current++,d.current=i,a(null),r(!0),l(!0),n=!0}catch(e){a(t5(e))}return u.current=u.current.filter(e=>e!==t),m(),n||await g(!0),n},i=p.current.then(n,n);return p.current=i,i},[g,m]),y=(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:v,apply:b,snapshot:y}),[e,n,s,o,x,v,b,y])}(),io=(0,i.useMemo)(()=>new Set(Object.keys(rX.projects)),[rX]),ia=(0,i.useMemo)(()=>new Set(Object.entries(rX.sessions).filter(e=>{let[,t]=e;return null!=t.pinnedAt}).map(e=>{let[t]=e;return t})),[rX]),id=rX.readAt,ic=(0,i.useMemo)(()=>new Set(tS(nr,id).keys()),[nr,id]);(0,i.useEffect)(()=>{ni(e=>tS(e,id))},[id,nr]);let iu=(0,i.useRef)({allSessions:Z,readAt:id,unreadMarks:nr,runningSessionIds:t1,subagentsActiveSessionIds:nt});iu.current={allSessions:Z,readAt:id,unreadMarks:nr,runningSessionIds:t1,subagentsActiveSessionIds:nt};let ip=(0,i.useCallback)(e=>{let t=np.current,n=[...new Set(e)].filter(e=>!t.has(e));if(0!==n.length){for(let e of n)t.add(e);ii({action:"read",ids:n}).then(e=>{for(let r of n)t.delete(r),e&&nu.current.delete(r)})}},[ii]),ih=(0,i.useCallback)((e,t)=>{var n;let r=iu.current;if(r.runningSessionIds.has(e)||r.subagentsActiveSessionIds.has(e))return;if(!tT()){t&&nu.current.add(e);return}let i=r.allSessions.find(t=>t.id===e),s=i?Date.parse(i.modified):0/0;((n={readAt:r.readAt&&Object.prototype.hasOwnProperty.call(r.readAt,e)?r.readAt[e]:void 0,modifiedMs:Number.isFinite(s)?s:void 0,marked:t,pending:nu.current.has(e)}).marked||n.pending||void 0===n.readAt||void 0!==n.modifiedMs&&n.modifiedMs>n.readAt)&&ip([e])},[ip]);(0,i.useEffect)(()=>{var e;let t,n;return e=()=>{let e=rR.current;e&&ih(e,!1)},t=tM().onAttended(e),0==tE++&&(t$=function(){let e=tM(),t=()=>e.noteInput(),n=()=>e.notePageChange(),r={capture:!0,passive:!0};for(let e of tC)window.addEventListener(e,t,r);return window.addEventListener("focus",n),window.addEventListener("blur",n),document.addEventListener("visibilitychange",n),()=>{for(let e of tC)window.removeEventListener(e,t,r);window.removeEventListener("focus",n),window.removeEventListener("blur",n),document.removeEventListener("visibilitychange",n)}}()),n=!1,()=>{n||(n=!0,t(),0==--tE&&(t$?.(),t$=null))}},[ih]);let im=(0,i.useRef)(null),ig=(0,i.useRef)(null);t4(ig);let ix=(0,i.useRef)(null),iv=(0,i.useRef)(null),ib=(0,i.useRef)(320),iy=(0,i.useCallback)(()=>{let e=iv.current,t=im.current;return e&&t&&0!==e.clientHeight?e.clientHeight-t.offsetHeight:window.innerHeight-36},[]),iw=(0,i.useCallback)(()=>Math.round(.45*iy()),[iy]),ik=(0,i.useCallback)(()=>iy()-120,[iy]),ij=t2({ariaLabel:_("sidebar.resizeFiles"),axis:"vertical",cssVariable:"--sidebar-files-height",defaultWidth:320,getDefaultWidth:iw,getMaxWidth:ik,growthDirection:"up",maxWidth:2e3,minWidth:220,persistClamp:!1,storageKey:"pi-web:sidebar-files-height",widthRef:ib}),iS=ij.panelRef,iC=(0,i.useCallback)(e=>{iv.current=e,iS.current=e},[iS]),iN=ij.reclampWidth;(0,i.useEffect)(()=>{let e=iv.current;if(!ny||!e||"u"<typeof ResizeObserver)return;let t=new ResizeObserver(()=>iN());return t.observe(e),()=>t.disconnect()},[iN,ny]),(0,i.useEffect)(()=>{let e=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:eV();if(!e)return"sessions";try{return"files"===e.getItem(eW)?"files":"sessions"}catch{return"sessions"}}();"sessions"!==e&&nk(e);let t=function(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:eV();if(!t)return{};try{let e=t.getItem(eO);if(null!==e)return eZ(JSON.parse(e))}catch{return{}}try{let n=t.getItem(eF);if(null===n)return{};e=eZ(JSON.parse(n))}catch{e={}}let n=Object.fromEntries(Object.entries(e).filter(e=>{let[,t]=e;return!t}));return eJ(n,t),n}();Object.keys(t).length>0&&nT(t),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:eV();if(!e)return!1;try{return"true"===e.getItem(eB)}catch{return!1}}()&&nW(!0);let n=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:eV();if(!e)return[];try{let t=e.getItem(eD),n=null===t?[]:JSON.parse(t);if(!Array.isArray(n))return[];let r=n.filter(e=>"string"==typeof e&&""!==e);return[...new Set(r)].slice(-300)}catch{return[]}}();n.length>0&&nB(n),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:eV();if(!e)return!1;try{return"true"===e.getItem(e_)}catch{return!1}}()&&nS(!0),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:eV();if(!e)return!1;try{return"true"===e.getItem(eH)}catch{return!1}}()&&tV(!0),nF(!0),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:eV();if(e)for(let t of eq)try{e.removeItem?.(t)}catch{}}()},[]);let iE=(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=++G.current;try{e&&ee(!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!==G.current)return;Y.current=s.sessionListVersion,J(s.sessions),n||eb(!0),nm.current||(nh.current=new Set(s.completionNotificationSuppressedSessionIds??[]),no.current={latest:Date.now(),before:no.current.latest},t3(e=>r6(e,s.runningSessionIds??[])),ne(e=>r6(e,s.awaitingInputSessionIds??[])));let l=new Set(s.sessions.filter(e=>!a(e.relation)).map(e=>e.id));ni(e=>{if(0===e.size)return e;let t=new Map([...e].filter(e=>{let[t]=e;return l.has(t)}));return t.size===e.size?e:t}),eP(null)}catch(e){r===G.current&&eP(String(e))}finally{r===G.current&&ee(!1)}},[]),i$=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!i$.current;i$.current=!0;let t=!0;return e?iE(!0,!1,!0).then(()=>{t&&(ng.current=setTimeout(()=>{ng.current=null,t&&iE(!1,!0)},750))}):iE(),()=>{t=!1,ng.current&&(clearTimeout(ng.current),ng.current=null)}},[iE,E]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/open-in-explorer").then(e=>e.ok?e.json():null).then(t=>{!e&&t&&tG(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{t0(null)},[eU,I]);let iI=(0,i.useCallback)(async()=>{let e=eU??I;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 t0(null),!1;let n=await t.json().catch(()=>({}));t0(n.error??`HTTP ${t.status}`)}catch(e){t0(e instanceof Error?e.message:String(e))}return!0},[eU,I]),iM=_(tY?.platform==="darwin"?"sidebar.openInFinder":tY?.platform==="win32"?"sidebar.openInExplorer":"sidebar.openInFileManager"),iT=tY?.supported===!1,iR=tX?_(r2[tX]??tX):null;(0,i.useEffect)(()=>{try{let e=0===nr.size?null:JSON.stringify(Object.fromEntries(nr));null===e?window.localStorage.removeItem(tw):window.localStorage.setItem(tw,e)}catch{}},[nr]),(0,i.useEffect)(()=>{let e=e=>{(null===e.key||e.key===tw)&&ni(t=>(function(e,t){if(e.size!==t.size)return t;for(let[n,r]of t)if(e.get(n)!==r)return t;return e})(t,tj(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 l=Date.now(),o=null,a="error",d=null;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:s.signal});if(d=t.status,!t.ok)return;a="ok";let r=await t.json();if(o=Date.now(),e||n!==s)return;nm.current=!0,"number"==typeof r.serverNow&&na.current?.note(r.serverNow,l,o),no.current={latest:l,before:no.current.latest},nh.current=new Set(r.completionNotificationSuppressedSessionIds??[]),t3(e=>r6(e,r.runningSessionIds??[])),ne(e=>r6(e,r.awaitingInputSessionIds??[])),nn(e=>r6(e,r.subagentsActiveSessionIds??[])),il(r.sessionUiStateRevision),r.sessionListVersion!==Y.current&&await iE()}catch{a=s.signal.aborted?"aborted":"error"}finally{n===s&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500)),function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,i=Date.now();tv.count+=1,"error"===t&&(tv.failures+=1),tv.last={at:i,durationMs:Math.max(0,(r??i)-e),outcome:t,httpStatus:n}}(l,a,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)}},[iE,il]),(0,i.useEffect)(()=>{B?.(t1)},[B,t1]),(0,i.useEffect)(()=>{H?.(Z)},[Z,H]),(0,i.useEffect)(()=>{!function(e){let t,n;if("u"<typeof document)return;let r=(n=(t=te(e.awaiting))+te(e.unread))<=0?null:{kind:t>0?"awaiting":"unread",count:Math.min(n,99)},i=r?`${r.kind}:${r.count}`:"none";if(i!==tt){if(tt=i,!r){for(let[e,t]of tr)e.href=t;return}for(let e of ti())tr.has(e)||tr.set(e,e.href);ts(r,i)}}({awaiting:t7.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}(ic,D)})},[t7,ic,D]),(0,i.useEffect)(()=>{let e=ns.current,t=[...e].filter(e=>!t1.has(e)&&e!==x),n=new Set([...t1,...nt]),r=[...nl.current].filter(e=>!n.has(e)&&e!==x),i=new Set(Z.filter(e=>a(e.relation)).map(e=>e.id)),s=r.filter(e=>!nf.current.has(e)&&!i.has(e)),l=[...t1].filter(t=>!e.has(t));if(s.length>0||l.length>0){let e=no.current.before,t=na.current.toServer(e??void 0);ni(e=>{let n=new Map(e);return t1.forEach(e=>n.delete(e)),s.forEach(e=>n.set(e,t)),n})}x&&nl.current.has(x)&&!n.has(x)&&(tT()?ip([x]):nu.current.add(x));let o=l.some(e=>!Z.some(t=>t.id===e));if((t.length>0||o)&&iE(),s.length>0){let e=no.current.before??Date.now()-5e3;O?.(s,e)}ns.current=t1,nl.current=n;let d=nf.current;nf.current=new Set([...n].filter(e=>nh.current.has(e)||i.has(e)||d.has(e)&&!t1.has(e)))},[t1,nt,x,Z,iE,O,ip]),(0,i.useEffect)(()=>{if(!x)return;let e=iu.current.unreadMarks.has(x);ih(x,e),e&&ni(e=>{if(!e.has(x))return e;let t=new Map(e);return t.delete(x),t})},[x,ih]),(0,i.useEffect)(()=>{void 0!==A&&tI(e=>e+1)},[A]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&e5(e.home)}).catch(()=>{})},[]);let iA=(0,i.useRef)(!1),iL=(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:U(s)}:{root:e,key:e}}(e,{validated:tp,listing:tm,sessions:Z}):null,[tp,tm,Z]),iz=(0,i.useMemo)(()=>iL(eU),[iL,eU]),iP=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=iL(eU),t=iP.current;(t?.cwd!==eU||t.key!==(e?.key??null))&&(iP.current={cwd:eU,key:e?.key??null},M?.(eU,e?.root??null,e?.key??null))},[eU,M,iL]);let iW=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!I){iW.current=null;return}I!==iW.current&&(iW.current=I,e2(I))},[I]);let[iO,iF]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!eU){tg(null),tb(null);return}let e=!1;return tb(eU),fetch(`/api/worktrees?cwd=${encodeURIComponent(eU)}`).then(e=>e.json()).then(t=>{if(!e){if(tb(null),t.error||!t.projectRoot)return void tg(null);t.isGit?ty.current?.delete(eU):ty.current?.add(eU),function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:eV();if(!n||!e)return;let r=eX(n),i=r.indexOf(e);if(t?-1===i:-1!==i&&i===r.length-1)return;let s=r.filter(t=>t!==e);t||s.push(e);try{n.setItem(eK,JSON.stringify(s.slice(-50)))}catch{}}(eU,!!t.isGit),tg({forCwd:eU,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),tg(null))}),()=>{e=!0}},[eU,iO,E]),(0,i.useEffect)(()=>{if(0!==Z.length&&!C&&null===eU){if(j&&!iA.current){iA.current=!0;let e=Z.find(e=>e.id===j);if(e){e2(e.cwd),v(e,!0);return}N?.(),S&&rP(_("sidebar.sessionNotFound"))}let e=K(Z,io);e.length>0&&e2(e[0].root)}},[Z,io,eU,j,S,C,v,N,rP,_]);let iD=tm?tm.worktrees.find(e=>e.path===eU)??(tm.forCwd===eU&&tm.currentWorktreePath?tm.worktrees.find(e=>e.path===tm.currentWorktreePath):void 0)??tm.worktrees.find(e=>e.isMain):void 0,iB=iD?.path??null,iH=(0,i.useCallback)(async function(e){let{remember:t=!0,purpose:n=e9}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=(e??tn).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(r8,i)}catch{}tl(s.cwd)}if(e7(!1),"new-session"===n){let e=rU.current,t=rq.current;rU.current=null,rq.current=null,e?.({cwd:s.cwd,projectKey:s.projectKey,projectRoot:s.projectRoot}),rY(()=>t?.isConnected?t:null);return}th({cwd:s.cwd,root:s.projectRoot,key:s.projectKey}),e2(s.cwd)}catch(e){td(e instanceof Error?e.message:String(e))}finally{tu(!1)}}},[e9,tn,tc,rY]),i_=(0,i.useCallback)(()=>{e7("files"),td(null)},[]),iU=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"files";try{let t=await fetch("/api/default-cwd",{method:"POST"}),n=await t.json();n.cwd&&await iH(n.cwd,{remember:!1,purpose:e})}catch{}},[iH]),iK=(0,i.useRef)(iU);iK.current=iU;let iq=(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:_(t.key,{...t.params,path:e1(t.params.path)})}:t}let s=i.path;return tg(n=>n&&n.projectKey===e.key&&!n.worktrees.some(e=>e.path===s)?{...n,worktrees:[...n.worktrees,{path:s,branch:t,isMain:!1}]}:n),iF(e=>e+1),{path:s}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},[_]),iV=(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 iB===t&&e2(e.root),iF(e=>e+1),"removed"}catch(e){return{error:e instanceof Error?e.message:String(e)}}},[iB]),iZ=(0,i.useCallback)(()=>iF(e=>e+1),[]),iJ=(0,i.useCallback)(e=>{let{cwd:t,projectKey:n,projectRoot:r}=e;n&&r&&th({cwd:t,root:r,key:n}),e2(t)},[]),iY=(0,i.useCallback)((e,t,n,r)=>{J(t=>t.some(t=>t.id===e.id)?t:[e,...t]),e.cwd&&e2(e.cwd),v(e,!1,t,n,r)},[v]),iG=(0,i.useCallback)(e=>{let{cwd:t,projectKey:n,projectRoot:r,carryComposer:i}=e;n&&r&&th({cwd:t,root:r,key:n}),e2(t),y?.("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)},[y]),iX=(0,i.useRef)(iG);iX.current=iG,(0,i.useImperativeHandle)(w,()=>({startNewSessionIn:e=>iX.current(e),openFolderForNewSession:(e,t)=>{rU.current=e,rq.current=t,td(null),e7("new-session")},openDefaultDirectoryForNewSession:e=>{rU.current=e,rq.current=null,iK.current("new-session")},refreshWorktrees:iZ,createWorktree:iq}),[iq,iZ]);let iQ=(0,i.useCallback)(()=>{eU&&iG({cwd:eU})},[eU,iG]),i0=(0,i.useMemo)(()=>K(Z,io),[Z,io]),i1=(0,i.useMemo)(()=>d(Z,ia),[Z,ia]),i2=(0,i.useMemo)(()=>new Map(i1.map(e=>[e.root.id,e])),[i1]),i4=(0,i.useMemo)(()=>{let e=new Set,t=new Map;for(let n of i1){if(!ey(n,rX,t1))continue;for(let t of ev(n))e.add(t);let r=U(n.root);t.set(r,(t.get(r)??0)+1)}return{ids:e,countByProject:t}},[i1,rX,t1]),i8=(0,i.useMemo)(()=>(function(e,t,n){let r=new Map;for(let i of e){let e=U(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===i4.ids.size?Z:Z.filter(e=>!i4.ids.has(e.id)),t1,ic),[Z,i4,t1,ic]),i3=!!(tm?.isGit&&tm.isTopLevel&&eU&&iz?.key===tm.projectKey),i5=eU&&tm?.isGit&&iz?.key===tm.projectKey&&!i3?{label:_("sidebar.openRepoRoot"),title:_("sidebar.openRepoRootTitle")}:null,i6=!!(eU&&tx===eU),i9=i5??(!i6||i3||eU&&ty.current?.has(eU)?null:{label:_("sidebar.worktrees"),title:_("sidebar.checkingWorktrees")}),i7=iz?.key??null,se=iz?.root??null,st=(0,i.useMemo)(()=>i7&&se?{key:i7,root:se}:null,[i7,se]),sn=(0,i.useMemo)(()=>0===nR.size?nM:Object.fromEntries([...[...nR].filter(e=>!Object.hasOwn(nM,e)).map(e=>[e,!0]),...Object.entries(nM)]),[nM,nR]),sr=(0,i.useMemo)(()=>(function(e){let{uiState:t,runningIds:n,currentProject:r}=e,i=d(e.sessions),s=eE(t,r),l=0,o=[],a=new Map,c=new Map,u=new Set;for(let e of i){if(ey(e,t,n)){l++;continue}s.noteFamily(e);let r=eN(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),ew(e,t,n)){o.push(e);continue}let d=a.get(r);d?d.push(e):a.set(r,[e])}let p=[{kind:"spacer",key:"top-spacer"}];if(o.length>0){let n=e=>eg(em(t,e.root.id)?.pinnedAt)??0,r=o.map((e,t)=>({family:e,index:t})).sort((e,t)=>ex(n(e.family),n(t.family))||e.index-t.index).map(e=>{let{family:t}=e;return t}),{running:i,awaiting:l,unread:a}=eC(r,e);if(p.push({kind:"pinned-header",key:"pinned-header",count:r.length,collapsed:e.pinnedCollapsed,running:i,awaiting:l,unread:a}),!e.pinnedCollapsed){let{visible:t,revealed:n,nextShown:i}=eI(r,8,eM(e.moreShown,ef),e);for(let n of t)p.push(e$(n,"pinned",s.get(eN(n)),e));let l=eR(r.length,t.length,n);l&&p.push({kind:"pinned-more",key:"pinned-more",...l,nextShown:i})}p.push({kind:"spacer",key:"pinned-spacer"})}let h=[...a.keys()],f=new Set(h),m=e=>{f.has(e)||(f.add(e),h.push(e))};for(let e of(r&&m(r.key),Object.keys(t.projects)))m(e);let g=h.map(e=>s.get(e)),x=new Map;(t.projectOrder??[]).forEach((e,t)=>{x.has(e)||x.set(e,t)});let v=e=>e.pinned||u.has(e.key),b=(e,t)=>[...e.filter(e=>{let{project:t}=e;return!x.has(t.key)}).sort((e,n)=>Number(v(e.project))-Number(v(n.project))||t(e,n)),...e.filter(e=>{let{project:t}=e;return x.has(t.key)}).sort((e,t)=>(x.get(e.project.key)??0)-(x.get(t.project.key)??0))].map(e=>{let{project:t}=e;return t}),y=e=>c.get(e.key)??(e.current?1/0:-1/0),w=e=>eg(t.projects[e.key]?.pinnedAt)??0,k=g.map((e,t)=>({project:e,index:t})),j=b(k.filter(e=>{let{project:t}=e;return t.pinned}),(e,t)=>ex(w(t.project),w(e.project))||e.index-t.index),S=b(k.filter(e=>{let{project:t}=e;return!t.pinned}),(e,t)=>ex(y(e.project),y(t.project))||e.index-t.index),C=[...j,...S],N=e=>e.filter(e=>!x.has(e.key)).map(e=>e.key),E={pinned:N(j),other:N(S)},$=C.filter(e=>!x.has(e.key)&&v(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=a.get(n.key)??[],i=ej(n,e.groupExpansion),{running:s,awaiting:l,unread:o}=eC(r,e);if(p.push({kind:"group",key:`group:${n.key}`,project:n,expanded:i,running:s,awaiting:l,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}=eI(r,6,eM(e.moreShown,n.key),e);for(let r of t)p.push(e$(r,"group",n,e));let l=eR(r.length,t.length,i);l&&p.push({kind:"group-more",key:`more:${n.key}`,projectKey:n.key,...l,nextShown:s})}}return C.length>0&&p.push({kind:"spacer",key:"footer-spacer"}),p.push({kind:"footer-open",key:"footer-open"}),l>0&&p.push({kind:"footer-archived",key:"footer-archived",count:l}),{rows:p,projects:C,archivedCount:l,unorderedKeysByBand:E,projectKeysToRecord:$}})({sessions:Z,uiState:rX,runningIds:t1,awaitingIds:t7,unreadIds:ic,selectedSessionId:x,currentProject:st,groupExpansion:sn,moreShown:nL,pinnedCollapsed:nP}),[Z,rX,t1,t7,ic,x,st,sn,nL,nP]),si=n2.archiveMounted,ss=(0,i.useMemo)(()=>new Set(nD),[nD]),sl=(0,i.useMemo)(()=>si?function(e){let{uiState:t,runningIds:n}=e,r=eE(t,e.currentProject),i=new Map;for(let s of d(e.sessions)){if(!ey(s,t,n))continue;r.noteFamily(s);let e=eg(em(t,s.root.id)?.archivedAt)??0,l=eN(s),o=i.get(l);o?(o.families.push({family:s,archivedAt:e}),o.newest=Math.max(o.newest,e)):i.set(l,{newest:e,families:[{family:s,archivedAt:e}]})}let s=[];for(let{key:t,group:n}of[...i.entries()].map((e,t)=>{let[n,r]=e;return{key:n,group:r,index:t}}).sort((e,t)=>ex(e.group.newest,t.group.newest)||e.index-t.index)){let i=r.get(t),l=!e.collapsed?.has(t);if(s.push({kind:"archive-group",key:`archive:${t}`,project:i,count:n.families.length,expanded:l}),l)for(let{family:t}of n.families.map((e,t)=>({...e,index:t})).sort((e,t)=>ex(e.archivedAt,t.archivedAt)||e.index-t.index))s.push(e$(t,"archive",i,e))}return s}({sessions:Z,uiState:rX,runningIds:t1,awaitingIds:t7,unreadIds:ic,selectedSessionId:x,currentProject:st,collapsed:ss}):[],[si,Z,rX,t1,t7,ic,x,st,ss]),so=(0,i.useMemo)(()=>sl.flatMap(e=>"archive-group"===e.kind?[e]:[]),[sl]),sa=(0,i.useMemo)(()=>new Map(sr.projects.map(e=>[e.key,e])),[sr.projects]),sd=(0,i.useRef)(new Set),sc=sr.projectKeysToRecord,su=rX.projectOrder?.length??0;(0,i.useEffect)(()=>{if(X||!it||!eh||su>=1e3)return;let e=sd.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)}(sc,e);if(0!==t.length){for(let n of t)e.add(n);ii({action:"add-projects",keys:t})}},[ii,X,sc,eh,su,it]);let sp=rX.projectNames,sh=(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(e6(s,n)));return i})(sr.projects,i0,sp),[sr.projects,i0,sp]),sf=(0,i.useMemo)(()=>{if(!eU||!iz)return null;let e=i3&&null!==tm;return{cwd:eU,project:e6(iz,sp),worktrees:e?tm.worktrees.map(e=>{let{path:t,branch:n,isMain:r}=e;return{path:t,branch:n,isMain:r}}):null,currentWorktreePath:e?iB:null,projects:sh}},[eU,iz,i3,tm,iB,sh,sp]),sm=(0,i.useRef)(sf);sm.current=sf;let sg=sf?JSON.stringify([sf.cwd,sf.project.key,sf.project.root,sf.project.alias??null,sf.currentWorktreePath,sf.worktrees?.map(e=>[e.path,e.branch,e.isMain])??null,sf.projects.map(e=>[e.key,e.root,e.alias??null])]):"";(0,i.useEffect)(()=>{k?.(sm.current)},[sg,k]);let sx=(0,i.useRef)(i7);(0,i.useLayoutEffect)(()=>{let e=sx.current;if(sx.current=i7,null===e||e===i7)return;let t=sa.get(e);nA(e=>!t||t.current||t.pinned||e.has(t.key)||Object.hasOwn(nM,t.key)?e:new Set(e).add(t.key))},[i7,nM,sa]);let sv=(0,i.useCallback)((e,t)=>{nT(e),eJ(e),nA(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)),nz(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))},[]),sb=(0,i.useCallback)(()=>(nE.current?.hidden?nN:nC).current??ix.current,[]),sy=(0,i.useCallback)(e=>{let t=nE.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 sb()},[sb]),sw=(0,i.useCallback)(e=>{let t=CSS.escape(`group:${e}`),n=nE.current?.querySelector(`[data-row-key="${t}"] .session-tree-group-toggle`);return n&&n.getClientRects().length>0?n:sb()},[sb]),sk=(0,i.useCallback)(async e=>{let t=await ii(e);return t||rO(e=>e+1),t},[ii]);(0,i.useEffect)(()=>{rW!==rF.current&&(rF.current=rW,rP(_("sidebar.uiStateFailed",{error:ir??""})))},[rW,ir,rP,_]);let sj=(0,i.useCallback)((e,t,n)=>{let r=sa.get(e),i=sa.get(t);r&&i&&r!==i&&r.pinned===i.pinned&&(sk({action:"move-project",projectKey:e,anchorKey:t,position:n,add:sr.unorderedKeysByBand[r.pinned?"pinned":"other"].slice(-500)}),rE.current+=1,rN({id:rE.current,at:Date.now(),rowKey:`group:${e}`}))},[sk,sr.unorderedKeysByBand,sa]),sS=(0,i.useCallback)(e=>{ny||(nk(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eV();if(t)try{t.setItem(eW,e)}catch{}}(e))},[ny]),sC=(0,i.useCallback)(e=>{e!==nX.current&&nK(e?"out":"in"),nS(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eV();if(t)try{t.setItem(e_,String(e))}catch{}}(e)},[nK]),sN=(0,i.useCallback)(e=>{let t=e.target;t instanceof Element&&nI.current.set(t,t.scrollTop)},[]);(0,i.useLayoutEffect)(()=>{for(let e of[nE.current,n$.current])if(e&&!e.hidden)for(let t of e.querySelectorAll(".session-tree-scroll, .sidebar-files-scroll")){let e=nI.current.get(t);void 0!==e&&t.scrollTop!==e&&(t.scrollTop=e)}},[nw,nH,ny,nj]);let sE=(0,i.useCallback)(e=>{if(rS(null),n0(!0),tW(!1),sS("sessions"),void 0!==e){if(nD.includes(e)){let t=nD.filter(t=>t!==e);nB(t),eY(t)}rE.current+=1,rM({id:rE.current,at:Date.now(),rowKey:`archive:${e}`,block:"start"})}},[nD,n0,sS]),s$=(0,i.useRef)(null),sI=(0,i.useRef)(nH),sM=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(sI.current===nH)return;if(sI.current=nH,nH)return void r7(s$.current);let e=nE.current?.querySelector('[data-row-key="footer-archived"] button'),t=e&&e.getClientRects().length>0?e:sb();r7(t),t&&document.activeElement===t&&(sM.current=t)},[nH,sb]);let sT=(0,i.useRef)(null),sR=(0,i.useRef)(ny);(0,i.useLayoutEffect)(()=>{if(sR.current===ny)return;sR.current=ny;let e=sT.current;e&&(!e.isConnected||0===e.getClientRects().length)&&r7(sb())},[ny,sb]);let sA=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"===nw?"files":"sessions";sS(t),("sessions"===t?nC:nN).current?.focus()},sL=(0,i.useCallback)((e,t)=>{sk({action:"set",ids:[e.root.id],pinned:t})},[sk]),sz=(0,i.useCallback)((e,t)=>{var n;if(t){let t=iu.current.unreadMarks;ip([e.root.id,...ev(e).filter(e=>t.has(e))])}let r=iu.current.readAt,i=r&&Object.prototype.hasOwnProperty.call(r,e.root.id)?r[e.root.id]:void 0,s=(n=na.current.toServer(),void 0===i?n:Math.max(n,i+1));ni(n=>{let r=new Map(n);if(t)for(let t of ev(e))r.delete(t);else r.set(e.root.id,s);return r})},[ip]),sP=(0,i.useCallback)(e=>{0!==e.length&&ni(t=>{let n=new Map(t);for(let[t,r]of e)t===rR.current||n.has(t)||n.set(t,r);return n.size===t.size?t:n})},[]),sW=(0,i.useCallback)(e=>{let t=e.filter(e=>!e.root.transient);if(0===t.length)return;let n=is(t.map(e=>e.root.id)),r=t.flatMap(e=>ev(e)),i=r.flatMap(e=>{let t=nr.get(e);return void 0!==t&&ic.has(e)?[[e,t]]:[]});for(let e of ep(t))sk({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=>ev(e)));sP(i.filter(e=>{let[t]=e;return n.has(t)}))});i.length>0&&ni(e=>{let t=new Map(e);for(let e of r)t.delete(e);return t}),rP(1===t.length?_("sidebar.archivedToast",{title:r9(ry(t[0].root),28)}):_("sidebar.archivedManyToast",{count:t.length}),[{id:"undo",label:_("sidebar.undo"),onClick:()=>{for(let e of ep(n))sk({action:"restore",entries:e});sP(i),rY(()=>sy(t[0].root.id))}},{id:"view",label:_("sidebar.viewArchive"),onClick:()=>sE()}])},[sk,rY,sy,sE,sP,rP,is,_,nr,ic]),sO=(0,i.useCallback)(e=>{ev(e).some(e=>t1.has(e))||sW([e])},[sW,t1]),sF=(0,i.useCallback)(e=>{if(0===e.length)return;let t=e.map(e=>e.root.id),n=is(t);for(let e of ep(t))sk({action:"set",ids:e,archived:!1});rP(1===e.length?_("sidebar.restoredToast",{title:r9(ry(e[0].root),28)}):_("sidebar.restoredManyToast",{count:e.length}),[{id:"undo",label:_("sidebar.undo"),onClick:()=>{for(let e of ep(n))sk({action:"restore",entries:e});rY(()=>sy(e[0].root.id))}}])},[sk,sy,rY,rP,is,_]),sD=(0,i.useCallback)(e=>sF([e]),[sF]),sB=(0,i.useCallback)(e=>{e.root.transient||(rw(null),rt(e.root.id))},[]),sH=(0,i.useCallback)(async(e,t)=>{let n=e.root,r=ry(n),i=t.trim();if(rt(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})}),iE()}catch{}},[iE]),s_=(0,i.useCallback)(e=>{ru(e.key)},[]),sU=(0,i.useCallback)(e=>{ru(t=>t===e?null:t),rY(()=>sw(e))},[rY,sw]),sK=(0,i.useCallback)((e,t)=>{sU(e.key);let n=function(e,t){let n=t.trim();if(n===e.name)return null;let r=""===n||n===ek(e.root);return r&&null===e.customName?null:{action:"rename-project",projectKey:e.key,name:r?null:n}}(e,t);n&&sk(n)},[sk,sU]),sq=(0,i.useCallback)(async e=>{let t=e.root;if(!t.transient){rw(e=>e===t.id?null:e);try{(await fetch(`/api/sessions/${encodeURIComponent(t.id)}`,{method:"DELETE"})).ok&&[t,...e.subagents].forEach(e=>L(e.id)),$?.(t.id),iE()}catch{}}},[iE,$]),sV=(0,i.useCallback)((e,t)=>{t?sq(e):(rt(null),rw(e.root.id))},[sq]),sZ=(ny||"sessions"===nw)&&!nH&&!(tP&&""!==tO.trim()),sJ=(0,i.useRef)(null),sY=(0,i.useRef)(null),sG=(0,i.useRef)(null);(0,i.useEffect)(()=>{x!==sY.current&&(sY.current=x,sJ.current=x);let e=sJ.current;if(!e||X||!r0||!nO||!sZ)return;sJ.current=null;let t=sG.current;sG.current=null;let n=function(e,t){let n=c(e.sessions,t);if(!n||ey(n,e.uiState,e.runningIds))return null;let r=eN(n);if(ew(n,e.uiState,e.runningIds))return{rowKey:`session:pinned:${n.root.id}`,projectKey:r,unfoldPinned:e.pinnedCollapsed,unfoldGroup:!1};let i=Object.hasOwn(e.groupExpansion,r)&&!1===e.groupExpansion[r];return{rowKey:`session:group:${n.root.id}`,projectKey:r,unfoldPinned:!1,unfoldGroup:i}}({sessions:Z,uiState:rX,runningIds:t1,groupExpansion:sn,pinnedCollapsed:nP},e);if(n){if(n.unfoldPinned&&(nW(!1),eG(!1)),n.unfoldGroup){let e={...nM};delete e[n.projectKey],e[n.projectKey]=!0,sv(e,[n.projectKey])}rE.current+=1,rN({id:rE.current,at:Date.now(),rowKey:n.rowKey,block:"nearest",...t?.sessionId===e?{takeFocusFrom:t.takeFocusFrom}:{}})}},[x,Z,rX,t1,sn,nM,nP,X,r0,nO,sZ,sv]);let sX=(e,t)=>{if(sM.current=null,nH){let e=nE.current?.querySelector(".sidebar-sessions-view .session-tree-scroll");e&&nI.current.delete(e),n0(!1)}let n=t?`[data-row-key="${CSS.escape(t)}"]`:null;sG.current={sessionId:e.id,takeFocusFrom:e=>null!==n&&null!==e.closest(n)||e===sM.current},iY(e,void 0,void 0,{keepSidebarOpen:null!==t}),iE()},sQ=(0,i.useRef)(sX);sQ.current=sX;let s0=(0,i.useRef)(new Set),s1=(0,i.useCallback)(async e=>{let t=e.family.root;if(t.transient||s0.current.has(t.id))return;s0.current.add(t.id);let n=rR.current;try{var r;let i,s,l=await fetch(`/api/sessions/${encodeURIComponent(t.id)}/fork`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),o=await l.json().catch(()=>({}));if(!l.ok||!o.session){let{key:e,params:t}=eQ(o.code,o.error??`HTTP ${l.status}`);rP(_(e,t)),"not_found"===o.code&&iE();return}let a=o.session,d=ry(a),{head:c,tail:u}=(r=_("sidebar.forkedToast",{title:d}),((s=(i=e8(d)?.suffix)?r.lastIndexOf(i):-1)>0?{head:r.slice(0,s),tail:r.slice(s)}:null)??{head:_("sidebar.forkedToast",{title:r9(d,28)}),tail:void 0});if(rR.current!==n){J(e=>e.some(e=>e.id===a.id)?e:[a,...e]);let e=na.current.toServer();ni(t=>new Map(t).set(a.id,e)),iE(),rP(c,[{id:"open",label:_("sidebar.open"),onClick:()=>sQ.current(a,null)}],u);return}sQ.current(a,e.key),rP(c,[],u)}catch(e){rP(_("sidebar.forkFailed",{error:e instanceof Error?e.message:String(e)}))}finally{s0.current.delete(t.id)}},[iE,rP,_]),s2=(0,i.useCallback)(e=>{e.root.transient||window.open(F(e.root.id),"_blank","noopener,noreferrer")},[]),s4=(0,i.useCallback)((e,t,n)=>{e.status.transient||rS({kind:"row",row:e,anchor:t,opener:n})},[]),s8=(0,i.useCallback)((e,t)=>{let n=e.family.root;if(n.id===n4||n.id===rb)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:()=>{iE()}})){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?ie(r,"start"):{kind:"point",x:t.clientX,y:t.clientY},s=document.activeElement,l=s instanceof HTMLElement&&null!==r&&r.contains(s);r_.current=!l&&s instanceof HTMLElement&&s!==document.body?s:null,s4(e,i,l?s:null)},[rb,iE,s4,n4]),s3=(0,i.useMemo)(()=>({sessions:Z,uiState:rX,runningIds:t1,awaitingIds:t7,unreadIds:ic,selectedSessionId:x}),[Z,rX,t1,t7,ic,x]),s5=(0,i.useCallback)((e,t)=>{let n=eA(s3,e.key,6048e5,Date.now()).length;rS({kind:"group",project:e,olderCount:n,anchor:ie(t,"end"),opener:t})},[s3]),s6=(0,i.useCallback)(e=>{sW(eA(s3,e.key,6048e5,Date.now()).flatMap(e=>{let t=i2.get(e);return t?[t]:[]}))},[sW,i2,s3]),s9=(0,i.useCallback)((e,t)=>{rS(n=>n?.kind==="group"&&n.project.key===e?{...n,askDelete:t}:n)},[]),s7=(0,i.useRef)(new Set),le=(0,i.useCallback)(async(e,t,n)=>{if(rS(null),!(0===t.length||s7.current.has(e))){s7.current.add(e),rP(_("sidebar.deletingSessions"));try{let e=await e0(t,fetch);for(let t of e.deleted)L(t),$?.(t);if(iE().then(()=>rY(n)),null!==e.error)return void rP(_("sidebar.deleteFailed",{error:e.error}));let r=e.deletedRoots.length,i=[1===r?_("sidebar.deletedOneToast"):_("sidebar.deletedManyToast",{count:r})];e.running.length>0&&i.push(_("sidebar.keptRunningToast",{count:e.running.length})),rP(i.join(" \xb7 "))}finally{s7.current.delete(e)}}},[rY,iE,$,rP,_]),lt=(0,i.useCallback)(e=>{let{ids:t}=eL(s3,e.key);le(`project:${e.key}`,t,()=>sw(e.key))},[le,sw,s3]),ln=(0,i.useCallback)(e=>{let t=null===e?null:CSS.escape(`archive:${e}`),n=null===t?null:nE.current?.querySelector(`[data-row-key="${t}"] .session-tree-group-toggle`);if(n&&n.getClientRects().length>0)return n;let r=s$.current;return r&&r.getClientRects().length>0?r:sb()},[sb]),lr=(0,i.useCallback)(e=>e.flatMap(e=>{let t=i2.get(e);return t?[t]:[]}),[i2]),li=(0,i.useCallback)((e,t)=>{rS({kind:"archive-group",project:e,anchor:ie(t,"end"),opener:t})},[]),ls=(0,i.useCallback)(e=>{rS(t=>t?.kind==="archive"?null:{kind:"archive",anchor:ie(e,"end"),opener:e})},[]),ll=(0,i.useCallback)(e=>{rS(t=>t?.kind==="archive"?{...t,askDelete:e}:t?.kind==="archive-group"?{...t,askDelete:void 0!==e}:t)},[]),lo=(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||eN(r)===t.projectKey)&&ey(r,e.uiState,e.runningIds)){if(void 0!==t.archivedBefore){let n=eg(em(e.uiState,r.root.id)?.archivedAt);if(null===n||n>=t.archivedBefore)continue}n.push(r.root.id)}return n})(s3,"all"===e?{}:"old"===e?{archivedBefore:Date.now()-2592e6}:e),[s3]),la=(0,i.useCallback)(e=>{let t=lo(e);le("string"==typeof e?`archive:${e}`:`archive-project:${e.projectKey}`,t,()=>"string"==typeof e?ln(null):ln(e.projectKey))},[lo,ln,le]),ld=(0,i.useCallback)(e=>{nB(e),eY(e)},[]),lc=(0,i.useCallback)(e=>{let t=so.map(e=>e.project.key),n=nD.filter(e=>!t.includes(e));ld(e?n:[...n,...t])},[nD,so,ld]),lu=(0,i.useCallback)((e,t)=>{let n=nD.includes(e);if(t)return void lc(n);let r=nD.filter(t=>t!==e);ld(n?r:[...r,e])},[nD,ld,lc]),lp=(0,i.useCallback)(e=>{rS(null),iG(e3(e,eU))},[eU,iG]),lh=(0,i.useCallback)(()=>rS(null),[]);(0,i.useEffect)(()=>{if(null!==rj)return;let e=r_.current;if(r_.current=null,!e?.isConnected)return;let t=document.activeElement;t&&t!==document.body||e.focus({preventScroll:!0})},[rj]);let lf=nH?sl:sr.rows;(0,i.useEffect)(()=>{rj?.kind!=="row"||lf.some(e=>e.key===rj.row.key)||rS(null),rj?.kind!=="archive-group"||lf.some(e=>e.key===`archive:${rj.project.key}`)||rS(null)},[rj,lf]);let lm=rj?.kind==="row"?lf.find(e=>"session"===e.kind&&e.key===rj.row.key)??rj.row:null,lg=(0,i.useCallback)(e=>{iY(e.root)},[iY]),lx=(0,i.useCallback)(e=>{let t={...nM};for(let n of sr.projects)delete t[n.key],t[n.key]=e(n);sv(t,null)},[nM,sr.projects,sv]),lv=(0,i.useCallback)((e,t)=>{let n=sa.get(e);if(!n)return;let r=!ej(n,sn);if(t)return void lx(()=>r);let i={...nM};delete i[e],i[e]=r,sv(i,[e])},[nM,sa,sv,lx,sn]),lb=(0,i.useCallback)(e=>{let t=sr.rows.find(t=>"group-more"===t.kind&&t.projectKey===e||"pinned-more"===t.kind&&e===ef);(t?.kind==="group-more"||t?.kind==="pinned-more")&&nz(n=>{var r;return r=t.nextShown,{...n,[e]:Math.max(eM(n,e),Math.floor(r))}})},[sr.rows]),ly=(0,i.useCallback)(e=>{nz(t=>eT(t,e))},[]),lw=(0,i.useCallback)(e=>{rD.current=e,rH(e=>e+1),ny?sC(!1):sS("files")},[sC,ny,sS]),lk=ny?n1.open:"files"===nw;(0,i.useEffect)(()=>{let e=rD.current;e&&lk&&(rD.current=null,"project-list"===e?tf.current?.openMenu("project"):"file-search"===e?document.getElementById("file-search-input")?.focus({preventScroll:!0}):tf.current?.button("project")?.focus({preventScroll:!0}))},[lk,rB]);let lj=e=>{let{heading:t,headingTitle:n,notes:i,count:s,onConfirm:l,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:l,children:_("sidebar.deleteCount",{count:s})}),!q&&(0,r.jsx)("button",{type:"button",className:"sidebar-menu-question-cancel","data-sidebar-menu-autofocus":"",onClick:o,children:_("sidebar.cancel")})]})]})},lS=(e,t)=>lj({heading:t?_("sidebar.deleteArchivedInProjectHeading",{name:t.name}):_("old"===e?"sidebar.deleteOldArchivedHeading":"sidebar.deleteAllArchivedHeading"),headingTitle:t?.root,notes:[_("sidebar.deleteArchivedMessage")],count:lo(e).length,onConfirm:()=>la(e),onCancel:()=>ll(void 0)}),lC="",lN=null;if(rj?.kind==="row"&&lm)f=ry(lm.family.root),lC=_("sidebar.sessionActions"),g=(function(e,t){if(t.transient)return[];let n={kind:"action",id:"open-new-tab",shortcut:"T"};return"archive"===e?[{kind:"action",id:"unarchive",shortcut:"A"},{kind:"action",id:"pin",shortcut:"P"},{kind:"action",id:"rename",shortcut:"R"},{kind:"action",id:"fork",shortcut:"F"},n,{kind:"separator"},{kind:"action",id:"delete",shortcut:"D"}]:[{kind:"action",id:"pinned"===e?"unpin":"pin",shortcut:"P"},{kind:"action",id:"rename",shortcut:"R"},{kind:"action",id:"fork",shortcut:"F"},{kind:"action",id:t.unread?"mark-read":"mark-unread",shortcut:"U"},t.running?{kind:"action",id:"archive",shortcut:"A",disabledReason:"running"}:{kind:"action",id:"archive",shortcut:"A"},n,{kind:"separator"},{kind:"action",id:"delete",shortcut:"D"}]})(lm.context,lm.status).map((e,t)=>{if("separator"===e.kind)return{type:"separator",id:`separator-${t}`};let n=_(r3[e.id]);return{type:"item",id:e.id,label:"delete"===e.id?`${n}…`:n,icon:function(e){switch(e){case"open-new-tab":return(0,r.jsx)(rr,{});case"pin":return(0,r.jsx)(n9,{});case"unpin":return(0,r.jsx)(n7,{});case"rename":return(0,r.jsx)(rs,{});case"fork":return(0,r.jsx)(rn,{});case"mark-read":return(0,r.jsx)(ro,{});case"mark-unread":return(0,r.jsx)(rl,{});case"archive":return(0,r.jsx)(n5,{});case"unarchive":return(0,r.jsx)(n6,{});case"delete":return(0,r.jsx)(ri,{})}}(e.id),shortcut:e.shortcut,danger:"delete"===e.id,disabled:void 0!==e.disabledReason,disabledReason:"running"===e.disabledReason?_("sidebar.cannotArchiveRunning"):void 0,onSelect:t=>{let{shiftKey:n}=t;return((e,t,n)=>{let{family:r}=t;switch(e){case"open-new-tab":s2(r);break;case"pin":sL(r,!0);break;case"unpin":sL(r,!1);break;case"rename":sB(r);break;case"fork":s1(t);break;case"mark-read":sz(r,!0);break;case"mark-unread":sz(r,!1);break;case"archive":sO(r);break;case"unarchive":sD(r);break;case"delete":sV(r,n)}})(e.id,lm,n)}}});else if(rj?.kind==="group"){let e,t,i,l,o,a=sa.get(rj.project.key)??rj.project;f=a.name,lC=_("sidebar.projectActions",{name:a.name}),n=a,s=rj.olderCount,e=i4.countByProject.get(n.key)??0,t=eL(s3,n.key),i=ez(sr.projects,n.key,"up"),l=ez(sr.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:_("sidebar.renameProject"),icon:(0,r.jsx)(rs,{}),onSelect:()=>s_(n)}:{type:"item",id:e,label:_("sidebar.resetProjectName"),icon:(0,r.jsx)(n6,{}),onSelect:()=>{sk({action:"rename-project",projectKey:n.key,name:null})}}),g=[{type:"item",id:"pin-project",label:_(n.pinned?"sidebar.unpinProject":"sidebar.pinProject"),icon:n.pinned?(0,r.jsx)(n7,{}):(0,r.jsx)(n9,{}),onSelect:()=>{sk({action:"pin-project",projectKey:n.key,root:n.root,pinned:!n.pinned})}},...o,{type:"item",id:"open-in-files",label:_("sidebar.openInFilesTab"),icon:(0,r.jsx)(rc,{}),onSelect:()=>{n.current||e2(n.root),lw("project-button")}},{type:"item",id:"open-new-tab",label:_("sidebar.openInNewTab"),icon:(0,r.jsx)(rr,{}),shortcut:"T",onSelect:()=>(e=>{let{cwd:t}=e3(e,eU);window.open(`?cwd=${encodeURIComponent(t)}`,"_blank","noopener,noreferrer")})(n)},{type:"separator",id:"separator-layout"},{type:"item",id:"move-up",label:_("sidebar.moveProjectUp"),icon:(0,r.jsx)(re,{className:"sidebar-icon-up"}),disabled:null===i,onSelect:()=>{i&&sj(n.key,i.anchorKey,i.position)}},{type:"item",id:"move-down",label:_("sidebar.moveProjectDown"),icon:(0,r.jsx)(re,{className:"sidebar-icon-down"}),disabled:null===l,onSelect:()=>{l&&sj(n.key,l.anchorKey,l.position)}},{type:"item",id:"collapse-others",label:_("sidebar.collapseOtherGroups"),icon:(0,r.jsx)(re,{}),disabled:sr.projects.every(e=>ej(e,sn)===(e.key===n.key)),onSelect:()=>lx(e=>e.key===n.key)},{type:"item",id:"expand-all",label:_("sidebar.expandAllGroups"),icon:(0,r.jsx)(re,{className:"sidebar-icon-down"}),disabled:sr.projects.every(e=>ej(e,sn)),onSelect:()=>lx(()=>!0)},{type:"separator",id:"separator-sessions"},{type:"item",id:"archive-older",label:_("sidebar.archiveOlderThanWeek",{count:s}),icon:(0,r.jsx)(n5,{}),disabled:0===s,onSelect:()=>s6(n)},{type:"item",id:"view-archived",label:_("sidebar.viewArchived",{count:e}),icon:(0,r.jsx)(n5,{}),disabled:0===e,onSelect:()=>sE(n.key)},{type:"item",id:"delete-all",label:_("sidebar.deleteProjectSessions",{count:t.ids.length}),icon:(0,r.jsx)(ri,{}),danger:!0,disabled:0===t.ids.length,onSelect:e=>{let{keepOpen:t}=e;t(),s9(n.key,!0)}}],rj.askDelete&&(lN=(e=>{let{ids:t,running:n}=eL(s3,e.key);return lj({heading:_("sidebar.deleteProjectSessionsHeading",{name:e.name}),headingTitle:e.root,notes:[_("sidebar.deleteProjectSessionsMessage"),...n>0?[_("sidebar.deleteProjectSessionsRunning",{count:n})]:[]],count:t.length,onConfirm:()=>lt(e),onCancel:()=>s9(e.key,!1)})})(a)),m=264}else if(rj?.kind==="archive-group"){let e,t=so.find(e=>e.project.key===rj.project.key)?.project??rj.project;f=t.name,lC=_("sidebar.archivedProjectActions",{name:t.name}),g=[{type:"item",id:"restore-all",label:_("sidebar.restoreAllArchived",{count:(e=lo({projectKey:t.key})).length}),icon:(0,r.jsx)(n6,{}),disabled:0===e.length,onSelect:()=>sF(lr(e))},{type:"separator",id:"separator-delete"},{type:"item",id:"delete-all",label:_("sidebar.deleteAllArchived",{count:e.length}),icon:(0,r.jsx)(ri,{}),danger:!0,disabled:0===e.length,onSelect:e=>{let{keepOpen:t}=e;t(),ll("all")}}],rj.askDelete&&(lN=lS({projectKey:t.key},t)),m=248}else if(rj?.kind==="archive"){let e,t,n;f=_("sidebar.archived"),lC=_("sidebar.archiveActions"),e=lo("all"),t=lo("old"),n=so.filter(e=>!e.expanded).length,g=[{type:"item",id:"collapse-all",label:_("sidebar.collapseAllGroups"),icon:(0,r.jsx)(re,{}),disabled:n===so.length,onSelect:()=>lc(!1)},{type:"item",id:"expand-all",label:_("sidebar.expandAllGroups"),icon:(0,r.jsx)(re,{className:"sidebar-icon-down"}),disabled:0===n,onSelect:()=>lc(!0)},{type:"separator",id:"separator-sessions"},{type:"item",id:"restore-all",label:_("sidebar.restoreAllArchived",{count:e.length}),icon:(0,r.jsx)(n6,{}),disabled:0===e.length,onSelect:()=>sF(lr(e))},{type:"item",id:"delete-old",label:_("sidebar.deleteOldArchived",{count:t.length}),icon:(0,r.jsx)(ri,{}),danger:!0,disabled:0===t.length,onSelect:e=>{let{keepOpen:t}=e;t(),ll("old")}},{type:"item",id:"delete-all",label:_("sidebar.deleteAllArchived",{count:e.length}),icon:(0,r.jsx)(ri,{}),danger:!0,disabled:0===e.length,onSelect:e=>{let{keepOpen:t}=e;t(),ll("all")}}],rj.askDelete&&(lN=lS(rj.askDelete,null)),m=280}let lE={layout:q?"mobile":"desktop",loading:X||!r0,error:eS,renamingRootId:n4,renamingProjectKey:rd,confirmDeleteRootId:rb,activeMenuRowKey:rj?.kind==="row"?rj.row.key:rj?.kind==="group"?`group:${rj.project.key}`:rj?.kind==="archive-group"?`archive:${rj.project.key}`:null,onSelectFamily:lg,onToggleGroup:lv,onShowMore:lb,onShowLess:ly,onTogglePinned:()=>{let e=!nP;nW(e),eG(e),e&&nz(e=>eT(e,ef))},onArchiveFamily:sO,onRestoreFamily:sD,onOpenRowMenu:s4,onRowContextMenu:s8,onRenameCommit:(e,t)=>{sH(e,t)},onRenameCancel:()=>rt(null),onRenameProjectCommit:sK,onRenameProjectCancel:()=>{rd&&sU(rd)},onDeleteConfirm:e=>{sq(e)},onDeleteCancel:()=>{rw(null),rb&&rY(()=>sy(rb))},onGroupNew:lp,onGroupMenu:s5,onPinEmptyGroup:e=>{sk({action:"pin-project",projectKey:e.key,root:e.root,pinned:!0}),rY(()=>sw(e.key))},onToggleArchiveGroup:lu,onArchiveGroupMenu:li,onOpenOtherProject:()=>{lw("project-list")},onOpenArchive:()=>sE(),onMoveGroup:sj},l$=eU??I??null,lI=l$&&tD>0?_("sidebar.changedFiles",{count:tD}):void 0,lM=(0,i.useRef)(null),lT=!l$||0===tD;(0,i.useLayoutEffect)(()=>{let e=lM.current;if(lT&&e&&sT.current===e){var t,n;let r;t=document,n=sb(),(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}):to(t,r)}},[lT,sb]);let lR=ny||"sessions"===nw,lA=!ny&&"files"===nw&&null!==l$,lL=(t=(ny?["below",_("sidebar.new")]:["tabs",_("sidebar.tabSessions"),_("sidebar.tabFiles"),_("sidebar.new"),l$&&tD>0?tD:"",nw]).join("\n"),h=(0,i.useCallback)(()=>{let e=im.current;if(e){for(let t of["0","1","2"])if(e.dataset.fit=t,e.scrollWidth<=e.clientWidth)return}},[im]),(0,i.useLayoutEffect)(()=>{let e=im.current;if(!e)return;h();let t=new ResizeObserver(h);return t.observe(e),()=>t.disconnect()},[im,h,t]),h),lz=sr.archivedCount,lP=ny?13:14,lW=(0,r.jsx)(r4,{onClick:()=>{l$&&R?.(l$)},disabled:!l$||!R,title:_("terminal.open"),children:(0,r.jsx)(rp,{size:lP})}),lO=(0,r.jsx)(r4,{onClick:()=>{iI().then(e=>{e&&ny&&sC(!1)})},disabled:!l$||iT,title:iT?_(tY?.reason==="remote"?"sidebar.openInExplorerRemoteOnly":"sidebar.openInExplorerUnsupported"):iM,children:(0,r.jsx)(rc,{size:lP})}),lF=(0,r.jsx)(r4,{onClick:()=>{ny&&nj&&sC(!1),nv.current?.openUploadPicker()},disabled:!l$||tR,title:_("sidebar.uploadFilesTitle"),children:(0,r.jsx)(rf,{size:lP})}),lD=(0,r.jsx)(r4,{onClick:()=>{z?z():tI(e=>e+1),tJ(!0),nx.current&&clearTimeout(nx.current),nx.current=setTimeout(()=>tJ(!1),2e3)},disabled:!l$,title:_("sidebar.refreshExplorer"),done:tZ,children:tZ?(0,r.jsx)(ra,{size:lP}):(0,r.jsx)(rm,{size:lP})}),lB=e=>(0,r.jsx)(r4,{onClick:()=>{let e=!tq;tV(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eV();if(t)try{t.setItem(eH,String(e))}catch{}}(e)},disabled:!l$,title:_("sidebar.showIgnoredFiles"),pressed:tq,className:e,children:(0,r.jsx)(rx,{size:lP})}),lH=(0,r.jsx)(r4,{ref:lM,onClick:()=>{if(ny&&nj){sC(!1),tK(!1);return}tK(e=>!e)},disabled:lT,title:_("sidebar.changedFiles",{count:tD}),pressed:!lT&&!tU,children:(0,r.jsx)(rg,{size:lP})});return(0,r.jsxs)("div",{ref:iC,className:`session-sidebar${ny?" is-files-below":""}${ny&&nj?" is-files-collapsed":""}${ny&&n1.moving?" is-files-folding":""}${rA?" has-toast":""}`,style:{"--sidebar-files-height":`${ij.width}px`},onFocus:e=>{sT.current=e.target},onBlur:e=>{(null!==e.relatedTarget||document.hasFocus())&&(e.currentTarget.contains(e.relatedTarget)||(sT.current=null))},children:[e9&&(0,r.jsx)(nd,{initialPath:tn,busy:tc,error:ta,onCancel:()=>{let e="new-session"===e9?rq.current:null;rU.current=null,rq.current=null,e7(!1),td(null),e&&rY(()=>e.isConnected?e:null)},onSelect:e=>void iH(e)}),(0,r.jsxs)("div",{ref:im,className:"sidebar-header",children:[ny&&(0,r.jsx)(nY,{onWidthChange:lL}),!ny&&(0,r.jsxs)("div",{className:"sidebar-tabs-list",role:"tablist","aria-label":_("sidebar.tabsLabel"),children:[(0,r.jsxs)("button",{ref:nC,type:"button",role:"tab",id:"session-sidebar-tab-sessions","aria-selected":"sessions"===nw,"aria-controls":"session-sidebar-panel-sessions",tabIndex:"sessions"===nw?0:-1,className:`sidebar-tab${"sessions"===nw?" is-selected":""}`,onClick:()=>sS("sessions"),onKeyDown:sA,children:[(0,r.jsx)(rv,{size:13,className:"sidebar-tab-icon"}),(0,r.jsx)("span",{className:"sidebar-tab-label",children:_("sidebar.tabSessions")})]}),(0,r.jsxs)("button",{ref:nN,type:"button",role:"tab",id:"session-sidebar-tab-files","aria-selected":"files"===nw,"aria-controls":"session-sidebar-panel-files",tabIndex:"files"===nw?0:-1,title:lI,className:`sidebar-tab${"files"===nw?" is-selected":""}`,onClick:()=>sS("files"),onKeyDown:sA,children:[(0,r.jsx)(rc,{size:13,className:"sidebar-tab-icon"}),(0,r.jsx)("span",{className:"sidebar-tab-label",children:_("sidebar.tabFiles")}),l$&&tD>0&&(0,r.jsx)("span",{className:"sidebar-tab-count","aria-hidden":"true",children:tD})]})]}),(0,r.jsx)("span",{className:"sidebar-header-spacer"}),(0,r.jsxs)("button",{type:"button",className:"sidebar-new-button",onClick:iQ,disabled:!eU,title:eU?_("sidebar.newSessionTitle",{path:eU}):_("sidebar.selectProject"),children:[(0,r.jsx)(n8,{size:12}),(0,r.jsx)("span",{className:"sidebar-new-label",children:_("sidebar.new")})]}),(0,r.jsx)("button",{ref:ix,type:"button",onClick:()=>{if(lA)return void tz(e=>!e);if(!lR){sS("sessions"),tW(!0);return}tW(e=>!e)},title:lA?_("sidebar.searchFiles"):_("sidebar.toggleSessionSearch"),"aria-label":lA?_("sidebar.searchFiles"):_("sidebar.toggleSessionSearch"),"aria-expanded":lA?tL:tP,"aria-controls":lA?"file-search-input":"session-search-input",className:`sidebar-search-toggle${(lA?tL:tP)?" is-active":""}`,children:(0,r.jsx)(rh,{size:16})})]}),(0,r.jsxs)("div",{ref:nE,id:"session-sidebar-panel-sessions",role:ny?"region":"tabpanel","aria-label":ny?_("sidebar.tabSessions"):void 0,"aria-labelledby":ny?void 0:"session-sidebar-tab-sessions",hidden:!ny&&"sessions"!==nw,className:"sidebar-panel sidebar-sessions-panel",onScrollCapture:sN,children:[tP&&(0,r.jsx)("div",{className:"sidebar-search",children:(0,r.jsx)("input",{id:"session-search-input",type:"search",autoFocus:!0,value:tO,maxLength:200,"aria-label":_("sidebar.searchSessions"),placeholder:_("sidebar.searchSessions"),onChange:e=>tF(e.target.value),onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.stopPropagation(),tF(""))},className:"sidebar-search-input"})}),(0,r.jsx)(rQ,{open:tP,query:tO,selectedSessionId:x,onSelectSession:iY,onSelectSideChat:b,sessions:Z,archivedSessionIds:i4.ids,projectNames:sp,children:(0,r.jsxs)("div",{className:"sidebar-sessions-views",children:[(0,r.jsx)("div",{className:"sidebar-sessions-view",hidden:n2.mainHidden,inert:n2.mainInert,children:(0,r.jsx)(rk,{...lE,rows:sr.rows,emptyLabel:_("sidebar.noSessions"),reveal:rC,onRevealHandled:r$})}),n2.archiveMounted&&(0,r.jsxs)("div",{className:`sidebar-sessions-view sidebar-archive-view${n2.archiveClass?` ${n2.archiveClass}`:""}`,inert:n2.archiveInert,onAnimationEnd:e=>{e.target===e.currentTarget&&nG()},children:[(0,r.jsxs)("div",{className:"sidebar-archive-bar",children:[(0,r.jsxs)("button",{ref:s$,type:"button",className:"sidebar-archive-back",title:_("sidebar.backToSessions"),"aria-label":`${_("sidebar.backToSessions")}: ${_("sidebar.archivedCount",{count:lz})}`,onClick:()=>n0(!1),children:[(0,r.jsx)(re,{size:13,className:"sidebar-icon-back"}),(0,r.jsx)("span",{children:_("sidebar.archived")}),(0,r.jsxs)("span",{className:"sidebar-archive-count",children:["\xb7 ",lz]})]}),(0,r.jsx)("button",{type:"button",className:`sidebar-archive-menu-button${rj?.kind==="archive"?" is-active":""}`,title:_("sidebar.archiveActions"),"aria-label":_("sidebar.archiveActions"),"aria-haspopup":"menu","aria-expanded":rj?.kind==="archive",disabled:0===so.length,onClick:e=>ls(e.currentTarget),children:(0,r.jsx)(n3,{size:13})})]}),(0,r.jsx)(rk,{...lE,rows:sl,emptyLabel:_("sidebar.noArchived"),reveal:rI,onRevealHandled:rT})]})]})})]}),ny&&n1.open&&(0,r.jsx)("div",{...ij.separatorProps,"aria-controls":"session-sidebar-panel-files",className:`panel-resize-handle sidebar-files-resize-handle${ij.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar-files",title:`${_("sidebar.resizeFiles")}: ${_("sidebar.resizeFilesHint")}`}),(0,r.jsxs)("div",{ref:n$,id:"session-sidebar-panel-files",role:ny?"region":"tabpanel","aria-label":ny?_("sidebar.tabFiles"):void 0,"aria-labelledby":ny?void 0:"session-sidebar-tab-files",hidden:!ny&&"files"!==nw,className:"sidebar-panel sidebar-files-panel",onScrollCapture:sN,onTransitionEnd:e=>{e.target===e.currentTarget&&"height"===e.propertyName&&nq()},children:[ny&&(0,r.jsxs)("div",{className:"sidebar-files-section",children:[(0,r.jsxs)("button",{type:"button",className:"sidebar-files-section-toggle","aria-expanded":!nj,"aria-controls":"session-sidebar-files-body",title:lI,onClick:()=>sC(!nj),children:[(0,r.jsx)(re,{size:12,strokeWidth:3,className:`session-tree-chevron${nj?"":" is-open"}`}),(0,r.jsx)("span",{className:"sidebar-files-section-label",children:_("sidebar.tabFiles")}),lI&&(0,r.jsxs)("span",{className:"sidebar-files-section-count","aria-hidden":"true",children:["\xb7 ",tD]})]}),(0,r.jsxs)("div",{className:"sidebar-files-keys",role:"group","aria-label":_("sidebar.fileActions"),children:[lW,lO,lF,lD,lB(),lH,(0,r.jsx)(r4,{onClick:()=>{if(nj){tz(!0),lw("file-search");return}tz(e=>!e)},disabled:!l$,title:_("sidebar.searchFiles"),expanded:tL,controls:"file-search-input",children:(0,r.jsx)(rh,{size:13})})]})]}),(0,r.jsxs)("div",{id:"session-sidebar-files-body",className:"sidebar-files-body",hidden:ny&&n1.bodyHidden,inert:ny&&n1.bodyInert,children:[(0,r.jsxs)("div",{className:"sidebar-files-head",children:[(0,r.jsx)(rG,{handleRef:tf,layout:ny?"row":"stacked",context:sf??{project:null,worktrees:null,currentWorktreePath:null,projects:sh},mobile:q,label:_("sidebar.projectAndWorktree"),placeholder:j&&!iA.current?"":_("sidebar.selectProject"),homeDir:e4,projectActivity:i8,worktreeHint:i9,newWorktreeTitle:_("sidebar.createWorktreeTitle"),onPick:iJ,onUseDefaultDirectory:()=>{iU()},onOpenFolder:i_,onRefreshWorktrees:iZ,onCreateWorktree:iq,onRemoveWorktree:iV}),!ny&&l$&&(0,r.jsxs)("div",{className:"sidebar-files-actions",role:"group","aria-label":_("sidebar.fileActions"),children:[R&&lW,lO,lF,lD,lB("sidebar-files-views-start"),lH]})]}),l$&&iR&&(0,r.jsxs)("div",{role:"alert",className:"sidebar-files-error",children:[(0,r.jsx)("span",{className:"sidebar-files-error-text",children:iR}),(0,r.jsx)(nc,{onClick:()=>t0(null),title:_("files.dismissError")})]}),(0,r.jsx)("div",{ref:ig,className:"sidebar-files-scroll scrollbar-subtle",children:l$&&(0,r.jsx)(nV,{ref:nv,cwd:l$,onOpenFile:T??(()=>{}),refreshKey:tN,onAtMention:P,onAtMentions:W,onUploadBusyChange:tA,changesCollapsed:tU,onChangesCountChange:tB,fileSearchOpen:tL,onFileSearchOpenChange:tz,showHidden:tq})})]})]}),(0,r.jsx)(rK,{open:null!==rj,anchor:rj?.anchor??null,sheet:q,ariaLabel:lC,title:f,items:g,cancelLabel:_("sidebar.cancel"),focusCancel:null!==lN,onClose:lh,returnFocusTo:rj?.opener??null,width:m,children:lN}),(0,r.jsx)(r1,{toast:rA,onDismiss:()=>rL(null),dismissLabel:_("sidebar.dismiss")})]})}var ir=n(5772);let ii=/\x1B(?:\][^\x07\x1B]*(?:\x07|\x1B\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g,is=/^\x1B(?:\][^\x07\x1B]*(?:\x07|\x1B\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/,il=/\x1B_pi:[^\x07\x1B\n]*(?:\x07|\x1B\\)/g;function io(e){return e.replace(il,"").replace(ii,"")}function ia(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(is);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 id(e,t){let n=ia(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function ic(e){return ia(e)[0]?.char}let iu=/[▀-▟]/,ip=/https?:\/\/(?:\[[0-9A-Fa-f:.]+\])?[^\s<>"'`\]}。,、;:!?)」』】]*/gi,ih=/^[.,;:!?]$/,im={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:""},ig={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"},ix="\x1b[200~",iv="\x1b[201~";function ib(e){return"custom"===e.role&&!e.display}function iy(e){return"user"===e.role||"custom"===e.role&&!ib(e)&&("compaction"===e.customType||"pi-web:subagent-notification"===e.customType||"subagent-notification"===e.customType)}function iw(e){return"user"===e.role||"assistant"===e.role||"toolResult"===e.role}function ik(e,t){return"assistant"===e.role||t&&!ib(e)}function ij(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===e.thinking.trim()}function iS(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return(e.content??[]).filter(e=>!ij(e,t))}function iC(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function iN(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return!t.isStreaming&&"aborted"===e.stopReason}function iE(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return!t.isStreaming&&"length"===e.stopReason}function i$(e){return(e.content??[]).some(e=>"text"===e.type?e.text.trim().length>0:"image"===e.type||"toolCall"===e.type)}function iI(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=iS(e,t),r=n.findLastIndex(e=>"text"!==e.type&&"image"!==e.type);return -1===r?{answerBlocks:n,processBlocks:[]}:{answerBlocks:n.slice(r+1),processBlocks:n.slice(0,r+1)}}function iM(e){return!e.defaultPrevented&&0===e.button&&!e.shiftKey&&!e.altKey}function iT(e){try{return decodeURIComponent(e)}catch{return e}}function iR(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function iA(e){return!!e&&(/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\"))}let iL=/^\/(?:mnt\/|cygdrive\/)?([a-zA-Z])(?:\/(.*))?$/;function iz(e){if(!e.startsWith("/")||e.startsWith("//"))return e;let t=e.match(iL);if(!t)return e;let[,n,r]=t;return`${n.toUpperCase()}:/${r??""}`}function iP(e){let t=iR(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),i=t.startsWith("/")&&!n&&!r,s=n?1:2*!!r,l=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){l.length>s&&".."!==l[l.length-1]?l.pop():i||n||r||l.push(e);continue}l.push(e)}let o=l.join("/");return n?1===l.length?`${o}/`:o:r?`//${o}`:i?`/${o}`:o}function iW(e,t){let n,r,i,s,l,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t;if(!e)return null;let a=e.split("#",1)[0].split("?",1)[0].trim();if(!a)return null;let d=null,c=null,u=iT(a),p=u.startsWith("\\\\"),h=iR(u),f=h.toLowerCase();if(f.startsWith("/api/")||f.startsWith("/_next/")||!p&&h.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(h)&&!f.startsWith("file:")&&!/^[a-zA-Z]:\//.test(h))return null;if(f.startsWith("file:")?c=(d=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=iT(t.pathname);if(t.hostname)return`//${t.hostname}${n.startsWith("/")?n:`/${n}`}`;if(/^\/[a-zA-Z]:\//.test(n))return n.slice(1);return n}catch{return null}}(a))?"absolute":null:/^[a-zA-Z]:\//.test(h)?(d=h,c="absolute"):h.startsWith("/")?(d=iA(t)?iz(h):h,c="absolute"):t&&!(h.startsWith("#")||h.startsWith("?"))&&(h.startsWith("./")||h.startsWith("../")||h.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(h))&&(d=`${iR(t).replace(/\/+$/,"")}/${h}`,c="relative"),!d)return null;let m=iP(d).replace(/:\d+(?:(?::|-)\d+)?$/,"");return"relative"===c&&o&&(n=iP(m).replace(/\/+$/,""),r=iP(o).replace(/\/+$/,""),s=(i=/^[a-zA-Z]:\//.test(n)||/^[a-zA-Z]:\//.test(r))?n.toLowerCase():n,!(s===(l=i?r.toLowerCase():r)||s.startsWith(`${l}/`)))?null:m}let iO=/^page=(\d+)$/i;function iF(e){if(!e)return null;let t=e.indexOf("#");if(-1===t)return null;let n=e.slice(t+1).trim().match(iO);if(!n)return null;let r=Number.parseInt(n[1],10);return Number.isInteger(r)&&r>0?r:null}function iD(e){let t=e.toLowerCase();return"write"===t||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")}function iB(e){let t=e.toLowerCase();return"edit"===t||t.startsWith("edit_")||t.endsWith(".edit")||t.endsWith("_edit")||t.includes("str_replace")||t.includes("replace_editor")}function iH(e){let t=e.toLowerCase();return"apply_patch"===t||t.startsWith("apply_patch_")||t.endsWith(".apply_patch")||t.endsWith("_apply_patch")}function i_(e,t){if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.input;if("string"==typeof t&&t.length>0)return t}return"string"==typeof t?t:""}function iU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function iK(e){if(!iU(e)||!iU(e.result))return!1;let t=e.result.failures;return Array.isArray(t)&&t.length>0}function iq(){let e=[],t=[],n=[],r=()=>({lineNo:null,text:"",type:"empty"}),i=()=>{let i=Math.max(t.length,n.length);for(let s=0;s<i;s++)e.push({type:"line",left:t[s]??r(),right:n[s]??r()});t=[],n=[]};return{rows:e,context(t,n){i(),e.push({type:"line",left:{lineNo:n,text:t,type:"context"},right:{lineNo:n,text:t,type:"context"}})},removed(e,n){t.push({lineNo:n,text:e,type:"removed"})},added(e,t){n.push({lineNo:t,text:e,type:"added"})},gap(){i(),e.length>0&&"gap"!==e[e.length-1].type&&e.push({type:"gap",count:null})},finish(){i(),e.length>0&&"gap"===e[e.length-1].type&&e.pop()}}}function iV(e){if(!e.includes("*** Begin Patch")&&!/\*\*\* (?:Add|Delete|Update) File: /.test(e))return null;let t=[],n=null,r=null,i=null;for(let s of e.split(/\r?\n/)){let e=s.match(/^\*\*\* (Add|Delete|Update) File: (.+)$/);if(e){let s=e[1]?.toLowerCase()??"update",l=(e[2]??"").trim();n?.finish(),i=s,r={oldPath:"add"===s?void 0:l,newPath:"delete"===s?void 0:l,rows:(n=iq()).rows},t.push(r);continue}if(/^\*\*\* Move to: /.test(s)){let e=s.replace(/^\*\*\* Move to: /,"").trim();r&&"update"===i&&(r.newPath=e);continue}if(!n||!r)continue;let l=n;if(!s.startsWith("*** ")){if("update"===i&&s.startsWith("@@")){l.gap();continue}if("update"===i){let e=s[0],t=s.slice(1);"+"===e?l.added(t,null):"-"===e?l.removed(t,null):" "===e?l.context(t,null):""!==s&&l.context(s,null)}else if("add"===i){if(""===s)continue;n.added(s.startsWith("+")?s.slice(1):s,null)}else if("delete"===i){if(""===s)continue;n.removed(s.startsWith("-")?s.slice(1):s,null)}}}n?.finish();let s=t.filter(e=>e.rows.length>0);return s.length>0?s:null}function iZ(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t=e.files;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(!e||"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.filePath||"string"!=typeof e.diff)continue;let t=iq();for(let n of e.diff.split(/\r?\n/)){let e=n.match(/^([+\- ])\s*(\d+) (.*)$/);if(!e)continue;let[,r,i,s]=e,l=Number(i);"+"===r?t.added(s,l):"-"===r?t.removed(s,l):t.context(s,l)}t.finish();let r="add"===e.operation,i="delete"===e.operation;n.push({oldPath:r?void 0:e.filePath,newPath:i?void 0:e.movePath??e.filePath,rows:t.rows})}let r=n.filter(e=>e.rows.length>0);return r.length>0?r:null}function iJ(e){return e?e.map(e=>e.newPath).filter(e=>"string"==typeof e&&e.length>0):[]}function iY(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={...e,content:t};return n.omitUsage&&(r.usage=void 0),n.omitStop&&(r.stopReason=void 0,r.errorMessage=void 0),r}function iG(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0}function iX(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return n<60?`${n}m ${r}s`:`${Math.floor(n/60)}h ${n%60}m ${r}s`}var iQ=n(32316);function i0(e){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);let t=document.activeElement,n=null;try{return(n=document.createElement("textarea")).value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy")?Promise.resolve():Promise.reject(Error("Copy was refused"))}catch(e){return Promise.reject(e)}finally{n?.remove(),t?.isConnected&&t instanceof HTMLElement&&t.focus({preventScroll:!0})}}let i1={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},i2={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm"},i4={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",mov:"video/quicktime",ogv:"video/ogg"};function i8(e){let t=(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase(),n=t.lastIndexOf(".");return n>0?t.slice(n+1):""}function i3(e){let t;return null!==(Object.hasOwn(i2,t=i8(e))?i2[t]:null)}function i5(e){let t;return null!==(Object.hasOwn(i4,t=i8(e))?i4[t]:null)}var i6=n(88374),i9=n(5924),i7=n(94764),se=n(63835),st=n(54152),sn=n(31678),sr=n(6796),si=n(98164);let ss=["obsidian","logseq","notion","vscode","vscode-insiders","cursor","zed","jetbrains","zoommtg","zoomus","msteams","slack"],sl=RegExp(`^(?:${ss.join("|")}):`,"i"),so=i7.j.clobberPrefix??"user-content-",sa={...i7.j,clobberPrefix:so,attributes:{...i7.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},protocols:{...i7.j.protocols,href:[...i7.j.protocols?.href??[],"file",...ss]},strip:[...i7.j.strip||[],"iframe","object","style","form"]};function sd(e){return sl.test(e)?e:(0,iQ.Lv)(e)}function sc(e){return/^file:/i.test(e)?e:sd(e)}function su(e){return!!(e&&/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(e))}function sp(e){if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("href");if(!t?.startsWith("#"))return;e.preventDefault();let n=t.slice(1);if(!n)return;try{n=decodeURIComponent(n)}catch{}let r=CSS.escape(n);e.currentTarget.closest(".markdown-body")?.querySelector(`[id="${r}"], a[name="${r}"]`)?.scrollIntoView({block:"start"})}function sh(e,t,n,r,i){let s="",l=0;for(let o=e.indexOf(t);-1!==o;o=e.indexOf(t,o+1)){if(o>0&&n.includes(e[o-1]))continue;r.lastIndex=o;let t=r.exec(e);t&&(s+=e.slice(l,o)+i(t),o=(l=r.lastIndex)-1)}return s+e.slice(l)}let sf=/`((?:[^`\n]|\\`)*?[^\\`\n])`(?!`)/y;function sm(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,s=0,l=null,o=new Map;for(let e=0;e<n.length;e++){var a,d;let t=n[e];if(l){r.push(t),RegExp(`</${l}\\s*>`,"i").test(t)&&(l=null);continue}let c=t.match(/^ {0,3}(`{3,}|~{3,})/);if(c){let e=c[1][0],n=c[1].length;i?e===i.marker&&n>=i.size&&/^[ \t]*$/.test(t.slice(c[0].length))&&(i=null):i={marker:e,size:n},s=0,r.push(t);continue}if(i){r.push(t);continue}let u=t.match(/<(code|pre|script|style)\b/i);if(u){let e=u[1].toLowerCase(),n=t.slice((u.index??0)+u[0].length);RegExp(`</${e}\\s*>`,"i").test(n)||(l=e),s=0,r.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){s=0,r.push(t);continue}if(s||(t=sh(t,"`","\\`",sf,e=>{let[t,n]=e,r=n.replace(/\\`/g,"`");if(r===n)return t;let i="`".repeat(Math.max(...r.match(/`+/g)?.map(e=>e.length)??[0])+1);return`${i}${r}${i}`})),s||t.includes("`")){s=function(e,t){let n=t;for(let t=0;t<e.length;){if("`"!==e[t]){t++;continue}let r=t+1;for(;"`"===e[r];)r++;let i=r-t;0===n?n=i:i===n&&(n=0),t=r}return n}(t,s),r.push(t);continue}let p=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(p){let e=p[2].trim();if(e){r.push(`${p[1]}$$`,`${p[1]}${e}`,`${p[1]}$$`);continue}}let h=t.match(/^([ ]{0,3})\[[ \t]*(.+?)[ \t]*\][ \t]*$/);if(h){let e=h[2].trim();if(a=e,/\\[A-Za-z]+/.test(a)&&!/\b(?:https?|file|mailto):|\b[A-Za-z]:\\|^\\\\/i.test(a)){r.push(`${h[1]}$$`,`${h[1]}${e}`,`${h[1]}$$`);continue}}let f=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(f){let t=function(e,t){for(let n=t;n<e.length;n++){let t=e[n];if(/^ {0,3}\\\][ \t]*$/.test(t))return n;if(/^ {0,3}(`{3,}|~{3,})/.test(t)||/^ {0,3}\\\[[ \t]*$/.test(t)||/<(code|pre|script|style)\b/i.test(t))break}return -1}(n,e+1);if(-1!==t){r.push(`${f[1]}$$`,...n.slice(e+1,t).map(e=>sx(e,f[1])),`${f[1]}$$`),e=t;continue}}let m=t.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \t]*$/);if(m){let e=m[2].trim();if(e){r.push(`${m[1]}$$`,`${m[1]}${e}`,`${m[1]}$$`);continue}}let g=t.match(/^([ \t]{0,3})\$\$(.+)$/);if(g){let t=g[1],i=g[2].trimEnd();if(i&&!i.includes("$$")){let s=sg(n,e+1,t,o);if(s){r.push(`${t}$$`,`${t}${i}`);for(let i=e+1;i<s.index;i++)r.push(sx(n[i],t));s.content&&r.push(`${t}${s.content}`),r.push(`${t}$$`),e=s.index;continue}}}let x=t.match(/^([ \t]{0,3})\$\$\s*$/);if(x){let t=x[1],i=sg(n,e+1,t,o);if(i&&(i.glued||""!==t)){r.push(`${t}$$`);for(let s=e+1;s<i.index;s++)r.push(sx(n[s],t));i.content&&r.push(`${t}${i.content}`),r.push(`${t}$$`),e=i.index;continue}}r.push((d=t,/^\s{0,3}\[[^\]]+\]:/.test(d)||/]\s*\(/.test(d)||/<(?:!--|\/?[A-Za-z][^>]*>)/.test(d)||/\b(?:https?|file|mailto):/i.test(d)||/\b[A-Za-z]:\\/.test(d)?d:sh(d,"\\(","\\",sv,e=>{let[t,n]=e;return n.trim()?`$${n}$`:t})))}return r.join(t)}function sg(e,t,n,r){let i=r.get(n);if(void 0!==i&&t<i)return null;for(let i=t;i<e.length;i++){var s,l,o,a;let t=e[i];if(s=t,""===(l=n)?/^ {0,3}\$\$\s*$/.test(s):s.startsWith(l)&&/^\$\$\s*$/.test(s.slice(l.length)))return{index:i,content:"",glued:!1};if(o=t,/^ {0,3}(`{3,}|~{3,})/.test(o)||/^[ \t]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/.test(o)||/^ {0,3}#{1,6}(?:[ \t]+|$)/.test(o)||/^ {0,3}>/.test(o)||/<(code|pre|script|style)\b/i.test(o)||(a=t,/^ {0,3}\$\$(?:\S|[ \t]+\S)/.test(a)))return r.set(n,i),null;let d=function(e,t){if(!e.startsWith(t))return null;let n=e.slice(t.length).match(/^(.+?)\$\$\s*$/);if(!n)return null;let r=n[1].trimEnd();return r&&!r.includes("$$")?r:null}(t,n);if(null!==d)return{index:i,content:d,glued:!0}}return r.set(n,e.length),null}function sx(e,t){if(!t||!e||e.startsWith(" "))return e;let n=e.match(/^ */)?.[0].length??0;return n>=t.length?e:`${t.slice(n)}${e}`}let sv=/\\\(([^`\r\n$]*?[^`\r\n$\\])\\\)/y,sb={singleTilde:!1},sy=/[\u3001\u3002\u3008-\u3011\u3014-\u301B\uFF01\uFF08\uFF09\uFF0C\uFF1A\uFF1B\uFF1F\u2018\u2019\u201C\u201D\u2013\u2014\u2026\u00B7\uFF5E\u301C]/;function sw(){return(e,t)=>{var n;let r;n="string"==typeof t.value?t.value:"",(r=e=>{let t=e.children;for(let e=0;e<t.length;e++){let i=t[e];"link"===i.type&&function(e,t,n,r){if(null!=n.title||1!==n.children.length)return;let i=n.children[0];if("text"!==i.type)return;let s=n.position?.start,l=n.position?.end;if(s?.offset==null||l?.offset==null||r.slice(s.offset,l.offset)!==i.value)return;let o=i.value,a=o.search(sy);if(a<=0||!n.url.endsWith(o))return;let d=o.slice(0,a),c={line:s.line,column:s.column+a,offset:s.offset+a};n.url=n.url.slice(0,n.url.length-o.length)+d,i.value=d,n.position={start:s,end:c},e.splice(t+1,0,{type:"text",value:o.slice(a),position:{start:c,end:l}})}(t,e,i,n);let s=t[e];"children"in s&&Array.isArray(s.children)&&r(s)}})(e)}}let sk=function(){si.A.call(this);let e=this.data(),t=e.micromarkExtensions?.at(-1),n=t?.text?.[36];for(let e of Array.isArray(n)?n:n?[n]:[]){if("mathText"!==e.name)continue;let t=e.tokenize;e.tokenize=function(e,n,r){let i=this.now();return t.call(this,e,e=>{let t=this.sliceSerialize({start:i,end:this.now()});if(t.startsWith("$")&&!t.startsWith("$$")){let n=t.slice(1,-1),i=/^\s*[+-]?(?:\d|\.\d)/.test(n),s=null!==e&&e>=48&&e<=57,l=/^\s/.test(n)!==/\s$/.test(n);if(i&&(s||l))return r(e)}return n(e)},r)}}};function sj(){return e=>{let t=e=>{("link"===e.type||"definition"===e.type)&&/^\/?[A-Za-z]:\//.test(e.url)&&(e.url=`file:///${e.url.replace(/^\//,"")}`),"children"in e&&e.children.forEach(t)};t(e)}}let sS=[[st.A,["yaml"]],[sn.A,sb],sr.A,sw,sk,sj],sC=/[ \t]*(?:\r\n|\r|\n)[ \t]*/,sN=new Set(["root","blockquote","listItem","footnoteDefinition"]);function sE(){return{type:"lineBreak",data:{hName:"br"}}}function s$(e){if(!e.children)return;let t=sN.has(e.type);e.children=e.children.map(e=>{if("html"!==e.type)return s$(e),e;let n={type:"text",value:e.value??""};return t?{type:"paragraph",children:[n]}:n})}function sI(e){e.children&&(e.children=e.children.flatMap(e=>"break"===e.type?[sE()]:"text"===e.type&&e.value?e.value.split(sC).flatMap((e,t)=>[...t>0?[sE()]:[],...e?[{type:"text",value:e}]:[]]):(sI(e),[e])))}let sM=[...sS??[],function(){return e=>{s$(e),sI(e)}}],sT=[...sS??[],function(){return(e,t)=>{s$(e),sI(e);let n=String(t.value).split(/\r\n|\r|\n/);for(let t of e.children??[])"paragraph"===t.type&&function(e,t){if(!e.position)return;let n=e.position.start.line-1,r=()=>{let e=/^[ \t]*/.exec(t[n]??"")?.[0];return e?[{type:"text",value:e}]:[]},i=r(),s=e=>{e.children=e.children?.flatMap(e=>"lineBreak"===e.type?(n+=1,[e,...r()]):(e.children?s(e):e.position&&(n+=e.position.end.line-e.position.start.line),[e]))};s(e),e.children=[...i,...e.children??[]]}(t,n)}}],sR=[[st.A,["yaml"]],[sn.A,sb],sr.A,sw,sk,sj];function sA(){return e=>{let t=e=>{if(!e||"object"!=typeof e)return;let n=e.properties?.href;for(let r of("element"===e.type&&"string"==typeof n&&n.startsWith("#")&&n.length>1&&(e.properties.href=`#${so}${n.slice(1)}`),e.children??[]))t(r)};t(e)}}function sL(e){return"text"===e.type?e.value:"element"===e.type?e.children.map(sL).join(""):""}function sz(){return e=>{let t=e=>{e.children=e.children.map(e=>{if("element"!==e.type)return e;let n="pre"===e.tagName&&1===e.children.length?e.children[0]:null,r=n?.type==="element"&&"code"===n.tagName?n.properties.className:null;return Array.isArray(r)&&r.includes("language-math")?{type:"element",tagName:"div",properties:{className:["markdown-math-display"],dataMathSource:sL(e).replace(/\n$/,"")},children:[e]}:(t(e),e)})};t(e)}}let sP=[i9.A,[se.A,sa],sA,sz,[i6.A,{throwOnError:!1,strict:!1}]],sW=[i9.A,[se.A,sa],function(){return e=>{let t=new Map,n=e=>e.children.forEach(e=>{if("element"===e.type){if(/^h[1-6]$/.test(e.tagName)){let n=sL(e).toLowerCase().replace(/[^\p{L}\p{M}\p{N}_\- ]/gu,"").replace(/ /g,"-"),r=n;for(;t.has(r);)t.set(n,t.get(n)+1),r=`${n}-${t.get(n)}`;t.set(r,0),e.properties.dataHeadingAnchor=r}n(e)}});n(e)}},sz,[i6.A,{throwOnError:!1,strict:!1}]],sO=[i9.A,[se.A,sa],sA,[i6.A,{throwOnError:!1,strict:!1}]],sF=/^ {0,3}(`{3,}|~{3,})/,sD=/^(?:[*+-]|\d{1,9}[.)])(?:[ \t]|$)/,sB=/<[A-Za-z!/?]/,sH=/`[^`]*`/g,s_=/^ {0,3}\[[^\]]+\]:/,sU=/^(`{3,}|~{3,})[ \t]*([^`\s]*)[^`]*$/;function sK(e){return"plantuml"===e||"puml"===e}let sq="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";async function sV(e){if("u"<typeof CompressionStream)return null;try{let t=new Blob([e]).stream().pipeThrough(new CompressionStream("deflate-raw"));return new Uint8Array(await new Response(t).arrayBuffer())}catch{return null}}async function sZ(e){let t=new TextEncoder().encode(e),n=await sV(t);return n?function(e){let t="";for(let n=0;n<e.length;n+=3){let r=e[n],i=e[n+1]??0,s=e[n+2]??0;t+=sq[r>>2]+sq[(3&r)<<4|i>>4]+sq[(15&i)<<2|s>>6]+sq[63&s]}return t}(n):function(e){let t="~h";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}(t)}async function sJ(e){let t="https://www.plantuml.com/plantuml/svg/"+await sZ(e);return t.length<=6e3?t:null}function sY(e){let{src:t,alt:n="",children:s,className:l,style:o}=e,{t:a}=(0,t_.s)(),d=a("chat.previewImage"),c=n.trim()?`${d}: ${n}`:d,[u,p]=(0,i.useState)(!1),h=(0,i.useRef)(null),f=(0,i.useRef)(null),m=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!u)return;let e=f.current;if(!e)return;let t=h.current,n=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),m.current?.focus({preventScroll:!0}),()=>{document.body.style.overflow=n,e.open&&e.close(),t?.isConnected&&t.focus({preventScroll:!0})}},[u]);let g=()=>{f.current?.open&&f.current.close(),p(!1)};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{ref:h,type:"button",className:l,style:{display:"block",padding:0,border:"none",background:"none",color:"inherit",cursor:"zoom-in",...o},onClick:()=>p(!0),"aria-label":c,"aria-haspopup":"dialog","aria-expanded":u,title:d,children:s}),u&&(0,r.jsxs)("dialog",{ref:f,className:"image-preview-dialog","aria-label":a("chat.previewImage"),onCancel:e=>{e.preventDefault(),e.stopPropagation(),g()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),g())},onClick:e=>{e.target===e.currentTarget&&g()},children:[(0,r.jsx)("img",{className:"image-preview-image",src:t,alt:n}),(0,r.jsx)("button",{ref:m,type:"button",className:"image-preview-close",onClick:g,"aria-label":a("chat.close"),title:a("chat.close"),children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]})}var sG=n(50640),sX=n(55961),sQ=n(7644);let s0=[{id:"auto",label:"settings.themeSystem",scheme:null},{id:"light",label:"settings.themeLight",scheme:"light"},{id:"mist",label:"settings.themeMist",scheme:"light"},{id:"lilac",label:"settings.themeLilac",scheme:"light"},{id:"sand",label:"settings.themeSand",scheme:"light"},{id:"rose",label:"settings.themeRose",scheme:"light"},{id:"dark",label:"settings.themeDark",scheme:"dark"},{id:"pine",label:"settings.themePine",scheme:"dark"},{id:"dusk",label:"settings.themeDusk",scheme:"dark"},{id:"ember",label:"settings.themeEmber",scheme:"dark"},{id:"slate",label:"settings.themeSlate",scheme:"dark"},{id:"contrast-light",label:"settings.themeContrastLight",scheme:"light"},{id:"contrast-dark",label:"settings.themeContrastDark",scheme:"dark"},{id:"zenburn",label:"settings.themeZenburn",scheme:"dark"}];s0.flatMap(e=>"light"===e.scheme?[e.id]:[]);let s1=s0.flatMap(e=>"dark"===e.scheme?[e.id]:[]);function s2(e){return s1.includes(e)}let s4="pi-theme",s8={preference:"auto",theme:"light"},s3=new Set,s5=null,s6=!1;function s9(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function s7(e){return"auto"===e?s9():e}function le(e){"u">typeof document&&(document.documentElement.dataset.theme=e,document.documentElement.classList.toggle("dark",s2(e)))}function lt(){if(s5)return s5;let e=function(){try{let e=localStorage.getItem(s4);if(s0.some(t=>t.id===e))return e}catch{}return"auto"}(),t=s7(e);return le(t),s5={preference:e,theme:t}}function ln(e,t,n){if(le(t),n)try{localStorage.setItem(s4,e)}catch{}s5={preference:e,theme:t},s3.forEach(e=>e())}function lr(){let e=lt();if("auto"!==e.preference)return;let t=s9();t!==e.theme&&ln("auto",t,!1)}function li(e){return s3.add(e),lt(),s6||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",lr),window.addEventListener("focus",lr),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&lr()}),s6=!0),lr(),()=>{s3.delete(e)}}function ls(){return lt()}function ll(){return s8}function lo(){let e=(0,i.useSyncExternalStore)(li,ls,ll),t=(0,i.useCallback)((e,t)=>{if(lt().preference===e)return;let n=s7(e),r=()=>{ln(e,n,!0)},i=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||i)return void r();let s=t?.x??window.innerWidth/2,l=t?.y??window.innerHeight/2,o=Math.hypot(Math.max(s,window.innerWidth-s),Math.max(l,window.innerHeight-l));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${s}px ${l}px)`,`circle(${o}px at ${s}px ${l}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]);return{theme:e.theme,preference:e.preference,setThemePreference:t,isDark:s2(e.theme)}}let la=!1,ld=null;function lc(){return la}function lu(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0],[t,r]=(0,i.useState)(lc);return(0,i.useEffect)(()=>{if(t||!e)return;let i=!0;return(ld??=n.e(1326).then(n.bind(n,61326)).then(()=>{la=!0},e=>{throw ld=null,e})).then(()=>{i&&r(!0)},()=>{}),()=>{i=!1}},[e,t]),t}let lp=2e3,lh=!1,lf=[],lm=!1;function lg(){lm=!1,lf.pop()?.(),lf.length>0&&lx()}function lx(){!lm&&(lm=!0,"function"==typeof window.requestIdleCallback?window.requestIdleCallback(lg,{timeout:500}):setTimeout(lg,50))}function lv(e,t){let n=URL.createObjectURL(new Blob([e],{type:"image/svg+xml;charset=utf-8"})),r=document.createElement("a");r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),0)}function lb(e){let{code:t,isStreaming:s,defaultPreview:l=!1}=e,{isDark:o}=lo(),{t:a}=(0,t_.s)(),[d,c]=(0,i.useState)(l),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!1),m=(0,i.useRef)(null),g=`${o?"dark":"light"}
6
+ ${t}`,x=d&&!s;(0,i.useEffect)(()=>{if(!x)return;let e=!1;return p({key:g,status:"loading"}),(async()=>{let{default:r}=await Promise.all([n.e(866),n.e(8367),n.e(3308)]).then(n.bind(n,43328));if(r.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:o?"dark":"default"}),!await r.parse(t,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let i="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,s=await r.render(i,t);e||p({key:g,status:"ready",svg:s.svg})})().catch(()=>{e||p({key:g,status:"error"})}),()=>{e=!0}},[t,g,o,x]);let v=(0,i.useMemo)(()=>(0,r.jsx)(ly,{isStreaming:s,previewVisible:x,onToggle:()=>c(e=>!e),title:x?a("i18n.showMermaidSource"):a("i18n.previewMermaid")}),[s,x,a]);if(!x)return(0,r.jsx)(l$,{code:t,lang:"mermaid",headerAction:v,isStreaming:s});let b=u?.key===g&&"error"===u.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:a("i18n.invalidMermaid")}):u?.key!==g||"ready"!==u.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":a("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!h&&(0,r.jsx)("button",{ref:m,type:"button",className:"mermaid-block mermaid-preview-button",title:a("i18n.openMermaidViewer"),"aria-label":a("i18n.openMermaidViewer"),onClick:()=>f(!0),dangerouslySetInnerHTML:{__html:u.svg}}),h&&(0,r.jsx)(lj,{title:a("i18n.mermaidDiagram"),label:a("i18n.mermaidViewer"),onClose:()=>f(!1),children:(0,r.jsx)("div",{dangerouslySetInnerHTML:{__html:u.svg}})})]});return(0,r.jsx)(lk,{lang:"mermaid",actions:(0,r.jsxs)(r.Fragment,{children:[u?.key===g&&"ready"===u.status&&(0,r.jsx)(lw,{onClick:()=>{let e=m.current?.querySelector("svg");e&&lv(new XMLSerializer().serializeToString(e),"mermaid-diagram.svg")}}),v]}),children:b})}function ly(e){let{isStreaming:t,previewVisible:n,onToggle:i,title:s,previewLabel:l}=e,{t:o}=(0,t_.s)();return(0,r.jsx)("button",{type:"button",onClick:i,disabled:t,title:t?o("i18n.previewAfterStreaming"):s,className:["markdown-code-action",n?"is-active":""].filter(Boolean).join(" "),children:n?o("i18n.source"):l??o("i18n.preview")})}function lw(e){let{onClick:t}=e,{t:n}=(0,t_.s)();return(0,r.jsx)("button",{type:"button",className:"markdown-code-action",title:`${n("i18n.downloadFile")} (SVG)`,"aria-label":`${n("i18n.downloadFile")} (SVG)`,onClick:t,children:"SVG"})}function lk(e){let{lang:t,actions:n,children:i}=e;return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:t}),(0,r.jsx)("div",{className:"markdown-code-actions",children:n})]}),i]})}function lj(e){let{title:t,label:n,onClose:s,children:l}=e,{t:o}=(0,t_.s)(),a=(0,i.useRef)(null),[d,c]=(0,i.useState)(1);return(0,i.useEffect)(()=>{let e=a.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,r.jsx)("dialog",{ref:a,className:"mermaid-zoom-dialog","aria-label":n,onCancel:e=>{e.preventDefault(),s()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),s())},children:(0,r.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,r.jsx)("span",{className:"mermaid-zoom-title",children:t}),(0,r.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,r.jsx)("button",{type:"button",onClick:()=>c(e=>Math.max(.5,e-.25)),disabled:d<=.5,title:o("i18n.zoomOut"),"aria-label":o("i18n.zoomOut"),children:(0,r.jsx)("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)("path",{d:"M5 12h14"})})}),(0,r.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*d),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>c(e=>Math.min(3,e+.25)),disabled:d>=3,title:o("i18n.zoomIn"),"aria-label":o("i18n.zoomIn"),children:(0,r.jsx)("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)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>c(1),title:o("i18n.fitToWidth"),"aria-label":o("i18n.fitToWidth"),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:"M8 3H3v5M16 3h5v5M8 21H3v-5M16 21h5v-5"})})}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:s,title:o("i18n.close"),"aria-label":o("i18n.close"),children:(0,r.jsx)("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)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]}),(0,r.jsx)("div",{className:"mermaid-zoom-viewport",onClick:e=>{e.target===e.currentTarget&&s()},children:(0,r.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*d}%`},children:l})})]})})}let lS={...sQ.xJ,'pre[class*="language-"]':{...sQ.xJ['pre[class*="language-"]']}};function lC(e){let{rows:t,stylesheet:n,useInlineStyles:i}=e;return t.map((e,t)=>{let s=e.children??[],l=s[0]?.properties?.className.includes("react-syntax-highlighter-line-number")?s[0]:null,o={...e,properties:{...e.properties,className:[...e.properties?.className??[],"markdown-code-line-text"]},children:l?s.slice(1):s};return(0,r.jsxs)("span",{className:"markdown-code-line",children:[l&&(0,r.jsx)("span",{className:"markdown-code-line-number","data-line-number":t+1,"aria-hidden":"true",style:l.properties?.style}),(0,sG.Ay)({node:o,stylesheet:n,useInlineStyles:i,key:"text"})]},t)})}delete lS['pre[class*="language-"]'].background;let lN=(0,i.memo)(function(e){let{text:t}=e;return(0,r.jsx)("span",{className:"markdown-code-stream-chunk is-frozen",children:t})});function lE(e){let{code:t}=e,n=[],i=0,s=0;for(let e=t.indexOf("\n");-1!==e;e=t.indexOf("\n",e+1))64===(s+=1)&&(n.push(t.slice(i,e)),i=e+1,s=0);let l=t.slice(i);return(0,r.jsxs)(r.Fragment,{children:[n.map((e,t)=>(0,r.jsx)(lN,{text:e},t)),(0,r.jsx)("span",{className:"markdown-code-stream-chunk",children:l})]})}let l$=(0,i.memo)(function(e){let{code:t,lang:n,headerAction:s,isStreaming:l}=e,{isDark:o}=lo(),{t:a}=(0,t_.s)(),[d,c]=(0,i.useState)(!1),u=lu(),[p,h]=(0,i.useState)(()=>{var e;return!l&&lc()&&(e=t.length,lh||(lh=!0,setTimeout(()=>{lp=2e3,lh=!1},0)),!(e>lp)&&(lp-=e,!0))});return(0,i.useEffect)(()=>{if(!l&&!p&&u){var e;return e=()=>h(!0),lf.push(e),lx(),()=>{let t=lf.indexOf(e);-1!==t&&lf.splice(t,1)}}},[l,p,u]),(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:n||"text"}),(0,r.jsxs)("div",{className:"markdown-code-actions",children:[s,(0,r.jsx)("button",{onClick:()=>{i0(t).then(()=>{c(!0),setTimeout(()=>c(!1),1500)},()=>{})},className:"markdown-code-action",children:a(d?"i18n.copied":"i18n.copy")})]})]}),l?(0,r.jsx)("pre",{style:{margin:0,padding:"11px 13px",fontSize:"calc(12.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.62,whiteSpace:"pre-wrap",overflowWrap:"anywhere",backgroundColor:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},children:(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:(0,r.jsx)(lE,{code:t})})}):(0,r.jsx)(sX.A,{language:p&&n||"text",style:o?lS:sQ.vs,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-dim)",fontStyle:"normal",flexShrink:0},renderer:lC,customStyle:{margin:0,padding:"11px 13px",fontSize:"calc(12.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.62,fontWeight:"var(--font-mono-weight)",border:"none",borderRadius:0,backgroundColor:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},codeTagProps:{style:{fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)"}},children:t})]})}),lI=new Set;function lM(e){let{code:t,lang:n,isStreaming:s}=e,{t:l}=(0,t_.s)(),o=""!==t.trim(),[a,d]=(0,i.useState)(()=>lI.has(t)?t:null),[c,u]=(0,i.useState)(null),p=o&&a===t&&!s,h=c?.code===t?c:void 0;(0,i.useEffect)(()=>{if(!p||h)return;let e=!1;return sJ(t).then(n=>{e||u(n?{code:t,status:"ready",url:n}:{code:t,status:"tooLong"})},()=>{e||u({code:t,status:"failed"})}),()=>{e=!0}},[t,h,p]);let f=(0,i.useMemo)(()=>(0,r.jsx)(ly,{isStreaming:s,previewVisible:p,onToggle:()=>{if(p)d(null);else lI.add(t),d(t)},title:p?l("i18n.showPlantUmlSource"):l("i18n.renderOnPlantUml"),previewLabel:l("i18n.renderOnPlantUml")}),[t,s,p,l]);return p?(0,r.jsx)(lk,{lang:n,actions:f,children:(0,r.jsx)(lT,{result:h})}):(0,r.jsx)(l$,{code:t,lang:n,headerAction:o?f:void 0,isStreaming:s})}function lT(e){let{result:t}=e,{t:n}=(0,t_.s)();return t?"tooLong"===t.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:n("i18n.plantUmlTooLong")}):"failed"===t.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:n("i18n.plantUmlLoadFailed")}):(0,r.jsx)(lR,{url:t.url},t.url):(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":n("i18n.renderingPlantUml")})}function lR(e){let{url:t}=e,{t:n}=(0,t_.s)(),[s,l]=(0,i.useState)(!1),[o,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(!1);if(o)return(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:n("i18n.plantUmlLoadFailed")});let u=e=>(0,r.jsx)("img",{src:t,alt:n("i18n.plantUmlDiagram"),className:e,referrerPolicy:"no-referrer",onLoad:()=>l(!0),onError:()=>a(!0)});return(0,r.jsxs)(r.Fragment,{children:[!s&&(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":n("i18n.renderingPlantUml")}),!d&&(0,r.jsx)("button",{type:"button",className:"mermaid-block mermaid-preview-button",title:n("i18n.openPlantUmlViewer"),"aria-label":n("i18n.openPlantUmlViewer"),hidden:!s,onClick:()=>c(!0),children:u("svg-block-image")}),d&&(0,r.jsx)(lj,{title:n("i18n.plantUmlDiagram"),label:n("i18n.plantUmlViewer"),onClose:()=>c(!1),children:u("svg-zoom-image")})]})}let lA="http://www.w3.org/2000/svg";function lL(e,t){let n=t.parseFromString(e,"image/svg+xml");return n.getElementsByTagName("parsererror").length>0?null:n.documentElement}function lz(e){let{code:t,isStreaming:n}=e,{t:s}=(0,t_.s)(),[l,o]=(0,i.useState)(!0),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),f=l&&!n,m=(0,i.useMemo)(()=>{var e;let n,r;return f&&"u">typeof DOMParser?(e=new DOMParser,r=lL(n=t,e),r?.localName!=="svg"||null!==r.namespaceURI||r.hasAttribute("xmlns")||(r=lL(n=t.replace(/<svg(?=[\s/>])/,`<svg xmlns="${lA}"`),e)),r?.localName==="svg"&&r.namespaceURI===lA?n:null):void 0},[t,f]),g=(0,i.useMemo)(()=>m?`data:image/svg+xml;charset=utf-8,${encodeURIComponent(m)}`:null,[m]),x=(0,i.useMemo)(()=>(0,r.jsx)(ly,{isStreaming:n,previewVisible:f,onToggle:()=>o(e=>!e),title:f?s("i18n.showSvgSource"):s("i18n.previewSvg")}),[n,f,s]);if(!f)return(0,r.jsx)(l$,{code:t,lang:"svg",headerAction:x,isStreaming:n});let v=null!==g&&c!==g,b=e=>(0,r.jsx)("img",{src:g??void 0,alt:s("i18n.svgImage"),className:[e,p===g?"is-unsized":""].filter(Boolean).join(" "),onLoad:e=>{let{naturalWidth:t,naturalHeight:n}=e.currentTarget;t&&n||h(g)},onError:()=>u(g)});return(0,r.jsx)(lk,{lang:"svg",actions:(0,r.jsxs)(r.Fragment,{children:[v&&m&&(0,r.jsx)(lw,{onClick:()=>lv(m,"image.svg")}),x]}),children:void 0===m?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading"}):v?(0,r.jsxs)(r.Fragment,{children:[!a&&(0,r.jsx)("button",{type:"button",className:"mermaid-block mermaid-preview-button",title:s("i18n.openSvgViewer"),"aria-label":s("i18n.openSvgViewer"),onClick:()=>d(!0),children:b("svg-block-image")}),a&&(0,r.jsx)(lj,{title:s("i18n.svgImage"),label:s("i18n.svgViewer"),onClose:()=>d(!1),children:b("svg-zoom-image")})]}):(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:s("i18n.invalidSvg")})})}let lP=(0,i.createContext)(!1);function lW(e){let{src:t,alt:n,cwd:s,...l}=e,o=(0,i.useContext)(lP);delete l.node;let a="string"==typeof t?t:void 0,d=a?iW(a,s):null,c=d?`/api/files/${nv(d)}?type=read`:a,u=d??a?.split(/[?#]/,1)[0]??"",p=n?.trim()?n:void 0;if(i3(u))return(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:c,"aria-label":p});if(i5(u))return(0,r.jsx)("video",{controls:!0,playsInline:!0,preload:"metadata",src:c,"aria-label":p});let h=(0,r.jsx)("img",{src:c,alt:n??"",loading:"lazy",...l});return!c||o?h:(0,r.jsx)(sY,{src:c,alt:n??"",className:"markdown-image",children:h})}function lO(e){let{source:t,children:n}=e,{t:s}=(0,t_.s)(),[l,o]=(0,i.useState)(!1);return(0,r.jsxs)("div",{className:"markdown-math-display",children:[n,(0,r.jsx)("button",{type:"button",onClick:()=>{i0(t).then(()=>{o(!0),setTimeout(()=>o(!1),1500)},()=>{})},className:"markdown-code-action markdown-math-copy",children:s(l?"i18n.copied":"i18n.copy")})]})}let lF=(0,i.memo)(function(e){let{markdown:t,remarkPlugins:n,urlTransform:i,rehypePlugins:s,components:l}=e;return(0,r.jsx)(iQ.oz,{remarkPlugins:n,rehypePlugins:s,urlTransform:i,components:l,children:t})});function lD(e,t,n){return"mermaid"===e?(0,r.jsx)(lb,{code:t,isStreaming:n,defaultPreview:!0}):"svg"===e?(0,r.jsx)(lz,{code:t,isStreaming:n}):sK(e)?(0,r.jsx)(lM,{code:t,lang:e,isStreaming:n}):(0,r.jsx)(l$,{code:t,lang:e,isStreaming:n})}let lB=(0,i.memo)(function(e){let{children:t,className:n,isStreaming:s,cwd:l,onOpenFile:o,onNavigateLink:a,keepLineBreaks:d,keepTextLayout:c}=e,u=(0,i.useMemo)(()=>sm(t),[t]),p=(0,i.useMemo)(()=>s?function(e){let t=e.split("\n");if(/^---[ \t]*\r?$/.test(t[0]))return[e];let n=[],r=[],i=null,s=!1,l=!1,o=!1;for(let a of t){let t=""===a.trim();!o||t||i||s||l||!(r.length>0)||/^[ \t]/.test(a)||sD.test(a)||(n.push(r.join("\n")+"\n"),r=[]),r.push(a);let d=a.match(sF);if(d){let e=d[1][0],t=d[1].length;i?e===i.marker&&t>=i.size&&/^[ \t]*\r?$/.test(a.slice(d[0].length))&&(i=null):i={marker:e,size:t}}else if(!i){if(s_.test(a))return[e];let t=a.replace(sH,"");sB.test(t)&&(l=!0),(t.match(/\$\$/g)?.length??0)%2==1&&(s=!s)}o=t}return n.push(r.join("\n")),n}(u):[u],[s,u]),h=(0,i.useMemo)(()=>({code(e){let{className:t,children:n,...i}=e,l=t?.replace("language-","").toLowerCase()??"",o=String(n);return t?.includes("language-")||o.includes("\n")?lD(l,o.replace(/\n$/,""),s):(0,r.jsx)("code",{className:"markdown-inline-code",...i,children:n})},pre(e){let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})},a(e){let{href:t,children:n,...i}=e;if(delete i.node,a&&t&&!su(t)){let e=()=>a(t);return(0,r.jsx)(lP.Provider,{value:!0,children:(0,r.jsx)("a",{...i,role:"link",tabIndex:0,onClick:e,onKeyDown:t=>{"Enter"===t.key&&e()},children:n})})}if(t?.startsWith("#"))return(0,r.jsx)(lP.Provider,{value:!0,children:(0,r.jsx)("a",{href:t,...i,onClick:sp,children:n})});let s=o?iW(t,l):null;return s&&o?(0,r.jsx)(lP.Provider,{value:!0,children:(0,r.jsx)("a",{href:t,...i,onClick:e=>{if(!iM(e))return;let n=e.currentTarget.getAttribute("target");n&&"_self"!==n||(e.preventDefault(),o(s,iF(t)??void 0))},children:n})}):(0,r.jsx)(lP.Provider,{value:!0,children:(0,r.jsx)("a",{href:t,...i,target:"_blank",rel:"noopener noreferrer",children:n})})},img:e=>(0,r.jsx)(lW,{cwd:l,...e}),ol(e){let{node:t,start:n,style:i,...s}=e,l=String(Math.abs((n??1)+Math.max(t?.children.filter(e=>"element"===e.type&&"li"===e.tagName).length??0,1)-1)).length;return(0,r.jsx)("ol",{start:n,style:{...i,"--ol-marker-digits":Math.max(l,2)},...s})},div(e){let{node:t,children:n,...i}=e,s=t?.properties?.dataMathSource;return"string"==typeof s?(0,r.jsx)(lO,{source:s,children:n}):(0,r.jsx)("div",{...i,children:n})},table(e){let{children:t}=e;return(0,r.jsx)("div",{className:"markdown-table-frame",children:(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:t})})})}}),[l,s,o,a]);return(0,r.jsx)("div",{className:["markdown-body",n].filter(Boolean).join(" "),children:p.map((e,t)=>{let n=s?function(e){if(e.includes("\r"))return null;let t=e.split("\n"),n=t[0].match(sU);if(!n||/[\\&]/.test(n[2]))return null;let r=n[1][0],i=n[1].length,s=-1;for(let e=1;e<t.length;e+=1){let n=t[e].match(/^ {0,3}(`{3,}|~{3,})[ \t]*$/);if(n&&n[1][0]===r&&n[1].length>=i){s=e;break}}if(-1!==s&&t.slice(s+1).some(e=>""!==e.trim()))return null;let l=n[2].toLowerCase();if("math"===l)return null;let o=-1!==s?s:t.length>1&&""===t[t.length-1]?t.length-1:t.length;return{lang:l,code:t.slice(1,o).join("\n")}}(e):null;return n?(0,r.jsx)(i.Fragment,{children:lD(n.lang,n.code,!0)},t):(0,r.jsx)(lF,{markdown:e,remarkPlugins:c?sT:d?sM:sS,urlTransform:o?sc:sd,rehypePlugins:a?sW:sP,components:h},t)})})});function lH(e){let{active:t,size:n=14}=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",style:{flexShrink:0},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",stroke:t?"#d4a017":void 0,fill:t?"rgba(250, 204, 21, 0.18)":"none",style:{filter:t?"drop-shadow(0 0 2px rgba(250, 204, 21, 0.35))":"none"}}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]})}let l_=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,lU=/(?:\r?\n){2,}((?:[ \t]*<(?:read-files|modified-files)>[ \t]*\r?\n[\s\S]*?\r?\n[ \t]*<\/(?:read-files|modified-files)>[ \t]*(?:\r?\n)?)+)\s*$/,lK=new Map;function lq(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0}function lV(e,t,n){let r=t.toolCallId;if("string"!=typeof r||"string"==typeof t.parentToolCallId&&""!==t.parentToolCallId)return e;if("tool_execution_start"===t.type){if(e.has(r))return e;let i=new Map(e);return i.set(r,{startedAt:n-(lq(t.elapsedMs)??0)}),i}if("tool_execution_end"===t.type){let n=lq(t.durationMs);if(void 0===n)return lZ(e,r);let i=new Map(e);return i.set(r,{durationMs:n}),i}return e}function lZ(e,t){if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}function lJ(e){let t=new Map([...e].filter(e=>{let[,t]=e;return"durationMs"in t}));return t.size===e.size?e:t.size?t:lK}function lY(e){let t,n=[],r=null,i=0,s=0,l=0,o=0,a=null,d=[],c=[],u=[],p=()=>({lineNo:null,text:"",type:"empty"}),h=()=>{if(!r){d=[],c=[],u=[];return}let e=Math.max(d.length,c.length);for(let t=0;t<e;t++){let e=d[t]?{lineNo:d[t].lineNo,text:d[t].text,type:"removed"}:p(),n=c[t]?{lineNo:c[t].lineNo,text:c[t].text,type:"added"}:p();r.rows.push({type:"line",left:e,right:n})}for(let e of u)r.rows.push({type:"hunk",text:e});d=[],c=[],u=[]};for(let p of e.split(/\r?\n/)){if(!(l>0||o>0)){if(p.startsWith("--- ")){h(),t=lQ(p.slice(4));continue}if(p.startsWith("+++ ")){h(),r={oldPath:t,newPath:lQ(p.slice(4)),rows:[]},n.push(r),a=null;continue}}let e=p.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){r||(r={rows:[]},n.push(r)),h(),i=Number(e[1]),s=Number(e[3]),l=void 0===e[2]?1:Number(e[2]),o=void 0===e[4]?1:Number(e[4]);let t=0===l?i+1:i,d=0===o?s+1:s;if(a){let e=t-a.old,n=d-a.new;(e>0||n>0)&&r.rows.push({type:"gap",count:e===n?e:null})}a={old:t+l,new:d+o},r.rows.push({type:"hunk",text:p});continue}if(!r)continue;if(p.startsWith("\\ ")){d.length||c.length?u.push(p):r.rows.push({type:"hunk",text:p});continue}let f=p[0],m=p.slice(1);" "===f?(h(),r.rows.push({type:"line",left:{lineNo:i++,text:m,type:"context"},right:{lineNo:s++,text:m,type:"context"}}),l>0&&l--,o>0&&o--):"-"===f?(d.push({lineNo:i++,text:m}),l>0&&l--):"+"===f?(c.push({lineNo:s++,text:m}),o>0&&o--):""!==p&&(h(),r.rows.push({type:"hunk",text:p}))}h();let f=n.filter(e=>e.rows.some(e=>"line"===e.type));return f.length>0?f:null}function lG(e){let t=[];for(let n of e.rows)if("hunk"!==n.type){if("gap"===n.type){t.push(n);continue}if("context"===n.left.type&&"context"===n.right.type){t.push({type:"context",text:n.right.text,oldLineNo:n.left.lineNo,newLineNo:n.right.lineNo});continue}"empty"!==n.left.type&&t.push({type:"removed",text:n.left.text,oldLineNo:n.left.lineNo,newLineNo:null}),"empty"!==n.right.type&&t.push({type:"added",text:n.right.text,oldLineNo:null,newLineNo:n.right.lineNo})}return t}function lX(e,t){return 1===e?t("diff.unchangedLine"):t("diff.unchangedLines",{count:e})}function lQ(e){return e.split(" ")[0].trim()}function l0(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"string"==typeof e.oldText&&"string"==typeof e.newText}function l1(e){if(""===e)return{lines:[],lastEnded:!1};let t=e.split(/\r\n|\r|\n/),n=t.length>1&&""===t[t.length-1];return n&&t.pop(),{lines:t,lastEnded:n}}function l2(e,t,n,r){return e.lines[t]===n.lines[r]&&(t<e.lines.length-1||e.lastEnded)===(r<n.lines.length-1||n.lastEnded)}function l4(e){if(e.length<=4e3)return e;let t=4e3,n=e.charCodeAt(t-1);return n>=55296&&n<=56319&&t--,`${e.slice(0,t)}…`}let l8=()=>({lineNo:null,text:"",type:"empty"}),l3=new Set,l5="pi-thinking-expanded",l6="pi-thinking-expanded-changed";function l9(){try{return"true"===window.localStorage.getItem(l5)}catch{return!1}}function l7(e){let{files:t,onOpenFile:n}=e,{t:i}=(0,t_.s)();return 0===t.length?null:(0,r.jsx)("div",{"aria-label":i("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:t.map(e=>{let{filePath:t}=e,s=nb(t);return(0,r.jsxs)("button",{type:"button",title:t,"aria-label":i("chat.openWrittenFile",{name:s}),onClick:()=>n?.(t),style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",fontSize:12,fontFamily:"var(--font-mono)",color:"var(--text)",background:"var(--bg-subtle)",border:"1px solid var(--border)",borderRadius:6,cursor:"pointer"},children:[ng(s,12),(0,r.jsx)("span",{children:s})]},t)})})}let oe="codemode",ot=new Set(["running","ok","error","cancelled"]);function on(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function or(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function oi(e){if(!on(e)||!Array.isArray(e.calls))return{calls:[],omitted:0};let t=e.calls.flatMap(e=>{let t=function(e){if(!on(e)||"string"!=typeof e.name)return null;let t="string"==typeof e.status&&ot.has(e.status)?e.status:"ok",n=or(e.durationMs),r=or(e.cost);return{id:"string"==typeof e.id?e.id:"",name:e.name,args:"string"==typeof e.args?e.args:"",status:t,...void 0!==n?{durationMs:n}:{},..."string"==typeof e.error&&e.error?{error:e.error}:{},...void 0!==r&&r>0?{cost:r}:{}}}(e);return t?[t]:[]}),n=or(e.omittedCalls);return{calls:t,omitted:void 0!==n&&n>0?Math.floor(n):0}}let os=/^Script (completed|failed)\nWall time ([\d.]+) seconds\nOutput:\n$/;function ol(e){return`$${e>=.01?e.toFixed(2):e.toPrecision(2)}`}let oo={running:{icon:"…",color:"#d97706"},ok:{icon:"✓",color:"#16a34a"},error:{icon:"✗",color:"#f87171"},cancelled:{icon:"⊘",color:"var(--text-dim)"}};function oa(e){var t;let{call:n}=e,{t:i}=(0,t_.s)(),s=oo[n.status],l=void 0===(t=n.durationMs)?"":t<1e3?`${Math.round(t)}ms`:`${(t/1e3).toFixed(1)}s`;return(0,r.jsxs)("li",{style:{display:"flex",flexDirection:"column",gap:2,minWidth:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:6,minWidth:0},children:[(0,r.jsx)("span",{role:"img","aria-label":i(`codemode.status.${n.status}`),title:i(`codemode.status.${n.status}`),style:{color:s.color,width:12,flexShrink:0,textAlign:"center"},children:s.icon}),(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontWeight:600,flexShrink:0},children:n.name}),n.args&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:n.args}),l&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",flexShrink:0,marginLeft:"auto",fontVariantNumeric:"tabular-nums"},children:l}),void 0!==n.cost&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:ol(n.cost)})]}),n.error&&(0,r.jsx)("div",{style:{color:"#f87171",paddingLeft:18,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n.error})]})}function od(e){let t,{calls:n,omitted:s,isError:l}=e,{t:o}=(0,t_.s)(),[a,d]=(0,i.useState)(!1);if(0===n.length&&0===s)return null;let c=a?0:Math.max(0,n.length-20),u=c>0?n.slice(c):n,p=(t=n.filter(e=>void 0!==e.cost)).length>1?t.reduce((e,t)=>e+(t.cost??0),0):null;return(0,r.jsxs)("div",{style:{borderTop:l?"1px solid rgba(248,113,113,0.25)":"1px solid rgba(34,197,94,0.2)",background:"var(--bg-subtle)",padding:"6px 10px",fontFamily:"var(--font-mono)",fontSize:"calc(11.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,display:"flex",flexDirection:"column",gap:3,minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"inherit",fontSize:11},children:o("codemode.calls")}),s>0&&(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:o("codemode.omittedCalls",{count:s})}),c>0&&(0,r.jsx)("button",{type:"button",onClick:()=>d(!0),style:{alignSelf:"flex-start",padding:0,border:"none",background:"none",color:"var(--accent)",cursor:"pointer",font:"inherit"},children:o("codemode.showEarlierCalls",{count:c})}),(0,r.jsx)("ul",{style:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:3,minWidth:0},children:u.map((e,t)=>(0,r.jsx)(oa,{call:e},e.id||`${c+t}`))}),null!==p&&(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:o("codemode.modelCost",{cost:ol(p)})})]})}function oc(e){return"string"==typeof e?e.trim()?e:null:"number"==typeof e||"boolean"==typeof e?String(e):null}function ou(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:", ";if(!Array.isArray(e))return oc(e);if(0===e.length||!e.every(e=>null===e||"object"!=typeof e))return null;let n=e.map(oc).filter(e=>null!==e);return n.length>0?n.join(t):null}var op=n(9701);let oh=new Map;function of(e){return"number"!=typeof e.timestamp?null:`${e.provider??""}/${e.model??""}@${e.timestamp}`}let om="transcriptNotices";function og(e){if("object"!=typeof e||null===e)return[];let t=e[om];return Array.isArray(t)?t:[]}function ox(e){return e<1e3?e.toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${Math.round(e/1e3)}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${Math.round(e/1e6)}M`}let ov="#d97706";function ob(e,t){let n=t>=.01?`$${t.toFixed(2)}`:void 0;return n?e("transcriptNotice.costSuffix",{cost:n}):""}function oy(e,t){switch(t.kind){case"cache_miss":{let n={tokens:ox(t.missedTokens),cost:ob(e,t.missedCost)};if(t.modelChanged)return e("transcriptNotice.cacheMissModelSwitch",n);if(void 0!==t.idleMinutes)return e("transcriptNotice.cacheMissIdle",{...n,minutes:t.idleMinutes});return e("transcriptNotice.cacheMiss",n)}case"cache_warm":var n;return e("transcriptNotice.cacheWarmed",{note:t.note?e("transcriptNotice.cacheWarmedNote",{note:t.note}):"",cost:(n=t.cost,`$${n.toFixed(6).replace(/(\.\d{3}\d*?)0+$/,"$1")}`)});case"summary_cost":return e("compaction"===t.source?"transcriptNotice.compactionCost":"transcriptNotice.branchSummaryCost",{tokens:ox(t.tokens),cost:ob(e,t.cost)});case"thinking_dropped":return e(1===t.count?"transcriptNotice.thinkingDroppedOne":"transcriptNotice.thinkingDropped",{count:t.count})}}let ow=(0,i.memo)(function(e){let{notices:t}=e,{t:n}=(0,t_.s)(),i=t.filter(e=>"summary_cost"!==e.kind||"compaction"!==e.source);return 0===i.length?null:(0,r.jsx)("div",{className:"transcript-notices",style:{display:"flex",flexDirection:"column",gap:2,margin:"-6px 0 12px"},children:i.map((e,t)=>{let i="cache_warm"!==e.kind;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:6,fontSize:12,lineHeight:1.5,color:i?ov:"var(--text-dim)",overflowWrap:"anywhere"},children:[i&&(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,marginTop:3},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)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsx)("span",{children:oy(n,e)})]},t)})})}),ok=/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}\uac00-\ud7af]/u;function oj(e){let t=0,n=0;for(let r of e)ok.test(r)?t++:n++;return t+n/4}let oS=new Map;function oC(e){let{children:t,className:n,...s}=e,{t:l}=(0,t_.s)(),[o,a]=(0,i.useState)(!1);if(t.length<=1e5)return(0,r.jsx)(lB,{className:n,...s,children:t});if(!o){var d;return(0,r.jsxs)("button",{onClick:()=>a(!0),style:{display:"block",width:"100%",margin:"4px 0",padding:"7px 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:["⚠ ",l("i18n.largeMessageReveal",{size:(d=t.length)>=1e6?`${(d/1e6).toFixed(1)} MB`:d>=1e3?`${Math.round(d/1e3)} KB`:`${d} B`})]})}return(0,r.jsx)("div",{className:n,style:{maxHeight:420,overflow:"auto",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)",color:"var(--text-muted)"},children:t})})}function oN(e){if(!e)return null;let t=new Date(e),n=new Date,r=t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate(),i=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});if(r)return i;let s=t.toLocaleDateString([],{month:"short",day:"numeric",year:t.getFullYear()!==n.getFullYear()?"numeric":void 0});return`${s} ${i}`}function oE(e,t,n){if(t===n||"assistant"!==e.role)return!0;for(let r of e.content??[])if("toolCall"===r.type&&t?.get(r.toolCallId)!==n?.get(r.toolCallId))return!1;return!0}let o$=(0,i.memo)(function(e){let{message:t,isStreaming:n,toolResults:i,toolClocks:s,modelNames:l,cwd:o,onOpenFile:a,onOpenSubagent:d,entryId:c,searchBlock:u,onFork:p,forking:h,onEditContent:f,onCancelEdit:m,isEditing:g,showTimestamp:x,prevTimestamp:v,sessionId:b,writtenFiles:y,turnDurationMs:w,onCompact:k,isCompacting:j,compactError:S}=e;return"user"===t.role?(0,r.jsx)(oI,{message:t,cwd:o,onOpenFile:a,entryId:c,onFork:p,forking:h,onEditContent:f,onCancelEdit:m,isEditing:g}):"assistant"===t.role?(0,r.jsx)(oT,{message:t,isStreaming:n,toolResults:i,toolClocks:s,modelNames:l,cwd:o,onOpenFile:a,onOpenSubagent:d,showTimestamp:x,prevTimestamp:v,sessionId:b,entryId:c,searchBlock:u,writtenFiles:y,turnDurationMs:w,onCompact:k,isCompacting:j,compactError:S}):"toolResult"===t.role?null:"custom"===t.role?"compaction"===t.customType?(0,r.jsx)(o0,{message:t}):(0,r.jsx)(o8,{message:t,cwd:o,onOpenFile:a}):"bashExecution"===t.role?(0,r.jsx)(al,{message:t,sessionId:b}):null},(e,t)=>e.message===t.message&&e.isStreaming===t.isStreaming&&oE(e.message,e.toolResults,t.toolResults)&&oE(e.message,e.toolClocks,t.toolClocks)&&e.modelNames===t.modelNames&&e.cwd===t.cwd&&e.onOpenFile===t.onOpenFile&&e.onOpenSubagent===t.onOpenSubagent&&e.entryId===t.entryId&&e.searchBlock===t.searchBlock&&e.onFork===t.onFork&&e.forking===t.forking&&e.onEditContent===t.onEditContent&&e.onCancelEdit===t.onCancelEdit&&e.isEditing===t.isEditing&&e.showTimestamp===t.showTimestamp&&e.prevTimestamp===t.prevTimestamp&&e.writtenFiles===t.writtenFiles&&e.turnDurationMs===t.turnDurationMs&&e.sessionId===t.sessionId&&e.onCompact===t.onCompact&&e.isCompacting===t.isCompacting&&e.compactError===t.compactError);function oI(e){let{message:t,cwd:n,onOpenFile:s,entryId:l,onFork:o,forking:a,onEditContent:d,onCancelEdit:c,isEditing:u}=e,{t:p}=(0,t_.s)(),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(!1),[x,v]=(0,i.useState)(!1),b=("string"==typeof t.content?t.content:t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")).replace(/\r\n?/g,"\n"),y="string"==typeof t.content?[]:t.content.filter(e=>"image"===e.type),w=nQ(b),k=w?.search(/\s/)??-1,j=w?-1===k?w:w.slice(0,k):"",S=w&&-1!==k?w.slice(k+1):"",C=oN(t.timestamp),N=!!l&&!!o,E=w??b,$=w?function(e,t){if("string"==typeof e.content)return{...e,content:t};let n=[],r=!1;for(let i of e.content){if("text"!==i.type){n.push(i);continue}r||(n.push({...i,text:t}),r=!0)}return r||n.unshift({type:"text",text:t}),{...e,content:n}}(t,w):t,I=y.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!b},children:y.map((e,t)=>{let n=e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:"";return(0,r.jsx)(sY,{src:n,children:(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:6,objectFit:"contain",display:"block",border:"1px solid rgba(59,130,246,0.15)"}})},t)})}),M=!!l&&!!d,T=!!u&&!!c;return(0,r.jsxs)("div",{style:{marginBottom:16,display:"flex",flexDirection:"column",alignItems:"flex-end"},onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,maxWidth:"85%"},children:(0,r.jsx)("div",{style:{flex:1,minWidth:0,background:u?"color-mix(in srgb, var(--accent) 14%, var(--user-bg))":"var(--user-bg)",border:u?"1px solid color-mix(in srgb, var(--accent) 62%, var(--user-bg))":"1px solid rgba(59,130,246,0.2)",boxShadow:u?"0 0 0 2px color-mix(in srgb, var(--accent) 16%, transparent)":void 0,borderRadius:12,padding:"8px 12px",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.6,color:"var(--text)",wordBreak:"break-word",maxHeight:300,overflowY:"auto"},children:w?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0},children:[I,(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexWrap:"wrap"},children:[(0,r.jsxs)("button",{onClick:()=>v(e=>!e),title:p(x?"i18n.collapse":"i18n.expand"),"aria-expanded":x,style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,padding:0,background:"none",border:"none",cursor:"pointer",color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",textAlign:"left"},children:[(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:j}),(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,opacity:.75,transform:x?"rotate(180deg)":"none",transition:"transform 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),S&&(0,r.jsx)("span",{style:{color:"var(--text)",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.6,whiteSpace:"pre-wrap",wordBreak:"break-word",minWidth:0,flex:1},children:S})]}),x&&(0,r.jsx)(lB,{className:"markdown-user-message",keepLineBreaks:!0,cwd:n,onOpenFile:s,children:function(e){let t=e.match(nX);if(!t)return null;let n=t[4],r=void 0===n?9:11+n.length;return e.slice(e.indexOf("\n")+1,e.length-r)}(b)??b})]}):(0,r.jsxs)(r.Fragment,{children:[I,b&&(0,r.jsx)(oC,{className:"markdown-user-message",keepLineBreaks:!0,cwd:n,onOpenFile:s,children:b})]})})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:3},children:[(0,r.jsx)("div",{style:{display:"flex",gap:3,opacity:+!!h,pointerEvents:h?"auto":"none",transition:"opacity 0.12s"},children:(0,r.jsxs)("button",{onClick:()=>{i0(E).then(()=>{g(!0),setTimeout(()=>g(!1),1500)},()=>{})},title:p("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:m?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{m||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{m||(e.currentTarget.style.color="var(--text-dim)")},children:[m?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",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"})]}),(0,r.jsx)("span",{className:"message-action-label",children:p(m?"i18n.copied":"i18n.copy")})]})}),(N||M||T)&&(0,r.jsxs)("div",{style:{display:"flex",gap:3,opacity:h||a||T?1:0,pointerEvents:h||a||T?"auto":"none",transition:"opacity 0.12s"},children:[M&&!T&&(0,r.jsxs)("button",{onClick:()=>d($,l),title:p("i18n.editFromHereTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"15 10 20 15 15 20"}),(0,r.jsx)("path",{d:"M4 4v7a4 4 0 0 0 4 4h12"})]}),(0,r.jsx)("span",{className:"message-action-label",children:p("i18n.editFromHere")})]}),T&&(0,r.jsxs)("button",{type:"button",onClick:c,title:p("i18n.cancel"),"aria-label":p("i18n.cancel"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:500,whiteSpace:"nowrap"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6L6 18"})}),(0,r.jsx)("span",{className:"message-action-label",children:p("i18n.cancel")})]}),N&&(0,r.jsxs)("button",{onClick:()=>{o(l,$)},disabled:a,title:p(a?"i18n.creatingSession":"i18n.newSessionTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:a?"var(--accent)":"var(--text-dim)",cursor:a?"not-allowed":"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{a||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{a||(e.currentTarget.style.color="var(--text-dim)")},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",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)("span",{className:"message-action-label",children:p(a?"i18n.creating":"i18n.newSession")})]})]}),C&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:C})]})]})}function oM(e){let{modelName:t,estimatedTokens:n=0,tps:i=null}=e,{t:s}=(0,t_.s)(),l=null!==i?i>=50?"#53b3cb":i>=30?"#9bc53d":i>=15?"#f9c22e":"#e01a4f":void 0;return(0,r.jsxs)("div",{style:{fontSize:11,lineHeight:1.5,minHeight:"calc(1.5em + 2px)",color:"var(--text-dim)",marginBottom:4,display:"flex",alignItems:"center",gap:6,fontVariantNumeric:"tabular-nums"},children:[t&&(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t}),n>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4,flexShrink:0,whiteSpace:"nowrap",color:"var(--text)"},title:s("i18n.estimatedTokens"),children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:2,fontSize:11,fontWeight:400},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",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"})]}),(0,r.jsx)("span",{children:n})]}),null!==i&&(0,r.jsxs)("span",{style:{marginLeft:6,padding:"1px 6px",minWidth:"calc(8ch + 1px)",boxSizing:"content-box",textAlign:"center",borderRadius:4,background:l,color:"#fff",fontSize:11,fontWeight:400},children:[i.toFixed(1)," t/s"]})]})]})}function oT(e){var t,n,s,l,o;let a,d,c,u,{message:p,isStreaming:h,toolResults:f,toolClocks:m,modelNames:g,cwd:x,onOpenFile:v,onOpenSubagent:b,showTimestamp:y,prevTimestamp:w,sessionId:k,entryId:j,searchBlock:S,writtenFiles:C,turnDurationMs:N,onCompact:E,isCompacting:$,compactError:I}=e,{t:M}=(0,t_.s)(),T=y?oN(p.timestamp):null,R=(0,i.useMemo)(()=>(p.content??[]).map((e,t)=>({block:e,originalIndex:t})).filter(e=>{let{block:t}=e;return!ij(t,{isStreaming:h})}),[p.content,h]),A=(0,i.useMemo)(()=>R.map(e=>{let{block:t}=e;return t}),[R]),L=iC(p,{isStreaming:h}),z=iN(p,{isStreaming:h}),P=iE(p,{isStreaming:h}),W=P&&!i$(p),[O,F]=(0,i.useState)(!1),[D,B]=(0,i.useState)(!1),H=(0,i.useRef)(null),_=of(p),U=(0,i.useRef)(_);U.current=_;let[K,q]=(0,i.useState)(null),V=(0,i.useRef)(R);V.current=R;let Z=(0,i.useRef)(new Map),J=(0,i.useMemo)(()=>{if(!h)return Z.current=new Map,0;let e=new Map,t=0;for(let{block:n,originalIndex:r}of R){let i="text"===n.type?n.text:"thinking"===n.type?n.thinking:"toolCall"===n.type?n.rawInput??JSON.stringify(n.input??{})??"":null;if(null===i)continue;let s=function(e,t){var n,r;if(!e||!t.startsWith(e.text))return oj(t);let i=e.tokens,s=e.text.length;return s>0&&s<t.length&&(n=e.text.charCodeAt(s-1))>=55296&&n<=56319&&(r=t.charCodeAt(s))>=56320&&r<=57343&&(i-=.25,s--),i+oj(t.slice(s))}(Z.current.get(r),i);e.set(r,{text:i,tokens:s}),t+=s}return Z.current=e,t},[R,h]),Y=(0,i.useRef)(J);Y.current=J;let G=(0,i.useRef)(new Map),[X,Q]=(0,i.useState)(new Map),ee="assistant"===p.role?oP(p.durationMs):void 0,et=(0,i.useMemo)(()=>{let e=ee??(p.timestamp&&w?p.timestamp-w:void 0);if(void 0===e)return;let t=Math.round(e/1e3);return t>0?t:void 0},[ee,p.timestamp,w]),en=(0,i.useMemo)(()=>{let e=new Map;if(!f)return e;for(let[t,n]of f){let r=oP(n.durationMs)??(n.timestamp&&p.timestamp?n.timestamp-p.timestamp:void 0);void 0!==r&&r>=oW&&e.set(t,r)}return e},[f,p.timestamp]),er=A.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),ei=p.usage?(s=p.usage,a=[],s.input&&a.push({icon:"up",before:"↑",text:ox(s.input)}),s.output&&a.push({icon:"down",before:"↓",text:ox(s.output)}),s.cacheRead&&a.push({text:`R${ox(s.cacheRead)}`}),s.cacheWrite&&a.push({text:`W${ox(s.cacheWrite)}`}),s.cost?.total&&a.push({text:`$${s.cost.total.toFixed(4)}`}),a):[];if(z&&ei.unshift({text:M("chat.operationAborted")},...ei.length>0?[{text:"\xb7"}]:[]),void 0!==N){let e;ei.length>0&&ei.push({text:"\xb7"});let t=iX(N);ei.push((l=M("chat.turnDuration",{time:t}),o=t,(e=l.indexOf(o))<0?{text:l}:{icon:"clock",before:l.slice(0,e),text:o,after:l.slice(e+o.length)}))}return((0,i.useEffect)(()=>{if(!h){let e=new Date().getTime();Q(t=>{let n=new Map(t);for(let[t,r]of G.current)n.has(t)||n.set(t,Math.round((e-r)/1e3));return n}),H.current=null,q(null);return}let e=setInterval(()=>{var e;let t,n=V.current,r=Date.now();n.forEach(e=>{let{originalIndex:t}=e;G.current.has(t)||G.current.set(t,r)}),Q(e=>{let t=!1,i=new Map(e);for(let e=0;e<n.length-1;e++){let s=n[e].originalIndex,l=n[e+1].originalIndex;if(!i.has(s)&&G.current.has(s)){let e=G.current.get(s),n=G.current.get(l)??r;i.set(s,Math.round((n-e)/1e3)),t=!0}}return t?i:e});let i=Y.current;if(0===i)return;H.current??=function(e,t,n){let r=null===e?void 0:oh.get(e);if(r)return r;let i={at:n,tokens:t};return null!==e&&(oh.set(e,i),oh.size>32&&oh.delete(oh.keys().next().value)),i}(U.current,i,r);let s=(e=H.current,(t=(r-e.at)/1e3)>.5?(i-e.tokens)/t:null);null!==s&&q(s)},300);return()=>clearInterval(e)},[h]),0!==A.length||h||L||P||z)?(0,r.jsxs)("div",{"data-message-role":"assistant","data-entry-id":j,style:{marginBottom:16},onMouseEnter:()=>F(!0),onMouseLeave:()=>F(!1),children:[(0,r.jsx)(oM,{modelName:p.provider?(t=p.provider,n=p.model,d=t.toLowerCase(),c=n.toLowerCase(),u=Object.entries(g??{}).flatMap(e=>{let[t,n]=e,r=t.indexOf(":");return r>0&&t.slice(0,r).toLowerCase()===d?[{id:t.slice(r+1).toLowerCase(),name:n}]:[]}),u.find(e=>e.id===c)?.name??u.find(e=>c.endsWith(`/${e.id}`))?.name??Object.entries(g??{}).find(e=>{let[t]=e;return t.toLowerCase()===c})?.[1]??`${t}/${n}`):void 0,estimatedTokens:h?Math.round(J):0,tps:h?K:null}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:R.map(e=>{let{block:t,originalIndex:n}=e;return(0,r.jsx)(oR,{block:t,searchTarget:t===S,toolResults:f,toolsNotRun:z||null!==L,isStreaming:h,streamingDuration:X.get(n)??("thinking"===t.type?et:void 0),toolCallDurations:en,toolClocks:m,cwd:x,onOpenFile:v,onOpenSubagent:b,sessionId:k,entryId:j,blockIndex:n},n)})}),L&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:8*(A.length>0),padding:"7px 10px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:6,background:"rgba(239,68,68,0.07)",color:"#ef4444",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Error: ",L]}),P&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:A.length>0||L?8:0,padding:"7px 10px",border:"1px solid rgba(234,179,8,0.3)",borderRadius:6,background:"rgba(234,179,8,0.07)",color:"#ca8a04",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:[M(W?"chat.truncatedWithoutAnswer":"chat.truncatedByOutputLimit"),W&&E&&(0,r.jsx)("button",{type:"button",onClick:E,disabled:$,style:{display:"block",marginTop:8,padding:"3px 8px",border:"1px solid currentColor",borderRadius:5,background:"transparent",color:"inherit",cursor:$?"default":"pointer",font:"inherit"},children:M($?"chat.compacting":"chat.compactContext")}),W&&I&&(0,r.jsx)("div",{style:{marginTop:8,color:"#ef4444",whiteSpace:"pre-wrap"},children:I})]}),C&&C.length>0&&(0,r.jsx)(l7,{files:C,onOpenFile:v}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:4},children:[ei.length>0&&!h&&(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",columnGap:7,fontSize:11,color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:ei.map((e,t)=>(0,r.jsxs)(i.Fragment,{children:[t>0&&" ",(0,r.jsx)(as,{part:e})]},t))}),er&&!h&&(0,r.jsxs)("button",{onClick:()=>{i0(er).then(()=>{B(!0),setTimeout(()=>B(!1),1500)},()=>{})},title:M("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:D?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:+!!O,pointerEvents:O?"auto":"none",transition:"opacity 0.12s, color 0.12s"},onMouseEnter:e=>{D||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{D||(e.currentTarget.style.color="var(--text-dim)")},children:[D?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",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"})]}),(0,r.jsx)("span",{className:"message-action-label",children:M(D?"i18n.copied":"i18n.copy")})]}),T&&!h&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginLeft:"auto",whiteSpace:"nowrap"},children:T})]})]}):null}function oR(e){let{block:t,searchTarget:n,toolResults:i,toolsNotRun:s,isStreaming:l,streamingDuration:o,toolCallDurations:a,toolClocks:d,cwd:c,onOpenFile:u,onOpenSubagent:p,sessionId:h,entryId:f,blockIndex:m}=e;if("text"===t.type)return(0,r.jsx)("div",{"data-message-text":!0,"data-search-target":n||void 0,children:(0,r.jsx)(oA,{block:t,isStreaming:l,cwd:c,onOpenFile:u})});if("thinking"===t.type)return(0,r.jsx)(oz,{block:t,duration:o,sessionId:h,entryId:f,blockIndex:m});if("toolCall"===t.type){let e=i?.get(t.toolCallId),n=a?.get(t.toolCallId);return(0,r.jsx)(oD,{block:t,result:e,notRun:s,duration:n,clock:d?.get(t.toolCallId),onOpenSubagent:p})}return null}function oA(e){let{block:t,isStreaming:n,cwd:i,onOpenFile:s}=e;return(0,r.jsx)(oC,{isStreaming:n,cwd:i,onOpenFile:s,children:t.text})}function oL(e){let{text:t}=e,n=(0,i.useMemo)(()=>(function(e){let t=[],n=0;for(;e.length-n>8e3;){let r=n+8e3,i=r+8e3,s=e.slice(r,i+1),l=s.indexOf("\n");for(;l>=0&&/\n\r?$/.test(e.slice(r+l-2,r+l));)l=s.indexOf("\n",l+1);if(l>=0){let i=r+l;if(i===e.length-1)break;t.push({text:e.slice(n,i),lineBreak:!0}),n=i+1}else if(e.length>i){let r=e.charCodeAt(i-1),s=r>=55296&&r<=56319?i-1:i;t.push({text:e.slice(n,s),lineBreak:!1}),n=s}else break}return t.push({text:e.slice(n),lineBreak:!1}),t})(t),[t]);return 1===n.length?t:n.map((e,t)=>(0,r.jsx)("div",{children:e.text},t))}function oz(e){var t;let{block:n,duration:s,sessionId:l,entryId:o,blockIndex:a}=e,{t:d}=(0,t_.s)(),[c,u]=(0,i.useState)(l9),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(!1),[g,x]=(0,i.useState)(null),v=`${l}:${o}:${a}`,[b,y]=(0,i.useState)(v);b!==v&&(y(v),h(null),m(!1),x(null));let w=(0,i.useRef)(d);w.current=d;let k=(t=n.thinking,t.trimStart().match(/^[^\r\n]{0,240}/u)?.[0].trimEnd()??"");return(0,i.useEffect)(()=>{let e=()=>u(l9());return window.addEventListener(l6,e),()=>window.removeEventListener(l6,e)},[]),(0,i.useEffect)(()=>{if(!c||!n.deferred||null!==p)return;if(!l||!o)return void x(w.current("i18n.thinkingUnavailable"));let e=!1;return m(!0),x(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=oS.get(r);if(i)return oS.delete(r),oS.set(r,i),i;let s=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${n}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw oS.delete(r),e});if(oS.set(r,s),oS.size>100){let e=oS.keys().next().value;e&&oS.delete(e)}return s})(l,o,a).then(t=>{e||(h(t),m(!1))}).catch(t=>{e||(x(t instanceof Error?t.message:String(t)),m(!1))}),()=>{e=!0}},[c,n.deferred,p,l,o,a]),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:6,minWidth:0,border:"1px solid var(--border)",borderRadius:7,padding:"6px 10px",background:"var(--bg)",fontFamily:"var(--font-mono)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":c,"aria-label":`${d("i18n.thinking")}${k?`: ${k}`:""}`,title:d("i18n.thinking"),onClick:()=>u(e=>!e),style:{display:"inline-flex",alignItems:"center",gap:6,width:c?14:"100%",flexShrink:+!c,minWidth:0,minHeight:"1.5em",padding:0,background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",font:"inherit",textAlign:"left"},children:[(0,r.jsx)(lH,{active:c}),!c&&(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k?(0,r.jsx)(iQ.oz,{allowedElements:[],unwrapDisallowed:!0,skipHtml:!0,children:k}):"..."})]}),c&&(0,r.jsx)("div",{style:{flex:1,minWidth:0,color:g?"#f87171":"var(--text-muted)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:f?d("i18n.loadingThinking"):g??(0,r.jsx)(oL,{text:(n.deferred?p:n.thinking)??""})}),void 0!==s&&(0,r.jsxs)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:[s,"s"]})]})}function oP(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0}let oW=100;function oO(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t),r=Math.floor(n/60),i=n%60;return r<60?`${r}m ${i}s`:`${Math.floor(r/60)}h ${r%60}m ${i}s`}function oF(e){let{clock:t}=e,n="startedAt"in t,[s,l]=(0,i.useState)(()=>performance.now());(0,i.useEffect)(()=>{if(!n)return;let e=window.setInterval(()=>l(performance.now()),1e3);return()=>window.clearInterval(e)},[n]);let o="durationMs"in t?t.durationMs:Math.max(0,s-t.startedAt);return o<oW?null:(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:oO(o)})}function oD(e){var t,n,s,l;let o,{block:a,result:d,notRun:c,duration:u,clock:p,onOpenSubagent:h,resultFooter:f}=e,{t:m}=(0,t_.s)(),[g,x]=(0,i.useState)(()=>{var e;return void 0!==(e=a.toolCallId)&&l3.has(e)}),v=function(e){if(void 0!==e.rawInput||!iD(e.toolName))return null;let{content:t}=e.input;return"string"!=typeof t||""===t?null:Object.keys(e.input).every(e=>o9.has(e))?t:null}(a),b=v??(s=a).rawInput??JSON.stringify(s.input,null,2),y=void 0!==a.rawInput,w=iB(a.toolName),k=d&&!d.isError?function(e){let t=e.details;if(!oG(t))return null;let n="string"==typeof t.patch?t.patch:null;if(n)return{text:n};let r="string"==typeof t.diff?t.diff:null;return r?{text:r}:null}(d):null,j=k?.text,S=(0,i.useMemo)(()=>(function(e){if(!e)return null;let t=lY(e);return t?.length===1&&oq(t[0])||null})(j),[j]),C=function(e,t){if(!iH(e.toolName))return null;let n=iV(i_(e.input,e.rawInput));if(n)return n;let r=t&&!t.isError?t.details:void 0;if(oG(r)){let e=iZ(r.preview);if(e)return e}return null}(a,d),N=!g||!w||y||d||c?null:a.input,E=(0,i.useMemo)(()=>{let e=null===N?null:function(e){let t=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t=e.edits;if("string"==typeof t)try{let e=JSON.parse(t);t=l0(e)?[e]:e}catch{}else l0(t)&&(t=[t]);let n=Array.isArray(t)?[...t]:[];return("string"==typeof e.oldText&&"string"==typeof e.newText&&n.push({oldText:e.oldText,newText:e.newText}),0!==n.length&&n.every(l0))?n:null}(e);if(!t)return null;let n="string"==typeof e.path?e.path:"string"==typeof e.file_path?e.file_path:void 0,r=[],i=0,s=!1,l=e=>{let t=r[r.length-1];t?.type==="gap"?t.count=null===t.count||null===e?null:t.count+e:r.push({type:"gap",count:e})},o=(e,t)=>i>=1e3?(s||l(null),s=!0,!1):(r.push({type:"line",left:e,right:t}),i++,!0),a=e=>{let t={lineNo:null,text:l4(e),type:"context"};return o(t,{...t})};for(let[e,n]of t.entries()){if(s)break;e>0&&l(null);let t=l1(n.oldText),r=l1(n.newText),i=t.lines,d=r.lines,c=0;for(;c<i.length&&c<d.length&&l2(t,c,r,c);)c++;let u=i.length,p=d.length;for(;u>c&&p>c&&l2(t,u-1,r,p-1);)u--,p--;let h=Math.max(0,c-4);h>0&&l(h);for(let e=h;e<c&&a(i[e]);e++);let f=Math.max(u-c,p-c);for(let e=0;e<f;e++){let t=c+e<u?i[c+e]:null,n=c+e<p?d[c+e]:null;if(!o(null===t?l8():{lineNo:null,text:l4(t),type:"removed"},null===n?l8():{lineNo:null,text:l4(n),type:"added"}))break}let m=i.length-u,g=Math.min(m,4);for(let e=0;e<g&&a(i[u+e]);e++);!s&&m>g&&l(m-g)}return r.some(e=>"line"===e.type)?{oldPath:n,newPath:n,rows:r}:null}(N);return e?[e]:null},[N]),$=iH(a.toolName)?0===(o=function(e){let t=[];for(let n of e.matchAll(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/gm)){let e=(n[1]??"").trim();e&&!t.includes(e)&&t.push(e)}return t}(i_((l=a).input,l.rawInput))).length?null:o.join(", ").slice(0,120):null,I=a.toolName!==oe||y?null:on(t=a.input)&&"string"==typeof t.code?t.code:null,M=null===I?null:{code:I,...oi(d?.details)},T=null!==M&&void 0!==d&&0===d.content.length,R=g&&null===v&&null===M&&null===C?function(e){if(null===e||"object"!=typeof e||Array.isArray(e))return null;let t=Object.entries(e);if(0===t.length)return null;let n=[];for(let[e,r]of t){if(null!==r&&"string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r)return null;let t=null===r?"null":String(r);n.push({key:e,value:""===t?"(empty)":t,multiline:t.includes("\n")})}return n}(y?(0,op.o2)(a.rawInput):a.input):null,A=function(e,t){if(!e.startsWith("mcp__")||!("object"==typeof t&&null!==t&&!Array.isArray(t)))return null;let{server:n,tool:r}=t;return"string"==typeof n&&"string"==typeof r&&n&&r?{server:n,tool:r}:null}(a.toolName,d?.details),L=d?M?function(e){let[t,...n]=e;return t?.type==="text"&&"string"==typeof t.text&&os.test(t.text)?n:[...e]}(d.content):d.content:[],z=d?L.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,P=A&&null!==z?function(e){let t=e.trim();if(t.length>2e5||!/^[[{]/.test(t))return e;try{let n=!1,r=JSON.parse(t,(e,t)=>("number"==typeof t&&(!Number.isFinite(t)||Number.isInteger(t)&&!Number.isSafeInteger(t))&&(n=!0),t));return n?e:JSON.stringify(r,null,2)}catch{return e}}(z):z,W=o5(L),O=null!==P&&("(no output)"===P.trim()||""===P.trim()),F=(d?.isError??!1)||iH(a.toolName)&&iK(d?.details),D=(n=d?.details)&&"object"==typeof n&&"pi-web-subagent"===n.kind&&"string"==typeof n.sessionId?d.details:null,B=M?M.calls.length+M.omitted:0;return(0,r.jsxs)("div",{style:{borderRadius:7,overflow:"hidden",fontSize:12,border:F?"1px solid rgba(248,113,113,0.45)":"1px solid rgba(34,197,94,0.25)",background:F?"rgba(248,113,113,0.05)":"rgba(34,197,94,0.04)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",minWidth:0},children:[(0,r.jsxs)("button",{onClick:()=>{var e;let t=!g;e=a.toolCallId,e&&(t?l3.add(e):l3.delete(e)),x(t)},style:{display:"flex",alignItems:"center",gap:7,flex:1,minWidth:0,padding:"6px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:[(0,r.jsx)("span",{title:A?a.toolName:void 0,style:{color:F?"#f87171":"#16a34a",fontFamily:"var(--font-mono)",fontWeight:600,fontSize:11,flexShrink:0},children:A?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{style:{fontWeight:500,opacity:.75},children:[A.server,"/"]}),A.tool]}):a.toolName}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:y?m("chat.generatingToolInput"):$??(M?function(e){for(let t of e.split(/\r?\n/)){let e=t.trim();if(e&&!e.startsWith("// @options:"))return e}return""}(M.code):function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2?arguments[2]:void 0;if(!e||"object"!=typeof e||Array.isArray(e))return"";let r=e=>{if(e.length<=120)return e;let t=e.charCodeAt(119);return e.slice(0,t>=55296&&t<=56319?119:120)};if("grep"===n||"find"===n){let t=ou(e.pattern);if(null!==t)return r(t)}for(let t of["command","path","file_path"]){let n=ou(e[t],"command"===t?" ":", ");if(null!==n)return r(n)}if(t)return r(t);for(let t of["pattern","query"]){let n=ou(e[t]);if(null!==n)return r(n)}let i=Object.values(e);for(let e of i){let t=ou(e);if(null!==t)return r(t)}for(let e of i){let t=function e(t){if(Array.isArray(t)){let n=t.map(t=>oc(t)??e(t)).filter(e=>null!==e);return n.length>0?n.join(", "):null}if(t&&"object"==typeof t)for(let n of Object.values(t)){let t=ou(n)??e(n);if(null!==t)return t}return null}(e);if(null!==t)return r(t)}return""}(a.input,S,a.toolName))}),B>0&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:1===B?m("codemode.callCountOne"):m("codemode.callCount",{count:B})}),void 0!==u?(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:oO(u)}):p&&(0,r.jsx)(oF,{clock:p},"startedAt"in p?p.startedAt:"ended"),(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:{flexShrink:0,transform:g?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),D&&h&&(0,r.jsx)("button",{type:"button",onClick:()=>h(D.sessionId,D.description||D.profile),title:m("subagent.openTab"),"aria-label":m("subagent.openTab"),style:{width:32,display:"grid",placeItems:"center",border:"none",borderLeft:"1px solid var(--border)",background:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},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:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]})})]}),g&&(y||!w||!d&&!c&&!E)&&!C&&(R?(0,r.jsx)("div",{style:{padding:"6px 10px 8px",background:"var(--bg-subtle)",borderTop:F?"1px solid rgba(248,113,113,0.25)":"1px solid rgba(34,197,94,0.2)"},children:(0,r.jsx)(an,{fields:R})}):(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,overflow:"auto",background:"var(--bg-subtle)",borderTop:F?"1px solid rgba(248,113,113,0.25)":"1px solid rgba(34,197,94,0.2)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:M?M.code.replace(/\r/g,"").trimEnd():b})),g&&M&&(0,r.jsx)(od,{calls:M.calls,omitted:M.omitted,isError:F}),W.length>0&&(0,r.jsx)(oX,{images:W,isError:F}),E&&(0,r.jsx)("div",{style:{borderTop:"1px solid rgba(34,197,94,0.15)",background:"var(--bg)"},children:(0,r.jsx)(o_,{files:E})}),g&&C&&(0,r.jsx)("div",{style:{borderTop:"1px solid rgba(34,197,94,0.15)",background:"var(--bg)"},children:(0,r.jsx)(o_,{files:C})}),g&&d&&C&&F&&(0,r.jsx)(oQ,{text:P??"",isEmpty:O,isError:F}),g&&d&&!C&&!T&&(k?(0,r.jsx)(oB,{diff:k}):(!O||0===W.length)&&(0,r.jsx)(oQ,{text:P??"",isEmpty:O,isError:F})),g&&d&&f]})}function oB(e){let{diff:t}=e;return(0,r.jsx)("div",{style:{borderTop:"1px solid rgba(34,197,94,0.15)",background:"var(--bg)"},children:(0,r.jsx)(oH,{text:t.text})})}function oH(e){let{text:t}=e,n=(0,i.useMemo)(()=>lY(t),[t]);return n?(0,r.jsx)(o_,{files:n}):(0,r.jsx)(oY,{text:t})}function o_(e){let{files:t}=e,n=tQ()?"stacked":"split";return(0,r.jsx)(oU,{files:t,layout:n})}function oU(e){let{files:t,layout:n}=e,{t:i}=(0,t_.s)(),s=t.length>1;return(0,r.jsx)("div",{style:{maxHeight:560,overflowY:"auto",overflowX:"hidden",background:"var(--bg)"},children:t.map((e,t)=>(0,r.jsxs)("div",{style:{minWidth:0,borderTop:0===t?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.55},children:[s&&"split"===n&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)(oZ,{title:e.oldPath||i("i18n.before"),side:"left"}),(0,r.jsx)(oZ,{title:e.newPath||i("i18n.after"),side:"right"})]}),s&&"stacked"===n&&oq(e)&&(0,r.jsx)("div",{title:oq(e),style:{position:"sticky",top:0,zIndex:1,padding:"5px 10px",color:"var(--text-dim)",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:oq(e)}),"split"===n&&(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)"},children:e.rows.map((e,t)=>"hunk"===e.type?null:"gap"===e.type?(0,r.jsx)(oK,{gap:e},t):(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)(oJ,{cell:e.left,side:"left"}),(0,r.jsx)(oJ,{cell:e.right,side:"right"})]},t))}),"stacked"===n&&lG(e).map((e,t)=>"gap"===e.type?(0,r.jsx)(oK,{gap:e},t):(0,r.jsx)(oV,{line:e},t))]},t))})}function oK(e){let{gap:t}=e,{t:n}=(0,t_.s)();return(0,r.jsx)("div",{style:{gridColumn:"1 / -1",padding:"0 10px",color:"var(--text-dim)",background:"var(--bg-panel)",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)",userSelect:"none"},children:null===t.count?"⋯":`⋯ ${lX(t.count,n)}`})}function oq(e){return e.newPath&&"/dev/null"!==e.newPath?e.newPath:e.oldPath||e.newPath||""}function oV(e){let{line:t}=e;return(0,r.jsx)(oJ,{side:"right",cell:{lineNo:"removed"===t.type?t.oldLineNo:t.newLineNo,text:t.text,type:t.type}})}function oZ(e){let{title:t,side:n}=e;return(0,r.jsx)("div",{title:t,style:{padding:"5px 10px",color:"var(--text-dim)",borderRight:"left"===n?"1px solid var(--border)":"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t})}function oJ(e){let{cell:t,side:n}=e,i="added"===t.type?"rgba(34,197,94,0.12)":"removed"===t.type?"rgba(248,113,113,0.13)":"empty"===t.type?"var(--bg-subtle)":"transparent",s="added"===t.type?"+":"removed"===t.type?"-":" ",l="added"===t.type?"#22c55e":"removed"===t.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",minWidth:0,background:i,borderRight:"left"===n?"1px solid var(--border)":"none"},children:[(0,r.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",flexShrink:0},children:t.lineNo??""}),(0,r.jsx)("span",{style:{width:18,padding:"0 5px",color:l,userSelect:"none",fontWeight:"context"===t.type||"empty"===t.type?400:700,flexShrink:0},children:s}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===t.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:t.text||"\xa0"})]})}function oY(e){let{text:t}=e,n=t.split(/\r?\n/);return(0,r.jsx)("div",{style:{maxHeight:520,overflowY:"auto",overflowX:"hidden",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.55,minWidth:0},children:n.map((e,t)=>{let n=e.startsWith("@@")?"hunk":e.startsWith("+")&&!e.startsWith("+++")?"added":e.startsWith("-")&&!e.startsWith("---")?"removed":"context";return(0,r.jsxs)("div",{style:{display:"flex",background:"added"===n?"rgba(34,197,94,0.12)":"removed"===n?"rgba(248,113,113,0.13)":"hunk"===n?"rgba(96,165,250,0.12)":"transparent",borderLeft:"added"===n?"3px solid #22c55e":"removed"===n?"3px solid #f87171":"hunk"===n?"3px solid var(--accent)":"3px solid transparent"},children:[(0,r.jsx)("span",{style:{width:48,padding:"0 8px",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",textAlign:"right",userSelect:"none",flexShrink:0},children:t+1}),(0,r.jsx)("span",{style:{padding:"0 10px",whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:"added"===n?"#22c55e":"removed"===n?"#f87171":"hunk"===n?"var(--accent)":"var(--text)"},children:e||"\xa0"})]},t)})})}function oG(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function oX(e){let{images:t,isError:n}=e;return(0,r.jsx)("div",{style:{display:"flex",gap:8,flexWrap:"wrap",padding:"10px",background:"var(--bg)",borderTop:`1px solid ${n?"rgba(248,113,113,0.3)":"rgba(34,197,94,0.15)"}`},children:t.map((e,t)=>{let n=o6(e);return n?(0,r.jsx)(sY,{src:n,style:{maxWidth:"100%"},children:(0,r.jsx)("img",{src:n,alt:"",loading:"lazy",style:{display:"block",maxWidth:"min(100%, 720px)",maxHeight:520,borderRadius:6,objectFit:"contain",border:"1px solid var(--border)"}})},`${n}-${t}`):null})})}function oQ(e){let{text:t,isEmpty:n,isError:i}=e,{t:s}=(0,t_.s)();return(0,r.jsx)("div",{style:{borderTop:`1px solid ${i?"rgba(248,113,113,0.3)":"rgba(34,197,94,0.15)"}`,background:i?"rgba(248,113,113,0.04)":"var(--bg-subtle)"},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:i?"#f87171":n?"var(--text-dim)":"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,overflow:"auto",maxHeight:400,background:"var(--bg)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontStyle:n?"italic":"normal",opacity:n?.6:1},children:n?s("i18n.noOutput"):t})})}function o0(e){let{message:t}=e,{t:n}=(0,t_.s)(),[s,l]=(0,i.useState)(!1),o=o3(t.content),a=oN(t.timestamp),d=t.details?.tokensBefore,c=og(t).find(e=>"summary_cost"===e.kind&&"compaction"===e.source);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:"compaction"}),a&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:a})]}),(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":s,title:n(s?"i18n.collapse":"i18n.expand"),onClick:()=>l(e=>!e),style:{display:"flex",alignItems:"flex-start",gap:8,width:"100%",padding:0,border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",font:"inherit",textAlign:"left"},children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:4,color:"var(--text-muted)",transform:s?"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},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:"calc(15px + var(--chat-font-size-offset, 0px))",fontWeight:700,lineHeight:1.35},children:n("i18n.conversationCompacted")}),"number"==typeof d&&Number.isFinite(d)&&(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:n("i18n.compactedFromTokens",{tokens:d.toLocaleString()})}),c&&(0,r.jsx)("span",{style:{display:"block",marginTop:2,color:ov,fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:oy(n,c)})]})]}),s&&(0,r.jsx)(o1,{summary:o})]})]})})}function o1(e){let{summary:t}=e,{t:n}=(0,t_.s)(),s=(0,i.useMemo)(()=>{let e,n,r,i,s;return e=[],n=[],r=t.match(lU),i=r?.[1]??"",s=r?.index===void 0?t:t.slice(0,r.index),i.replace(l_,(t,r,i)=>{let s=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...s):n.push(...s),""}),{body:s.trim(),readFiles:e,modifiedFiles:n}},[t]);return(0,r.jsxs)("div",{style:{marginTop:10},children:[s.body?(0,r.jsx)(lB,{className:"markdown-compaction-message",children:s.body}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:n("i18n.noSummary")}),(0,r.jsx)(o2,{readFiles:s.readFiles,modifiedFiles:s.modifiedFiles})]})}function o2(e){let{readFiles:t,modifiedFiles:n}=e,{t:i}=(0,t_.s)();if(0===t.length+n.length)return null;let s=[];return t.length>0&&s.push(`${t.length} read`),n.length>0&&s.push(`${n.length} modified`),(0,r.jsxs)("details",{className:"compaction-file-details",children:[(0,r.jsx)("summary",{children:i("i18n.fileContext",{details:s.join(", ")})}),n.length>0&&(0,r.jsx)(o4,{title:i("i18n.modifiedFiles"),files:n}),t.length>0&&(0,r.jsx)(o4,{title:i("i18n.readFiles"),files:t})]})}function o4(e){let{title:t,files:n}=e;return(0,r.jsxs)("div",{className:"compaction-file-section",children:[(0,r.jsx)("div",{className:"compaction-file-title",children:t}),(0,r.jsx)("ul",{className:"compaction-file-list",children:n.map(e=>(0,r.jsx)("li",{children:e},e))})]})}function o8(e){let{message:t,cwd:n,onOpenFile:s}=e,{t:l}=(0,t_.s)(),[o,a]=(0,i.useState)(!0),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=o3(t.content),f=o5(t.content),m=void 0!==t.details,g=m?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(t.details):"",x=t.customType||"extension",v=oN(t.timestamp);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:o?"1px solid var(--border)":"none",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:(0,r.jsxs)("button",{type:"button",onClick:()=>a(e=>!e),"aria-expanded":o,title:l(o?"i18n.collapse":"i18n.expand"),style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1,padding:0,border:"none",background:"none",color:"inherit",cursor:"pointer",fontSize:"inherit",textAlign:"left"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650,flexShrink:0},children:x}),!o&&h&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:h.slice(0,300).replace(/\s+/g," ").trim()}),v&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,flexShrink:0},children:v}),(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","aria-hidden":"true",style:{flexShrink:0,transform:o?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]})}),o&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[f.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!h},children:f.map((e,t)=>{let n=o6(e);return n?(0,r.jsx)(sY,{src:n,children:(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:6,objectFit:"contain",display:"block",border:"1px solid var(--border)"}})},t):null})}),h?(0,r.jsx)(lB,{className:"markdown-custom-message",keepTextLayout:!0,cwd:n,onOpenFile:s,children:h}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:l("i18n.noMessage")})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[h||g?(0,r.jsx)("button",{onClick:()=>{i0(h||g).then(()=>{p(!0),setTimeout(()=>p(!1),1500)},()=>{})},style:{padding:"3px 7px",border:"none",background:"none",color:u?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:l(u?"i18n.copied":"i18n.copy")}):null,m&&(0,r.jsx)("button",{onClick:()=>c(e=>!e),style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:l(d?"i18n.hideDetails":"i18n.showDetails")})]}),m&&d&&(0,r.jsx)("pre",{style:{margin:0,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto",fontFamily:"var(--font-mono)"},children:g})]})]})})}function o3(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function o5(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)}function o6(e){return e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:""}let o9=new Set(["path","file_path","content"]),o7={padding:"4px 12px 4px 0",color:"var(--text-dim)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",whiteSpace:"nowrap",verticalAlign:"top"},ae={padding:"4px 0",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},at={margin:0,padding:"8px 10px",maxHeight:260,overflow:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",font:"inherit",lineHeight:1.5,whiteSpace:"pre-wrap"};function an(e){let{fields:t}=e;return(0,r.jsx)("table",{style:{borderCollapse:"collapse"},children:(0,r.jsx)("tbody",{children:t.map(e=>(0,r.jsxs)("tr",{children:[(0,r.jsx)("td",{style:o7,children:e.key}),(0,r.jsx)("td",{style:ae,children:e.multiline?(0,r.jsx)("pre",{style:at,children:e.value}):e.value})]},e.key))})})}let ar={up:"M6 10.5V1.5M2.5 5 6 1.5 9.5 5",down:"M6 1.5v9M2.5 7 6 10.5 9.5 7",clock:"M6 1.25a4.75 4.75 0 1 0 0 9.5 4.75 4.75 0 1 0 0-9.5M6 3.5V6l1.75 1"},ai={fontSize:0};function as(e){let{part:t}=e;return t.icon?(0,r.jsxs)("span",{children:[t.before&&(0,r.jsx)("span",{style:ai,children:t.before}),(0,r.jsx)("svg",{width:"clock"===t.icon?10:9,height:"clock"===t.icon?10:9,viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,style:{display:"inline",verticalAlign:"clock"===t.icon?"-0.1em":"-0.05em",marginRight:"clock"===t.icon?3:1},children:(0,r.jsx)("path",{d:ar[t.icon]})}),t.text,t.after&&(0,r.jsx)("span",{style:ai,children:t.after})]}):(0,r.jsx)("span",{children:t.text})}function al(e){let{message:t,sessionId:n}=e,{t:s}=(0,t_.s)(),[l,o]=(0,i.useState)(null),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),p=!t.output&&void 0===t.exitCode&&!t.cancelled,h=t.cancelled||void 0!==t.exitCode&&0!==t.exitCode,f=n&&t.fullOutputPath?`/api/agent/${encodeURIComponent(n)}/bash-output?path=${encodeURIComponent(t.fullOutputPath)}`:null,m=null!==l,g=l??t.output;async function x(){if(f){d(!0),u(null);try{let e=await fetch(f),t=await e.json().catch(()=>null);t?.success?o(t.data?.output??""):u(s(413===e.status?"chat.fullOutputTooLarge":"chat.fullOutputUnavailable"))}catch{u(s("chat.fullOutputUnavailable"))}finally{d(!1)}}}let v=t.excludeFromContext?"bash (local)":"bash",b={type:"toolCall",toolCallId:`bash-${t.timestamp??""}`,toolName:v,input:{command:t.command}},y=p?void 0:{role:"toolResult",toolCallId:b.toolCallId,toolName:v,content:g?[{type:"text",text:g}]:[],isError:h,timestamp:t.timestamp},w={color:"var(--accent)",fontSize:11,textDecoration:"underline"},k=t.truncated&&f?(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"baseline",gap:"2px 10px",padding:"5px 10px",fontSize:11,color:"var(--text-dim)",borderTop:`1px solid ${h?"rgba(248,113,113,0.3)":"rgba(34,197,94,0.15)"}`},children:[(0,r.jsx)("span",{role:"status",children:c??s(m?"chat.fullOutputShown":"chat.outputTruncated")}),!m&&(0,r.jsx)("button",{type:"button",onClick:x,disabled:a,style:{...w,background:"none",border:"none",cursor:a?"default":"pointer",padding:0},children:a?s("chat.loadingFullOutput"):s("chat.viewFullOutput")}),(0,r.jsx)("a",{href:`${f}&download=1`,style:w,children:s("chat.downloadFullOutput")})]}):null;return(0,r.jsx)("div",{style:{margin:"6px 0"},children:(0,r.jsx)(oD,{block:b,result:y,resultFooter:k})})}let ao=/^([ \t]*)([-*+])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,aa=/^([ \t]*)(\d{1,9})([.)])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,ad=/^([ \t]*)(\d{1,3})(、)([ \t]*)/,ac=/^[ \t]*([-*_])(?:[ \t]*\1){2,}[ \t]*$/,au=/^[ \t]{0,3}(`{3,}|~{3,})/;function ap(e){let t=e.trim().split("\n").map(e=>`> ${e}`).join("\n");return`${t}
7
+
8
+ `}function ah(e){return!e.trim()||e.endsWith("\n\n")?"":e.endsWith("\n")?"\n":"\n\n"}function af(e){return"mcp"===e.name&&e.sourceInfo?.path==="builtin:mcp"}function am(e){return"/mcp"===e.trim()}let ag="pi-enter-send-mode",ax="enter",av=null,ab=new Set;function ay(){return null===av&&(av=function(){try{let e=window.localStorage.getItem(ag);return"ctrlEnter"===e?"ctrlEnter":"enter"}catch{return ax}}()),av}function aw(e){return ab.add(e),()=>{ab.delete(e)}}function ak(e){av=e;try{window.localStorage.setItem(ag,e)}catch{}ab.forEach(e=>e())}function aj(){return(0,i.useSyncExternalStore)(aw,ay,()=>ax)}let aS="pi-chat-content-width",aC="pi-chat-content-font-size",aN={width:820,fontSize:14},aE=null,a$=new Set;function aI(e){let t=Number(e);return Number.isFinite(t)?Math.max(820,Math.min(2e3,Math.round(t))):820}function aM(e){let t=Number(e??14);return Number.isFinite(t)?Math.max(12,Math.min(24,Math.round(t))):14}function aT(e){try{return window.localStorage.getItem(e)}catch{return null}}function aR(e){let{width:t,fontSize:n}=e;"u">typeof document&&(document.documentElement.style.setProperty("--chat-content-max-width",`${t}px`),document.documentElement.style.setProperty("--chat-content-font-size",`${n}px`))}function aA(){return aE||aR(aE={width:aI(aT(aS)),fontSize:aM(aT(aC))}),aE}function aL(e){return a$.add(e),()=>{a$.delete(e)}}function az(e,t){let n="width"===e?aI(t):aM(t);aR(aE={...aA(),[e]:n});try{window.localStorage.setItem("width"===e?aS:aC,String(n))}catch{}a$.forEach(e=>e())}let aP=e=>az("width",e),aW=e=>az("fontSize",e);function aO(){return{...(0,i.useSyncExternalStore)(aL,aA,()=>aN),setWidth:aP,setFontSize:aW}}let aF=[{value:100,label:"settings.fontWeightThin"},{value:200,label:"settings.fontWeightExtraLight"},{value:300,label:"settings.fontWeightLight"},{value:400,label:"settings.fontWeightRegular"},{value:500,label:"settings.fontWeightMedium"},{value:600,label:"settings.fontWeightSemiBold"}],aD={ui:"pi-ui-font-family",mono:"pi-mono-font-family",uiWeight:"pi-ui-font-weight",monoWeight:"pi-mono-font-weight"},aB={ui:"",mono:"",uiWeight:400,monoWeight:400};function aH(e){let t="string"==typeof e?Number(e):e;return aF.find(e=>e.value===t)?.value??400}function a_(e){return"string"==typeof e&&e.length<=500?e:""}let aU=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded"]),aK=["ui","mono"],aq=Object.keys(aD),aV=null,aZ=new Set;function aJ(){let e={...aB};for(let t of aK)try{e[t]=a_(window.localStorage.getItem(aD[t]));let n=`${t}Weight`;e[n]=aH(window.localStorage.getItem(aD[n]))}catch{}return e}function aY(e){for(let t of aK){let n=`--font-${t}`,r=function(e,t){let n=a_(t).split(",").flatMap(e=>{let t=e.trim().replace(/\s+/g," "),n=t.length>=2&&('"'===t[0]||"'"===t[0])&&t.endsWith(t[0]);return(n&&(t=t.slice(1,-1).trim()),t)?[!n&&aU.has(t.toLowerCase())?t.toLowerCase():JSON.stringify(t)]:[]}).join(", ");return n?`${n}, var(--font-${e}-default)`:""}(t,e[t]);r?document.documentElement.style.setProperty(n,r):document.documentElement.style.removeProperty(n);let i=e[`${t}Weight`];400===i?document.documentElement.style.removeProperty(`${n}-weight`):document.documentElement.style.setProperty(`${n}-weight`,String(i))}}function aG(){return aV||aY(aV=aJ()),aV}function aX(){aZ.forEach(e=>e())}function aQ(e){if(null!==e.key&&!Object.values(aD).includes(e.key))return;let t=aJ(),n=aG();aq.every(e=>t[e]===n[e])||(aV=t,aY(t),aX())}function a0(e){return 0===aZ.size&&window.addEventListener("storage",aQ),aZ.add(e),aG(),()=>{aZ.delete(e),0===aZ.size&&window.removeEventListener("storage",aQ)}}function a1(e){let t=aG(),n=aq.filter(n=>t[n]!==e[n]);if(n.length){for(let t of(aV=e,aY(e),n))try{e[t]===aB[t]?window.localStorage.removeItem(aD[t]):window.localStorage.setItem(aD[t],String(e[t]))}catch{}aX()}}function a2(e,t){a1({...aG(),[e]:a_(t)})}function a4(e,t){a1({...aG(),[`${e}Weight`]:aH(t)})}function a8(e){a1({...aG(),[e]:"",[`${e}Weight`]:400})}function a3(){return{...(0,i.useSyncExternalStore)(a0,aG,()=>aB),setFontPreference:a2,setFontWeight:a4,resetFontPreference:a8}}function a5(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 a6(e){let{active:t,onSelect:n,star:s,gutter:l=!!s,children:o}=e,a=tQ(),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=!!(s&&!s.isDefault),f=h&&(d||u||a);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:l?"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)(a5,{filled:!0,size:10})}),s&&h&&(0,r.jsx)("button",{type:"button",title:s.saveLabel,"aria-label":s.saveLabel,tabIndex:f?0:-1,onClick:e=>{e.stopPropagation(),s.onSave()},style:{position:"absolute",top:"50%",right:6,transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,padding:0,background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",opacity:+!!f,pointerEvents:f?"auto":"none",transition:"opacity 0.1s, background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="rgba(37,99,235,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},children:(0,r.jsx)(a5,{filled:!1,size:12})})]})}function a9(e){var t;let n,s,l,o,a,d,c,u,p,h,f,{options:m,value:g,onChange:x,onReselect:v,onClear:b,emptyLabel:y,selectedLabel:w,disabled:k=!1,busy:j=!1,isAutoSelection:S=!1,ariaLabel:C,variant:N="toolbar",placement:E="up",defaultValue:$,onSetDefault:I,allOptions:M,onShowAll:T}=e,{t:R}=(0,t_.s)(),A=tQ(),L=(0,i.useRef)(null),z=(0,i.useRef)(null),[P,W]=(0,i.useState)(!1),[O,F]=(0,i.useState)(null),[D,B]=(0,i.useState)(""),[H,_]=(0,i.useState)(!1),U=k||j,K=H?M:m,q=(t=K??[],(n=D.trim().toLocaleLowerCase())?t.filter(e=>`${e.name} ${e.providerName??""} ${e.modelId} ${e.provider}/${e.modelId}`.toLocaleLowerCase().includes(n)):t),V=!!T||m.length>8,Z=(e,t)=>e?.find(e=>e.modelId===t.modelId&&e.provider===t.provider),J=()=>{H||T?.(),_(!H)},Y=function(e){let t=[];for(let n of e){let e=t.find(e=>e.provider===n.provider);e?(e.options.push(n),e.providerName===e.provider&&n.providerName?.trim()&&(e.providerName=n.providerName.trim())):t.push({provider:n.provider,providerName:n.providerName?.trim()||n.provider,options:[n]})}return t}(q),G=w??(g?(Z(m,g)??Z(M,g))?.name??g.modelId:y??(m.length>0?R("chat.selectModel"):R("chat.noModels")));(0,i.useEffect)(()=>{let e=e=>{L.current&&!L.current.contains(e.target)&&z.current&&!z.current.contains(e.target)&&(W(!1),B(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{if(!P)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)}},[P]),(0,i.useEffect)(()=>{U&&(W(!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:P?"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&&P&&(e.preventDefault(),e.stopPropagation(),B(""),W(!1))},children:[(0,r.jsxs)("button",{type:"button","aria-label":C,"aria-haspopup":"listbox","aria-expanded":P,"aria-busy":j||void 0,disabled:U,title:j?R("chat.switchingModel"):U?G:m.length>0||b?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}),W(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=P?"var(--bg-hover)":"field"===N?"var(--bg)":"none",e.currentTarget.style.color="field"===N?"var(--text)":"var(--text-muted)"},children:[j?(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:G}),"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"})})]}),P&&O&&(s=window.visualViewport?.offsetTop??0,l=window.visualViewport?.height??window.innerHeight,o=window.visualViewport?.width??window.innerWidth,d=(a=Math.min(O.top-6,s+l-8))-s-8,c=s+l-O.bottom-6-8,p=Math.max(120,Math.min((u="up"===E||d>c)?d:c,.6*l)),h=u?{top:a,transform:"translateY(-100%)"}:{top:O.bottom+6},f=A?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:O.left,width:"max-content",minWidth:O.width,maxWidth:Math.max(O.width,o-O.left-8)},(0,r.jsxs)("div",{ref:z,role:"listbox","aria-label":C,style:{position:"fixed",...h,...f,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:[T&&(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"})]}),V&&(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=>{T&&"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:[b&&!D.trim()&&(0,r.jsx)(a6,{active:!g,gutter:!!I,onSelect:()=>{W(!1),B(""),b()},children:(0,r.jsx)(a7,{label:y??R("i18n.default")})}),0===Y.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:K?D.trim()?R("chat.noMatchingModels"):R("chat.noAvailableModels"):R("agents.modelsLoading")}):Y.map((e,t)=>(0,r.jsxs)("div",{children:[Y.length>1&&(0,r.jsx)("div",{title:e.providerName===e.provider?void 0:e.provider,style:{padding:"6px 12px 4px",borderTop:t>0||b?"1px solid var(--border)":"none",color:"var(--text-dim)",fontSize:10,fontWeight:600,letterSpacing:0,textTransform:e.providerName===e.provider?"uppercase":"none"},children:e.providerName}),e.options.map(e=>(0,r.jsx)(a6,{active:e.modelId===g?.modelId&&e.provider===g?.provider,onSelect:()=>{let t;return t=e.modelId===g?.modelId&&e.provider===g?.provider,void(W(!1),B(""),!t||S?x(e.provider,e.modelId):v?.(e.provider,e.modelId))},star:I&&(!H||Z(m,e))?{isDefault:e.modelId===$?.modelId&&e.provider===$?.provider,saveLabel:R("chat.saveDefaultModel"),defaultLabel:R("chat.defaultModel"),onSave:()=>{W(!1),B(""),I?.(e.provider,e.modelId)}}:void 0,children:(0,r.jsx)(a7,{label:e.name})},`${e.provider}:${e.modelId}`))]},e.provider))]})]}))]})}function a7(e){let{label:t}=e;return(0,r.jsx)("span",{title:t,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})}let de=["configured","chat-only","read-only","default","full"],dt={configured:"configured","chat-only":"none","read-only":"read-only",default:"default",full:"full"},dn=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function dr(e,t,n){return t<=0?0:((e+n)%t+t)%t}function di(e,t,n,r){e.setRangeText(r,t,n,"end"),e.dispatchEvent(new Event("input",{bubbles:!0}))}function ds(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:r.length,s=e.selectionStart,l=e.selectionEnd;if(e.focus(),s===l&&t<=s&&n>=l){let i=e.value.length-(n-t)+r.length;for(let n=s-t;n>0&&e.selectionStart>t&&document.execCommand("delete");n--);if(document.execCommand("insertText",!1,r))for(let t=n-l;t>0&&e.value.length>i&&document.execCommand("forwardDelete");t--);else di(e,t,e.selectionStart+(n-l),r)}else e.setSelectionRange(t,n),document.execCommand("insertText",!1,r)||di(e,t,n,r);i!==r.length&&e.setSelectionRange(t+i,t+i)}function dl(e){let t=e.scrollTop;e.style.height="auto",e.style.height=`${e.value?Math.min(e.scrollHeight,200):e.clientHeight}px`,e.style.overflowY=e.value&&e.scrollHeight>e.clientHeight?"auto":"hidden",e.scrollTop=t}function da(e){e.selectionEnd===e.value.length&&(e.scrollTop=e.scrollHeight)}function dd(e,t){let n=null,r=()=>{n=null,t(function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8;return Math.max(0,Math.floor(e-t-n))}(e.getBoundingClientRect().bottom,function(e){let t=window.visualViewport?.offsetTop??0;for(let n=e.parentElement;n;n=n.parentElement){let e=window.getComputedStyle(n).overflowY;("auto"===e||"scroll"===e||"hidden"===e||"clip"===e)&&(t=Math.max(t,n.getBoundingClientRect().top+n.clientTop))}return t}(e)))},i=()=>{null!==n&&cancelAnimationFrame(n),n=requestAnimationFrame(r)};r();let s=e.parentElement,l=s?.parentElement,o="u">typeof ResizeObserver&&s?new ResizeObserver(i):null;s&&o?.observe(s),l&&o?.observe(l);let a=window.visualViewport;return a?.addEventListener("resize",i),a?.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("scroll",i,!0),()=>{o?.disconnect(),a?.removeEventListener("resize",i),a?.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("scroll",i,!0),null!==n&&cancelAnimationFrame(n)}}let dc=["auto","off","minimal","low","medium","high","xhigh","max"],du={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 dp(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let dh=[{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 df(e){return function(e){let t=e.trim().match(/^\/([^\s]+)(?:\s|$)/);if(t)return dh.find(e=>e.name===t[1])}(e)?.availableWhileStreaming===!0}let dm=["builtin","extension","prompt","skill"],dg={builtin:"chat.builtIn",extension:"chat.extensions",prompt:"chat.prompts",skill:"chat.skills"},dx={builtin:0,extension:1,prompt:2,skill:3};function dv(e,t){return"builtin"===e.source?t(e.description):e.description??""}function db(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function dy(e){return{data:e.data,mimeType:e.mimeType}}function dw(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function dk(e){return(e??[]).filter(p).slice(0,10).map(dw)}function dj(e){return"string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function dS(e){return"string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,n=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof n)return[];let r={data:t,mimeType:n};return p(r)?[r]:[]})}function dC(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function dN(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 dE(e){let{tone:t,title:n,body:i,onClose:s,children:l}=e,{t:o}=(0,t_.s)(),a="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(${a},0.3)`,borderRadius:6,background:`rgba(${a},0.07)`,color:`rgb(${a})`,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}),l]}),s&&(0,r.jsx)("button",{type:"button",onClick:s,"aria-label":o("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 d$(e){let{cwd:t,onFork:n}=e,{t:i}=(0,t_.s)();return t?(0,r.jsx)(dE,{tone:"error",title:i("chat.cwdMissingTitle"),body:i("chat.cwdMissingBody",{cwd:t}),children:n&&(0,r.jsx)("button",{type:"button",onClick:n,style:{display:"block",marginTop:6,padding:"2px 8px",border:"1px solid currentColor",borderRadius:5,background:"transparent",color:"inherit",cursor:"pointer",font:"inherit"},children:i("chat.cwdMissingFork")})}):null}function dI(e){let{error:t}=e,{t:n}=(0,t_.s)();return t?(0,r.jsx)(dE,{tone:"error",title:n("chat.modelError"),body:t}):null}function dM(e){let{warnings:t}=e,{t:n}=(0,t_.s)();return t&&0!==t.length?(0,r.jsx)(dE,{tone:"warning",title:n(t.length>1?"chat.modelScopeWarnings":"chat.modelScopeWarning"),body:t.join("\n")}):null}let dT=(0,i.memo)((0,i.forwardRef)(function(e,t){let n,s,l,o,a,{onSend:d,onAbort:c,onSteer:u,onSideChat:p,onFollowUp:h,isStreaming:f,model:m,isAutoModelSelection:g,modelNames:x,modelList:v,modelError:b,missingCwd:y,onForkMissingCwd:w,modelScopeWarnings:k,allModelList:j,onLoadAllModels:S,onModelChange:C,modelSwitching:N,defaultModel:E,onSetDefaultModel:$,onCompact:M,onAbortCompaction:T,isCompacting:W,compactError:F,onDismissCompactError:D,compactResult:B,toolPreset:H,onToolPresetChange:_,thinkingLevel:U,isAutoThinkingSelection:K=!1,onThinkingLevelChange:q,availableThinkingLevels:V,thinkingLevelMap:Z,savedDefaultThinkingLevel:J,onSetDefaultThinkingLevel:Y,retryInfo:G,queuedMessages:X,inputHistory:Q=[],onRecallQueue:ee,slashCommands:et,slashCommandsLoading:en,onLoadSlashCommands:er,extensionUiOpen:ei=!1,onBuiltinCommand:es,soundEnabled:el,onSoundToggle:eo,onAudioUnlock:ea,onPromptWithStreamingBehavior:ed,draftKey:ec,cwd:eu,onAttachFiles:ep,compact:eh=!1}=e,{t:ef}=(0,t_.s)(),{fontSize:em}=aO(),{ui:eg,uiWeight:ex}=a3(),ev=tQ(),eb=ev?44:32,ey=aj(),[ew,ek]=(0,i.useState)(()=>ec?R(ec)?.value??"":""),[ej,eS]=(0,i.useState)(!1),[eC,eN]=(0,i.useState)(!1),[eE,e$]=(0,i.useState)(!1),[eI,eM]=(0,i.useState)(()=>ec?dk(R(ec)?.images):[]),eT=ew.trimStart(),eR=0===eI.length&&eT.startsWith("!"),eA=eR&&eT.startsWith("!!"),[eL,ez]=(0,i.useState)(!1),[eP,eW]=(0,i.useState)(0),[eO,eF]=(0,i.useState)(null),[eD,eB]=(0,i.useState)(null),[eH,e_]=(0,i.useState)(!1),[eU,eK]=(0,i.useState)(null),[eq,eV]=(0,i.useState)(0),[eZ,eJ]=(0,i.useState)(!1),[eY,eG]=(0,i.useState)(!1),[eX,eQ]=(0,i.useState)(0),[e0,e1]=(0,i.useState)(!1),e2=(0,i.useRef)(!1),e4=(0,i.useRef)(null),[e8,e3]=(0,i.useState)(null),[e5,e6]=(0,i.useState)(!1),[e9,e7]=(0,i.useState)(null),[te,tt]=(0,i.useState)(null),tn=eu&&te?.cwd===eu?te.values:{},tr=(0,i.useRef)(null),ti=(0,i.useRef)(null),ts=(0,i.useRef)(null),tl=(0,i.useRef)(null),to=(0,i.useRef)(null),ta=(0,i.useRef)(null),td=(0,i.useRef)(!1),tc=(0,i.useRef)(0),tu=(0,i.useRef)(null),tp=(0,i.useRef)(!1),th=(0,i.useRef)(null),tf=(0,i.useRef)([]),tm=(0,i.useRef)(null),tg=(0,i.useRef)([]),tx=(0,i.useRef)([]),tv=(0,i.useRef)(null),tb=(0,i.useRef)(null),ty=(0,i.useRef)(ec),tw=(0,i.useRef)(ew),tk=(0,i.useRef)(eI),tj=(0,i.useRef)(0);tw.current=ew,tk.current=eI,(0,i.useImperativeHandle)(t,()=>({setText(e){let t=tr.current;if(!t){tw.current=e,ek(e);return}t.setSelectionRange(0,t.value.length),ds(t,0,t.value.length,e),eB(null),requestAnimationFrame(()=>dl(t))},pasteText(e){if(!e)return;let t=tr.current;t?(ds(t,t.selectionStart??t.value.length,t.selectionEnd??t.value.length,e),eB(null),requestAnimationFrame(()=>dl(t))):ek(t=>t+e)},insertIfEmpty(e){let t=tr.current;(t?t.value:ew).trim()||(tw.current=e,ek(e),eB(null),requestAnimationFrame(()=>{t&&(t.focus(),dl(t),da(t))}))},replaceMessage(e){var t,n,r;let i=tr.current;if(t=i?i.value:ew,n=tk.current.length,r=tj.current,t.trim()||0!==n||0!==r)return;let s=dj(e),l=dk(dS(e));tw.current=s,tk.current=l,ek(s),eB(null),eG(!1),eM(e=>(e.forEach(dC),l)),requestAnimationFrame(()=>{i&&(i.focus(),dl(i),da(i))})},prependText(e){if(!e.trim())return;let t=tr.current,n=[e,t?t.value:ew].filter(e=>e.trim()).join("\n\n");tw.current=n,ek(n),eB(null),requestAnimationFrame(()=>{t&&(t.focus(),t.setSelectionRange(n.length,n.length),dl(t),da(t))})},rekeyDraft(e,t){if(e===t)return;if(ty.current!==e)return void O(e,t);let n={value:tw.current,images:tk.current.map(dy)},r=O(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(ty.current=t,i)return;let s=dk(r.images);tw.current=r.value,tk.current=s,ek(r.value),eM(e=>(e.forEach(dC),s)),eB(null),eG(!1)},restoreSubmission(e,t,n){if(!e.trim()&&!t?.length)return;let r=ty.current,i=n??r,s=i===r,l=!s&&i?R(i):null,o=P(e,t,s?tw.current:l?.value??"",s?tk.current.map(dy):l?.images??[]);if(i&&A(i,o),!s)return;let a=t?.length?[...dk(t).slice(0,Math.max(0,10-tk.current.length)),...tk.current].slice(0,10):tk.current;tw.current=o.value,tk.current=a,ek(t=>{let n=z(e,t);return tw.current=n,n}),eB(null),eG(!1),t?.length&&eM(e=>{let n=Math.max(0,10-e.length),r=dk(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tk.current=i,i}),requestAnimationFrame(()=>{let e=tr.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),dl(e),da(e))})},focus(){let e=tr.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length))},insertText(e){let t=tr.current;if(!t)return void ek(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n);ds(t,n,r,(i.length>0&&!i.endsWith(" ")?" ":"")+e),eB(null)},insertQuote(e){let t=tr.current;if(!t)return void ek(t=>t+ah(t)+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length;ds(t,n,r,ah(t.value.slice(0,n))+e),eB(null)},addImages(e){tS(e)}}));let tS=(0,i.useCallback)(async e=>{if(eh)return;let t=Math.max(0,10-tk.current.length-tj.current),n=e.filter(e=>e.type.startsWith("image/")&&e.size<=0xa00000).slice(0,t);if(n.length){tj.current+=n.length;try{let e=await Promise.all(n.map(async e=>{var t;return{...await (t=e.type,new Promise((n,r)=>{let i=new FileReader;i.onload=()=>{let e="string"==typeof i.result?i.result.split(",")[1]:void 0;e?n({data:e,mimeType:t}):r(Error("Failed to read image"))},i.onerror=r,i.readAsDataURL(e)})),previewUrl:URL.createObjectURL(e)}}));eM(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(dC);let r=[...t,...n];return tk.current=r,r})}finally{tj.current-=n.length}}},[eh]),tC=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",ep?ep(t):tS(t)},[ep,tS]),tN=(0,i.useCallback)(e=>{eM(t=>{let n=[...t],[r]=n.splice(e,1);return r&&dC(r),tk.current=n,n})},[]),tE=(0,i.useCallback)(()=>{tk.current=[],eM(e=>(e.forEach(dC),[]))},[]),t$=(0,i.useCallback)(()=>{tw.current="",ek(""),eB(null),eG(!1),ec&&L(ec),ty.current&&ty.current!==ec&&L(ty.current),tE(),tr.current&&(tr.current.style.height="auto")},[tE,ec]);(0,i.useEffect)(()=>{ec&&ty.current===ec&&A(ec,{value:ew,images:eI.map(dy)})},[eI,ec,ew]),(0,i.useEffect)(()=>{let e=ty.current;if(e===ec)return;e&&A(e,{value:tw.current,images:tk.current.map(dy)});let t=ec?R(ec):null;ty.current=ec;let n=t?.value??"",r=dk(t?.images);tw.current=n,tk.current=r,ek(n),eB(null),eG(!1),eM(e=>(e.forEach(dC),r))},[ec]);let tI=(0,i.useCallback)(()=>{let e=tr.current;e&&(e.value?dl(e):(e.style.height="auto",e.style.overflowY="hidden"))},[]);(0,i.useLayoutEffect)(tI,[ew,em,eg,ex,tI]),(0,i.useEffect)(()=>{let e=tr.current;if(!e)return;let t=-1,n=new ResizeObserver(e=>{let[n]=e;n.contentRect.width!==t&&(t=n.contentRect.width,tI())});return n.observe(e),()=>n.disconnect()},[tI]),(0,i.useEffect)(()=>{let e=tr.current;if(!e)return;let t=t=>{if("insertLineBreak"!==t.inputType||t.isComposing)return;let n=function(e,t,n){let r;if(t!==n)return null;let i=e.lastIndexOf("\n",t-1)+1,s=e.indexOf("\n",t),l=-1===s?e.length:s,o=e.slice(i,l),a=function(e){if(ac.test(e))return null;let t=ao.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=aa.exec(e)??ad.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!a||t-i<a.length||function(e){let t=null;for(let n of e.split("\n")){let e=au.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(a.length).trim()?{start:i,end:l,text:""}:{start:t,end:t,text:`
9
+ ${r=null===a.number?a.marker:`${String(Number(a.number)+1).padStart(a.number.length,"0")}${a.delimiter}`,`${a.indent}${r}${a.spacing}${a.task?"[ ] ":""}`}`}}(e.value,e.selectionStart,e.selectionEnd);n&&(t.preventDefault(),e.setSelectionRange(n.start,n.end),document.execCommand(n.text?"insertText":"delete",!1,n.text))};return e.addEventListener("beforeinput",t),()=>e.removeEventListener("beforeinput",t)},[]),(0,i.useEffect)(()=>()=>{tk.current.forEach(dC)},[]),(0,i.useLayoutEffect)(()=>{if(e0){let e=e=>{e.target!==e4.current&&(e4.current=null)};return document.addEventListener("pointerdown",e,!0),()=>document.removeEventListener("pointerdown",e,!0)}let e=e4.current;e4.current=null,e?.isConnected&&document.activeElement===document.body&&!document.querySelector('[aria-modal="true"]')&&e.focus({preventScroll:!0})},[e0]);let tM=(0,i.useCallback)(async e=>{if(eI.length||!e.startsWith("/")||!es)return!1;if(e2.current)return!0;e4.current=document.activeElement===tr.current?tr.current:null,e2.current=!0,e1(!0);let t=ty.current?I(ty.current):null;try{var n,r;let t=await es(e);if(!t.handled)return!1;return t.error||(n=tw.current,r=tk.current.length,0!==r||n.trim()!==e)||t$(),!0}finally{t?.(),e2.current=!1,e1(!1)}},[eI.length,t$,es]),tT=(0,i.useCallback)(async()=>{var e;let t=ew.trim();(t||eI.length)&&(ea?.(),(!f||df(e=t)||am(e))&&await tM(t)||(!f||t.startsWith("!")&&!eI.length)&&(t$(),d(t,eI.length?eI:void 0)))},[ew,eI,f,tM,d,t$,ea]),tR=!eh&&ew.startsWith("/")&&!/\s/.test(ew.slice(1))?ew.slice(1).toLowerCase():null,tA=(()=>{var e;let t,n;return null===tR?[]:(e=[...f?dh.filter(e=>e.availableWhileStreaming):dh,...et??[]],((n=(t=e.map(e=>{let t,n;return{command:e,rank:(t=e.name.toLowerCase(),(n="skill"===e.source&&t.startsWith("skill:")?t.slice(6):t)===tR||t===tR?0:n.startsWith(tR)||t.startsWith(tR)?1:t.includes(tR)?2:3)}})).filter(e=>{let{rank:t}=e;return t<3})).length>0?n:t.filter(e=>{let{command:t}=e;return dv(t,ef).toLowerCase().includes(tR)})).sort((e,t)=>e.rank-t.rank||dx[e.command.source]-dx[t.command.source]||dn.compare(e.command.name,t.command.name)).map(e=>{let{command:t}=e;return t}))})(),{commands:tL,groups:tz}=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",r=0,i=dm.map(i=>{let s=e.filter(e=>e.source===i),l="skill"!==i||n?s:[...s.filter(e=>!db(e,t)),...s.filter(e=>db(e,t))];return{source:i,items:l.map(e=>({command:e,index:r++}))}}).filter(e=>e.items.length>0);return{commands:i.flatMap(e=>e.items.map(e=>{let{command:t}=e;return t})),groups:i}}(tA,tn,tR??""),tP=1===tA.length?ef(tR?"chat.match":"chat.command"):ef(tR?"chat.matches":"chat.commands",{count:tA.length}),tW=!!ew.trim()||eI.length>0,tO=eh||ev&&f,tF=eI.length>0&&!function(e,t){if(!e)return!0;let n=t?.find(t=>t.provider===e.provider&&t.id===e.modelId);return!n||!n.input||n.input.includes("image")}(m,v)&&!eZ;(0,i.useEffect)(()=>{0===eI.length&&eJ(!1)},[eI.length]);let tD=(0,i.useCallback)((e,t)=>{if(!eu)return void eB(null);let n=t??e.length;eB(nj(e.slice(0,n)))},[eu]),tB=eD?.query??null,tH=i.useMemo(()=>null!==tB&&e8&&e8.cwd===eu?function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:20,r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:nC(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),i=-1===e?n:n.slice(e+1);i===t?r=100:i.startsWith(t)?r=80:i.includes(t)?r=50:n.includes(t)?r=30:nC(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||nS(e.entry.path)-nS(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(e8.entries,tB):[],[tB,e8,eu]),tU=!!(tB&&e8?.truncated&&e8.cwd===eu);(0,i.useEffect)(()=>{if(!tU||!eu||!tB)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(eu)}&q=${encodeURIComponent(tB)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>e7({cwd:eu,query:tB,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tU,tB,eu]);let tK=tU&&null!==e9&&e9.cwd===eu&&e9.query===tB,tq=tK?e9.matches:tH,tV=null===eD?null:`${eD.start}:${+!!eD.quoted}:${eD.query}`;(0,i.useEffect)(()=>{if(null===tV){e_(!1),eV(0);return}e_(!0),eV(0)},[tV]);let tZ=null!==eD;(0,i.useEffect)(()=>{if(!tZ||!eu)return;let e=tv.current;e&&e.cwd===eu&&Date.now()-e.fetchedAt<1e4||tb.current===eu||(tb.current=eu,e6(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(eu)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{e3({cwd:eu,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>nS(e.path)-nS(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tv.current={cwd:eu,fetchedAt:Date.now()}}).catch(()=>{tv.current=null}).finally(()=>{tb.current=null,e6(!1)}))},[tZ,eu]);let tJ=(0,i.useCallback)(e=>{if(!eD)return;let t=tr.current;if(!t)return;let n=t.selectionStart??t.value.length,r=n+(eD.quoted&&'"'===t.value[n]?1:0),i=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let s=i?`@"${r}" `:`@${r} `;return{text:s,cursorOffset:s.length}}(e.path,e.isDir,eD.quoted),s=eD.start+i.cursorOffset;ds(t,eD.start,r,i.text,i.cursorOffset),eB(nj(t.value.slice(0,s)))},[eD]);(0,i.useEffect)(()=>{eq>=tq.length&&eV(Math.max(0,tq.length-1))},[tq.length,eq]),(0,i.useEffect)(()=>{tg.current.length=tq.length},[tq.length]),(0,i.useEffect)(()=>{eH&&tg.current[eq]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eq,eH]),(0,i.useEffect)(()=>{eX>=Q.length&&eQ(Math.max(0,Q.length-1))},[Q.length,eX]),(0,i.useEffect)(()=>{tx.current.length=Q.length},[Q.length]),(0,i.useEffect)(()=>{eY&&!ei&&tx.current[eX]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eX,eY,ei]);let tY=(0,i.useCallback)(e=>{ek(e),eG(!1),eQ(0),eB(null),requestAnimationFrame(()=>{let t=tr.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),dl(t),da(t))})},[]),tG=(0,i.useCallback)(e=>{let t=`/${e.name} `;ek(t),ez(!1),eW(0),requestAnimationFrame(()=>{let e=tr.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),dl(e))})},[]),tX=(0,i.useCallback)(()=>{let e=ew.trim();e&&!eI.length&&p&&(t$(),p(e))},[ew,eI,p,t$]),t0=(0,i.useCallback)(e=>{let t=ew.trim();if(!t&&!eI.length)return;if(t.startsWith("!")&&!eI.length)return void tT();ea?.();let n=eI.length?eI:void 0,r=()=>{if(t.startsWith("/")&&ed){t$(),ed(t,"steer"===e?"steer":"followUp",n);return}t$(),"steer"===e&&u?u(t,n):"followup"===e&&h&&h(t,n)};!eI.length&&es&&df(t)?tM(t):!eI.length&&es&&am(t)?tM(t).then(e=>{e||r()},()=>r()):r()},[ew,eI,es,ed,u,h,t$,ea,tM,tT]),t1=(0,i.useCallback)(e=>{let t=tL.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eP-1);if("right"===e)return Math.min(t,eP+1);let n=tf.current[eP];if(!n)return"down"===e?Math.min(t,eP+1):Math.max(0,eP-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,s=r.top+r.height/2,l=-1,o=1/0;for(let n=0;n<=t;n+=1){if(n===eP)continue;let t=tf.current[n];if(!t)continue;let r=t.getBoundingClientRect(),a=r.top+r.height/2-s;if("down"===e?a<=4:a>=-4)continue;let d=1e3*Math.abs(a)+Math.abs(r.left+r.width/2-i);d<o&&(l=n,o=d)}return l>=0?l:"down"===e?Math.min(t,eP+1):Math.max(0,eP-1)},[tL.length,eP]),t2=(0,i.useCallback)(e=>{let t=e.nativeEvent,n="Enter"===e.key&&!e.shiftKey,r=ev||"ctrlEnter"===ey?n&&(e.ctrlKey||e.metaKey):n,i=ev?r:n,s=Date.now()-tc.current<100,l=td.current||t.isComposing||229===t.keyCode;if(i&&(l||s)){s&&e.preventDefault();return}if(eY&&!ei&&!l){if("ArrowDown"===e.key){e.preventDefault(),eQ(e=>Math.min(Math.max(0,Q.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eQ(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),eG(!1);return}if(("Tab"===e.key||i)&&Q[eX]){e.preventDefault(),tY(Q[eX]);return}}if(eL&&null!==tR&&!ei){if("ArrowDown"===e.key){e.preventDefault(),eW(t1("down"));return}if("ArrowUp"===e.key){e.preventDefault(),eW(t1("up"));return}if("ArrowRight"===e.key){e.preventDefault(),eW(t1("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),eW(t1("left"));return}if("Escape"===e.key){e.preventDefault(),ez(!1);return}let t=tL[eP];if("Tab"===e.key&&t){e.preventDefault(),tG(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 af(t)&&am(e)}(ew,t,f)?(ez(!1),tT()):tG(t);return}}if(eH&&null!==eD&&!ei&&!l){if("ArrowDown"===e.key){e.preventDefault(),eV(e=>dr(e,tq.length,1));return}if("ArrowUp"===e.key){e.preventDefault(),eV(e=>dr(e,tq.length,-1));return}if("Escape"===e.key){e.preventDefault(),e_(!1);return}if(("Tab"===e.key||i)&&tq[eq]){e.preventDefault(),tJ(tq[eq]);return}}if("ArrowUp"===e.key&&!l&&!f&&Q.length>0&&0===ew.trim().length){e.preventDefault(),ez(!1),e_(!1),eQ(Q.length-1),eG(!0);return}if("Escape"===e.key&&!l&&f&&c){e.preventDefault(),c();return}r&&(e.preventDefault(),f&&(u||h)?t0(e.altKey&&h||!u?"followup":"steer"):tT())},[ev,ey,f,u,h,c,ei,eL,tR,tL,eP,tG,t0,tT,t1,eH,eD,tq,eq,tJ,eY,Q,eX,tY,ew]),t4=(0,i.useCallback)(()=>{tu.current=null;let e=tr.current;e&&dl(e)},[]),t8=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!eh&&t.length){e.preventDefault(),tS(t.map(e=>e.getAsFile()).filter(e=>null!==e));return}let n=e.clipboardData.getData("text/html"),r=e.clipboardData.getData("text/plain");if(r){let t=e.currentTarget,n=e.nativeEvent,i=t.selectionStart,s=t.selectionEnd,l={};tu.current=l,setTimeout(()=>{tu.current===l&&(tu.current=null,!n.defaultPrevented&&t.isConnected&&ds(t,i,s,r))},0)}if(!n||!r)return;let i=new DOMParser().parseFromString(n,"text/html"),s=function(e,t){let n="",r=0,i=!1;for(let{label:s,href:l,occurrence:o}of t){if(!s||!l)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 a=s.replace(/([\\[\]])/g,"\\$1"),d=l.replace(/([\\()])/g,"\\$1");n+=`${e.slice(r,t)}[${a}](${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 l=e.currentTarget,o=l.selectionStart,a=l.value.slice(0,o)+s+l.value.slice(l.selectionEnd);e.preventDefault(),tw.current=a,ek(a),eG(!1),tD(a,o+s.length),requestAnimationFrame(()=>{l.focus(),l.setSelectionRange(o+s.length,o+s.length),da(l)})},[eh,tS,tD]);(0,i.useEffect)(()=>{if(null===tR){ez(!1),eW(0),tp.current=!1;return}ez(!0),eW(0),!tp.current&&er&&(tp.current=!0,Promise.resolve(er()).catch(()=>{tp.current=!1}))},[tR,er]),(0,i.useEffect)(()=>{if(!eL||!eu)return;let e=!1;return tt({cwd:eu,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(eu)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;tt({cwd:eu,values:n})}).catch(()=>{e||tt({cwd:eu,values:{}})}),()=>{e=!0}},[eL,eu]),(0,i.useEffect)(()=>{eP>=tL.length&&eW(Math.max(0,tL.length-1))},[tL.length,eP]),(0,i.useEffect)(()=>{tf.current.length=tL.length},[tL.length]),(0,i.useEffect)(()=>{eL&&!ei&&tf.current[eP]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eP,eL,ei]),(0,i.useLayoutEffect)(()=>{if(!eL||null===tR||ei)return void eF(null);let e=th.current;if(e)return dd(e,e=>{eF(t=>t===e?t:e)})},[eL,tR,ei]),(0,i.useLayoutEffect)(()=>{if(!eH||null===eD||ei)return void eK(null);let e=tm.current;if(e)return dd(e,e=>{eK(t=>t===e?t:e)})},[eH,eD,ei]);let t3=v&&v.length>0?v.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:m?.provider??"unknown",modelId:t,name:n}}),t5=B?Math.max(0,B.tokensBefore-B.estimatedTokensAfter):0,t6=B?`${B.reason&&"manual"!==B.reason?`${B.reason[0].toUpperCase()}${B.reason.slice(1)} `:ef("chat.compacted")} ${dp(B.tokensBefore)} -> ${dp(B.estimatedTokensAfter)} tokens (${ef("chat.tokensSaved",{saved:dp(t5)})})`:null,t9=U&&"auto"!==U?U:null,t7="auto"!==(n=t9??"auto")&&Z?Z[n]??n:n,ne=Object.entries(dt).find(e=>{let[,t]=e;return t===(H??"configured")})?.[0]??"configured",nt="chat-only"===ne?ef("chat.chatOnly"):ne;(0,i.useEffect)(()=>{let e=e=>{ti.current&&!ti.current.contains(e.target)&&eS(!1),ts.current&&!ts.current.contains(e.target)&&eN(!1),tl.current&&!tl.current.contains(e.target)&&e$(!1),!to.current||to.current.contains(e.target)||tr.current?.contains(e.target)||eG(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{f&&eS(!1)},[f]);let nn=(0,i.useRef)(-1/0);(0,i.useLayoutEffect)(()=>{if(f)return()=>{nn.current=performance.now()}},[f]);let nr=e=>{var t,n;return t=e.detail,n=performance.now()-nn.current,t>0&&n<600};return(0,i.useEffect)(()=>{ev||e$(!1)},[ev]),(0,r.jsxs)("fieldset",{disabled:e0,"aria-busy":e0,className:eh?void 0:"chat-input-shell",style:{...eh?{flexShrink:0}:{display:"flex",flexDirection:"column",minHeight:0},minWidth:0,margin:0,border:0,background:"transparent",padding:eh?0:"0 16px 8px",paddingRight:eh?0:ev?16:52,opacity:e0?.5:1,transition:"opacity 0.15s"},children:[!eh&&(0,r.jsx)("input",{ref:ta,type:"file",accept:ep?void 0:"image/*",multiple:!0,style:{display:"none"},onChange:tC}),(0,r.jsxs)("div",{style:{...eh?void 0:{display:"flex",flexDirection:"column",minHeight:0,width:"100%"},maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(0,r.jsx)(d$,{cwd:y,onFork:w}),(0,r.jsx)(dI,{error:b}),(0,r.jsx)(dM,{warnings:k}),tF&&(s=v?.find(e=>e.provider===m?.provider&&e.id===m?.modelId),(0,r.jsx)(dE,{tone:"warning",title:ef("chat.imageNotSupportedTitle"),body:ef("chat.imageNotSupportedBody",{model:s?.name||m?.modelId||""}),onClose:()=>eJ(!0)})),(X?.steering.length??0)+(X?.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:ef("chat.queued",{count:(X?.steering.length??0)+(X?.followUp.length??0)})}),ee&&(0,r.jsxs)("button",{onClick:ee,title:ef("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"})]}),ef("chat.recall")]})]}),(0,r.jsxs)("div",{style:{maxHeight:"min(180px, calc(var(--app-viewport-height, 100dvh) * 0.25))",overflowY:"auto",overscrollBehavior:"contain"},children:[X?.steering.map((e,t)=>(0,r.jsx)(dN,{kind:"steer",text:e},`steer-${t}`)),X?.followUp.map((e,t)=>(0,r.jsx)(dN,{kind:"follow-up",text:e},`followup-${t}`))]})]}),G&&(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"})]}),ef("chat.retrying",{attempt:G.attempt,max:G.maxAttempts}),G.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",G.errorMessage]})]}),t6&&(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"})}),t6]}),F&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,marginBottom:8,padding:D?"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:D?"4px 0":0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:F}),D&&(0,r.jsx)(nc,{onClick:D,title:ef("chat.dismissCompactError")})]}),eI.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:eI.map((e,t)=>(0,r.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,r.jsx)(sY,{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:()=>tN(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:[eY&&!ei&&Q.length>0&&(0,r.jsxs)("div",{ref:to,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",maxHeight:"min(44vh, 360px)"},children:[(0,r.jsx)("div",{title:ef("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===eX;return(0,r.jsxs)("button",{ref:e=>{tx.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tY(e)},onMouseEnter:()=>eQ(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,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}`)})})]}),eL&&null!==tR&&!ei&&(0,r.jsxs)("div",{ref:th,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===eO?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${eO}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:en?ef("chat.loadingCommands"):ef("chat.slashCommands",{label:tP})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ef("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:10},children:en||0!==tA.length?tz.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:ef(dg[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===eP,s=db(t,tn);return(0,r.jsxs)("button",{ref:e=>{tf.current[n]=e},type:"button",onMouseDown:e=>{e.preventDefault(),tG(t)},onMouseEnter:()=>eW(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:ef("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:dv(t,ef)})]},`${t.source}:${t.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:ef("chat.noCommands")})})]}),eH&&null!==eD&&!ei&&(l=e5&&(!e8||e8.cwd!==eu),o=1===tq.length?ef("chat.match"):ef("chat.matches",{count:tq.length}),a=e8?.truncated&&!tK?eD.query?ef("chat.searchingAll"):ef("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:tm,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eU?"min(48vh, 400px)":`min(48vh, 400px, ${eU}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:l?ef("chat.loadingFiles"):ef("chat.files",{label:o,hint:a})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ef("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:l||0!==tq.length?tq.map((e,t)=>{let n=t===eq,i=e.path.split("/").pop()??e.path,s=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tg.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tJ(e)},onMouseEnter:()=>eV(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(nh,{size:14}):ng(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:tU&&!tK?ef("chat.searching"):ef("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:tO?void 0:"chat-composer-row",style:{minWidth:0,display:"flex",flexDirection:tO?"column":"row",gap:8,alignItems:tO?"stretch":"center",background:"var(--bg)",border:eh?"none":`1px solid ${eR?"var(--tool-bg)":f&&(u||h)?"rgba(234,179,8,0.4)":"color-mix(in srgb, var(--border) 70%, transparent)"}`,borderRadius:14*!eh,padding:eh?0:ev?"6px 6px 6px 12px":"10px 10px 10px 14px",boxShadow:eh?"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:tr,className:"chat-input-textarea","aria-label":eh?ef("chat.askInSideChat"):void 0,value:ew,onChange:e=>{tw.current=e.target.value,ek(e.target.value),eG(!1),tD(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;tD(t.value,t.selectionStart)},onKeyDown:t2,onCompositionStart:()=>{td.current=!0},onCompositionEnd:e=>{td.current=!1,tc.current=Date.now();let t=e.currentTarget;tD(t.value,t.selectionStart)},onInput:t4,onPaste:t8,placeholder:W?ef("chat.compactingPlaceholder"):f&&(u||h)?ef("chat.steerPlaceholder"):f?ef("chat.agentPlaceholder"):ef("chat.messagePlaceholder"),rows:1,style:{flex:tO?"none":1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:"var(--chat-content-font-size, 14px)",lineHeight:1.6,fontFamily:"inherit",minHeight:eh?96:24,maxHeight:200,overflow:"auto"}}),f&&!eR?(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:tX,disabled:!ew.trim()||eI.length>0,title:ef("chat.sideChatHint"),"aria-label":ef("chat.sideChat"),className:`bg-transparent ${ew.trim()&&!eI.length?"cursor-pointer text-text-muted hover:bg-bg-hover hover:text-text":"cursor-not-allowed text-text-dim"}`,style:{width:38,display:"grid",placeItems:"center",padding:0,border:"1px solid var(--border)",borderRadius:8,transition:"background 0.12s"},children:(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"}),(0,r.jsx)("path",{d:"M13 8.5v7M9.5 12h7"})]})}),u&&(0,r.jsxs)("button",{onClick:()=>t0("steer"),disabled:!tW,title:ef("chat.steerHint"),"aria-label":ef("chat.steer"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tW?"rgba(234,179,8,0.12)":"none",border:"1px solid rgba(234,179,8,0.35)",borderRadius:8,color:tW?"rgba(180,130,0,1)":"var(--text-dim)",cursor:tW?"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:ef("chat.steer")})]}),h&&(0,r.jsxs)("button",{onClick:()=>t0("followup"),disabled:!tW,title:`${ef("chat.followUpHint")} (${ev?"Ctrl/Cmd+":""}Alt/Option+Enter)`,"aria-label":ef("chat.followUp"),"aria-keyshortcuts":ev?"Control+Alt+Enter Meta+Alt+Enter":"Alt+Enter",style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tW?"rgba(129,140,248,0.12)":"none",border:"1px solid rgba(129,140,248,0.35)",borderRadius:8,color:tW?"rgba(99,102,241,1)":"var(--text-dim)",cursor:tW?"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:ef("chat.followUp")})]})]}):(0,r.jsxs)("button",{onClick:tT,disabled:!ew.trim()&&!eI.length,title:ef("chat.send"),"aria-label":ef("chat.send"),style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,...ev?{width:36,height:36,padding:0}:{padding:"7px 14px"},background:ew.trim()||eI.length?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:ew.trim()||eI.length?"var(--accent-contrast)":"var(--text-dim)",cursor:ew.trim()||eI.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:ew.trim()||eI.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"})]}),!ev&&ef("chat.send")]})]})]}),eR&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eA?"var(--text-muted)":"var(--accent)",marginTop:4},children:[ef("chat.shell")," \xb7 ",eA?ef("chat.outputLocal"):ef("chat.outputModel")]}),!eh&&(0,r.jsxs)("div",{className:"chat-input-controls",style:{marginTop:ev?4:8,display:ev?"grid":"flex",gridTemplateColumns:ev?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:ev?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2},children:[(0,r.jsx)("button",{onClick:()=>ta.current?.click(),title:ef("chat.attachFiles"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:eb,height:eb,padding:0,background:"none",border:"none",borderRadius:9,color:eI.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=eI.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=eI.length?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:ev?18:15,height:ev?18:15,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,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"})]})}),(t3.length>0||m||b)&&C&&(0,r.jsx)(a9,{options:t3,value:m,onChange:C,onReselect:C,busy:N,isAutoSelection:g,defaultValue:E,onSetDefault:$,allOptions:j?.map(e=>({provider:e.provider,providerName:e.providerName,modelId:e.id,name:e.name})),onShowAll:S})]}),!ev&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsxs)("div",{ref:tl,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:ev?0:"auto"},children:[ev&&(0,r.jsx)("button",{type:"button",title:eE?void 0:ef("chat.moreControls"),"aria-label":ef("chat.moreControls"),"aria-expanded":eE,"aria-hidden":eE||void 0,tabIndex:eE?-1:void 0,onClick:()=>{e$(!0)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:eb,padding:"8px 10px",background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:eE?"default":"pointer",fontSize:12,fontWeight:500,visibility:eE?"hidden":"visible",pointerEvents:eE?"none":"auto",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{eE||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{eE||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:ef("chat.moreControls")}),(0,r.jsxs)("div",{style:{display:ev?eE?"flex":"none":"flex",alignItems:"center",gap:ev?1:2,...ev?{position:"absolute",right:0,bottom:0,zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"nowrap",justifyContent:"flex-end",border:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:10,background:"color-mix(in srgb, var(--bg-panel) 92%, var(--bg))",boxShadow:"0 8px 24px rgba(0,0,0,0.14)",backdropFilter:"blur(10px)"}:null},children:[q&&(0,r.jsxs)("div",{ref:ts,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>eN(e=>!e),title:f?ef("chat.currentReasoning",{level:t7}):ef("chat.changeReasoning",{level:t7}),"aria-label":ef("chat.changeReasoningLabel"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ev?"0 10px":"8px 12px",width:ev?"auto":void 0,height:eb,background:eC?"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=eC?"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"})]}),(!ev||eE)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t7})]}),eC&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",...ev?{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:dc.filter(e=>!V||"auto"===e||V.includes(e)).map(e=>{let t="auto"===e?K:!K&&t9===e,n=ef(du[e]),i="auto"!==e&&Z?Z[e]:void 0,s=null!=i&&i!==e?i:e,l=null!=i&&i!==e;return(0,r.jsxs)(a6,{active:t,onSelect:()=>{if(eN(!1),"auto"===e){K||q("auto");return}(!t||K)&&q(e)},gutter:!!Y,star:Y&&"auto"!==e?{isDefault:J===e,saveLabel:ef("chat.saveDefaultThinking"),defaultLabel:ef("chat.defaultThinking"),onSave:()=>{eN(!1),Y(e)}}:void 0,children:[(0,r.jsxs)("span",{style:{flex:1},children:[s,l&&(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)})})]}),!f&&_&&(0,r.jsxs)("div",{ref:ti,style:{position:ev?"static":"relative"},children:[(0,r.jsxs)("button",{onClick:e=>{f||nr(e)||eS(e=>!e)},disabled:f,title:ef("chat.changeToolPreset")+`: ${nt}`,"aria-label":ef("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ev?"0 10px":"8px 12px",width:ev?"auto":void 0,height:eb,background:ej?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:f?"not-allowed":"pointer",fontSize:12,opacity:f?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{f||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ej?"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"})}),(!ev||eE)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nt})]}),ej&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,maxWidth:ev?"calc(100vw - 16px)":void 0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:120},children:de.map(e=>{let t,n=dt[e],i=(H??"configured")===n;return t="configured"===e?ef("chat.configuredTools"):"chat-only"===e?ef("chat.chatOnly"):"read-only"===e?ef("chat.readOnlyTools",{count:4}):"default"===e?ef("chat.builtInTools",{count:4}):ef("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{eS(!1),i||_(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)})})]}),(!f||W)&&M&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{onClick:W?T:e=>{nr(e)||M()},style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ev?"0 10px":"8px 12px",width:ev?"auto":void 0,height:eb,background:W?"rgba(239,68,68,0.08)":"none",border:"none",borderRadius:9,color:W?"#ef4444":"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=W?"rgba(239,68,68,0.16)":"var(--bg-hover)",e.currentTarget.style.color=W?"#ef4444":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=W?"rgba(239,68,68,0.08)":"none",e.currentTarget.style.color=W?"#ef4444":"var(--text-muted)"},title:W?ef("chat.stopCompaction"):ef("chat.compactContext"),"aria-label":W?ef("chat.stopCompaction"):ef("chat.compactContext"),children:W?(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"})}),(!ev||eE)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:ef("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"})]}),(!ev||eE)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:ef("chat.compact")})]})})}),f&&(0,r.jsxs)("button",{onClick:c,title:ef("chat.stopAgent"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:eb,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"})}),ef("chat.stop")]}),void 0!==eo&&(0,r.jsx)("button",{onClick:eo,title:el?ef("chat.disableSound"):ef("chat.enableSound"),"aria-label":el?ef("chat.disableSound"):ef("chat.enableSound"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:eb,height:eb,padding:0,background:"none",border:"none",borderRadius:9,color:el?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",opacity:el?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=el?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.opacity=el?"1":"0.55"},children:el?(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"})]})}),ev&&eE&&(0,r.jsx)("button",{type:"button",title:ef("chat.collapseControls"),"aria-label":ef("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eS(!1),eN(!1),e$(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:ev?eb:36,height:eb,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,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"})]})})]})]})]})]})]})}));function dR(){try{return window.localStorage}catch{return null}}function dA(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:dR();if(!t)return!1;try{return"true"===t.getItem(e)}catch{return!1}}function dL(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:dR();if(n)try{n.setItem(e,String(t))}catch{}}let dz="pi-web:minimap-preview-locked";function dP(e){return dA(dz,e)}var dW=n(88576),dO=n.n(dW),dF=n(5284),dD=n.n(dF);function dB(e){let{locked:t,iconSize:n=16,className:i,...s}=e;return(0,r.jsx)("button",{...s,type:"button","aria-pressed":t,className:i?`${dD().lock} ${i}`:dD().lock,children:(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"4",y:"11",width:"16",height:"10",rx:"2"}),t?(0,r.jsx)("path",{d:"M8 11V7a4 4 0 0 1 8 0v4"}):(0,r.jsx)("path",{d:"M8 11V7a4 4 0 0 1 7.9-.9"})]})})}function dH(e){let{level:t,children:n,headingIndex:i,onClick:s}=e;return(0,r.jsx)("button",{type:"button",className:dO().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 d_=[...sR??[],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]:[]}}],dU=[[i6.A,{throwOnError:!1,strict:!1}]];function dK(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 dq=(0,i.memo)(function(e){let{markdown:t,onHeadingClick:n,onAnswerClick:s}=e,l=(0,i.useMemo)(()=>sm(t),[t]);return t?(0,r.jsx)("div",{className:dO().outline,children:(0,r.jsx)(iQ.oz,{remarkPlugins:d_,rehypePlugins:dU,components:{h1:e=>{let{children:t,node:i}=e;return(0,r.jsx)(dH,{level:1,headingIndex:dK(i),onClick:n,children:t})},h2:e=>{let{children:t,node:i}=e;return(0,r.jsx)(dH,{level:2,headingIndex:dK(i),onClick:n,children:t})},h3:e=>{let{children:t,node:i}=e;return(0,r.jsx)(dH,{level:3,headingIndex:dK(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:dO().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:l})}):null}),dV=(0,i.memo)(function(e){let{messages:t,getStreamingMessage:n,scrollContainer:s,messageRefs:l,onRevealHistory:o,turnsBefore:a,turnAnchors:d}=e,{t:c}=(0,t_.s)(),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)([]),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(600),[b,y]=(0,i.useState)(!1),[w,k]=(0,i.useState)(dP),[j,S]=(0,i.useState)(null),C=(0,i.useRef)(!1),N=(0,i.useRef)(null),E=(0,i.useRef)([]),$=(0,i.useRef)({nodes:[],gap:50,fillsHeight:!1}),I=(0,i.useRef)(null),M=(0,i.useRef)(new Map),T=(0,i.useRef)(null),R=(0,i.useRef)(null),A=(0,i.useRef)(null),L=(0,i.useRef)(t);L.current=t;let z=(0,i.useRef)(d);z.current=d;let P=(0,i.useMemo)(()=>(function(e,t){if(0===e.length)return{nodes:[],gap:50,fillsHeight:!1};let n=Math.max(1,t),r=Math.max(0,n-12-48);if(1===e.length)return{nodes:[{...e[0],topRatio:12/n}],gap:50,fillsHeight:!1};let i=r/(e.length-1),s=Math.min(50,i);return{nodes:e.map((e,t)=>({...e,topRatio:(12+t*s)/n})),gap:s,fillsHeight:i<=50}})(h,x),[h,x]),{nodes:W,gap:O}=P;$.current=P;let F=(0,i.useCallback)(e=>{R.current={index:e,until:Date.now()+1600},g(e)},[]),D=(0,i.useCallback)((e,t)=>{let n=R.current;if(n&&Date.now()<n.until)return void g(n.index);R.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)},[]),B=(0,i.useCallback)(()=>{let e=s.current;if(!e)return;let t=e.scrollHeight-e.clientHeight,n=E.current;p(t>20),D(e,n)},[s,D]),H=(0,i.useRef)(null),_=(0,i.useCallback)(()=>{H.current||(H.current=setTimeout(()=>{H.current=null;let e=s.current,t=N.current;if(!e||!t)return;let r=l.current,i=e.getBoundingClientRect(),o=[],a=0,d=null,c=n();for(let[t,n]of(c?[...L.current,c]:L.current).entries()){let s=!0===z.current[t];if(!s&&"assistant"!==n.role)continue;let l=null;if(ik(n,s)&&(l=r?.[a]??null,a++),s){d=null;let t=l?.getBoundingClientRect();d={userMessage:n,assistantPreviews:[],scrollTop:t?t.top-i.top+e.scrollTop:null,toolCount:0},o.push(d);continue}if(!d)continue;null===d.scrollTop&&l&&ib(d.userMessage)&&(d.scrollTop=l.getBoundingClientRect().top-i.top+e.scrollTop),d.toolCount+="assistant"===n.role&&Array.isArray(n.content)?n.content.reduce((e,t)=>e+ +("toolCall"===t.type),0):0;let c=function(e){if("assistant"!==e.role)return"";let{answerBlocks:t}=iI(e);return t.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n").trim()}(n);c&&d.assistantPreviews.push({markdown:c,element:l})}let u=o.map((e,t)=>({topRatio:0,targetTurn:e,index:t}));v(t.clientHeight),E.current=u,f(u),p(e.scrollHeight-e.clientHeight>20),D(e,u);let h=A.current,m=h?u[h.nodeIndex]:null;if(h&&m){let t=void 0===h.assistantIndex?null:m.targetTurn.assistantPreviews[h.assistantIndex],n=m.targetTurn.scrollTop;if("assistant"===h.target){let r=t?.element?.getBoundingClientRect();n=r?r.top-i.top+e.scrollTop:null}else if("heading"===h.target){let r=void 0===h.headingIndex?null:t?.element?.querySelectorAll("h1, h2, h3").item(h.headingIndex),s=r?.getBoundingClientRect();n=s?s.top-i.top+e.scrollTop:null}if(null===n)return;A.current=null,F(m.index);let r=.3*e.clientHeight;e.scrollTo({top:Math.max(0,n-r),behavior:"smooth"})}},150))},[n,F,l,s,D]);(0,i.useEffect)(()=>{let e=s.current;if(e)return e.addEventListener("scroll",B,{passive:!0}),()=>e.removeEventListener("scroll",B)},[s,B]),(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=()=>{_(),B()},n=new ResizeObserver(t);return n.observe(e),e.firstElementChild&&n.observe(e.firstElementChild),t(),()=>{n.disconnect(),H.current&&(clearTimeout(H.current),H.current=null)}},[_,s,B]),(0,i.useEffect)(()=>{let e=setTimeout(()=>{_(),B()},50);return()=>clearTimeout(e)},[t.length,d,_,B]);let U=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;if(F(e.index),null===e.targetTurn.scrollTop){A.current={nodeIndex:e.index,target:"user"},o();return}let r=Math.max(0,e.targetTurn.scrollTop-.3*n.clientHeight);n.scrollTo({top:r,behavior:t})},[F,o,s]),K=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;let r=e.targetTurn.assistantPreviews[t]?.element;if(!r){A.current={nodeIndex:e.index,target:"assistant",assistantIndex:t},o();return}let i=n.getBoundingClientRect(),l=r.getBoundingClientRect().top-i.top+n.scrollTop-.3*n.clientHeight;F(e.index),n.scrollTo({top:Math.max(0,l),behavior:"smooth"})},[F,o,s]),q=(0,i.useCallback)(e=>{let{nodes:t,gap:n,fillsHeight:r}=$.current,i=N.current?.clientHeight??0;if(0===t.length||i<=0)return null;let s=Math.max(0,Math.min(i,e*i)),l=t[0].topRatio*i,o=n>0?Math.round((s-l)/n):0,a=Math.max(0,Math.min(t.length-1,o)),d=t[a];if(!r&&Math.abs(s-d.topRatio*i)>Math.max(10,n/2))return null;return d},[]),V=(0,i.useCallback)((e,t,n)=>{let r=s.current;if(!r)return;let i=e.targetTurn.assistantPreviews[t]?.element;if(!i){A.current={nodeIndex:e.index,target:"heading",assistantIndex:t,headingIndex:n},o();return}let l=i.querySelectorAll("h1, h2, h3").item(n);if(!l)return;let a=r.getBoundingClientRect(),d=l.getBoundingClientRect().top-a.top+r.scrollTop-.3*r.clientHeight;F(e.index),r.scrollTo({top:Math.max(0,d),behavior:"smooth"})},[F,o,s]),Z=(0,i.useCallback)(()=>{T.current&&(clearTimeout(T.current),T.current=null)},[]),J=(0,i.useCallback)(()=>{w||(Z(),y(!0))},[Z,w]),Y=(0,i.useCallback)(()=>{let e=!w;k(e),dL(dz,e,void 0),e&&(Z(),y(!1),S(null))},[Z,w]),G=(0,i.useCallback)(()=>{Z(),T.current=setTimeout(()=>{T.current=null,y(!1),S(null)},250)},[Z]);(0,i.useEffect)(()=>()=>Z(),[Z]);let X=(0,i.useCallback)(e=>{if(!u)return;C.current=!0,J();let t=e.currentTarget.getBoundingClientRect();S(Math.max(0,Math.min(1,(e.clientY-t.top)/t.height)));let n=(e,n)=>{let r=q(Math.max(0,Math.min(1,(e-t.top)/t.height)));r&&U(r,n)};n(e.clientY,"smooth");let r=e=>{C.current&&n(e.clientY,"auto")},i=()=>{C.current=!1,window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",i)};window.addEventListener("mousemove",r),window.addEventListener("mouseup",i)},[q,U,J,u]),Q=null===j?null:q(j),ee=Q?.index??null;if((0,i.useEffect)(()=>{if(!b||null===ee)return;let e=I.current,t=M.current.get(ee);if(!e||!t)return;let n=t.offsetTop-(e.clientHeight-t.offsetHeight)/2;e.scrollTop=Math.max(0,n)},[h,b,ee]),!u)return null;let et=Math.max(1,(W.length>0?W[W.length-1].topRatio*x:12)-12);return(0,r.jsxs)("div",{ref:N,onMouseDown:X,onMouseEnter:J,onMouseLeave:G,onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();S((e.clientY-t.top)/t.height)},style:{width:36,flexShrink:0,position:"relative",cursor:"pointer",userSelect:"none",borderLeft:"1px solid var(--border)",background:"var(--bg-panel)",overflow:"visible"},children:[a>0&&(0,r.jsx)("div",{"data-minimap-earlier":"",style:{position:"absolute",left:"50%",top:0,height:12,width:1,background:"repeating-linear-gradient(to bottom, var(--text-dim) 0 2px, transparent 2px 4px)",transform:"translateX(-50%)",zIndex:0}}),(0,r.jsx)("div",{style:{position:"absolute",left:"50%",top:12,height:et,width:1,background:"var(--border)",transform:"translateX(-50%)",zIndex:0}}),W.map(e=>{let t=b&&Q?.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,O),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)(dB,{locked:w,className:dO().lock,"data-minimap-lock":w?"on":"off",title:c(w?"chatMinimap.unlockPreview":"chatMinimap.lockPreview"),"aria-label":c("chatMinimap.lockPreview"),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),Y()}}),b&&h.length>0&&(0,r.jsxs)("div",{ref:I,className:dO().preview,"data-minimap-preview-box":"",onMouseEnter:J,onMouseDown:e=>e.stopPropagation(),onMouseMove:e=>e.stopPropagation(),children:[a>0&&(0,r.jsx)("button",{type:"button",className:dO().earlier,"data-minimap-preview-earlier":"",onClick:()=>s.current?.scrollTo({top:0,behavior:"smooth"}),children:c("chatMinimap.earlierTurns",{count:a})}),h.map(e=>{var t;let n=ee===e.index;return(0,r.jsxs)("div",{ref:t=>{t?M.current.set(e.index,t):M.current.delete(e.index)},className:dO().turn,"data-minimap-preview-index":e.index,"data-located":n?"true":void 0,children:[(0,r.jsxs)("span",{className:dO().number,children:[(0,r.jsx)("span",{"aria-hidden":"true",children:String(a+e.index+1).padStart(2,"0")}),e.targetTurn.toolCount>0&&(0,r.jsx)("span",{className:dO().toolBadge,role:"img",title:c("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),"aria-label":c("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),children:e.targetTurn.toolCount>99?"99+":e.targetTurn.toolCount})]}),(0,r.jsxs)("div",{className:dO().content,children:[(0,r.jsx)("button",{type:"button",className:dO().user,"data-minimap-preview-user":e.index,onClick:()=>{U(e,"smooth")},children:(0,r.jsx)("span",{className:dO().userText,children:ib(e.targetTurn.userMessage)?c("chatMinimap.extensionTurn",{type:e.targetTurn.userMessage.customType}):"string"==typeof(t=e.targetTurn.userMessage).content?t.content.trim():t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim()})}),e.targetTurn.assistantPreviews.map((t,n)=>(0,r.jsxs)("div",{className:dO().assistant,children:[(0,r.jsx)("button",{type:"button",className:dO().assistantJump,"data-minimap-preview-assistant":`${e.index}-${n}`,onClick:()=>K(e,n),"aria-label":c("chatMinimap.locateAssistant"),title:c("chatMinimap.locateAssistant"),children:"A"}),(0,r.jsx)(dq,{markdown:t.markdown,onAnswerClick:()=>K(e,n),onHeadingClick:t=>V(e,n,t)})]},n))]})]},e.index)})]})]})});function dZ(e){let{rootRef:t,chatInputRef:n,startSideChat:s}=e,{t:l}=(0,t_.s)(),[o,a]=(0,i.useState)(null),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(null),m=(0,i.useRef)(null),g=(0,i.useRef)(null),x=(0,i.useCallback)(()=>{a(null),c(!1),f(null)},[]);(0,i.useEffect)(()=>{if(d)return;let e=e=>{let n=t.current;if(!n||!(e.target instanceof Node)||!n.contains(e.target))return;let r=window.getSelection(),i=r?.rangeCount?r.getRangeAt(0):null;if(!r||r.isCollapsed||!i||!n.contains(i.commonAncestorContainer))return void a(null);let s=r.toString().trim();if(!s)return void a(null);let l=i.getBoundingClientRect();a({text:s,top:Math.min(window.innerHeight-44,l.bottom+8),left:Math.max(64,Math.min(window.innerWidth-64,l.left+l.width/2))})};return document.addEventListener("pointerup",e),()=>document.removeEventListener("pointerup",e)},[t,d]),(0,i.useEffect)(()=>{d&&o&&g.current?.insertIfEmpty(ap(o.text))},[d,o]),(0,i.useLayoutEffect)(()=>{let e=m.current;if(!e||!o)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(o.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(o.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)}},[o,d,h]),(0,i.useEffect)(()=>{if(!o)return;let e=e=>{d||m.current?.contains(e.target)||x()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),u||x())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[o,d,u,x]);let v=(0,i.useCallback)(()=>{o&&(n?.current?.insertQuote(ap(o.text)),x())},[n,o,x]),b=(0,i.useCallback)(async e=>{if(s&&!u&&e.trim()&&o){p(!0),f(null);try{let t=await s(e,o.text);if(!t)return void x();g.current?.restoreSubmission(e),f(t)}catch(t){g.current?.restoreSubmission(e),f(t instanceof Error?t.message:String(t))}finally{p(!1)}}},[o,u,x,s]);return o?(0,t7.createPortal)((0,r.jsx)("div",{ref:m,role:d?"dialog":"toolbar","aria-label":l(d?"chat.newQuoteChat":"chat.selectionActions"),style:{position:"fixed",top:o.top,left:o.left,zIndex:260,display:"flex",flexWrap:"wrap",gap:3,width:d?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:d?12:3,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",boxShadow:"0 2px 10px rgba(0,0,0,0.12)"},children:d?(0,r.jsxs)("fieldset",{disabled:u,"aria-busy":u,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:l("chat.askInSideChat")}),(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button",title:l("i18n.close"),"aria-label":l("i18n.close"),disabled:u,onClick:x,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)(dT,{ref:g,compact:!0,onSend:b,onAbort:x,isStreaming:!1}),h&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:h})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:l("chat.quoteSelection"),"aria-label":l("chat.quoteSelection"),onPointerDown:e=>e.preventDefault(),onClick:v,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:l("chat.quoteSelection")})]}),s&&(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:l("chat.askInSideChat"),"aria-label":l("chat.askInSideChat"),onPointerDown:e=>e.preventDefault(),onClick:()=>{c(!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:l("chat.askInSideChat")})]})]})}),document.body):null}var dJ=n(42790);function dY(e){let{text:t}=e,n=(0,i.useMemo)(()=>{let e=new dJ.v;e.use_classes=!0;let n=t.replace(il,"");return e.ansi_to_html(n).replaceAll('<a href="','<a target="_blank" rel="noopener noreferrer" href="')},[t]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:n}})}function dG(e){let t,n,s,{widgets:l,children:o}=e,{t:a}=(0,t_.s)(),d=(0,i.useId)(),c=(0,i.useRef)(null),u=(0,i.useRef)(new Map),[p,h]=(0,i.useState)(()=>l.find(e=>{let t=e.lines.length;return t>1&&t<=3})?.key??null),[f,m]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{var e;let t=new Map(l.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(m(e=>{let r=new Set(Array.from(e).filter(e=>t.has(e)));for(let e of n)r.add(e);return r.size===e.size&&Array.from(r).every(t=>e.has(t))?e:r}),n)){let t=u.current.get(e);t&&clearTimeout(t),u.current.set(e,setTimeout(()=>{u.current.delete(e),m(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},1100))}},[l]),(0,i.useEffect)(()=>()=>{for(let e of u.current.values())clearTimeout(e);u.current.clear()},[]),0===l.length)return null;let g=l.find(e=>e.key===p&&e.lines.length>0);return(0,r.jsxs)(r.Fragment,{children:[g&&(0,r.jsx)("div",{className:"extension-widget-panels",children:(t=l.indexOf(g),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:g.key}),(0,r.jsx)("pre",{className:"extension-widget-content",children:(0,r.jsx)(dY,{text:g.lines.join("\n")})})]},g.key))}),(0,r.jsxs)("div",{className:"extension-status-row",children:[(0,r.jsx)("div",{className:"extension-widget-triggers","aria-label":a("chat.extensionWidgets"),children:l.map((e,t)=>{let n=e.lines.length>0,i=n&&e.key===g?.key,s=f.has(e.key),l=a(1===e.lines.length?"chat.extensionWidgetLine":"chat.extensionWidgetLines",{count:e.lines.length}),o=a("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}, ${l}`,title:`${e.key} - ${o} - ${i?a("i18n.collapse"):a("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}, ${l}`,title:`${e.key} - ${o}`,children:p},e.key)})}),o]})]})}let dX="command:";function dQ(e){let{statuses:t,widgets:n=[],onCommand:i,commandsDisabled:s=!1}=e,l=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(dX))return null;let t=e.slice(dX.length).trim();return t.length>1&&t.startsWith("/")?t:null}(n.key);if(r){let n=io(e).replace(/\s+/g," ").trim();t.push({kind:"command",command:r,label:n||r})}else io(e).trim()&&t.push({kind:"text",text:e})}return t}(t);if(0===l.length&&0===n.length)return null;let o=l.some(e=>"command"===e.kind),a=l.map(e=>"text"===e.kind?io(e.text):e.label).join(" "),d=l.length>0?(0,r.jsx)("div",{role:"status",className:"extension-status-line","aria-label":a,title:a,children:(0,r.jsx)("span",{className:"extension-status-text",children:l.map((e,t)=>"text"===e.kind?(0,r.jsx)("span",{className:"extension-status-item",children:(0,r.jsx)(dY,{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":""}${l.length>0?" has-status":""}${o?" has-commands":""}`,children:n.length>0?(0,r.jsx)(dG,{widgets:n,children:d}):d})}function d0(e,t){return e?.kind==="running_tools"&&e.tools.length>0?e:t?{kind:"waiting_model"}:{kind:"running_command"}}function d1(e){switch(e.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==e.closed;default:return!1}}function d2(e,t){return e.every(e=>t.has(e.id))?e:e.filter(e=>t.has(e.id))}function d4(e,t){return e.some(e=>e.id===t)?e.filter(e=>e.id!==t):e}function d8(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function d3(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(!d8(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=d8(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=d8(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 d5(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 d6 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 d9(e){return e instanceof d6&&"prompt_rejected"===e.code&&!1===e.accepted}function d7(e){return`/api/agent/${encodeURIComponent(e)}?systemPrompt=0`}async function ce(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 d6(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted,d5(r)??void 0);return r.data}let ct={not_found:"sideChat.error.notFound",unsaved:"sideChat.error.unsaved",empty:"sideChat.error.empty",subagent:"sideChat.error.subagent",side:"sideChat.error.side"};async function cn(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 ct?t(ct[i.code]):i?.error??`HTTP ${r.status}`}}async function cr(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 ci(){return globalThis.__piSessionViewCache||(globalThis.__piSessionViewCache=new Map),globalThis.__piSessionViewCache}let cs=new WeakMap;function cl(e){let t,n=cs.get(e);if(void 0!==n)return n;try{t=JSON.stringify(e).length}catch{t=Number.MAX_SAFE_INTEGER}return cs.set(e,t),t}function co(e){let t=ci().get(e);return t?Date.now()-t.savedAt>6e5?(ci().delete(e),null):(ci().delete(e),ci().set(e,t),t):null}function ca(e){if(!e.sessionId||!e.revision)return!1;let t=ci();t.delete(e.sessionId);let n={...e,savedAt:Date.now()};return!(cl(n)>0x2000000)&&(t.set(n.sessionId,n),!function(){let e=ci();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+=cl(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-=cl(r))}}(),ci().has(n.sessionId))}function cd(e){ci().delete(e)}var cc=n(14755);let cu="pi-tool-preset";function cp(){try{return window.localStorage}catch{return null}}function ch(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 cf(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,ch(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),ch(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function cm(e){return e>=999500?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e)}function cg(e){return e>0?e>=.01?`$${e.toFixed(2)}`:"<$0.01":null}function cx(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 cv(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 cb(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(cv).filter(Boolean)}):JSON.stringify({text:"",images:[]})}let cy=(e,t)=>`live:${e??""}:${t}`;class cw 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 ck{constructor(e){this.options=e,this.current=null,this.retry=null,this.retryGeneration=0,this.endedSessionId=null,this.opens=0,this.retries=0,this.lastError=null,this.lastClose=null}close(e){let t=null!==this.lastError&&!(this.lastClose&&this.lastClose.at>=this.lastError.at);(this.current||this.retry||t)&&(this.lastClose={reason:e??null,at:Date.now()}),this.stopRetrying(),this.current&&this.discard(this.current,new cw("closed"))}snapshot(){let e=this.current,t=this.retry;return{sessionId:e?.sessionId??t?.sessionId??null,state:e?e.attempt.ready?"connected":"connecting":t?"retrying":"idle",readyState:e?e.source.readyState:null,openedAt:e?.openedAt??null,connectedAt:e?.connectedAt??null,lastSeenAt:e?.lastSeenAt??null,lastHeartbeatAt:e?.lastHeartbeatAt??null,events:e?.events??0,opens:this.opens,retries:this.retries,retryDueAt:t?.dueAt??null,watchdogArmed:!!(e&&null!==e.watchdog),staleAfterMs:this.options.staleAfterMs??null,lastError:this.lastError?{...this.lastError}:null,lastClose:this.lastClose?{...this.lastClose}:null}}maintain(e){if(this.endedSessionId===e||!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof cw?"startup_error"===n.status?this.stopRetrying():this.scheduleRetry(e):this.options.onUnexpectedError?.(n))})}async ensureConnected(e){if(this.endedSessionId===e)throw new cw("closed");for(;;){let t=this.current;if(t&&t.sessionId===e){if(t.attempt.ready&&1===t.source.readyState)return}else t=this.open(e);if(await t.attempt.promise,this.current!==t){if(this.current?.sessionId===e)continue;throw new cw("closed")}if(1===t.source.readyState)return;this.lastClose={reason:"stuck",at:Date.now()},this.discard(t,new cw("closed"))}}open(e){let t,n,r;this.current&&(this.lastClose={reason:"replaced",at:Date.now()},this.discard(this.current,new cw("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 cw("closed",e)}this.opens+=1;let i=!1,s=new Promise((e,t)=>{n=e,r=t}),l=setTimeout(()=>{this.fail(d,new cw("ready_timeout"),"ready_timeout")},this.options.readinessTimeoutMs),o={promise:s,ready:!1,succeed(){i||(i=!0,clearTimeout(l),n())},fail(e){i||(i=!0,clearTimeout(l),r(e))}},a=Date.now(),d={sessionId:e,source:t,attempt:o,watchdog:null,openedAt:a,connectedAt:null,lastSeenAt:null,lastHeartbeatAt:null,events:0};return this.current=d,t.onmessage=t=>{let n;if(this.current===d){d.lastSeenAt=Date.now();try{n=JSON.parse(t.data)}catch{return}if("session_ended"===n.type&&n.sessionId===e){this.endedSessionId=e,this.close(),this.options.onEvent(n);return}if("heartbeat"===n.type){d.lastHeartbeatAt=d.lastSeenAt;return}if("connected"===n.type){d.connectedAt??=d.lastSeenAt,o.ready=!0,o.succeed(),this.stopRetrying();let e=this.options.staleAfterMs;e&&null===d.watchdog&&(d.watchdog=setInterval(()=>{Date.now()-(d.lastSeenAt??a)>e&&this.fail(d,new cw("closed"),"stale")},Math.max(1e3,Math.floor(e/3))))}else if("startup_error"===n.type){let e="string"==typeof n.errorMessage?n.errorMessage:void 0;this.fail(d,new cw("startup_error",e),"startup_error");return}d.events+=1,this.options.onEvent(n)}},t.onerror=()=>{this.fail(d,new cw("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 cj(e){return!!e&&"unanswered"!==e&&!!(e.running||e.awaitingInput||e.subagentsActive)}function cS(e){return"u"<typeof document?()=>{}:(document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e))}let cC=()=>"hidden"===document.visibilityState,cN=()=>!1;function cE(e){return("tool_execution_start"===e.type||"tool_execution_update"===e.type||"tool_execution_end"===e.type)&&"string"==typeof e.parentToolCallId&&""!==e.parentToolCallId}function c$(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 cI(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let cM=/^(?:custom-ui|extension-widget):/;function cT(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return e+t>=n-r}let cR={isStreaming:!1,streamingMessage:null};function cA(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 cL(){let e=cR,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=d3(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 cA(e,n.contentIndex,()=>({type:"text",text:""}));case"text_delta":return cA(e,n.contentIndex,e=>e?.type==="text"?{...e,text:e.text+n.delta}:null);case"text_end":return cA(e,n.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:n.content}));case"thinking_start":return cA(e,n.contentIndex,()=>({type:"thinking",thinking:""}));case"thinking_delta":return cA(e,n.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+n.delta}:null);case"thinking_end":return cA(e,n.contentIndex,e=>({...e?.type==="thinking"?e:{},type:"thinking",thinking:n.content}));case"toolcall_start":return cA(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 cA(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 cA(e,n.contentIndex,()=>({type:"toolCall",toolCallId:n.toolCall.id,toolName:n.toolCall.name,input:n.toolCall.arguments}));default:return e}case"end":return cR;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 cz(e,t){let n=e.lastIndexOf(t);return -1===n?e:[...e.slice(0,n),...e.slice(n+1)]}function cP(e,t){return e.reduce((e,n)=>"user"===n.role&&cb(n)===t?e+1:e,0)}function cW(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function cO(e){return e&&"auto"!==e?e:null}let cF=new Map,cD=new Map;function cB(e,t){if(t){cF.set(e,t),cD.has(e)||cD.set(e,I(e));return}cF.delete(e),cD.get(e)?.(),cD.delete(e)}let cH=[2e3,5e3,1e4],c_=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:200,t=new Set;return n=>!t.has(n)&&(t.add(n),t.size>e&&t.delete(t.values().next().value),!0)}();function cU(e){return new Promise(t=>setTimeout(t,e))}function cK(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function cq(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:cK(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:cK(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=cK(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function cV(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 cZ(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 cJ=e=>e.isStreaming,cY=e=>!!e.streamingMessage?.content.length,cG=e=>e.streamingMessage;function cX(e){let t=getComputedStyle(e);return Math.max(0,["paddingTop","paddingBottom","borderTopWidth","borderBottomWidth"].reduce((e,n)=>e-(parseFloat(t[n])||0),e.getBoundingClientRect().height))}let cQ="pi-web:done-chimes";function c0(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Date.now(),r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:function(){try{return window.localStorage}catch{return null}}();if(0===e.length)return!1;if(!r)return!0;try{let i=function(e){let t=e.getItem(cQ);if(!t)return{};try{let e=JSON.parse(t);if(!e||"object"!=typeof e||Array.isArray(e))return{};let n={};for(let[t,r]of Object.entries(e))"number"==typeof r&&Number.isFinite(r)&&(n[t]=r);return n}catch{return{}}}(r),s=e.filter(e=>!("number"==typeof i[e]&&i[e]>=t));if(0===s.length)return!1;for(let e of s)i[e]=n;let l=Object.entries(i).filter(e=>{let[,t]=e;return n-t<=864e5}).sort((e,t)=>t[1]-e[1]).slice(0,200);return r.setItem(cQ,JSON.stringify(Object.fromEntries(l))),!0}catch{return!0}}let c1=null,c2=null;function c4(e){let{label:t}=e,[n,s]=(0,i.useState)(()=>c2);if((0,i.useEffect)(()=>{if(c2)return;let e=!1;return(c1??=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=>(c2=e,e)).catch(()=>(c1=null,null))).then(t=>{!e&&t&&s(t)}),()=>{e=!0}},[]),!n)return null;let l=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:l,"aria-label":l,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 c8(e){let t,{messageCount:n,toolCallCount:s,durationMs:l,cacheMisses:o,defaultExpanded:a=!1,reveal:d=!1,children:c,t:u}=e,[p,h]=(0,i.useState)(a);(0,i.useLayoutEffect)(()=>{d&&h(!0)},[d]);let f=[`${n} ${u(1===n?"chat.message":"chat.messages")}`];s>0&&f.push(`${s} ${u(1===s?"chat.toolCall":"chat.toolCalls")}`),void 0!==l&&f.push(u("chat.turnDuration",{time:iX(l)}));let m=o&&!(p||d)?(t={count:o.count,tokens:ox(o.missedTokens),cost:ob(u,o.missedCost)},u(1===o.count?"transcriptNotice.foldCacheMiss":"transcriptNotice.foldCacheMisses",t)):void 0;return(0,r.jsxs)("div",{style:{marginBottom:14},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":p||d,"aria-label":[u("chat.processDetails"),...f,...m?[m]:[]].join(" \xb7 "),onClick:()=>h(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:u(p?"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:p?"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:[f.join(" \xb7 "),m&&(0,r.jsx)("span",{style:{color:ov},children:` \xb7 ${m}`})]})]}),(p||d)&&(0,r.jsx)("div",{style:{marginTop:8},children:c})]})}function c3(e){let t,{session:s,searchTarget:o,onSearchTargetHandled:d,initialScrollPosition:c,onScrollPositionChange:u,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:f,newSessionContextBar:g,initialNewSessionChoices:x,onNewSessionChoicesChange:v,onAgentEnd:b,onSessionEnded:y,onToolEnd:w,onAttentionNeeded:k,onSessionCreated:j,onSessionForked:S,panel:C=!1,onSideSession:N,modelsRefreshKey:E,chatInputRef:$,onBranchDataChange:I,onSystemPromptChange:M,onSystemToolsChange:T,onSystemInfoLoaderChange:z,onDebugSnapshotReaderChange:P,onSessionStatsChange:F,onSessionStatsPanelOpen:D,onOpenSettings:B,onContextUsageChange:H,onOpenFile:_,onFilesUploaded:U,onOpenSubagent:K,quoteSelectionEnabled:q=!1,initialPrompt:V,onInitialPromptConsumed:Z,soundEnabled:J=!0,onSoundToggle:Y,playDoneSound:G=()=>{},unlockAudio:X,holdAudio:Q}=e,{t:ee}=(0,t_.s)(),et=tQ(),en=!a(s?.relation),er=(0,i.useRef)(G);er.current=G;let ei=(0,i.useRef)(J);ei.current=J;let es=(0,i.useRef)(!1),el=(0,i.useCallback)(e=>{if(en&&ei.current&&!e.aborted&&!e.subagentsActive){let e=tl.current??s?.id;(!e||c0([e],Date.now()-3e3))&&er.current()}b?.(e)},[en,b,s?.id]),eo=(0,i.useRef)(o?null:c??null),[ea,ed]=(0,i.useState)(()=>{let e=eo.current;return e&&!e.atBottom?e:null}),[ec,eu]=(0,i.useState)(!1),{loading:ep,error:eh,messages:ef,activeToolResults:em,toolClocks:eg,entryIds:ex,messageKeys:ev,historyCursor:eb,hasEarlierMessages:ey,earlierTurnCount:ew,streamingStore:ek,agentRunning:ej,bashRunning:eS,pendingBash:eC,modelNames:eN,modelList:eE,modelError:e$,missingCwd:eI,canForkMissingCwd:eM,modelScopeWarnings:eT,isModelScopeActive:eR,allModelList:eA,modelThinkingLevels:eL,modelThinkingLevelMaps:ez,toolPreset:eP,thinkingLevel:eW,retryInfo:eO,contextUsage:eF,forkingEntryId:eD,isCompacting:eB,compactError:eH,compactResult:e_,displayModel:eU,modelSwitching:eK,sessionStats:eq,slashCommands:eV,slashCommandsLoading:eZ,queuedMessages:eJ,notices:eY,extensionDialog:eG,waitingExtensionDialogCount:eX,extensionCustomUi:e0,waitingExtensionCustomUiCount:e1,extensionStatuses:e2,extensionWidgets:e4,respondToExtensionUi:e8,sendExtensionCustomInput:e3,setNoticePaused:e5,addNotice:e6,isAutoModelSelection:e9,isAutoThinkingSelection:e7,defaultModel:te,savedDefaultThinkingLevel:tt,agentPhase:tn,isNew:tr,editEntryId:ti,showScrollToBottom:ts,sessionIdRef:tl,scrollContainerRef:to,lastUserMsgRef:tc,promptAnchorActive:tu,handleSend:tp,handleAbort:tf,startSideChat:tm,handleFork:tg,forkIntoCwd:tx,handleEditContent:tv,cancelEdit:tb,handleModelChange:ty,handleCompact:tw,handleSteer:tk,handleFollowUp:tj,handlePromptWithStreamingBehavior:tS,handleAbortCompaction:tC,dismissCompactError:tN,handleRecallQueue:tE,handleBuiltinSlashCommand:t$,handleToolPresetChange:tI,handleThinkingLevelChange:tM,handleSetDefaultModel:tT,handleSetDefaultThinkingLevel:tR,loadSlashCommands:tA,loadAllModels:tL,scrollUserMsgToTop:tz,loadContext:tP,activeLeafId:tW,scrollToBottom:tO,scrollToMessage:tF}=function(e){var t;let r,s,{session:l,newSessionCwd:o,newSessionDraftKey:a,onAgentEnd:d,onSessionEnded:c,onToolEnd:u,onAttentionNeeded:p,onSessionCreated:h,onSessionForked:f,onSideSession:g,modelsRefreshKey:x,onBranchDataChange:v,onSystemPromptChange:b,onSystemToolsChange:y,onSystemInfoLoaderChange:w,onSessionStatsPanelOpen:k,onOpenSettings:j,onDebugSnapshotReaderChange:S}=e,C=null===l&&null!==o,N=C?e.initialNewSessionChoices??null:null,[E,$]=(0,i.useState)(null),[I,M]=(0,i.useState)(!C),[T,z]=(0,i.useState)(null),[P,F]=(0,i.useState)(null),[D,B]=(0,i.useState)([]),[H,_]=(0,i.useState)(new Map),[U,K]=(0,i.useState)(lK),[q,V]=(0,i.useState)([]),[Z,J]=(0,i.useState)(()=>new Map),[Y,G]=(0,i.useState)(null),[X,Q]=(0,i.useState)(!1),[ee,et]=(0,i.useState)(0),[en]=(0,i.useState)(cL),er=en.dispatch,[ei,es]=(0,i.useState)(!1),[el,eo]=(0,i.useState)(!1),[ea,ed]=(0,i.useState)(null),[ec,eu]=(0,i.useState)({}),[ep,eh]=(0,i.useState)([]),[ef,em]=(0,i.useState)(null),[eg,ex]=(0,i.useState)(null),[ev,eb]=(0,i.useState)(null),ey=ev??eg,[ew,ek]=(0,i.useState)([]),[ej,eS]=(0,i.useState)(!1),[eC,eN]=(0,i.useState)(null),eE=(0,i.useRef)(null),[e$,eI]=(0,i.useState)({}),[eM,eT]=(0,i.useState)({}),[eR,eA]=(0,i.useState)(()=>N?.model??null),[eL,ez]=(0,i.useState)(null),[eP,eW]=(0,i.useState)(cc.Q8),[eO,eF]=(0,i.useState)(()=>N?.thinkingLevel??null),[eD,eB]=(0,i.useState)(null),[eH,e_]=(0,i.useState)(null),[eU,eK]=(0,i.useState)(null),[eq,eV]=(0,i.useState)(null),[eZ,eJ]=(0,i.useState)(null),[eY,eG]=(0,i.useState)(null),[eX,e0]=(0,i.useState)(null),e1=(0,i.useRef)(0),e2=(0,i.useRef)(0),[e4,e8]=(0,i.useState)(null),[e3,e5]=(0,i.useState)(null),[e6,e9]=(0,i.useState)(null),[e7,te]=(0,i.useState)(null),[tt,tn]=(0,i.useState)(null),[tr,ti]=(0,i.useState)(!1),[ts,tl]=(0,i.useState)(!1),[to,tc]=(0,i.useState)(!0),[tu,tp]=(0,i.useState)(null),[tf,tm]=(0,i.useState)(null),[tg,tx]=(0,i.useState)(null),[tv,tb]=(0,i.useState)(!1),[ty,tw]=(0,i.useState)(!1),[tk,tj]=(0,i.useState)([]),[tS,tC]=(0,i.useState)(!1),[tN,tE]=(0,i.useReducer)(cq,{visible:[],pending:[]}),[t$,tI]=(0,i.useState)(null),[tM,tT]=(0,i.useState)([]),[tR,tA]=(0,i.useState)([]),[tL,tz]=(0,i.useState)([]),[tP,tW]=(0,i.useState)([]),[tO,tF]=(0,i.useState)({steering:[],followUp:[]}),tD=(0,i.useRef)(null),tB=(0,i.useRef)(null),tH=(0,i.useRef)(0),t_=(0,i.useRef)(!1),tU=(0,i.useRef)(!1),[tK,tq]=(0,i.useState)(0),tV=(0,i.useRef)(null),tZ=(0,i.useRef)(()=>{}),tJ=(0,i.useRef)({renewStartedAt:null,inFlightSince:null,requests:0,unanswered:0,errors:0,last:null}),tY=(0,i.useRef)({count:0,lastAt:null}),tG=(0,i.useRef)({count:0,lastAt:null,lastReason:null}),tX=(0,i.useRef)(null),tQ=(0,i.useRef)(null),t0=(0,i.useRef)(!1),t1=(0,i.useRef)(0),t2=(0,i.useRef)(l?.id??null),t4=(0,i.useRef)(null),t8=(0,i.useRef)(l?.id??null),t3=(0,i.useRef)(!1),t5=(0,i.useRef)(!1),t6=(0,i.useRef)(!1),t9=(0,i.useRef)(!1),t7=(0,i.useRef)(-1),ne=(0,i.useRef)(!1),nt=(0,i.useRef)(0),nn=(0,i.useRef)(0),nr=(0,i.useRef)(null),ni=(0,i.useRef)(!!e.deferInitialScroll),ns=(0,i.useRef)(null),nl=(0,i.useRef)(!1),no=(0,i.useRef)(!0),na=(0,i.useRef)(0),nd=(0,i.useRef)(null),nc=(0,i.useRef)(void 0),nu=(0,i.useRef)(void 0),np=(0,i.useRef)(null),nh=(0,i.useRef)(null),nf=(0,i.useRef)([]),nm=(0,i.useRef)(null),ng=(0,i.useRef)(0),nx=(0,i.useRef)(!1),nv=(0,i.useRef)(N?.model??null),nb=(0,i.useRef)(N?.thinkingLevel??null),ny=(0,i.useRef)({}),nw=(0,i.useRef)(null),nk=(0,i.useRef)(0),nj=(0,i.useRef)(null),nS=(0,i.useRef)(null),nC=(0,i.useRef)(null),nN=(0,i.useRef)(0),nE=(0,i.useRef)(null),n$=(0,i.useCallback)(()=>{nS.current=nk.current,nC.current?.runId===nk.current&&(nC.current=null)},[]),nI=(0,i.useRef)(!1),nM=(0,i.useRef)(new Map),nT=(0,i.useRef)(!0),nR=(0,i.useRef)(new Map),nA=(0,i.useRef)(null),nL=(0,i.useRef)([]),nz=(0,i.useRef)([]),nP=(0,i.useRef)(null),nW=(0,i.useRef)(null),nO=(0,i.useRef)(!1),nF=(0,i.useRef)(0);t8.current=l?.id??null,nA.current=E,nL.current=D,nz.current=q,nP.current=P,nW.current=Y,nO.current=X,nF.current=ee,t0.current=ts,t1.current=tM.length+tR.length;let nD=(0,i.useCallback)(e=>nT.current&&t4.current!==e&&t2.current===e&&(t5.current||t_.current||t8.current===e&&!tU.current),[]);tD.current||(tD.current=new ck({createSource:e=>th("agent",new EventSource(`/api/agent/${encodeURIComponent(e)}/events?holder=${encodeURIComponent(td())}`),e),onEvent:e=>nr.current?.(e),shouldMaintain:nD,readinessTimeoutMs:6e4,reconnectDelayMs:1e3,staleAfterMs:75e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let nB=e.setToolPreset??eW,nH=l?.id;(0,i.useLayoutEffect)(()=>{(nH||C&&!t2.current)&&nB(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:cp();if(!e)return cc.Q8;try{let t=e.getItem(cu);return(0,cc.sn)(t)?t:cc.Q8}catch{return cc.Q8}}())},[nH,C,nB]);let n_=e.onNewSessionChoicesChange;(0,i.useEffect)(()=>{C&&n_?.({model:eR,thinkingLevel:eO})},[C,eR,eO,n_]);let nU=(0,i.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"smooth",t=np.current;t&&(t.scrollTo({top:t.scrollHeight,behavior:e}),na.current=t.scrollTop)},[]),nK=e6??e7??E?.context.model??tt??null,nq=C?eR??eL:nK??(E?.context.messages.length===0?eL:null),nV=cO(E?.context.thinkingLevel&&"off"!==E.context.thinkingLevel?E.context.thinkingLevel:null),nZ=C?eO??eD:eU??eq??nV??(E?.context.messages.length===0?eD:null),nJ=l?.id??a??void 0,nY=(0,i.useCallback)(e=>{te(e?.model?{provider:e.model.provider,modelId:e.model.id}:null),e?.thinkingLevel!==void 0&&eV(cO(e.thinkingLevel))},[]),nG=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=nM.current.get(t);if(!e)break;t=e}return t},[]),nX=(0,i.useCallback)((t,n,r)=>{let i=n?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}}),s=nG(r);if(!nT.current&&!nx.current&&r===a)return;let l=e.chatInputRef?.current;l?l.restoreSubmission(t,i,s):s&&W(s,t,i)},[a,e.chatInputRef,nG]),[nQ,n0]=(0,i.useState)(()=>{let e=l?.id;return e&&!R(e)&&cB(e,null),e&&cF.get(e)||null}),n1=(0,i.useCallback)(e=>{l?.id&&(cB(l.id,e),n0(e))},[l?.id]),n2=(0,i.useCallback)((t,n)=>{l?.id&&(e.chatInputRef?.current?.replaceMessage(t),n1(n))},[e.chatInputRef,l?.id,n1]),n4=(0,i.useCallback)(()=>n1(null),[n1]),n8=(0,i.useMemo)(()=>{let e=E?.totalActiveMs,t=eX&&eX.sessionId===E?.sessionId?eX.value:void 0,n=void 0===e&&void 0===t?void 0:Math.max(e??0,t??0);if(t$)return{...t$,totalActiveMs:n,...eY?{contextUsage:eY}:{}};let r=E?.stats,i=function(e,t,n){let r=cf(n);if(!e)return r;let i=cf(t),s=(e,t)=>Math.max(0,e-t),l={input:e.tokens.input+s(r.tokens.input,i.tokens.input),output:e.tokens.output+s(r.tokens.output,i.tokens.output),cacheRead:e.tokens.cacheRead+s(r.tokens.cacheRead,i.tokens.cacheRead),cacheWrite:e.tokens.cacheWrite+s(r.tokens.cacheWrite,i.tokens.cacheWrite),total:0};return l.total=l.input+l.output+l.cacheRead+l.cacheWrite,{userMessages:e.userMessages+s(r.userMessages,i.userMessages),assistantMessages:e.assistantMessages+s(r.assistantMessages,i.assistantMessages),toolCalls:e.toolCalls+s(r.toolCalls,i.toolCalls),toolResults:e.toolResults+s(r.toolResults,i.toolResults),totalMessages:e.totalMessages+s(r.totalMessages,i.totalMessages),tokens:l,cost:e.cost+s(r.cost,i.cost)}}(r,E?.context.messages??[],D);return 0!==i.tokens.total||0!==D.length||r?{sessionFile:E?.filePath||void 0,sessionId:t2.current??l?.id??"",sessionName:l?.name,...i,totalActiveMs:n,...eY?{contextUsage:eY}:{}}:null},[D,t$,eY,eX,E?.sessionId,E?.context.messages,E?.filePath,E?.totalActiveMs,E?.stats,l?.id,l?.name]),n3=(0,i.useCallback)((e,t,n,r)=>{nT.current&&t2.current===t&&nk.current===n&&!(r<=e2.current)&&(e2.current=r,e?.contextUsage!==void 0&&eG(e.contextUsage??null),"number"==typeof e?.totalActiveMs&&e0({sessionId:t,value:e.totalActiveMs}))},[]),n5=(0,i.useCallback)(async e=>{let t=nk.current,n=++e1.current;try{let r=await fetch(d7(e));if(!r.ok)return;let i=await r.json();n3(i.state,e,t,n)}catch{}},[n3]),n6=(0,i.useCallback)(async function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3?arguments[3]:void 0,i=r?.force?`force:${e}`:e,s=r?.force?void 0:nR.current.get(i);if(s)return await s;let l=(async()=>{let i=!1,s=++nN.current,l=!t5.current;try{t&&M(!0);let o=new URLSearchParams({deferThinking:"1",deferMedia:"1",tree:"summary"});r?.force&&o.set("force","1");let a=await fetch(`/api/sessions/${encodeURIComponent(e)}?${o}`);if(404===a.status)return t&&($(null),F(null),B([]),V([]),G(null),Q(!1),et(0),z(null)),cd(e),null;if(!a.ok)throw Error(`HTTP ${a.status}`);let d=await a.json();if(t2.current!==e)return null;(nE.current?.seq??0)<s&&(nE.current={sid:e,seq:s,messages:d.context.messages,entryIds:d.context.entryIds??[]});let c=co(e),u=!!(d.snapshotRevision&&c?.revision===d.snapshotRevision&&c.entryIds.length>=(d.context.entryIds??[]).length),p=u?nL.current:d.context.messages;if($(u?{...d,context:{...d.context,messages:nL.current,entryIds:nz.current,oldestEntryId:nW.current,hasMore:nO.current,turnsBefore:nF.current}}:d),F(d.leafId),u)ca({sessionId:e,revision:d.snapshotRevision,messages:nL.current,entryIds:nz.current,leafId:d.leafId,oldestEntryId:nW.current,hasMore:nO.current,turnsBefore:nF.current,summaryTree:d.tree,thinkingLevel:d.context.thinkingLevel,model:d.context.model,stats:d.stats,totalActiveMs:d.totalActiveMs,loadedEntryIds:nz.current});else{let e={messages:nL.current,entryIds:nz.current},t={messages:p,entryIds:d.context.entryIds??[]};J(n=>(function(e,t){let n=new Set(t.entryIds),r=new Map([...e.aliases].filter(e=>{let[t]=e;return n.has(t)})),i=e.entryIds.length,s=e.entryIds[i-1],l=void 0===s?0:t.entryIds.indexOf(s)+1;if(0===l&&void 0!==s)return r;for(let n=0;i+n<e.messages.length;n++){var o,a;let d=t.entryIds[l+n];if(void 0===d||(o=e.messages[i+n],a=t.messages[l+n],o.role!==a.role||("user"===o.role?cb(o)!==cb(a):"custom"===o.role?o.customType!==a.customType:o.timestamp!==a.timestamp)))break;r.set(d,cy(s,n))}return r})({...e,aliases:n},t)),B(t.messages),V(t.entryIds),G(d.context.oldestEntryId),Q(d.context.hasMore),et(d.context.turnsBefore??0)}if(t3.current=void 0!==d.toolNames,nB(void 0!==d.toolNames?(0,cc.YO)(d.toolNames):cc.Q8),e9(e=>nI.current?e:null),eK(null),z(null),"summary"===d.treeFormat&&d.snapshotRevision&&ca({sessionId:e,revision:d.snapshotRevision,messages:p,entryIds:d.context.entryIds??[],leafId:d.leafId,oldestEntryId:d.context.oldestEntryId,hasMore:d.context.hasMore,turnsBefore:d.context.turnsBefore??0,summaryTree:d.tree,thinkingLevel:d.context.thinkingLevel,model:d.context.model,stats:d.stats,totalActiveMs:d.totalActiveMs,loadedEntryIds:d.context.entryIds??[]}),d.wrapperRebuilt&&(tD.current?.close("rebuilt"),tD.current?.maintain(e)),!n&&d.context.thinkingLevel&&"off"!==d.context.thinkingLevel&&eV(cO(d.context.thinkingLevel)),i=!0,l&&s>nt.current&&ed(e=>e?.result?null:e),t&&M(!1),!n)return null;try{let t=nk.current,n=++e1.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(t2.current!==e)return null;let s=i.state;return nY(s),s?(n3(s,e,t,n),void 0!==s.systemPrompt&&e8(s.systemPrompt??null),void 0!==s.extensionStatuses&&tz(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tW(s.extensionWidgets??[]),void 0!==s.queuedMessages&&tF(cW(s.queuedMessages)),void 0!==s.autoCompactionEnabled&&tc(s.autoCompactionEnabled??!0)):i.running||tF({steering:[],followUp:[]}),i}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return z(String(e)),"error"}finally{t&&!i&&M(!1)}})();return nR.current.set(i,l),l.finally(()=>{nR.current.get(i)===l&&nR.current.delete(i)}),await l},[n3,nB,nY]),n9=(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}`,l=await fetch(s,{signal:r?.signal});if(!l.ok)throw Error(`HTTP ${l.status}`);let o=await l.json();if(t2.current!==e||r?.signal?.aborted||!nT.current)return;return G(o.context.oldestEntryId),Q(o.context.hasMore),et(o.context.turnsBefore??0),$(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?(B(e=>[...o.context.messages,...e]),V(e=>[...o.context.entryIds,...e])):(B(o.context.messages),V(o.context.entryIds??[])),o.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),n7=(0,i.useCallback)(async e=>{try{let t=await ce(e,{type:"get_tools"});if(!t||!nT.current||t2.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return nB(t3.current?r(t):cc.Q8),y?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[y,nB]),re=(0,i.useCallback)(function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"(no messages)",r=t2.current;if(C&&o&&r&&!nx.current&&(nx.current=!0,a)){if(a!==r){nM.current.set(a,r);let t=e.chatInputRef?.current;t?t.rekeyDraft(a,r):O(a,r)}h?.({id:r,path:"",cwd:o,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0},a)}},[C,o,a,h,e.chatInputRef]),rt=(0,i.useCallback)((e,t,n)=>{e.model&&nv.current===t&&(tn(e.model),t||ez(e.model)),e.thinkingLevel&&nb.current===n&&(eV(cO(e.thinkingLevel)),n||eB(cO(e.thinkingLevel)))},[]),rn=(0,i.useCallback)(async()=>{if(t2.current||!C||!o)return t2.current;if(nh.current)return nh.current;let e=(async()=>{let e=nv.current,t=nb.current;e&&tn(e);let n=(0,cc.xG)(eP);t3.current=void 0!==n;let r=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:o,type:"ensure_session",...void 0!==n?{toolNames:n}:{},...e?{provider:e.provider,modelId:e.modelId}:{},...t?{thinkingLevel:t}:{}})});if(!r.ok){let e=await r.json().catch(()=>null),t="string"==typeof e?.error?e.error:`HTTP ${r.status}`,n=d5(e);throw n?new d6(t,r.status,void 0,void 0,n):Error(t)}let i=await r.json(),s=i.sessionId;return t2.current=s,rt(i,e,t),s})();nh.current=e;try{return await e}finally{nh.current=null}},[rt,C,o,eP]),rr=(0,i.useCallback)(async()=>{let e=t2.current??await rn();if(!e)return;let[t]=await Promise.all([ce(e,{type:"get_state"}),n7(e)]);nT.current&&t2.current===e&&(nY(t),e8(t.systemPrompt??""))},[rn,n7,nY]),ri=(0,i.useCallback)(e=>{nf.current=e,tj(e)},[]),rs=(0,i.useCallback)(()=>{ng.current+=1,nm.current=null,ri([])},[ri]),rl=(0,i.useCallback)(async(e,t)=>{let n=null===t8.current&&nT.current;n&&tD.current?.ensureConnected(e).catch(()=>{});try{return await t()}finally{!n||null!==t8.current||t2.current!==e||0!==t1.current||t5.current||ne.current||tD.current?.close("grace_end")}},[]),ro=(0,i.useCallback)(()=>{let e=++ng.current,t=(async()=>{let t=t2.current??await rn();if(!t)return ng.current===e&&ri([]),[];tC(!0);try{let n=await rl(t,()=>ce(t,{type:"get_commands"})),r=n?.commands??[];return ng.current===e&&ri(r),r}catch(t){return console.error("Failed to load slash commands:",t),ng.current===e&&ri([]),null}finally{ng.current!==e&&nm.current||tC(!1)}})();nm.current=t;let n=()=>{nm.current===t&&(nm.current=null)};return t.then(n,n),t},[rn,ri,rl]),ra=(0,i.useCallback)(async()=>await ro()??[],[ro]),rd=(0,i.useCallback)(async()=>{let e=nm.current,t=nf.current;return!e&&t.length>0?t:await (e??ro()).catch(()=>null)??(t.length>0?t:null)},[ro]),rc=(0,i.useCallback)(()=>{tH.current+=1,t_.current=!1,tQ.current=null,tB.current&&(clearTimeout(tB.current),tB.current=null)},[]),ru=(0,i.useCallback)(e=>{tD.current?.close(e)},[]),rp=(0,i.useCallback)(e=>tD.current.ensureConnected(e),[]),rh=(0,i.useCallback)(e=>{tD.current.maintain(e)},[]);(0,i.useEffect)(()=>{let e=l?.id;if(e)return nT.current=!0,tU.current=!1,rh(e),()=>{t2.current===e&&tD.current?.close("deselected")}},[rh,l?.id]);let rf=(0,i.useCallback)(e=>{let t=tV.current;if(t?.sid===e)return t.promise;let n=new AbortController,r=setTimeout(()=>n.abort(),5e3),i={sid:e,promise:Promise.resolve(null)};return i.promise=(async()=>{let t=null,s=null,l=Date.now();tJ.current.inFlightSince=l,tJ.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),tV.current===i&&(tV.current=null);try{let e=tJ.current,n=Date.now(),r="unanswered"===s?"unanswered":null===s?"error":"reply";"unanswered"===r&&(e.unanswered+=1),"error"===r&&(e.errors+=1);let i="object"==typeof s&&null!==s?s:null;e.inFlightSince=null,e.last={at:n,durationMs:Math.max(0,n-l),outcome:r,httpStatus:t,reply:i&&{running:!0===i.running,awaitingInput:!0===i.awaitingInput,subagentsActive:!0===i.subagentsActive}}}catch{}}})(),tV.current=i,i.promise},[]),rm=!ei&&!el&&!ts&&0===tM.length&&0===tR.length;(0,i.useEffect)(()=>{let e=l?.id;if(!e||!rm)return;let t=!1,n=null,r=()=>!t&&"hidden"===document.visibilityState&&!tU.current&&t2.current===e&&t8.current===e&&!t5.current&&!ne.current,i=async()=>{if(n=null,tX.current=null,!r())return;let t=await rf(e);if(r()){if(!("unanswered"===t||t&&!cj(t)))return void s();tU.current=!0,tY.current={count:tY.current.count+1,lastAt:Date.now()},ru("released")}},s=()=>{null===n&&(n=setTimeout(()=>void i(),3e4),tX.current=Date.now()+3e4)},o=()=>{"hidden"===document.visibilityState?s():n&&(clearTimeout(n),n=null,tX.current=null)};return"hidden"===document.visibilityState&&s(),document.addEventListener("visibilitychange",o),()=>{t=!0,n&&clearTimeout(n),tX.current=null,document.removeEventListener("visibilitychange",o)}},[ru,rm,tK,rf,l?.id]);let rg=(0,i.useCallback)(async(e,t)=>{let n=t2.current;if(tT(t=>d4(t,e.id)),!n)return;try{await ce(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e);return}if(null!==t8.current)return;let r=nv.current,i=nb.current;try{let e=await ce(n,{type:"get_state"});if(!nT.current||t2.current!==n||null!==t8.current)return;rt({model:e.model?{provider:e.model.provider,modelId:e.model.id}:null,thinkingLevel:e.thinkingLevel},r,i),void 0!==e.systemPrompt&&e8(e.systemPrompt)}catch{}},[rt]),rx=(0,i.useCallback)(async(e,t)=>{let n=t2.current;if(n)try{await ce(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),rv=(0,i.useCallback)(e=>{let t=e.message.trim();t&&tE({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"}})},[]),rb=(0,i.useRef)(e.t);rb.current=e.t;let ry=(0,i.useCallback)((e,t)=>rb.current(e,t),[]),rw=(0,i.useCallback)(()=>{rv({type:"warning",message:ry("chat.sendUnconfirmed")})},[rv,ry]),rk=(0,i.useCallback)(e=>{nT.current&&B(t=>cz(t,e.bubble));let t=co(e.sid);t?.messages.includes(e.bubble)&&ca({...t,messages:cz(t.messages,e.bubble)})},[]),rj=(0,i.useCallback)((e,t,n)=>{let r=nC.current;if(!r||r.runId!==t||r.sid!==e)return;nC.current=null;let i=nE.current,s=i?.sid===e&&i.seq>n?i:null,l=s?null===r.lastEntryIdAtSend?0:s.entryIds.indexOf(r.lastEntryIdAtSend)+1||-1:-1;s&&l>=0&&cP(s.messages.slice(l),r.key)>r.sameTextAfterSend||(nX(r.message,r.images,r.draftKey),s&&rk(r),rv(s&&!r.command&&l===s.entryIds.length?{type:"error",message:ry("chat.sendNotReceived")}:{type:"warning",message:ry("chat.sendUnconfirmed")}))},[rv,rk,nX,ry]),rS=(0,i.useCallback)(()=>{let e=nC.current;if(nC.current=null,e){if(e.parkedDraftKey){let t=e.images?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});W(e.parkedDraftKey,e.message,t)}else nX(e.message,e.images,e.draftKey);rk(e)}},[rk,nX]),rC=(0,i.useRef)(rS);rC.current=rS;let rN=(0,i.useCallback)(t=>{switch(d1(t)&&p?.(t),t.method){case"select":case"confirm":case"input":case"editor":tT(e=>e.some(e=>e.id===t.id)?e:[...e,t]);break;case"notify":if(t.id&&!c_(t.id))break;rv({id:t.id,message:io(t.message),type:t.notifyType??"info"});break;case"setStatus":tz(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":tW(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=io(t.title));break;case"set_editor_text":e.chatInputRef?.current?.setText(io(t.text));break;case"custom":tA(e=>{let n;return t.closed?d4(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)})}},[rv,p,e.chatInputRef]),rE=(0,i.useCallback)(()=>{let e=t5.current;return t5.current=!1,es(!1),tx(null),eJ(null),_(new Map),K(lK),er({type:"end"}),e},[er]),r$=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t7.current!==e&&(t7.current=e,d?.({aborted:t,...n?{subagentsActive:n}:{}}),!0)},[d]),rI=(0,i.useCallback)(e=>{if(t8.current===e)return void rc();rc(),t_.current=!0;let t=tH.current,n=async()=>{if(t===tH.current&&t2.current===e&&t_.current)try{let r=await fetch(d7(e));if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(t!==tH.current||t2.current!==e||!t_.current)return;let s=i.state;if(nY(s),i.running&&s&&(s.isStreaming||s.isPromptRunning)){t_.current=!1,tB.current=null,tQ.current=null,t6.current=!!s?.isStreaming,t9.current=!!s?.isPromptRunning,t5.current=!0,es(!0),tx(e=>d0(e,!!s?.isStreaming));return}if(i.running&&s?.isCompacting){tl(!0),tB.current=setTimeout(()=>void n(),600),tQ.current=Date.now()+600;return}t_.current=!1,tB.current=null,tQ.current=null,ru("grace_end")}catch{if(t!==tH.current||t2.current!==e||!t_.current)return;tB.current=setTimeout(()=>void n(),600),tQ.current=Date.now()+600}};tB.current=setTimeout(()=>void n(),3e4),tQ.current=Date.now()+3e4},[rc,ru,nY]),rM=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:t2.current,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nk.current;if(nk.current!==t)return;let n=nN.current;try{e&&await n6(e)}finally{if(nk.current!==t)return;e&&rj(e,t,n);let r=t9.current,i=t6.current;t9.current=!1,t6.current=!1,nj.current=null;let s=rE();r?r$(t):i&&s&&d?.({aborted:!1}),e&&rI(e)}},[n6,r$,d,rI,rE,rj]),rT=(0,i.useCallback)(async(e,t)=>{await cU(800);let n=Date.now();for(;t5.current&&Date.now()-n<2e4;){if(void 0!==t&&nk.current!==t)return;try{let n=await fetch(d7(e));if(n.ok){let r=await n.json(),i=r.state;if(nY(i),!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await rM(e,t)}}catch{}await cU(600)}},[rM,nY]),rR=(0,i.useCallback)(async e=>{let t=nn.current+1;for(nn.current=t;ne.current&&nn.current===t&&t2.current===e;){await cU(1e3);try{let n=await fetch(d7(e));if(!n.ok)continue;let r=await n.json();if(nY(r.state),r.state?.isBashRunning)continue;if(await n6(e),nn.current!==t||t2.current!==e)return;ne.current=!1,eo(!1),ed(null);return}catch{}}},[n6,nY]),rA=(0,i.useCallback)(async e=>{if(!t5.current||t2.current!==e)return;let t=nk.current,n=++e1.current;try{let r=await fetch(d7(e));if(!r.ok)return;let i=await r.json();if(t2.current!==e||nk.current!==t)return;let s=i.state;if(n3(s,e,t,n),nY(s),tl(s?.isCompacting??!1),tc(s?.autoCompactionEnabled??!0),tF(cW(s?.queuedMessages)),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isCompacting)){t6.current=!!s.isStreaming,t9.current=!!s.isPromptRunning;return}if(!t5.current)return;s&&(void 0!==s.extensionStatuses&&tz(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tW(s.extensionWidgets??[]),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(t=>{t&&nT.current&&t2.current===e&&t.state?.systemPrompt!==void 0&&e8(t.state.systemPrompt??null)}).catch(()=>{})),await rM(e,t)}catch{}},[n3,rM,nY]);(0,i.useEffect)(()=>{if(!ei)return;let e=()=>{let e=t2.current;e&&rA(e)},t=()=>{"visible"===document.visibilityState&&e()},n=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[ei,rA]),(0,i.useEffect)(()=>{t5.current=ei},[ei]);let rL=(0,i.useCallback)(e=>nT.current&&t2.current===e&&!t5.current,[]),rz=(0,i.useRef)(null),rP=(0,i.useRef)(null),rW=(0,i.useCallback)(async e=>{var t;let n,r=new URLSearchParams({deferThinking:"1",deferMedia:"1",tail:"1"}),i=await fetch(`/api/sessions/${encodeURIComponent(e)}/context?${r}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let{context:s,leafId:l}=await i.json();if(!rL(e))return;let o=nz.current.at(-1),a=nL.current.at(-1),d=void 0!==o&&nL.current.length===nz.current.length?(n=(t={messages:s.messages,entryIds:s.entryIds??[]}).entryIds.lastIndexOf(o))<0?null:{messages:t.messages.slice(n+1),entryIds:t.entryIds.slice(n+1)}:null;if(!d)return void await n6(e);if(0===d.entryIds.length)return;if(ne.current&&d.messages.some(e=>"bashExecution"===e.role)){rP.current=e;return}nz.current=[...nz.current,...d.entryIds],nL.current=[...nL.current,...d.messages],V(e=>e.at(-1)===o?[...e,...d.entryIds]:e),B(e=>e.at(-1)===a?[...e,...d.messages]:e),l&&(rz.current={base:nP.current,lastEntryId:d.entryIds.at(-1),leafId:l});let c=co(e);c&&ca({...c,loadedEntryIds:[...c.loadedEntryIds,...d.entryIds]})},[rL,n6]),rO=(0,i.useRef)(rW);rO.current=rW;let rF=(0,i.useRef)(null);rF.current??=(t={pendingReads:e=>[nR.current.get(e),nR.current.get(`force:${e}`)],read:e=>rO.current(e),wanted:rL,onError:e=>console.error("Failed to read a message sent while idle:",e)},r=!1,s=null,e=>{s=e,r||(r=!0,(async()=>{try{for(;null!==s;){let e=s;if(s=null,t.wanted(e))try{await Promise.allSettled(t.pendingReads(e)),t.wanted(e)&&await t.read(e)}catch(e){t.onError?.(e)}}}finally{r=!1}})())}),nr.current=(0,i.useCallback)(t=>{if(!t4.current)switch(t.type){case"session_ended":{let e=t2.current;if(!e||t.sessionId!==e)return;t4.current=e,rc(),tD.current?.close(),cd(e),c?.(e);return}case"connected":if(er({type:"end"}),Array.isArray(t.pendingExtensionUiIds)){let e=new Set(t.pendingExtensionUiIds);tT(t=>d2(t,e)),tA(t=>d2(t,e))}K(lJ),!0===t.isStreaming&&(rc(),t6.current=!0,t5.current=!0,es(!0),tx({kind:"waiting_model"})),t2.current&&n5(t2.current);break;case"agent_start":n$(),rc(),t6.current=!0,t5.current=!0,es(!0),tx({kind:"waiting_model"}),eJ(null),er({type:"start"});break;case"agent_end":if(!t5.current)break;if(tx(null),eJ(null),er({type:"end"}),t2.current){let e=t2.current,t=nk.current,n=++e1.current;n6(e),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(r=>{r&&nT.current&&t2.current===e&&nk.current===t&&(nY(r.state),n3(r.state,e,t,n),r.state?.systemPrompt!==void 0&&e8(r.state.systemPrompt??null),r.state?.extensionStatuses!==void 0&&tz(r.state.extensionStatuses??[]),r.state?.extensionWidgets!==void 0&&tW(r.state.extensionWidgets??[]),tF(cW(r.state?.queuedMessages)))}).catch(()=>{})}break;case"agent_settled":{let e=t6.current;if(t6.current=!1,!e||t9.current)break;let n=t2.current,r=rE();tl(!1),n&&(n6(n),rI(n)),r&&d?.({aborted:!0===t.aborted,...!0===t.subagentsActive?{subagentsActive:!0}:{}});break}case"prompt_done":{n$();let e=nk.current,n=t9.current;t9.current=!1,nj.current=null;let r=r$(e,!0===t.aborted,!0===t.subagentsActive);if(!n&&!r)break;let i=t2.current;i&&n6(i),!t6.current&&(rE(),i&&rI(i))}break;case"prompt_error":rv({type:"error",message:t.errorMessage??"Command failed"});break;case"extension_error":var n,r;rv({type:"error",message:(n=t.extensionPath,r=t.error??"Extension command failed","string"==typeof n&&n&&!cM.test(n)?`Extension "${n}" error: ${r}`:r)});break;case"message_start":case"message_update":if(!t5.current||c$(t))break;if("message_start"===t.type){let e=t.message;if(e?.role==="user")break;e?.role==="assistant"?(er({type:"snapshot",message:e}),e.content.length>0&&tx(null)):e&&tx(null)}else{let e=t.assistantMessageEvent;e&&(er({type:"delta",event:e}),"toolcall_start"!==e.type&&"toolcall_delta"!==e.type&&tx(null))}!nl.current&&no.current&&null===nd.current&&(nd.current=requestAnimationFrame(()=>{nd.current=null,no.current&&nU("auto")}));break;case"message_end":{if(!t5.current){let e=t.message;e?.role==="custom"&&!ib(e)&&t2.current&&rF.current?.(t2.current);break}if(c$(t))break;let e=t.message;if(e&&"user"===e.role){let t=d3(e),n=cb(t),r=nj.current;nj.current=null,r&&n$(),B(e=>{let i=e[e.length-1];return r&&i?.role==="user"&&cb(i)===r?r===n?e:[...e.slice(0,-1),t]:[...e,t]})}else if(e){let n=Array.isArray(t.transcriptNotices)?t.transcriptNotices:void 0;if(B(t=>{var r;return[...t,(r=d3(e),n&&0!==n.length?{...r,[om]:[...n]}:r)]}),"toolResult"===e.role){let t=e.toolCallId;K(e=>lZ(e,t))}if("assistant"===e.role){let e=t2.current;e&&n5(e)}}er({type:"end"}),tx({kind:"waiting_model"});break}case"tool_execution_start":{if(cE(t))break;let e=t.toolCallId,n=t.toolName,r=performance.now();K(e=>lV(e,t,r)),tx(t=>{let r=t?.kind==="running_tools"?[...t.tools]:[];return r.some(t=>t.id===e)||r.push({id:e,name:n}),{kind:"running_tools",tools:r}});break}case"tool_execution_update":{if(cE(t))break;let e=t.toolCallId,n=t.toolName,r=t.partialResult,i=r?.content;("bash"===n||"powershell"===n||n===oe)&&Array.isArray(i)&&_(t=>{let s=new Map(t);return s.set(e,{role:"toolResult",toolCallId:e,toolName:n,content:i,isError:r?.isError,details:r?.details}),s});let s=n===oe?function(e){if(!on(e))return null;let{calls:t}=oi(e.details),n=t.findLast(e=>"running"===e.status)??t.at(-1);if(!n)return null;let r=n.args;if(r.length>120){let e=117,t=r.charCodeAt(e-1);t>=55296&&t<=56319&&e--,r=`${r.slice(0,e)}...`}return r?`${n.name} ${r}`:n.name}(t.partialResult):function(e){if(!cI(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>cI(e)&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n").split(/\r?\n/),r="";for(let e=n.length-1;e>=0&&!(r=n[e].trim());e-=1);if(!r)return null;let i=r.replace(/\s+/g," ");return i.length<=500?i:`...${i.slice(-497)}`}(t.partialResult);tx(t=>{let r=t?.kind==="running_tools"?[...t.tools]:[],i=r.find(t=>t.id===e),l={id:e,name:n||i?.name||"tool",progress:s??i?.progress};return{kind:"running_tools",tools:[...r.filter(t=>t.id!==e),l]}});break}case"tool_execution_end":{if(cE(t))break;let e=t.toolCallId;u?.(t.toolName);let n=performance.now();K(e=>lV(e,t,n)),_(t=>{if(!t.has(e))return t;let n=new Map(t);return n.delete(e),n}),tx(t=>{if(t?.kind!=="running_tools")return t;let n=t.tools.filter(t=>t.id!==e);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"queue_update":n$(),tF({steering:[...t.steering??[]],followUp:[...t.followUp??[]]});break;case"auto_retry_start":case"summarization_retry_scheduled":eJ({attempt:t.attempt,maxAttempts:t.maxAttempts,errorMessage:t.errorMessage});break;case"auto_retry_end":case"summarization_retry_attempt_start":case"summarization_retry_finished":eJ(null);break;case"auto_compaction_start":case"compaction_start":tl(!0),tp(null),tm(null);break;case"auto_compaction_end":case"compaction_end":tl(!1),eJ(null),t.errorMessage?(tp(t.errorMessage),tm(null)):!t.aborted&&(tm(cV(t.result,t.reason??"auto")),t2.current&&n6(t2.current));break;case"bash_output":{let e=t.output;if(!ne.current||"string"!=typeof e)break;ed(n=>n&&!n.result&&n.command===t.command?{...n,liveOutput:e}:n);break}case"editor_paste":"string"==typeof t.text&&e.chatInputRef?.current?.pasteText(io(t.text));break;case"extension_ui_request":rN(t);break;case"extension_ui_closed":tT(e=>d4(e,t.id))}},[rv,n3,e.chatInputRef,rc,er,rN,n6,n$,r$,d,c,u,n5,rI,nU,rE,nY]);let rD=(0,i.useCallback)(async(e,t)=>{let n=e.trim();if(!n&&!t?.length)return;let r=!t?.length&&n.startsWith("!");if(ne.current||t5.current&&!r){ne.current&&r&&rv({type:"warning",message:ry("chat.bashAlreadyRunning")}),nX(e,t,nJ);return}if(nQ&&(n1(null),!await nu.current?.(nQ))){n1(nQ),nX(e,t,nJ);return}let i=!t?.length&&n.startsWith("/");if(r){let r=n.startsWith("!!"),i=(r?n.slice(2):n.slice(1)).trim();return i?void await nc.current?.(i,r):void nX(e,t,nJ)}let s=nk.current+1;rc(),t9.current=!0;let a=t?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),d={role:"user",content:a?.length?[...e.trim()?[{type:"text",text:e}]:[],...a]:e,timestamp:Date.now()},c=cb(d),u=nz.current,p=u.at(-1)??null,h=cP(nL.current.slice(u.length),c);B(e=>[...e,d]),nj.current=c,nk.current=s,t5.current=!0,es(!0),tx(i?{kind:"running_command"}:{kind:"waiting_model"}),er({type:"start"}),nl.current=!0,tb(!0);let f=()=>{B(e=>{let t=e.lastIndexOf(d);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),nj.current=null},g=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),x=null,v=!1;try{if(C&&o){let t=t2.current??await nh.current,n=t??await rn();if(!n)throw Error("Unable to create a session for the prompt");x=n,eR&&(tn(eR),t&&await ce(n,{type:"set_model",provider:eR.provider,modelId:eR.modelId})),nT.current&&await rp(n).catch(e=>{if(nT.current)throw e}),v=!0;let r=await ce(n,{type:"prompt",message:e,...g?.length?{images:g}:{}});r?.queued&&f(),re(1,e)}else if(l){x=l.id,await rp(l.id),v=!0;let t=await ce(l.id,{type:"prompt",message:e,...g?.length?{images:g}:{}});t?.queued&&f()}else throw Error("No active session for the prompt");eb(null),i&&x&&rT(x,s)}catch(n){if(console.error("Failed to send message:",n),!(!v||d9(n))&&x){nS.current!==s&&(nC.current={runId:s,sid:x,message:e,images:t,draftKey:nJ,parkedDraftKey:C&&o?m(o):null,lastEntryIdAtSend:p,sameTextAfterSend:h,bubble:d,key:c,command:i},nT.current||rS()),rT(x,s);return}if(t9.current=!1,B(e=>cz(e,d)),n instanceof d6&&n.missingCwd?eb(n.missingCwd):rv({type:"error",message:n instanceof Error?n.message:String(n)}),nX(e,t,nJ),nj.current=null,x)return void rA(x);t5.current=!1,ru("send_failed"),es(!1),tx(null),er({type:"end"})}},[C,o,eR,l,rn,rp,re,rT,rv,rS,rc,ru,nJ,er,rA,nX,nQ,n1,ry]);nc.current=(0,i.useCallback)(async(e,t)=>{if(ne.current)return;let n=`${t?"!!":"!"}${e}`;ne.current=!0;let r=Date.now();ed({command:e,excludeFromContext:t,startedAt:r}),eo(!0);let i=null;try{let s=t2.current??l?.id??await rn();if(!s)throw Error("Unable to create a session for the shell command");await rp(s).catch(()=>{});let o=await ce(s,{type:"bash",command:e,excludeFromContext:t});t5.current&&o?(i={command:e,excludeFromContext:t,startedAt:r,result:o},nt.current=nN.current):(await n6(s),re(1,n))}catch(e){console.error("Failed to execute shell command:",e),e instanceof d6&&"extension_reported"===e.code||rv({type:"error",message:e instanceof Error?e.message:String(e)}),nX(n,void 0,nJ)}finally{ne.current=!1,ed(i),eo(!1);let e=rP.current;rP.current=null,e&&rF.current?.(e)}},[rv,nJ,rp,rn,n6,re,nX,l]);let rB=ea?.result;(0,i.useEffect)(()=>{if(ei||!rB)return;let e=t2.current;e&&n6(e,!1,!1,{force:!0})},[ei,rB,n6]);let rH=(0,i.useCallback)(t=>{let n=[...t?.steering??[],...t?.followUp??[]].join("\n\n");t?.images?.length?nX(n,t.images,nJ):n&&e.chatInputRef?.current?.prependText(n)},[nJ,e.chatInputRef,nX]),r_=(0,i.useCallback)(async()=>{let e=t2.current;if(e){if(ne.current&&!t5.current){try{await ce(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{let t=await ce(e,{type:"abort"});t&&tF({steering:[],followUp:[]}),rH(t)}catch(e){console.error("Failed to abort:",e)}}},[rH]),rU=(0,i.useCallback)(async(e,t)=>{if(ne.current)return;let n=t2.current;if(n){e5(e);try{let{cancelled:r,newSessionId:i}=await ce(n,{type:"fork",entryId:e})??{};!r&&i&&(t&&A(i,t),f?.(i))}catch(e){console.error("Fork failed:",e),rv({type:"error",message:e instanceof Error?e.message:String(e)})}finally{e5(null)}}},[rv,f]),rK=(0,i.useCallback)(async t=>{let n=t2.current;if(!n)return ry("sidebar.forkNotFound");try{let r=await fetch(`/api/sessions/${encodeURIComponent(n)}/fork`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),i=await r.json().catch(()=>({}));if(!r.ok||!i.sessionId||!i.session){let{key:e,params:t}=eQ(i.code,i.error??`HTTP ${r.status}`);return ry(e,t)}let s=e.chatInputRef?.current;return s?s.rekeyDraft(n,i.sessionId):O(n,i.sessionId),f?.(i.sessionId,i.session),null}catch(e){return ry("sidebar.forkFailed",{error:e instanceof Error?e.message:String(e)})}},[f,e.chatInputRef,ry]),rq=!!ey&&!C&&!!l?.id&&l?.relation?.kind!=="subagent"&&l?.relation?.kind!=="side",rV=(0,i.useCallback)(async e=>{if(ne.current)return!1;let t=t2.current;if(!t)return!1;try{let n=await ce(t,{type:"navigate_tree",targetId:e});if(n?.cancelled||t2.current!==t)return!1;return await n6(t),t2.current===t}catch(e){return console.error("Failed to navigate:",e),!1}},[n6]);nu.current=rV;let rZ=(0,i.useCallback)(async e=>{if(ne.current||t5.current||ts)return;F(e);let t=t2.current;t&&(await n9(t,e),e&&ce(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[ts,n9]),rJ=(0,i.useCallback)(async(e,t)=>{if(C){let n={provider:e,modelId:t};nv.current=n,eA(n),tn(n),null===nb.current&&eB(cO(ny.current[`${e}/${t}`])??nw.current);let r=t2.current??await nh.current;if(!r)return;try{await ce(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=t2.current;if(!n||nI.current)return;nI.current=!0,e9({provider:e,modelId:t}),ti(!0);let r=t5.current||ne.current,i=async()=>{let e=await fetch(d7(n)).catch(()=>null),t=e?.ok?await e.json().catch(()=>null):null;t?.state&&nT.current&&t2.current===n&&nY(t.state)};try{let s=await ce(n,{type:"set_model",provider:e,modelId:t});te({provider:s.provider,modelId:s.id}),nI.current=!1,r?(e9(null),await i()):await n6(n)}catch(e){console.error("Failed to set model:",e),nI.current=!1,e9(e6),rv({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),r?await i():await n6(n,!1,!0)}finally{nI.current=!1,ti(!1)}},[rv,e6,C,n6,eA,nY]),rY=(0,i.useCallback)(async e=>{let t=t2.current;if(!t||ts)return!0;tl(!0),tp(null),tm(null);try{let n=await ce(t,{type:"compact",...e?{customInstructions:e}:{}});return tm(cV(n,"manual")),await n6(t)&&re(),!0}catch(e){return tp(e instanceof Error?e.message:String(e)),tm(null),!1}finally{tl(!1)}},[ts,n6,re]),rG=(0,i.useCallback)(()=>tp(null),[]),rX=(0,i.useCallback)(async e=>{let t,n=o??l?.cwd??"",r=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",i=null;try{let n=await fetch(r,e?{signal:e}:void 0);if(!n.ok){let e="";try{let t=await n.json();t&&"object"==typeof t&&"error"in t&&"string"==typeof t.error&&(e=t.error),i=d5(t)}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw e}throw Error(e||`Failed to load models (HTTP ${n.status})`)}t=await n.json(),e?.throwIfAborted()}catch(t){throw e?.aborted||t instanceof DOMException&&"AbortError"===t.name||(ex(i),em(i?null:t instanceof Error?t.message:String(t))),t}ex(null),eu(t.models),em(t.modelError??null),ek(t.modelScopeWarnings??[]),eS(!!t.isScoped),eN(null),eE.current=null,eI(t.thinkingLevels??{}),eT(t.thinkingLevelMaps??{});let s=t.modelList??[];eh(s);let a=t.defaultModel?s.find(e=>e.id===t.defaultModel?.modelId&&e.provider===t.defaultModel?.provider):void 0;if(ez(a?{provider:a.provider,modelId:a.id}:null),ny.current=t.thinkingLevelPins??{},nw.current=cO(t.defaultThinkingLevel),e_(cO(t.savedDefaultThinkingLevel)),C&&!t2.current){let e=nv.current,n=e&&(0===s.length||!!t.isScoped||s.some(t=>t.provider===e.provider&&t.id===e.modelId));e&&!n&&(nv.current=null,eA(null));let r=n?e:a&&{provider:a.provider,modelId:a.id},i=r&&t.thinkingLevelPins?.[`${r.provider}/${r.modelId}`];null===nb.current&&eB(cO(i)??nw.current)}},[C,o,l?.cwd]),rQ=(0,i.useCallback)(()=>{if(eE.current)return;let e={};eE.current=e;let t=o??l?.cwd??"";fetch(`/api/models?scope=all${t?`&cwd=${encodeURIComponent(t)}`:""}`).then(async t=>{if(!t.ok)throw Error(`Failed to load models (HTTP ${t.status})`);let n=await t.json();eE.current===e&&(eu(e=>({...n.models,...e})),eI(e=>({...n.thinkingLevels,...e})),eT(e=>({...n.thinkingLevelMaps,...e})),eN(n.modelList??[]))}).catch(t=>{eE.current===e&&(eE.current=null,rv({type:"error",message:t instanceof Error?t.message:String(t)}))})},[rv,o,l?.cwd]);(0,i.useEffect)(()=>{!ej||!nq||eC||ep.some(e=>e.provider===nq.provider&&e.id===nq.modelId)||rQ()},[eC,nq,ej,rQ,ep]);let r0=(0,i.useCallback)(async e=>{let t=o??l?.cwd,n=await fetch("/api/models/default",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t?{cwd:t}:{},...e})});if(n.ok)return;let r="";try{let e=await n.json();e&&"object"==typeof e&&"error"in e&&"string"==typeof e.error&&(r=e.error)}catch{}throw Error(r||`HTTP ${n.status}`)},[o,l?.cwd]),r1=(0,i.useCallback)(()=>{rX().catch(()=>{})},[rX]),r2=(0,i.useCallback)(async(e,t)=>{try{await r0({provider:e,modelId:t})}catch(e){rv({type:"error",message:`Failed to save default model: ${e instanceof Error?e.message:String(e)}`});return}rv({type:"success",message:`Default model: ${e}/${t}`}),ez({provider:e,modelId:t}),(nq?.provider!==e||nq?.modelId!==t)&&await rJ(e,t),r1()},[rv,nq,rJ,r1,r0]),r4=(0,i.useCallback)(async(t,n)=>{let r=e.session?.relation?.kind;if("side"===r||"subagent"===r)return ry(ct[r]);let i=t2.current;if(!i)return ry("sideChat.error.noSession");let s=await cn(i,ry,n);return"error"in s?s.error:(g?.(s.session,t),null)},[g,e.session?.relation?.kind,ry]),r8=(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(),l=t2.current??await rn(),o=e=>(e.handled&&(e.error?rv({type:"error",message:e.error}):e.action||rv({type:"success",message:e.message??"Command completed"})),e);try{switch(r){case"compact":if(!l||ts)return o({handled:!0,error:"No active session to compact"});return rY(s||void 0).then(t=>{!t&&s&&e.chatInputRef?.current?.prependText(`/compact ${s}`)}),o({handled:!0,action:"compact"});case"auto-compact":{if(!l)return o({handled:!0,error:"No active session"});let e=await ce(l,{type:"get_state"}),t=!(e?.autoCompactionEnabled??!0);return await ce(l,{type:"set_auto_compaction",enabled:t}),tc(t),o({handled:!0,message:t?"Auto-compaction enabled":"Auto-compaction disabled"})}case"reload":if(!l)return o({handled:!0,error:"No active session to reload"});return await ce(l,{type:"reload"}),await Promise.all([n6(l,!1,!0),n7(l),ra(),rX()]),o({handled:!0,message:"Reloaded session resources"});case"name":if(!l)return o({handled:!0,error:"No active session to name"});if(!s)return o({handled:!0,error:"Usage: /name <name>"});return await ce(l,{type:"set_session_name",name:s}),await n6(l)&&re(),o({handled:!0,message:`Session renamed to ${s}`});case"session":{if(!l)return o({handled:!0,error:"No active session"});if(!k)return o({handled:!0,message:function(e,t){if(!e)return t("session.noUsage");let n=cg(e.cost);return[t(1===e.totalMessages?"session.usageSummaryOne":"session.usageSummary",{messages:e.totalMessages,tokens:cm(e.tokens.total)}),...n?[n]:[]].join(" \xb7 ")}(n8,ry)});let e=await ce(l,{type:"get_session_stats"});return e&&tI(e),k(),o({handled:!0,action:"openSessionStats"})}case"mcp":{if(s||!j)return{handled:!1};let e=await rd();if(!e||!(e.some(af)||!e.some(e=>"mcp"===e.name)))return{handled:!1};return j("mcp"),o({handled:!0,action:"openSettings"})}case"copy":{if(!l)return o({handled:!0,error:"No active session"});let e=await ce(l,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return o({handled:!0,error:"No assistant message to copy"});return await i0(t),o({handled:!0,message:"Copied last assistant message"})}case"clone":{if(!l)return o({handled:!0,error:"No active session to clone"});if(t5.current||ne.current)return o({handled:!0,error:"Cannot clone while the session is running"});let e=rz.current,t=await ce(l,{type:"clone",leafId:e?.base===P&&e.lastEntryId===nz.current.at(-1)?e.leafId:P});if(t?.cancelled&&t.byExtension)return{handled:!0};if(t?.cancelled||!t?.newSessionId)return o({handled:!0,error:"Cannot clone an empty or unsaved session"});let n=o({handled:!0,message:"Cloned current session branch"});return f?.(t.newSessionId),n}case"side":{let e=await r4(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)})}},[P,rv,rn,rY,ts,rX,n6,ra,n7,re,j,f,k,e.chatInputRef,n8,rd,r4,ry]),r3=(0,i.useCallback)(async(e,t,n)=>{let r=t2.current;if(nQ)return void nX(e,n,nJ);if(!r){nX(e,n,nJ),rv({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 ce(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){if(console.error("Failed to submit streaming prompt:",t),nX(e,n,nJ),t instanceof d6&&t.missingCwd)return void eb(t.missingCwd);d9(t)?rv({type:"error",message:t.message}):rw()}},[rv,rw,nJ,nQ,nX]),r5=(0,i.useCallback)(async(e,t)=>{await r3(e,"steer",t)},[r3]),r6=(0,i.useCallback)(async(e,t,n)=>{await r3(e,t,n)},[r3]),r9=(0,i.useCallback)(async(e,t)=>{await r3(e,"followUp",t)},[r3]),r7=(0,i.useCallback)(async()=>{let e=t2.current;if(e)try{await ce(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),ie=(0,i.useCallback)(async()=>{let e=t2.current;if(e)try{let t=await ce(e,{type:"clear_queue"});tF({steering:[],followUp:[]}),rH(t)}catch(e){console.error("Failed to recall queued messages:",e),rv({type:"error",message:"Failed to recall queued messages"})}},[rv,rH]),it=(0,i.useCallback)(async e=>{if("auto"===e){nb.current=null,eF(null),eK(null);return}C?(nb.current=e,eF(e)):eK(e);let t=t2.current??await nh.current;if(t)try{await ce(t,{type:"set_thinking_level",level:e}),nT.current&&t2.current===t&&(eV(e),eK(null))}catch(e){console.error("Failed to set thinking level:",e),eK(null)}},[C]),ir=(0,i.useCallback)(async e=>{try{await r0({thinkingLevel:e})}catch(e){rv({type:"error",message:`Failed to save default reasoning level: ${e instanceof Error?e.message:String(e)}`});return}rv({type:"success",message:`Default reasoning level: ${e}`}),e_(e),nZ!==e&&await it(e),r1()},[rv,nZ,it,r1,r0]),ii=(0,i.useCallback)(async e=>{let t=(0,cc.xG)(e);!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:cp();if(t)try{t.setItem(cu,e)}catch{}}(e),nB(e);let n=t2.current??await nh.current;if(!n){t3.current=void 0!==t;return}try{let e=await ce(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});t3.current=void 0!==t;let r=e?.sessionId??n;(r!==n||e?.recreated)&&(rc(),ru("set_tools"),tT([]),tA([]),t2.current=r,e?.recreated&&t8.current===r&&rh(r)),rs(),tz([]),tW([]);let[i]=await Promise.all([ce(r,{type:"get_state"}),n7(r)]);nT.current&&t2.current===r&&(e8(i.systemPrompt??""),nY(i))}catch(e){console.error("Failed to set tools:",e)}},[rc,rs,ru,n7,rh,nB,nY]),is=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=np.current;n&&(null!==nd.current&&(cancelAnimationFrame(nd.current),nd.current=null),ni.current=!0,nl.current=!1,no.current=!1,tb(!1),n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),na.current=n.scrollTop)},[]),il=(0,i.useCallback)(()=>{let e=np.current,t=ns.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!==nd.current&&(cancelAnimationFrame(nd.current),nd.current=null),no.current=!0,na.current=n,e.scrollTo({top:n,behavior:"auto"})},[]),ia=(0,i.useCallback)(()=>{let e=np.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=t5.current,s=no.current,l=function(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:96;return!!cT(n,r,i)||!(n<t)&&(!!(!e&&n>t&&cT(n,r,i,s))||e)}(s,na.current,t,n,r,i?96:8);no.current=l,na.current=t;let o=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return!(n<=t)&&!cT(e,t,n,r)}(t,n,r);tw(e=>e===o?e:o),!s&&l&&i?nU("auto"):l||null===nd.current||(cancelAnimationFrame(nd.current),nd.current=null)}},[nU]),id=(0,i.useCallback)((e,t)=>{t?.running&&(n7(e),(t.state?.isStreaming||t.state?.isPromptRunning)&&(t6.current=!!t.state.isStreaming,t9.current=!!t.state.isPromptRunning,t5.current=!0,es(!0),tx(e=>d0(e,t.state?.isStreaming===!0)),er({type:"resume"}),!t.state.isStreaming&&t.state.isPromptRunning&&rT(e)),t.state?.isBashRunning&&(ne.current=!0,eo(!0),rR(e))),t?.state&&(void 0!==t.state.isCompacting&&tl(t.state.isCompacting),void 0!==t.state.systemPrompt&&e8(t.state.systemPrompt??null),void 0!==t.state.extensionStatuses&&tz(t.state.extensionStatuses??[]),void 0!==t.state.extensionWidgets&&tW(t.state.extensionWidgets??[]),void 0!==t.state.queuedMessages&&tF(cW(t.state.queuedMessages)))},[er,n7,rR,rT]);tZ.current=(e,t)=>{!tU.current||t4.current===e||(tU.current=!1,tG.current={count:tG.current.count+1,lastAt:Date.now(),lastReason:t},tq(e=>e+1),nT.current&&t2.current===e&&t8.current===e&&(rh(e),n6(e,!1,!0).then(t=>{nT.current&&t2.current===e&&id(e,t)})))},(0,i.useEffect)(()=>{let e=l?.id;if(!e)return;let t=!1,n=tJ.current,r=async()=>{let n=await rf(e);!t&&"hidden"===document.visibilityState&&cj(n)&&tZ.current(e,"activity")};r();let i=setInterval(()=>void r(),3e4);n.renewStartedAt=Date.now();let s=()=>{"visible"===document.visibilityState&&(tZ.current(e,"visible"),r())};return document.addEventListener("visibilitychange",s),()=>{t=!0,clearInterval(i),n.renewStartedAt=null,document.removeEventListener("visibilitychange",s)}},[rf,l?.id]),(0,i.useEffect)(()=>{if(nT.current=!0,e2.current=e1.current,l){t2.current=l.id;let e=co(l.id);e&&($({sessionId:l.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}),F(e.leafId),B(e.messages),V(e.entryIds),G(e.oldestEntryId),Q(e.hasMore),et(e.turnsBefore),z(null),M(!1)),n6(l.id,!e,!0,{force:!0}).then(e=>{id(l.id,e)})}return()=>{nT.current=!1;let e=C?a:null;e&&queueMicrotask(()=>{nT.current||nx.current||L(e)});let t=t2.current,n=nA.current;if(t&&n&&n.sessionId===t&&n.snapshotRevision){let e=co(t),r=nz.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)?ca({sessionId:t,revision:n.snapshotRevision,messages:nL.current,entryIds:nz.current,leafId:nP.current,oldestEntryId:nW.current,hasMore:nO.current,turnsBefore:nF.current,summaryTree:n.tree,thinkingLevel:n.context.thinkingLevel,model:n.context.model,stats:n.stats,totalActiveMs:n.totalActiveMs,loadedEntryIds:nz.current}):cd(t)}rC.current(),null!==nd.current&&(cancelAnimationFrame(nd.current),nd.current=null),nn.current+=1,rc(),ru()}},[]),(0,i.useEffect)(()=>{b?.(e4)},[e4,b]),(0,i.useEffect)(()=>(w?.(rr),()=>w?.(null)),[rr,w]);let ic=(0,i.useCallback)(()=>{let e,t=null;try{t=tD.current?.snapshot?.()??null}catch{t=null}let n=t2.current,r=tJ.current,i=tG.current;return{pageId:"string"==typeof(e=globalThis[ta])?e:null,sessionId:n,selectedSessionId:t8.current,mounted:nT.current,wantsStream:null!==n&&nD(n),connection:t,released:{active:tU.current,...tY.current},reattached:{...i},hiddenReleaseDueAt:tX.current,hiddenGraceMs:3e4,graceDueAt:tQ.current,run:{agentRunning:t5.current,bashRunning:ne.current,compacting:t0.current,dialogs:t1.current},lease:{renewIntervalMs:3e4,renewStartedAt:r.renewStartedAt,inFlightSince:r.inFlightSince,requests:r.requests,unanswered:r.unanswered,errors:r.errors,last:r.last&&{...r.last,reply:r.last.reply&&{...r.last.reply}}}}},[nD]);(0,i.useEffect)(()=>(S?.(ic),()=>S?.(null)),[ic,S]);let iu=ei||el||ts;(0,i.useEffect)(()=>{v&&v(E?.tree??[],P,rZ,iu)},[E?.tree,P,rZ,iu,v]),(0,i.useEffect)(()=>{let e=np.current;if(e)return na.current=e.scrollTop,e.addEventListener("scroll",ia,{passive:!0}),()=>{e.removeEventListener("scroll",ia)}},[D.length,I,ia]),(0,i.useEffect)(()=>{ei||tb(!1)},[ei]),(0,i.useLayoutEffect)(()=>{D.length>0&&(nl.current?(nl.current=!1,ni.current=!0,il()):ni.current?!t5.current&&no.current&&nU("auto"):(ni.current=!0,nU("instant")))},[D.length,ei,nU,il]),(0,i.useEffect)(()=>{let e=new AbortController;return(async()=>{for(let t=0;;t++)try{await rX(e.signal);return}catch(n){if(e.signal.aborted||n instanceof DOMException&&"AbortError"===n.name||t>=cH.length||(await cU(cH[t]),e.signal.aborted))return}})(),()=>e.abort()},[rX,x]),(0,i.useEffect)(()=>{if(!tf)return;let e=setTimeout(()=>tm(null),6e3);return()=>clearTimeout(e)},[tf]);let[ip,ih]=(0,i.useState)(null),im=(0,i.useRef)(5e3),ig=(0,i.useRef)(null),ix=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(0===tN.visible.length){ix.current=null;return}let e=tN.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{tE({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=tN.visible[0];if(!t||(ix.current!==t.id&&(ix.current=t.id,im.current=5e3),tN.visible.some(e=>e.id===ip)))return;ig.current=Date.now();let n=setTimeout(()=>{tE({type:"mark_oldest_exiting"})},im.current);return()=>{clearTimeout(n),null!==ig.current&&(im.current=Math.max(0,im.current-(Date.now()-ig.current)),ig.current=null)}},[tN.visible,ip]),(0,i.useEffect)(()=>{tI(null)},[D.length,eY?.tokens,eY?.percent,eY?.contextWindow]);let iv=nZ??"auto",iy=tM[0]??null,iw=Math.max(0,tM.length-1),ik=tR[0]??null,ij=Math.max(0,tR.length-1),iS=(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?cy(r,s-e.length):n.get(t)??t)}return i})(q,D.length,Z),[q,D.length,Z]);return{data:E,loading:I,error:T,activeLeafId:P,messages:D,activeToolResults:H,toolClocks:U,entryIds:q,messageKeys:iS,historyCursor:Y,hasEarlierMessages:X,earlierTurnCount:ee,streamingStore:en,agentRunning:ei,modelNames:ec,modelList:ep,modelError:ef,missingCwd:ey,canForkMissingCwd:rq,modelScopeWarnings:ew,isModelScopeActive:ej,allModelList:eC,modelThinkingLevels:e$,modelThinkingLevelMaps:eM,newSessionModel:eR,toolPreset:eP,thinkingLevel:iv,retryInfo:eZ,contextUsage:eY,systemPrompt:e4,forkingEntryId:e3,isCompacting:ts,compactError:tu,compactResult:tf,currentModel:nK,displayModel:nq,modelSwitching:tr,sessionStats:n8,autoCompactionEnabled:to,slashCommands:tk,slashCommandsLoading:tS,queuedMessages:tO,notices:tN.visible,extensionDialog:iy,waitingExtensionDialogCount:iw,extensionCustomUi:ik,waitingExtensionCustomUiCount:ij,extensionStatuses:tL,extensionWidgets:tP,respondToExtensionUi:rg,sendExtensionCustomInput:rx,isAutoModelSelection:C&&null===eR,isAutoThinkingSelection:C&&null===eO,defaultModel:eL,savedDefaultThinkingLevel:eH,agentPhase:tg,isNew:C,editEntryId:nQ,promptAnchorActive:tv,showScrollToBottom:ty,sessionIdRef:t2,scrollContainerRef:np,lastUserMsgRef:ns,pendingScrollToUserRef:nl,initialScrollDoneRef:ni,handleSend:rD,handleAbort:r_,startSideChat:r4,handleFork:rU,forkIntoCwd:rK,handleNavigate:rV,handleModelChange:rJ,handleCompact:rY,handleSteer:r5,handleFollowUp:r9,handlePromptWithStreamingBehavior:r6,handleAbortCompaction:r7,dismissCompactError:rG,handleRecallQueue:ie,handleBuiltinSlashCommand:r8,handleEditContent:n2,cancelEdit:nQ?n4:void 0,addNotice:rv,setNoticePaused:ih,handleToolPresetChange:ii,handleThinkingLevelChange:it,handleSetDefaultModel:r2,handleSetDefaultThinkingLevel:ir,loadTools:n7,loadSlashCommands:ra,loadAllModels:rQ,setActiveLeafId:F,setData:$,setMessages:B,loadContext:n9,scrollToBottom:nU,scrollUserMsgToTop:il,scrollToMessage:is,dispatch:er,setAgentRunning:es,setForkingEntryId:e5,bashRunning:el,pendingBash:ea,handleAgentEventRef:nr}}({session:s,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:f,initialNewSessionChoices:x,onNewSessionChoicesChange:v,onAgentEnd:el,onSessionEnded:y,onToolEnd:w,onAttentionNeeded:k,onSessionCreated:j,onSessionForked:S,onSideSession:N,modelsRefreshKey:E,chatInputRef:$,onBranchDataChange:I,onSystemPromptChange:M,onSystemToolsChange:T,onSystemInfoLoaderChange:z,onSessionStatsPanelOpen:D,onOpenSettings:B,onDebugSnapshotReaderChange:P,t:ee,deferInitialScroll:!!ea}),tD=cZ(ek,cJ),tB=cZ(ek,cY),tH=(0,i.useCallback)(()=>ek.getState().streamingMessage,[ek]),tU=ej||eS,tK=(0,i.useCallback)((e,t)=>{tg(e,{value:dj(t),images:dS(t)})},[tg]);(0,i.useEffect)(()=>{if(ej&&Q)return Q()},[ej,Q]);let[tq,tV]=(0,i.useState)(!1),[tZ,tJ]=(0,i.useState)(!1),[tY,tG]=(0,i.useState)(null),tX=(0,i.useCallback)(()=>{tG(null),tV(!0)},[]),t0=(0,i.useCallback)(async e=>{tG(null),tJ(!0);let t=await tx(e);tJ(!1),t?tG(t):tV(!1)},[tx]),t1=(0,i.useCallback)(async e=>{let t;try{t=await tm(e)}catch(e){t=e instanceof Error?e.message:String(e)}t&&($?.current?.restoreSubmission(e),e6({type:"error",message:t}))},[e6,$,tm]),t2=(0,i.useRef)(!1);(0,i.useEffect)(()=>{ep||eh||!V||t2.current||(t2.current=!0,Z?.(),tp(V))},[V,ep,eh,tp,Z]),(0,i.useEffect)(()=>{let e=!!eG&&!es.current;es.current=!!eG,en&&e&&er.current()},[en,eG]),(0,i.useEffect)(()=>{C||(l=tU?tf:null)},[C,tU,tf]);let[t8,t3]=(0,i.useState)(50),[t5,t6]=(0,i.useState)(null),t9=(0,i.useRef)(null),t7=(0,i.useRef)(null),ne=(0,i.useCallback)(e=>{if(t7&&(t7.current=e),!e)return;let t=function(e){for(let t=e.parentElement;t;t=t.parentElement){let e=getComputedStyle(t).overflowY;if("auto"===e||"scroll"===e)return t}return null}(e);if(!t||"u"<typeof IntersectionObserver||!CSS.supports?.("content-visibility","auto"))return()=>{t7&&(t7.current=null)};let n=new Set,r=new Set,i=e=>{e.style.removeProperty("content-visibility"),e.style.removeProperty("contain-intrinsic-block-size"),e.style.removeProperty("contain"),r.delete(e)},s=e=>{for(let t of e)t.style.contain="layout";let t=e.map(cX);e.forEach((e,n)=>{e.style.containIntrinsicBlockSize=`auto ${t[n]}px`,e.style.contentVisibility="auto",r.add(e)})},l=new IntersectionObserver(t=>{let l=[];for(let s of t){let t=s.target;s.isIntersecting?(n.add(t),r.has(t)&&i(t)):(n.delete(t),r.has(t)||t.parentElement!==e||l.push(t))}l.length>0&&s(l)},{root:t,rootMargin:"100% 0px"}),o=e=>{e instanceof HTMLElement&&l.observe(e)},a=t=>{t instanceof HTMLElement&&t.parentElement!==e&&(l.unobserve(t),n.delete(t),r.has(t)&&i(t))};Array.from(e.children).forEach(o);let d=new MutationObserver(e=>{for(let t of e)t.removedNodes.forEach(a),t.addedNodes.forEach(o)});d.observe(e,{childList:!0});let c=e.getBoundingClientRect().width,u=null,p=new ResizeObserver(()=>{let t=e.getBoundingClientRect().width;t!==c&&(c=t,u&&clearTimeout(u),u=setTimeout(()=>{u=null;let t=Array.from(r);0!==t.length&&(t.forEach(i),s(t.filter(t=>t.parentElement===e&&!n.has(t))))},200))});return p.observe(e),()=>{t7&&(t7.current=null),u&&clearTimeout(u),l.disconnect(),d.disconnect(),p.disconnect(),r.forEach(i)}},[t7]),nt=(0,i.useRef)(null),nn=(0,i.useRef)(!1),nr=(0,i.useRef)(!1),ni=(0,i.useRef)(ea);ni.current=ea;let[ns,nl]=(0,i.useState)(null),no=ef[ex.indexOf(ns?.entryId??"")],na=no?.role==="assistant"?ns?.blockIndex===void 0?no.content.find(e=>"text"===e.type):no.content[ns.blockIndex]:void 0,nc=(0,i.useRef)({entryIds:ex,historyCursor:eb,hasEarlierMessages:ey});nc.current={entryIds:ex,historyCursor:eb,hasEarlierMessages:ey};let nu=(0,i.useRef)(null),np=(0,i.useCallback)(async(e,t,n)=>{nu.current=t;let r=await tP(e,tW,t,n);return r||nu.current!==t||(nu.current=null),r},[tW,tP]);(0,i.useEffect)(()=>{eb!==nu.current&&(nu.current=null)},[eb]),(0,i.useLayoutEffect)(()=>{let e=s?.id,t=to.current,n=t7.current;if(e&&u&&t&&n)return()=>{if(ni.current)return;if(cT(t.scrollTop,t.clientHeight,t.scrollHeight))return void u(e,{atBottom:!0});let r=t.getBoundingClientRect().top,i=function(e,t){let n=e[0];for(let r of e){if(r.top>t)break;n=r}return n?{anchorEntryId:n.entryId,anchorOffset:n.top-t}:null}(Array.from(n.children).flatMap(e=>{if(!(e instanceof HTMLElement)||!e.dataset.entryId)return[];let t=e.getBoundingClientRect();return[{entryId:e.dataset.entryId,top:t.top,bottom:t.bottom}]}),r);i&&u(e,{atBottom:!1,...i,oldestEntryId:nc.current.historyCursor})}},[ep,u,to,s?.id]),(0,i.useEffect)(()=>{o&&ed(null)},[o]),(0,i.useEffect)(()=>{let e=s?.id;if(!ea||!e||ep||o||nr.current)return;nr.current=!0;let t=new AbortController;return(async()=>{let n=nc.current;if(n.entryIds.includes(ea.anchorEntryId)){t3(e=>Math.max(e,2*n.entryIds.length)),eu(!0);return}nn.current=!0;let r=n.historyCursor,i=n.hasEarlierMessages;try{for(;i&&r&&!t.signal.aborted;){let n=await np(e,r,{signal:t.signal});if(t.signal.aborted)return;if(!n){tO("instant"),ed(null);return}if(t3(e=>e+Math.max(50,2*n.messages.length)),n.entryIds.includes(ea.anchorEntryId))return void eu(!0);if(n.oldestEntryId===ea.oldestEntryId)break;r=n.oldestEntryId,i=n.hasMore}t.signal.aborted||(tO("instant"),ed(null))}finally{nn.current=!1}})(),()=>{t.abort(),ed(null)}},[tW,np,ep,ea,tO,o,s?.id]),(0,i.useLayoutEffect)(()=>{let e=t7.current;if(!ea||!e||o)return;let t=Array.from(e.children).find(e=>e instanceof HTMLElement&&e.dataset.entryId===ea.anchorEntryId);if(t instanceof HTMLElement){tF(t,ea.anchorOffset),ed(null);return}ec&&(tO("instant"),ed(null))},[ex,ea,ec,tO,tF,o,t8]),(0,i.useEffect)(()=>{if(!o||ep)return;let e=new AbortController;return(async()=>{let t=nc.current,n=t.entryIds.includes(o.entryId);if(!n&&!tU&&t.hasEarlierMessages&&t.historyCursor&&!nn.current){nn.current=!0;let r=to.current;r&&(nt.current=r.scrollHeight-r.scrollTop);let i=await np(o.sessionId,t.historyCursor,{tail:200,signal:e.signal});nn.current=!1,n=!!i?.entryIds.includes(o.entryId)}e.signal.aborted||(n?(nt.current=null,t3(e=>Math.max(e,(nc.current.entryIds.length+200)*2)),nl(o)):d?.(o))})(),()=>e.abort()},[o,ep,tU,np,d,to]),(0,i.useLayoutEffect)(()=>{if(!ns||ns!==o)return;let e=`[data-entry-id="${CSS.escape(ns.entryId)}"]`,t=to.current?.querySelector(no?.role==="user"?e:`${e} [data-search-target]`);t&&(tF(t),t.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500})),nl(null),d?.(ns)},[ns,o,no,to,tF,d]),(0,i.useEffect)(()=>{let e=to.current;if(!t5||!e)return;let t=new IntersectionObserver(t=>{if(!t[0]?.isIntersecting||nn.current)return;if(!ey){nt.current=e.scrollHeight-e.scrollTop,t3(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50;return e+t})(e));return}if(!eb||eb===nu.current)return;let n=s?.id??tl.current;n&&(nn.current=!0,nt.current=e.scrollHeight-e.scrollTop,np(n,eb).finally(()=>{nn.current=!1}))},{root:e,threshold:0});return t.observe(t5),()=>t.disconnect()},[t5,t8,eb,ey,s,np,tl,to]),(0,i.useEffect)(()=>{t3(e=>Math.max(e,ef.length))},[ef.length]),(0,i.useEffect)(()=>{if(null==nt.current)return;let e=to.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nt.current),nt.current=null}},[t8,to]);let nh=eq?[eq.sessionId,eq.sessionFile??"",eq.sessionName??"",eq.userMessages,eq.assistantMessages,eq.toolCalls,eq.toolResults,eq.totalMessages,eq.tokens.input,eq.tokens.output,eq.tokens.cacheRead,eq.tokens.cacheWrite,eq.tokens.total,eq.cost??0,eq.totalActiveMs??0].join("|"):null,nf=(0,i.useRef)(eq);nf.current=eq,(0,i.useEffect)(()=>{F?.(nf.current)},[nh,F]),(0,i.useEffect)(()=>()=>{F?.(null)},[F]);let nm=eF?`${eF.percent??"null"}|${eF.contextWindow}|${eF.tokens??"null"}`:null,ng=(0,i.useRef)(eF);ng.current=eF,(0,i.useEffect)(()=>{H?.(ng.current)},[nm,H]),(0,i.useEffect)(()=>()=>{H?.(null)},[H]);let nx=(0,i.useCallback)(async e=>{let t=s?.cwd??h;if(!t)return void e6({type:"warning",message:ee("chat.dropNeedsCwd")});try{var n;let r,{status:i,data:s}=await nE(t,e,"skip");if(200!==i&&207!==i)throw Error(s.error??`HTTP ${i}`);let l=s.uploaded??[],o=s.skipped??[],a=(n=[...l,...o],r=new Set(n),e.filter(e=>r.has(e.name)).map(e=>nN(e.name,!1)).join(""));for(let e of(a&&$?.current?.insertText(a),l.length>0&&(e6({type:"success",message:ee("chat.dropUploaded",{count:l.length})}),U?.()),o.length>0&&e6({type:"warning",message:ee("chat.dropAlreadyExists",{names:o.join(", ")})}),s.errors??[]))e6({type:"error",message:ee("chat.dropFailed",{message:`${e.name}: ${e.error}`})})}catch(e){e6({type:"error",message:ee("chat.dropFailed",{message:e instanceof Error?e.message:String(e)})})}},[e6,$,h,U,s?.cwd,ee]),nv=(0,i.useCallback)(e=>{let{images:t,files:n,folders:r}=function(e){let t=[],n=[],r=[];for(let i of e)"folder"===i.kind?r.push(i.name):i.file.type.startsWith("image/")?t.push(i.file):n.push(i.file);return{images:t,files:n,folders:r}}(e);t.length>0&&$?.current?.addImages(t),r.length>0&&e6({type:"warning",message:ee("chat.dropFoldersUnsupported",{names:r.join(", ")})}),n.length>0&&nx(n)},[e6,$,ee,nx]),nb=(0,i.useCallback)(e=>{nv(e.map(e=>({kind:"file",file:e})))},[nv]),{isDragOver:ny,handleDragEnter:nw,handleDragOver:nk,handleDragLeave:nj,handleDrop:nS}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),s=(0,i.useCallback)(e=>{nI(e)&&(e.preventDefault(),r.current+=1,n(!0))},[]),l=(0,i.useCallback)(e=>{nI(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},[]);return{isDragOver:t,handleDragEnter:s,handleDragOver:l,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(nM(t.dataTransfer))},[e])}}(nv),nC=ej||tD,n$=(0,i.useMemo)(()=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.map(iy);for(let i=0;i<e.length;){var r;if(iw(e[i])){i+=1;continue}let s=i+1;for(;s<e.length&&!iw(e[s]);)s+=1;let l=e[s];if((l?"assistant"===l.role:!0===t.openTail)&&(r=e[i-1],r?.role==="assistant"&&("stop"===r.stopReason||"aborted"===r.stopReason))&&!n.slice(i,s).includes(!0)){let t=-1;for(let n=s-1;n>=i;n--){if("custom"!==e[n].role){if(-1!==t)break;continue}if(-1===t&&(t=n),!ib(e[n])){t=n;break}}-1!==t&&(n[t]=!0)}i=s}return n})(ef,{openTail:nC}),[ef,nC]),nT=ef.reduce((e,t,n)=>e+ +!!ik(t,n$[n]),0),nR=(0,i.useMemo)(()=>{let e=new Map(em);for(let t of ef)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[em,ef]),nA=(0,i.useMemo)(()=>new WeakMap,[]),nL=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=ef.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}(ef[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[ef]),nz=((t=(0,i.useRef)([])).current=Array(nT).fill(null).map((e,n)=>t.current[n]??null),t),nP=(0,i.useCallback)(()=>{t3(e=>Math.max(e,2*ef.length))},[ef.length]),nW=tr&&0===ef.length&&!tD&&!tU;t4(to,!!s?.id||!nW);let nO=s?.cwd??h??void 0,nF=(0,i.useRef)(null),nD=(0,i.useRef)(0),nB=(0,i.useRef)(null),nH=(0,i.useRef)(!1),n_=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=nF.current;if(!ej||!tu){n_.current=null,nD.current=0,nH.current=!1,e&&(e.style.height="");return}let t=to.current,n=t9.current,r=tc.current;if(!t||!n||!r||!e)return;let i=!1,s=()=>{var s;let l;if(i||to.current!==t||t9.current!==n||tc.current!==r||nF.current!==e)return;let o=t.getBoundingClientRect().top,a=Math.max(0,r.getBoundingClientRect().top-o+t.scrollTop-16),d=e.getBoundingClientRect().top-o+t.scrollTop,c=(s=t.clientHeight,0===(l=Math.max(0,a))?0:Math.max(0,Math.ceil(l+s-Math.max(0,d)))),u=!nH.current;u&&(nH.current=!0),c!==nD.current&&(nD.current=c,e.style.height=c>0?`${c}px`:"",u&&c>0&&tz())};n_.current=s,s();let l="u"<typeof ResizeObserver?null:new ResizeObserver(()=>{i||null!==nB.current||(nB.current=requestAnimationFrame(()=>{nB.current=null,s()}))});return l?.observe(t),l?.observe(n),l?.observe(r),()=>{i=!0,n_.current===s&&(n_.current=null),l?.disconnect(),null!==nB.current&&(cancelAnimationFrame(nB.current),nB.current=null)}},[ej,tc,ef.length,tu,to,tz]);let nU=(0,i.useCallback)(()=>{n_.current?.()},[]);(0,i.useLayoutEffect)(nU,[tD,tB,nU]);let nK=eU?eL[`${eU.provider}:${eU.modelId}`]??null:null,nq=eU?ez[`${eU.provider}:${eU.modelId}`]??null:null,nV=(0,r.jsx)(dT,{ref:$,onSend:tp,onAbort:tf,onSideChat:N&&!a(s?.relation)?t1:void 0,onSteer:ej?tk:void 0,onFollowUp:ej?tj:void 0,onPromptWithStreamingBehavior:ej?tS:void 0,isStreaming:tU,model:eU,isAutoModelSelection:e9,modelNames:eN,modelList:eE,modelError:e$,missingCwd:eI,onForkMissingCwd:eM?tX:void 0,modelScopeWarnings:eT,allModelList:eA,onLoadAllModels:eR?tL:void 0,onModelChange:ty,modelSwitching:eK,defaultModel:te,onSetDefaultModel:tT,onCompact:s||tr?tw:void 0,onAbortCompaction:tC,isCompacting:eB,compactError:eH,onDismissCompactError:tN,compactResult:e_,toolPreset:eP,onToolPresetChange:s&&!a(s.relation)||tr?tI:void 0,thinkingLevel:eW,isAutoThinkingSelection:e7,onThinkingLevelChange:s||tr?tM:void 0,availableThinkingLevels:nK,thinkingLevelMap:nq,savedDefaultThinkingLevel:tt,onSetDefaultThinkingLevel:s||tr?tR:void 0,retryInfo:eO,queuedMessages:eJ,inputHistory:nL,onRecallQueue:tE,slashCommands:eV,slashCommandsLoading:eZ,onLoadSlashCommands:tA,extensionUiOpen:!!(eG||e0),onBuiltinCommand:t$,soundEnabled:J,onSoundToggle:Y,onAudioUnlock:X,draftKey:s?.id??f??void 0,cwd:s?.cwd??h,onAttachFiles:nb});return ep?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:ee("chat.loadingSession")}):eh?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:eh}):(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:nw,onDragOver:nk,onDragLeave:nj,onDrop:nS,children:[ny&&(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*!et,zIndex:40,display:"flex",justifyContent:"flex-end",padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)(c9,{notices:eY,floating:!0,onPauseChange:e5})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[eG&&(0,r.jsx)(ut,{request:eG,waitingCount:eX,onRespond:e8},eG.id),e0&&(0,r.jsx)(un,{request:e0,waitingCount:e1,onInput:e3},e0.id),!nW&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:to,className:"scrollbar-subtle min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-gutter:stable]",style:{visibility:ea?"hidden":void 0},children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{ref:t9,style:{width:"100%",minWidth:0,maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(()=>{var e;let t,n,l=-1;for(let e=ef.length-1;e>=0;e--)if("user"===ef[e].role){l=e;break}let o=-1;for(let e=ef.length-1;e>=0;e--)if(n$[e]){o=e;break}let a=new Map,d=0;ef.forEach((e,t)=>{ik(e,n$[t])&&a.set(t,d++)});let c=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.messageOverride??ef[e];if("custom"===n.role&&"pi-web:side-boundary"===n.customType)return(0,r.jsx)(c5,{},"side-chat-divider");if(ib(n))return null;let o=!1===t.withNotices?[]:og(ef[e]),d=ik(n,n$[e]),c=a.get(e),u=t.keyPrefix??"message",p=ev[e],h=!1;if("assistant"===n.role){h=!0;for(let t=e+1;t<ef.length&&!n$[t];t++)if("assistant"===ef[t].role){h=!1;break}h&&tD&&e===ef.length-1&&(h=!1)}void 0!==t.showTimestamp&&(h=t.showTimestamp);let f=(0,r.jsx)(o$,{message:n,toolResults:nR,toolClocks:eg,modelNames:eN,cwd:nO,onOpenFile:_,onOpenSubagent:K,entryId:ex[e],searchBlock:ex[e]===ns?.entryId?na:void 0,onFork:eS||tr?void 0:tK,forking:eD===ex[e],onEditContent:tU?void 0:tv,onCancelEdit:tb,isEditing:ti===ex[e],showTimestamp:h,prevTimestamp:e>0?ef[e-1].timestamp:void 0,sessionId:s?.id??tl.current??void 0,writtenFiles:t.writtenFiles,turnDurationMs:t.turnDurationMs,onCompact:t.recoverTruncation?tw:void 0,isCompacting:t.recoverTruncation?eB:void 0,compactError:t.recoverTruncation?eH:void 0},`${u}-view-${p}`),m=o.length>0?(0,r.jsx)(ow,{notices:o},`${u}-notices-${p}`):null;return d&&void 0!==c?(0,r.jsxs)("div",{"data-entry-id":ex[e],ref:!1===t.attachRef?void 0:t=>{nz.current[c]=t,e===l&&(tc.current=t)},children:[f,m]},`${u}-${p}`):(0,r.jsxs)(i.Fragment,{children:[f,m]},`${u}-${p}`)},u=[];for(let e=0;e<ef.length;){let t,n=n$[e];if(!n&&0!==e){u.push(c(e)),e+=1;continue}let i=n?e:-1,s=n?e:0,l=e+1;for(;l<ef.length&&!n$[l];)l+=1;let d=function(e,t,n){for(let i=n-1;i>t;i--){var r;if("assistant"===(r=e[i]).role&&iI(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}(ef,i,l);if(-1===d||(tU||tD)&&l===ef.length&&i===o){for(let e=s;e<l;e++)u.push(c(e));e=l;continue}n&&u.push(c(i));let p=n&&ex[i]?function(e,t,n){let r,i,s,l=iG(e[t]?.timestamp);if(void 0===l)return;for(let r=t+1;r<n&&"custom"===e[r].role;r++){let t=iG(e[r].timestamp);void 0!==t&&(l=Math.max(l,t))}let o=!1,a=0;for(let l=t+1;l<n;l++){let t=e[l];if("assistant"===t.role){var d;void 0!==i&&void 0!==s&&(a+=Math.max(0,s-i)),i=s=void 0;let e=function(e){if("assistant"!==e.role)return;let t=iG(e.timestamp),n=iG(e.durationMs);return void 0!==t&&void 0!==n?t+n:void 0}(t);o=void 0!==e,void 0!==e&&(r=Math.max(r??e,e)),void 0!==e&&"assistant"===(d=t).role&&("stop"===d.stopReason||"length"===d.stopReason)&&(i=r)}else if("toolResult"===t.role){let e=iG(t.timestamp);void 0!==e&&(r=Math.max(r??e,e))}else if(void 0!==i){let e=iG(t.timestamp);void 0!==e&&(s=Math.max(s??e,e))}}if(o&&void 0!==r)return Math.max(0,r-l-a)}(ef,i,l):void 0,h=function(e,t){let n=e.get(t);if(n)return n;let{answerBlocks:r}=iI(t),i=r.length>0||iC(t)||iE(t)||iN(t)?iY(t,r):null,s=t.content.indexOf(r[0]),l={answer:i,process:iY(t,t.content.slice(0,s<0?void 0:s),{omitUsage:!!i,omitStop:!!i})};return e.set(t,l),l}(nA,ef[d]),f=h.answer,m=[],g=0,x=0,v=!1;for(let e=i+1;e<=d;e++){let n=ef[e];if("custom"===n.role){if(ib(n))continue;v||=!!(ns&&ns.entryId===ex[e]),g+=1,m.push(c(e,{attachRef:!1,keyPrefix:"process"}));continue}if("assistant"!==n.role)continue;let i=e===d?h.process:n,s=e!==d||!f,l=iS(i);if(0===l.length){let t=s?og(n):[];t.length>0&&m.push((0,r.jsx)(ow,{notices:t},`process-notices-${ev[e]}`));continue}t??=a.get(e),x+=l.filter(e=>"toolCall"===e.type).length,g+=1,v||=!!(ns&&ex[e]===ns.entryId&&(!na||l.includes(na))),m.push(c(e,{attachRef:!1,keyPrefix:"process",messageOverride:i,showTimestamp:!1,withNotices:s}))}if(0===g)u.push(...m);else if(m.length>0){let e=(f?.content??[]).some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0),n=function(e){let t;for(let n of e)for(let e of og(n))"cache_miss"===e.kind&&(t??={count:0,missedTokens:0,missedCost:0},t.count+=1,t.missedTokens+=e.missedTokens,t.missedCost+=e.missedCost);return t}(ef.slice(i+1,f?d:d+1));u.push((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{nz.current[t]=e},children:(0,r.jsx)(c8,{messageCount:g,toolCallCount:x,durationMs:p,cacheMisses:n,defaultExpanded:!e,reveal:v,t:ee,children:m},e?"answered":"unanswered")},`process-group-${ev[s]}`))}if(f){let e=[];for(let t=i+1;t<=d;t++){let n=ef[t];if(n?.role==="assistant")for(let t of n.content??[])e.push(t)}let t=function(e,t){let n=e.writtenFiles;return n&&n.length===t.length&&n.every((e,n)=>e.filePath===t[n].filePath)?n:(e.writtenFiles=t,t)}(h,function(e,t,n){let r=new Set,i=[];for(let l of e){var s;if("toolCall"!==l.type||!(iD(s=l.toolName)||iB(s))&&!iH(l.toolName))continue;let e=t?.get(l.toolCallId);if(e&&!e.isError)for(let t of iH(l.toolName)?function(e,t){let n=t?.details,r=function(e,t){let n=new Set;if(t&&"object"==typeof t&&!Array.isArray(t)){let e=t.preview;if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.files;if(Array.isArray(t))for(let e of t)!(!e||"object"!=typeof e||Array.isArray(e))&&"delete"===e.operation&&"string"==typeof e.filePath&&e.filePath.length>0&&n.add(e.filePath)}}for(let t of i_(e).matchAll(/^\*\*\* Delete File: (.+)$/gm)){let e=(t[1]??"").trim();e&&n.add(e)}return n}(e,n),i=function(e){if(!iU(e)||!iU(e.result))return null;let t=e.result.appliedFiles;return Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):null}(n);if(i)return i.filter(e=>!r.has(e));if(iK(n))return[];if(n&&"object"==typeof n&&!Array.isArray(n)){let e=iJ(iZ(n.preview));if(e.length>0)return e}return iJ(iV(i_(e)))}(l.input,e):[function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(l.input)]){if(!t)continue;let e=function(e,t){let n;if(!e)return null;let r=iA(e)||iA(t),i=e=>r?e.replace(/\\/g,"/"):e,s=i(e),l=t?i(t).replace(/\/+$/,""):void 0,o=/^[a-zA-Z]:\//.test(s),a=s.startsWith("//"),d=r?iz(s):s;if(o||a||d!==s)n=d;else if(s.startsWith("/")){let e=l?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??l?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${s}`:s}else{if(!l)return null;n=`${l}/${s}`}return iP(n)}(t,n);e&&(r.has(e)||(r.add(e),i.push({filePath:e})))}}return i}(e,nR,nO));u.push(c(d,{messageOverride:f,writtenFiles:t,turnDurationMs:0===m.length?p:void 0,recoverTruncation:l===ef.length&&!tD&&!i$(f)}))}for(let e=d+1;e<l;e++)u.push(c(e));e=l}let{startIndex:p}=(t=Math.min(Math.max(t8,0),Math.max(e=u.length,0)),{startIndex:n=Math.max(0,e-t),hasMore:n>0}),h=p>0||ey;return(0,r.jsxs)(r.Fragment,{children:[h&&(0,r.jsx)("div",{ref:t6,className:"py-3 text-center text-xs text-text-muted",children:ee("chat.loadEarlier")}),(0,r.jsx)("div",{ref:ne,children:u.slice(p)})]})})(),tD&&tB&&(0,r.jsx)(c6,{store:ek,onCommit:nU,toolResults:nR,modelNames:eN,cwd:nO,onOpenFile:_,onOpenSubagent:K}),(ej||eB)&&!tB&&(tn||eB)&&(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}(tn,ee,eB,(eJ?.steering.length??0)+(eJ?.followUp.length??0))})}),eS&&!eC&&(0,r.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:ee("chat.runningCommand")})}),eC&&(0,r.jsx)(o$,{message:{role:"bashExecution",command:eC.command,output:"",...eC.result,excludeFromContext:eC.excludeFromContext,timestamp:eC.startedAt},sessionId:s?.id??tl.current??void 0,onOpenSubagent:K}),eC?.liveOutput&&!eC.result&&(0,r.jsx)("div",{"aria-live":"off",className:"rounded-md border border-border px-2.5 py-1.5 font-mono text-[12px] leading-[1.45] text-text-muted",style:{marginTop:-2,background:"var(--tool-bg)"},children:(0,r.jsx)("pre",{className:"m-0 flex flex-col justify-end overflow-hidden whitespace-pre-wrap break-words",style:{maxHeight:"29em"},children:(0,r.jsx)("span",{children:eC.liveOutput.replace(/\n+$/,"").split("\n").slice(-20).join("\n")})})}),(0,r.jsx)("div",{ref:nF,"aria-hidden":"true"})]})})}),et||ea?null:(0,r.jsx)(dV,{messages:ef,getStreamingMessage:tH,scrollContainer:to,messageRefs:nz,onRevealHistory:nP,turnsBefore:ew,turnAnchors:n$})]})]}),q&&(0,r.jsx)(dZ,{rootRef:t9,chatInputRef:$,startSideChat:N&&!a(s?.relation)?tm:void 0}),(0,r.jsxs)("div",{className:"relative flex min-h-0 flex-col",children:[!nW&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"100%",left:0,right:36*!et,display:"flex",justifyContent:"center",paddingBottom:10,pointerEvents:"none",zIndex:20},children:(0,r.jsx)("button",{type:"button",className:`chat-scroll-to-bottom${ts&&!ea?" is-visible":""}`,title:ee("chat.scrollToLatest"),"aria-label":ee("chat.scrollToLatest"),onClick:()=>tO("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"})})})}),nW&&(0,r.jsx)("div",{className:"new-session-hero",style:{paddingLeft:16,paddingRight:et?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)(ir.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.12.12"]}),(0,r.jsx)(c4,{label:e=>ee("appUpdate.releaseNotes",{version:e})}),(0,r.jsx)("span",{"aria-hidden":"true",children:"\xb7"}),(0,r.jsxs)("span",{className:"new-session-meta-pi",children:["pi v","1.5.2"]})]})]})]}),g]})}),nV,(0,r.jsx)(dQ,{statuses:e2,widgets:e4,onCommand:tp,commandsDisabled:tU})]}),nW&&(0,r.jsx)("div",{className:"min-h-0 flex-1"}),tq&&(0,r.jsx)(nd,{busy:tZ,error:tY,onCancel:()=>{tV(!1),tG(null)},onSelect:e=>void t0(e)})]})}function c5(){let{t:e}=(0,t_.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 c6=(0,i.memo)(function(e){let{store:t,onCommit:n,toolResults:s,modelNames:l,cwd:o,onOpenFile:a,onOpenSubagent:d}=e,c=cZ(t,cG);return((0,i.useLayoutEffect)(n,[c,n]),c)?(0,r.jsx)(o$,{message:c,toolResults:s,isStreaming:!0,modelNames:l,cwd:o,onOpenFile:a,onOpenSubagent:d},of(c)):null});function c9(e){let{notices:t,floating:n=!1,onPauseChange:s}=e;return 0===t.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",marginBottom:10*!n},children:t.map((e,l)=>{var o;let a,d,c,u="error"===e.type?"#ef4444":"warning"===e.type?"#d97706":"success"===e.type?"#10b981":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",onMouseEnter:()=>s?.(e.id),onMouseLeave:e=>{e.currentTarget.contains(document.activeElement)||s?.(null)},onFocus:()=>s?.(e.id),onBlur:e=>{e.currentTarget.matches(":hover")||s?.(null)},style:{display:"flex",alignItems:"flex-start",gap:10,minHeight:60,height:"auto",maxHeight:500,pointerEvents:"auto",marginBottom:6*(l!==t.length-1),overflow:"hidden",borderRadius:14,border:"1px solid color-mix(in srgb, var(--border) 70%, transparent)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:n?"0 1px 2px rgba(15,23,42,0.05), 0 10px 28px -14px rgba(15,23,42,0.24)":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",fontSize:14,lineHeight:1.5,transformOrigin:"top right",animation:e.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out backwards",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:u,flexShrink:0,marginTop:25.5}}),(0,r.jsx)("span",{tabIndex:0,style:{padding:"18.5px 0",minWidth:0,maxWidth:"100%",maxHeight:498,overflowY:"auto",scrollbarWidth:"thin",whiteSpace:"pre-line",wordBreak:"break-word"},children:(o=e.message,a=[],d=(e,t)=>{if(!t)return;let n=a[a.length-1];n?.kind===e?n.text+=t:a.push({kind:e,text:t})},c=!1,o.split("\n").forEach((e,t)=>{let n=iu.test(e);t>0&&d(n&&c?"art":"text","\n"),d(n?"art":"text",e),c=n}),a).map((e,t)=>"art"===e.kind?(0,r.jsx)("span",{style:{display:"inline-block",verticalAlign:"top",maxWidth:"100%",overflowX:"auto",whiteSpace:"pre",fontFamily:"Menlo, Consolas, 'DejaVu Sans Mono', monospace",lineHeight:1,color:"var(--text)"},children:e.text},t):(0,r.jsx)(i.Fragment,{children:(function(e){let t=[],n=0;for(let r of e.matchAll(ip)){let i=function(e){let t=0,n=0;for(let r of e)"("===r?t+=1:")"===r&&(n+=1);let r=e.length;for(;r>0;){let i=e[r-1];if(ih.test(i))r-=1;else if(")"===i&&n>t)r-=1,n-=1;else break}return e.slice(0,r)}(r[0]);if(!/^https?:\/\/[^/]/i.test(i))continue;let s=r.index??0;s>n&&t.push({kind:"text",text:e.slice(n,s)}),t.push({kind:"link",text:i}),n=s+i.length}return n<e.length&&t.push({kind:"text",text:e.slice(n)}),t})(e.text).map((e,n)=>"link"===e.kind?(0,r.jsx)("a",{href:e.text,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",textDecoration:"underline",textUnderlineOffset:2,wordBreak:"break-all"},children:e.text},`${t}-${n}`):e.text)},t))})]},e.id)})})}function c7(e){let{count:t}=e,{t:n}=(0,t_.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 ue(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 ut(e){let{request:t,waitingCount:n,onRespond:s}=e,{t:l}=(0,t_.s)(),[o,a]=(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,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(!1),x=(0,i.useCallback)(()=>g(e=>!e),[]),[v,b]=(0,i.useState)(()=>Date.now()),y=(0,i.useCallback)(e=>e?.focus(),[]),w=function(e){if("select"===e.method&&e.options.length>0)return io(e.options[0]);if("confirm"===e.method){let t=io(e.message).split("\n").find(e=>e.trim());return t?.trim()}}(t),k=void 0===t.expiresAt?null:Math.max(0,Math.ceil((t.expiresAt-v)/1e3));(0,i.useLayoutEffect)(()=>{if(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&&f(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(()=>b(Date.now()),1e3);return()=>clearInterval(e)},[t.expiresAt]);let j=null!==k&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:l("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||229===e.nativeEvent.keyCode||(e.preventDefault(),e.stopPropagation(),s(t,{cancelled:!0}))},style:{position:"absolute",inset:0,zIndex:90,display:"flex",alignItems:d?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:d?(0,r.jsxs)("button",{type:"button",onClick:()=>c(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(560px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:l("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:io(t.title)}),w&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:w}),(0,r.jsx)(c7,{count:n}),j,(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:l("chat.extensionExpand")})]}):(0,r.jsxs)("div",{ref:u,role:"dialog","aria-label":io(t.title),style:{pointerEvents:"auto",width:m?"100%":`min(${h??560}px, 100%)`,maxHeight:m?"100%":"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{flexShrink:1,minHeight:0,display:"flex",alignItems:"flex-start",gap:8,padding:"12px 14px",borderBottom:"1px solid var(--border)",maxHeight:"50vh",overflowY:"auto"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:650,lineHeight:1.45,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:io(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:l("chat.extensionRequest")}),(0,r.jsx)(c7,{count:n}),j]})]}),(0,r.jsx)("button",{type:"button",onClick:x,title:l(m?"chat.extensionRestoreSize":"chat.extensionMaximize"),"aria-label":l(m?"chat.extensionRestoreSize":"chat.extensionMaximize"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)(ue,{expanded:m})}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:l("chat.extensionCollapse"),"aria-label":l("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)(lB,{children:io(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":io(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)(lB,{children:io(e)})})},e))}),"input"===t.method&&(0,r.jsx)("input",{autoFocus:!0,value:o,placeholder:t.placeholder,onChange:e=>a(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode||S()},style:{width:"100%",padding:"9px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",fontSize:13}}),"editor"===t.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:o,onChange:e=>a(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&!e.nativeEvent.isComposing&&229!==e.nativeEvent.keyCode&&S()},style:{width:"100%",minHeight:220,padding:10,borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:13,lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 14px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("button",{autoFocus:"confirm"===t.method||"select"===t.method&&0===t.options.length,onClick:()=>s(t,{cancelled:!0}),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"},children:l("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:l("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:l("chat.submit")}):null]})]})})}function un(e){let{request:t,waitingCount:n,onInput:s}=e,{t:l}=(0,t_.s)(),o=(0,i.useRef)(null),a=(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(il,""),i=io(e).trimEnd();if(t.test(i))continue;let s=e,l=ic(s);("│"===l||"┃"===l)&&" "===ic(s=id(s,0))&&(s=id(s,0));let o=function(e){let t=ia(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(s),a=o>=0?ia(s)[o]?.char:void 0;("│"===a||"┃"===a)&&(s=id(s,o)),n.push(function(e){let t=e;for(;;){let e=ia(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&&""===io(n[0]).trim();)n.shift();for(;n.length>0&&""===io(n[n.length-1]).trim();)n.pop();return n.length?n:e.map(e=>e.replace(il,""))}(t.lines),p=u.map(io).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:l("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:l("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)(c7,{count:n}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:l("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":l("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:e=>{if(a.current||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode)return;let n=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;if(" "===e)return"\0";if("/"===e||"-"===e)return"\x1f";let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}let t=im[e.key],n=1+ +!!e.shiftKey+2*!!e.altKey+4*!!e.ctrlKey;if(n>1&&!(e.altKey&&!e.ctrlKey&&!e.shiftKey&&ig[e.key])){if(/^\x1b\[[ABCDHF]$/.test(t??""))return`\x1b[1;${n}${t.at(-1)}`;if(/^\x1b\[\d+~$/.test(t??""))return`${t.slice(0,-1)};${n}~`}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=ig[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":" ":im[e.key]??null}(e);n&&(e.preventDefault(),e.stopPropagation(),s(t,n))},onInput:e=>{if(a.current||e.nativeEvent.isComposing)return;let n=e.currentTarget.value;e.currentTarget.value="",n&&s(t,n)},onCompositionStart:()=>{a.current=!0},onCompositionEnd:e=>{a.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,function(e){let t=e;for(;t.includes(ix)||t.includes(iv);)t=t.split(ix).join("").split(iv).join("");return`${ix}${t}${iv}`}(n))},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:l("chat.extensionPanel")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)(c7,{count:n}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:l("chat.extensionCollapse"),"aria-label":l("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:l("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)(dY,{text:u.join("\n")})})]})})}let ur=null,ui="";function us(e){let{context:t,mobile:n,initialFocus:s,onInitialFocusDone:l,onPick:o,onUseDefaultDirectory:a,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u}=e,{t:p}=(0,t_.s)(),[h,f]=(0,i.useState)(()=>ui),m=(0,i.useRef)(null),g=(0,i.useRef)(s),x=(0,i.useRef)(l);return x.current=l,(0,i.useEffect)(()=>{if(ui)return;let e=!1;return(ur??=fetch("/api/home").then(e=>e.json()).then(e=>ui=e.home??"").catch(()=>(ur=null,""))).then(t=>{!e&&t&&f(t)}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=g.current;if(!e)return;g.current=null,x.current();let t=m.current;to(document,("worktree"===e?t?.button("worktree"):null)??t?.button("project")??null)},[]),(0,r.jsx)("div",{className:"new-session-context",children:(0,r.jsx)(rG,{handleRef:m,layout:"inline",context:t,mobile:n,label:p("workspace.newSessionContext"),homeDir:h,newWorktreeTitle:p("sidebar.newWorktreeForSession"),onPick:o,onUseDefaultDirectory:a,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u})})}function ul(e){return e&&"number"==typeof e.size&&"string"==typeof e.mtime?`${e.size}:${e.mtime}`:null}function uo(e,t){return null===e||null===t||e!==t}let ua=`<script data-pi-web-polyfill="storage">
10
+ (function() {
11
+ function createMemoryStorage() {
12
+ var store = Object.create(null);
13
+ function hasKey(key) { return Object.prototype.hasOwnProperty.call(store, key); }
14
+ var storage = Object.create({
15
+ getItem: function(key) {
16
+ if (arguments.length < 1) throw new TypeError("getItem requires a key");
17
+ key = String(key);
18
+ return hasKey(key) ? store[key] : null;
19
+ },
20
+ setItem: function(key, value) {
21
+ if (arguments.length < 2) throw new TypeError("setItem requires a key and value");
22
+ store[String(key)] = String(value);
23
+ },
24
+ removeItem: function(key) {
25
+ if (arguments.length < 1) throw new TypeError("removeItem requires a key");
26
+ delete store[String(key)];
27
+ },
28
+ clear: function() { store = Object.create(null); },
29
+ key: function(index) {
30
+ if (arguments.length < 1) throw new TypeError("key requires an index");
31
+ var key = Object.keys(store)[(+index) >>> 0];
32
+ return key === undefined ? null : key;
33
+ },
34
+ get length() { return Object.keys(store).length; }
35
+ });
36
+ // Storage also exposes its keys as named properties, apart from the API's
37
+ // own names (which remain callable even if a key has the same name).
38
+ return new Proxy(storage, {
39
+ get: function(target, key, receiver) {
40
+ if (typeof key === "string" && !(key in target)) return store[key];
41
+ return Reflect.get(target, key, receiver);
42
+ },
43
+ set: function(target, key, value, receiver) {
44
+ if (typeof key !== "string") return Reflect.set(target, key, value, receiver);
45
+ target.setItem(key, value);
46
+ return true;
47
+ },
48
+ deleteProperty: function(target, key) {
49
+ if (typeof key !== "string") return Reflect.deleteProperty(target, key);
50
+ target.removeItem(key);
51
+ return true;
52
+ },
53
+ has: function(target, key) {
54
+ return key in target || (typeof key === "string" && hasKey(key));
55
+ },
56
+ ownKeys: function(target) {
57
+ var own = Reflect.ownKeys(target);
58
+ return own.concat(Object.keys(store).filter(function(key) { return own.indexOf(key) === -1; }));
59
+ },
60
+ getOwnPropertyDescriptor: function(target, key) {
61
+ var own = Reflect.getOwnPropertyDescriptor(target, key);
62
+ if (own || typeof key !== "string" || !hasKey(key)) return own;
63
+ return { value: store[key], writable: true, enumerable: true, configurable: true };
64
+ }
65
+ });
66
+ }
67
+
68
+ function polyfillStorage(type) {
69
+ try {
70
+ window[type].getItem("__pi_web_storage_probe__");
71
+ } catch (error) {
72
+ if (error && error.name === "SecurityError") {
73
+ Object.defineProperty(window, type, {
74
+ value: createMemoryStorage(), configurable: true, enumerable: true
75
+ });
76
+ }
77
+ }
78
+ }
79
+ polyfillStorage("localStorage");
80
+ polyfillStorage("sessionStorage");
81
+ })();
82
+ <\/script>`,ud=/\uFEFF?(?:\s|<!--[\s\S]*?-->|<!doctype\b[^>]*>|<\?[^>]*>)*/iy,uc=/<html(?=[\s/>])(?:[^>"']|"[^"]*"|'[^']*')*>(?:\s|<!--[\s\S]*?-->)*/iy,uu=/<head(?=[\s/>])(?:[^>"']|"[^"]*"|'[^']*')*>/iy;function up(e,t,n){return e.lastIndex=n,e.exec(t)?e.lastIndex:n}var uh=n(73620);let uf=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function um(e){let t=function(e){let t=uf.exec(e);if(!t)return null;let n=/^---[ \t]*(?:(?:\r\n|\n|\r)|$)/gm;n.lastIndex=t[0].length;let r=n.exec(e);return r?{yaml:e.slice(t[0].length,r.index).replace(/(?:\r\n|\n|\r)$/,""),rest:e.slice(r.index+r[0].length)}:null}(e);if(!t)return{data:null,rest:e};try{let e=(0,uh.Hh)(t.yaml);if(e&&"object"==typeof e&&!Array.isArray(e))return{data:e,rest:t.rest}}catch{}return{data:null,rest:t.rest}}function ug(e){return function e(t,n){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(n.has(t))return"[Circular]";n.add(t);try{return t.map(t=>e(t,n)).filter(Boolean).join(", ")}finally{n.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}let ux=[",",";"," ","|"];function uv(e){let t=/\.(csv|tsv)$/i.exec(e);return t?"tsv"===t[1].toLowerCase()?" ":",":null}function ub(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.complete??!0,i=n.maxRecords??1/0,s=[],l=[],o=e.length,a=t.charCodeAt(0),d=+(65279===e.charCodeAt(0)),c=1,u=[],p=1,h=!1,f=()=>{(1!==u.length||""!==u[0]||h)&&(s.push(u),l.push(p)),u=[],h=!1};for(;d<o&&s.length<i;){let t="",n=!1;if(34===e.charCodeAt(d)){h=!0,n=!0;let r=d+=1;for(;d<o;){let i=e.indexOf('"',d);if(-1===i)break;if(34===e.charCodeAt(i+1)){t+=e.slice(r,i+1),r=d=i+2;continue}t+=e.slice(r,i),d=i+1,n=!1;break}n&&(t+=e.slice(r),d=o),c+=function(e){let t=0,n=e.indexOf("\n");for(;-1!==n;)t+=1,n=e.indexOf("\n",n+1);return t}(t)}let i=d;for(;i<o;){let t=e.charCodeAt(i);if(t===a||10===t)break;i+=1}let s=i<o?e.charCodeAt(i):-1,l=s!==a&&i>d&&13===e.charCodeAt(i-1)?i-1:i;t+=e.slice(d,l),u.push(t),d=i,s===a?(d+=1)===o&&(u.push(""),r&&f()):10===s?(d+=1,c+=1,f(),p=c):r&&f()}return{records:s,lines:l}}function uy(e){let t=e.indexOf("\n"),n=-1===t?e:e.slice(0,t),r=0;for(let e=0;e<n.length;e+=1){let t=n.charCodeAt(e);t>=56320&&t<=57343||(r+=t>=11904?2:1)}return r}let uw={display:"flex",height:26,boxSizing:"border-box",borderBottom:"1px solid var(--border)"},uk={position:"sticky",left:0,zIndex:1,boxSizing:"border-box",width:56,flexShrink:0,padding:"0 10px",display:"flex",alignItems:"center",justifyContent:"flex-end",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontSize:11,fontVariantNumeric:"tabular-nums",userSelect:"none"},uj={boxSizing:"border-box",flexShrink:0,padding:"0 10px",lineHeight:"25px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",borderRight:"1px solid var(--border)"};function uS(e){let{content:t,filePath:n,complete:s,scrollRef:l}=e,o=(0,i.useMemo)(()=>(function(e,t){let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2],r=uv(t)??",",i=","===r?function(e){let t=e.slice(0,65536),n=t.length===e.length,r=",",i=0;for(let e of ux){let{records:s}=ub(t,e,{complete:n,maxRecords:20}),l=s[0]?.length??0;if(l<2)continue;let o=1e3*s.filter(e=>e.length===l).length+Math.min(l,999);o>i&&(r=e,i=o)}return r}(e):r,{records:s,lines:l}=ub(e,i,{complete:n});if(0===s.length)return{columns:[],headerLine:0,rows:[],rowLines:[]};let o=0;for(let e of s)e.length>o&&(o=e.length);let a=s[0];return{columns:a.length===o?a:[...a,...Array.from({length:o-a.length},()=>"")],headerLine:l[0],rows:s.slice(1),rowLines:l.slice(1)}})(t,n,s),[s,t,n]),a=(0,i.useMemo)(()=>{var e,t;let n;return e=o.columns,n=Math.max(1,Math.ceil((t=o.rows).length/500)),e.map((e,r)=>{let i=uy(e);for(let e=0;e<t.length;e+=n){let n=t[e][r];if(n){let e=uy(n);e>i&&(i=e)}}return Math.min(Math.max(Math.ceil(7.4*i+22),64),420)})},[o]),d=(0,i.useMemo)(()=>a.reduce((e,t)=>e+t,56),[a]),[c,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(0);if((0,i.useEffect)(()=>{let e=l.current;if(!e)return;let t=null,n=()=>{u(e.scrollTop),h(e.clientHeight)},r=()=>{null===t&&(t=requestAnimationFrame(()=>{t=null,n()}))};n(),e.addEventListener("scroll",r,{passive:!0});let i="u"<typeof ResizeObserver?null:new ResizeObserver(n);return i?.observe(e),()=>{e.removeEventListener("scroll",r),i?.disconnect(),null!==t&&cancelAnimationFrame(t)}},[l]),0===o.columns.length)return null;let{start:f,end:m}=function(e,t,n){if(e<=0)return{start:0,end:0};let r=Number.isFinite(t)?Math.max(0,t):0,i=Number.isFinite(n)&&n>0?n:800,s=Math.max(0,Math.floor(r/26)-20),l=Math.min(e,Math.ceil((r+i)/26)+20);return{start:Math.min(s,l),end:l}}(o.rows.length,c-26,p),g=[];for(let e=f;e<m;e+=1){let t=o.rows[e];g.push((0,r.jsxs)("div",{role:"row","aria-rowindex":e+2,style:{...uw,position:"absolute",top:26*e,left:0,width:d},children:[(0,r.jsx)("div",{role:"rowheader",style:uk,children:o.rowLines[e]}),a.map((e,n)=>{let i=t[n]??"";return(0,r.jsx)("div",{role:"cell",style:{...uj,width:e},title:i||void 0,children:i},n)})]},e))}return(0,r.jsxs)("div",{role:"table","aria-rowcount":o.rows.length+1,"aria-colcount":o.columns.length,style:{width:d,minWidth:"100%",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:12,color:"var(--text-muted)",background:"var(--bg)"},children:[(0,r.jsxs)("div",{role:"row","aria-rowindex":1,style:{...uw,position:"sticky",top:0,zIndex:2,width:d,background:"var(--bg-panel)",color:"var(--text)",fontWeight:600},children:[(0,r.jsx)("div",{role:"rowheader",style:uk,children:o.headerLine}),o.columns.map((e,t)=>(0,r.jsx)("div",{role:"columnheader",style:{...uj,width:a[t]},title:e||void 0,children:e},t))]}),(0,r.jsx)("div",{style:{position:"relative",height:26*o.rows.length},children:g})]})}let uC=["tags","categories","keywords","tag","category"];function uN(e){var t;let{data:n}=e;if(!n)return null;let i=Object.entries(n);if(0===i.length)return null;let s="string"==typeof(t=n.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,l=uC.find(e=>Array.isArray(n[e])),o=l?n[l].map(ug).filter(Boolean):[],a=i.filter(e=>{let[t]=e;return t!==l&&("title"!==t||!s)});return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[s&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:s}),o.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:o.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),a.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:a.map(e=>{let[t,n]=e;return(0,r.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,r.jsx)("dt",{children:t}),(0,r.jsx)("dd",{children:function(e){let t=ug(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,r.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(n)})]},t)})})]})}let uE=new Set(["md","markdown","mdx","mdown","mkd","rst","adoc","txt"]),u$={source:"Source",preview:"Preview",diff:"Diff"},uI={fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:13,lineHeight:1.6},uM={...sQ.xJ,'pre[class*="language-"]':{...sQ.xJ['pre[class*="language-"]']}};delete uM['pre[class*="language-"]'].background;let uT={width:48,minWidth:48,padding:"0 10px",textAlign:"right",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:11,fontStyle:"normal",fontVariantNumeric:"tabular-nums",lineHeight:"20.8px",userSelect:"none",flexShrink:0,verticalAlign:"top"},uR={...uT,position:"sticky",left:0,zIndex:1};function uA(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function uL(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function uz(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let n=t.getRangeAt(0);if(!e.contains(n.startContainer)||!e.contains(n.endContainer))return null;let r=uL(n.startContainer),i=uL(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let s=Number(r.dataset.lineNumber),l=Number(i.dataset.lineNumber);if(!Number.isInteger(s)||!Number.isInteger(l))return null;if(s<l){let e=r.querySelector(".file-source-line-content");if(e?.contains(n.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(n.startContainer,n.startOffset),0===t.toString().length){let e=r.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((r=e).dataset.lineNumber))}}let t=i.querySelector(".file-source-line-content");if(t?.contains(n.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(n.endContainer,n.endOffset),0===e.toString().length){let e=i.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(l=Number((i=e).dataset.lineNumber))}}}return s>l?null:{startLine:s,endLine:l}}function uP(e){let{rows:t,stylesheet:n,useInlineStyles:i,wrapLines:s}=e;return t.map((e,t)=>{let l=e.children??[],o=l[0]?.properties?.className,a=Array.isArray(o)&&o.includes("react-syntax-highlighter-line-number"),d=a?l[0]:null,c=a?l.slice(1):l;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":t+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,sG.Ay)({node:d,stylesheet:n,useInlineStyles:i,key:`source-line-number-${t}`}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:s?"anywhere":"normal",whiteSpace:s?"pre-wrap":"pre"},children:c.map((e,r)=>(0,sG.Ay)({node:e,stylesheet:n,useInlineStyles:i,key:`source-token-${t}-${r}`}))})]},`source-line-${t}`)})}function uW(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=nv(e),s=new URLSearchParams({type:t});for(let[e,i]of(n&&s.set("sessionId",n),"watch"===t&&s.set("holder",td()),Object.entries(r)))void 0!==i&&s.set(e,String(i));return`/api/files/${i}?${s.toString()}`}let uO=0;function uF(e,t,n,r){return(0,i.useMemo)(()=>uW(e,t,n,{v:++uO}),[e,t,n,r])}function uD(){let[e,t]=(0,i.useState)(0),n=(0,i.useRef)(0);return[e,(0,i.useCallback)(e=>{let r,i,s=()=>{clearTimeout(r),e.close(),i??=setTimeout(()=>t(e=>e+1),Math.min(1e3*2**n.current++,3e4))},l=()=>{clearTimeout(r),r=setTimeout(s,75e3)};for(let t of(e.addEventListener("connected",()=>{n.current=0}),["connected","change","ping"]))e.addEventListener(t,l);return e.addEventListener("error",()=>{e.readyState===EventSource.CLOSED&&s()}),l(),()=>{clearTimeout(r),clearTimeout(i)}},[])]}function uB(e){let{filePath:t,sourceSessionId:n}=e,{t:i}=(0,t_.s)();return(0,r.jsx)("a",{href:uW(t,"download",n),download:nb(t),title:i("i18n.downloadFile"),"aria-label":i("i18n.downloadFile"),className:"file-viewer-icon-button",children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})}function uH(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}let u_=(0,i.memo)(function(e){let{text:t,language:n,prismReady:i,isDark:s,wrapLines:l}=e;return i&&"text"!==n&&t?(0,r.jsx)(sX.A,{language:n,style:s?uM:sQ.vs,showLineNumbers:!1,wrapLongLines:l,PreTag:"span",CodeTag:"span",customStyle:{margin:0,padding:0,border:0,backgroundColor:"transparent",display:"inline",overflow:"visible",fontFamily:"inherit",fontSize:"inherit",lineHeight:"inherit",whiteSpace:"inherit",overflowWrap:"inherit"},codeTagProps:{style:{fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)"}},children:t}):(0,r.jsx)(r.Fragment,{children:t||"\xa0"})}),uU=(0,i.memo)(function(e){let t,{patch:n,wrapLines:i,language:s="text",prismReady:l=!1,isDark:o=!1}=e,{t:a}=(0,t_.s)(),d=(t=lY(n))?t.flatMap(lG):[],c=e=>"added"===e.type||"removed"===e.type;if(!d.some(c))return(0,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:a("i18n.noChanges")});let u=new Set(d.flatMap((e,t)=>c(e)?[t]:[])),p=new Set;for(let e of u)for(let t=Math.max(0,e-3);t<=Math.min(d.length-1,e+3);t++)p.add(t);let h=p.size<=1e3?uR:uT,f="text"!==s&&l&&p.size<=1e3,m=e=>"gap"!==d[e].type&&p.has(e),g=[],x=0;for(;x<d.length;)if(m(x)){let e=[];for(;x<d.length&&m(x);){let t=d[x];"gap"!==t.type&&e.push(t),x++}g.push({hidden:!1,lines:e})}else{let e=0;for(;x<d.length&&!m(x);){let t=d[x],n="gap"===t.type?t.count:1;e=null===e||null===n?null:e+n,x++}g.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:i?"100%":"max-content",minWidth:"100%",...uI},children:g.map((e,t)=>{if(e.hidden)return(0,r.jsx)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:null===e.count?"⋯":`⋯ ${lX(e.count,a)}`},t);let n=e.lines.map((e,t)=>{let n="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",a="added"===e.type?"+":"removed"===e.type?"-":" ",d="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:n,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,r.jsx)("span",{style:h,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:d,userSelect:"none",flexShrink:0,fontWeight:600},children:a}),(0,r.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:+!!i,minWidth:0,padding:"0 8px 0 0",whiteSpace:i?"pre-wrap":"pre",overflowWrap:i?"anywhere":"normal",color:"var(--text)"},children:f?(0,r.jsx)(u_,{text:e.text||"",language:s,prismReady:l,isDark:o,wrapLines:i}):e.text||"\xa0"})]},t)});return(0,r.jsx)("div",{children:n},t)})})});function uK(e){let{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:l=!0}=e,{t:o}=(0,t_.s)(),[a,d]=(0,i.useState)(!1),[c,u]=uD(),[p,h]=(0,i.useState)(0),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(null),y=(0,i.useRef)(null),w=(0,i.useRef)(0),k=(0,i.useRef)(null),j=nb(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{h(0),m(null),x(null),b(null),d(!1),k.current=null},[t,s]),(0,i.useEffect)(()=>{if(d(!1),y.current&&(y.current.close(),y.current=null),!l)return;let e=!0,n=th("file-watch",new EventSource(uW(t,"watch",s)),t);y.current=n;let r=u(n);n.addEventListener("connected",()=>{let n;d(!0),n=++w.current,fetch(uW(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==w.current)return;if(t.error)return void b(t.error);"number"==typeof t.size&&m(t.size),b(null);let r=ul(t);uo(k.current,r)&&(k.current=r,x(null),h(e=>e+1))}).catch(t=>{e&&n===w.current&&b(String(t))})}),n.addEventListener("change",e=>{w.current+=1,k.current=null;try{let t=JSON.parse(e.data);k.current=ul(t),"number"==typeof t.size&&m(t.size)}catch{}x(null),b(null),h(e=>e+1)});let i=()=>{d(!1)};return n.addEventListener("error",i),n.onerror=i,()=>{e=!1,n.close(),r(),y.current===n&&(y.current=null)}},[t,s,l,c,u]);let S=uF(t,"read",s,p),C=null!=f?uH(f):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:t,children:nw(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:j||"image"}),g&&(0,r.jsxs)("span",{children:[g.w," \xd7 ",g.h]}),C&&(0,r.jsx)("span",{children:C}),(0,r.jsxs)("span",{title:a?o("i18n.liveSync"):o("i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(uB,{filePath:t,sourceSessionId:s})]}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:v?(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13},children:v}):(0,r.jsx)("img",{src:S,alt:t,onLoad:e=>{let t=e.currentTarget;x({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>b(o("files.imageLoadFailed")),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function uq(e){if(!Number.isFinite(e))return"";let t=Math.round(e),n=Math.floor(t/60);return`${n}:${String(t%60).padStart(2,"0")}`}function uV(e){let{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:l=!0}=e,{t:o}=(0,t_.s)(),[a,d]=(0,i.useState)(!1),[c,u]=uD(),[p,h]=(0,i.useState)(0),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(null),y=(0,i.useRef)(null),w=(0,i.useRef)(0),k=(0,i.useRef)(null),j=nb(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{h(0),m(null),x(null),b(null),d(!1),k.current=null},[t,s]),(0,i.useEffect)(()=>{if(d(!1),y.current&&(y.current.close(),y.current=null),!l)return;let e=!0,n=th("file-watch",new EventSource(uW(t,"watch",s)),t);y.current=n;let r=u(n);n.addEventListener("connected",()=>{let n;d(!0),n=++w.current,fetch(uW(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==w.current)return;if(t.error)return void b(t.error);"number"==typeof t.size&&m(t.size),b(null);let r=ul(t);uo(k.current,r)&&(k.current=r,x(null),h(e=>e+1))}).catch(t=>{e&&n===w.current&&b(String(t))})}),n.addEventListener("change",e=>{w.current+=1,k.current=null;try{let t=JSON.parse(e.data);k.current=ul(t),"number"==typeof t.size&&m(t.size)}catch{}x(null),b(null),h(e=>e+1)});let i=()=>{d(!1)};return n.addEventListener("error",i),n.onerror=i,()=>{e=!1,n.close(),r(),y.current===n&&(y.current=null)}},[t,s,l,c,u]);let S=uF(t,"read",s,p);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:t,children:nw(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:j||"audio"}),null!=g&&(0,r.jsx)("span",{children:uq(g)}),null!=f&&(0,r.jsx)("span",{children:uH(f)}),(0,r.jsxs)("span",{title:a?o("i18n.liveSync"):o("i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(uB,{filePath:t,sourceSessionId:s})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,r.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[v&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:v}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:S,onLoadedMetadata:e=>x(e.currentTarget.duration),onError:()=>b(o("files.audioLoadFailed")),style:{width:"100%"}},S)]})})]})}function uZ(e){let{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:l=!0}=e,{t:o}=(0,t_.s)(),[a,d]=(0,i.useState)(!1),[c,u]=uD(),[p,h]=(0,i.useState)(0),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(null),y=(0,i.useRef)(null),w=(0,i.useRef)(0),k=(0,i.useRef)(null),j=nb(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{h(0),m(null),x(null),b(null),d(!1),k.current=null},[t,s]),(0,i.useEffect)(()=>{if(d(!1),y.current&&(y.current.close(),y.current=null),!l)return;let e=!0,n=th("file-watch",new EventSource(uW(t,"watch",s)),t);y.current=n;let r=u(n);n.addEventListener("connected",()=>{let n;d(!0),n=++w.current,fetch(uW(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==w.current)return;if(t.error)return void b(t.error);"number"==typeof t.size&&m(t.size),b(null);let r=ul(t);uo(k.current,r)&&(k.current=r,x(null),h(e=>e+1))}).catch(t=>{e&&n===w.current&&b(String(t))})}),n.addEventListener("change",e=>{w.current+=1,k.current=null;try{let t=JSON.parse(e.data);k.current=ul(t),"number"==typeof t.size&&m(t.size)}catch{}x(null),b(null),h(e=>e+1)});let i=()=>{d(!1)};return n.addEventListener("error",i),n.onerror=i,()=>{e=!1,n.close(),r(),y.current===n&&(y.current=null)}},[t,s,l,c,u]);let S=uF(t,"read",s,p);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:t,children:nw(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:j||"video"}),null!=g&&(0,r.jsx)("span",{children:uq(g)}),null!=f&&(0,r.jsx)("span",{children:uH(f)}),(0,r.jsxs)("span",{title:a?o("i18n.liveSync"):o("i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(uB,{filePath:t,sourceSessionId:s})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)",minHeight:0},children:(0,r.jsxs)("div",{style:{width:"min(960px, 100%)",height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:0},children:[v&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:v}),(0,r.jsx)("video",{controls:!0,playsInline:!0,preload:"metadata",src:S,onLoadedMetadata:e=>x(e.currentTarget.duration),onError:()=>b(o("files.videoLoadFailed")),style:{maxWidth:"100%",maxHeight:"100%"}},S)]})})]})}function uJ(e){let{filePath:t,cwd:n,sourceSessionId:s,initialPage:l,watchEnabled:o=!0}=e,{t:a}=(0,t_.s)(),[d,c]=(0,i.useState)(!1),[u,p]=uD(),[h,f]=(0,i.useState)(0),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),b=(0,i.useRef)(null),y=(0,i.useRef)(0),w=(0,i.useRef)(null),k=i8(t),j="pdf"===k,S=j&&l&&l>0?`#page=${l}`:"",C=`${uF(t,j?"read":"preview",s,h)}${S}`;return(0,i.useEffect)(()=>{f(0),g(null),v(null),c(!1),w.current=null;let e=!0,n=++y.current;return fetch(uW(t,"meta",s)).then(e=>e.json()).then(t=>{e&&n===y.current&&(t.error&&v(t.error),"number"==typeof t.size&&(g(t.size),!j&&t.size>0xa00000&&v("DOCX too large for preview (>10MB)")))}).catch(t=>{e&&n===y.current&&v(String(t))}),()=>{e=!1}},[t,j,s]),(0,i.useEffect)(()=>{if(c(!1),b.current&&(b.current.close(),b.current=null),!o)return;let e=!0,n=th("file-watch",new EventSource(uW(t,"watch",s)),t);b.current=n;let r=p(n);n.addEventListener("connected",()=>{let n;c(!0),n=++y.current,fetch(uW(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==y.current)return;if(t.error)return void v(t.error);if("number"==typeof t.size&&(g(t.size),!j&&t.size>0xa00000))return void v("DOCX too large for preview (>10MB)");v(null);let r=ul(t);uo(w.current,r)&&(w.current=r,f(e=>e+1))}).catch(t=>{e&&n===y.current&&v(String(t))})}),n.addEventListener("change",e=>{y.current+=1,w.current=null;try{let t=JSON.parse(e.data);if(w.current=ul(t),"number"==typeof t.size&&(g(t.size),!j&&t.size>0xa00000))return void v("DOCX too large for preview (>10MB)")}catch{}v(null),f(e=>e+1)});let i=()=>{c(!1)};return n.addEventListener("error",i),n.onerror=i,()=>{e=!1,n.close(),r(),b.current===n&&(b.current=null)}},[t,j,s,o,u,p]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:t,children:nw(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===k?"docx preview":"pdf"}),null!=m&&(0,r.jsx)("span",{children:uH(m)}),(0,r.jsx)(uB,{filePath:t,sourceSessionId:s}),(0,r.jsxs)("span",{title:a(d?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:d?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:d?"#4ade80":"var(--border)",display:"inline-block",boxShadow:d?"0 0 4px #4ade80":"none"}}),d?"live":"static"]})]}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:x?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:x}):(0,r.jsx)("iframe",{src:C,sandbox:j?void 0:"allow-same-origin",title:a("i18n.previewFile",{file:nb(t)}),style:{width:"100%",height:"100%",border:"none",background:j?"var(--bg)":"#eef1f5"}},C)})]})}function uY(e){let t,n,{filePath:s,cwd:l,sourceSessionId:o,onOpenFile:a,onMentionLines:d,onAtMention:c,gitRefreshKey:u,initialDisplayMode:p,initialState:h,initialPage:f,onStateChange:m,watchEnabled:g=!0}=e,x=function(){let e=(0,i.useSyncExternalStore)(cS,cC,cN),[t,n]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{if(!e)return void n(!1);let t=setTimeout(()=>n(!0),3e4);return()=>clearTimeout(t)},[3e4,e]),e&&t}(),v=g&&!x;return null!==(Object.hasOwn(i1,t=i8(s))?i1[t]:null)?(0,r.jsx)(uK,{filePath:s,cwd:l,sourceSessionId:o,watchEnabled:v}):i3(s)?(0,r.jsx)(uV,{filePath:s,cwd:l,sourceSessionId:o,watchEnabled:v}):i5(s)?(0,r.jsx)(uZ,{filePath:s,cwd:l,sourceSessionId:o,watchEnabled:v}):null!==("pdf"===(n=i8(s))||"docx"===n?n:null)?(0,r.jsx)(uJ,{filePath:s,cwd:l,sourceSessionId:o,initialPage:f,watchEnabled:v}):(0,r.jsx)(uG,{filePath:s,cwd:l,sourceSessionId:o,onOpenFile:a,onMentionLines:d,onAtMention:c,gitRefreshKey:u,initialDisplayMode:p,initialState:h,onStateChange:m,watchEnabled:v})}function uG(e){let{filePath:t,cwd:n,sourceSessionId:s,onOpenFile:l,onMentionLines:o,onAtMention:a,gitRefreshKey:d,initialDisplayMode:c,initialState:u,onStateChange:p,watchEnabled:h=!0}=e,{isDark:f}=lo(),{t:m}=(0,t_.s)(),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(null),[y,w]=(0,i.useState)(!1),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!0),[N,E]=(0,i.useState)(!1),[$,I]=(0,i.useState)(null),M=u?.displayMode??c??"source",T=u?.wrapLines??function(e){if(!e)return!1;let t=(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??"";return uE.has(t)}(t),R=u?.scrollTop??0,A=u?.scrollLeft??0,[L,z]=(0,i.useState)(M),[P,W]=(0,i.useState)(T),[O,F]=(0,i.useState)(!1),[D,B]=uD(),H=(0,i.useRef)(null),_=(0,i.useRef)(0),U=(0,i.useRef)(null),K=(0,i.useRef)(0),q=(0,i.useRef)(null),V=(0,i.useRef)(!1),Z=(0,i.useRef)(void 0===u&&void 0===c),J=(0,i.useRef)(!0),Y=(0,i.useRef)({displayMode:M,wrapLines:T,scrollTop:R,scrollLeft:A}),G=(0,i.useRef)(p),[X,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(null);G.current=p;let en=(0,i.useRef)(l);en.current=l;let er=(0,i.useCallback)(e=>{Y.current.displayMode=e,z(e)},[]),ei=(0,i.useCallback)(()=>{W(e=>{let t=!e;return Y.current.wrapLines=t,t})},[]);(0,i.useEffect)(()=>(Y.current={displayMode:M,wrapLines:T,scrollTop:R,scrollLeft:A},J.current=!0,V.current=!1,z(M),W(T),()=>{G.current?.({...Y.current})}),[t,s,M,T,R,A]);let es=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=++_.current;return fetch(uW(e,"read",s,{offset:t||void 0})).then(e=>e.json()).then(e=>n!==_.current?null:e.error?(I(e.error),null):(U.current=ul(e),I(null),x(n=>t&&n?{...e,content:n.content+e.content}:e),e)).catch(e=>(n!==_.current||I(String(e)),null))},[s]),el=(0,i.useCallback)(async e=>{let t=++K.current;if(w(!0),!n){b(null),w(!1),j(!0);return}try{let r=new URLSearchParams({cwd:n,path:e}),i=await fetch(`/api/git/diff?${r.toString()}`),s=await i.json();if(t!==K.current)return;b(i.ok&&s.supported&&"string"==typeof s.patch?s:null)}catch{t===K.current&&b(null)}finally{t===K.current&&(w(!1),j(!0))}},[n]);(0,i.useEffect)(()=>{let e=!0;return C(!0),I(null),x(null),b(null),j(!1),F(!1),U.current=null,es(t).finally(()=>{e&&C(!1)}),()=>{e=!1}},[t,es,s]),(0,i.useEffect)(()=>{if(F(!1),H.current&&(H.current.close(),H.current=null),!h)return;let e=!0,n=()=>{es(t),el(t)},r=th("file-watch",new EventSource(uW(t,"watch",s)),t);H.current=r;let i=B(r);r.addEventListener("connected",()=>{(F(!0),null===U.current)?n():fetch(uW(t,"meta",s)).then(e=>e.json()).then(r=>{e&&(uo(U.current,ul(r))?n():el(t))}).catch(()=>{e&&n()})}),r.addEventListener("change",n);let l=()=>{F(!1)};return r.addEventListener("error",l),r.onerror=l,()=>{e=!1,r.close(),i(),H.current===r&&(H.current=null)}},[t,es,el,s,h,D,B]),(0,i.useEffect)(()=>{el(t)},[el,t,d]);let eo=g?.binary===!0,ea=!eo&&null!==uv(t);(0,i.useEffect)(()=>{Z.current&&g&&!g.binary&&(ea||"markdown"===g.language&&!g.truncated||"html"===g.language&&(!g.truncated||g.size<=0xa00000))&&(Z.current=!1,er("preview"))},[g,ea,er]);let ed="preview"===L&&g?.language==="html"&&g.truncated&&g.size<=0xa00000;(0,i.useEffect)(()=>{if(!ed)return void et(null);let e=new AbortController;return fetch(uW(t,"download",s),{signal:e.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);et({text:await e.text()})}).catch(t=>{e.signal.aborted||et({error:String(t)})}),()=>e.abort()},[ed,g,t,s]);let ec=v?.supported===!0&&"string"==typeof v.patch,eu=ec&&"deleted"===v.status;(0,i.useEffect)(()=>{k&&!ec&&"diff"===L&&er("source")},[L,k,ec,er]),(0,i.useEffect)(()=>{"diff"===M&&ec&&!V.current&&(V.current=!0,er("diff"))},[M,ec,er]);let ep=(0,i.useMemo)(()=>g?.language==="markdown"?sm(g.content):"",[g]),eh=(0,i.useMemo)(()=>g?.language==="markdown"?um(g.content):null,[g]),ef=g?.content??"",em=(0,i.useMemo)(()=>ef.split("\n"),[ef]),eg=g?.language??"text",ex=lu(!!g&&"text"!==eg),ev=!eo&&"html"===eg,eb=!eo&&"markdown"===eg,ey=ea||(ev?!!g&&(!g.truncated||g.size<=0xa00000):eb&&!g?.truncated),ew=eu?"diff":L,ek=g?.truncated?ee?.text:ef,ej=(0,i.useMemo)(()=>ev&&"preview"===ew?function(e){if(!e||e.includes(ua))return e;let t=up(ud,e,0),n=up(uc,e,t),r=up(uu,e,n),i=r>n?r:t;return e.slice(0,i)+ua+e.slice(i)}(ek??""):"",[ev,ew,ek]),eS=!!g?.truncated&&!(ev&&"preview"===ew),eC=em.length>1e3&&!("diff"===ew&&ec)&&!("preview"===ew&&ey),eN=(0,i.useMemo)(()=>(0,r.jsx)(sX.A,{className:P?"file-source-view is-wrapped":"file-source-view",language:"text"!==eg&&ex?eg:"plaintext",style:f?uM:sQ.vs,showLineNumbers:!0,lineNumberStyle:{...uR},customStyle:{margin:0,padding:0,border:0,backgroundColor:"var(--bg)",...uI,width:P?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",overflowWrap:P?"anywhere":"normal"}},renderer:e=>(0,r.jsx)(uP,{...e,wrapLines:P}),wrapLongLines:P,children:ef}),[f,eg,ex,ef,P]),eE=(0,i.useMemo)(()=>eC?em.map((e,t)=>(0,r.jsxs)("span",{className:"file-source-line","data-line-number":t+1,style:{display:"flex",minWidth:"100%"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:uT,children:t+1}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:P?"anywhere":"normal",whiteSpace:P?"pre-wrap":"pre"},children:e})]},`source-line-${t}`)):null,[em,eC,P]);(0,i.useEffect)(()=>{let e=()=>{let e=q.current;Q(t=>{let n=o&&"source"===L&&e?uz(e,window.getSelection()):null;return null===t&&null===n||t&&n&&t.startLine===n.startLine&&t.endLine===n.endLine?t:n})};if(e(),o&&"source"===L)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[g?.content,L,o]);let e$=(0,i.useCallback)(e=>{o&&e&&o(nw(t,n),e.startLine,e.endLine)},[n,t,o]);(0,i.useEffect)(()=>{if(!o||"source"!==L)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let n=q.current,r=n?uz(n,window.getSelection()):null;r&&(e.preventDefault(),e$(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[L,e$,o]),(0,i.useEffect)(()=>{if(!J.current||S||$&&!eu||"diff"===M&&!k||"diff"===M&&ec&&"diff"!==L)return;let e=q.current;e&&(e.scrollTop=Y.current.scrollTop,e.scrollLeft=Y.current.scrollLeft,J.current=!1)},[g?.content,L,$,k,ec,eu,S,M]);let eI=!!l,eM=(0,i.useMemo)(()=>{let e=ny(t);return{code(e){let{className:t,children:n,...i}=e,s=t?.replace("language-","").toLowerCase()??"",l=String(n);return t?.includes("language-")||l.includes("\n")?"mermaid"===s?(0,r.jsx)(lb,{code:l.replace(/\n$/,""),defaultPreview:!0}):sK(s)?(0,r.jsx)(lM,{code:l.replace(/\n$/,""),lang:s}):(0,r.jsx)(l$,{code:l.replace(/\n$/,""),lang:s}):(0,r.jsx)("code",{className:t,...i,children:n})},pre(e){let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})},a(t){let{href:i,children:s,...l}=t;delete l.node;let o=eI?iW(i,e,n??e):null;return o&&eI?(0,r.jsx)("a",{href:i,...l,onClick:e=>{iM(e)&&(e.preventDefault(),en.current?.(o,iF(i)??void 0))},children:s}):su(i)?(0,r.jsx)("a",{href:i,...l,target:"_blank",rel:"noopener noreferrer",children:s}):(0,r.jsx)("a",{href:i,...l,onClick:sp,children:s})},img(t){let{src:i,alt:l,...o}=t;delete o.node;let a="string"==typeof i?iW(i,e,n??e):null,d=a?uW(a,"read",s):i;return(0,r.jsx)("img",{src:d,alt:l??"",loading:"lazy",...o})}}},[n,t,eI,s]);if(S||"diff"===M&&y&&!g)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:m("i18n.loading")});if($&&!eu)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:$});if(!g&&!eu)return null;let eT=eu?["diff"]:["source",...ey?["preview"]:[],...ec?["diff"]:[]],eR=eu?m("files.deleted"):eo?`${m("files.binary")} \xb7 ${uH(g.size)}`:`${eg} \xb7 ${em.length} lines \xb7 ${uH(g.size)}`;return(0,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",position:"relative"},children:[(0,r.jsxs)("div",{className:"file-viewer-toolbar",style:{display:"flex",alignItems:"center",gap:8,padding:"5px 12px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{className:"file-viewer-path",style:{fontFamily:"var(--font-mono)"},title:t,children:nw(t,n)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:eR,children:eR}),!eu&&(0,r.jsx)("span",{title:O?m("i18n.liveSync"):m("i18n.notWatching"),"aria-label":O?m("i18n.liveSync"):m("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:O?"#4ade80":"var(--border)",boxShadow:O?"0 0 4px #4ade80":"none"}}),(0,r.jsxs)("div",{className:"file-viewer-controls",children:[eT.length>1&&(0,r.jsx)("div",{className:"file-viewer-mode-switch","aria-label":m("i18n.fileViewMode"),children:eT.map(e=>{let t=ew===e;return(0,r.jsx)("button",{type:"button",onClick:()=>er(e),title:"diff"===e?m("i18n.compareHead"):void 0,"aria-pressed":t,className:"file-viewer-mode-button",style:{background:t?"var(--bg-selected)":"transparent",color:t?"var(--text)":"var(--text-muted)"},children:u$[e]},e)})}),(0,r.jsxs)("div",{className:"file-viewer-actions",children:[(a||o)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{X&&o?e$(X):a?.(nw(t,n),!1)},title:X&&o?`${m("i18n.mentionSelectedLines")} (L${X.startLine}${X.startLine!==X.endLine?`-L${X.endLine}`:""})`:m("files.insertPath"),"aria-label":m("files.mention"),disabled:!a&&!o,className:"file-viewer-icon-button",children:(0,r.jsx)(uA,{})}),("source"===ew||"diff"===ew)&&!eo&&(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("button",{type:"button",onClick:ei,title:P?m("i18n.disableWrap"):m("i18n.enableWrap"),"aria-label":P?m("i18n.disableWrap"):m("i18n.enableWrap"),"aria-pressed":P,className:"file-viewer-icon-button",style:{background:P?"var(--bg-selected)":"transparent",color:P?"var(--text)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,r.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,r.jsx)("path",{d:"M3 18h7"})]})})})]}),!eu&&(0,r.jsx)(uB,{filePath:t,sourceSessionId:s})]})]}),eS&&g?.truncated&&(0,r.jsxs)("div",{className:"file-viewer-load-more",style:{display:"flex",alignItems:"center",justifyContent:"center",gap:10,padding:"5px 8px",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-dim)",fontSize:11},children:[(0,r.jsxs)("span",{children:[uH(g.nextOffset)," / ",uH(g.size)]}),(0,r.jsx)("button",{type:"button",className:"file-viewer-mode-button",disabled:N,onClick:()=>{E(!0),es(t,g.nextOffset).finally(()=>E(!1))},children:N?m("i18n.loading"):m("i18n.loadMore")})]}),(0,r.jsx)("div",{ref:q,className:"file-viewer-content",onScroll:e=>{Y.current.scrollTop=e.currentTarget.scrollTop,Y.current.scrollLeft=e.currentTarget.scrollLeft},style:{flex:1,overflow:"auto",background:"var(--bg)",paddingBottom:eS?48:void 0},children:"diff"===ew&&ec?(0,r.jsx)(uU,{patch:v.patch,wrapLines:P,language:eg,prismReady:ex,isDark:f}):ev&&"preview"===ew&&g?.truncated&&!ee?.text?(0,r.jsx)("div",{style:{padding:24,color:"var(--text-dim)",fontSize:12},children:ee?.error??m("i18n.loading")}):ev&&"preview"===ew?(0,r.jsx)("iframe",{srcDoc:ej,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:m("i18n.htmlPreview")}):eb&&"preview"===ew?(0,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[eh?.data&&(0,r.jsx)(uN,{data:eh.data}),(0,r.jsx)(iQ.oz,{remarkPlugins:sR,rehypePlugins:sO,urlTransform:l?sc:sd,components:eM,children:ep})]}):ea&&"preview"===ew?(0,r.jsx)(uS,{content:ef,filePath:t,complete:!g?.truncated,scrollRef:q}):eo?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:10,padding:24,color:"var(--text-muted)",fontSize:13,textAlign:"center"},children:[(0,r.jsx)("span",{children:m("files.binaryNoPreview")}),(0,r.jsx)("a",{href:uW(t,"download",s),download:nb(t),className:"file-viewer-mode-button",style:{display:"inline-flex",alignItems:"center",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",textDecoration:"none"},children:m("files.download")})]}):eC?(0,r.jsx)("div",{className:"file-source-view is-lightweight",style:{width:P?"100%":"max-content",minWidth:"100%",minHeight:"100%",background:"var(--bg)",...uI},children:eE}):eN})]})}function uX(e,t){let n=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=n.current;if(!e)return;let t=t=>{t.ctrlKey||Math.abs(t.deltaY)<=Math.abs(t.deltaX)||e.scrollWidth<=e.clientWidth||(t.preventDefault(),e.scrollLeft+=t.deltaY*(1===t.deltaMode?16:2===t.deltaMode?e.clientWidth:1))};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[]),(0,i.useEffect)(()=>{let t=n.current,r=t?.querySelector(e);if(!t||!r)return;let i=t.getBoundingClientRect(),{left:s,right:l}=r.getBoundingClientRect();s<i.left?t.scrollLeft-=i.left-s:l>i.right&&(t.scrollLeft+=l-i.right)},[e,t]),n}function uQ(e){let{tabs:t,activeTabId:n,onSelectTab:s,onCloseTab:l,onReorderTab:o}=e,{t:a}=(0,t_.s)(),[d,c]=(0,i.useState)(null),u=uX('[role="tab"][aria-selected="true"]',`${t.length}
83
+ ${n}`),p=(0,i.useRef)(null),[h,f]=(0,i.useState)(null);return(0,r.jsx)("div",{ref:u,role:"tablist",className:"tabbar-scroll",style:{display:"flex",alignItems:"stretch",background:"var(--bg-panel)",overflowX:"auto",overflowY:"hidden",flexShrink:0,height:"var(--top-bar-height)"},children:t.map(e=>{let i=e.id===n;return(0,r.jsxs)("div",{role:"tab","aria-label":"terminal"===e.kind?a("terminal.tabLabel",{name:e.label}):"agent"===e.kind?a("subagent.tabLabel",{name:e.label}):"side"===e.kind?a("sideChat.tabLabel"):e.label,"aria-selected":i,draggable:!!o,onDragStart:t=>{o&&(p.current=e.id,t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",e.id))},onDragOver:t=>{if(!p.current||p.current===e.id)return;t.preventDefault(),t.dataTransfer.dropEffect="move";let n=t.currentTarget.getBoundingClientRect(),r=t.clientX>=n.left+n.width/2;f(t=>t?.id===e.id&&t.after===r?t:{id:e.id,after:r})},onDrop:t=>{if(!p.current||p.current===e.id)return;t.preventDefault(),t.stopPropagation();let n=t.currentTarget.getBoundingClientRect();o?.(p.current,e.id,t.clientX>=n.left+n.width/2),p.current=null,f(null)},onDragLeave:t=>{t.currentTarget.contains(t.relatedTarget)||f(t=>t?.id===e.id?null:t)},onDragEnd:()=>{p.current=null,f(null)},tabIndex:i||!n&&t[0].id===e.id?0:-1,onKeyDown:n=>{if(n.target===n.currentTarget){if("Enter"===n.key||" "===n.key)n.preventDefault(),s(e.id);else if(["ArrowLeft","ArrowRight","Home","End"].includes(n.key)){n.preventDefault();let r=t.findIndex(t=>t.id===e.id),i="Home"===n.key?0:"End"===n.key?t.length-1:(r+("ArrowRight"===n.key?1:-1)+t.length)%t.length;s(t[i].id),n.currentTarget.parentElement?.children[i]?.focus()}}},onClick:()=>s(e.id),onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:t=>{1===t.button&&(t.preventDefault(),t.stopPropagation(),e.closing||l(e.id))},style:{display:"flex",alignItems:"center",gap:6,paddingLeft:12,paddingRight:6,borderRight:"1px solid var(--border)",background:i?"var(--bg)":"var(--bg-panel)",cursor:"pointer",fontSize:12,color:i?"var(--text)":"var(--text-muted)",whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s",boxShadow:h?.id===e.id?`inset ${h.after?"-2px":"2px"} 0 var(--accent)`:void 0},children:[(0,r.jsx)("span",{style:{flexShrink:0,opacity:i?1:.7,display:"flex",alignItems:"center"},children:"terminal"===e.kind?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]}):"agent"===e.kind?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]}):"side"===e.kind?(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:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"})}):ng(e.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:i?500:400},title:e.filePath,children:e.label}),(0,r.jsx)("button",{draggable:!1,onDragStart:e=>e.stopPropagation(),disabled:e.closing,onClick:t=>{t.stopPropagation(),l(e.id)},onMouseEnter:()=>c(e.id),onMouseLeave:()=>c(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:d===e.id?"var(--bg-hover)":"transparent",border:"none",borderRadius:4,color:d===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:a("terminal"===e.kind?"terminal.close":"i18n.close"),"aria-label":`${a("terminal"===e.kind?"terminal.close":"i18n.close")} ${e.label}`,children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,r.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})})}function u0(e,t,n,r){let i=e.findIndex(e=>e.id===t);if(-1===i||(e[i].viewerRevision??0)!==n)return e;let s=[...e];return s[i]={...s[i],viewerState:r},s}let u1=["general","models","archives","skills","agents","plugins","mcp"],u2="pi-web:settings-navigation",u4=new Set(["skills","agents","plugins"]);function u8(e){return u4.has(e)}function u3(){try{return window.localStorage}catch{return null}}function u5(e){let t=e.getItem(u2);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 u6(e,t){return"models"===e?e:t?JSON.stringify([e,t]):"mcp"===e?e:null}function u9(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:u3();if(t)try{let n=u5(t);n.section=e,t.setItem(u2,JSON.stringify(n))}catch{}}function u7(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:u3();if(!n)return null;let r=u6(e,t);if(!r)return null;try{let e=u5(n).selections?.[r];return"string"==typeof e&&e.length>0?e:null}catch{return null}}function pe(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:u3();if(!r||!t)return;let i=u6(e,n);if(i)try{let e=u5(r);e.selections={...e.selections,[i]:t},r.setItem(u2,JSON.stringify(e))}catch{}}let pt="llama.cpp";function pn(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}class pr extends Error{constructor(e){super(`Context window of ${e} must be a positive number of tokens`),this.name="ContextWindowError",this.model=e}}function pi(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 ps={empty:e=>`Provider ${e} needs a Base URL or at least one model`,baseUrl:e=>`Provider ${e} needs a Base URL`};class pl extends Error{constructor(e,t){super(ps[t](e)),this.name="ProviderEntryError",this.provider=e,this.problem=t}}function po(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function pa(e){return!po(e)||"string"!=typeof e.id||e.id.trim().length>0}function pd(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function pc(e){let t=pd(e.inputLimits)?e.inputLimits.images:void 0,n=pd(t)?t.resize:void 0;return pd(n)?n.maxBytes:void 0}function pu(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 pp(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 ph 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 pf=["input","output","cacheRead","cacheWrite"];function pm(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 pg(e){if(!px(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 px(e){return pf.some(t=>""!==e[t].trim())}function pv(e,t,n){return{...e,compat:{...e.compat??{},[t]:n}}}function pb(e){return new Map(Object.entries(e.providers??{}).map(e=>{let[t,n]=e;return[t,(n.models??[]).map(e=>e.id)]}))}function py(e,t,n){if(n<=0)return;let r=e.get(t)??[];e.set(t,[...r,...Array.from({length:n},()=>null)])}function pw(e,t,n,r){let i=e.providers??{},s=i[n],l=s?.models;if(!l||r.every((e,t)=>e===t))return null;let 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=>l[e])}}},providerName:n,order:r}}function pk(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 pj(e,t,n){let r=e.trim().toLowerCase();return!r||n.toLowerCase().includes(r)||t.toLowerCase().includes(r)}function pS(e){return e.name?.trim()||e.id}function pC(e){let t=new Map;for(let[n,r]of Object.entries(e.providers??{}))"string"==typeof r.name&&t.set(n,r.name);return t}function pN(e){let{embedded:t,title:n,subtitle:i,closeLabel:s="Close",onClose:l,children:o,width:a=900,height:d="78vh"}=e,c=t?void 0:{"--config-panel-width":`${a}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||l()},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:l,title:s,"aria-label":s,children:"\xd7"})]}),o]})})}let pE=(0,i.createContext)(null);function p$(){return(0,i.useContext)(pE)??pI}let pI={detailOpen:!1,openDetail:()=>{},closeDetail:()=>{},reportDetailTitle:()=>{}};function pM(e,t){let{detailOpen:n,reportDetailTitle:r}=p$(),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 pT(e){let{children:t}=e,n=(0,i.useContext)(pE);return(0,r.jsx)("div",{className:"config-split-view","data-pane":n?n.detailOpen?"detail":"list":void 0,children:t})}function pR(e){let{children:t}=e;return(0,r.jsx)("aside",{className:"config-sidebar",children:t})}function pA(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-sidebar-list",children:t})}function pL(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 pz(e){let{enabled:t,total:n,checked:i,label:s,disabled:l=!1,loading:o=!1,describedBy:a,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)(p5,{checked:i??(n>0&&t===n),disabled:l,loading:o,label:s,describedBy:a,onChange:d})]})}function pP(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 pW(e){let{active:t=!1,className:n,children:i,onClick:s,ref:l,...o}=e,{openDetail:a}=p$(),d=pM(t,l);return(0,r.jsx)("button",{type:"button",...o,ref:d,onClick:e=>{s?.(e),e.defaultPrevented||a()},"aria-current":t?"page":void 0,className:["config-sidebar-item",n].filter(Boolean).join(" "),children:i})}function pO(e){let{className:t,...n}=e;return(0,r.jsx)("span",{...n,className:["config-sidebar-text",t].filter(Boolean).join(" ")})}function pF(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-stack",t].filter(Boolean).join(" ")})}function pD(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header",t].filter(Boolean).join(" ")})}function pB(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header-info",t].filter(Boolean).join(" ")})}function pH(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-actions",t].filter(Boolean).join(" ")})}function p_(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-title",children:t})}function pU(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-section-title",children:t})}function pK(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 pq(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-grid",children:t})}function pV(e){let{label:t,tone:n="muted",mono:i=!1,className:s,style:l,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:l,children:o})]})}function pZ(e){let{scope:t,children:n}=e;return(0,r.jsx)("span",{className:`config-scope-tag${"project"===t?" is-project":""}`,children:n})}function pJ(e){let{value:t,options:n,label:s,disabledReason:l,size:o="default",onChange:a,children:d}=e,c=(0,i.useId)(),u=l&&n.some(e=>e.disabled)?l: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||a(e.value)},children:e.label},e.value))}),d]}),u&&(0,r.jsx)("span",{id:c,className:"config-scope-switch-reason",children:u})]})}function pY(e){let{value:t,options:n,label:s,path:l,disabledReason:o,onChange:a,children:d}=e;return(0,r.jsxs)("div",{className:"config-save-target",children:[(0,r.jsx)(pJ,{value:t,options:n,label:s,disabledReason:o,size:"small",onChange:a,children:(0,r.jsx)("span",{className:"config-save-target-path",children:"string"==typeof l?l.split(/([\\/])/).map((e,t)=>"/"===e||"\\"===e?(0,r.jsxs)(i.Fragment,{children:[e,(0,r.jsx)("wbr",{})]},t):e):l})}),d]})}function pG(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)(p_,{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 pX(e){let{title:t,catalogs:n,target:s,inputLabel:l,inputId:o,placeholder:a,value:d,canSubmit:c,normalizeValue:u,onValueChange:p,onSubmit:h,examplesLabel:f,examples:m,error:g,multiline:x=!1,children:v}=e,b=(0,i.useRef)(null),y=(0,i.useRef)(null);(0,i.useEffect)(()=>{x?window.matchMedia?.("(pointer: coarse)").matches||y.current?.focus():b.current?.focus()},[x]);let w=e=>{if(!u)return;let t=e.clipboardData.getData("text"),n=u(t);n!==t&&(e.preventDefault(),p(n))};return(0,r.jsxs)(pF,{className:"is-fill",children:[(0,r.jsx)(pG,{title:t,catalogs:n,target:s}),(0,r.jsx)(pK,{label:l,children:x?(0,r.jsx)("textarea",{id:o,ref:y,value:d,"aria-label":l,className:"config-add-source-input is-multiline",placeholder:a,rows:5,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>p(e.target.value),onPaste:w,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:b,value:d,"aria-label":l,className:"config-add-source-input",placeholder:a,onChange:e=>p(e.target.value),onPaste:w,onBlur:e=>{u&&p(u(e.currentTarget.value))},onKeyDown:e=>{!e.nativeEvent.isComposing&&229!==e.keyCode&&"Enter"===e.key&&c&&h()}})}),v,m.length>0&&(0,r.jsxs)("div",{className:"config-add-source-examples",children:[(0,r.jsx)("div",{className:"config-add-source-examples-label",children:f}),(0,r.jsx)("div",{className:"config-add-source-example-list",children:m.map(e=>"string"==typeof e?(0,r.jsx)("button",{type:"button",className:"config-add-source-example",onClick:()=>p(e),children:e},e):(0,r.jsxs)("button",{type:"button",className:"config-add-source-example has-label",onClick:()=>p(e.value),children:[(0,r.jsx)("span",{className:"config-add-source-example-label",children:e.label}),(0,r.jsx)("span",{className:"config-add-source-example-value",children:e.value})]},e.value))})]}),g&&(0,r.jsx)("div",{role:"alert",className:"config-add-source-error",children:g})]})}function pQ(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 p0(e){let{id:t,message:n,trustLabel:i,trusting:s=!1,onTrust:l}=e;return(0,r.jsx)(pQ,{id:t,action:l&&i?(0,r.jsx)(p3,{size:"small",onClick:l,disabled:s,children:i}):void 0,children:n})}function p1(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-empty-state",children:t})}function p2(e){let{children:t,style:n}=e;return(0,r.jsx)("div",{className:"config-detail",style:n,children:t})}function p4(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 p8(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 p3(e){let{variant:t="secondary",size:n="default",className:i,children:s,...l}=e;return(0,r.jsx)("button",{type:"button",...l,className:["config-button",`config-button-${t}`,`config-button-${n}`,i].filter(Boolean).join(" "),children:s})}function p5(e){let{checked:t,disabled:n=!1,loading:i=!1,size:s="default",label:l,describedBy:o,onChange:a}=e,d=n||i;return(0,r.jsx)("button",{type:"button",role:"switch","aria-checked":t,"aria-busy":i||void 0,"aria-label":l,"aria-describedby":o,title:l,disabled:d,className:`config-switch${"small"===s?" is-small":""}${i?" is-loading":""}`,onClick:()=>a(!t),children:(0,r.jsx)("span",{className:"config-switch-knob","aria-hidden":"true"})})}function p6(e){let{active:t=!1,children:n,className:i,onClick:s,ref:l,...o}=e,{openDetail:a}=p$(),d=pM(t,l);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||a()},"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 p9(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 p7(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 he(e,t){let n=p7(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 ht(e,t){return t.enabled&&(e?.enabledTotal??0)<=1}function hn(e,t){return e?.providers.find(e=>e.id===t)}function hr(e){let{modelName:t,effective:n,value:i,onChange:s,disabled:l=!1,describedBy:o}=e,{t:a}=(0,t_.s)(),d=void 0!==i&&void 0===pi(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:a("models.contextWindow"),"aria-label":a("models.contextForModel",{model:t}),"aria-invalid":d||void 0,"aria-describedby":o,disabled:l,onChange:e=>s(""===e.target.value.trim()?void 0:e.target.value)})}let hi={"last-model":"models.enabledLastModel","project-scope":"models.enabledProjectScope"};function hs(e){let{controller:t}=e,{t:n}=(0,t_.s)(),{view:i,pending:s}=t;if(!i)return null;let l=!i.allEnabled,o=i.stalePatterns.length;return l||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)(p3,{size:"small",onClick:t.pruneStale,disabled:null!==s,title:n("models.enabledPruneHint"),children:n("models.enabledPrune")}),i.editable&&l&&(0,r.jsx)(p3,{size:"small",onClick:t.clearScope,disabled:null!==s,title:n("models.enabledClearHint"),children:n("models.enabledClear")})]}):null}function hl(e){let{providerId:t,controller:n,noteId:i}=e,{t:s}=(0,t_.s)(),{view:l,loading:o,pending:a,failure:d}=n,c=hn(l,t),u=d?d.messageKey?s(d.messageKey):d.message:null,p=ho(n,t)?i:void 0;if(o&&!l)return null;if(!c)return(0,r.jsx)(p5,{checked:!1,disabled:!0,label:s("models.enabledProviderToggle",{provider:t}),describedBy:p,onChange:()=>{}});let h=he(l,c);return(0,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("span",{className:"enabled-models-switch-error",children:u}),(0,r.jsx)(p5,{checked:h.checked,loading:a===`provider:${c.id}`,disabled:null!==a||h.blocked,label:s("models.enabledProviderToggle",{provider:c.name}),describedBy:p,onChange:e=>n.setProvider(c.id,e)})]})}function ho(e,t){let{view:n,loading:r}=e;if(r&&!n)return null;let i=hn(n,t);if(!i)return"models.enabledCustomEmpty";let{reason:s}=he(n,i);return s?hi[s]:null}function ha(e){let{providerId:t,controller:n,id:i}=e,{t:s}=(0,t_.s)(),l=ho(n,t);return l?(0,r.jsx)("div",{id:i,className:"config-detail-heading-note",children:s(l)}):null}function hd(e){var t;let n,{providerId:s,controller:l,contextSettings:o,emptyCatalogHint:a}=e,{t:d}=(0,t_.s)(),[c,u]=(0,i.useState)(""),{view:p,loading:h,pending:f,failure:m}=l,g=hn(p,s)??(a&&!m?{id:s,models:[],enabledCount:0}:void 0),x=function(e,t){let[n,r]=(0,i.useState)(!1),[s,l]=(0,i.useState)(null);return(0,i.useEffect)(()=>l(null),[e]),{refreshing:n,note:s,refresh:(0,i.useCallback)(()=>{r(!0),l(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?l("models.catalogOffline"):r.completed?l(r.changed?"models.catalogUpdated":"models.catalogUnchanged"):l("models.catalogUnreachable"),r.changed&&t()}catch{l("models.catalogUnreachable")}finally{r(!1)}})()},[e,t])}}(s,l.refresh),v=(0,i.useId)();if((0,i.useEffect)(()=>u(""),[s]),h&&!p)return(0,r.jsx)("div",{className:"enabled-models-empty",children:d("agents.modelsLoading")});if(!g)return m?.message?(0,r.jsx)("div",{className:"enabled-models-error",children:m.message}):(0,r.jsx)("div",{className:"enabled-models-empty",children:d("models.enabledUnavailable")});let b=(t=g.models,(n=c.trim().toLowerCase())?t.filter(e=>e.id.toLowerCase().includes(n)||e.name.toLowerCase().includes(n)):[...t]),y=p7(p,b),w=b.length!==g.models.length,k=null!==f,j=`provider:${g.id}`,S=p?.editable===!0,C=`${v}-scope`,N=`${v}-last`,E=`${v}-context`,$=S&&!y.canDisable&&y.disableRefs.length>0,I=$||S&&b.some(e=>ht(p,e)),M=(e,t)=>{w?l.setModels(j,t,e):l.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:d("models.enabledSection")}),(0,r.jsx)("span",{className:"enabled-models-count",children:d("models.enabledCount",{enabled:g.enabledCount,total:g.models.length})}),(0,r.jsx)(p3,{size:"small",disabled:k||!y.canEnable,"aria-describedby":S?void 0:C,onClick:()=>M(!0,y.enableRefs),children:w?d("models.enableShown"):d("models.enableAll")}),(0,r.jsx)(p3,{size:"small",disabled:k||!y.canDisable,"aria-describedby":S?$?N:void 0:C,onClick:()=>M(!1,y.disableRefs),children:w?d("models.disableShown"):d("models.disableAll")}),(0,r.jsx)(p3,{size:"small",disabled:k||x.refreshing,title:d("models.refreshCatalogHint"),onClick:x.refresh,children:x.refreshing?d("models.refreshingCatalog"):d("models.refreshCatalog")})]}),x.note&&(0,r.jsx)("div",{className:"enabled-models-note",children:d(x.note)}),!S&&(0,r.jsx)("div",{id:C,className:"enabled-models-note",children:d("models.enabledProjectScope")}),I&&(0,r.jsx)("div",{id:N,className:"enabled-models-note",children:d("models.enabledLastModel")}),m&&(0,r.jsx)("div",{className:"enabled-models-error",children:m.messageKey?d(m.messageKey):m.message}),g.models.length>8&&(0,r.jsx)("input",{value:c,onChange:e=>u(e.target.value),placeholder:d("models.enabledFilterPlaceholder",{count:g.models.length}),"aria-label":d("models.enabledFilter"),className:"enabled-models-filter"}),o&&g.models.length>0&&(0,r.jsx)("div",{id:E,className:"enabled-models-note",children:d("models.contextOverrideHelp")}),(0,r.jsx)("div",{className:"enabled-models-list",children:0===b.length?(0,r.jsx)("div",{className:"enabled-models-empty",children:0===g.models.length&&a||d("models.enabledNoMatches")}):b.map(e=>{let t=ht(p,e),n=o?.overrides?.[e.id],i=n&&"object"==typeof n&&!Array.isArray(n)?n.contextWindow:void 0;return(0,r.jsxs)("div",{className:"enabled-models-row",children:[(0,r.jsxs)("span",{className:"enabled-models-row-text",children:[(0,r.jsx)("span",{className:"enabled-models-row-name",children:e.name}),(0,r.jsx)("code",{className:"enabled-models-row-id",children:e.id})]}),e.thinkingPin&&(0,r.jsx)("span",{className:"enabled-models-pin",title:d("models.enabledPinHint"),children:e.thinkingPin}),o&&(0,r.jsx)(hr,{modelName:e.name,effective:e.contextWindow,value:i,disabled:o.disabled,describedBy:E,onChange:t=>o.onChange(e.id,t)}),(0,r.jsx)(p5,{checked:e.enabled,loading:f===e.ref,disabled:k||!p?.editable||t,label:d("models.enabledToggle",{model:e.name}),describedBy:S?t?N:void 0:C,onChange:t=>l.setModels(e.ref,[e.ref],t)})]},e.ref)})})]})}function hc(e){let{message:t,hint:n,value:i,placeholder:s,submitLabel:l,inputLabel:o,disabled:a=!1,plainEnterSubmits:d=!0,inputRef:c,onValueChange:u,onSubmit:p}=e,h=!a&&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:a||void 0,onChange:e=>u(e.target.value),onKeyDown:e=>{var t;t={key:e.key,metaKey:e.metaKey,ctrlKey:e.ctrlKey,isComposing:e.nativeEvent.isComposing,keyCode:e.keyCode},"Enter"===t.key&&!t.isComposing&&229!==t.keyCode&&(d||t.metaKey||t.ctrlKey)&&h&&p()}}),(0,r.jsx)("button",{type:"button",className:"oauth-paste-submit",onClick:p,disabled:!h,children:l})]})]})}let hu={anthropic:{symbol:"anthropic",color:!1},openai:{symbol:"openai",color:!1},"openai-codex":{symbol:"openai",color:!1},google:{symbol:"google",color:!0},"google-vertex":{symbol:"google",color:!0},"ant-ling":{symbol:"antgroup",color:!0},deepseek:{symbol:"deepseek",color:!0},groq:{symbol:"groq",color:!1},"llama.cpp":{symbol:"llama-cpp",color:!1},mistral:{symbol:"mistral",color:!0},moonshotai:{symbol:"moonshot",color:!1},"moonshotai-cn":{symbol:"moonshot",color:!1},moonshot:{symbol:"moonshot",color:!1},minimax:{symbol:"minimax",color:!0},"minimax-cn":{symbol:"minimax",color:!0},fireworks:{symbol:"fireworks",color:!0},huggingface:{symbol:"huggingface",color:!0},cerebras:{symbol:"cerebras",color:!0},openrouter:{symbol:"openrouter",color:!1},xai:{symbol:"xai",color:!1},"cloudflare-ai-gateway":{symbol:"cloudflare",color:!0},"cloudflare-workers-ai":{symbol:"cloudflare",color:!0},"vercel-ai-gateway":{symbol:"vercel",color:!1},"github-copilot":{symbol:"githubcopilot",color:!1},"amazon-bedrock":{symbol:"aws",color:!0},azure:{symbol:"azure",color:!0},"azure-openai-responses":{symbol:"azure",color:!0},"kimi-coding":{symbol:"kimi",color:!0},nvidia:{symbol:"nvidia",color:!0},opencode:{symbol:"opencode",color:!1},"opencode-go":{symbol:"opencode",color:!1},qwen:{symbol:"qwen",color:!0},xiaomi:{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-ams":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-cn":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-sgp":{symbol:"xiaomimimo",color:!1},zai:{symbol:"zai",color:!1},"zai-coding-cn":{symbol:"zai",color:!1},zhipu:{symbol:"zhipu",color:!0},cohere:{symbol:"cohere",color:!0},perplexity:{symbol:"perplexity",color:!0},together:{symbol:"together",color:!0},grok:{symbol:"grok",color:!1}};function hp(e){let{id:t,size:n}=e,i=hu[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 hh=["openai-codex","deepseek","openrouter","moonshotai","moonshotai-cn","minimax","minimax-cn","vercel-ai-gateway","opencode-go","kimi-coding"],hf="pi-web:provider-usage:";function hm(e){let{providerId:t,enabled:n}=e;return hh.includes(t)?(0,r.jsx)(hg,{providerId:t,enabled:n}):null}function hg(e){let{providerId:t,enabled:n}=e,[s,l]=(0,i.useState)(null),[o,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),h=(0,i.useRef)(null),{locale:f,t:m}=(0,t_.s)();(0,i.useEffect)(()=>{h.current&&clearTimeout(h.current),p(!1),l(null);try{let e=localStorage.getItem(`${hf}${t}`);if(e){let t=JSON.parse(e);t?.status==="ready"&&t.report&&Array.isArray(t.report.buckets)&&Array.isArray(t.report.metrics)&&l(t)}}catch{try{localStorage.removeItem(`${hf}${t}`)}catch{}}return c(null),()=>{h.current&&clearTimeout(h.current)}},[t]);let g=(0,i.useCallback)(async()=>{a(!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){l(n);try{localStorage.setItem(`${hf}${t}`,JSON.stringify(n))}catch{}p(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>p(!1),2e3)}else c(n.message??m("providerUsage.queryFailed"))}catch(e){c(e instanceof Error?e.message:m("providerUsage.queryFailed"))}finally{a(!1)}},[t,m]),x=s?.status==="ready"?s.report:void 0;return(0,r.jsxs)("section",{style:{paddingTop:10,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:13,color:"var(--text)",fontWeight:600,lineHeight:1.35},children:m("providerUsage.usage")}),(0,r.jsx)("button",{type:"button",onClick:g,disabled:!n||o,title:m(o?"providerUsage.refreshing":"providerUsage.refresh"),"aria-label":m(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(f),style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap"},children:m("providerUsage.updated",{time:(0,nG.ob)(x.capturedAt,f)})})]}),!x&&!d&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)"},children:m("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 ":"$"}${hx(e.remaining??e.limit)}`:void 0!==e.remaining&&void 0!==e.limit?`${hx(e.remaining)} / ${hx(e.limit)}`:e.period??t}(e,m("providerUsage.available"))})]},e.id)),x.metrics.map(e=>{var t;return(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("span",{style:{color:"var(--text)",fontFamily:"var(--font-mono)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:"currency"===(t=e).unit?`${"CNY"===t.currency?"CNY ":"$"}${t.value}`:String(t.value)})]},e.id)})]})]})}function hx(e){return void 0===e?"-":Number.isInteger(e)?String(e):e.toFixed(2)}function hv(){let e=u7("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 hb(e){return 1===Object.keys(e).length&&Object.keys(e.modelOverrides??{}).length>0}let hy=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],hw={empty:"models.providerIncomplete",baseUrl:"models.providerNeedsBaseUrl"};function hk(e){let{label:t,children:n}=e;return(0,r.jsx)(pK,{label:t,children:n})}let hj={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 hS(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:{...hj,fontFamily:s?"var(--font-mono)":"inherit"}})}function hC(e){let{value:t,onChange:n,placeholder:s,mono:l,onKeyDown:o,autoComplete:a="off",spellCheck:d=!1,style:c}=e,[u,p]=(0,i.useState)(!1),{t:h}=(0,t_.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:{...hj,paddingRight:34,fontFamily:l?"var(--font-mono)":"inherit"},autoComplete:a,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 hN(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?{...hj,borderColor:"#ef4444"}:hj})}function hE(e){let{value:t,onChange:n,options:i,required:s}=e,{t:l}=(0,t_.s)();return(0,r.jsxs)("select",{value:t,onChange:e=>n(e.target.value),style:{...hj,color:t?"var(--text)":"var(--text-dim)"},children:[!s&&(0,r.jsxs)("option",{value:"",children:["— ",l("i18n.default")," / none —"]}),i.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]})}function h$(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 hI(e){let{children:t}=e;return(0,r.jsx)(pU,{children:t})}function hM(e){let{name:t,editingName:n,fallbackLabel:s,provider:l,onChange:o,onEditingNameChange:a,onRename:d,onDelete:c,onAddModels:u,enabledModels:p}=e,{t:h}=(0,t_.s)(),[f,m]=(0,i.useState)({phase:"idle"}),[g,x]=(0,i.useState)(""),[v,b]=(0,i.useState)([]),y=(0,i.useRef)(0),w=(0,i.useRef)(null),k=(0,i.useId)(),j=(e,t)=>o({...l,[e]:t});(0,i.useEffect)(()=>{y.current+=1,m({phase:"idle"}),x(""),b([])},[t,l.baseUrl,l.api,l.apiKey]);let S=(0,i.useCallback)(async()=>{if("loading"===f.phase)return;let e=++y.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:{...l,models:void 0}})}),r=await n.json();if(e!==y.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??l.baseUrl??""})}catch(t){if(e!==y.current)return;m({phase:"error",message:t instanceof Error?t.message:String(t)})}},[f.phase,t,l]),C=new Set((l.models??[]).map(e=>e.id)),N="success"===f.phase?f.models:[],E=g.trim().toLocaleLowerCase(),$=N.filter(e=>!E||e.id.toLocaleLowerCase().includes(E)||e.name?.toLocaleLowerCase().includes(E)),I=$.slice(0,300),M=I.filter(e=>!C.has(e.id)).map(e=>e.id),T=v.filter(e=>!C.has(e)).length,R=M.length>0&&M.every(e=>v.includes(e)),A=!R&&M.some(e=>v.includes(e));return(0,i.useEffect)(()=>{w.current&&(w.current.indeterminate=A)},[A]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(pD,{children:[(0,r.jsx)(pB,{children:(0,r.jsx)(hI,{children:h("i18n.provider")})}),(0,r.jsxs)(pH,{children:[(0,r.jsx)(hl,{providerId:t,controller:p,noteId:k}),(0,r.jsx)(p3,{variant:"danger",size:"small",onClick:c,children:h("i18n.delete")})]})]}),(0,r.jsx)(ha,{providerId:t,controller:p,id:k})]}),(0,r.jsxs)(hk,{label:h("i18n.providerId"),children:[(0,r.jsx)(hS,{value:n,onChange:a,placeholder:"provider-id",mono:!0}),n!==t&&n.trim()&&(0,r.jsx)("button",{onClick:()=>d(n.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--accent)",border:"none",borderRadius:4,color:"var(--accent-contrast)",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:h("i18n.rename")})]}),(0,r.jsx)(hk,{label:h("models.providerDisplayName"),children:(0,r.jsx)(hS,{value:l.name??"",onChange:e=>o(function(e,t){if(!t.trim()){let t={...e};return delete t.name,t}return"name"in e?{...e,name:t}:{name:t,...e}}(l,e)),placeholder:s})}),(0,r.jsx)(hk,{label:"Base URL",children:(0,r.jsx)(hS,{value:l.baseUrl??"",onChange:e=>j("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsx)(hk,{label:"API Key",children:(0,r.jsx)(hC,{value:l.apiKey??"",onChange:e=>j("apiKey",e||void 0),placeholder:h("models.apiKeyPlaceholder"),mono:!0})}),(0,r.jsx)(hk,{label:"API",children:(0,r.jsx)(hE,{value:l.api??"",onChange:e=>j("api",e||void 0),options:hy})}),(0,r.jsx)(hk,{label:"Headers",children:(0,r.jsx)(hW,{headers:l.headers,onChange:e=>j("headers",e)})}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==f.phase&&(0,r.jsx)("button",{onClick:S,disabled:"loading"===f.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:"loading"===f.phase?"var(--text-dim)":"var(--text-muted)",cursor:"loading"===f.phase?"not-allowed":"pointer",fontSize:11},children:"loading"===f.phase?h("models.discoveryFetching"):h("models.discoveryFetch")}),"error"===f.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:f.message}),"success"===f.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:g,onChange:e=>x(e.target.value),placeholder:h("models.discoveryFilterPlaceholder",{count:f.models.length}),"aria-label":h("models.discoveryFilter"),style:{...hj,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:M.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:w,type:"checkbox",checked:R,disabled:0===M.length,onChange:()=>{let e=new Set(M);b(t=>R?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...M])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),h("models.discoverySelectShown")]}),0===I.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:h("models.discoveryNoMatches")}):I.map((e,t)=>{let n=C.has(e.id),i=v.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:i||n,disabled:n,onChange:()=>{var t;return t=e.id,void 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:h("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:f.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:$.length>I.length?h("models.discoveryShowing",{shown:I.length,total:$.length}):h("models.discoveryFetched",{count:f.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==f.phase)return;let e=new Set(v),t=f.models.filter(t=>e.has(t.id)&&!C.has(t.id));0!==t.length&&(u(t),b([]))},disabled:0===T,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:T?"var(--accent)":"var(--bg-panel)",color:T?"var(--accent-contrast)":"var(--text-dim)",cursor:T?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:T?h("models.discoveryAddSelectedCount",{count:T}):h("models.discoveryAddSelected")})]})]})]})]})}let hT=["off","minimal","low","medium","high","xhigh","max"],hR={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function hA(e){let{value:t,onChange:n}=e,{t:i}=(0,t_.s)(),s=t??{},l=(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:hT.map(e=>{let t=s[e],n=e in s?null===t?"null":"string":"omit",o="string"==typeof t?t:"",a=hR[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:a,flexShrink:0,opacity:"null"===n?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===n?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===n?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>l(e,"omit"),style:{...d,..."omit"===n?c:{}},children:i("i18n.default")}),(0,r.jsx)("button",{onClick:()=>l(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:()=>l(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=>l(e,t.target.value),onFocus:()=>{"string"!==n&&l(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 hL={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function hz(e){return e.compat?.thinkingFormat==="deepseek"}function hP(e,t){return{...e.compat??{},...t.compat??{}}}function hW(e){let{headers:t,onChange:n}=e,{t:s}=(0,t_.s)(),[l,o]=(0,i.useState)(()=>Object.entries(t??{}).map((e,t)=>{let[n,r]=e;return{id:t,name:n,value:r}})),a=(0,i.useRef)(l.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(l.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:[l.map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{value:e.name,onChange:t=>c(e.id,{name:t.target.value}),"aria-label":s("models.headerName"),placeholder:"Header-Name",style:{...hj,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>c(e.id,{value:t.target.value}),"aria-label":s("models.headerValue"),placeholder:"value",style:{...hj,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{"aria-label":s("models.removeHeader"),onClick:()=>{var t;return t=e.id,void d(l.filter(e=>e.id!==t))},style:u,children:"✕"})]},e.id)),(0,r.jsxs)("button",{onClick:()=>o(e=>[...e,{id:a.current++,name:"",value:""}]),style:{padding:"5px 9px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,alignSelf:"flex-start"},children:["+ ",s("models.addHeader")]})]})}function hO(e){let{providerName:t,provider:n,model:s,onChange:l,onDelete:o}=e,[a,d]=(0,i.useState)({phase:"idle"}),{t:c}=(0,t_.s)(),[u,p]=(0,i.useState)({phase:"idle"}),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(()=>pm(s.cost)),x=(0,i.useRef)(m),[v,b]=(0,i.useState)(!1),y=(0,i.useRef)(0),w=s.baseUrl??n.baseUrl,k=(0,i.useRef)(0),j=(0,i.useRef)(null),S=(0,i.useRef)(s.cost),C=(e,t)=>l({...s,[e]:t}),N=(()=>{if("idle"===a.phase)return null;if("testing"===a.phase)return c("i18n.testingModel");let e=[void 0!==a.latencyMs?`${a.latencyMs}ms`:null,void 0!==a.status?`HTTP ${a.status}`:null].filter(Boolean);return"success"===a.phase?[c("i18n.connected"),...e,a.responseText||null].filter(Boolean).join(" \xb7 "):[c("i18n.failed"),...e,a.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"}),j.current=null},[t,w,s.id]);let E=(0,i.useCallback)(async()=>{if(!s.id.trim()||"testing"===a.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,a.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"});w?.trim()&&r.set("baseUrl",w.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 a=function(e,t){let n={...e},r=0;if(!e.name?.trim()&&t.name&&(n.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(n.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(n.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(n.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(n.maxTokens=t.maxTokens,r+=1),t.cost){let i={...e.cost??{}},s=0;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],s+=1);let l=pg(pm(i));s>0&&l&&(n.cost={...i,...l},r+=s)}return{model:n,appliedCount:r}}(s,o.recommendation.preset);a.appliedCount>0&&(j.current=s,l(a.model)),f(!1),p({phase:"success",recommendation:o.recommendation,appliedCount:a.appliedCount})}catch(e){if(n!==k.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,s,l,w,t]),I=(()=>{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}`})(),M="error"===u.phase?u.message:I,T="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;hz(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 z=pc(s),P=pu(z),W=[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!==P?c("models.imageMaxBytesSummary",{size:pp(P)}):null].filter(e=>!!e),O=W.length?W.join(" \xb7 "):c("models.providerDefaults");return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(pD,{children:[(0,r.jsx)(pB,{children:(0,r.jsx)(hI,{children:c("i18n.model")})}),(0,r.jsxs)(pH,{children:[N&&(0,r.jsx)("span",{title:N,style:{maxWidth:260,height:28,padding:"0 8px",border:`1px solid ${"error"===a.phase?"#fecaca":"success"===a.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===a.phase?"#fee2e2":"success"===a.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)(p3,{size:"small",variant:"success"===a.phase?"primary":"secondary",onClick:"success"===a.phase?()=>d({phase:"idle"}):E,disabled:!s.id.trim()||"testing"===a.phase,title:c("i18n.testConnection"),className:"success"===a.phase?"is-success":void 0,children:["success"===a.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"===a.phase?c("i18n.checking"):"success"===a.phase?c("common.ok"):c("i18n.test")]}),(0,r.jsx)(p3,{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)(hk,{label:"ID *",children:(0,r.jsx)(hS,{value:s.id,onChange:e=>C("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(hk,{label:"Name",children:(0,r.jsx)(hS,{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")})]}),M&&(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:8,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:T,fontSize:10},children:[(0,r.jsx)("span",{title:M,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M}),j.current&&(0,r.jsx)("button",{onClick:()=>{let e=j.current;e&&(j.current=null,l(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)(hI,{children:c("models.capabilities")}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginTop:8},children:[(0,r.jsx)(h$,{label:c("models.reasoning"),checked:s.reasoning??!1,onChange:e=>C("reasoning",e||void 0)}),(0,r.jsx)(h$,{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)(hI,{children:c("models.modelSpecs")}),(0,r.jsx)("button",{type:"button",onClick:()=>{if(h)return void f(!1);S.current=s.cost;let e=pm(s.cost);x.current=e,g(e),f(!0)},"aria-expanded":h,style:{padding:"2px 4px",border:"none",background:"transparent",color:"var(--accent)",cursor:"pointer",fontSize:10},children:h?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)(hk,{label:c("models.contextWindow"),children:(0,r.jsx)(hN,{value:void 0!==s.contextWindow?String(s.contextWindow):"",onChange:e=>C("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(hk,{label:c("models.maxOutputTokens"),children:(0,r.jsx)(hN,{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)(hk,{label:n,children:(0,r.jsx)(hN,{value:m[t],onChange:e=>{let n,r,i;return r=pg(n={...x.current,[t]:e}),i={...s},void(x.current=n,g(n),r?(i.cost={...S.current??{},...r},S.current=i.cost):delete i.cost,l(i))},placeholder:"0"})},t)}),px(m)&&!pg(m)&&(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,l=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:l?"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:()=>b(e=>!e),"aria-expanded":v,"aria-controls":"model-advanced-settings",style:{width:"100%",minHeight:48,padding:"8px 0",border:"none",background:"transparent",display:"grid",gridTemplateColumns:"minmax(0, 1fr) 18px",alignItems:"center",gap:10,color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:11,fontWeight:600},children: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:O})]}),(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{color:"var(--text-dim)",transform:v?"rotate(180deg)":"none",transition:"transform 0.15s ease"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),v&&(0,r.jsxs)("div",{id:"model-advanced-settings",style:{display:"flex",flexDirection:"column",gap:14,padding:"4px 0 16px"},children:[(0,r.jsx)(hk,{label:c("models.baseUrlOverride"),children:(0,r.jsx)(hS,{value:s.baseUrl??"",onChange:e=>C("baseUrl",e.trim()||void 0),placeholder:n.baseUrl??c("models.providerDefaults"),mono:!0})}),(0,r.jsx)(hk,{label:c("models.apiOverride"),children:(0,r.jsx)(hE,{value:s.api??"",onChange:e=>C("api",e||void 0),options:hy})}),(0,r.jsxs)(hk,{label:c("models.headers"),children:[(0,r.jsx)(hW,{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!==z)&&(0,r.jsxs)(hk,{label:c("models.imageMaxBytes"),children:[(0,r.jsx)(hN,{value:void 0===z?"":String(z),onChange:e=>{var t;let n,r,i,o;return l((t=e.trim()||void 0,n={...pd(s.inputLimits)?s.inputLimits:{}},r={...pd(n.images)?n.images:{}},i={...pd(r.resize)?r.resize:{}},void 0===t?delete i.maxBytes:i.maxBytes=pu(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===P&&void 0!==z}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[void 0!==P&&`${pp(P)} \xb7 `,c("models.imageMaxBytesHelp",{size:pp(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)(hI,{children:c("models.compatibility")}),(0,r.jsx)(h$,{label:c("models.deepSeekThinkingCompat"),checked:hz(s),onChange:e=>l(function(e,t){if(t)return{...e,compat:{...e.compat??{},...hL}};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)(h$,{label:c("models.developerRole"),checked:!1!==hP(n,s).supportsDeveloperRole,onChange:e=>l(pv(s,"supportsDeveloperRole",e))}),(s.api??n.api)==="anthropic-messages"&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[(0,r.jsx)(h$,{label:c("models.adaptiveThinking"),checked:!0===hP(n,s).forceAdaptiveThinking,onChange:e=>l(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(n!==r)return pv(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)(hI,{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)(hA,{value:s.thinkingLevelMap,onChange:e=>C("thinkingLevelMap",e)})]})]})]})]})]})}function hF(e){let{provider:t,onRefresh:n,enabledModels:s,contextSettings:l}=e,[o,a]=(0,i.useState)({phase:"idle"}),{t:d}=(0,t_.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)(()=>{a({phase:"idle"}),u(""),p.current?.close(),p.current=null},[t.id]),(0,i.useEffect)(()=>()=>{p.current?.close()},[]);let f=(0,i.useCallback)(()=>{p.current?.close(),a({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?(a({phase:"auth",url:r.url,instructions:r.instructions??null,token:r.token}),window.open(r.url,"_blank","noopener,noreferrer")):"device_code"===r.type?(a({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?a({phase:"prompt",message:r.message,placeholder:r.placeholder??null,token:r.token}):"select_request"===r.type?a({phase:"select",message:r.message,options:r.options??[],token:r.token}):"progress"===r.type?a({phase:"progress",message:r.message}):"success"===r.type?(e.close(),a({phase:"success"}),n()):"error"===r.type?(e.close(),a({phase:"error",message:r.message})):"cancelled"===r.type&&(e.close(),a({phase:"idle"}))},e.onerror=()=>{e.close(),a(e=>"success"===e.phase?e:{phase:"error",message:d("models.connectionLost")})}},[t.id,n,d]),m=(0,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(t.id)}`,{method:"POST"}),a({phase:"idle"}),n()},[t.id,n]),g=(0,i.useCallback)(async(e,n)=>{if(n.trim()){a({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(()=>({}));a({phase:"error",message:e.error??d("models.serverError",{status:r.status})});return}u("")}catch(e){a({phase:"error",message:e instanceof Error?e.message:d("i18n.networkError")})}}},[t.id,d]),x=(0,i.useCallback)(async(e,n)=>{a({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(()=>({}));a({phase:"error",message:e.error??d("models.serverError",{status:r.status})})}}catch(e){a({phase:"error",message:e instanceof Error?e.message:d("i18n.networkError")})}},[t.id,d]),v="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)(pD,{children:[(0,r.jsx)(pB,{children:(0,r.jsx)(hI,{children:d("i18n.subscription")})}),(0,r.jsxs)(pH,{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")})]}),v?(0,r.jsx)(p3,{size:"small",onClick:()=>{p.current?.close(),a({phase:"idle"})},children:d("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(p3,{variant:"primary",size:"small",onClick:f,children:t.loggedIn?d("i18n.relogin"):d("i18n.login")}),t.loggedIn&&(0,r.jsx)(p3,{variant:"danger",size:"small",onClick:m,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)(hc,{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 g(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)(hm,{providerId:t.id,enabled:t.loggedIn}),t.loggedIn&&(0,r.jsx)(hd,{providerId:t.id,controller:s,contextSettings:l})]})}let hD="http://127.0.0.1:8080";function hB(e){let{provider:t,onRefresh:n,enabledModels:s,contextSettings:l}=e,o=t.id===pt,[a,d]=(0,i.useState)(o&&!t.configured?hD:""),[c,u]=(0,i.useState)(""),[p,h]=(0,i.useState)(!1),[f,m]=(0,i.useState)(!1),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(!1),{t:y}=(0,t_.s)(),w=!!(o?a.trim():c.trim());async function k(){if(w&&!p){h(!0),x(null),b(!1);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:c.trim(),...o?{serverUrl:a.trim()}:{}})}),r=await e.json();!e.ok||r.error?x(r.error??`HTTP ${e.status}`):(u(""),o&&(d(""),s.refresh(),r.catalog?.completed||x(y(r.catalog?.reason==="offline"?"models.catalogOffline":"models.catalogUnreachable"))),b(!0),setTimeout(()=>b(!1),2e3),n())}catch(e){x(String(e))}finally{h(!1)}}}let j=(0,i.useCallback)(async()=>{m(!0),x(null);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"DELETE"}),r=await e.json();!e.ok||r.error?x(r.error??`HTTP ${e.status}`):n()}catch(e){x(String(e))}finally{m(!1)}},[t.id,n]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(pD,{children:[(0,r.jsx)(pB,{children:(0,r.jsx)(hI,{children:o?t.displayName:"API Key"})}),(0,r.jsxs)(pH,{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:t.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:t.configured?"#4ade80":"var(--text-dim)"},children:t.configured?y("i18n.configured"):y("i18n.notConfigured")})]}),t.configured&&(0,r.jsx)(p3,{variant:"danger",size:"small",onClick:j,disabled:f,children:f?y("i18n.removing"):y("i18n.disconnect")})]})]}),o&&(0,r.jsxs)("label",{style:{display:"grid",gap:6},children:[y("models.llamaRouterUrl"),(0,r.jsx)("input",{type:"url",style:hj,value:a,placeholder:hD,onChange:e=>d(e.target.value),spellCheck:!1})]}),!o&&!t.configured&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:1===t.modelCount?y("models.apiKeyEnableOne",{provider:t.displayName}):y("models.apiKeyEnable",{provider:t.displayName,count:t.modelCount})}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(hC,{value:c,onChange:u,onKeyDown:e=>{"Enter"===e.key&&k()},placeholder:o?y("models.optionalApiKey"):t.configured?y("models.replaceApiKey"):"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:k,disabled:p||!w||v,style:{padding:"6px 12px",background:v?"#16a34a":w?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:v?"#fff":w?"var(--accent-contrast)":"var(--text-dim)",cursor:p||!w||v?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[v&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),v?y("i18n.saved"):p?y("i18n.saving"):y("i18n.save")]})]}),g&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:g}),(0,r.jsx)(hm,{providerId:t.id,enabled:t.configured}),t.configured&&(0,r.jsx)(hd,{providerId:t.id,controller:s,contextSettings:l,emptyCatalogHint:o?y("models.llamaEmptyCatalog"):void 0})]})}function hH(e){let{oauthProviders:t,apiKeyProviders:n,onSelectOAuth:s,onSelectApiKey:l,onAddCustom:o,onClose:a}=e,[d,c]=(0,i.useState)(""),{t:u}=(0,t_.s)(),p=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>p.current?.focus(),30)},[]);let h=d.trim().toLowerCase(),f=t.filter(e=>!e.loggedIn&&pj(h,e.id,e.name)),m=n.filter(e=>!e.configured&&pj(h,e.id,e.displayName)),g=!h||"custom".includes(h)||"openai-compatible".includes(h)||"anthropic-compatible".includes(h),x=f.length+m.length+ +!!g,v={display:"flex",flexDirection:"row",alignItems:"center",gap:8,padding:"10px 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:7,boxSizing:"border-box",cursor:"pointer",minWidth:0,textAlign:"left",transition:"border-color 0.12s, background 0.12s",width:"100%"};return(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&a()},onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.preventDefault(),e.stopPropagation(),a())},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:[g&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:u("i18n.custom")}),g&&(0,r.jsxs)("button",{onClick:()=>{o(),a()},style:v,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:u("i18n.customEndpoint")})]}),(0,r.jsx)("span",{style:{width:26,height:26,borderRadius:5,background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),f.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!g,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:u("i18n.subscriptions")}),f.map(e=>(0,r.jsxs)("button",{onClick:()=>{s(e.id),a()},style:v,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(hp,{id:e.id,size:28})]},e.id)),m.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(f.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),m.map(e=>(0,r.jsxs)("button",{onClick:()=>{l(e.id),a()},style:v,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:e.id===pt?u("models.optionalApiKey"):u(1===e.modelCount?"models.modelCountOne":"models.modelCount",{count:e.modelCount})})]}),(0,r.jsx)(hp,{id:e.id,size:28})]},e.id))]})})]})})}function h_(e){let{onClose:t,embedded:n=!1,cwd:s=null}=e,{t:l}=(0,t_.s)(),{openDetail:o,closeDetail:a}=p$(),d=function(e){let[t,n]=(0,i.useState)(null),[r,s]=(0,i.useState)(!0),[l,o]=(0,i.useState)(null),[a,d]=(0,i.useState)(null),c=(0,i.useRef)(null),u=(0,i.useRef)(null),p=(0,i.useRef)(null),[h,f]=(0,i.useState)(0);(0,i.useEffect)(()=>{let t=new AbortController;s(!0);let r=e?`?cwd=${encodeURIComponent(e)}`:"";return fetch(`/api/models/enabled${r}`,{signal:t.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);n(t),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 m=(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?hi[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=m;let g=(0,i.useCallback)((e,t,n)=>{m(e,{op:"models",refs:t,enabled:n})},[m]),x=(0,i.useCallback)((e,t)=>{m(`provider:${e}`,{op:"provider",provider:e,enabled:t})},[m]),v=(0,i.useCallback)(()=>m("clear",{op:"clear"}),[m]),b=(0,i.useCallback)(()=>m("prune",{op:"prune"}),[m]),y=(0,i.useCallback)(()=>f(e=>e+1),[]),w=(0,i.useCallback)((e,n)=>{m("resync",{op:"resync",renames:e,modelRenames:n,fullyEnabled:(t?.providers??[]).filter(e=>e.models.length>0&&e.enabledCount===e.models.length).map(e=>e.id)})},[m,t]);return{view:t,loading:r,pending:l,failure:a,setModels:g,setProvider:x,clearScope:v,pruneStale:b,refresh:y,resync:w}}(s),[c,u]=(0,i.useState)({providers:{}}),[p,h]=(0,i.useState)(!0),[f,m]=(0,i.useState)(!1),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(null),[y,w]=(0,i.useState)(!1),[k,j]=(0,i.useState)(hv),[S,C]=(0,i.useState)([]),[N,E]=(0,i.useState)([]),[$,I]=(0,i.useState)({}),[M,T]=(0,i.useState)(()=>new Map),[R,A]=(0,i.useState)(!1),[L,z]=(0,i.useState)(!1),P=(0,i.useRef)(new Set),W=(0,i.useRef)(new Map),O=(0,i.useRef)(new Map),F=(0,i.useRef)(new WeakMap),D=(0,i.useRef)(0),B=(0,i.useRef)(null),[H,_]=(0,i.useState)(null),[U,K]=(0,i.useState)(null),q=(0,i.useCallback)(()=>fetch("/api/auth/providers").then(e=>e.json()).then(e=>(Array.isArray(e.oauthProviders)&&C(e.oauthProviders),Array.isArray(e.apiKeyProviders)&&E(e.apiKeyProviders),I(e.providerNames??{}),!0)).catch(()=>!1).finally(()=>A(!0)),[]);(0,i.useEffect)(()=>{fetch("/api/models-config").then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);return t}).then(e=>{let t=e.providers?e:{...e,providers:{}};u(t),P.current=new Set(Object.keys(t.providers??{})),O.current=pb(t),T(pC(t));let n=Object.keys(t.providers??{});j(e=>e&&("provider"===e.type?t.providers?.[e.name]:"model"!==e.type||t.providers?.[e.providerName]?.models?.[e.index])?e:n[0]?{type:"provider",name:n[0]}:null)}).catch(e=>b(e instanceof Error?e.message:String(e))).finally(()=>h(!1)),q()},[q]),(0,i.useEffect)(()=>{k&&pe("models",JSON.stringify(k))},[k]),(0,i.useEffect)(()=>{if(k?.type!=="provider")return;let e=c.providers?.[k.name];!(!e||!hb(e)||M.has(k.name))&&(S.some(e=>e.id===k.name)?j({type:"oauth",providerId:k.name}):N.some(e=>e.id===k.name)&&j({type:"apikey",providerId:k.name}))},[N,c.providers,S,M,k]);let V=e=>({overrides:c.providers?.[e]?.modelOverrides,disabled:p||f||null!==v,onChange:(t,n)=>{try{u(function(e,t,n,r){let i={...e.providers},s={...Object.hasOwn(i,t)?i[t]:{}},l={...s.modelOverrides},o=Object.hasOwn(l,n)?l[n]:void 0;if(void 0!==o&&!pn(o))throw Error("Model override must be an object");let a={...o};return void 0===r?delete a.contextWindow:a.contextWindow=r,Object.keys(a).length?Object.defineProperty(l,n,{value:a,enumerable:!0,configurable:!0}):delete l[n],Object.keys(l).length?s.modelOverrides=l:delete s.modelOverrides,Object.keys(s).length?Object.defineProperty(i,t,{value:s,enumerable:!0,configurable:!0}):delete i[t],{...e,providers:i}}(c,e,t,n)),w(!1),x(null)}catch(e){x(String(e))}}}),Z=(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"}}})),j({type:"provider",name:e})},[c.providers]),J=(0,i.useCallback)((e,t)=>{u(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),Y=(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:l}=t,o=pk(t,n);o===r?s.delete(o):null!==o&&s.set(o,r);let a=l.get(n);a&&(l.delete(n),l.set(r,a));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:P.current,renames:W.current,slots:O.current},t,n);return r?(u(r),K(null),j(e=>e?"provider"===e.type&&e.name===t?{type:"provider",name:n}:"model"===e.type&&e.providerName===t?{...e,providerName:n}:e:e),r):null},[]),G=(0,i.useCallback)((e,t)=>{Y(c,e,t)?x(null):x(l("models.providerIdTaken",{name:t}))},[Y,c,l]),X=(0,i.useCallback)(e=>{var t;let n,r,i=(null!==(n=pk(t={savedProviders:P.current,renames:W.current,slots:O.current},e))&&(t.renames.delete(n),t.savedProviders.delete(n)),t.slots.delete(e),r={...c.providers??{}},delete r[e],{...c,providers:r}),s=Object.keys(i.providers??{});K(t=>t?.provider===e?null:t),u(i),j(s.length>0?{type:"provider",name:s[0]}:null),a()},[c,a]),Q=(0,i.useCallback)(e=>{py(O.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 j({type:"model",providerName:e,index:n}),t})},[]),ee=(0,i.useCallback)((e,t)=>{u(n=>{let r=new Set((n.providers?.[e]?.models??[]).map(e=>e.id));py(O.current,e,t.filter(e=>!r.has(e.id)).length);let i=n.providers?.[e]??{},s=[...i.models??[]],l=new Set(s.map(e=>e.id));for(let e of t)l.has(e.id)||(l.add(e.id),s.push({...e}));return{...n,providers:{...n.providers??{},[e]:{...i,models:s}}}})},[]),et=(0,i.useCallback)((e,t,n)=>{u(r=>{let i=r.providers?.[e]??{},s=[...i.models??[]],l=F.current.get(s[t]);return l&&F.current.set(n,l),s[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:s}}}})},[]),en=(0,i.useCallback)(e=>{e&&(u(e.config),w(!1),x(null),j(t=>t?.type==="model"&&t.providerName===e.providerName?{...t,index:e.order.indexOf(t.index)}:t))},[]),er=(0,i.useCallback)((e,t,n)=>{f||v||en(function(e,t,n,r,i){let s=e.providers?.[n]?.models??[];if(r<0||r>=s.length||i<0||i>=s.length)return null;let l=[...s.keys()];return l.splice(r,1),l.splice(i,0,r),pw(e,t,n,l)}(c,O.current,e,t,n))},[en,c,v,f]),ei=(0,i.useCallback)(e=>{if(!f&&!v){var t;let n,r;en((t=O.current,n=c.providers?.[e]?.models??[],r=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),pw(c,t,e,[...n.keys()].sort((e,t)=>r.compare(pS(n[e]),pS(n[t]))))))}},[en,c,v,f]),es=(0,i.useCallback)((e,t)=>{O.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}}}}),j({type:"provider",name:e}),a()},[a]),el=(0,i.useCallback)(async()=>{if(v)return;m(!0),x(null),w(!1);let e=c,t=U?.name.trim();if(U&&t&&c.providers?.[U.provider]){let n=Y(c,U.provider,t);if(!n){x(l("models.providerIdTaken",{name:t})),m(!1);return}e=n}try{var n=e=function(e){let t=structuredClone(e);if(!pn(t.providers))return t;for(let[e,n]of Object.entries(t.providers))if(pn(n)&&pn(n.modelOverrides))for(let[t,r]of Object.entries(n.modelOverrides)){if(!pn(r)||!Object.hasOwn(r,"contextWindow"))continue;let n=pi(r.contextWindow);if(void 0===n)throw new pr(`${e}/${t}`);r.contextWindow=n}return t}(e);if(po(n.providers))for(let[e,t]of Object.entries(n.providers)){if(!po(t))continue;if(t.oauth&&!t.baseUrl)throw new pl(e,"baseUrl");let n=Array.isArray(t.models)&&t.models.some(pa),r=po(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 pl(e,"empty")}var r=e;if(pd(r.providers)){for(let[e,t]of Object.entries(r.providers))if(pd(t)&&Array.isArray(t.models))for(let n of t.models){if(!pd(n)||"string"==typeof n.id&&!n.id.trim())continue;let t=pc(n);if(void 0!==t&&void 0===pu(t))throw new ph(`${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{w(!0),setTimeout(()=>w(!1),2e3);let t=[...W.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 l=e[s];l&&t.id&&l!==t.id&&i.push({from:`${r(n)}/${l}`,to:`${n}/${t.id}`})})}return i}(e,O.current,W.current);P.current=new Set(Object.keys(e.providers??{})),O.current=pb(e),W.current.clear(),d.resync(t,n);let r=pC(e);q().then(e=>{e&&T(r)})}}catch(e){e instanceof pl?(x(l(hw[e.problem],{provider:e.provider})),j({type:"provider",name:e.provider})):e instanceof pr?x(l("models.contextInvalid",{model:e.model})):x(e instanceof ph?l("models.imageMaxBytesInvalid",{model:e.model}):String(e))}finally{m(!1)}},[Y,c,d,v,U,q,l]),eo=Object.entries(c.providers??{}).filter(e=>{let[t,n]=e;if(!hb(n)||M.has(t))return!0;let r=S.some(e=>e.id===t)||N.some(e=>e.id===t);return R&&!r}),ea=(e,t)=>{var n,r,i;return n=$[e]??d.view?.providers.find(t=>t.id===e)?.name,i=void 0!==(r=M.get(e))&&n?.trim()===r.trim()?void 0:n,t.name?.trim()||i?.trim()||e},ed=e=>{let t=function(e,t){if(!e||e.allEnabled)return null;let n=hn(e,t);return n?`${n.enabledCount}/${n.models.length}`:null}(d.view,e);return t?(0,r.jsx)("span",{className:"models-sidebar-badge",children:t}):null},ec=S.filter(e=>e.loggedIn),eu=N.filter(e=>e.configured),ep=(()=>{if(!k)return null;if("oauth"===k.type){let e=S.find(e=>e.id===k.providerId);return e?(0,r.jsx)(hF,{provider:e,onRefresh:q,enabledModels:d,contextSettings:V(e.id)},e.id):null}if("apikey"===k.type){let e=N.find(e=>e.id===k.providerId);return e?(0,r.jsx)(hB,{provider:e,onRefresh:q,enabledModels:d,contextSettings:V(e.id)},e.id):null}if("provider"===k.type){let e=c.providers?.[k.name];return e&&eo.some(e=>{let[t]=e;return t===k.name})?(0,r.jsx)(hM,{name:k.name,editingName:U?.provider===k.name?U.name:k.name,fallbackLabel:ea(k.name,{}),provider:e,onChange:e=>J(k.name,e),onEditingNameChange:e=>K(e===k.name?null:{provider:k.name,name:e}),onRename:e=>G(k.name,e),onDelete:()=>X(k.name),onAddModels:e=>ee(k.name,e),enabledModels:d},k.name):null}let e=c.providers?.[k.providerName],t=e?.models?.[k.index];return t?(0,r.jsx)(hO,{providerName:k.providerName,provider:e,model:t,onChange:e=>et(k.providerName,k.index,e),onDelete:()=>es(k.providerName,k.index)},`${k.providerName}-${k.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(pN,{embedded:n,title:l("common.models"),subtitle:"~/.pi/agent/models.json",closeLabel:l("i18n.close"),onClose:t,children:[(0,r.jsx)(hs,{controller:d}),(0,r.jsxs)(pT,{children:[(0,r.jsxs)(pR,{children:[(0,r.jsxs)(pA,{children:[ec.map(e=>{let t=k?.type==="oauth"&&k.providerId===e.id;return(0,r.jsxs)(pW,{active:t,onClick:()=>j({type:"oauth",providerId:e.id}),children:[(0,r.jsx)(hp,{id:e.id,size:16}),(0,r.jsx)(pO,{className:"is-grow",children:e.name}),ed(e.id)]},e.id)}),eu.map(e=>{let t=k?.type==="apikey"&&k.providerId===e.id;return(0,r.jsxs)(pW,{active:t,onClick:()=>j({type:"apikey",providerId:e.id}),children:[(0,r.jsx)(hp,{id:e.id,size:16}),(0,r.jsx)(pO,{className:"is-grow",children:e.displayName}),ed(e.id)]},e.id)}),(ec.length>0||eu.length>0)&&eo.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),p?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:l("i18n.loading")}):eo.map(e=>{let[t,n]=e,i=k?.type==="provider"&&k.name===t,s=n.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)(pW,{onClick:()=>j({type:"provider",name:t}),active:i,children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)(pO,{className:"is-grow",children:ea(t,n)}),ed(t)]}),s.map((e,n)=>{var i;let s,o,a=k?.type==="model"&&k.providerName===t&&k.index===n,d=F.current.get(e);d||(d=`model-${++D.current}`,F.current.set(e,d));let c=H?.providerName===t&&H.index===n?H:null;return(0,r.jsxs)(pW,{active:a,className:"models-sidebar-indented-item",style:c?{boxShadow:`inset 0 ${c.after?"-2px":"2px"} 0 var(--accent)`}:void 0,"aria-keyshortcuts":"Alt+ArrowUp Alt+ArrowDown",onClick:()=>j({type:"model",providerName:t,index:n}),onKeyDown:e=>{if(!e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let r="ArrowUp"===e.key?-1:"ArrowDown"===e.key?1:null;null!==r&&(e.preventDefault(),er(t,n,n+r))},...(i=e.id,s=e=>{var r;let i,s=B.current;if(s?.providerName!==t)return null;let l=e.currentTarget.getBoundingClientRect(),o=e.clientY>=l.top+l.height/2;return{from:s.index,to:(r=s.index,r<(i=o?n+1:n)?i-1:i),after:o}},{draggable:!f&&!v,onDragStart:e=>{B.current={providerName:t,index:n},e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",i)},onDragOver:e=>{let r=s(e);if(!r)return;e.preventDefault(),e.dataTransfer.dropEffect="move";let i=r.to===r.from?null:{providerName:t,index:n,after:r.after};_(e=>e?.providerName===i?.providerName&&e?.index===i?.index&&e?.after===i?.after?e:i)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||_(e=>e?.providerName===t&&e.index===n?null:e)},onDrop:e=>{let n=s(e);n&&(e.preventDefault(),er(t,n.from,n.to),o())},onDragEnd:o=()=>{B.current=null,_(null)}}),children:[(0,r.jsx)(pO,{className:"is-grow",style:{color:e.id?"var(--text-muted)":"var(--text-dim)"},children:pS(e)||l("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)(pW,{className:"models-sidebar-indented-item models-sidebar-add-item",onClick:e=>{e.stopPropagation(),Q(t)},children:(0,r.jsxs)(pO,{children:["+ ",l("i18n.model")]})}),(0,r.jsx)("button",{type:"button",className:"models-sidebar-sort-button","aria-label":l("models.sortByName"),title:l("models.sortByName"),disabled:f||null!==v||s.length<2,onClick:()=>ei(t),children:"A–Z"})]})]},t)})]}),(0,r.jsx)(p6,{onClick:e=>{e.preventDefault(),z(!0)},children:l("i18n.addProvider")})]}),(0,r.jsx)(p2,{children:(0,r.jsx)(pF,{className:"is-fill",children:p?null:ep??(0,r.jsx)(p1,{children:l("i18n.selectProviderModel")})})})]}),(0,r.jsxs)(p4,{status:v||g?(0,r.jsx)("span",{style:{color:"#f87171"},children:v?l("models.configUnreadable",{error:v}):g}):l("models.applyHelp"),children:[!n&&(0,r.jsx)(p3,{onClick:t,children:l("i18n.cancel")}),(0,r.jsxs)(p3,{variant:"primary",onClick:el,disabled:f||y||null!==v,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?l("i18n.saved"):f?l("i18n.saving"):l("i18n.save")})]})]})]}),L&&(0,r.jsx)(hH,{oauthProviders:S,apiKeyProviders:N,onSelectOAuth:e=>{j({type:"oauth",providerId:e}),o()},onSelectApiKey:e=>{j({type:"apikey",providerId:e}),o()},onAddCustom:()=>{Z(),o()},onClose:()=>z(!1)})]})}let hU=null;async function hK(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(hU)return hU;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 hU=null,!1}})();return hU=t,t.then(e=>{e||hU!==t||(hU=null)}),t}function hq(e,t,n,r){return e.filter(e=>n(e)!==t&&(t||!r?.(e)))}function hV(e){return e?JSON.stringify([e.requiresTrust,e.trusted,e.decision,e.decisionPath??null,e.inherited]):""}function hZ(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function hJ(e,t){return t("project"===e?"skills.scope.project":"global"===e?"skills.scope.global":"skills.scope.path")}function hY(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function hG(e,t){return e?e.slice(0,8):t}function hX(e){let{skill:t,cwd:n,onToggle:s,toggling:l,saveError:o,updateStatus:a,checkingUpdate:d,updating:c,updateError:u,onCheckUpdate:p,onUpdate:h}=e,{t:f}=(0,t_.s)(),m=hZ(t),g=!t.disableModelInvocation,[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(null),w=t.filePath.split(/[\\/]/).pop(),[k,j]=(0,i.useState)([]),S=k.at(-1)??w,C=(0,i.useRef)(null),N=(0,i.useRef)(null),[E,$]=(0,i.useState)(0),I=(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):j(e=>[...e,t.document])},[S]);return(0,i.useLayoutEffect)(()=>{let e=N.current,t=C.current;null!==e&&(null!==x||b)&&t&&(N.current=null,((e?t.querySelector(`[data-heading-anchor="${CSS.escape(e)}"]`):null)??t).scrollIntoView({block:"start"}))},[x,b,E]),(0,i.useEffect)(()=>{let e=new AbortController;return v(null),y(null),(async()=>{try{let r=new URLSearchParams({cwd:n,filePath:t.filePath});S!==w&&r.set("document",S);let i=await fetch(`/api/skills/content?${r}`,{signal:e.signal}),s=await i.json();if(!i.ok||s.error||"string"!=typeof s.content)throw Error(s.error??`HTTP ${i.status}`);v(function(e,t){let n=um(e).rest.trim();if(!t)return n;let r=n.match(/^#{1,6}[ \t]+(.*?)[ \t]*#*[ \t]*(?:\r?\n|$)/);return r&&r[1].trim().toLowerCase()===t.trim().toLowerCase()?n.slice(r[0].length).trim():n}(s.content,S===w?t.name:void 0))}catch(t){if(e.signal.aborted)return;y(t instanceof Error?t.message:String(t))}})(),()=>e.abort()},[n,t.filePath,t.name,S,w]),(0,r.jsxs)(pF,{children:[(0,r.jsxs)("div",{className:"skill-detail-heading",children:[(0,r.jsxs)(pD,{children:[(0,r.jsxs)(pB,{children:[(0,r.jsx)(pZ,{scope:m,children:hJ(m,f)}),(0,r.jsx)("span",{className:"config-detail-path",children:"project"===m?e2(t.filePath,n):e1(t.filePath)})]}),(0,r.jsx)(pH,{children:(0,r.jsx)(p5,{checked:g,loading:l,label:f(g?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),onChange:()=>s(t)})})]}),(0,r.jsxs)("div",{className:"skill-detail-status-row",children:[!g&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:f("i18n.hiddenButInvocable")}),o&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:o})]})]}),t.install?.skillsShUrl&&(0,r.jsx)(pK,{label:f("config.source"),children:(0,r.jsx)("a",{href:t.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:t.install.skillsShUrl,className:"skill-source-link",children:(0,r.jsxs)("span",{className:"skill-source-link-text",children:[t.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})}),t.install&&(0,r.jsxs)(pK,{label:f("i18n.version"),children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:hG(a?.currentVersion??t.install.versionHash,f("i18n.unknown"))}),t.install.canCheckForUpdates&&(0,r.jsx)(p3,{size:"small",onClick:p,disabled:d||c,children:f("i18n.check")}),a?.state==="update-available"&&(0,r.jsx)("span",{className:"skill-version-value is-update",children:hG(a.latestVersion,f("i18n.unknown"))}),(d||a&&"update-available"!==a.state)&&(0,r.jsx)("span",{className:`skill-update-status ${d?"is-checking":a?.state==="up-to-date"?"is-success":a?.state==="error"?"is-error":"is-muted"}`,children:d?f("i18n.checking"):a?.state==="up-to-date"?f("i18n.upToDate"):a?.state==="unsupported"?f("i18n.automaticChecksUnavailable"):a?.message||f("i18n.checkFailed")}),a?.state==="update-available"&&(0,r.jsx)(p3,{variant:"primary",size:"small",onClick:h,disabled:c||d,children:f(c?"i18n.updating":"i18n.update")})]}),u&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:u})]}),(0,r.jsx)(pK,{label:f("config.name"),children:(0,r.jsx)("span",{className:"skill-name-value",children:t.name})}),(0,r.jsx)(pK,{label:f("i18n.description"),children:(0,r.jsx)("span",{className:"skill-description",children:t.description})}),(0,r.jsxs)(pK,{label:f("skills.instructions"),ref:C,children:[k.length>0&&(0,r.jsx)(pD,{children:(0,r.jsxs)(pB,{children:[(0,r.jsx)(p3,{size:"small",onClick:()=>{N.current="",j(e=>e.slice(0,-1))},children:f("skills.documentBack")}),(0,r.jsx)("span",{className:"config-detail-path",title:S,children:S})]})}),b?(0,r.jsx)("span",{role:"alert",className:"skill-instructions-status is-error",children:b}):null===x?(0,r.jsx)("span",{role:"status",className:"skill-instructions-status",children:f("i18n.loading")}):x?(0,r.jsx)(lB,{className:"skill-instructions",cwd:[t.baseDir,...S.split("/").slice(0,-1)].join("/"),onNavigateLink:I,children:x}):(0,r.jsx)("span",{className:"skill-instructions-status",children:f("skills.noInstructions")})]})]})}function hQ(e){let{cwd:t,installedPackages:n,projectResourcesLoaded:s,onInstalled:l}=e,{t:o}=(0,t_.s)(),[a,d]=(0,i.useState)(""),[c,u]=(0,i.useState)([]),[p,h]=(0,i.useState)(!1),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(null),[y,w]=(0,i.useState)(new Set),[k,j]=(0,i.useState)("global"),S=(0,i.useRef)(null);(0,i.useEffect)(()=>{S.current?.focus()},[]);let C=(0,i.useCallback)(async e=>{if(e.trim()){h(!0),m(null),u([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),n=await t.json();if(n.error)return void m(n.error);u(n.results??[]),0===(n.results??[]).length&&m(o("i18n.noSkills"))}catch(e){m(String(e))}finally{h(!1)}}},[o]),N=(0,i.useCallback)(async e=>{x(e),b(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:e,scope:k,cwd:t})}),r=await n.json();if(!n.ok||r.error)return void b(r.error??`HTTP ${n.status}`);w(t=>new Set(t).add(`${k}:${e}`)),l()}catch(e){b(String(e))}finally{x(null)}},[l,k,t]),E="global"===k?"~/.pi/agent/skills/":`${e1(t)}/.pi/skills/`;return(0,r.jsxs)(pF,{className:"is-full-height",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)(pG,{title:o("i18n.addSkill"),catalogs:[{href:"https://skills.sh",label:"skills.sh"}],target:(0,r.jsx)(pY,{value:k,label:o("config.saveTo"),options:[{value:"global",label:hJ("global",o)},{value:"project",label:hJ("project",o),disabled:!s}],path:E,disabledReason:o("trust.projectScopeUnavailable"),onChange:j})}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:S,value:a,onChange:e=>d(e.target.value),onKeyDown:e=>{!e.nativeEvent.isComposing&&229!==e.keyCode&&("Enter"!==e.key||p||C(a))},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)(p3,{variant:"primary",onClick:()=>C(a),disabled:p||!a.trim(),children:p?o("i18n.searching"):o("i18n.search")})]}),f&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:f}),v&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:v})]}),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=g===e.package,s=e.package.indexOf("@"),l=s>-1?e.package.slice(0,s):e.package,a=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:a??l}),(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:l}),(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)(p3,{size:"small",onClick:()=>!t&&!i&&N(e.package),disabled:t||i||null!==g,style:{flexShrink:0,background:t?"rgba(34,197,94,0.1)":"none",color:t?"#16a34a":i?"var(--accent)":"var(--text-muted)"},children:t?`✓ ${o("i18n.installed")}`:i?o("i18n.installing"):o("i18n.install")})]},e.package)})})]})}function h0(e){let{cwd:t,onClose:n,embedded:s=!1,trust:l}=e,{t:o}=(0,t_.s)(),[a,d]=(0,i.useState)([]),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(()=>u7("skills",t)),[g,x]=(0,i.useState)(new Set),[v,b]=(0,i.useState)(null),[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(null),[S,C]=(0,i.useState)(!1),[N,E]=(0,i.useState)({}),[$,I]=(0,i.useState)(new Set),[M,T]=(0,i.useState)(!1),[R,A]=(0,i.useState)(null),[L,z]=(0,i.useState)(null),[P,W]=(0,i.useState)(!0),O=(0,i.useCallback)(async()=>{u(!0),h(null);try{let e=await fetch(`/api/skills?cwd=${encodeURIComponent(t)}`),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);let r=n.skills??[];return d(r),W(n.projectResourcesLoaded??!0),m(e=>{if(e&&r.some(t=>t.filePath===e))return e;let t=r.find(e=>!e.disableModelInvocation)??r[0];return t?.filePath??null}),r}catch(e){return h(String(e)),[]}finally{u(!1)}},[t]);(0,i.useEffect)(()=>{E({}),z(null),O()},[t]);let F=hV(l),D=(0,i.useRef)(F);(0,i.useEffect)(()=>{D.current!==F&&(D.current=F,O())},[F,O]),(0,i.useEffect)(()=>{f&&pe("skills",f,t)},[t,f]);let B=(0,i.useCallback)(async e=>{let n=(e?[e]:a.filter(e=>!!e.install)).map(hY).filter(e=>!!e);if(0!==n.length){z(null),I(e=>new Set([...e,...n])),e||T(!0);try{let n=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,package:e?.install?.package,scope:e?.install?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);E(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){z(e instanceof Error?e.message:String(e))}finally{I(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),e||T(!1)}}},[t,a]),H=(0,i.useCallback)(async e=>{if(!e.install)return;let n=hY(e);A(n),z(null);try{let r=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,package:e.install.package,scope:e.install.scope})}),i=await r.json();if(!r.ok||i.error||!i.success)throw Error(i.error??`HTTP ${r.status}`);await O();let s=i.skill?.install?.versionHash;E(t=>({...t,[n]:{package:e.install.package,scope:e.install.scope,state:"up-to-date",currentVersion:s,latestVersion:s}}))}catch(e){z(e instanceof Error?e.message:String(e))}finally{A(null)}},[t,O]),_=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;x(t=>new Set(t).add(e.filePath)),b(null),j(null);try{let n=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),r=await n.json();if(!n.ok||r.error)return void b(r.error??`HTTP ${n.status}`);d(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n))}catch(e){b(String(e))}finally{x(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),U=(0,i.useCallback)(async(e,t,n)=>{let r=hq(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])),w(e),b(null),j(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 l=n.results;d(e=>{let t;return t=new Set(l.filter(e=>!e.error).map(e=>e.filePath)),e.map(e=>t.has(e.filePath)?{...e,disableModelInvocation:s}:e)});let a=l.filter(e=>e.error);if(a.length>0){let t=new Map(r.map(e=>[e.filePath,e.name]));j({group:e,error:[o("skills.bulkFailed",{count:a.length,total:l.length}),...a.map(e=>`${t.get(e.filePath)??e.filePath}: ${e.error}`)].join("\n")})}}catch(t){j({group:e,error:t instanceof Error?t.message:String(t)})}finally{w(null),x(e=>{let t=new Set(e);for(let e of i)t.delete(e);return t})}},[o]),K=a.find(e=>e.filePath===f)??null,q=c||g.size>0||null!==R;return(0,r.jsxs)(pN,{embedded:s,title:o("common.skills"),subtitle:e1(t),closeLabel:o("i18n.close"),onClose:n,children:[!P&&(0,r.jsx)(p0,{message:o("trust.skillsNotLoaded")}),(0,r.jsxs)(pT,{children:[(0,r.jsxs)(pR,{children:[(0,r.jsx)(pA,{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===a.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"===hZ(e)&&!!e.install?.skillsShUrl},{label:t.project,matches:e=>"project"===hZ(e)&&!e.install?.skillsShUrl},{label:`${t.global} / skills.sh`,matches:e=>"global"===hZ(e)&&!!e.install?.skillsShUrl},{label:t.global,matches:e=>"global"===hZ(e)&&!e.install?.skillsShUrl},{label:t.path,matches:e=>"path"===hZ(e)}]){let t=a.filter(r);t.length>0&&e.push({label:n,skills:t})}let n=e=>{let t,n,i=!S&&f===e.filePath,s=e.disableModelInvocation;return(0,r.jsxs)(pW,{active:i,onClick:()=>{m(e.filePath),C(!1)},children:[(0,r.jsx)(p9,{active:!s}),(0,r.jsx)(pO,{className:`is-grow${s?" is-muted":""}`,children:e.name}),(n=(t=hY(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,l=s===i.length;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(pL,{aside:(0,r.jsx)(pz,{enabled:s,total:i.length,disabled:q,loading:y===t,label:o(l?"skills.groupSwitchOn":"skills.groupSwitchOff",{group:t}),onChange:e=>void U(t,i,e)}),children:t}),k?.group===t&&(0,r.jsx)(pP,{error:k.error}),[...i.filter(e=>!e.disableModelInvocation),...i.filter(e=>e.disableModelInvocation)].map(n)]},t)})})()}),(0,r.jsx)(p6,{onClick:()=>C(!0),active:S,children:o("i18n.addSkill")})]}),(0,r.jsx)(p2,{children:(0,r.jsx)(pF,{className:"is-fill",children:S?(0,r.jsx)(hQ,{cwd:t,projectResourcesLoaded:P,installedPackages:{global:new Set(a.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(a.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{O()}}):c?null:K?(0,r.jsx)(hX,{skill:K,cwd:t,onToggle:_,toggling:g.has(K.filePath),saveError:v,updateStatus:hY(K)?N[hY(K)]:void 0,checkingUpdate:!!hY(K)&&$.has(hY(K)),updating:R===hY(K),updateError:L,onCheckUpdate:()=>void B(K),onUpdate:()=>void H(K)},K.filePath):(0,r.jsx)(p1,{children:o("i18n.selectSkill")})})})]}),(0,r.jsxs)(p4,{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)(p3,{onClick:n,children:o("i18n.close")}),a.some(e=>!!e.install)&&(0,r.jsx)(p3,{variant:"secondary",onClick:()=>void B(),disabled:M||null!==R,children:M?o("i18n.checking"):o("i18n.checkUpdates")})]})]})}let h1={builtin:0,global:1,workspace:2,project:3},h2=["read","bash","edit","write","grep","find","ls"],h4=["","off","minimal","low","medium","high","xhigh","max"],h8={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},h3={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"},h5={background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"default"};function h6(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 h9(e){return`${e.scope}:${e.name}`}function h7(e){return"global"===e||"project"===e}function fe(e){return h7(e)||"builtin"===e}function ft(e){let{label:t,children:n}=e;return(0,r.jsx)(pK,{label:t,children:n})}function fn(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 fr(e){let{cwd:t,sessionId:n=null,onClose:s,onReloaded:l,embedded:o=!1,trust:a}=e,d=tQ(),{t:c}=(0,t_.s)(),[u,p]=(0,i.useState)([]),[h,f]=(0,i.useState)([]),[m,g]=(0,i.useState)(!0),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(()=>u7("agents",t)),[w,k]=(0,i.useState)(h8),[j,S]=(0,i.useState)("view"),[C,N]=(0,i.useState)("global"),[E,$]=(0,i.useState)(!0),[I,M]=(0,i.useState)(!1),[T,R]=(0,i.useState)(!1),[A,L]=(0,i.useState)(!1),[z,P]=(0,i.useState)(null),[W,O]=(0,i.useState)(!1),[F,D]=(0,i.useState)(10),[B,H]=(0,i.useState)(!0),[_,U]=(0,i.useState)(!1),[K,q]=(0,i.useState)(null),[V,Z]=(0,i.useState)(!1),[J,Y]=(0,i.useState)(!1),G=(0,i.useMemo)(()=>u.find(e=>h9(e)===b)??null,[u,b]),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),P(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??u7("agents",t),l=i.find(e=>h9(e)===s)??i.find(e=>"project"===e.scope)??i.find(e=>"global"===e.scope)??i[0]??null;y(l?h9(l):null),l&&(k(h6(l)),S(h7(l.scope)?"edit":"view"),h7(l.scope)&&N(l.scope))}catch(e){P(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),q(null),(async()=>{try{let t=await fetch("/api/subagents/settings",{cache:"no-store",signal:e.signal}),n=await t.json();if(!t.ok||n.error||"boolean"!=typeof n.enabled)throw Error(n.error??`HTTP ${t.status}`);O(n.enabled),"number"==typeof n.maxConcurrent&&D(n.maxConcurrent)}catch(t){if(e.signal.aborted)return;q(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||H(!1)}})(),()=>e.abort()},[]),(0,i.useEffect)(()=>{b&&pe("agents",b,t)},[t,b]);let ee=hV(a);(0,i.useEffect)(()=>{let e=new AbortController;return g(!0),v(null),(async()=>{try{let n=await fetch(`/api/models?cwd=${encodeURIComponent(t)}`,{signal:e.signal}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);f(r.modelList??[]),v(r.modelError??null)}catch(t){if(e.signal.aborted)return;v(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||g(!1)}})(),()=>e.abort()},[t,ee]);let et=async()=>{M(!0),P(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:w})}),n=await e.json();if(!e.ok||n.error||!n.profile)throw Error(n.error??`HTTP ${e.status}`);await Q(h9(n.profile)),R(!0),setTimeout(()=>R(!1),2e3)}catch(e){P(e instanceof Error?e.message:String(e))}finally{M(!1)}},en=async()=>{if(G&&h7(G.scope)&&window.confirm(c("agents.deleteConfirm",{name:G.displayName}))){M(!0),P(null);try{let e=await fetch("/api/subagents/profiles",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:G.scope,name:G.name})}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);await Q()}catch(e){P(e instanceof Error?e.message:String(e))}finally{M(!1)}}},er="view"!==j,ei="create"===j,es=!er||I||A,el=ei?C:G?.scope,eo=ei?"global"===C?`~/.pi/agent/agents/${w.name||"..."}.md`:`./.pi/agents/${w.name||"..."}.md`:G?(G.filePath?"project"===G.scope||"workspace"===G.scope?e2(G.filePath,t):e1(G.filePath):null)??c("agents.builtinPath"):"",ea=ei?eo:G?.filePath??eo,ed=e=>h.some(t=>`${t.provider}/${t.id}`===e),ec=w.model&&function(e,t){if(t(e))return e;let n=e.lastIndexOf(":"),r=e.slice(n+1);return n>0&&r&&h4.includes(r)?e.slice(0,n):e}(w.model,ed),eu=!ec||ed(ec),ep=(()=>{if(!ec)return null;let e=ec.indexOf("/");return e<0?{provider:"",modelId:ec}:{provider:ec.slice(0,e),modelId:ec.slice(e+1)}})(),eh=es?{...h3,...h5}:h3,ef=ei?es:!G||!fe(G.scope)||I||A,em=(e,t)=>{k(n=>({...n,[e]:t}))},eg=0===w.tools.length&&!w.loadSkills&&!w.loadExtensions,ex=async e=>{if(ei)return void em("enabled",e);if(G&&fe(G.scope)){L(!0),P(null);try{let n=await fetch("/api/subagents/profiles",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:G.scope,name:G.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=>h9(e)===h9(i)?i:e)),k(e=>({...e,enabled:i.enabled}))}catch(e){P(e instanceof Error?e.message:String(e))}finally{L(!1)}}},ev=async e=>{U(!0),q(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),r=await t.json();if(!t.ok||r.error||"boolean"!=typeof r.enabled)throw Error(r.error??`HTTP ${t.status}`);O(r.enabled),Z(!!n)}catch(e){q(e instanceof Error?e.message:String(e))}finally{U(!1)}},eb=async e=>{D(e),q(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxConcurrent:e})}),n=await t.json();if(!t.ok||n.error||"number"!=typeof n.maxConcurrent)throw Error(n.error??`HTTP ${t.status}`);D(n.maxConcurrent)}catch(e){q(e instanceof Error?e.message:String(e))}},ey=async()=>{if(n){Y(!0),q(null);try{await ce(n,{type:"reload"}),Z(!1),l?.()}catch(e){q(e instanceof Error?e.message:String(e))}finally{Y(!1)}}};return(0,r.jsxs)(pN,{embedded:o,title:c("common.agents"),subtitle:e1(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")}),V&&(0,r.jsx)("span",{role:"status",className:"agents-feature-reload-notice",children:c("agents.reloadRequired")})]}),(0,r.jsxs)("div",{className:"agents-feature-actions",children:[V&&n&&(0,r.jsx)(p3,{size:"small",onClick:()=>void ey(),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 eb(F)})]}),(0,r.jsx)(p5,{checked:W,disabled:B||J,loading:_,label:c("agents.builtInTitle"),onChange:e=>void ev(e)})]})]}),(0,r.jsxs)(pT,{children:[(0,r.jsxs)(pR,{children:[(0,r.jsx)(pA,{children:E?(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)(pL,{children:c(`agents.scope.${e}`)}),t.map(e=>{let t,n,i=(t=e.name.toLowerCase(),n=h1[e.scope],u.some(e=>e.name.toLowerCase()===t&&h1[e.scope]>n));return(0,r.jsxs)(pW,{active:b===h9(e)&&!ei,onClick:()=>{y(h9(e)),k(h6(e)),S(h7(e.scope)?"edit":"view"),h7(e.scope)&&N(e.scope),P(null)},children:[(0,r.jsx)(p9,{active:e.enabled}),(0,r.jsx)(pO,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.displayName}),i&&(0,r.jsx)("span",{className:"agents-overridden-label",children:c("agents.overridden")})]},h9(e))})]},e)})}),(0,r.jsx)(p6,{active:ei,onClick:()=>{let e="custom-agent",t=2;for(;u.some(t=>t.name===e);)e=`custom-agent-${t++}`;y(null),k({...h8,name:e,displayName:e}),S("create"),N("global"),P(null)},children:c("agents.new")})]}),(0,r.jsx)(p2,{children:(0,r.jsx)(pF,{className:"is-fill",children:G||ei?(0,r.jsxs)(pF,{children:[(0,r.jsxs)(pD,{children:[(0,r.jsx)(pB,{children:ei?(0,r.jsx)(pY,{value:C,label:c("config.saveTo"),options:["global","project"].map(e=>({value:e,label:c(`agents.scope.${e}`),disabled:I})),path:eo,onChange:N}):(0,r.jsxs)(r.Fragment,{children:[el&&(0,r.jsx)(pZ,{scope:el,children:c(`agents.scope.${el}`)}),(0,r.jsx)("span",{title:ea,className:"config-detail-path",children:eo})]})}),(0,r.jsxs)(pH,{children:[G&&("view"===j||"edit"===j)&&(0,r.jsx)(p3,{size:"small",onClick:()=>{if(!G)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}(G.name,u);y(null),k({...h6(G),name:e,displayName:c("agents.copyName",{name:G.displayName})}),S("create"),N(h7(G.scope)?G.scope:"global"),P(null)},disabled:I||A,children:c("agents.duplicate")}),G&&h7(G.scope)&&"edit"===j&&(0,r.jsx)(p3,{variant:"danger",size:"small",onClick:()=>void en(),disabled:I||A,children:c("agents.delete")}),(0,r.jsx)(p5,{checked:w.enabled,disabled:ef,label:w.enabled?c("agents.disable"):c("agents.enable"),onChange:e=>void ex(e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:d?"1fr":"minmax(0, 1fr) minmax(0, 1fr)",gap:12},children:[(0,r.jsx)(ft,{label:c("agents.name"),children:ei?(0,r.jsx)("input",{"aria-label":c("agents.name"),value:w.name,disabled:es,onChange:e=>em("name",e.target.value),style:h3}):(0,r.jsx)("code",{style:{minHeight:34,display:"flex",alignItems:"center",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:w.name})}),(0,r.jsx)(ft,{label:c("agents.displayName"),children:(0,r.jsx)("input",{"aria-label":c("agents.displayName"),value:w.displayName,disabled:es,onChange:e=>em("displayName",e.target.value),style:eh})})]}),(0,r.jsx)(ft,{label:c("agents.description"),children:(0,r.jsx)("input",{"aria-label":c("agents.description"),value:w.description,disabled:es,onChange:e=>em("description",e.target.value),style:eh})}),(0,r.jsx)(ft,{label:c("agents.prompt"),children:(0,r.jsx)("textarea",{className:"agents-system-prompt","aria-label":c("agents.prompt"),value:w.systemPrompt,disabled:es,onChange:e=>em("systemPrompt",e.target.value),style:{...eh,height:195,minHeight:195,maxHeight:"60vh",padding:9,overflow:"auto",resize:es?"none":"vertical",lineHeight:1.5}})}),(0,r.jsx)(ft,{label:c("agents.tools"),children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 16px"},children:[...h2,...w.tools.filter(e=>"powershell"===e)].map(e=>(0,r.jsx)(fn,{label:e,disabled:es,checked:w.tools.includes(e),onChange:t=>em("tools",t?[...w.tools,e]:w.tools.filter(t=>t!==e))},e))})}),(0,r.jsxs)(ft,{label:c("agents.resources"),children:[(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 20px"},children:[(0,r.jsx)(fn,{label:c("agents.loadSkills"),disabled:es,checked:w.loadSkills,onChange:e=>em("loadSkills",e)}),(0,r.jsx)(fn,{label:c("agents.loadExtensions"),disabled:es,checked:w.loadExtensions,onChange:e=>em("loadExtensions",e)}),(0,r.jsx)(fn,{label:c("agents.mcp"),disabled:es||eg&&"on"!==w.mcp,checked:"on"===w.mcp,onChange:e=>em("mcp",e?"on":"off")})]}),w.loadSkills&&void 0!==w.skills&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:w.skills.length>0?c("agents.skillsOnly",{skills:w.skills.join(", ")}):c("agents.skillsNone")}),w.loadExtensions&&void 0!==w.extensions&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:w.extensions.length>0?c("agents.extensionsOnly",{extensions:w.extensions.join(", ")}):c("agents.extensionsNone")}),!es&&eg?(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:c("agents.mcpChatOnly")}):"on"===w.mcp&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:c("agents.mcpHint")})]}),(0,r.jsx)(ft,{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:w.codemode??"off",disabled:es,onChange:e=>em("codemode",e.target.value),style:{...eh,width:"auto",minWidth:180,alignSelf:"flex-start"},children:[(0,r.jsx)("option",{value:"inherit",children: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)(ft,{label:c("agents.model"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(a9,{options:X,value:ep,onChange:(e,t)=>em("model",`${e}/${t}`),onClear:()=>em("model",void 0),emptyLabel:m?c("agents.modelsLoading"):c("agents.inherit"),selectedLabel:w.model&&!eu?c("agents.modelUnavailable",{model:w.model}):w.model!==ec?w.model:void 0,disabled:es||m||0===h.length&&!w.model,ariaLabel:c("agents.model"),variant:"field",placement:"auto"}),x&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:10},children:x})]})}),(0,r.jsx)(ft,{label:c("agents.thinking"),children:(0,r.jsx)("select",{"aria-label":c("agents.thinking"),value:w.thinking??"",disabled:es,onChange:e=>em("thinking",e.target.value||void 0),style:eh,children:h4.map(e=>(0,r.jsx)("option",{value:e,children:e||c("agents.inherit")},e||"default"))})}),(0,r.jsx)(ft,{label:c("agents.maxTurns"),children:(0,r.jsx)("input",{"aria-label":c("agents.maxTurns"),type:"number",min:1,value:w.maxTurns??"",disabled:es,onChange:e=>em("maxTurns",e.target.value?Number(e.target.value):void 0),style:eh})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"10px 20px"},children:[(0,r.jsx)(fn,{label:c("agents.inheritContext"),disabled:es,checked:w.inheritContext,onChange:e=>em("inheritContext",e)}),(0,r.jsx)(fn,{label:c("agents.background"),disabled:es,checked:w.runInBackground,onChange:e=>em("runInBackground",e)})]})]}):(0,r.jsx)(p1,{children:c("agents.empty")})})})]}),(0,r.jsx)(p4,{status:(K||z)&&(0,r.jsx)("span",{role:"alert",style:{color:"#ef4444"},children:K||z}),children:er&&(0,r.jsxs)(p3,{variant:"primary",onClick:()=>void et(),disabled:I||T||A||!w.name.trim(),className:T?"is-success":void 0,children:[T&&(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:T?c("i18n.saved"):I?c("agents.saving"):c("agents.save")})]})})]})}let fi=["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"];function fs(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function fl(e){return`${e.scope}\0${e.source}`}function fo(e){return`extension\0${e.path}`}function fa(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function fd(e,t){return t(`plugins.status.${e}`)}function fc(e){return`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`}function fu(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function fp(e){let{pkg:t}=e,{t:n}=(0,t_.s)(),i=[["extension",n("i18n.extensions")],["skill",n("i18n.skills")],["prompt",n("i18n.prompts")],["theme",n("i18n.themes")]].map(e=>{let[n,r]=e;return{kind:n,label:r,resources:t.resources.filter(e=>e.kind===n)}}).filter(e=>e.resources.length>0);return 0===i.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:n("i18n.noResolvedResources")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:i.map((e,t)=>(0,r.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function fh(e){let{cwd:t,source:n,scope:i,projectResourcesLoaded:s,busy:l,actionError:o,onSourceChange:a,onScopeChange:d,onInstall:c}=e,{t:u}=(0,t_.s)();return(0,r.jsx)(pX,{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)(pY,{value:i,label:u("config.saveTo"),options:[{value:"global",label:fa("global",u)},{value:"project",label:fa("project",u),disabled:!s}],path:"project"===i?`${e1(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:!l&&!!n.trim(),normalizeValue:fs,onValueChange:a,onSubmit:c,examplesLabel:u("config.examples"),examples:fi,error:o,children:(0,r.jsx)(p3,{variant:"primary",onClick:c,disabled:l||!n.trim(),className:"is-pushed-right",children:u(l?"i18n.installing":"i18n.install")})})}function ff(e){let t,n,{pkg:s,cwd:l,busyKey:o,actionError:a,actionMessage:d,sessionId:c,updateStatus:u,checkingUpdate:p,updateError:h,onAction:f,onCheckUpdate:m,onReloadSession:g}=e,{t:x}=(0,t_.s)(),v=fl(s),b=(o?.endsWith(v)||o?.startsWith("bulk:"))??!1,y="reload"===o,w=!s.disabled,k=s.canCheckForUpdates,j=u?.state==="update-available",S=s.description?.trim(),C=(0,i.useId)();return(0,r.jsxs)(pF,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(pD,{className:"is-top-aligned",children:[(0,r.jsxs)(pB,{children:[(0,r.jsx)(pZ,{scope:s.scope,children:fa(s.scope,x)}),!s.disabled&&s.filtered&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:x("i18n.filtered")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s.source})]}),(0,r.jsxs)(pH,{children:[(0,r.jsx)(p3,{size:"small",variant:j?"primary":void 0,onClick:j||!k?()=>f("update",s):m,disabled:b||y||p,title:j?x("i18n.updateAvailable"):void 0,children:x(o===`update:${v}`?"i18n.updating":p?"i18n.checking":j||!k?"i18n.update":"i18n.check")}),(0,r.jsx)(p3,{size:"small",onClick:g,disabled:!c||y||b,"aria-describedby":c?void 0:C,children:x(y?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)(p3,{variant:"danger",size:"small",onClick:()=>f("remove",s),disabled:b||y,children:x(o===`remove:${v}`?"i18n.removing":"i18n.remove")}),(0,r.jsx)(p5,{checked:w,loading:b||y,onChange:()=>f(s.disabled?"enable":"disable",s),label:x(s.disabled?"i18n.enablePackage":"i18n.disablePackage")})]})]}),!c&&(0,r.jsx)("div",{id:C,className:"config-detail-heading-note",children:x("i18n.openSessionToReload")})]}),(0,r.jsxs)(pq,{children:[S&&(0,r.jsx)(pV,{label:x("i18n.description"),children:S}),(0,r.jsx)(pV,{label:x("i18n.status"),tone:"plain",style:{color:fu(s.status),textTransform:"capitalize"},children:fd(s.status,x)}),(0,r.jsxs)(pV,{label:x("i18n.version"),tone:"plain",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:(t=[],s.version&&t.push(x("i18n.installedVersion",{version:s.version})),s.configuredVersion&&t.push(x("i18n.configuredVersion",{version:s.configuredVersion})),t.length?t.join(" \xb7 "):x("i18n.unknown"))}),j&&(0,r.jsx)("span",{className:"skill-version-value is-update",title:u.displayName,children:x("i18n.updateAvailable")}),k&&(p||u&&!j)&&(0,r.jsx)("span",{className:`skill-update-status ${p?"is-checking":u?.state==="up-to-date"?"is-success":u?.state==="error"?"is-error":"is-muted"}`,children:p?x("i18n.checking"):u?.state==="up-to-date"?x("i18n.upToDate"):u?.state==="unsupported"?x("i18n.automaticChecksUnavailable"):u?.message||x("i18n.checkFailed")})]}),h&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:h})]}),!(s.packageName&&s.source.endsWith(s.packageName))&&(0,r.jsx)(pV,{label:x("i18n.package"),mono:!0,children:s.packageName??x("i18n.unknown")}),!s.disabled&&(0,r.jsx)(pV,{label:x("i18n.resources"),children:(n=[s.counts.extensions?x("i18n.resourceCount",{count:s.counts.extensions,label:x("i18n.extensionShort")}):"",s.counts.skills?x("i18n.resourceCount",{count:s.counts.skills,label:x("i18n.skillShort")}):"",s.counts.prompts?x("i18n.resourceCount",{count:s.counts.prompts,label:x("i18n.promptShort")}):"",s.counts.themes?x("i18n.resourceCount",{count:s.counts.themes,label:x("i18n.themeShort")}):""].filter(Boolean)).length?n.join(" \xb7 "):x("i18n.noResources")}),(0,r.jsx)(pV,{label:x("i18n.installedPath"),tone:s.installedPath?"muted":"error",mono:!0,children:s.installedPath?e1(s.installedPath):x("i18n.notFound")}),(0,r.jsx)(pV,{label:x("i18n.cwd"),tone:"dim",mono:!0,children:e1(l)})]}),!s.disabled&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)(pU,{children:x("i18n.resolvedResources")}),(0,r.jsx)(fp,{pkg:s})]}),d&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:d}),a&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:a})]})}function fm(e){let{extension:t}=e,{t:n}=(0,t_.s)(),i=t.enabled?"loaded":"disabled";return(0,r.jsxs)(pF,{children:[(0,r.jsx)(pD,{children:(0,r.jsxs)(pB,{children:[(0,r.jsx)(pZ,{scope:t.scope,children:fa(t.scope,n)}),(0,r.jsx)(p_,{children:t.name})]})}),(0,r.jsxs)(pq,{children:[(0,r.jsx)(pV,{label:n("i18n.status"),tone:"plain",style:{color:t.enabled?"var(--accent)":"var(--text-dim)"},children:fd(i,n)}),(0,r.jsx)(pV,{label:n("i18n.installedPath"),mono:!0,children:e1(t.path)})]})]})}function fg(e){var t;let{cwd:n,sessionId:s,onClose:l,onReloaded:o,embedded:a=!1,trust:d}=e,{t:c}=(0,t_.s)(),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!0),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(()=>u7("plugins",n)),[b,y]=(0,i.useState)(!1),[w,k]=(0,i.useState)(""),[j,S]=(0,i.useState)("global"),[C,N]=(0,i.useState)(null),[E,$]=(0,i.useState)(null),[I,M]=(0,i.useState)(null),[T,R]=(0,i.useState)(null),[A,L]=(0,i.useState)({}),[z,P]=(0,i.useState)(new Set),[W,O]=(0,i.useState)(!1),[F,D]=(0,i.useState)(null),[B,H]=(0,i.useState)(!1),_=(0,i.useMemo)(()=>u?.packages??[],[u?.packages]),U=(0,i.useMemo)(()=>u?.standaloneExtensions??[],[u?.standaloneExtensions]),K=_.find(e=>fl(e)===x)??null,q=U.find(e=>fo(e)===x)??null,V=u?.projectResourcesLoaded??!0,Z=(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()=>{f(!0),g(null),R(null);try{let e=await fetch(`/api/plugins?cwd=${encodeURIComponent(n)}`),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);p(t),y(e=>0===t.packages.length&&0===t.standaloneExtensions.length||e),v(e=>e&&(t.packages.some(t=>fl(t)===e)||t.standaloneExtensions.some(t=>fo(t)===e))?e:t.packages[0]?fl(t.packages[0]):t.standaloneExtensions[0]?fo(t.standaloneExtensions[0]):null)}catch(e){g(e instanceof Error?e.message:String(e))}finally{f(!1)}},[n]);(0,i.useEffect)(()=>{L({}),D(null),J()},[n]);let Y=hV(d),G=(0,i.useRef)(Y);(0,i.useEffect)(()=>{G.current!==Y&&(G.current=Y,J())},[Y,J]),(0,i.useEffect)(()=>{x&&pe("plugins",x,n)},[n,x]);let X=(0,i.useCallback)(async e=>{let t=(e?[e]:_.filter(e=>e.canCheckForUpdates)).map(fl);if(0!==t.length){D(null),P(e=>new Set([...e,...t])),e||O(!0);try{let t=await fetch("/api/plugins/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n,source:e?.source,scope:e?.scope})}),r=await t.json();if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);L(e=>{let t={...e};for(let e of r.updates??[])t[fl(e)]=e;return t})}catch(e){D(e instanceof Error?e.message:String(e))}finally{P(e=>{let n=new Set(e);for(let e of t)n.delete(e);return n}),e||O(!1)}}},[n,_]),Q=(0,i.useCallback)(async()=>{H(!0),$(null),M(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({}),M(c("i18n.packagesUpdated")),s&&M(`${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=fl(t);N(`${e}:${r}`),$(null),M(null),R(null);try{let i=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,source:t.source,scope:t.scope,cwd:n})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);if(p(s),"remove"===e)v(s.packages[0]?fl(s.packages[0]):s.standaloneExtensions[0]?fo(s.standaloneExtensions[0]):null),0===s.packages.length&&0===s.standaloneExtensions.length&&y(!0),M(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")};M(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=hq(t,r,e=>!e.disabled,e=>e.filtered),l=r?0:t.filter(e=>!e.disabled&&e.filtered).length,o=l>0?c("plugins.bulkKeptFiltered",{count:l}):void 0;if($(null),M(null),R(o?{scope:e,note:o}:null),0===i.length)return;let a=r?"enable":"disable";N(`bulk:${e}`);try{let t=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:a,cwd:n,packages:i.map(t=>{let{source:n}=t;return{source:n,scope:e}})})}),l=await t.json();if(!t.ok||l.error||!l.results)throw Error(l.error??`HTTP ${t.status}`);let{results:d,...u}=l;p(u);let h=d.filter(e=>e.error);if(h.length<d.length){let e=r?c("plugins.bulkEnabled"):c("plugins.bulkDisabled");M(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=fs(w).trim();if(!e)return;k(e);let t=`${j}\0${e}`;N(`install:${t}`),$(null),M(null),R(null);try{var r;let i,s,l=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:e,scope:j,cwd:n})}),o=await l.json();if(!l.ok||o.error)throw Error(o.error??`HTTP ${l.status}`);p(o);let a=(r=o.packages,s=(i=e.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===j&&e.source===i)??r.find(e=>e.scope===j&&e.source===`npm:${s}`)??r.find(e=>e.scope===j&&e.source.endsWith(i)));v(a?fl(a):t),y(!1),k(""),M(c("i18n.packageInstalled"))}catch(e){$(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,j,w,c]),er=(0,i.useCallback)(async()=>{if(s){N("reload"),$(null),M(null),R(null);try{await ce(s,{type:"reload"}),o?.(),await J(),M(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,el=_.some(e=>e.canCheckForUpdates),eo=h||null!==C||z.size>0||B;return(0,r.jsxs)(pN,{embedded:a,title:c("common.plugins"),subtitle:e1(n),closeLabel:c("i18n.close"),onClose:l,children:[!V&&(0,r.jsx)(p0,{message:c("trust.pluginsNotLoaded")}),(0,r.jsxs)(pT,{children:[(0,r.jsxs)(pR,{children:[(0,r.jsx)(pA,{children:h?(0,r.jsx)("div",{className:"config-sidebar-message",children:c("i18n.loading")}):m?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:m}):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)(pL,{children:c("i18n.extensions")}),U.map(e=>{let t=fo(e);return(0,r.jsxs)(pW,{active:!b&&x===t,title:e.path,onClick:()=>{v(t),y(!1),$(null),M(null)},children:[(0,r.jsx)(p9,{active:e.enabled}),(0,r.jsx)(pO,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.name})]},t)})]}),Z.map(e=>{let t=e.packages.filter(e=>!e.disabled).length,n=t===e.packages.length;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(pL,{aside:(0,r.jsx)(pz,{enabled:t,total:e.packages.length,disabled:eo,loading:C===`bulk:${e.scope}`,label:c(n?"plugins.groupSwitchOn":"plugins.groupSwitchOff",{group:fa(e.scope,c)}),onChange:t=>void et(e.scope,e.packages,t)}),children:fa(e.scope,c)}),T?.scope===e.scope&&(0,r.jsx)(pP,{error:T.error,note:T.note}),e.packages.map(e=>{let t=fl(e),n=!b&&x===t;return(0,r.jsxs)(pW,{active:n,title:e.description??e.source,onClick:()=>{v(t),y(!1),$(null),M(null)},children:[(0,r.jsx)(p9,{active:!e.disabled,color:fu(e.status)}),(0,r.jsx)(pO,{className:`is-grow${e.disabled?" is-muted":""}`,children:e.source}),A[fl(e)]?.state==="update-available"&&(0,r.jsx)("span",{title:c("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"})]},t)})]},e.scope)})]})}),(0,r.jsx)(p6,{active:b,onClick:()=>{y(!0),$(null),M(null)},children:c("i18n.addPlugin")})]}),(0,r.jsx)(p2,{children:(0,r.jsx)(pF,{className:"is-fill",children:b?(0,r.jsx)(fh,{cwd:n,source:w,scope:j,projectResourcesLoaded:V,busy:ei,actionError:E,onSourceChange:k,onScopeChange:S,onInstall:en}):h?null:q?(0,r.jsx)(fm,{extension:q}):K?(0,r.jsx)(ff,{pkg:K,cwd:n,busyKey:C,actionError:E,actionMessage:I,sessionId:s,updateStatus:A[fl(K)],checkingUpdate:z.has(fl(K)),updateError:F,onAction:ee,onCheckUpdate:()=>void X(K),onReloadSession:er},fl(K)):(0,r.jsx)(p1,{children:c("i18n.selectPackage")})})})]}),(0,r.jsxs)(p4,{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)(p8,{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(fc)}):(0,r.jsx)(p8,{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:[!a&&(0,r.jsx)(p3,{onClick:l,children:c("i18n.close")}),el&&(0,r.jsx)(p3,{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"):W?c("i18n.checking"):es>0?`${c("i18n.updateAllPlugins")} (${es})`:c("i18n.checkUpdates")}),(0,r.jsx)(p3,{variant:"secondary",onClick:()=>void J(),disabled:eo,children:c("i18n.refresh")})]})]})}let fx={en:{title:"Archives",empty:"No archived projects.",loadFailed:"Could not load archives.",sessions:"{count} sessions",unarchive:"Unarchive",deleteSessions:"Delete",deleteConfirmLead:"Deletes {count} chat sessions. Does not delete the code folder.",deleteConfirmHint:"Type confirm to continue.",deleteConfirmName:"confirm",cancel:"Cancel",busy:"Working…",runningBlocked:"Stop the running agent in this project first.",deleteFailed:"Could not delete those sessions.",path:"Path",untitled:"Untitled session",messages:"{count} messages"},"zh-CN":{title:"归档",empty:"没有已归档的项目。",loadFailed:"无法加载归档列表。",sessions:"{count} 个会话",unarchive:"取消归档",deleteSessions:"删除",deleteConfirmLead:"将删除该项目下 {count} 个聊天会话,不会删除磁盘上的代码目录。",deleteConfirmHint:"输入「确认」继续。",deleteConfirmName:"确认",cancel:"取消",busy:"处理中…",runningBlocked:"请先停止该项目中正在运行的 agent。",deleteFailed:"删除会话失败。",path:"路径",untitled:"未命名会话",messages:"{count} 条消息"},"zh-TW":{title:"封存",empty:"沒有已封存的專案。",loadFailed:"無法載入封存清單。",sessions:"{count} 個工作階段",unarchive:"取消封存",deleteSessions:"刪除",deleteConfirmLead:"將刪除該專案下 {count} 個聊天工作階段,不會刪除磁碟上的程式碼目錄。",deleteConfirmHint:"輸入「確認」繼續。",deleteConfirmName:"確認",cancel:"取消",busy:"處理中…",runningBlocked:"請先停止該專案中正在執行的 agent。",deleteFailed:"刪除工作階段失敗。",path:"路徑",untitled:"未命名工作階段",messages:"{count} 則訊息"}},fv={en:fx.en.title,"zh-CN":fx["zh-CN"].title,"zh-TW":fx["zh-TW"].title};function fb(e,t){return e.replace(/\{(\w+)\}/g,(e,n)=>void 0===t[n]?e:String(t[n]))}function fy(e){let t=e.replace(/[\\/]+$/,""),n=t.split(/[\\/]/);return n[n.length-1]||t}function fw(e){var t;let n,{onClose:s,embedded:l=!1}=e,{locale:o}=(0,t_.s)(),a=fx[o]??fx.en,[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(""),[m,g]=(0,i.useState)(!1),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(!1),[w,k]=(0,i.useState)(""),[j,S]=(0,i.useState)(null),C=(0,i.useCallback)(async()=>{g(!1);try{let[e,t]=await Promise.all([fetch("/api/archives",{cache:"no-store"}),fetch("/api/home",{cache:"no-store"})]);if(!e.ok)throw Error("load failed");let n=await e.json(),r=await t.json().catch(()=>({}));"string"==typeof r.home&&f(r.home);let i=Array.isArray(n.projects)?n.projects:[];c(i),p(e=>e&&i.some(t=>t.key===e)?e:i[0]?.key??null)}catch{g(!0)}},[]);(0,i.useEffect)(()=>{C()},[C]);let N=d.find(e=>e.key===u)??null,E=async e=>{if(0!==e.length){v(!0),S(null);try{for(let t of ep(e)){let e={action:"set",ids:t,archived:!1},n=await fetch("/api/sessions/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store"});if(!n.ok)throw Error(`unarchive failed: ${n.status}`)}y(!1),k(""),await C()}catch{S(a.loadFailed)}finally{v(!1)}}},$=async e=>{v(!0),S(null);try{let t=await fetch("/api/archives/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectKey:e.key,confirm:w.trim()})}),n=await t.json().catch(()=>({}));if(409===t.status&&n.runningSessionIds?.length)return void S(a.runningBlocked);if(!t.ok)throw Error(n.error??"delete failed");y(!1),k(""),c(t=>t.filter(t=>t.key!==e.key)),p(t=>t===e.key?null:t)}catch{S(a.deleteFailed)}finally{v(!1)}};return(0,r.jsx)(pN,{embedded:l,title:a.title,onClose:s,children:m?(0,r.jsx)(p1,{children:a.loadFailed}):0===d.length?(0,r.jsx)(p1,{children:a.empty}):(0,r.jsxs)(pT,{children:[(0,r.jsx)(pR,{children:(0,r.jsx)(pA,{children:d.map(e=>(0,r.jsx)(pW,{active:e.key===u,onClick:()=>{p(e.key),y(!1),k(""),S(null)},children:(0,r.jsx)(pO,{title:e.root,children:fy(e.root)})},e.key))})}),(0,r.jsx)(p2,{children:N?(0,r.jsxs)(pF,{children:[(0,r.jsxs)(pD,{children:[(0,r.jsx)(pB,{children:(0,r.jsx)(p_,{children:fy(N.root)})}),(0,r.jsxs)(pH,{children:[(0,r.jsx)(p3,{variant:"secondary",size:"small",disabled:x||0===N.families.length,onClick:()=>void E(N.families.map(e=>e.id)),children:x?a.busy:a.unarchive}),!b&&(0,r.jsx)(p3,{variant:"danger",size:"small",disabled:x||0===N.families.length,onClick:()=>{y(!0),k(""),S(null)},children:a.deleteSessions})]})]}),(0,r.jsx)(pK,{label:a.path,children:(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",wordBreak:"break-all"},children:(t=N.root,h&&t.startsWith(h)?"~"+t.slice(h.length):t)})}),b&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:fb(a.deleteConfirmLead,{count:N.families.length})}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:a.deleteConfirmHint}),(0,r.jsx)("input",{value:w,onChange:e=>k(e.target.value),placeholder:a.deleteConfirmName,"aria-label":a.deleteConfirmName,autoComplete:"off",style:{alignSelf:"flex-start",width:"min(220px, 100%)",fontFamily:"var(--font-mono)",fontSize:12,padding:"6px 8px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text)"}}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)(p3,{variant:"danger",size:"small",disabled:x||"confirm"!==(n=w.trim().toLowerCase())&&"确认"!==n&&"確認"!==n,onClick:()=>void $(N),children:x?a.busy:a.deleteSessions}),(0,r.jsx)(p3,{variant:"ghost",size:"small",disabled:x,onClick:()=>{y(!1),k("")},children:a.cancel})]})]}),(0,r.jsx)(pU,{children:fb(a.sessions,{count:N.families.length})}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2,minHeight:0,overflowY:"auto"},children:N.families.map(e=>{let t=function(e,t){let n=e.name?.trim();if(n)return n;let r=e.firstMessage?.replace(/\s+/g," ").trim();return r&&"(no messages)"!==r?r:t}(e,a.untitled);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3,padding:"8px 10px",borderRadius:6,background:"var(--bg-hover)"},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:500,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:t,children:t}),(0,r.jsx)(p3,{variant:"ghost",size:"small",disabled:x,onClick:()=>void E([e.id]),children:x?a.busy:a.unarchive})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,fontSize:11,color:"var(--text-muted)"},children:[(0,r.jsx)("span",{children:(0,nG.fw)(new Date(e.archivedAt),o)}),(0,r.jsx)("span",{children:fb(a.messages,{count:e.messageCount})})]})]},e.id)})}),j&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:j})]}):(0,r.jsx)(p1,{children:a.empty})})]})})}let fk="\\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",fj=RegExp(`[${fk}]`,"gu"),fS=RegExp(`[${fk}]`,"u");function fC(e){return e.replace(fj,e=>{let t=e.codePointAt(0)??0;return`\\u{${t.toString(16).toUpperCase().padStart(4,"0")}}`})}let fN=/[\s"'`$|&;<>()*?#~]/;function fE(e){let t=fS.test(e),n=fC(e);return""===n||t||fN.test(n)?`"${n.replace(/"/g,'\\"')}"`:n}function f$(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return[e,...t].map(fE).join(" ")}function fI(e){let t=void 0!==e.command?f$(e.command,e.args):void 0,n=void 0!==e.url?fC(e.url):void 0;return"http"===e.transport?n:"stdio"===e.transport?t:n??t}function fM(e){return[e.name,e.command,e.cwd,e.url,...e.args??[],...e.envNames,...e.headerNames].some(e=>void 0!==e&&fS.test(e))}function fT(e){return"oauth-client-secret"===e.kind?{key:"mcp.field.oauthClientSecret"}:{key:"env"===e.kind?"mcp.field.env":"mcp.field.header",params:{name:fC(e.name??"")}}}function fR(e){return"http"===e.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables"}function fA(e){return e.length>0?{key:"mcp.server.overridesGlobal",params:{keys:e.join(", ")}}:{key:"mcp.server.overridesGlobalNothing"}}function fL(e){return e.flatMap(e=>{let{variables:t,...n}=e;return t.map(e=>({variable:e,field:n}))})}function fz(e,t){return"unparsable"===e.reason||"unreadable"===e.reason?fC(e.error):"link-outside"===e.reason?void 0===t?void 0:fC(t):void 0}let fP="codemode";function fW(e){return`${e.scope}\0${e.name}`}function fO(e){return e?.trust?.decision===!0}function fF(e){return"test"===e.origin?e.state:void 0!==e.closedAt||"not-trusted"===e.state?"on":e.state}function fD(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?fF(e.status):"on":"mcp-off":"not-trusted":"disabled"}let fB={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"},fH={connected:"mcp.state.session.connected",failed:"mcp.state.session.failed"};function f_(e,t){return(t?.origin==="session"?fH[e]:void 0)??fB[e]}let fU={disconnected:"mcp.stateDetail.disconnected",conflict:"mcp.stateDetail.conflict"},fK={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 fq(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 fV(e){return"on"===e?{active:!0}:"off"===e?{active:!1}:{color:"error"===e?"#ef4444":"#f59e0b"}}function fZ(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 fJ={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"},fY={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"},fG={connecting:"off",connected:"on","needs-auth":"warning",failed:"error",disconnected:"warning",conflict:"error","not-trusted":"warning"},fX={codemode:"mcp.exposure.codemode",deferred:"mcp.exposure.deferred",direct:"mcp.exposure.direct",hidden:"mcp.exposure.hidden"},fQ=["codemode","deferred","direct","hidden"],f0={codemode:"mcp.exposureShort.codemode",deferred:"mcp.exposureShort.deferred",direct:"mcp.exposureShort.direct",hidden:"mcp.exposureShort.hidden"};function f1(e){return"auto-enable-codemode-invalid"!==e.reason}function f2(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 f4(e){return{enabled:e.filter(e=>e.enabled).length,total:e.length}}function f8(e,t){let n=e.flatMap(e=>e.servers.map(fW));return t===fP||null!==t&&n.includes(t)?t:n[0]??null}function f3(e){let t=e?.trust;return void 0!==t&&t.requiresTrust&&!t.trusted}function f5(e){return e.projectOverride?.preference??e.preference}let f6={always:"mcp.codemode.projectOverride.always",automatic:"mcp.codemode.projectOverride.automatic"},f9={on:"mcp.codemode.toolMode.onDescription",only:"mcp.codemode.toolMode.onlyDescription"},f7={on:"mcp.codemode.toolMode.projectOverride.on",only:"mcp.codemode.toolMode.projectOverride.only"},me={automatic:"mcp.codemode.automatic",always:"mcp.codemode.always",unavailable:"mcp.codemode.unavailable",unknown:"i18n.unknown"};function mt(e){return"unavailable"===e?"error":"unknown"===e?"off":"on"}let mn=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e);function mr(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}:{},...mn(n.names)?{names:n.names}:{},...mn(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 mi(e,t,n,r){let i,{abortAtDeadline:s=!0}=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},l=new AbortController,o=()=>l.abort();r?.aborted?l.abort():r?.addEventListener("abort",o,{once:!0});let a=new Promise(e=>{i=setTimeout(()=>{e(t()),s&&l.abort()},n)});try{return await Promise.race([e(l.signal),a])}finally{clearTimeout(i),r?.removeEventListener("abort",o)}}function ms(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 ml(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&&ms(i)?{ok:!0,data:i}:{ok:!1,error:mr(i,r.status)}}let mo=new Set(["cwd-invalid","cwd-denied","cwd-not-directory"]);async function ma(e,t,n){let r=await ml(e,t,n);if(r.ok||!e||!r.error.reason||!mo.has(r.error.reason))return r;let i=await ml(null,t,n);return i.ok?{...i,projectError:r.error}:i}async function md(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 mi(n=>ma(e,t,n),()=>({ok:!1,error:{error:`GET /api/mcp did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function mc(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 l=i.ok&&null!==s&&"object"==typeof s?t(s):void 0;return void 0!==l?{ok:!0,stored:l}:{ok:!1,error:mr(s,i.status)}}async function mu(e,t,n){let r=await mc({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 mp(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 mi(n=>mu(e,t,n),()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function mh(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 mi(async n=>{let r=await mc({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 mf(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 mi(async n=>{let r=await mc({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 mm(e){return!e.available&&"builtin-disabled"!==e.reason}function mg(e,t){if(mm(t.mcp))return"mcp-off";if("project"===e){if(!t.project?.trust)return"trust-unreadable";if(!fO(t.project))return"project-untrusted"}}let mx={"mcp-off":"mcp.readOnly.mcp-off","project-untrusted":"mcp.readOnly.project-untrusted","trust-unreadable":"mcp.readOnly.trust-unreadable"};function mv(e){return!0!==e.notAnObject}function mb(e){return mv(e)&&void 0===e.webPasswordField}async function my(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&&ms(i)?{ok:!0,data:i}:{ok:!1,error:mr(i,r.status)}}async function mw(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 mi(e=>my(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp did not answer within ${i} ms`,timedOut:!0}}),i,r)}let mk={"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 mj(e,t){let n=mg(e.scope,t);return n||(void 0===e.invalidError&&e.validated?e.webPasswordField?"web-password":void 0:"invalid")}let mS={"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"},mC={connected:"mcp.test.state.connected","needs-auth":"mcp.test.state.needs-auth",failed:"mcp.test.state.failed",timedOut:"mcp.test.state.timedOut"},mN={connected:"mcp.test.summary.connected","needs-auth":"mcp.test.summary.needs-auth",failed:"mcp.test.summary.failed",timedOut:"mcp.test.summary.timedOut"},mE={connected:"mcp.signIn.summary.connected","needs-auth":"mcp.signIn.summary.needs-auth",failed:"mcp.signIn.summary.failed",timedOut:"mcp.signIn.summary.timedOut"};function m$(e){return(Math.max(0,e)/1e3).toFixed(1)}async function mI(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:mr(i,r.status)}}async function mM(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 mi(e=>mI(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp/test did not answer within ${i} ms`,timedOut:!0}}),i,r,{abortAtDeadline:!1})}let mT="•••",mR=new Set(["key","apikey","token","secret","password","passwd","passphrase","pwd","pass","credential","credentials","authorization","bearer","jwt","cookie","signature","pat"]),mA=new Set([...mR,"auth","sig","code","pw"]),mL=["token","secret","password","passwd","apikey"],mz=new Set(["file","path","dir","url","uri","endpoint","id","name","type","header","env","var","length","ttl","expiry","expires","timeout","mode","format"]),mP=new Set(["-k"]);function mW(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 mO(e,t){let n=mW(e);return!(n.length>1&&mz.has(n[n.length-1]))&&n.some(e=>t.has(e)||mL.some(t=>e.length>t.length&&e.endsWith(t)))}function mF(e){return mO(e,mR)}let mD=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,})"),mB=/^eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*$/,mH=/^[A-Za-z0-9_\-+/=.~]+$/;function m_(e){return!(/\s/.test(e)||mZ(e))&&(!!(mD.test(e)||mB.test(e))||!(e.length<24||!mH.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 mU=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Za-z_][A-Za-z0-9_]*/,mK=RegExp(mU.source,"g"),mq=/^(?:bearer|basic|token)\s+/i;function mV(e,t,n){let r=e.replace(mq,"");return t.test(r)&&/^[^A-Za-z0-9]*$/.test(r.replace(n,""))}function mZ(e){return mV(e.replace(/\$[$!]/g,"_x"),mU,mK)}let mJ=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Z_][A-Z0-9_]*(?![A-Za-z0-9_])/,mY=RegExp(mJ.source,"g");function mG(e){return mV(e,mJ,mY)}function mX(e,t){if(!e||""===t)return;e.push(t);let n=m1(t);n!==t&&e.push(n)}let mQ=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#]*)/;function m0(e,t,n){let r=!1,i=e,s="",l=mQ.exec(e);if(l){let[o,a,d]=l,c=d.lastIndexOf("@");if(c>=0&&!t(m1(d.slice(0,c)))){s=`${a}${mT}${d.slice(c)}`,r=!0;let e=d.slice(0,c);mX(n,e);let t=e.indexOf(":");t>=0&&mX(n,e.slice(t+1))}else s=o;i=e.slice(o.length)}let o=i.search(/[?#]/),a=o<0?i:i.slice(0,o),d=o<0?"":i.slice(o),c=a.split("/").map(e=>m_(m1(e))?(r=!0,mX(n,e),mT):e).join("/");return d=d.replace(/([?&#;])([^&#;]*)/g,(e,i,s)=>{let l=s.indexOf("=");if(l<0){let l=m1(s);return!m_(l)||t(l)?e:(r=!0,mX(n,s),`${i}${mT}`)}let o=s.slice(0,l),a=m1(s.slice(l+1));return""===a||t(a)||!function(e){let t=e;try{t=decodeURIComponent(e)}catch{}return mO(t,mA)}(o)&&!m_(a)?e:(r=!0,mX(n,s.slice(l+1)),`${i}${o}=${mT}`)}),{value:`${s}${c}${d}`,masked:r}}function m1(e){try{return decodeURIComponent(e)}catch{return e}}let m2=/^(\s*[A-Za-z][A-Za-z0-9 _.-]*=)([\s\S]*)$/;function m4(e,t,n){let r=/^([A-Za-z0-9_-]+):(\s*)([\s\S]*)$/.exec(e);if(r&&""!==r[3]&&!r[3].startsWith("//")&&mF(r[1])){let[,i,s,l]=r;return t(l)?{value:e,masked:!1}:(mX(n,l.trim()),{value:`${i}:${s}${mT}`,masked:!0})}let i=e.includes(";")?function(e,t,n){let r=e.split(";");if(r.length<2||!r.every(e=>""===e.trim()||m2.test(e)))return;let i=!1;return{value:r.map(e=>{let r=m2.exec(e);if(!r)return e;let[,s,l]=r;if(""===l.trim()||t(l))return e;if(mF(s.slice(0,-1).trim()))return i=!0,mX(n,l.trim()),`${s}${mT}`;let o=m4(l,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]&&mF(s[1]))return t(s[2])?{value:e,masked:!1}:(mX(n,s[2]),{value:`${s[1]}=${mT}`,masked:!0});if(/\s/.test(e)){var l,o,a;let r,i;return l=e,o=t,a=n,i=m5((r=l.split(/(\s+)/)).filter((e,t)=>t%2==0),o,!0,a),{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 m0(e,t,n);if(s&&""!==s[2]){let e=m4(s[2],t,n);return{value:`${s[1]}=${e.value}`,masked:e.masked}}return m_(e)&&!t(e)?(mX(n,e),{value:mT,masked:!0}):{value:e,masked:!1}}function m8(e){if(mP.has(e))return!0;if(!/^--?[A-Za-z]/.test(e))return!1;let t=e.replace(/^-+/,"");return mF(t)||"auth"===mW(t).at(-1)}let m3=/^(?:bearer|basic|token)$/i;function m5(e,t,n,r){let i=!1,s=!1;return{values:e.map(e=>{if(""===e)return e;if(s){if(n&&m3.test(e))return e;if(s=!1,!/^-[A-Za-z-]/.test(e))return t(e)?e:(i=!0,mX(r,e),mT)}let l=/^(--?[A-Za-z][A-Za-z0-9_.-]*)=([\s\S]*)$/.exec(e);if(l){let[,e,n]=l;if(""!==n&&m8(e)&&!t(n))return i=!0,mX(r,n),`${e}=${mT}`;let s=m4(n,t,r);return i||=s.masked,`${e}=${s.value}`}if(/^--?[A-Za-z][A-Za-z0-9_.-]*$/.test(e))return s=m8(e),e;if(n){let t=/^([A-Za-z0-9_-]+):$/.exec(e);if(m3.test(e)||t&&mF(t[1]))return s=!0,e}let o=m4(e,t,r);return i||=o.masked,o.value}),masked:i}}function m6(e){let{values:t,masked:n}=m5(e,mG,!1);return{args:t,masked:n}}function m9(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function m7(e){return!e.startsWith("!")&&!mZ(e)}function ge(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 gt={"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(gt);let gn={dollarBrace:!1,bareDollar:!1,percent:!1,braceEnv:!1},gr={dollarBrace:!0,bareDollar:!1,percent:!0,braceEnv:!0},gi={...gr,bareDollar:!0},gs={...gn,braceEnv:!0},gl=/^[A-Za-z_][A-Za-z0-9_]*$/,go=/\$\{([^{}]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)|%([A-Za-z_][A-Za-z0-9_]*)%|\{(env|file):([^{}]*)\}/g;function ga(e,t){if(!t)return;let n=e[e.length-1];n?.kind==="text"?n.text+=t:e.push({kind:"text",text:t})}function gd(e,t,n){let r=[],i=0;go.lastIndex=0;for(let s=go.exec(e);s;s=go.exec(e)){let[l,o,a,d,c,u]=s,p=l;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(gl.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,l);else if(void 0!==a&&t.bareDollar)p={kind:"env",name:a,from:l};else if(void 0!==d&&t.percent&&n)p={kind:"env",name:d,from:l};else if(void 0!==c&&t.braceEnv)p="env"===c&&gl.test(u)?{kind:"env",name:u,from:l}:{kind:"unsupported",from:l};else if(void 0!==d||void 0!==c){ga(r,e.slice(i,s.index+1)),i=s.index+1,go.lastIndex=s.index+1;continue}ga(r,e.slice(i,s.index)),"string"==typeof p?ga(r,p):r.push(p),i=s.index+l.length}return ga(r,e.slice(i)),r}function gc(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 gu(e){return e.startsWith("!")}function gp(e){if(gu(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);gl.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 gh=/<[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,gf=/^(?:\.\.\.|…|\*{3,}|x{3,}|TODO|FIXME|changeme|change[-_]me|replace[-_]?me|placeholder|redacted|\[[^\]]+\])$/i,gm=/(?:^|[\\/])(?:path[\\/]to(?:[\\/]|$)|Users[\\/](?:username|yourname|your[-_][A-Za-z_-]+|user[-_]?name|<[^>]+>)(?:[\\/]|$)|home[\\/](?:username|yourname|your[-_][A-Za-z_-]+|<[^>]+>)(?:[\\/]|$))/i,gg=/^(Bearer|Basic|Token|Bot|ApiKey|Api-Key)\s+(.+)$/i;function gx(e){return e.join("\0")}function gv(e){return"args"===e[0]?`args[${e[1]}]`:e.join(".")}function gb(e){return"env"===e[0]||"headers"===e[0]||"oauth"===e[0]&&"clientSecret"===e[1]}function gy(e){return"command"===e[0]||"args"===e[0]||"cwd"===e[0]}let gw=new Set(["HOME","USERPROFILE"]);class gk{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 gj(e){return e.map(e=>"text"in e?e.text:e.from).join("")}let gS=/\$\{[^{}]*\}/g,gC=new Set(["variable","home","workspace-basename","unsupported-variable","input"]);class gN{constructor(e){this.draft=e,this.fields=new Map,this.argTexts=e.args.map(gj),this.urlText=gj(e.url??[])}encode(e,t){let n,r=gb(e),i=gv(e),s=gj(t),l=[],o=!1,a=()=>l.every(e=>""===e),d=e=>{if(!r)return void l.push(e);let t=/\$([A-Za-z_][A-Za-z0-9_]*)/.exec(e);t&&this.draft.note("bare-dollar-literal",{field:i,name:t[1]});let n=gc(e,{atStart:a()});n!==e&&(o=!0),l.push(n)},c=e=>l.push(e),u=e=>l.push({field:e});if(!r&&gy(e)&&1===t.length&&"text"in t[0]&&gm.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(gm.test(n))return t&&c(t),u(this.field(e,"placeholder-path",n,n,"text")),this.target(e,l,void 0)}let p=0;return t.forEach((l,o)=>{let h=t[o+1],f=void 0===h||"text"in h&&/^[\\/]/.test(h.text),m=(t,r,i)=>{let l=0;for(let[d,c]of function(e){let t=e.trim();if(gf.test(t)){let n=e.indexOf(t);return[[n,n+t.length]]}let n=gg.exec(t);if(n&&gf.test(n[2].trim())){let t=e.lastIndexOf(n[2].trim());return[[t,t+n[2].trim().length]]}let r=[];gh.lastIndex=0;for(let t=gh.exec(e);t;t=gh.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,a;if(i.some(e=>{let[t,n]=e;return d<n&&c>t}))continue;d>l&&r(t.slice(l,d)),"url"===e[0]&&gE(s,p+d)&&(n="uri-component");let h=t.slice(d,c);u(this.field(e,"placeholder",(o=e,a=h,"env"===o[0]||"headers"===o[0]?o[1]:a.replace(/^[<{\s]+|[>}\s]+$/g,"")||gv(o)),h)),l=c}l<t.length&&r(t.slice(l))};switch(l.kind){case"text":m(l.text,d,[]);break;case"pi":{var g;let e=h?(g=l.text,(/\$+$/.exec(g)?.[0].length??0)%2==1?`${g}$`:g):l.text;if(r&&a()&&gu(e)){this.draft.note("shell-command-value",{field:i}),c(e);break}let t=[...e.matchAll(gS)].map(e=>[e.index,e.index+e[0].length]);m(e,c,t);break}case"env":r?(c(`$\{${l.name}}`),void 0!==l.fallback&&this.draft.note("variable-fallback-dropped",{field:i,name:l.name,fallback:l.fallback}),l.shell?this.draft.note("shell-variable",{field:i,name:l.name}):l.from!==`$\{${l.name}}`&&this.draft.note("variable-translated",{field:i,from:l.from,to:`$\{${l.name}}`})):gy(e)&&a()&&gw.has(l.name)&&f?(c("~"),this.draft.note("home-translated",{field:i,from:l.from})):(u(this.field(e,"variable",l.name,l.from,void 0,l.fallback)),this.draft.note(l.shell?"shell-variable":"variable-unsupported-here",{field:i,name:l.name}));break;case"input":u(this.inputField(e,l));break;case"home":r?(c("${HOME}"),this.draft.note("home-variable-translated",{field:i,from:l.from,to:"${HOME}"})):gy(e)&&a()&&f?(c("~"),this.draft.note("home-translated",{field:i,from:l.from})):u(this.field(e,"home","userHome",l.from,"text"));break;case"workspace":"url"===e[0]||"oauth"===e[0]?u(this.field(e,"variable","workspaceFolder",l.from,"text")):(c("."),this.draft.note("workspace-folder-relative",{field:i,from:l.from}));break;case"workspace-basename":u(this.field(e,"workspace-basename","workspaceFolderBasename",l.from,"text"));break;case"unsupported":u(this.field(e,"unsupported-variable",l.from,l.from)),this.draft.note("unsupported-variable",{field:i,variable:l.from});break;case"prompt":"url"===e[0]&&gE(s,p)&&(n="uri-component"),u(this.promptField(e,l))}p+=("text"in l?l.text:l.from).length}),o&&this.draft.note("escaped-value",{field:i}),this.target(e,l,n)}target(e,t,n){let r=t.filter(e=>""!==e);for(let t of new Set(r.flatMap(e=>"string"==typeof e?[]:[e.field]))){let i=this.fields.get(t);i.targets.some(t=>gx(t.path)===gx(e))||i.targets.push({path:e,parts:r,...n?{encoding:n}:{}})}return r.map(e=>"string"==typeof e?e:this.fields.get(e.field).placeholder??"").join("")}field(e,t,n,r,i,s){let l=gC.has(t)?`${t}.${n}`:gv(e);if(gC.has(t)){if(this.fields.has(l))return l}else for(let t=2;this.fields.has(l);t++)l=`${gv(e)}#${t}`;let o=this.isSecretContext(e,r)||mF(n),a="headers"===e[0]&&"authorization"===e[1].toLowerCase();return this.fields.set(l,{id:l,kind:i??(o?"password":"text"),reason:t,label:n,placeholder:r,...void 0!==s?{defaultValue:s}:{},..."placeholder"===t&&a?{optional:!0}:{},targets:[]}),l}inputField(e,t){let n=`input.${t.id}`;if(this.fields.has(n))return n;let r=this.draft.inputs?.get(t.id);r?"command"===r.type&&this.draft.note("input-command-unsupported",{id:t.id}):this.draft.note("input-undefined",{id:t.id});let i=r?.type==="pickString"&&r.options&&r.options.length>0?r.options:void 0,s=r?.password===!0||this.isSecretContext(e,t.from);return this.fields.set(n,{id:n,kind:i?"select":s?"password":"text",reason:"input",label:t.id,placeholder:t.from,...r?.description?{description:r.description}:{},...r?.default!==void 0?{defaultValue:r.default}:{},...i?{options:i}:{},targets:[]}),n}promptField(e,t){return this.fields.has(t.id)||this.fields.set(t.id,{id:t.id,kind:t.options?"select":t.secret||this.isSecretContext(e,t.from)?"password":"text",reason:t.reason,label:t.label,placeholder:t.from,...t.description?{description:t.description}:{},...void 0!==t.defaultValue?{defaultValue:t.defaultValue}:{},...t.options?{options:t.options}:{},...t.optional?{optional:!0}:{},targets:[]}),t.id}isSecretContext(e,t){switch(e[0]){case"env":case"headers":return mF(e[1]);case"oauth":return"clientSecret"===e[1];case"args":{if(m6([this.argTexts[e[1]]??""]).masked)return!0;let t=this.argTexts[e[1]-1];return void 0!==t&&m6([t,"x"]).args[1]===mT}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,m0(`https://host.invalid/?${n}=x`,mG).masked)}default:return!1}}}function gE(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 g$(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 gI=/^[A-Za-z0-9_-]+$/;function gM(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 gT=new Set(["mcp","server","mcp-server","mcpserver","cli","index","main","app","src","dist","build","bin","lib"]);function gR(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=gL(t);return s&&!gT.has(s.toLowerCase())?s:gL(r)||r||s||t}let gA=[/^mcp[-_]server[-_]/i,/^server[-_]/i,/^mcp[-_]/i,/[-_]mcp[-_]server$/i,/[-_]mcp$/i,/[-_]server$/i];function gL(e){let t=e;for(let e=!0;e;)for(let n of(e=!1,gA)){let r=t.replace(n,"");r!==t&&r&&(t=r,e=!0)}return t}let gz=new Set(["mcp","www","api","app","server","servers","remote","gateway"]);function gP(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=>!gz.has(e.toLowerCase()));return r[r.length-1]??n[n.length-1]??""}let gW=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 gO(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 gF(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(!gT.has(n.toLowerCase())&&"."!==n&&".."!==n)return gL(n.replace(/_/g,"-"))||n}return""}function gD(e,t){gB(e,t)&&gH(e,Math.ceil(t/1e3),t)}function gB(e,t){return!!("number"==typeof t&&Number.isFinite(t))&&t>0||(void 0!==t&&e.note("timeout-dropped",{value:String(t)}),!1)}function gH(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 g_=["codemode","deferred","direct","hidden"],gU={"codemode-deferred":"codemode"},gK=["localhost","127.0.0.1","[::1]"];function gq(e){return"string"==typeof e&&g_.includes(e)?e:"string"==typeof e&&Object.hasOwn(gU,e)?gU[e]:void 0}function gV(e){try{return new URL(e)}catch{return}}function gZ(e){let t=gV(e);return void 0!==t&&"http:"===t.protocol&&gK.includes(t.hostname)&&""===t.search&&""===t.hash}function gJ(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function gY(e){return gJ(e)&&Object.values(e).every(e=>"string"==typeof e)}function gG(e,t){if(!gI.test(e))return{problem:"name",name:e};if(!gJ(t))return{problem:"not-an-object"};let{type:n,exposure:r,enabled:i,timeout:s,toolExposure:l,description:o}=t;if(void 0!==r&&!gq(r))return{problem:"exposure",value:String(r)};if(void 0!==l){if(!gJ(l))return{problem:"tool-exposure"};for(let[e,t]of Object.entries(l))if(!gq(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=gV(t.url);if(!e||!/^https?:$/.test(e.protocol))return{problem:"url",url:t.url};if(void 0!==t.headers&&!gY(t.headers))return{problem:"headers"};let n=function(e){var t;let n;if(void 0===e)return;if(!gJ(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||!gZ(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?gV(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)?gV(t):void 0)&&("https:"===n.protocol||"http:"===n.protocol&&gK.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(!gJ(r)||"string"!=typeof r.provider||!r.provider)return{problem:"auth"};if("https:"!==e.protocol&&!gK.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||gY(t.env)?void 0!==t.cwd&&"string"!=typeof t.cwd?{problem:"cwd"}:void 0:{problem:"env"}:{problem:"args"}:{problem:"no-command-or-url"}}let gX=/[A-Za-z_]/,gQ=/[A-Za-z0-9_]/,g0=/^[A-Za-z_][A-Za-z0-9_]*$/,g1=new Set([..." \n'\"\\$`|&;<>()#*?[]{}!~="]),g2=new Set([..."|&;<>()"]),g4=/[0-9@*#?$!-]/,g8={n:"\n",t:" ",r:"\r",a:"\x07",b:"\b",e:"\x1b",E:"\x1b",f:"\f",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function g3(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 g5(e,t){return/^(?:[A-Za-z]:\\|\\\\[A-Za-z0-9.$_-])/.test(e.slice(t,t+4))}class g6{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 g9)return{ok:!1,error:e.detail};throw e}return{ok:!0,words:this.words}}fail(e){throw new g9(e)}startWord(){return this.parts||(this.lineBreak&&this.fail({code:"multiple-commands"}),this.parts=[],this.windowsWord=g5(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)&&g3(e,this.index)>0)this.index+=g3(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:"`"}):g2.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||!g1.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=g5(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 g8?(t+=g8[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&&gX.test(n)){let n=this.index+1;for(;n<t.length&&gQ.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&&g4.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}),g0.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 g9 extends Error{constructor(e){super(e.code),this.detail=e}}function g7(e){return new g6(e).run()}function xe(e){return e.parts.every(e=>"text"===e.type)?e.text:void 0}function xt(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let xn=["httpUrl","trust","includeTools","excludeTools","authProviderType","targetAudience","targetServiceAccount","tcp"];function xr(e){if(xn.some(t=>t in e))return!0;let t=e.oauth;return xt(t)&&["redirectUri","authorizationUrl","tokenUrl","audiences","tokenParamName"].some(e=>e in t)}function xi(e){if(!xt(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]||xt(t)&&"string"==typeof t.path||"string"==typeof n||"string"==typeof r||"string"==typeof i}function xs(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 xl(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 xo(e,t){let n=t?xl(t):void 0;return{code:"sse-transport",params:{...e?{server:e}:{},...t?{url:t}:{},...n?{suggestedUrl:n}:{}}}}function xa(e){return e?{server:e}:{}}function xd(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?String(e):void 0}function xc(e,t,n){let r;if(!xt(t))return{note:{code:"no-command-or-url",params:xa(e)}};let i=new Set,s=e=>(i.add(e),t[e]),l=n.rawPi,o=function(e,t){switch(e.flavor){case"zed":return gn;case"opencode":return gs;case"vscode":return gr;default:return xr(t)?gi:gr}}(n,t),a=s("name"),d=e??("string"==typeof a?a:void 0),c=new gk(n.source,l),u=(e,t)=>{if(l)return e?[{kind:"pi",text:e}]:[];return t&&"mcp-servers"===n.flavor&&/^!|\$\$|\$!/.test(e)&&c.note("looks-like-pi-config"),gd(e,o,t)};c.name=d,c.inputs=n.inputs;let p=s("inputs");Array.isArray(p)&&(c.inputs=new Map([...n.inputs??[],...xh(p)]));let h=s("type"),f=s("command"),m=[s("httpUrl"),s("url"),s("serverUrl")].find(e=>"string"==typeof e);if("tcp"in t)return{note:{code:"websocket-transport",params:xa(d)}};if(void 0!==h&&"unknown"===(r="string"==typeof h?xs(h):"unknown"))return{note:{code:"unsupported-transport",params:{...xa(d),type:String(h)}}};let g="string"==typeof f&&""!==f||Array.isArray(f)||xt(f),x=void 0!==m;if("sse"===r)return{note:xo(d,m)};if("ws"===r)return{note:{code:"websocket-transport",params:{...xa(d),...m?{url:m}:{}}}};if(void 0===r){if(g&&x)return{note:{code:"ambiguous-command-and-url",params:xa(d)}};if(x){if(void 0!==xl(m))return{note:xo(d,m)};r="http","mcp-servers"===n.flavor&&"string"==typeof t.url&&"string"!=typeof t.httpUrl&&c.note("transport-guessed")}else{if(!g)return{note:{code:"no-command-or-url",params:xa(d)}};r="stdio"}}if("stdio"!==r&&"http"!==r)return{note:{code:"unsupported-transport",params:{...xa(d),type:String(h)}}};if("stdio"===r&&!g||"http"===r&&!x)return{note:{code:"no-command-or-url",params:xa(d)}};if(c.transport=r,"stdio"===r){let e=function(e,t,n,r,i,s){let l,o=r("args"),a=r("opencode"===s.flavor?"environment":"env");if("opencode"===s.flavor&&void 0===a&&(a=r("env")),Array.isArray(n)){if(!n.every(e=>"string"==typeof e)||0===n.length)return{code:"invalid-config",params:{...xa(e.name),problem:"args"}};l=n[0],o=[...n.slice(1),...Array.isArray(o)?o:[]]}else if(xt(n))for(let t of(l="string"==typeof n.path?n.path:void 0,void 0===o&&(o=n.args),void 0===a&&(a=n.env),Object.keys(n)))["path","args","env"].includes(t)||e.note("dropped-key",{key:`command.${t}`});else"string"==typeof n&&(l=n);if(!l)return{code:"no-command-or-url",params:xa(e.name)};let d=Array.isArray(o)?[...o]:[];if(void 0!==o&&!Array.isArray(o))return{code:"invalid-config",params:{...xa(e.name),problem:"args"}};if(0===d.length&&/\s/.test(l.trim())&&!/^(?:[A-Za-z]:[\\/]|[\\/]|~[\\/]|\.{1,2}[\\/])/.test(l.trim())){let t=g7(l.trim()),n=t.ok?t.words.map(xe):void 0;n&&n.length>1&&n.every(e=>void 0!==e)&&(e.note("command-split",{command:l}),l=n[0],d.push(...n.slice(1)))}for(let[t,n]of(e.command=i(l,!1),d.entries())){let r=xd(n);if(void 0===r)return{code:"invalid-config",params:{...xa(e.name),problem:"args",index:t}};e.args.push(i(r,!1))}if(void 0!==a){if(!xt(a))return{code:"invalid-config",params:{...xa(e.name),problem:"env"}};for(let[t,n]of Object.entries(a)){if(null===n){e.note("env-null-dropped",{name:t});continue}let r=xd(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&&mF(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,f,s,u,n);if(e)return{note:e}}else!function(e,t,n,r,i){let s=r("headers"),l=i(n,!1),o=xt(s)&&Object.keys(s).some(e=>"authorization"===e.toLowerCase());if(1===l.length&&"text"in l[0]?g$(e,n,o):e.url=l,xt(s))for(let[t,n]of Object.entries(s)){let r=xd(n);if(void 0===r){e.note("dropped-key",{key:`headers.${t}`});continue}if(""===r.trim()){"authorization"===t.toLowerCase()?e.note("empty-authorization-dropped"):mF(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 a=r("oauth"),d=r("auth");if(!1===a?e.note("oauth-disable-unsupported"):xt(a)?xu(e,a,i):void 0!==a&&e.note("dropped-key",{key:"oauth"}),xt(d))for(let t of(xu(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,m,s,u);let v=s("timeout");if(void 0!==v)if(l)"number"==typeof v&&v>0?c.timeout=v:c.note("timeout-dropped",{value:String(v)});else if("opencode"===n.flavor)c.note("timeout-dropped",{value:String(v)});else if(xr(t))gD(c,v);else["autoApprove","alwaysAllow","transportType"].some(e=>e in t)||"streamableHttp"===t.type?gB(c,v)&&gH(c,Math.ceil(v),void 0):!function(e,t){if(!gB(e,t))return;let n=t>=1e3;e.note("timeout-unit-guessed",{value:t,unit:n?"milliseconds":"seconds"}),n?gH(e,Math.ceil(t/1e3),t):gH(e,Math.ceil(t),void 0)}(c,v);let b=s("enabled"),y=s("disabled");!1===b||!0===y?(c.enabled=!1,c.note("imported-disabled")):(void 0!==b&&"boolean"!=typeof b||void 0!==y&&"boolean"!=typeof y)&&c.note("dropped-key",{key:void 0!==b?"enabled":"disabled"});let w=s("exposure");if(void 0!==w){let e=gq(w);e?c.exposure=e:c.note("invalid-exposure-dropped",{value:String(w)})}let k=s("toolExposure");if(void 0!==k){let e=xt(k)?Object.entries(k).map(e=>{let[t,n]=e;return[t,gq(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(l||void 0===w&&void 0===k||c.note("looks-like-pi-config"),l){let e=s("description");"string"==typeof e?c.description=e:void 0!==e&&c.note("dropped-key",{key:"description"})}for(let e of(xp(c,s("includeTools"),s("excludeTools")),Object.keys(t)))i.has(e)||c.note("dropped-key",{key:e});return{draft:c}}function xu(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&&gZ(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 xp(e,t,n){let r=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e&&""!==e):[],i=r(t),s=r(n);if(0===i.length&&0===s.length)return;let l={...e.toolExposure??{}};if(i.length>0){let t=e.exposure??"codemode";for(let n of(e.exposure="hidden",i))l[n]=t;e.note("tool-filter-imported",{mode:"include",tools:i.join(", ")})}for(let e of s)l[e]="hidden";s.length>0&&e.note("tool-filter-imported",{mode:"exclude",tools:s.join(", ")}),e.toolExposure=l}function xh(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e)xt(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=>xt(e)?e.value:e).filter(e=>"string"==typeof e)}:{}});return t}function xf(e,t,n,r){let i=[],s=0;for(let l of e.matchAll(/\{([A-Za-z_][A-Za-z0-9_-]*)\}/g)){l.index>s&&i.push({kind:"text",text:e.slice(s,l.index)});let o=xt(t)&&xt(t[l[1]])?t[l[1]]:{};i.push(xm(`${n}${l[1]}`,l[1],l[0],o,r)),s=l.index+l[0].length}return s<e.length&&i.push({kind:"text",text:e.slice(s)}),i}function xm(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 xg(e,t,n){let r=[],i="",s=()=>{i&&("pi"===t?r.push({kind:"pi",text:i}):r.push(...gd(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 xx(e,t){let n="";for(let r=0;r<e.length;r++){let i=e[r];if("variable"===i.type){n+=i.raw;continue}let s=i.value.indexOf(t);if(s<0){n+=i.value;continue}n+=i.value.slice(0,s);let l=i.value.slice(s+t.length);return[n,[...l?[{...i,value:l}]:[],...e.slice(r+1)]]}}let xv=/^https?:\/\//i,xb=/^wss?:\/\//i,xy={"@earendil-works/pi-coding-agent":"pi","@anthropic-ai/claude-code":"claude","@openai/codex":"codex","@google/gemini-cli":"gemini"},xw=new Set(["pi","claude","codex","gemini"]),xk=new Set(["install","remove","uninstall","update","list","config"]);function xj(e){return"error"in e?{error:e.error}:{entries:[e],notes:[]}}let xS={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"},xC=new Map([["-l","--local"]]),xN=["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name","oauth-client-registration"],xE=["env","cwd"];function x$(e,t,n,r){let i={positional:[],afterDashDash:[],values:new Map,lists:new Map,seen:new Map};for(let s=0;s<t.length;s++){let l=t[s],o=l.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(l);continue}let a=o.startsWith("--")?o.indexOf("="):-1,d=a>0?o.slice(0,a):o,c=n[d];if(!c){if(i.positional.length>=r.asArgAfter){i.positional.push(l),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=a>0?xI(l,a+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 xI(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 xM=/^[A-Za-z_][A-Za-z0-9_]*=/,xT=/^[^\s:]+:/;function xR(e,t,n,r){for(let i of t??[]){let t=xx(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],xg(t[1],n,!0)])}}function xA(e,t,n,r){for(let i of t??[]){let t=xx(i.parts,":"),s=t?.[0].trim();if(!t||!s)return{code:"cli-invalid-pair",params:{cli:r,option:"--header",value:i.text}};let l=function(e){let t=e.map(e=>({...e})),n=t[0];n?.type==="text"&&(n.value=n.value.replace(/^\s+/,""));let r=t[t.length-1];return r?.type==="text"&&(r.value=r.value.replace(/\s+$/,"")),t}(t[1]);if("authorization"===s.toLowerCase()&&l.every(e=>"text"===e.type&&""===e.value)){e.note("empty-authorization-dropped");continue}e.headers.push([s,xg(l,n,!0)])}}function xL(e){if(void 0!==e&&!0!==e){if("user"===e.text)return"global";if("project"===e.text)return"project"}}function xz(e,t,n,r,i){let s,[l,o,...a]=r;if(!l||!o)return{code:"cli-usage",params:{cli:t}};e.name=l.text;let d=void 0===n||!0===n?void 0:n.text.toLowerCase();if(void 0===d){if("http"==(s=xv.test(o.text)?"http":xb.test(o.text)?"ws":"stdio")&&void 0!==xl(o.text))return xo(l.text,o.text);"http"===s&&"gemini"===t&&e.note("transport-assumed-http")}else s="streamable-http"===d?"http":d;return"sse"===s?xo(l.text,o.text):"ws"===s?{code:"websocket-transport",params:{server:l.text,url:o.text}}:"http"===s?(e.transport="http",e.url=xg(o.parts,i,!1),a.length>0&&e.note("cli-extra-arguments",{cli:t,arguments:a.map(e=>e.text).join(" ")}),"http"):"stdio"!==s?{code:"unsupported-transport",params:{server:l.text,type:s}}:(e.transport="stdio",e.command=xg(o.parts,i,!1),e.args=a.map(e=>xg(e.parts,i,!1)),"stdio")}let xP={"-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 xW(e,t){return"env"===e?xM.test(t.text):xT.test(t.text)&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(t.text)}function xO(e){e.oauth.clientSecret=[{kind:"prompt",id:"oauth.clientSecret",reason:"client-secret",label:"clientSecret",from:"",secret:!0}],e.note("client-secret-prompt")}let xF={"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"--client-secret":{name:"client-secret",kind:"flag"}};function xD(e){let t,n=xe(e)??e.text;try{t=ge(n)}catch(e){return{error:{code:"invalid-json",params:{detail:e instanceof Error?e.message:String(e)}}}}return xt(t)?{value:t}:{error:{code:"no-servers-found"}}}let xB={"--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"}},xH={"-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 x_(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(xU(r),xU(i))}return t}function xU(e){try{return decodeURIComponent(e)}catch{return e}}function xK(e){let t=e.trim();for(let e=0;e<4;e++)try{return ge(t)}catch{let e=xU(t);if(e===t)break;t=e.trim()}}function xq(e){return{error:{code:"install-link-invalid",params:{detail:e}}}}function xV(e){let t=e.get("config");if(!t)return xq("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:xK(n);return xt(r)?{entries:[xc(e.get("name")||void 0,r,{source:"cursor-install-link",flavor:"mcp-servers",rawPi:!1})],notes:[]}:xq("config")}function xZ(e,t,n,r){return xt(e)?{entries:[xc(n,e,{source:t,flavor:"vscode",rawPi:!1,inputs:xh(r)})],notes:[]}:xq("config")}function xJ(e){return{error:{code:"by-name-link",params:{name:e}}}}function xY(e){let t=e.indexOf("?");return t<0?"":e.slice(t+1)}function xG(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:[xQ(void 0,r)],notes:[]};return{error:{code:"unrecognized-input"}}}if(n>3)return xq("nesting");let i=t.protocol.replace(/:$/,"").toLowerCase();switch(i){case"cursor":if(/\/mcp\/install\/?$/.test(t.pathname))return xV(x_(t.search));return xq("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 xJ(xU(t[1]));if(/^mcp\/api\.mcp\.github\.com\//.test(e))return xJ(e.replace(/^mcp\//,""));if(/^mcp\/install\?/.test(e))return xZ(xK(xY(r)),"vscode-install-link");return xq(i)}case"vsweb+mcp":return xZ(xK(xY(r)),"visual-studio-install-link");case"ghapp":if(/^\/\/mcp\/install/.test(r.slice(r.indexOf(":")+1)))return xZ(xK(xY(r)),"copilot-app-install-link");return xq(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 xV(x_(e.search));if("vscode.dev"===r||"insiders.vscode.dev"===r){let t=x_(e.search);if(/^\/redirect\/?$/.test(i)&&t.get("url"))return xG(t.get("url"),n+1);if(/^\/redirect\/mcp\/install\/?$/.test(i)){let e=t.get("config");return e?xZ(xK(e),"vscode-install-link",t.get("name")||void 0,xK(t.get("inputs")??"[]")):xq("config")}}if("aka.ms"===r&&/^\/vs\/mcp-install\/?$/i.test(i))return xZ(xK(e.search.slice(1)),"visual-studio-install-link");if("github.com"===r&&/^\/copilot\/app\/launch\/?$/.test(i)){let t=x_(e.search).get("open");return t?xG(t,n+1):xq("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:[xQ(e,t)],notes:[]}}(t,r,n);default:return{error:{code:"unsupported-url-scheme",params:{scheme:i}}}}}let xX=new Set(["localhost","127.0.0.1","[::1]"]);function xQ(e,t){let n=gP(t)||void 0;if(void 0!==xl(t))return{note:xo(n,t)};let r=new gk("url",!1);return r.transport="http",g$(r,t,!1),e?.protocol!=="http:"||xX.has(e.hostname)||r.note("insecure-http",{host:e.hostname}),{draft:r}}let x0=/[\u200B-\u200D\u2060\uFEFF]/g,x1=/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]\S*)?$/i,x2={"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 x4(e){return new Set(e.fields.flatMap(e=>e.targets.map(e=>gx(e.path))))}function x8(e){var t;let n,r,i,s,l=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=(n=e.replace(x0,"").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=ge(e)}catch(t){try{n=ge(`{${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 xc(n,r,t)});if(Array.isArray(e)){let r=e.filter(xi);return 0===r.length?{error:{code:"no-servers-found"}}:{entries:r.map(e=>xc(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})),notes:n}}if(!xt(e))return{error:{code:"no-servers-found"}};let i=xt(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?gR(t.split("/").pop()??t):void 0,r=Array.isArray(e.remotes)?e.remotes.filter(xt):[],i=r.filter(e=>"string"==typeof e.type&&"http"===xs(e.type)&&"string"==typeof e.url);if(0===i.length){let e=r.find(e=>"sse"===e.type);return e?[{note:xo(n,"string"==typeof e.url?e.url:void 0)}]:[{note:{code:"registry-packages-unsupported",params:xa(n)}}]}return i.map(e=>{let r=new gk("registry-server-json",!1);for(let i of(r.name=n,t&&n!==t&&(r.originalName=t),r.transport="http",r.url=xf(e.url,e.variables,"url.","registry-variable"),Array.isArray(e.headers)?e.headers.filter(xt):[])){if("string"!=typeof i.name||""===i.name)continue;let e=i.name;"string"==typeof i.value&&""!==i.value?r.headers.push([e,xf(i.value,i.variables,`headers.${e}.`,"registry-header")]):r.headers.push([e,[xm(`headers.${e}`,e,"",i,"registry-header")]])}return{draft:r}})}(i),notes:n};if(xt(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(xt(e.servers)){let t=xh(e.inputs);return{entries:r(e.servers,{source:"vscode-json",flavor:"vscode",rawPi:!1,inputs:t}),notes:n}}if(xt(e.mcp)){let t=e.mcp;if(xt(t.servers)){let e=xh(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(xt(e.context_servers))return{entries:Object.entries(e.context_servers).map(e=>{let t,[n,r]=e;return xt(r)&&("extension"===r.source||!xi(r))?{note:{code:"zed-extension-server",params:{server:n}}}:xc(n,xt(r)?(t={...r},delete t.source,t):r,{source:"zed-json",flavor:"zed",rawPi:!1})}),notes:n};if(xi(e))return{entries:[xc(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})],notes:n};let s=Object.values(e);return s.length>0&&s.every(xt)&&s.some(xi)?{entries:r(e,{source:"server-map",flavor:"mcp-servers",rawPi:t}),notes:n}:{error:{code:"no-servers-found"}}}(n,t)}(o,!0===l.rawPi);else if(x1.test(o)){if(!("error"in(s=xG(`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)?xG(o):(e=g7(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&&xy[i]&&e[t+1]?.text==="mcp"&&(n=t,r=xy[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 xj(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=xC.get(e[t].text)??e[t].text;if("--"===s||n.length>=2){n.push(...e.slice("--"===s?t+1:t));break}if(!s.startsWith("--")){n.push(e[t]);continue}let l=s.slice(2),o=xS[l];if(!o)return{error:{code:"cli-unknown-option",params:{cli:"pi",option:s}}};if("flag"===o){r.set(l,!0);continue}let a=e[++t];if(void 0===a)return{error:{code:"cli-option-needs-value",params:{cli:"pi",option:s}}};"list"===o?i.set(l,[...i.get(l)??[],a]):r.set(l,a)}let[s,...l]=n,o=r.get("url");if(!s||""===s.text||void 0===o==(0===l.length))return{error:{code:"cli-usage",params:{cli:"pi"}}};let a=e=>{let t=r.get(e);return!0===t?void 0:t},d=(void 0===o?xN:xE).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 gk("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=xx(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=xg(o.parts,"pi",!1);let e=u("header");if("error"in e)return e;for(let[t,n]of e)c.headers.push([t,xg(n,"pi",!0)]);let t=a("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=a("oauth-client-id"),r=a("oauth-client-secret"),i=a("oauth-callback-port"),s=a("oauth-client-name"),l=a("oauth-client-registration");n&&(c.oauth.clientId=xg(n.parts,"pi",!1)),r&&(c.oauth.clientSecret=xg(r.parts,"pi",!0)),i&&(c.oauth.callbackPort=Number(i.text)),s&&(c.oauth.clientName=xg(s.parts,"pi",!1)),l&&(c.oauth.clientRegistration=l.text),p.url=o.parts.some(e=>"variable"===e.type)?"https://placeholder.invalid/":o.text,(i||s||l)&&(p.oauth={...n?{clientId:n.text}:{},...i?{callbackPort:Number(i.text)}:{},...s?{clientName:s.text}:{},...l?{clientRegistration:l.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,xg(n,"pi",!0)]);let[t,...n]=l;c.command=xg(t.parts,"pi",!1),c.args=n.map(e=>xg(e.parts,"pi",!1));let r=a("cwd");r&&(c.cwd=xg(r.parts,"pi",!1)),p.command=t.text}let h=a("exposure");void 0!==h&&(p.exposure=h.text,c.exposure=gq(h.text)??h.text);let f=a("description");void 0!==f&&(p.description=f.text,c.description=f.text);let m=gG("server",p);return m?{note:{code:"invalid-config",params:{server:s.text,...m}}}:{draft:c}}(t,i.slice(1)));if("claude"===r&&"add"===e)return xj(function(e){let t=x$("claude",e,xP,{asArgAfter:2,variadic:xW});if("error"in t)return{error:t.error};let n=new gk("claude-mcp-add",!1),r=xz(n,"claude",t.values.get("transport"),[...t.positional,...t.afterDashDash],gr);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=xL(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=xA(n,t.lists.get("header"),gr,"claude");if(r)return{error:r};let l=t.values.get("client-id");l&&!0!==l&&(n.oauth.clientId=xg(l.parts,gr,!1)),t.values.has("client-secret")&&xO(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=xR(n,t.lists.get("env"),gr,"claude");if(e)return{error:e}}return{draft:n}}(t));if("claude"===r&&"add-json"===e)return xj(function(e){let t=x$("claude",e,xF,{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=xD(r);if("error"in s)return s;let l=xc(n.text,s.value,{source:"claude-mcp-add-json",flavor:"mcp-servers",rawPi:!1});return"note"in l||(l.draft.scopeHint=xL(t.values.get("scope")),t.values.has("client-secret")&&"http"===l.draft.transport&&!l.draft.oauth.clientSecret&&xO(l.draft)),l}(t));if("claude"===r&&"add-from-claude-desktop"===e)return{error:{code:"claude-desktop-import"}};if("codex"===r&&"add"===e)return xj(function(e){let t=x$("codex",e,xB,{asArgAfter:1/0,stopAfter:2});if("error"in t)return{error:t.error};let n=t.afterDashDash,r=t.lists.get("env")??[],[i,...s]=t.positional,l=n.length>0?n:s,o=t.values.get("url");if(!i||void 0===o==(0===l.length)||n.length>0&&s.length>0)return{error:{code:"cli-usage",params:{cli:"codex"}}};let a=new gk("codex-mcp-add",!1);for(let e of(a.name=i.text,["config","enable","disable"]))t.values.has(e)&&a.note("cli-option-ignored",{cli:"codex",option:t.seen.get(e)});if(t.values.has("oauth-resource")&&a.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!==xl(o.text))return{note:xo(i.text,o.text)};a.transport="http",a.url=xg(o.parts,gn,!1);let e=t.values.get("bearer-token-env-var");e&&!0!==e&&a.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&&(a.oauth.clientId=xg(n.parts,gn,!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"}}};a.transport="stdio";let e=xR(a,r,gn,"codex");if(e)return{error:e};a.command=xg(l[0].parts,gn,!1),a.args=l.slice(1).map(e=>xg(e.parts,gn,!1))}return{draft:a}}(t));if("gemini"===r&&"add"===e)return xj(function(e){let t=x$("gemini",e,xH,{asArgAfter:2});if("error"in t)return{error:t.error};let n=new gk("gemini-mcp-add",!1),r=xz(n,"gemini",t.values.get("transport"),[...t.positional,...t.afterDashDash],gi);if("string"!=typeof r)return"cli-usage"===r.code?{error:r}:{note:r};if(n.scopeHint=xL(t.values.get("scope")),"http"===r){t.lists.has("env")&&n.note("cli-option-wrong-transport",{cli:"gemini",option:"--env",transport:"http"});let e=xA(n,t.lists.get("header"),gi,"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=xR(n,t.lists.get("env"),gi,"gemini");if(e)return{error:e}}let i=t.values.get("timeout");for(let e of(i&&!0!==i&&gD(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 xp(n,s("include-tools"),s("exclude-tools")),{draft:n}}(t));if("add"===e||"install"===e)return{error:{code:"cli-unsupported",params:{cli:r}}};if(xw.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]&&xk.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=xI(e[n],10)}if(!r)return{error:{code:"cli-option-needs-value",params:{cli:"code",option:"--add-mcp"}}};let s=xD(r);if("error"in s)return s;t.push(xc(void 0,s.value,{source:"vscode-add-mcp",flavor:"vscode",rawPi:!1}))}return{entries:t,notes:[]}}(e.slice(1)):xj(function(e){let t=new gk("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,xg(r.value,gn,!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=xg(i.parts,gn,!1),t.args=e.slice(n+1).map(e=>xg(e.parts,gn,!1));let s=e.slice(n+1).map(e=>e.text),l=s.some(e=>/^mcp-remote(?:@|$)/.test(e))?s.find(e=>xv.test(e)):void 0;return l&&t.note("mcp-remote-bridge",{url:l}),{draft:t}}(e))}(e.words):{error:function(e){let{code:t,...n}=e;return Object.keys(n).length>0?{code:x2[t],params:n}:{code:x2[t]}}(e.error)}}if("error"in s)return{ok:!1,notes:[s.error]};let a=[...s.notes],d=[],c=[...l.takenNames??[]],u=new Set;for(let e of s.entries){if("note"in e){a.push(e.note);continue}let n=function(e){let t,n=new gN(e);if("stdio"===e.transport&&e.command&&""!==gj(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||""===gj(e.url))return{note:{code:"no-command-or-url",...e.name?{params:{server:e.name}}:{}}};let r=n.encode(["url"],e.url),i={};for(let[t,r]of e.headers)i[t]=n.encode(["headers",t],r);let s={},{clientId:l,clientSecret:o,callbackPort:a,clientName:d,clientRegistration:c,callbackUrl:u,scope:p,authServerMetadataUrl:h}=e.oauth;l&&(s.clientId=n.encode(["oauth","clientId"],l)),o&&(s.clientSecret=n.encode(["oauth","clientSecret"],o)),void 0!==a&&(s.callbackPort=a),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){a.push(n.note);continue}let r=n.server,i=r.name,s=!i;s&&(i=function(e){if("url"in e)return gP(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&&gP(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=gO(t,new Set(["-p","--package","-c","--call"]));return e?gR(e):""}case"pnpm":case"yarn":case"bun":case"npm":{let e=t.findIndex(e=>"dlx"===e||"exec"===e||"x"===e),n=e>=0?gO(t.slice(e+1),new Set(["-p","--package"])):void 0;return n?gR(n):""}case"uvx":case"pipx":{let e=gO("pipx"===n&&"run"===t[0]?t.slice(1):t,new Set(["--from","--with","--python","-p","--index-url","--spec"]));return e?gR(e):""}case"uv":{let e=t.indexOf("run"),n=e>=0?gO(t.slice(e+1),new Set(["--with","--directory","--python","-p","--from","--project"])):void 0;return n?gF(n):""}case"docker":case"podman":{let e=t.indexOf("run"),n=e>=0?gO(t.slice(e+1),gW):void 0;if(!n)return"";let r=n.split("/").pop().replace(/[:@].*$/,"");return gL(r)||r}case"python":case"python3":case"py":{let e=t.indexOf("-m");if(e>=0&&t[e+1])return gR(t[e+1].replace(/_/g,"-"));let n=gO(t,new Set(["-X","-W"]));return n?gF(n):""}case"node":case"deno":case"tsx":case"ts-node":{let e=gO("deno"===n&&"run"===t[0]?t.slice(1):t,new Set(["-r","--require","--import","--loader"]));return e?gF(e):""}default:return gL(n.replace(/_/g,"-"))||n}}(e.command,t)}(r.config))&&r.notes.push({code:"name-derived",params:{name:i}});let l=(t=i,gI.test(t))?i:i.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/-{2,}/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,48).replace(/[-_]+$/g,"")||"server";l!==i&&i&&(r.originalName=r.originalName??i,r.notes.push({code:"name-sanitized",params:{original:i,name:l}}));let o=gM(l,s?[...c,...u]:u);o!==l&&(r.notes.push({code:"name-deduplicated",params:{original:l,name:o}}),l=o),!s&&c.includes(l)&&r.notes.push({code:"name-taken",params:{name:l,suggestedName:gM(l,[...c,...u])}}),r.name=l;let p=gG(l,function(e){let t=x4(e),n=JSON.parse(JSON.stringify(e.config));t.has(gx(["url"]))&&(n.url="https://placeholder.invalid/");let r=n.oauth;return r&&t.has(gx(["oauth","callbackUrl"]))&&delete r.callbackUrl,n}(r));if(p){a.push({code:"invalid-config",params:{server:l,...p}});continue}!function(e){let t=x4(e);for(let n of vn(e.config))t.has(gx(n))||e.notes.push({code:"literal-secret",params:{field:gv(n)}});let n=e.config;if("url"in n){for(let[t,r]of Object.entries(n.headers??{})){let n=gp(r);n.length>0&&e.notes.push({code:"header-env-reference",params:{header:t,names:n.join(", ")}})}let t=gp(n.oauth?.clientSecret??"");t.length>0&&e.notes.push({code:"client-secret-env-reference",params:{names:t.join(", ")}})}}(r),u.add(l),d.push(r)}return 0===d.length?{ok:!1,notes:a.length>0?a:[{code:"no-servers-found"}]}:{ok:!0,servers:d,notes:a}}let x3=/^[A-Za-z_][A-Za-z0-9_]*$/;function x5(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 x6(e){let t=x4(e);return vn(e.config).filter(e=>gb(e)&&!t.has(gx(e)))}function x9(e){return"string"==typeof e&&""===e.trim()?"missing":"name"}let x7=/^(?:bearer|basic|token)\s+/i;function ve(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.parse(JSON.stringify(e.config)),i=new Map,s=[],l=new Map(x6(e).map(e=>[gv(e),e])),o=[];for(let[e,t]of Object.entries(n)){let n="string"==typeof t?t.trim():"",r=l.get(e);r?x3.test(n)?o.push([r,n]):s.push({code:"field-reference-invalid",params:{field:e,problem:x9(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():"";x3.test(r)?"select"!==n.kind&&n.targets.every(e=>gb(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:x9(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 a=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&&a.add(gv(e.path));let s=gx(e.path);if(d.has(s))continue;if(d.add(s),e.parts.some(e=>"string"!=typeof e&&void 0===i.get(e.field))){x5(r,e.path,void 0);continue}let l="";for(let t of e.parts){var c,u,p,h;l+="string"==typeof t?t:(c=i.get(t.field),u=e.path,p=""===l,h=e.encoding,"reference"in c?`$\{${c.reference}}`:"uri-component"===h?encodeURIComponent(c.text):gb(u)?gc(c.text,{atStart:p}):c.text)}x5(r,e.path,l)}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(x7)?.[0]??"":"";x5(r,e,`${i}$\{${t}}`)}for(let e of vn(r))a.add(gv(e));return{ok:!0,config:r,secretPaths:[...a]}}let vt=["command","args","env","cwd","url","headers","oauth"];function vn(e){let t=[];for(let n of function(e){if(!m9(e))return[];let t=[];for(let n of["env","headers"]){let r=e[n];if(m9(r))for(let[e,i]of Object.entries(r))"string"==typeof i&&m7(i)&&""!==i&&(mF(e)||/^(?:bearer|basic|token)\s+\S/i.test(i)||m4(i,mZ).masked)&&t.push({kind:"env"===n?"env":"header",name:e})}let n=m9(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&""!==n&&m7(n)&&t.push({kind:"oauth-client-secret"}),"string"==typeof e.url&&m0(e.url,mG).masked&&t.push({kind:"url"}),"string"==typeof e.command&&m4(e.command,mG).masked&&t.push({kind:"command"}),Array.isArray(e.args)&&m6(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:""):[];m6(n).args.forEach((e,r)=>{e!==n[r]&&t.push(["args",r])})}}return t.sort((e,t)=>vt.indexOf(e[0])-vt.indexOf(t[0]))}let vr="PI_WEB_PASSWORD";function vi(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function vs(e){return vi(e)?Object.entries(e).filter(e=>"string"==typeof e[1]):[]}function vl(e){if(!vi(e))return[];if(!("url"in e))return vs(e.env).map(e=>{let[t,n]=e;return{kind:"env",name:t,value:n}});let t=vs(e.headers).map(e=>{let[t,n]=e;return{kind:"header",name:t,value:n}}),n=vi(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&t.push({kind:"oauth-client-secret",value:n}),t}let vo={text:"",rawPi:!1,server:0,values:{},references:{},secretReferences:{}};function va(e,t,n){let r=x8(e,{rawPi:t});if(!r.ok)return;let i=r.servers[Math.min(n,r.servers.length-1)],{config:s}=i,l="url"in s?["url",s.url]:["command",s.command,s.args??[]];return JSON.stringify([i.source,i.originalName??i.name,l])}function vd(e,t){let n={...e,...t},r=va(e.text,e.rawPi,e.server);if(void 0!==r&&r===va(n.text,n.rawPi,e.server))return n;let i={...n,server:0,values:{},references:{},secretReferences:{}};return delete i.name,i}function vc(e){return gt[e.code]??"warning"}function vu(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?fC(t):t;if("string"==typeof i.field&&e.code.startsWith("field-")){let e=r.find(e=>e.id===i.field);e&&(s.field=fC(e.label))}"invalid-config"===e.code&&(s.problem=t("tool-exposure"===(n=String(i.problem??"no-command-or-url"))&&void 0!==i.tool?"mcp.importProblem.tool-exposure.tool":"args"===n&&void 0!==i.index?"mcp.importProblem.args.index":`mcp.importProblem.${n}`,s)),"cli-option-wrong-transport"===e.code&&("stdio"===i.transport||"http"===i.transport)&&(s.transport=t(`mcp.transport.${i.transport}`));let l=t(function(e){let t=e.params??{};switch(e.code){case"field-reference-invalid":return`mcp.importNote.field-reference-invalid.${"target"===t.problem||"missing"===t.problem?t.problem:"name"}`;case"sse-transport":return void 0===t.suggestedUrl?"mcp.importNote.sse-transport":"mcp.importNote.sse-transport.suggested";case"timeout-unit-guessed":return`mcp.importNote.timeout-unit-guessed.${"milliseconds"===t.unit?"milliseconds":"seconds"}`;case"tool-filter-imported":return`mcp.importNote.tool-filter-imported.${"exclude"===t.mode?"exclude":"include"}`;default:return`mcp.importNote.${e.code}`}}(e),s);return"string"==typeof s.server?t("mcp.importNote.forServer",{server:s.server,note:l}):l}let vp={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"},vh={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"},vf=JSON.stringify({command:"uvx",args:["mcp-server-fetch"]}),vm=JSON.stringify({name:"fetch",command:"uvx",args:["mcp-server-fetch"]}),vg=[{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 '${vm}'`},{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(vf)}`},{source:"vscode-install-link",text:`vscode:mcp/install?${encodeURIComponent(vm)}`},{source:"visual-studio-install-link",text:`vsweb+mcp:/install?${encodeURIComponent(vm)}`},{source:"copilot-app-install-link",text:`ghapp://mcp/install?${encodeURIComponent(vm)}`}];function vx(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?fC(r):r.field===e.id?n:`‹${fC(t.find(e=>{let{id:t}=e;return t===r.field})?.label??r.field)}›`).join("")}))].join(", ")}function vv(e){return"select"!==e.kind&&e.targets.every(e=>gb(e.path)&&void 0===e.encoding)}let vb=/^[A-Za-z_][A-Za-z0-9_]*$/;function vy(){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 vb.test(r)?r:void 0}let vw=/^(?:proxy-)?authorization$/i;function vk(e,t){let n=function(e,t){if(e.startsWith("env.")){let t=e.slice(4);return vb.test(t)?t:vy(t)}let n=function(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];return vy(t,...n)??vy(...n)};if(e.startsWith("headers.")){let t=e.slice(8);return n(vw.test(t)?"TOKEN":t.replace(/^x-/i,""))}if("oauth.clientSecret"===e)return n("CLIENT_SECRET")}(e,t);return n===vr?void 0:n}function vj(e){return e.startsWith("env.")||e.startsWith("headers.")||"oauth.clientSecret"===e}function vS(e,t){let n=e;for(let e of t)n=n.split(e).join(mT);return{text:n,masked:n!==e}}function vC(e){let{kind:t,name:n}=e;return void 0===n?{kind:t}:{kind:t,name:n}}function vN(e,t){let n=t.files.find(t=>t.scope===e),r=n?.problems.find(f1);return n&&r?{kind:"file-problem",path:n.path,reason:r.reason}:void 0}function vE(e,t){return e.servers.filter(e=>e.scope===t).map(e=>e.name)}function v$(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 vI(e,t,n){switch(e.kind){case"trust-too-broad":return t(vT[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(vM[e.kind])}}let vM={"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"},vT={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 vR(e){return fC(e1(e))}function vA(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}let vL=[{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"}],vz=new Set(["name-derived","name-sanitized","name-deduplicated","name-taken"]);function vP(e){let{notes:t,fields:n=[]}=e,{t:i}=(0,t_.s)();if(0===t.length)return null;let s={error:0,warning:1,info:2},l=[...t].sort((e,t)=>s[vc(e)]-s[vc(t)]);return(0,r.jsx)("ul",{className:"mcp-add-notes",children:l.map((e,t)=>(0,r.jsx)("li",{className:`mcp-add-note is-${vc(e)}`,children:vu(e,i,n)},`${t}\0${e.code}`))})}let vW={"server-invalid":"mcp.add.refused.server-invalid","web-password":"mcp.add.blocked.web-password"};function vO(e){let{data:t,cwd:n,draft:s,busy:l,controlsBusy:o,failure:a,onDraftChange:d,onSubmit:c,onTrustProject:u}=e,{t:p}=(0,t_.s)(),h=(0,i.useId)(),f=(0,i.useId)(),m=(0,i.useMemo)(()=>(function e(t,n,r){let i,s=function(e,t){let n=e=>({kind:"blocked",block:e});if(!t)return n({kind:"no-project"});let r=e.project;if(!r)return n({kind:"project-not-listed"});let i=r.trust;if(!i||void 0!==i.decisionError)return n({kind:"trust-unreadable"});if(!0===i.decision)return{kind:"write"};if(!1===i.decision)return n({kind:"untrusted-decision"});if(i.requiresTrust)return n({kind:"project-untrusted",trustable:f3(r)});let s=r.trustFolder;return s?s.allowed?{kind:"trust-and-write",folder:r.cwd}:n("trust-too-broad"===s.reason?{kind:"trust-too-broad",breadth:s.breadth}:{kind:"folder-not-fresh"}):n({kind:"project-untrusted",trustable:!1})}(n,r),l=e=>x8(t.text,{rawPi:t.rawPi,takenNames:vE(n,e)}),o=l(t.scope??"global"),a=o.ok?o.servers[Math.min(t.server,o.servers.length-1)]:void 0,d=t.scope??(a?.scopeHint==="project"&&"write"===s.kind?"project":"global");d!==(t.scope??"global")&&(a=(o=l(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=mm(n.mcp);if(!a)return{...c,submitBlock:{kind:u?"mcp-off":"nothing"}};let p=t.name??a.name,h=function(e,t){let n={};for(let r of e.fields){let e=t.references[r.id];void 0!==e&&vv(r)?n[r.id]={reference:e}:void 0!==t.values[r.id]&&(n[r.id]=t.values[r.id])}return n}(a,t),f=x6(a).map(gv),m=Object.fromEntries(f.flatMap(e=>{let n=t.secretReferences[e];return void 0===n?[]:[[e,n]]})),g=ve(a,h,m),x={};if(!g.ok)for(let e of g.notes){let t=e.params?.field;"field-required"===e.code||"string"!=typeof t||t in x||(x[t]=e)}let v=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={};for(let n of e.fields){let e=t[n.id];"object"==typeof e?r[n.id]=vb.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=ve(e,r,Object.fromEntries(Object.entries(n).map(e=>{let[t,n]=e;return[t,vb.test(n.trim())?n:"VALUE"]})));return i.ok?i.secretPaths:[]}(a,h,m),b=function(e,t,n){let r=n?.ok?n.config:e.config,i=n?.ok?function(e,t){let n=new Set;for(let r of e.fields){let e=t[r.id];if("password"!==r.kind||"string"!=typeof e||""===e.trim())continue;let i=e.trim();n.add(i),n.add(i.replace(/\$/g,"$$$$")),n.add(encodeURIComponent(i))}return[...n].filter(e=>""!==e).sort((e,t)=>t.length-e.length)}(e,t):[],s=!1!==r.enabled,l={source:e.source,commandFields:vl(r).filter(e=>{let{value:t}=e;return gu(t)}).map(vC),variableReferences:vl(r).map(e=>({...vC(e),variables:gp(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=vS(r.url,i);return{...l,transport:"http",target:fC(e.text),envNames:[],headerNames:Object.keys(r.headers??{}),masked:e.masked}}let o=vS(f$(r.command,r.args??[]),i);return{...l,transport:"stdio",target:o.text,...void 0!==r.cwd?{cwd:fC(r.cwd)}:{},envNames:Object.keys(r.env??{}),headerNames:[],masked:o.masked}}(a,h,g),y=g.ok?gG(p,g.config):void 0,w="blocked"===s.kind?s.block:v.length>0?{kind:"secret",fields:v,fixed:!v.every(vj)}:vN("project",n),k=vE(n,d),j=n.files.find(e=>e.scope===d);if(u)i={kind:"mcp-off"};else if(gI.test(p))if(k.includes(p))i={kind:"name-taken",name:p,suggestedName:gM(p,k),...j?{path:j.path}:{}};else if(g.ok)if(y)i={kind:"config-invalid",note:{code:"invalid-config",params:"url"===y.problem?{...y,url:b.target}:y}};else if(void 0!==function(e,t){for(let{value:n,...r}of vl(e))if(t.isCommandConfigValue(n)?n.toUpperCase().includes(vr):t.getConfigValueEnvVarNames(n).some(e=>e.toUpperCase()===vr))return r}(g.config,{isCommandConfigValue:gu,getConfigValueEnvVarNames:gp}))i={kind:"web-password"};else if("project"===d&&w)i={kind:"scope",block:w};else{let e=vN(d,n);e&&(i={kind:"scope",block:e})}else{let e=e=>{let t=String(e.params?.field??"");return a.fields.find(e=>e.id===t)?.label??t},t=g.notes.filter(e=>"field-required"===e.code||"field-reference-invalid"===e.code&&e.params?.problem==="missing");i=t.length>0?{kind:"fields",fields:[...new Set(t.map(e))]}:{kind:"field-invalid",fields:[...new Set(g.notes.map(e))]}}else i={kind:"name-invalid"};return void 0===t.scope&&"project"===d&&w?e({...t,scope:"global"},n,r):{parsed:o,server:a,name:p,scope:d,projectMode:s,...w?{projectBlock:w}:{},values:h,pasteSecrets:f,secretReferences:m,fill:g,fieldProblems:x,secretPaths:v,preview:b,...i?{submitBlock:i}:{},trustFolder:"project"===d&&"trust-and-write"===s.kind}})(s,t,n),[s,t,n]),g=(0,i.useMemo)(()=>(function(e){let t=x8(e,{rawPi:!0});if(!t.ok)return!1;let n=x8(e,{rawPi:!1});return t.servers.some((e,t)=>e.rawPi&&!(n.ok&&n.servers[t]?.rawPi))})(s.text),[s.text]),{parsed:x,server:v,preview:b,projectBlock:y,submitBlock:w}=m,k=v?[...v.notes,...x.notes].filter(e=>"literal-secret"!==e.code||!m.pasteSecrets.includes(String(e.params?.field))):[],j=void 0!==s.name&&s.name!==v?.name?[]:k.filter(e=>vz.has(e.code)),S=k.filter(e=>!vz.has(e.code)),C=!l&&!o&&void 0===w,N=()=>{C&&c(v$(s,m))},E=e=>d({...s,...e}),$=t.files.find(e=>e.scope===m.scope)?.path??("project"===m.scope&&n?`${n.replace(/[\\/]+$/,"")}/.pi/mcp.json`:"mcp.json"),I=w&&(""!==s.text.trim()||"mcp-off"===w.kind)?function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];switch(e.kind){case"mcp-off":return t("mcp.reason.mcp-off");case"nothing":return t("mcp.add.blocked.nothing");case"name-invalid":return t("mcp.add.nameInvalid");case"name-taken":return t("mcp.add.nameTaken",{name:fC(e.name),path:e.path?vR(e.path):"mcp.json"});case"fields":return t("mcp.add.blocked.fields",{fields:e.fields.map(fC).join(", ")});case"field-invalid":return t("mcp.add.blocked.fieldsInvalid",{fields:e.fields.map(fC).join(", ")});case"config-invalid":return vu(e.note,t,n);case"web-password":return t("mcp.add.blocked.web-password");case"scope":return vI(e.block,t,vR)}}(w,p,v?.fields):void 0,M=y?.kind==="project-untrusted"&&y.trustable&&u,T=b?"http"===b.transport?b.headerNames:b.envNames:[];return(0,r.jsxs)(pX,{title:p("mcp.add.title"),catalogs:vL,target:(0,r.jsxs)(pY,{value:m.scope,label:p("config.saveTo"),options:[{value:"global",label:vA("global",p)},{value:"project",label:vA("project",p),disabled:void 0!==y&&"project"!==m.scope}],path:vR($),disabledReason:y?vI(y,p,vR):null,onChange:e=>E({scope:e}),children:[M&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(p3,{size:"small",onClick:u,children:p("mcp.trust.trustButton")})}),m.trustFolder&&"trust-and-write"===m.projectMode.kind&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:p("mcp.add.trustExplain",{path:vR(m.projectMode.folder)})})]}),inputLabel:p("mcp.add.inputLabel"),inputId:"mcp-add-source",placeholder:p("mcp.add.placeholder"),value:s.text,canSubmit:C,onValueChange:e=>d(vd(s,{text:e})),onSubmit:N,examplesLabel:p("mcp.add.examples"),examples:""===s.text.trim()?vg.map(e=>{let{source:t,text:n}=e;return{label:p(vh[t]),value:n}}):[],multiline:!0,children:[g&&(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:s.rawPi,onChange:e=>d(vd(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)(vP,{notes:x.notes}),x.ok&&x.servers.length>1&&(0,r.jsxs)(pK,{label:p("mcp.add.serverLabel"),children:[(0,r.jsx)("select",{className:"mcp-add-input","aria-label":p("mcp.add.serverLabel"),value:String(x.servers.indexOf(v??x.servers[0])),onChange:e=>E({server:Number(e.target.value),name:void 0,values:{},references:{},secretReferences:{}}),children:x.servers.map((e,t)=>(0,r.jsx)("option",{value:t,children:fC(e.name)},`${t}\0${e.name}`))}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.serverCount",{count:x.servers.length})})]}),v&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(pK,{label:p("config.name"),children:(0,r.jsx)("input",{id:f,className:"mcp-add-input","aria-label":p("config.name"),value:m.name,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>E({name:e.target.value})})}),(0,r.jsx)(vP,{notes:j,fields:v.fields}),w?.kind==="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(p3,{size:"small",onClick:()=>E({name:w.suggestedName}),children:p("mcp.add.useName",{name:fC(w.suggestedName)})})})]}),v&&b&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(pU,{children:p("mcp.add.preview")}),(0,r.jsxs)(pq,{children:[(0,r.jsx)(pV,{label:p("mcp.add.readAs"),children:p(vh[b.source])}),(0,r.jsx)(pV,{label:p("mcp.detail.transport"),children:p(`mcp.transport.${b.transport}`)}),(0,r.jsx)(pV,{label:"http"===b.transport?p("mcp.detail.url"):p("mcp.detail.command"),tone:"plain",mono:!0,children:b.target}),"stdio"===b.transport&&void 0!==b.cwd&&(0,r.jsx)(pV,{label:p("mcp.detail.cwd"),mono:!0,children:b.cwd}),T.length>0&&(0,r.jsx)(pV,{label:"http"===b.transport?p("mcp.detail.headers"):p("mcp.detail.env"),children:(0,r.jsx)(vF,{names:T})}),b.commandFields.length>0&&(0,r.jsx)(pV,{label:p("mcp.detail.shellCommands"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.server.commandFields")}),(0,r.jsx)("span",{className:"mcp-config-chips",children:b.commandFields.map(e=>{let t=fT(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})]})}),b.variableReferences.length>0&&(0,r.jsx)(pV,{label:p("mcp.detail.variables"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("http"===b.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables")}),(0,r.jsx)("span",{className:"mcp-config-chips",children:fL(b.variableReferences).map(e=>{let{variable:t,field:n}=e,i=fT(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p("mcp.server.variableIn",{variable:fC(t),field:p(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[b.unfilled&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.previewUnfilled")}),b.masked&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.server.masked")})]}),(0,r.jsx)(vP,{notes:S,fields:v.fields}),v.fields.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(pU,{children:p("mcp.add.fields")}),v.fields.map(e=>{var t;let n;return(0,r.jsx)(vD,{field:e,fields:v.fields,draft:s,suggestedName:(t=m.name,(n=e.targets[0])?vk(gv(n.path),t):void 0),problem:m.fieldProblems[e.id],onDraftChange:d},e.id)})]}),m.pasteSecrets.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(pU,{children:p("mcp.add.secrets")}),m.pasteSecrets.map(e=>{var t,n;let i;return(0,r.jsx)(vB,{label:e,draft:s,suggestedName:vk(e,m.name),stored:m.fill?.ok?(t=m.fill.config,void 0!==(i="oauth.clientSecret"===(n=e)?"url"in t?t.oauth?.clientSecret:void 0:n.startsWith("headers.")?"url"in t?t.headers?.[n.slice(8)]:void 0:n.startsWith("env.")&&"command"in t?t.env?.[n.slice(4)]:void 0)&&mZ(i)?i:void 0):void 0,problem:m.fieldProblems[e],onDraftChange:d},e)})]})]}),(0,r.jsx)(p3,{variant:"primary",className:"is-pushed-right",disabled:!C,"aria-busy":l||void 0,"aria-describedby":I?h:void 0,onClick:N,children:l?p("mcp.add.adding"):m.trustFolder?p("mcp.add.buttonTrust"):p("mcp.add.button")}),I&&(0,r.jsx)("p",{id:h,className:`mcp-config-line ${w?.kind==="scope"?"is-warning":"is-dim"}`,children:I}),v&&!w&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:p("mcp.add.afterAdd")}),a&&(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(vT[e.breadth.kind],{path:vR(e.breadth.path)});if("secret-global-only"===e.reason&&e.fields)return t(e.fields.every(vj)?"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:fC(e.name),path:e.path?vR(e.path):"mcp.json"});let n=e.reason?vW[e.reason]:void 0;return n?t(n,{error:fC(e.error)}):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):fC(e.error)}(a,p)]}),a.trustKept&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.trustKept",{folder:vR(a.trust?.decisionPath??n??"")})}),a.notes&&a.notes.length>0&&(0,r.jsx)(vP,{notes:a.notes,fields:v?.fields}),"name-taken"===a.reason&&a.suggestedName&&w?.kind!=="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(p3,{size:"small",onClick:()=>E({name:a.suggestedName}),children:p("mcp.add.useName",{name:fC(a.suggestedName)})})}),"host-env-confirm"===a.reason&&a.names&&a.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:a.names.map(fC).join(", ")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(p3,{variant:"danger",size:"small",disabled:l||o||void 0!==w,onClick:()=>c(v$(s,m,a.names)),children:p("mcp.add.hostEnv.confirm")})})]})]})]})}function vF(e){let{names:t}=e,{t:n}=(0,t_.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:fC(e)},e))}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.detail.valuesHidden")})]})}function vD(e){let t,{field:n,fields:s,draft:l,suggestedName:o,problem:a,onDraftChange:d}=e,{t:c}=(0,t_.s)(),u=(0,i.useId)(),p=a?{"aria-invalid":!0,"aria-describedby":u}:{},h=vv(n),f=h?l.references[n.id]:void 0,m=void 0!==f,g=fC(n.label),x=l.values[n.id]??n.defaultValue??"",v=vp[n.reason],b=n.optional&&1===(t=new Set(n.targets.map(e=>{let{path:t}=e;return"headers"===t[0]?t[1]:void 0}))).size?[...t][0]:void 0,y=m?f&&!a?vx(n,s,"${"+f+"}",!0):void 0:vx(n,s,`‹${c("mcp.add.field.slot")}›`),w=e=>d({...l,values:{...l.values,[n.id]:e}}),k=e=>{let t={...l.references};void 0===e?delete t[n.id]:t[n.id]=e,d({...l,references:t})};return(0,r.jsxs)("div",{className:"mcp-add-field",children:[(0,r.jsx)(pK,{label:g,children:m?(0,r.jsx)("input",{className:"mcp-add-input","aria-label":c("mcp.add.field.variableName",{field:g}),value:f,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":g,value:x,...p,onChange:e=>w(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:fC(e)},e))]}):(0,r.jsx)("input",{className:"mcp-add-input",type:"password"===n.kind?"password":"text","aria-label":g,value:x,autoComplete:"off",placeholder:n.placeholder?fC(n.placeholder):void 0,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...p,onChange:e=>w(e.target.value)})}),a&&(0,r.jsx)("span",{id:u,className:"mcp-config-line is-error",children:vu(a,c,[n])}),(0,r.jsxs)("span",{className:"mcp-config-lines",children:[n.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:fC(n.description)}),v&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:c(v)}),m?(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:b?c("mcp.add.field.optionalHeader",{name:fC(b)}):c("mcp.add.field.optional")})]})]}),h&&(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:m,onChange:e=>k(e.target.checked?o??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:c("mcp.add.field.useVariable")})]})]})}function vB(e){let{label:t,draft:n,suggestedName:s,stored:l,problem:o,onDraftChange:a}=e,{t:d}=(0,t_.s)(),c=(0,i.useId)(),u=n.secretReferences[t],p=void 0!==u,h=fC(t),f=e=>{let r={...n.secretReferences};void 0===e?delete r[t]:r[t]=e,a({...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=>f(e.target.checked?s??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("mcp.add.field.useVariable")})]}),p&&(0,r.jsx)(pK,{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=>f(e.target.value)})}),o&&(0,r.jsx)("span",{id:c,className:"mcp-config-line is-error",children:vu(o,d)}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p?void 0!==l?d("mcp.add.secret.storedAs",{value:fC(l)}):d("mcp.add.field.variableHint"):d("mcp.add.secret.asPasted")})]})}let vH=new Set(["done","failed","cancelled","expired"]);function v_(e){var t;return e?.flow!==void 0&&!e.gone&&(t=e.flow.phase,!vH.has(t))}let vU={"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"},vK={"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"},vq={connecting:"mcp.signIn.phase.connecting",starting:"mcp.signIn.phase.starting",finishing:"mcp.signIn.phase.finishing"},vV={"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 vZ(e,t,n){var r;let i={...e,flow:t,deadlineAt:n+t.expiresInMs,gone:!1};return r=t.phase,vH.has(r)&&(delete i.pasteError,delete i.cancelError,i.pasting&&(i.pasting=!1),i.cancelling&&(i.cancelling=!1)),i}function vJ(e){return"sign-in-unknown"===e.reason}async function vY(e,t,n,r){var i;let s,l;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{l=await s.json()}catch{return{ok:!1,error:{error:`HTTP ${s.status}`}}}return s.ok&&null!==(i=l)&&"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:l}:{ok:!1,error:mr(l,s.status)}}function vG(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},l=t.method??"GET";return mi(r=>vY(e,t,n,r),()=>({ok:!1,error:{error:`${l} ${e} did not answer within ${i} ms`,timedOut:!0}}),i,r,s)}function vX(e){return`/api/mcp/sign-in/${encodeURIComponent(e)}`}function vQ(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?vK[e.reason]:void 0;return r?t(r):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function v0(e){let{server:t,run:n,block:s,signOutBlock:l,blockSaidBy:o,signOutBlockSaidBy:a,controlsBusy:d,signingOut:c,onSignIn:u,onSignOut:p,onPaste:h,onCancel:f}=e,{t:m}=(0,t_.s)(),g=(0,i.useId)(),x=(0,i.useId)(),v=(0,i.useId)(),b=(0,i.useRef)(null),y=(0,i.useRef)(null),w=v_(n),k=(0,i.useRef)(w);if((0,i.useEffect)(()=>{let e=k.current;k.current=w,!e&&w?to(document,y.current):e&&!w&&to(document,b.current)},[w]),!t.usesOAuth)return void 0===t.authProvider&&t.headerNames.some(e=>"authorization"===e.toLowerCase())?null:(0,r.jsx)(pV,{label:m("mcp.detail.signIn"),children:void 0!==t.authProvider?m("mcp.signIn.provider",{provider:fC(t.authProvider)}):m("mcp.signIn.header")});let j=n?.flow,S=n?.starting===!0,C=void 0!==j&&(j.scope!==t.scope||j.name!==t.name),N=(t.oauthStateStored??t.signedIn)!==!1,E=S||c||void 0!==s,$=d||S||void 0!==l,I=j?.phase==="finishing";return(0,r.jsx)(pV,{label:m("mcp.detail.signIn"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line",children:m(!0===t.signedIn?"mcp.signIn.signedIn":!1===t.signedIn?t.oauthStateStored?"mcp.signIn.registrationOnly":"mcp.signIn.notSignedIn":"mcp.signIn.unknown")}),j&&w&&C&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:m("mcp.signIn.shared",{name:fC(j.name)})}),j&&w&&("authorize"===j.phase?(0,r.jsx)(v1,{flow:j,pasting:n?.pasting===!0,pasteError:n?.pasteError,onPaste:e=>h(t,j.flowId,e)},j.flowId):(0,r.jsx)("span",{role:"status",className:"mcp-config-line",children:m(vq[j.phase]??"mcp.signIn.phase.connecting")})),j&&w&&I&&(0,r.jsx)("span",{id:v,className:"mcp-config-line is-dim",children:m("mcp.signIn.phase.noCancel")}),j&&!w&&!n?.gone&&(0,r.jsx)(v2,{flow:j,shared:C}),n?.gone&&(0,r.jsx)("span",{role:"alert",className:"mcp-config-line is-warning",children:m("mcp.signIn.gone")}),n?.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[m("mcp.signIn.requestFailed")," ",vQ(n.error,m)]}),w&&n?.cancelError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[m("mcp.signIn.cancelFailed")," ",vQ(n.cancelError,m,"mcp.signIn.cancelTimedOut")]}),n?.signOutError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[m("mcp.signIn.signOutFailed")," ",vQ(n.signOutError,m,"mcp.actionTimedOut")]}),n?.signedOut&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line",children:m(n.signedOut.removed?"mcp.signIn.signedOutDone":"mcp.signIn.signedOutNothing")}),s&&!o&&(0,r.jsx)("span",{id:g,className:"mcp-config-line is-dim",children:m(vU[s])}),!s&&l&&!a&&N&&!w&&(0,r.jsx)("span",{id:x,className:"mcp-config-line is-dim",children:m(vU[l])}),(0,r.jsxs)("div",{className:"mcp-sign-in-actions",children:[w&&j?(0,r.jsx)(p3,{ref:y,size:"small",disabled:n?.cancelling===!0||I,"aria-busy":n?.cancelling===!0||void 0,"aria-describedby":I?v:void 0,onClick:()=>f(t,j.flowId),children:m(n?.cancelling?"mcp.signIn.cancelling":"mcp.signIn.cancel")}):(0,r.jsx)(p3,{ref:b,size:"small",variant:"primary",disabled:E,"aria-busy":S||void 0,"aria-describedby":s?o??g:void 0,onClick:()=>u(t),children:m(S?"mcp.signIn.starting":"mcp.signIn.button")}),N&&!w&&(0,r.jsx)(p3,{size:"small",disabled:$,"aria-busy":c||void 0,"aria-describedby":l?s?o??g:a??x:void 0,onClick:()=>p(t),children:m(c?"mcp.signIn.signingOut":"mcp.signIn.signOut")})]}),!s&&!w&&N&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:m("mcp.signIn.replaces")}),N&&!l&&!w&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:m("mcp.signIn.signOutExplain")})]})})}function v1(e){let{flow:t,pasting:n,pasteError:s,onPaste:l}=e,{t:o}=(0,t_.s)(),[a,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&&to(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)(hc,{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:fC(p)})]}):(0,r.jsxs)(r.Fragment,{children:[o("mcp.signIn.authorize.notALink")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:fC(t.authorizationUrl??"")})]}),value:a,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:()=>l(a)}),s&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[o("mcp.signIn.paste.refused")," ",vQ(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:fC(s.error)})]})]}),t.redirectUrl&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.signIn.authorize.redirect",{url:fC(t.redirectUrl)})}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.signIn.authorize.wait")})]})}function v2(e){let{flow:t,shared:n}=e,{t:i}=(0,t_.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 vV[e.failure??"internal"];case"cancelled":return"mcp.signIn.cancelled";case"expired":return"mcp.signIn.expired";default:return}}(t,n);if(!s)return null;let l=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"===l?"mcp-config-line is-error":"warning"===l?"mcp-config-line is-warning":"mcp-config-line",children:i(s,{name:fC(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:fC(t.error)})]})]})}function v4(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function v8(e){return fC(e1(e))}function v3(e,t){let{key:n,params:r}=e;return r?t(n,void 0===r.path?r:{...r,path:v8(r.path)}):t(n)}function v5(e,t){return e.timedOut?t("mcp.loadTimedOut"):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function v6(e,t){return e.timedOut?t("mcp.actionTimedOut"):v5(e,t)}function v9(){if("u"<typeof document)return null;let e=document.activeElement;return e instanceof HTMLButtonElement||e instanceof HTMLSelectElement?e:null}function v7(e){let{cwd:t,onClose:n,embedded:s=!1,trust:l,onTrustProject:o,onProjectTrustChanged:a}=e,[d,c]=(0,i.useState)({state:"loading"}),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(()=>u7("mcp",t)),[m,g]=(0,i.useState)({saving:!1,error:null}),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),[E,$]=(0,i.useState)({}),I=(0,i.useRef)(0),M=(0,i.useRef)(null),T=(0,i.useRef)(null),R=(0,i.useRef)(null),A=(0,i.useRef)(new Map),[L,z]=(0,i.useState)({}),P=(0,i.useRef)(L);P.current=L;let[W,O]=(0,i.useState)(0),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)(vo),_=(0,i.useRef)(B);_.current=B;let[U,K]=(0,i.useState)(null),[q,V]=(0,i.useState)(null),Z=(0,i.useRef)(!0),J=(0,i.useRef)(d);J.current=d;let Y=(0,i.useCallback)(async()=>{let e=++I.current;M.current?.abort();let n=new AbortController;M.current=n,p(!0);let r=await md(t,void 0,n.signal);if(e===I.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}:{}}),f(e=>f8(f2(r.data,!!t),e))}},[t]),G=hV(l);(0,i.useEffect)(()=>(Y(),()=>{I.current+=1,M.current?.abort()}),[Y,G]);let X=(0,i.useCallback)(async e=>{let t=new AbortController;T.current=t,g({saving:!0,error:null,target:"preference"});let n=await mp(e,void 0,t.signal);T.current===t&&(T.current=null,g({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}),Y())},[Y]),Q=(0,i.useCallback)(async e=>{let t=new AbortController;T.current=t,g({saving:!0,error:null,target:"mode"});let n=await mh(e,void 0,t.signal);T.current===t&&(T.current=null,g({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),Y())},[Y]),ee=(0,i.useCallback)(async e=>{let t=new AbortController;T.current=t,g({saving:!0,error:null,target:"inlineBudget"});let n=await mf(e,void 0,t.signal);T.current===t&&(T.current=null,g({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),Y())},[Y]);(0,i.useEffect)(()=>{let e=A.current;return Z.current=!0,()=>{Z.current=!1,T.current?.abort(),T.current=null,R.current?.abort(),R.current=null,e.clear()}},[]);let et=(0,i.useCallback)(async e=>{let n=fW(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,l=await mM({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],l,e.configKey)}));let o=J.current,a="loaded"===o.state?o.data.servers.find(e=>fW(e)===n):void 0;(l.ok?a?.configKey===l.data.configKey:void 0===l.error.reason||l.error.timedOut)||Y()},[t,Y]),en=(0,i.useCallback)((e,n)=>{I.current+=1,M.current?.abort(),p(!1),c(t=>({state:"loaded",data:e,..."loaded"===t.state&&t.projectError?{projectError:t.projectError}:{}})),f(r=>f8(f2(e,!!t),n??r))},[t]),er=(0,i.useCallback)(async e=>{let n=fW(e),r=P.current[n];if(r?.starting||v_(r))return;z(e=>({...e,[n]:{starting:!0}}));let i=J.current,s="loaded"===i.state&&i.data.project?t:null,l=await function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(e,t)=>fetch(e,t),r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:15e3;return vG("/api/mcp/sign-in",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:e.scope,name:e.name,...t?{cwd:t}:{}})},n,r,i,{abortAtDeadline:!1})}({scope:e.scope,name:e.name},s);Z.current&&(z(e=>({...e,[n]:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();return e.ok?vZ({},e.data,t):{error:e.error}}(l)})),l.ok||void 0===l.error.reason||l.error.timedOut||Y())},[t,Y]),ei=(0,i.useCallback)(async(e,t,n)=>{let r=fW(e);z(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 vG(vX(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirectUrl:t})},n,r,i)}(t,n);Z.current&&z(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?{...vZ(i,n.data,r),pasteError:void 0}:vJ(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=fW(e);z(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 vG(vX(e),{method:"DELETE"},t,n,r)}(t);Z.current&&z(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?vZ(i,n.data,r):vJ(n.error)?{...i,gone:!0}:{...i,cancelError:n.error}}(e[n],t,r);return void 0===i||i===e[n]?e:{...e,[n]:i}})},[]),el=Object.entries(L).flatMap(e=>{let[t,n]=e;return v_(n)&&n.flow?[`${t}\x01${n.flow.flowId}`]:[]}).join("\x02");(0,i.useEffect)(()=>{if(!el)return;let e=new AbortController,t=setTimeout(async()=>{for(let t of el.split("\x02")){let[n,r]=t.split("\x01"),i=P.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 vG(vX(e),{},t,n,r)}(r,void 0,e.signal);if(e.signal.aborted)return;z(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?vZ(e,n.data,r):vJ(n.error)||void 0!==e.deadlineAt&&r>e.deadlineAt+5e3?{...e,gone:!0}:e:e}(e[n],r,s,Date.now(),i);return void 0===t||t===e[n]?e:{...e,[n]:t}})}O(e=>e+1)},1e3);return()=>{clearTimeout(t),e.abort()}},[el,W]);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],v_(n)&&!v_(r)})&&Y()},[L,Y]);let ea=(0,i.useCallback)(async(e,n,r)=>{R.current?.abort();let i=new AbortController;R.current=i,v(n);let s=J.current,l="loaded"===s.state&&s.data.project?t:null,o=await mw(e,l,void 0,i.signal);if(R.current===i)return R.current=null,v(null),o.ok?en(o.data,r?.(o.data)):Y(),o},[en,t,Y]),ed=(0,i.useCallback)(async(e,t)=>{let n=fW(e),r=v9();y(null),k(null);let i=await ea({action:t?"enable":"disable",scope:e.scope,name:e.name},`switch:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[ea]),ec=(0,i.useCallback)(async(e,t)=>{let n=fW(e),r=v9();y(null),k(null);let i=await ea({action:"set-in-project",name:e.name,enabled:t},`in-project:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[ea]),eu=(0,i.useCallback)(async(e,t)=>{let n=fW(e),r=v9();y(null),k(null);let i=await ea({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}))},[ea]),ep=(0,i.useCallback)(async e=>{let t=fW(e),n=v9();y(null),k(null);let r=await ea({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})},[ea]),eh=(0,i.useCallback)(async()=>{if(!j)return;let e=v9();y(null),k(null),S({...j,undoing:!0,error:void 0});let t=await ea({action:"undo",token:j.token},"undo",e=>e.restored?fW(e.restored):void 0);t&&(S(e=>e?.token!==j.token?e:t.ok?null:{...e,undoing:!1,error:t.error}),t.ok||N({control:e}))},[ea,j]),ef=(0,i.useCallback)(async e=>{let t=fW(e),n=v9();y(null),k(null),z(e=>({...e,[t]:{...e[t],signOutError:void 0,signedOut:void 0}}));let r=await ea({action:"sign-out",scope:e.scope,name:e.name},`sign-out:${t}`);if(r){if(z(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})}},[ea]),em=(0,i.useCallback)(async e=>{let n=v9(),r=_.current;y(null),k(null),K(null);let i=await ea(e,"add",e=>e.added?fW(e.added):void 0);if(!i)return;let s=_.current!==r;if(!i.ok){s||K(i.error),i.error.trust&&t&&a?.(t,i.error.trust),N({control:n});return}let{added:l,trust:o,trustedFolder:d}=i.data;if(D(!1),s||H(vo),N({control:null,toSelectedRow:!0}),!l)return;V({...l,key:fW(l),...d&&t?{trustedFolder:t}:{}}),o&&t&&a?.(t,o);let c=i.data.servers.find(e=>fW(e)===fW(l));c&&!mj(c,i.data)&&et(c)},[t,a,ea,et]),eg=j?.token,ex=j?.expiresInMs;(0,i.useEffect)(()=>{if(void 0===eg||void 0===ex)return;let e=setTimeout(()=>S(e=>e?.token===eg?null:e),ex);return()=>clearTimeout(e)},[eg,ex]);let ev=(0,i.useCallback)(async(e,t,n)=>{let{targets:r,keptOff:i}={targets:hq(t,n,e=>e.enabled).filter(n?mb:mv),keptOff:n?t.filter(e=>!e.enabled&&mv(e)&&!mb(e)).length:0},s=v9();if(y(null),k(i>0?{scope:e,keptOff:i,failures:[],total:0}:null),0===r.length)return;let l=await ea({action:"set-enabled",enabled:n,servers:r.map(e=>{let{scope:t,name:n}=e;return{scope:t,name:n}})},`group:${e}`);if(!l)return;if(N({control:s}),!l.ok)return void k({scope:e,keptOff:i,failures:[],total:r.length,error:l.error});let o=l.data.results??[],a=o.filter(e=>void 0!==e.reason).map(e=>({name:e.name,failure:{error:e.error??"",reason:e.reason}}));k(a.length>0||i>0?{scope:e,keptOff:i,failures:a,total:o.length}:null)},[ea]);return(0,i.useEffect)(()=>{h&&pe("mcp",h,t)},[t,h]),(0,r.jsx)(be,{cwd:t,load:d,selected:h,refreshing:u,embedded:s,codemodeSave:m,busy:x,actionError:b,groupStatus:w,undo:j,focusBack:C,tests:E,signIns:L,adding:F,addDraft:B,addFailure:U,added:q,onAddOpen:()=>{D(!0),V(null),y(null)},onAddDraftChange:e=>{_.current=e,H(e),K(null)},onAddSubmit:e=>void em(e),onTest:e=>void et(e),onSignIn:e=>void er(e),onSignOut:e=>void ef(e),onSignInPaste:(e,t,n)=>void ei(e,t,n),onSignInCancel:(e,t)=>void es(e,t),onSelect:e=>{f(e),y(null),D(!1),V(t=>t?.key===e?t:null)},onRefresh:()=>void Y(),onCodemodeChange:e=>void X(e),onCodemodeModeChange:e=>void Q(e),onCodemodeInlineBudgetSave:e=>void ee(e),onServerSwitch:(e,t)=>void ed(e,t),onServerSwitchInProject:(e,t)=>void ec(e,t),onExposureChange:(e,t)=>void eu(e,t),onGroupSwitch:(e,t,n)=>void ev(e,t,n),onRemove:e=>void ep(e),onUndo:()=>void eh(),onTrustProject:o,onClose:n})}function be(e){var t,n,s,l;let o,a,d,{cwd:c,load:u,selected:p,refreshing:h,embedded:f,codemodeSave:m={saving:!1,error:null},busy:g=null,actionError:x=null,groupStatus:v=null,undo:b=null,focusBack:y=null,tests:w={},signIns:k={},adding:j=!1,addDraft:S=vo,addFailure:C=null,added:N=null,onAddOpen:E=()=>{},onAddDraftChange:$=()=>{},onAddSubmit:I=()=>{},onSelect:M,onRefresh:T,onCodemodeChange:R,onCodemodeModeChange:A=()=>{},onCodemodeInlineBudgetSave:L=()=>{},onServerSwitch:z=()=>{},onServerSwitchInProject:P=()=>{},onExposureChange:W=()=>{},onGroupSwitch:O=()=>{},onRemove:F=()=>{},onUndo:D=()=>{},onTest:B=()=>{},onSignIn:H=()=>{},onSignOut:_=()=>{},onSignInPaste:U=()=>{},onSignInCancel:K=()=>{},onTrustProject:q,onClose:V}=e,{t:Z}=(0,t_.s)(),J=(0,i.useId)(),Y=(0,i.useId)(),G="loaded"===u.state?(t=u.data,o=!1,a=t.servers.map(e=>{var t;let n=w[fW(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:a}:t):void 0,X=G?f2(G,!!c):[],Q=G?{mcpAvailable:G.mcp.available,projectServersLoad:fO(G.project)}:void 0,ee=X.flatMap(e=>e.servers),et=ee.find(e=>fW(e)===p),en=N?ee.find(e=>fW(e)===N.key):void 0,er=G?function(e){if(!e.available)return"builtin-disabled"===e.reason?e.settingsPath?{key:"mcp.unavailable.builtin-disabled",params:{path:e.settingsPath}}:{key:"mcp.unavailable.builtin-disabled-unknown"}:{key:"operator-disabled"===e.reason?"mcp.unavailable.operator-disabled":"mcp.unavailable.internals-unavailable"}}(G.mcp):void 0,ei=er?void 0:G?.hostInactive,es=G?.files.find(e=>"project"===e.scope),el=G?function(e,t){if(!e||!t||!t.exists&&0===t.problems.length)return;let{trust:n}=e;return n?n.requiresTrust||!1===n.decision?!0===n.decision?n.inherited&&n.decisionPath?{kind:"inherited",key:"mcp.trust.trustedThrough",params:{path:n.decisionPath}}:void 0:!1===n.decision&&n.inherited&&n.decisionPath?{kind:"untrusted",key:"mcp.trust.untrustedThrough",params:{path:n.decisionPath}}:{kind:"untrusted",key:"mcp.trust.untrusted"}:void 0:{kind:"untrusted",key:"mcp.trust.unreadable"}}(G.project,es):void 0,eo=q&&f3(G?.project)?q:void 0,ea=el?.kind==="untrusted"&&void 0!==eo,ed=(0,i.useRef)(null),ec=(0,i.useRef)(null),eu=(0,i.useRef)(ea);(0,i.useEffect)(()=>{let e=eu.current;eu.current=ea,e&&!ea&&to(document,ed.current??ec.current)},[ea]);let ep=(0,i.useRef)(null),eh=b?.token,ef=(0,i.useRef)(eh);(0,i.useEffect)(()=>{let e=ef.current;ef.current=eh,void 0!==eh&&eh!==e?to(document,ep.current):void 0!==e&&void 0===eh&&to(document,ed.current??ec.current)},[eh]);let em=G?[...G.files].sort((e,t)=>e.scope===t.scope?0:"global"===e.scope?-1:1).flatMap(e=>e.problems.map(t=>({file:e,problem:t}))):[],eg=f4(ee),ex=G?.files.find(e=>"global"===e.scope),ev=G?function(e){let t=e.files.find(e=>"project"===e.scope);if(t?.autoEnableCodemode!==void 0&&fO(e.project))return t.autoEnableCodemode?{value:!0,path:t.path}:{value:!1,path:t.path};let n=e.files.find(e=>"global"===e.scope);return n?.autoEnableCodemode!==void 0?n.autoEnableCodemode?{value:!0,path:n.path}:{value:!1,path:n.path}:{value:!0}}(G):void 0,eb=G?(n=ee.length,s=G.files,n>0?"mcp.selectItem":s.some(e=>e.problems.some(f1))?"mcp.emptyFileProblem":"mcp.empty"):void 0,ey=null!==g||h||m.saving,ew=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(y&&!ey&&ew.current!==y)if(ew.current=y,y.toSelectedRow)to(document,ed.current??ec.current);else{var e,t,n;e=document,t=y.control,n=ed.current??ec.current,t&&to(e,t.isConnected&&!t.disabled?t:n)}},[y,ey]);let ek=e=>G?mg(e,G):void 0,ej=!!G&&mm(G.mcp),eS=X.find(e=>"project"===e.scope)?.servers??[],eC=ek("project"),eN=e=>"mcp-off"===e?er?J:void 0:e&&el?.kind==="untrusted"?Y:void 0,eE=el?.kind==="untrusted"?[v3(el,Z),eC&&"mcp-off"!==eC&&eS.length>0?Z(mx[eC]):null].filter(Boolean).join(" "):"";return(0,r.jsxs)(pN,{embedded:f,title:Z("settings.mcp"),subtitle:c?e1(c):void 0,closeLabel:Z("i18n.close"),onClose:V,children:[(0,r.jsxs)("div",{className:"mcp-config-notices",children:[er&&(0,r.jsxs)(pQ,{id:J,children:[v3(er,Z),ej&&(0,r.jsxs)(r.Fragment,{children:[" ",Z(mx["mcp-off"])]}),G&&!G.mcp.available&&G.mcp.detail&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:fC(G.mcp.detail)})]})]}),ei&&(0,r.jsx)(pQ,{children:Z("mcp.hostInactive",{path:v8(ei.cwd),owner:v8(ei.owner)})}),"loaded"===u.state&&u.projectError&&(0,r.jsx)(pQ,{children:Z("mcp.projectNotListed",{reason:v5(u.projectError,Z)})}),el?.kind==="untrusted"&&(0,r.jsx)(p0,{id:Y,message:eE,trustLabel:Z("mcp.trust.trustButton"),onTrust:eo}),el?.kind==="inherited"&&(0,r.jsx)(pQ,{children:v3(el,Z)}),b&&(0,r.jsxs)(pQ,{action:b.error?.reason==="undo-unavailable"?void 0:(0,r.jsx)(p3,{ref:ep,size:"small",onClick:D,disabled:b.undoing||ey,children:b.undoing?Z("mcp.undoing"):Z("mcp.undo")}),children:[Z("mcp.removed",{name:fC(b.name),path:v8(b.path)}),b.error&&(0,r.jsxs)(r.Fragment,{children:[" ",Z("mcp.undoFailed")," ",v6(b.error,Z)]})]}),N&&G&&en&&(0,r.jsx)(bt,{added:N,cwd:c,server:en,testing:w[N.key]?.running===!0,signIn:k[N.key],signingOut:g===`sign-out:${N.key}`,signInBlock:en?mj(en,G):void 0,onSignIn:H})]}),(0,r.jsxs)(pT,{children:[(0,r.jsxs)(pR,{children:[(0,r.jsx)(pA,{children:"loading"===u.state?(0,r.jsx)("div",{className:"config-sidebar-message",children:Z("i18n.loading")}):"failed"===u.state?(0,r.jsxs)("div",{role:"alert",className:"config-sidebar-message is-error",children:[Z("mcp.loadFailed")," ",v5(u.error,Z)]}):G&&Q?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-sidebar-group",children:(0,r.jsx)(bn,{codemode:G.codemode,active:!j&&p===fP,rowRef:ed,onSelect:M})}),X.map(e=>{let t=ek(e.scope);return(0,r.jsx)(br,{group:e,context:Q,selected:j?null:p,selectedRowRef:ed,block:t,blockNoticeId:eN(t),busy:g,controlsBusy:ey,status:v?.scope===e.scope?v:null,onSelect:M,onGroupSwitch:O},e.scope)})]}):null}),G&&(0,r.jsx)(p6,{ref:ec,active:j,onClick:E,children:Z("mcp.add.action")})]}),(0,r.jsx)(p2,{children:(0,r.jsx)(pF,{className:"is-fill",children:G&&Q&&ev&&eb?j?(0,r.jsx)(vO,{data:G,cwd:c,draft:S,busy:"add"===g,controlsBusy:ey,failure:C,onDraftChange:$,onSubmit:I,onTrustProject:eo}):p===fP?(0,r.jsx)(bm,{codemode:G.codemode,autoEnable:ev,save:m,serverBusy:null!==g,onChange:R,onModeChange:A,onInlineBudgetSave:L}):et?(0,r.jsx)(bl,{server:et,context:Q,codemode:G.codemode,toolSearchDisabled:G.toolSearchDisabled,autoEnable:ev,block:ek(et.scope),blockNoticeId:eN(ek(et.scope)),uncheckedSaid:er?.key==="mcp.unavailable.internals-unavailable",inProject:function(e,t){if("global"!==e.scope||void 0!==e.invalidError||e.notAnObject||!fO(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:fW(r),keys:r.override.keys,applies:!0===e.overriddenByProject}:void 0:{kind:"switch"}}(et,G),inProjectBlock:ek("project"),savedWhileOff:!G.mcp.available&&!ej,busy:g,controlsBusy:ey,actionError:x?.key===fW(et)?x.failure:null,test:(l=w[fW(et)],l&&void 0!==l.configKey&&l.configKey!==et.configKey?{running:l.running,...l.response?{response:l.response}:{}}:l),testBlock:mj(et,G),signIn:k[fW(et)],signInBlock:mj(et,G),signOutBlock:(d=mg(et.scope,G))||(void 0===et.invalidError&&et.validated?void 0:"invalid"),onSwitch:z,onSwitchInProject:P,onShowServer:e=>{M(e),requestAnimationFrame(()=>to(document,ed.current??ec.current))},onExposureChange:W,onRemove:F,onTest:B,onSignIn:H,onSignOut:_,onSignInPaste:U,onSignInCancel:K},fW(et)):(0,r.jsx)(p1,{children:"mcp.empty"===eb?Z(eb,{globalPath:v8(ex?.path??"~/.pi/agent/mcp.json")}):Z(eb)}):null})})]}),(0,r.jsxs)(p4,{status:em.length>0?(0,r.jsx)(p8,{tone:em.some(e=>{let{problem:t}=e;return f1(t)})?"error":"warning",summary:1===em.length?Z("mcp.footer.fileProblem"):Z("mcp.footer.fileProblems",{count:em.length}),details:em.map(e=>{let{file:t,problem:n}=e,i=fz(n,t.realPath);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:v8(t.path)})," ",Z(`mcp.fileProblem.${n.reason}`),i&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:i})]})]})})}):(0,r.jsx)(p8,{summary:eg.total>0?Z("mcp.serverCount",{enabled:eg.enabled,total:eg.total}):""}),children:[!f&&(0,r.jsx)(p3,{onClick:V,children:Z("i18n.close")}),(0,r.jsx)(p3,{variant:"secondary",onClick:T,disabled:ey,children:Z("i18n.refresh")})]})]})}function bt(e){let{added:t,cwd:n,server:i,testing:s,signIn:l,signingOut:o,signInBlock:a,onSignIn:d}=e,{t:c}=(0,t_.s)(),u=fC(t.name),p="project"===t.scope&&n?fC(e2(t.path,n)):v8(t.path),h=i.status,f=!s&&h?.origin==="test"&&"needs-auth"===h.state&&i.usesOAuth,m=l?.starting===!0||v_(l);return(0,r.jsxs)(pQ,{action:!f||m||o||a?void 0:(0,r.jsx)(p3,{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:v8(t.trustedFolder)}),s&&(0,r.jsxs)(r.Fragment,{children:[" ",c("mcp.add.testing")]}),f&&(0,r.jsxs)(r.Fragment,{children:[" ",c("mcp.add.needsSignIn")]})]})}function bn(e){let{codemode:t,active:n,rowRef:i,onSelect:s}=e,{t:l}=(0,t_.s)(),o=t.builtinDisabled||"unavailable"===t.sandbox.state?"unavailable":t.preference??"unknown",a=l(me[o]);return(0,r.jsxs)(pW,{ref:n?i:void 0,active:n,"aria-label":l("mcp.codemode.rowLabel",{state:a}),onClick:()=>s(fP),children:[(0,r.jsx)(p9,{...fV(mt(o))}),(0,r.jsx)(pO,{className:"is-grow",children:l("mcp.codemode.title")}),(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${mt(o)}`,children:a})]})}function br(e){var t;let n,i,{group:s,context:l,selected:o,selectedRowRef:a,block:d,blockNoticeId:c,busy:u,controlsBusy:p,status:h,onSelect:f,onGroupSwitch:m}=e,{t:g}=(0,t_.s)(),{enabled:x,total:v}=f4(s.servers),b=(t=s.servers).some(e=>e.enabled&&mv(e))&&t.every(e=>e.enabled||!mb(e)),y=function(e){if(!(e.servers.length>0))return e.file?e.file.problems.some(f1)?"mcp.group.fileProblem":"mcp.group.empty":"mcp.group.notListed"}(s),w=h?(n=h.keptOff>0?g("mcp.groupKeptOff",{count:h.keptOff}):void 0,i=h.error?`${g("mcp.actionFailed")} ${v6(h.error,g)}`:h.failures.length>0?[g("mcp.bulkFailed",{count:h.failures.length,total:h.total}),...h.failures.map(e=>{let{name:t,failure:n}=e;return`${fC(t)}: ${v6(n,g)}`})].join("\n"):void 0,{...n?{note:n}:{},...i?{error:i}:{}}):void 0;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(pL,{aside:v>0?(0,r.jsx)(pz,{enabled:x,total:v,checked:b,disabled:p||void 0!==d,loading:u===`group:${s.scope}`,describedBy:d?c:void 0,label:g(b?"mcp.groupSwitchOn":"mcp.groupSwitchOff",{group:v4(s.scope,g)}),onChange:e=>m(s.scope,s.servers,e)}):void 0,children:v4(s.scope,g)}),w&&(0,r.jsx)(pP,{note:w.note,error:w.error}),y&&(0,r.jsx)("div",{className:"mcp-sidebar-group-empty",children:g(y)}),s.servers.map(e=>{let t=fW(e),n=fD(e,l),i=fq(n),s=fK[n],d=fC(e.name);return(0,r.jsxs)(pW,{ref:o===t?a:void 0,active:o===t,"aria-label":g("mcp.rowLabel",{name:d,state:g(f_(n,e.status))}),onClick:()=>f(t),children:[(0,r.jsx)(p9,{...fV(i)}),(0,r.jsx)(pO,{className:`is-grow${"on"===i?"":" is-muted"}`,children:d}),s&&(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${i}`,children:g(s)})]},t)})]})}function bi(e){let{fields:t}=e,{t:n}=(0,t_.s)();return(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>{let t=fT(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function bs(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:fC(e)},e))})}function bl(e){let{server:t,context:n,codemode:s,toolSearchDisabled:l,autoEnable:o,block:a,blockNoticeId:d,uncheckedSaid:c,inProject:u,inProjectBlock:p,savedWhileOff:h,busy:f,controlsBusy:m,actionError:g,test:x,testBlock:v,signIn:b,signInBlock:y,signOutBlock:w,onSwitch:k,onSwitchInProject:j,onShowServer:S,onExposureChange:C,onRemove:N,onTest:E,onSignIn:$,onSignOut:I,onSignInPaste:M,onSignInCancel:T}=e,{t:R}=(0,t_.s)(),A=(0,i.useId)(),L=(0,i.useId)(),z=fD(t,n),P=fI(t),W=t.status,O=W?.origin==="test"&&"connected"===W.state&&W.toolCount>0?W:void 0,F=void 0===t.invalidError,D="http"===t.transport||void 0===t.transport&&void 0!==t.url,B=!D&&("stdio"===t.transport||void 0!==t.command),H=t.exposure?function(e,t,n){if("codemode"===e){var r;return r=t.codemode,"unavailable"===r.sandbox.state?{key:"mcp.exposure.sandboxUnavailable"}:r.builtinDisabled?{key:"mcp.exposure.builtinDisabled"}:n.value||"always"===f5(r)?void 0:{key:"mcp.exposure.autoEnableOff",params:{path:n.path}}}if("deferred"!==e||!t.toolSearchDisabled)return;let i=t.toolSearchDisabled.settingsPath;return i?{key:"mcp.exposure.toolSearchDisabled",params:{path:i}}:{key:"mcp.exposure.toolSearchDisabledUnknown"}}(t.exposure,{codemode:s,toolSearchDisabled:l},o):void 0,_=(0,i.useId)(),U=(0,i.useId)(),K=fW(t),q=fC(t.name),V=!t.enabled&&void 0!==t.webPasswordField,Z=!0===t.notAnObject,J=a?d?void 0:R(`mcp.reason.${a}`):Z?R("mcp.reason.entry-not-object"):V?R("mcp.reason.web-password"):h?R("mcp.write.savedWhileOff"):void 0,Y=J?A:a?d:void 0,G=e=>void 0!==e&&e===a&&void 0!==d;return(0,r.jsxs)(pF,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(pD,{children:[(0,r.jsxs)(pB,{children:[(0,r.jsx)(pZ,{scope:t.scope,children:v4(t.scope,R)}),(0,r.jsx)(p_,{children:q})]}),(0,r.jsxs)(pH,{children:[(0,r.jsx)(bh,{server:t,test:x,testBlock:v,describedBy:G(v)?d:L,onTest:E}),(0,r.jsx)(p3,{variant:"danger",size:"small",disabled:m||void 0!==a,"aria-describedby":a?Y:void 0,onClick:()=>N(t),children:f===`remove:${K}`?R("i18n.removing"):R("i18n.remove")}),(0,r.jsx)(p5,{checked:t.enabled,disabled:m||void 0!==a||Z||V,loading:f===`switch:${K}`,describedBy:Y,label:R(t.enabled?"mcp.server.switchOff":"mcp.server.switchOn",{name:q}),onChange:e=>k(t,e)})]})]}),J&&(0,r.jsx)("div",{id:A,className:"config-detail-heading-note",children:J})]}),g&&(0,r.jsxs)("p",{role:"alert",className:"mcp-config-line is-error",children:[R("mcp.actionFailed")," ",v6(g,R)]}),(0,r.jsxs)(pq,{children:[(0,r.jsx)(bf,{server:t,state:z,test:x,testBlock:v,testBlockSaid:G(v),testBlockId:L}),void 0!==t.description&&(0,r.jsx)(pV,{label:R("mcp.detail.description"),tone:"plain",children:fC(t.description)}),void 0!==P?(0,r.jsx)(pV,{label:D?R("mcp.detail.url"):R("mcp.detail.command"),tone:"plain",mono:!0,className:"mcp-config-code",children:P}):t.transport&&(0,r.jsx)(pV,{label:R("mcp.detail.transport"),children:R(`mcp.transport.${t.transport}`)}),B&&void 0!==t.cwd&&(0,r.jsx)(pV,{label:R("mcp.detail.cwd"),mono:!0,className:"mcp-config-code",children:fC(t.cwd)}),B&&t.envNames.length>0&&(0,r.jsx)(pV,{label:R("mcp.detail.env"),children:(0,r.jsx)(bs,{names:t.envNames})}),D&&t.headerNames.length>0&&(0,r.jsx)(pV,{label:R("mcp.detail.headers"),children:(0,r.jsx)(bs,{names:t.headerNames})}),F&&t.commandFields.length>0&&(0,r.jsx)(pV,{label:R("mcp.detail.shellCommands"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:R("mcp.server.commandFields")}),(0,r.jsx)(bi,{fields:t.commandFields})]})}),F&&t.variableReferences.length>0&&(0,r.jsx)(pV,{label:R("mcp.detail.variables"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:R(fR(t))}),(0,r.jsx)("span",{className:"mcp-config-chips",children:fL(t.variableReferences).map(e=>{let{variable:t,field:n}=e,i=fT(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:R("mcp.server.variableIn",{variable:t,field:R(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})}),D&&F&&(0,r.jsx)(v0,{server:t,run:b,block:y,signOutBlock:w,blockSaidBy:G(y)?d:void 0,signOutBlockSaidBy:G(w)?d:void 0,controlsBusy:m,signingOut:f===`sign-out:${K}`,onSignIn:$,onSignOut:I,onPaste:M,onCancel:T}),(t.exposure||O)&&(0,r.jsx)(pV,{label:R("mcp.detail.exposure"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[t.exposure&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-exposure-choice",children:[(0,r.jsx)("select",{className:"mcp-add-input mcp-exposure-select","aria-label":R("mcp.exposure.label",{name:q}),"aria-describedby":[_,a?Y:null].filter(Boolean).join(" "),value:t.exposure,disabled:m||void 0!==a,onChange:e=>{let n=e.target.value;n!==t.exposure&&C(t,n)},children:fQ.map(e=>(0,r.jsx)("option",{value:e,children:"codemode"===e?R("mcp.exposure.optionDefault",{label:R(f0[e])}):R(f0[e])},e))}),f===`exposure:${K}`&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:R("i18n.saving")})]}),(0,r.jsx)("span",{id:_,className:"mcp-config-line",children:R(fX[t.exposure])}),void 0!==t.toolExposureCount&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:R("mcp.exposure.toolOverrides",{count:t.toolExposureCount})}),H&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:v3(H,R)})]}),O&&(0,r.jsx)(bp,{status:O,serverExposure:t.exposure})]})}),u&&(0,r.jsx)(pV,{label:R("mcp.detail.inProject"),tone:"plain",children:(0,r.jsx)("span",{className:"mcp-config-lines",children:"override"===u.kind?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"mcp-config-line",children:u.applies?R("mcp.inProject.overridden",{keys:u.keys.join(", ")}):R("mcp.inProject.refused")}),(0,r.jsx)("span",{children:(0,r.jsx)(p3,{size:"small",onClick:()=>S(u.key),children:R("mcp.inProject.show")})})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:(0,r.jsx)(p3,{size:"small",disabled:m||void 0!==p||V,"aria-describedby":[U,p||V?Y:null].filter(Boolean).join(" "),onClick:()=>j(t,!t.enabled),children:f===`in-project:${K}`?R("i18n.saving"):R(t.enabled?"mcp.inProject.turnOff":"mcp.inProject.turnOn")})}),(0,r.jsx)("span",{id:U,className:"mcp-config-line is-dim",children:R("mcp.inProject.saved")})]})})}),(0,r.jsx)(pV,{label:R("mcp.detail.file"),tone:"dim",mono:!0,className:"mcp-config-code",children:v8(t.sourcePath)})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[fM(t)&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:R("mcp.server.hiddenCharacters")}),!t.validated&&!c&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:R("mcp.server.unchecked")}),t.replacesGlobal&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:R("mcp.server.replacesGlobal")}),t.override&&(0,r.jsx)("p",{className:"mcp-config-line",children:v3(fA(t.override.keys),R)}),t.shadowedByProject&&"replaced"!==z&&(0,r.jsx)("p",{className:"mcp-config-line",children:R("mcp.server.shadowedByProject")}),t.overriddenByProject&&"overridden"!==z&&(0,r.jsx)("p",{className:"mcp-config-line",children:R("mcp.server.overriddenByProject")}),t.masked&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:R("mcp.server.masked")})]})]})}function bo(e){let{error:t,stderr:n}=e,{t:i}=(0,t_.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:fC(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(fC).join("\n")})]})]})}function ba(e){let{status:t,showState:n,entryCwd:i}=e;return"session"===t.origin?(0,r.jsx)(bu,{status:t,showState:n}):(0,r.jsx)(bc,{status:t,showState:n,entryCwd:i})}function bd(e){let{view:t}=e,{t:n}=(0,t_.s)();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:`mcp-config-state is-${t.tone}`,children:n(t.key)})," "]})}function bc(e){let{status:t,showState:n,entryCwd:i}=e,{t:s,locale:l}=(0,t_.s)(),o=fZ(t.testedAt,l),a=t.serverInfo;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,r.jsx)(bd,{view:t.timedOut?{key:mC.timedOut,tone:"error"}:{key:mC[t.state],tone:fq(t.state)}}),s((t.afterSignIn?mE:mN)[t.timedOut?"timedOut":t.state],{count:t.toolCount,seconds:m$(t.durationMs),time:o})]}),(0,r.jsx)(bo,{error:t.error,stderr:t.stderr}),a&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.serverInfo",{name:fC(a.title??a.name),version:fC(a.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:v8(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:m$(t.queuedMs)})})]})}function bu(e){let{status:t,showState:n}=e,{t:i,locale:s}=(0,t_.s)(),l=fZ(t.updatedAt,s),o=void 0===t.closedAt?void 0:fZ(t.closedAt,s);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,r.jsx)(bd,{view:void 0!==t.closedAt?{key:"mcp.session.state.closed",tone:"off"}:{key:fJ[t.state],tone:fG[t.state]}}),i(void 0!==t.closedAt?"mcp.session.summary.closed":fY[t.state],{path:v8(t.cwd),time:l,...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:v8(t.conflict)})]}),(0,r.jsx)(bo,{error:t.error,stderr:t.stderr})]})}function bp(e){let{status:t,serverExposure:n}=e,{t:i}=(0,t_.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:fC(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(f0[e.exposure])})]}),e.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:fC(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 bh(e){let{server:t,test:n,testBlock:s,describedBy:l,onTest:o}=e,{t:a}=(0,t_.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&&to(document,d.current)},[c]),(0,r.jsx)(p3,{ref:d,size:"small",disabled:c||void 0!==s,"aria-busy":c||void 0,"aria-describedby":s?l:void 0,onClick:()=>o(t),children:a(c?"mcp.test.testing":"mcp.test.button")})}function bf(e){let{server:t,state:n,test:i,testBlock:s,testBlockSaid:l,testBlockId:o}=e,{t:a}=(0,t_.s)(),d=t.status,c=fU[n],u="invalid"===s&&"invalid"===n?"state":"web-password"===s&&void 0!==t.webPasswordField?"password":void 0;return(0,r.jsx)(pV,{label:a("i18n.status"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:`mcp-config-state is-${fq(n)}`,children:a(f_(n,d))}),"invalid"===n&&(0,r.jsxs)("span",{id:"state"===u?o:void 0,className:"mcp-config-line is-warning",children:[a("mcp.server.invalid")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:fC(t.invalidError??"")})]}),t.webPasswordField&&(0,r.jsxs)("span",{id:"password"===u?o:void 0,className:"mcp-config-line is-warning",children:[a("mcp.server.webPassword")," ",(0,r.jsx)(bi,{fields:[t.webPasswordField]})]}),d?(0,r.jsx)(ba,{status:d,showState:fF(d)!==n,entryCwd:t.cwd}):!s&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:a("mcp.test.never")}),c&&(0,r.jsx)("span",{className:"mcp-config-line",children:a(c)}),i?.queueTimedOut&&(0,r.jsx)("span",{role:"alert",className:"mcp-config-line is-error",children:a("mcp.test.queueTimedOut")}),i?.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[a("mcp.test.requestFailed")," ",function(e,t){if(e.timedOut)return t("mcp.test.requestTimedOut");let n=e.reason?mS[e.reason]:void 0;return n?t(n):v5(e,t)}(i.error,a)]}),s&&!u&&!l&&(0,r.jsx)("span",{id:o,className:"mcp-config-line is-dim",children:a(mk[s])}),!s&&t.commandFields.length>0&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:a("mcp.test.serial")})]})})}function bm(e){let{codemode:t,autoEnable:n,save:i,serverBusy:s,onChange:l,onModeChange:o,onInlineBudgetSave:a}=e,{t:d}=(0,t_.s)(),c=t.sandbox,u=t.preference,p=i.saving||s,h=void 0===i.target||"preference"===i.target?i:{saving:!1,error:null},f=function(e,t){if("automatic"===f5(e)&&!t.value)return{key:"mcp.codemode.autoEnableOff",params:{path:t.path}}}(t,n),m="unavailable"===t.sandbox.state?{key:"mcp.codemode.alwaysUnavailable.sandbox"}:t.globalBuiltinSettingsPath?{key:"mcp.codemode.alwaysUnavailable.builtin",params:{path:t.globalBuiltinSettingsPath}}:void 0,g=function(e){if(!e.builtinDisabled)return;let t=e.builtinSettingsPath;return t?e.globalBuiltinSettingsPath?{key:"mcp.codemode.builtinDisabled",params:{path:t}}:{key:"mcp.codemode.builtinDisabledProject",params:{path:t}}:{key:"mcp.codemode.builtinDisabledUnknown"}}(t),x=function(e){let t=e.projectOverride;if(t)return{key:f6[t.preference],params:{path:t.settingsPath}}}(t);return(0,r.jsxs)(pF,{children:[(0,r.jsx)(pD,{children:(0,r.jsx)(pB,{children:(0,r.jsx)(p_,{children:d("mcp.codemode.title")})})}),(0,r.jsx)("p",{className:"mcp-config-line",children:d("mcp.codemode.intro")}),(0,r.jsxs)(pq,{children:[(0,r.jsx)(pV,{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)(pJ,{value:u,label:d("mcp.codemode.title"),options:[{value:"automatic",label:d(me.automatic),disabled:p},{value:"always",label:d(me.always),disabled:p||void 0!==m}],disabledReason:m?v3(m,d):null,onChange:e=>{e!==u&&l(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:fC(t.preferenceError??"")})]}),h.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[d("mcp.codemode.saveFailed")," ",(0,r.jsx)(bg,{error:h.error})]}),x&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:v3(x,d)}),f&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:v3(f,d)})]})}),t.mode?(0,r.jsx)(bx,{mode:t.mode,codemode:t,save:i,waiting:p,onChange:o}):void 0!==t.modeError&&(0,r.jsx)(pV,{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:fC(t.modeError)})]})}),t.inlineBudget?(0,r.jsx)(bv,{budget:t.inlineBudget,save:i,waiting:p,onSave:a}):void 0!==t.inlineBudgetError&&(0,r.jsx)(pV,{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:fC(t.inlineBudgetError)})]})}),(0,r.jsx)(pV,{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:fC(c.error)})]}):(0,r.jsx)("span",{className:"mcp-config-line",children:d("available"===c.state?"mcp.codemode.sandbox.available":"mcp.codemode.sandbox.not-checked")})}),g&&(0,r.jsx)(pV,{label:d("mcp.codemode.builtin"),tone:"error",children:v3(g,d)})]})]})}function bg(e){let{error:t}=e,{t:n}=(0,t_.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:fC(t.error)})}function bx(e){let{mode:t,codemode:n,save:i,waiting:s,onChange:l}=e,{t:o}=(0,t_.s)(),a="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:f7[r.value],params:{path:r.settingsPath}}),"only"===(r??t).value&&"automatic"===f5(e)&&n.push({key:"mcp.codemode.toolMode.automaticNote"}),n}(n);return(0,r.jsx)(pV,{label:o("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)(pJ,{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)&&l(e)},children:a&&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(f9[t.value])}),d.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:v3(e,o)},e.key)),a&&i.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[o("mcp.codemode.toolMode.saveFailed")," ",(0,r.jsx)(bg,{error:i.error})]})]})})}function bv(e){let t,n,{budget:s,save:l,waiting:o,onSave:a}=e,{t:d}=(0,t_.s)(),c=(0,i.useRef)(null),u=(0,i.useId)(),p=void 0===s.value?"":String(s.value),[h,f]=(0,i.useState)(p);(0,i.useEffect)(()=>{f(p)},[p]);let m=function(e,t){let n=e.trim();if(""===n)return{ok:!0,value:null};if(!/^\d+$/.test(n))return{ok:!1};let r=Number(n);return r<=t?{ok:!0,value:r}:{ok:!1}}(h,s.max),g=!!m.ok&&(null===m.value?void 0!==s.value||void 0!==s.invalid:m.value!==s.value),x="inlineBudget"===l.target,v=x&&l.saving,b=(0,i.useRef)(v);(0,i.useEffect)(()=>{let e=b.current;b.current=v,e&&!v&&to(document,c.current)},[v]);let y=(t=[],void 0!==s.invalid&&t.push({key:"mcp.codemode.inlineBudget.invalid",params:{path:s.settingsPath,value:s.invalid,default:String(s.default)}}),(n=s.projectOverride)&&t.push(void 0!==n.value?{key:"mcp.codemode.inlineBudget.projectOverride",params:{path:n.settingsPath,value:String(n.value)}}:{key:"mcp.codemode.inlineBudget.projectOverrideDefault",params:{path:n.settingsPath,default:String(s.default)}}),t);return(0,r.jsx)(pV,{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(),m.ok&&g&&!o&&a(m.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":!m.ok||void 0,value:h,placeholder:String(s.default),readOnly:o,autoComplete:"off",spellCheck:!1,onChange:e=>f(e.target.value)}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("mcp.codemode.inlineBudget.unit")}),(0,r.jsx)(p3,{type:"submit",size:"small",disabled:!g||o,children:d("mcp.codemode.inlineBudget.save")}),v&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:d("i18n.saving")})]}),!m.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:v3(e,d)},e.key)),x&&l.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[d("mcp.codemode.inlineBudget.saveFailed")," ",(0,r.jsx)(bg,{error:l.error})]})]})})}let bb=[{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 by(){let{t:e}=(0,t_.s)(),t=a3();return(0,r.jsx)("div",{className:"settings-font-rows",children:bb.map(n=>{let{kind:i,label:s,placeholder:l,reset:o,weightLabel:a}=n,d=t[`${i}Weight`],c=aF.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(l),maxLength:500,"aria-describedby":"settings-typography-description",autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,onChange:e=>t.setFontPreference(i,e.target.value)}),(0,r.jsx)("output",{htmlFor:`settings-font-${i}-weight`,title:`${e(a)}: ${d}`,children:e(aF[c].label)}),(0,r.jsx)(p3,{variant:"ghost",size:"small",className:"settings-chat-reset",title:e(o),"aria-label":e(o),disabled:!t[i]&&400===d,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:aF[0].value,max:aF[aF.length-1].value,step:100,value:d,"aria-label":e(a),"aria-valuetext":`${d} ${e(aF[c].label)}`,onChange:e=>t.setFontWeight(i,Number(e.target.value))})]},i)})})}function bw(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"})]}):"archives"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"4",rx:"1"}),(0,r.jsx)("path",{d:"M5 8v11a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"}),(0,r.jsx)("path",{d:"M10 12h4"})]}):"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"})]}):(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 bk(e){let{sessionId:t,onSessionReloaded:n,quoteSelectionEnabled:s,onQuoteSelectionChange:l}=e,{locale:o,setLocale:a,supportedLocales:d,t:c}=(0,t_.s)(),{preference:u,setThemePreference:p}=lo(),{width:h,setWidth:f,fontSize:m,setFontSize:g}=aO(),x=aj(),b=tH(),[y,w]=(0,i.useState)(null),[j,C]=(0,i.useState)(!1),[N,E]=(0,i.useState)(null),[$,I]=(0,i.useState)(!1),[M,T]=(0,i.useState)(null),[R,A]=(0,i.useState)(!1),[L,z]=(0,i.useState)(null),[P,W]=(0,i.useState)(!1),[O,F]=(0,i.useState)(null),[D,B]=(0,i.useState)(!1),[H,_]=(0,i.useState)(null),[U,K]=(0,i.useState)(!1),[q,V]=(0,i.useState)(!1),[Z,J]=(0,i.useState)("");(0,i.useEffect)(()=>{A(l9()),fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>K(e?.enabled===!0)).catch(()=>{})},[]);let Y=async()=>{V(!0),J("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);v.clear();let t=k();if(t)try{S(t).forEach(e=>t.removeItem(e))}catch{}window.location.replace("/login")}catch{J(c("auth.logoutFailed"))}finally{V(!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||w(n)}).catch(t=>{e||E(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||z(!0===n.enabled)}).catch(t=>{e||F(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]);let G=async e=>{W(!0),F(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}`);z(!0===i.enabled),t&&n()}catch(e){F(e instanceof Error?e.message:String(e))}finally{W(!1)}},X=async e=>{C(!0),E(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}`);w(i),t&&(await ce(t,{type:"reload"}),n())}catch(e){E(e instanceof Error?e.message:String(e))}finally{C(!1)}},Q=async(e,t)=>{if(y){I(!0),T(null);try{let n=t?[...y.builtinTools,e]:y.builtinTools.filter(t=>t!==e),r=await fetch("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({builtinTools:n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);w(i)}catch(e){T(e instanceof Error?e.message:String(e))}finally{I(!1)}}},ee=async()=>{if(!D){B(!0),_(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 hK(o))throw Error("unsupported or not permitted");_({kind:"ok",message:c("settings.pushRegistered")})}catch(e){_({kind:"error",message:`${c("settings.pushRegisterFailed")} ${e instanceof Error?e.message:String(e)}`})}finally{B(!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:s0.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)(by,{}),(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:[m,"px"]}),(0,r.jsx)(p3,{variant:"ghost",size:"small",className:"settings-chat-reset",title:c("settings.resetChatContentFontSize"),"aria-label":c("settings.resetChatContentFontSize"),disabled:14===m,onClick:()=>g(14),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:"settings-chat-content-font-size",type:"range",min:12,max:24,step:1,value:m,onChange:e=>g(Number(e.target.value))})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-width",children:c("settings.chatContentWidth")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-width",children:[h,"px"]}),(0,r.jsx)(p3,{variant:"ghost",size:"small",className:"settings-chat-reset",title:c("settings.resetChatContentWidth"),"aria-label":c("settings.resetChatContentWidth"),disabled:820===h,onClick:()=>f(820),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:"settings-chat-content-width",type:"range",min:820,max:2e3,step:10,value:h,onChange:e=>f(Number(e.target.value))})]})]})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children: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)(p5,{checked:R,label:c("settings.thinkingExpandedDefault"),onChange:e=>{!function(e){try{window.localStorage.setItem(l5,String(e))}catch{return}window.dispatchEvent(new Event(l6))}(e),A(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)(p5,{checked:s,label:c("settings.quoteSelection"),onChange:l})]}),(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:()=>ak("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:()=>ak("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)(p5,{checked:!0===L,loading:null===L&&!O||P,label:c("settings.cacheMissNotices"),describedBy:"settings-cache-miss-notices-description",onChange:e=>void G(e)})]})]}),(0,r.jsx)("p",{id:"settings-cache-miss-notices-description",className:"settings-general-description",children:c("settings.cacheMissNoticesDescription")}),O&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:O})]}),(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:()=>tB("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:()=>tB("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")})]}),y&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.builtinTools")}),(0,r.jsx)("p",{id:"settings-builtin-tools-description",className:"settings-general-description",children:c("settings.builtinToolsDescription")}),(0,r.jsx)("div",{className:"settings-send-mode-options settings-builtin-tools",role:"group","aria-label":c("settings.builtinTools"),"aria-describedby":"settings-builtin-tools-description",children:cc.kt.map(e=>(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"checkbox",checked:y.builtinTools.includes(e),disabled:$,onChange:t=>void Q(e,t.target.checked),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:"bash"===e&&y.powerShellEnabled?"powershell":e})]},e))}),M&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:M})]}),y?.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)(p5,{checked:y.powerShellEnabled,loading:j,label:c("settings.usePowerShell"),onChange:e=>void X(e)})]}),N&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:N})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.pushPermission")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:c("settings.pushPermissionDescription")}),(0,r.jsx)("button",{type:"button",className:"config-button config-button-small config-button-secondary",disabled:D,onClick:()=>void ee(),children:D?c("settings.pushRegisterLoading"):c("settings.pushRegister")})]}),H&&(0,r.jsx)("p",{role:"status",className:"settings-general-error",style:"ok"===H.kind?{color:"var(--accent)"}:void 0,children:H.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:()=>a(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)})})]}),U&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsxs)(p3,{variant:"secondary",disabled:q,onClick:()=>void Y(),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"})}),q?c("auth.loggingOut"):c("auth.logOut")]}),Z&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:Z})]})]})}let bj={home:"home",section:"home",detail:"section"},bS={home:0,section:1,detail:2},bC="cubic-bezier(0.2, 0.8, 0.2, 1)";function bN(e){let t,{cwd:n,sessionId:s,initialSection:l,openAtHome:o=!1,onClose:a,onSessionReloaded:d,quoteSelectionEnabled:c,onQuoteSelectionChange:u,projectTrust:p,onOpenTrustDialog:h,onProjectTrustChanged:f}=e,{t:m,locale:g}=(0,t_.s)(),[x,v]=(0,i.useState)(l),[b,y]=(0,i.useState)(()=>new Set([x])),w=[{id:"general",label:m("settings.general")},{id:"models",label:m("common.models")},{id:"archives",label:fv[g]??fv.en},{id:"skills",label:m("common.skills")},{id:"agents",label:m("common.agents")},{id:"plugins",label:m("common.plugins")},{id:"mcp",label:m("settings.mcp")}].map(e=>({...e,requiresProject:u8(e.id)})),k=u8(x),j=tQ(),S=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 l=(0,i.useRef)(0);(0,i.useEffect)(()=>{if(!e)return;let t=()=>{0!==l.current&&(l.current-=1,r(e=>bj[e]))};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[e]);let o=(0,i.useCallback)(t=>{e&&(window.history.pushState(window.history.state,""),l.current+=1,r(t))},[e]);return{level:n,levelRef:s,enter:o,goUp:(0,i.useCallback)(()=>{l.current>0?window.history.back():r(e=>bj[e])},[]),dropHistory:(0,i.useCallback)(()=>{let e=l.current;l.current=0,e>0&&window.history.go(-e)},[])}}(j,o),{dropHistory:C,enter:N,goUp:E,levelRef:$}=S,I=(0,i.useRef)(null),M=(0,i.useRef)(!1),T=(0,i.useRef)(null),R=(0,i.useRef)(S.level);(0,i.useLayoutEffect)(()=>{let e=R.current;R.current=S.level,j&&e!==S.level&&function(e,t,n,r){if(!e||"function"!=typeof e.animate||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;let i=bS[r]>bS[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:bC}),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:bC})})}(T.current,I.current,e,S.level)},[j,S.level]);let A=(0,i.useCallback)(()=>{C(),a()},[a,C]),L=w.find(e=>e.id===x)?.label??m("settings.title"),[z,P]=(0,i.useState)(null),W=(0,i.useMemo)(()=>({detailOpen:"detail"===S.level,openDetail:()=>{"section"===$.current&&(P(null),N("detail"))},closeDetail:()=>{"detail"===$.current&&E()},reportDetailTitle:P}),[N,E,S.level,$]);(0,i.useEffect)(()=>u9(l),[l]),(0,i.useEffect)(()=>{var e;let t;return e=document,t=e=>{"Escape"!==e.key||e.defaultPrevented||tl(e)||(e.preventDefault(),A())},e.addEventListener("keydown",t,!1),()=>e.removeEventListener("keydown",t,!1)},[A]);let O=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>(function(e,t){let{restoreTextEntry:n=!0}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=e.activeElement,i=!!(r&&t&&t.contains(r)),s=r&&r!==e.body&&!i?r:null;return t&&!i&&t.focus({preventScroll:!0}),()=>{if(!s||!s.isConnected||!n&&function(e){if(e.isContentEditable)return!0;let t=e.tagName?.toUpperCase();return"TEXTAREA"===t||"INPUT"===t&&!["button","checkbox","color","file","hidden","image","radio","range","reset","submit"].includes((e.type??"text").toLowerCase())}(s))return;let r=e.activeElement;r&&r!==e.body&&!(t&&t.contains(r))||"function"==typeof s.focus&&s.focus({preventScroll:!0})}})(document,O.current,{restoreTextEntry:!window.matchMedia?.("(pointer: coarse)").matches}),[]),(0,i.useEffect)(()=>{!n&&k&&(v("general"),y(e=>new Set(e).add("general")),u9("general"))},[n,k]);let F=e=>{y(t=>new Set(t).add(e)),v(e),u9(e)},D=(e,t)=>b.has(e)?(0,r.jsx)("div",{hidden:x!==e||"home"===S.level,"data-phone-level":j?S.level:void 0,className:"settings-section-host",children:t},e):null;return(0,r.jsx)("div",{ref:O,role:"dialog","aria-modal":"true","aria-label":m("settings.title"),tabIndex:-1,onPointerDown:e=>{M.current=e.target===e.currentTarget},onPointerCancel:()=>{M.current=!1},onClick:e=>{let t=M.current;M.current=!1,t&&e.target===e.currentTarget&&A()},className:"settings-dialog-backdrop",children:(0,r.jsxs)("div",{className:"settings-dialog-surface",children:[(0,r.jsxs)("div",{ref:I,className:"settings-dialog-header",children:[j&&"home"!==S.level&&(t="detail"===S.level?L:m("settings.title"),(0,r.jsxs)("button",{type:"button",className:"settings-phone-back",onClick:E,"aria-label":m("settings.backTo",{name:t}),children:[(0,r.jsx)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m15 18-6-6 6-6"})}),(0,r.jsx)("span",{children:t})]})),(0,r.jsx)("strong",{className:"settings-dialog-title",children:j&&"home"!==S.level?"section"===S.level?L:z:m("settings.title")}),(0,r.jsx)("nav",{"aria-label":m("settings.title"),className:"settings-section-tabs",children:w.map(e=>{let t=x===e.id,i=e.requiresProject&&!n;return(0,r.jsxs)("button",{type:"button",className:"settings-section-tab",disabled:i,title:i?m("settings.projectRequired"):e.label,"aria-current":t?"page":void 0,onClick:()=>F(e.id),children:[(0,r.jsx)(bw,{section:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id)})}),(0,r.jsx)("button",{type:"button",onClick:A,title:m("i18n.close"),"aria-label":m("i18n.close"),className:"config-close-button settings-dialog-close",children:"\xd7"})]}),(0,r.jsxs)("main",{ref:T,className:"settings-dialog-main",children:[j&&"home"===S.level&&(0,r.jsx)("nav",{"aria-label":m("settings.title"),className:"settings-phone-home",children:w.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:()=>{F(e.id),N("section")},children:[(0,r.jsx)(bw,{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:m("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)(pE.Provider,{value:W,children:[D("general",(0,r.jsx)(bk,{sessionId:s,onSessionReloaded:d,quoteSelectionEnabled:c,onQuoteSelectionChange:u})),D("models",(0,r.jsx)(h_,{embedded:!0,cwd:n,onClose:A})),D("archives",(0,r.jsx)(fw,{embedded:!0,onClose:A})),n&&D("skills",(0,r.jsx)(h0,{embedded:!0,cwd:n,trust:p,onClose:A},n)),n&&D("agents",(0,r.jsx)(fr,{embedded:!0,cwd:n,sessionId:s,trust:p,onClose:A,onReloaded:d},n)),n&&D("plugins",(0,r.jsx)(fg,{embedded:!0,cwd:n,sessionId:s,trust:p,onClose:A,onReloaded:d},n)),D("mcp",(0,r.jsx)(v7,{embedded:!0,cwd:n,trust:p,onTrustProject:h,onProjectTrustChanged:f,onClose:A},n??""))]})]})]})})}let bE="project-trust-mcp-status";function b$(e){let{cwd:t,busy:n,error:s,onCancel:l,onConfirm:o,onStatus:a}=e,[d,c]=(0,i.useState)({state:"loading"}),u=(0,i.useRef)(a);return(0,i.useEffect)(()=>{u.current=a},[a]),(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)(bI,{cwd:t,busy:n,error:s,listing:d,onCancel:l,onConfirm:o})}function bI(e){let{cwd:t,busy:n,error:s,listing:l,onCancel:o,onConfirm:a}=e,{t:d}=(0,t_.s)(),c="loading"===l.state,u="loaded"===l.state?function(e){if(e){if(!e.requiresTrust)return"mcp.reason.trust-not-required";if(e.trusted)return"trust.alreadyTrusted"}}(l.status):void 0,p=(0,i.useRef)(null),h=(0,i.useRef)(n),f=(0,i.useRef)(o);return(0,i.useEffect)(()=>{h.current=n,f.current=o},[n,o]),(0,i.useEffect)(()=>{var e,t,n;let r,i,s;return e=document,t=p.current,n=()=>{h.current||f.current()},r=e.activeElement,t?.focus({preventScroll:!0}),i=e=>{"Escape"!==e.key||(e.stopPropagation(),tl(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:fC(t)}),u&&(0,r.jsx)("p",{id:"project-trust-notice",role:"status",className:"project-trust-notice",children:d(u)}),"loaded"===l.state&&void 0!==l.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:fC(l.statusError)})]}),(0,r.jsx)(bT,{listing:l})]})]}),s&&(0,r.jsx)(bM,{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:a,disabled:n||c,"aria-busy":n||void 0,"aria-describedby":c?bE:void 0,children:d(n?"trust.trusting":"trust.trustProject")})]})]})})}function bM(e){let{error:t}=e,{t:n}=(0,t_.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:fC(t.error)})]})}function bT(e){let{listing:t}=e,{t:n}=(0,t_.s)();if("loading"===t.state)return(0,r.jsx)("p",{id:bE,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:fC(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)(bR,{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)(bz,{server:e},e.name))})]}):null}function bR(e){let{file:t}=e,{t:n}=(0,t_.s)();return(0,r.jsx)(r.Fragment,{children:t.problems.map(e=>{let i=fz(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 bA(e){let{fields:t}=e,{t:n}=(0,t_.s)();return(0,r.jsx)(r.Fragment,{children:t.map(e=>{let t=fT(e);return(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function bL(e){let{server:t}=e,{t:n}=(0,t_.s)();return(0,r.jsx)(r.Fragment,{children:fL(t.variableReferences).map(e=>{let{variable:t,field:i}=e,s=fT(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 bz(e){let t,{server:n}=e,{t:i}=(0,t_.s)(),s=fI(n),l=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:fC(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:fC(n.cwd)})}),fM(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:fC(n.invalidError)})]}),n.webPasswordField&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.webPassword")," ",(0,r.jsx)(bA,{fields:[n.webPasswordField]})]}),!n.enabled&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:i("mcp.server.disabled")}),l&&n.commandFields.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.commandFields")," ",(0,r.jsx)(bA,{fields:n.commandFields})]}),l&&n.variableReferences.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i(fR(n))," ",(0,r.jsx)(bL,{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=fA(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 bP(e){return"message"===e.type&&"message"in e&&"system"!==e.message.role}function bW(e){let t=e,n=t.branchPreview,r=bP(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&bP(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function bO(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 bF(e){let{node:t,activePathIds:n,depth:i,isLast:s,parentLines:l,onSelect:o}=e,{node:a,skipped:d,branchPreview:c,labelEntry:u}=bW(t),p=n.has(a.entry.id),h=n.has(t.entry.id)||n.has(a.entry.id),f=c?.text??function(e){if("message"===e.type&&bP(e)){let t=e.message,n=t.content,r="";if("string"==typeof n?r=n:Array.isArray(n)&&(r=n.filter(e=>"text"===e.type).map(e=>e.text).join(" ")),r.length>40&&(r=r.slice(0,40)+"…"),r)return r;if("assistant"===t.role)return"[assistant]"}return e.type}(u),m=c?c.role??null:bP(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(a.entry.id):void 0,children:[l.map((e,t)=>(0,r.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,r.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:s?"50%":0,width:1,background:"var(--border)"}}),(0,r.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,r.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:p?"var(--accent)":h?"var(--text-muted)":"var(--border)",border:p?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),m&&(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===m?"var(--accent)":"var(--text-dim)",background:"user"===m?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===m?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===m?"U":"A"}),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:f})]}),a.children.map((e,t)=>(0,r.jsx)(bF,{node:e,activePathIds:n,depth:i+1,isLast:t===a.children.length-1,parentLines:[...l,!s],onSelect:o},e.entry.id))]})}function bD(e){let{tree:t,activeLeafId:n,onLeafChange:s,inline:l,containerRef:o,open:a,onToggle:d,hasSession:c,compact:u,hideInlineButton:p,locked:h=!1}=e,{t:f}=(0,t_.s)(),[m,g]=(0,i.useState)(!1),x=void 0!==a?a:m,v=(0,i.useRef)(null),[b,y]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!x||!l)return;let e=o?.current??v.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();y({top:t.bottom,left:t.left,width:t.width})};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[x,l,o]);let w=(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]),j=h?void 0:k,S=h&&(0,r.jsx)("div",{style:{padding:"2px 0 4px",fontSize:11,color:"var(--text-dim)",fontStyle:"italic"},children:f("i18n.branchesLockedWhileRunning")}),C=c?bO(t)?null:f("i18n.noBranches"):f("i18n.noActiveSession"),N=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=bW(e[0]).node;return t.children.length>1?t.children:[]}(t),E=!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:E?"var(--accent)":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),I=(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 l?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"stretch"},children:[(0,r.jsxs)("button",{ref:v,onClick:()=>d?d():g(e=>!e),style:{display:p?"none":"flex",alignItems:"center",gap:6,height:"100%",padding:"0 12px",background:x?"var(--bg-selected)":"none",border:"none",borderTop:x?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:"pointer",color:x?"var(--text)":"var(--text-muted)",fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color=x?"var(--text)":"var(--text-muted)"},title:f("i18n.branches"),"aria-label":f("i18n.branches"),"aria-pressed":x,children:[$,!u&&(0,r.jsx)("span",{children:f("i18n.branches")})]}),x&&b&&(0,r.jsx)("div",{style:{position:"fixed",top:b.top,left:b.left,width:b.width,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",zIndex:500},children:E?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(bF,{node:e,activePathIds:w,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:j},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C})})]}):(0,r.jsxs)("div",{style:{borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>g(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"5px 12px",background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",fontSize:11,textAlign:"left"},children:[$,(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:f("i18n.branches")}),I]}),x&&(0,r.jsx)("div",{style:{position:"absolute",top:"100%",left:0,right:0,background:"var(--bg)",borderBottom:"1px solid var(--border)",boxShadow:"0 4px 12px rgba(0,0,0,0.1)",zIndex:100},children:E?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(bF,{node:e,activePathIds:w,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:j},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C??f("i18n.noBranches")})})]})}function bB(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:`
84
+ .system-prompt-panel {
85
+ display: flex;
86
+ height: min(600px, 75dvh);
87
+ min-height: 220px;
88
+ flex-direction: column;
89
+ background: var(--bg-panel);
90
+ border-bottom: 1px solid var(--border);
91
+ }
92
+ .system-prompt-scroll {
93
+ min-height: 0;
94
+ flex: 1;
95
+ overflow: auto;
96
+ padding: 12px 16px;
97
+ }
98
+ .system-prompt-text {
99
+ color: var(--text-muted);
100
+ font-family: var(--font-mono);
101
+ font-size: 12px;
102
+ line-height: 1.6;
103
+ overflow-wrap: anywhere;
104
+ white-space: pre-wrap;
105
+ }
106
+ .system-prompt-empty {
107
+ padding: 10px 0;
108
+ color: var(--text-muted);
109
+ font-size: 12px;
110
+ font-style: italic;
111
+ }
112
+ `})]})}function bH(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e)}catch{return String(e)}}function b_(e){let{children:t}=e;return(0,r.jsx)("div",{className:"tool-definitions-empty",children:t})}function bU(e){let{loading:t,tools:n,translate:s}=e,l=(0,i.useMemo)(()=>n?.filter(e=>e.active&&!e.declarationHidden)??null,[n]),[o,a]=(0,i.useState)(null);(0,i.useEffect)(()=>{a(e=>l?.some(t=>t.name===e)?e:l?.[0]?.name??null)},[l]);let d=l?.find(e=>e.name===o)??l?.[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 bH(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(bH).join(", "):void 0,defaultValue:void 0===i.default?void 0:bH(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:l&&l.length>0?l.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:()=>a(e.name),children:(0,r.jsx)("code",{children:e.name})},e.name)}):l?(0,r.jsx)(b_,{children:s("tools.noTools")}):(0,r.jsx)(b_,{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)(b_,{children:l?s("tools.noTools"):t?s("tools.loading"):s("tools.load")})}),(0,r.jsx)("style",{children:`
113
+ .tool-definitions-panel {
114
+ display: grid;
115
+ grid-template-columns: clamp(112px, 26%, 220px) minmax(0, 1fr);
116
+ height: min(600px, 75dvh);
117
+ min-height: 240px;
118
+ overflow: hidden;
119
+ background: var(--bg-panel);
120
+ border-bottom: 1px solid var(--border);
121
+ }
122
+ .tool-definitions-sidebar,
123
+ .tool-definition-detail {
124
+ display: flex;
125
+ min-width: 0;
126
+ min-height: 0;
127
+ flex-direction: column;
128
+ }
129
+ .tool-definitions-sidebar {
130
+ border-right: 1px solid var(--border);
131
+ background: color-mix(in srgb, var(--bg-panel) 94%, var(--bg));
132
+ }
133
+ .tool-definitions-list,
134
+ .tool-definition-scroll {
135
+ min-height: 0;
136
+ flex: 1;
137
+ overflow: auto;
138
+ }
139
+ .tool-definitions-item {
140
+ display: flex;
141
+ width: 100%;
142
+ min-height: 38px;
143
+ align-items: center;
144
+ padding: 8px 12px;
145
+ border: none;
146
+ border-bottom: 1px solid var(--border);
147
+ background: transparent;
148
+ color: var(--text-muted);
149
+ cursor: pointer;
150
+ text-align: left;
151
+ }
152
+ .tool-definitions-item:hover {
153
+ background: var(--bg-hover);
154
+ color: var(--text);
155
+ }
156
+ .tool-definitions-item.selected {
157
+ background: var(--bg-selected);
158
+ box-shadow: inset 2px 0 0 var(--accent);
159
+ color: var(--text);
160
+ }
161
+ .tool-definitions-item code {
162
+ max-width: 100%;
163
+ color: inherit;
164
+ font-size: 11px;
165
+ font-weight: 600;
166
+ overflow-wrap: anywhere;
167
+ }
168
+ .tool-definition-scroll {
169
+ padding: 14px 16px 20px;
170
+ }
171
+ .tool-definition-section + .tool-definition-section {
172
+ margin-top: 18px;
173
+ }
174
+ .tool-definition-section-label {
175
+ display: flex;
176
+ align-items: center;
177
+ justify-content: space-between;
178
+ gap: 8px;
179
+ margin-bottom: 7px;
180
+ color: var(--text-dim);
181
+ font-size: 11px;
182
+ font-weight: 600;
183
+ }
184
+ .tool-definition-section-label > span:last-child {
185
+ font-weight: 400;
186
+ white-space: nowrap;
187
+ }
188
+ .tool-definition-description {
189
+ color: var(--text-muted);
190
+ font-size: 12px;
191
+ line-height: 1.55;
192
+ overflow-wrap: anywhere;
193
+ white-space: pre-wrap;
194
+ }
195
+ .tool-definition-fields {
196
+ border-top: 1px solid var(--border);
197
+ }
198
+ .tool-definition-field {
199
+ display: grid;
200
+ grid-template-columns: minmax(88px, 0.75fr) minmax(0, 1.5fr);
201
+ gap: 12px;
202
+ padding: 9px 0;
203
+ border-bottom: 1px solid var(--border);
204
+ font-size: 11px;
205
+ line-height: 1.45;
206
+ }
207
+ .tool-definition-field-name {
208
+ display: flex;
209
+ min-width: 0;
210
+ flex-direction: column;
211
+ gap: 3px;
212
+ color: var(--text);
213
+ }
214
+ .tool-definition-field-name code {
215
+ overflow-wrap: anywhere;
216
+ }
217
+ .tool-definition-field-name span {
218
+ color: var(--text-dim);
219
+ font-size: 10px;
220
+ }
221
+ .tool-definition-field-name span.required {
222
+ color: var(--accent);
223
+ }
224
+ .tool-definition-field-value {
225
+ min-width: 0;
226
+ color: var(--text-muted);
227
+ overflow-wrap: anywhere;
228
+ }
229
+ .tool-definition-type {
230
+ display: block;
231
+ margin-bottom: 3px;
232
+ color: var(--text);
233
+ }
234
+ .tool-definition-meta {
235
+ margin-top: 4px;
236
+ color: var(--text-dim);
237
+ }
238
+ .tool-definition-meta code {
239
+ color: var(--text-muted);
240
+ }
241
+ .tool-definition-no-parameters {
242
+ padding: 2px 0 10px;
243
+ color: var(--text-dim);
244
+ font-size: 11px;
245
+ }
246
+ .tool-definition-guidelines {
247
+ margin: 0;
248
+ padding-left: 18px;
249
+ color: var(--text-muted);
250
+ font-size: 11px;
251
+ line-height: 1.5;
252
+ }
253
+ .tool-definitions-empty {
254
+ padding: 14px 12px;
255
+ color: var(--text-muted);
256
+ font-size: 12px;
257
+ font-style: italic;
258
+ overflow-wrap: anywhere;
259
+ }
260
+ @media (max-width: 640px) {
261
+ .tool-definitions-panel {
262
+ grid-template-columns: 112px minmax(0, 1fr);
263
+ }
264
+ .tool-definitions-item {
265
+ padding: 8px 10px;
266
+ }
267
+ .tool-definition-scroll {
268
+ padding: 12px;
269
+ }
270
+ .tool-definition-field {
271
+ grid-template-columns: minmax(74px, 0.7fr) minmax(0, 1.3fr);
272
+ gap: 9px;
273
+ }
274
+ }
275
+ `})]})}async function bK(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:fetch,r={};for(let i=0;i<e.length;i+=200){let s=await n("/api/sessions/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:e.slice(i,i+200)}),signal:t,cache:"no-store"});if(!s.ok)return null;let l=await s.json();if(!l.stats)return null;Object.assign(r,l.stats)}return r}function bq(e){let{usage:t,style:n}=e,{locale:i,t:s}=(0,t_.s)(),l=cg(t.cost);return(0,r.jsxs)("span",{title:function(e,t,n){let{tokens:r}=e;return[`${t("session.totalActive")}: ${cx(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"})]}),cx(t.totalActiveMs)]}),t.tokens.total>0&&(0,r.jsx)("span",{children:s("agentSwitcher.tokens",{count:cm(t.tokens.total)})}),l&&(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:l})]})}function bV(e){return!!(e&&(e.tokens.total>0||e.totalActiveMs>0))}function bZ(e){return e.name||e.firstMessage||e.id.slice(0,12)}function bJ(e){let t=e.relation?.kind==="subagent"?e.relation:null;return e.name||t?.description||bZ(e)}function bY(e){let{kind:t,size:n}=e;return(0,r.jsx)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:"main"===t?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"8",r:"4"}),(0,r.jsx)("path",{d:"M4 21a8 8 0 0 1 16 0"})]}):"side"===t?(0,r.jsx)("path",{d:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]})})}function bG(e,t){let n=new Date(e).getTime();if(!Number.isFinite(n))return"";let r=Math.round((n-Date.now())/1e3),i=new Intl.RelativeTimeFormat(t,{numeric:"auto"});if(60>Math.abs(r))return i.format(r,"second");let s=Math.round(r/60);if(60>Math.abs(s))return i.format(s,"minute");let l=Math.round(s/60);return 24>Math.abs(l)?i.format(l,"hour"):i.format(Math.round(l/24),"day")}function bX(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 bQ(e){let{session:t,main:n,sideTitle:s,selected:l,running:o,usage:a,onSelect:d,tabShown:c,onToggleTab:u,onNewSideChat:p,newSideChatPending:h,onDelete:f,confirming:m,onDeleteConfirm:g,onDeleteCancel:x}=e,{locale:v,t:b}=(0,t_.s)(),y=t.relation?.kind==="subagent"?t.relation:null,w=t.relation?.kind==="side",k=o?"running":y?.status??"completed",j=n?b("agentSwitcher.main"):w?s??b("agentSwitcher.sideChat"):bJ(t),S=w?b("agentSwitcher.sideChat"):y?.profile??b("agentSwitcher.subagent"),C=a?.model?.modelId,N=a?.thinkingLevel&&"off"!==a.thinkingLevel?a.thinkingLevel:void 0,E=n?bZ(t):w?bG(t.modified,v):S,$=n?E:[S,a?.model?`${a.model.provider}/${a.model.modelId}`:void 0,N,bG(t.modified,v)].filter(Boolean).join(" \xb7 "),I=(0,i.useRef)(null),[M,T]=(0,i.useState)();return m&&g&&x?(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:5,height:M,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)(rN,{label:b("sidebar.deleteSession",{title:j}),deleteLabel:b("sidebar.delete"),cancelLabel:b("sidebar.cancel"),onConfirm:g,onCancel:x})}):(0,r.jsxs)("div",{ref:I,style:{display:"flex",borderBottom:"1px solid var(--border)",borderLeft:l?"2px solid var(--accent)":"2px solid transparent",background:l?"var(--bg-selected)":"transparent"},children:[(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":l,onClick:d,className:l?"bg-transparent":"bg-transparent hover:bg-bg-hover",style:{flex:1,minWidth:0,minHeight:56,display:"grid",gridTemplateColumns:"28px minmax(0, 1fr) auto",alignItems:"center",gap:9,padding:"7px 12px",border:"none",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{width:28,height:28,display:"grid",placeItems:"center",color:n?"var(--text-muted)":"var(--accent)"},children:(0,r.jsx)(bY,{kind:n?"main":w?"side":"subagent",size:17})}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12,fontWeight:l?600:500},title:j,children:j}),(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:E}),!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]})]}),bV(a)&&(0,r.jsx)(bq,{usage:a,style:{marginTop:3}})]}),(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",gap:6,color:(n||w)&&!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||w)&&!o?l?b("agentSwitcher.current"):null:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(bX,{status:k}),(0,r.jsx)("span",{children:b(`agentSwitcher.status.${k}`)})]})})]}),p&&(0,r.jsx)(b0,{title:b("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)(b0,{title:b(l?"agentSwitcher.openInMainChat":c?w?"sideChat.closeTab":"subagent.closeTab":w?"sideChat.openTab":"subagent.openTab"),pressed:c,disabled:l,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"})]})}),f&&(0,r.jsx)(b0,{title:b("sidebar.delete"),danger:!0,onClick:()=>{T(I.current?.offsetHeight),f()},children:(0,r.jsx)(ri,{size:14})})]})}function b0(e){let{title:t,pressed:n,danger:i,disabled:s,onClick:l,children:o}=e,a=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:l,title:t,"aria-label":t,"aria-pressed":n,disabled:s,className:`bg-transparent ${a}`,style:{width:36,display:"grid",placeItems:"center",border:"none",borderLeft:"1px solid var(--border)",flexShrink:0},children:o})}function b1(e){let{rootSession:t,subagents:n,selectedSessionId:s,runningSessionIds:l,onSelectSession:a,openSubagentTabIds:d,onToggleSubagentTab:c,onNewSideChat:p,onDeleteSideChat:h}=e,{t:f}=(0,t_.s)(),[m,g]=(0,i.useState)(""),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(null),C=async()=>{v(!0),y(null);try{y(await p())}catch(e){y(e instanceof Error?e.message:String(e))}finally{v(!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(f("sidebar.deleteFailed",{error:t}))},E=(0,i.useMemo)(()=>[...n].sort((e,t)=>{let n=l.has(e.id);return n!==l.has(t.id)?n?-1:1:t.modified.localeCompare(e.modified)}),[l,n]),$=m.trim().toLowerCase(),I=$?E.filter(e=>{let t=e.relation?.kind==="subagent"?e.relation:null,n=e.relation?.kind==="side"?f("agentSwitcher.sideChat"):null;return[t?.description,t?.profile,n,e.name,e.firstMessage].some(e=>e?.toLowerCase().includes($))}):E,M=u(n,l),T=(0,i.useMemo)(()=>[t.id,...n.map(e=>e.id)],[t.id,n]),R=T.filter(e=>l.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,l=async()=>{if(!i){i=!0;try{let t=await bK(e,n.signal);!n.signal.aborted&&t&&r(t)}catch{}finally{i=!1}}};if(l(),!t)return()=>n.abort();let o=setInterval(()=>{"visible"===document.visibilityState&&l()},3e3);return()=>{clearInterval(o),n.abort()}},[s,t]),n}(T,R),L=(0,i.useMemo)(()=>{let e=T.map(e=>A[e]).filter(bV);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},[T,A]);return(0,r.jsx)("div",{role:"listbox","aria-label":f("agentSwitcher.title"),style:{background:"var(--bg-panel)",borderRight:"1px solid var(--border)",borderBottom:"1px solid var(--border)",borderRadius:"0 0 6px 0",boxShadow:"0 10px 28px rgba(0,0,0,0.10)",overflow:"hidden"},children:(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{minHeight:44,display:"flex",alignItems:"center",gap:8,padding:"7px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("strong",{style:{fontSize:12,fontWeight:600},children:f("agentSwitcher.title")}),n.length>0&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:1===n.length?f("agentSwitcher.countOne",{count:n.length}):f("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:f("agentSwitcher.totalUsageHint"),children:f("agentSwitcher.totalUsage")}),(0,r.jsx)(bq,{usage:L})]}),M>0&&(0,r.jsx)("span",{style:{color:"var(--accent)",fontSize:11,whiteSpace:"nowrap"},children:f("agentSwitcher.runningCount",{count:M})})]})]}),n.length>8&&(0,r.jsx)("div",{style:{padding:8,borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{type:"search",value:m,onChange:e=>g(e.target.value),placeholder:f("agentSwitcher.search"),"aria-label":f("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)(bQ,{session:t,main:!0,selected:t.id===s,running:l.has(t.id),usage:A[t.id],onSelect:()=>a(t),onNewSideChat:C,newSideChatPending:x}),(b||j)&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 12px",borderBottom:"1px solid var(--border)",color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:b??j}),I.map(e=>(0,r.jsx)(bQ,{session:e,sideTitle:e.relation?.kind==="side"?o(e,f("agentSwitcher.sideChat"),n):void 0,selected:e.id===s,running:l.has(e.id),usage:A[e.id],onSelect:()=>a(e),tabShown:d.has(e.id),onToggleTab:()=>{let t=e.relation?.kind==="subagent"?e.relation:null;e.relation?.kind==="side"?c(e.id,f("sideChat.title"),!0):c(e.id,e.name||t?.description||t?.profile||bZ(e))},onDelete:e.relation?.kind==="side"?()=>k(e.id):void 0,confirming:w===e.id,onDeleteConfirm:()=>{N(e.id)},onDeleteCancel:()=>k(null)},e.id)),n.length>0&&0===I.length&&(0,r.jsx)("div",{style:{padding:"22px 12px",color:"var(--text-dim)",fontSize:12,textAlign:"center"},children:f("agentSwitcher.noMatches")})]})]})})}let b2="\0lock";function b4(e){let{rootSession:t,members:n,selectedSessionId:s,runningSessionIds:l,onSelectSession:a,locked:d,onToggleLock:c}=e,{t:u}=(0,t_.s)(),p=(0,i.useRef)(null),h=uX('[aria-current="true"]',`${n.length}
276
+ ${s}`),[f,m]=(0,i.useState)(null),g=f&&(f===t.id||f===b2||n.some(e=>e.id===f))?f:s,x=s===t.id,v=u("agentSwitcher.status.running"),b=l.has(t.id);return(0,r.jsxs)("div",{ref:p,role:"toolbar","aria-label":u("agentSwitcher.strip"),onKeyDown:e=>{let t=[...p.current?.querySelectorAll("button")??[]],n=t.indexOf(document.activeElement);if(n<0)return;let r="ArrowRight"===e.key?Math.min(n+1,t.length-1):"ArrowLeft"===e.key?Math.max(n-1,0):"Home"===e.key?0:"End"===e.key?t.length-1:-1;r<0||(e.preventDefault(),t[r].focus())},style:{display:"flex",alignItems:"center",gap:6,height:34,padding:"0 8px",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)(b8,{label:u("agentSwitcher.main"),title:x?u("agentSwitcher.main"):u("agentSwitcher.backToMain"),current:x,tabStop:g===t.id,icon:b?(0,r.jsx)(bX,{status:"running"}):x?(0,r.jsx)(bY,{kind:"main",size:12}):(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M19 12H5M11 6l-6 6 6 6"})}),running:b,onFocus:()=>m(t.id),onClick:()=>a(t)}),(0,r.jsx)("span",{"aria-hidden":"true",style:{width:1,height:16,flexShrink:0,background:"var(--border)"}}),(0,r.jsx)("div",{ref:h,className:"tabbar-scroll",style:{flex:1,minWidth:0,height:"100%",display:"flex",alignItems:"center",gap:6,overflowX:"auto",overflowY:"hidden"},children:n.map(e=>{let t=e.relation?.kind==="side",i=e.relation?.kind==="subagent"?e.relation:null,d=t?o(e,u("agentSwitcher.sideChat"),n):bJ(e),c=l.has(e.id),p=t?u("agentSwitcher.sideChat"):i?.profile??u("agentSwitcher.subagent");return(0,r.jsx)(b8,{label:d,title:[d,p,c?v:null].filter(Boolean).join(" \xb7 "),current:e.id===s,tabStop:g===e.id,icon:c?(0,r.jsx)(bX,{status:"running"}):(0,r.jsx)(bY,{kind:t?"side":"subagent",size:12}),running:c,onFocus:()=>m(e.id),onClick:()=>a(e)},e.id)})}),(0,r.jsx)("span",{"aria-hidden":"true",style:{width:1,height:16,flexShrink:0,background:"var(--border)"}}),(0,r.jsx)(dB,{locked:d,iconSize:14,onClick:c,onFocus:()=>m(b2),"aria-label":u("agentSwitcher.lockStrip"),title:d?u("agentSwitcher.unlockStrip"):u("agentSwitcher.lockStrip"),tabIndex:g===b2?0:-1,style:{flexShrink:0,width:24,height:24,borderRadius:6}})]})}function b8(e){let{label:t,title:n,current:i,tabStop:s,icon:l,running:o,onFocus:a,onClick:d}=e;return(0,r.jsxs)("button",{type:"button",onClick:d,onFocus:a,title:n,tabIndex:s?0:-1,"aria-current":i?"true":void 0,className:i?"cursor-pointer text-text":"cursor-pointer bg-transparent text-text-muted hover:bg-bg-hover hover:text-text",style:{display:"flex",alignItems:"center",gap:5,flexShrink:0,maxWidth:200,height:24,padding:"0 9px",border:`1px solid ${i?"var(--accent)":"var(--border)"}`,borderRadius:12,background:i?"var(--bg-selected)":void 0,fontSize:11,fontWeight:i?600:500,whiteSpace:"nowrap"},children:[(0,r.jsx)("span",{style:{display:"grid",placeItems:"center",flexShrink:0,color:o||i?"var(--accent)":"var(--text-dim)"},children:l}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})]})}let b3={idle:"debug.stream.state.idle",connecting:"debug.stream.state.connecting",connected:"debug.stream.state.connected",retrying:"debug.stream.state.retrying"},b5={ready_timeout:"debug.stream.error.readyTimeout",startup_error:"debug.stream.error.startup",error:"debug.stream.error.error",stale:"debug.stream.error.stale"},b6={visible:"debug.stream.reattach.visible",activity:"debug.stream.reattach.activity"},b9={agent:"debug.page.source.agent","file-watch":"debug.page.source.fileWatch",terminal:"debug.page.source.terminal"},b7={connecting:"debug.page.source.connecting",open:"debug.page.source.open"},ye={reply:"debug.lease.outcome.reply",unanswered:"debug.lease.outcome.unanswered",error:"debug.lease.outcome.error"},yt={alive:"debug.state.alive",closing:"debug.state.closing",none:"debug.state.none"},yn={timeout:"debug.poll.timeout",http:"debug.poll.http",network:"debug.poll.network",invalid:"debug.poll.invalid"},yr={starting:"agentSwitcher.status.starting",queued:"agentSwitcher.status.queued",running:"agentSwitcher.status.running",completed:"agentSwitcher.status.completed",failed:"agentSwitcher.status.failed",aborted:"agentSwitcher.status.aborted",interrupted:"agentSwitcher.status.interrupted",unknown:"debug.unknown"},yi={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 ys(e,t,n){return Object.prototype.hasOwnProperty.call(t,e)?n(t[e]):e}function yl(e){return Number.isFinite(e)?Math.max(0,e):0}function yo(e){return String(e).padStart(2,"0")}function ya(e,t){let n=yl(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:yo(Math.floor(n%6e4/1e3))}):n<864e5?t("debug.duration.hoursMinutes",{hours:Math.floor(n/36e5),minutes:yo(Math.floor(n%36e5/6e4))}):t("debug.duration.daysHours",{days:Math.floor(n/864e5),hours:Math.floor(n%864e5/36e5)})}function yd(e,t){return t("debug.time.ago",{time:ya(e,t)})}function yc(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"floor",r=Math[n](yl(e)/1e3);return r<60?t("debug.duration.seconds",{count:r}):ya(1e3*r,t)}function yu(e,t){return e>0?t("debug.time.in",{time:yc(e,t,"ceil")}):t("debug.time.due")}function yp(e,t){return e>0?t("debug.time.in",{time:ya(e,t)}):t("debug.time.due")}function yh(e){return e.length>8?e.slice(0,8):e}function yf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ym(e){return"number"==typeof e&&Number.isFinite(e)}function yg(e){var t;return yf(e)&&"string"==typeof e.sessionId&&"string"==typeof e.state&&ym(e.eventStreams)&&(null===(t=e.nextIdleCheckAt)||ym(t))}function yx(e,t){try{return e()}catch{return t}}function yv(e){if(!e)return{client:null,failed:!1};try{return{client:e()??null,failed:!1}}catch{return{client:null,failed:!0}}}function yb(e,t){return e?.sessionId??t}let yy={sessionId:null,reply:null,receivedAt:null,roundTripMs:null,failure:null,requests:0,failures:0,consecutiveFailures:0},yw=e=>e.filter(Boolean).join(" \xb7 ");function yk(e,t,n){return null===e?n("debug.holder.none"):`${n(e===t?"debug.holder.thisPage":"debug.holder.otherPage")} ${yh(e)}`}function yj(e,t){let n=e.filter(e=>null!==e.holder&&e.holder===t);return[...n,...e.filter(e=>!n.includes(e))]}let yS={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 yC(e){return e.awaitingInput?"awaiting":e.running?"running":e.state}function yN(e,t){return null===e.label?"—":"agent"===e.kind?t?.(e.label)??yh(e.label):ek(e.label)}function yE(e,t){if(!(t>0))return null;let n=e/t;return Number.isFinite(n)?Math.min(1,Math.max(0,n)):0}function y$(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 yI(e,t){return t>0?e>=t?"error":e>=t/2?"warning":"dim":"dim"}let yM={poll:[],running:[]};function yT(e){let t=yl(e);return{ms:t,tone:t>=2e3?"warning":"dim",failed:!1}}function yR(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 yA(e){let t=Date.parse(e.modified);return Number.isFinite(t)?t:-1/0}function yL(e,t){return e===t?0:t>e?1:-1}class yz 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 yP(e){let{readerRef:t,selectedSessionId:n,sessions:s,onClose:l}=e,{t:o}=(0,t_.s)(),a=(0,i.useRef)(n);a.current=n;let d=(0,i.useRef)(l);d.current=l;let c=(0,i.useRef)(null),u=(0,i.useRef)(!1),p=(0,i.useRef)(null),h=(0,i.useRef)(null),f=(0,i.useRef)(null),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(yy),[b,y]=(0,i.useState)(yM),[w,k]=(0,i.useState)(!1),[j,S]=(0,i.useState)(null),C=(0,i.useRef)({page:m,server:x,samples:b});C.current={page:m,server:x,samples:b},(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,l,o,d,h,m;u.current=!1;let x=(r=(e={fetch:(e,t)=>fetch(e,t),sessionId:()=>yb(yv(t.current).client,a.current),isVisible:()=>"visible"===document.visibilityState,onReading:e=>{v(e);let t=function(e){if(e.failure){let t="timeout"===e.failure.kind;return{ms:5e3*!!t,tone:t?"warning":"error",failed:!0}}return null===e.roundTripMs?null:yT(e.roundTripMs)}(e);t&&y(e=>({...e,poll:yR(e.poll,t)}))}}).now??(()=>Date.now()),i=e.setTimeout??((e,t)=>setTimeout(e,t)),s=e.clearTimeout??(e=>clearTimeout(e)),l=!1,o=null,d=yy,h=async t=>{let a=new AbortController,c={sessionId:t,controller:a,startedAt:r()};o=c,n=t;let u=!1,p=i(()=>{u=!0,a.abort()},5e3),h=null,f=null;try{var m,g;let n=await e.fetch(t?`/api/agent/debug?session=${encodeURIComponent(t)}`:"/api/agent/debug",{cache:"no-store",signal:a.signal});if(n.ok){let e=null;try{e=await n.json()}catch(e){if(a.signal.aborted)throw e}(m=e,yf(m)&&ym(m.now)&&yf(g=m.server)&&ym(g.startedAt)&&yf(g.wrappers)&&yf(g.eventStreams)&&ym(g.sseTotal)&&Array.isArray(g.pages)&&yf(g.terminals)&&Array.isArray(m.sessions)&&m.sessions.every(yg)&&(null===m.session||function(e){if(!yf(e)||"string"!=typeof e.sessionId)return!1;let t=e.wrapper,n=e.subagents,r=e.mcp;return(null===t||yf(t)&&"string"==typeof t.state&&yf(t.run)&&yf(t.idle))&&(null===e.lifecycle||yf(e.lifecycle))&&(null===e.providers||Array.isArray(e.providers))&&Array.isArray(e.eventStreams)&&yf(n)&&Array.isArray(n.runs)&&Array.isArray(n.notifications)&&(null===r||yf(r)&&Array.isArray(r.servers))}(m.session)))?h=e:f={kind:"invalid",status:n.status}}else f={kind:"http",status:n.status}}catch{f={kind:u?"timeout":"network",status:null}}finally{s(p),o===c&&(o=null)}if(l||a.signal.aborted&&!u||e.sessionId()!==t)return;let x=r(),v=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:v?d.reply:null,receivedAt:v?d.receivedAt:null,roundTripMs:v?d.roundTripMs:null,failure:{...f??{kind:"invalid",status:null},at:x},requests:d.requests+1,failures:d.failures+1,consecutiveFailures:d.consecutiveFailures+1},e.onReading(d)},{poll:m=()=>{if(l||!e.isVisible())return;let t=e.sessionId();if(o){if(o.sessionId===t)return;o.controller.abort()}h(t)},sync(){l||(o?o.sessionId:n)!==e.sessionId()&&m()},inFlightSince:()=>o?.startedAt??null,dispose(){l=!0,o?.controller.abort(),o=null}});c.current=x;let b=()=>{let e=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Date.now(),{client:r,failed:i}=yv(e);return{at:n,client:r,clientFailed:i,sources:yx(tf,[]),visibility:yx(tx,null),protocol:yx(ty,null),runningPoll:yx(tb,null),pollInFlightSince:t}}(t.current,x.inFlightSince());g(e);let n=e.runningPoll?.last??null;if(n&&n.at!==f.current){f.current=n.at;let e=n&&"aborted"!==n.outcome?"error"===n.outcome?{ms:yl(n.durationMs),tone:"error",failed:!0}:yT(n.durationMs):null;e&&y(t=>({...t,running:yR(t.running,e)}))}};b(),x.poll();let w=window.setInterval(()=>{"visible"===document.visibilityState&&(b(),x.sync())},1e3),k=window.setInterval(()=>x.poll(),2e3),j=()=>{"visible"===document.visibilityState&&(b(),x.poll())};return document.addEventListener("visibilitychange",j),()=>{u.current=!0,x.dispose(),c.current=null,window.clearInterval(w),window.clearInterval(k),document.removeEventListener("visibilitychange",j),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=j??{page:m,server:x,samples:b};return(0,r.jsx)(yW,{page:N.page,server:N.server,samples:N.samples,selectedSessionId:n,sessions:s,copied:w,onCopy:()=>{i0(JSON.stringify({client:m,server:x.reply},null,2)).then(()=>{u.current||(p.current&&clearTimeout(p.current),k(!0),p.current=setTimeout(()=>k(!1),1400))},()=>{})},t:o,sectionRef:h})}function yW(e){var t;let n,{page:s,server:l,samples:o=yM,selectedSessionId:a,sessions:d,copied:c,onCopy:u,t:p,sectionRef:h}=e,f=s?.at??l.receivedAt??0,m=s?.client??null,g=yb(m,a),x=l.reply,v=x&&null!==l.receivedAt?(t=x.now,n=Math.max(0,f-l.receivedAt),{remaining:e=>e-t-n,age:e=>t-e+n}):null,b=x?.session&&x.session.sessionId===g?x.session:null,y=m?.pageId??null,w=(0,i.useMemo)(()=>new Map(d.map(e=>[e.id,e])),[d]),k=(0,i.useMemo)(()=>e=>{let t=w.get(e);return t?ry(t):null},[w]),j=(0,i.useMemo)(()=>x?function(e,t,n){let r=e=>{let n=e,r=new Set([e.id]);for(let i=0;i<32;i++){let i=n.relation;if(i?.kind!=="subagent")break;let s=t.get(i.parentSessionId);if(!s)break;if(r.has(s.id))return e;r.add(s.id),n=s}return n},i=new Map,s=[];for(let n of e){let e=t.get(n.sessionId);if(!e){s.push(n);continue}let l=r(e),o=i.get(l.id);o||(o={root:l,summary:null,subagents:[]},i.set(l.id,o)),l.id===e.id?o.summary=n:o.subagents.push({info:e,summary:n})}let l=null===n?void 0:t.get(n),o=l?r(l).id:null,a=(e,t)=>yL(yA(e.root),yA(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=U(e.root),n=c.get(t);n||(n={key:t,name:ek(e.root.projectRoot??e.root.cwd),families:[]},c.set(t,n)),n.families.push(e)}let u=e=>Math.max(...e.families.map(e=>yA(e.root))),p=e=>e.families.some(e=>e.root.id===o),h=[...c.values()].sort((e,t)=>Number(p(t))-Number(p(e))||yL(u(e),u(t))).map(e=>{let t=[];for(let r of[...e.families].sort(a).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)=>yL(yA(e.info),yA(t.info)))))t.push({id:e.id,depth:1,info:e,summary:i,current:e.id===n,placeholder:!1});return{key:e.key,name:e.name,rows:t}});if(s.length>0){let e=null!==n&&!l&&s.some(e=>e.sessionId===n),t=(e,t)=>e<t?-1:+(e>t),r={key:"\0unlisted",name:null,rows:[...s].sort((e,r)=>Number(r.sessionId===n)-Number(e.sessionId===n)||t(yh(e.sessionId),yh(r.sessionId))||t(e.sessionId,r.sessionId)).map(e=>({id:e.sessionId,depth:0,info:null,summary:e,current:e.sessionId===n,placeholder:!1}))};e?h.unshift(r):h.push(r)}return h}(x.sessions,w,g):null,[x,w,g]),S=s?function(e){let{page:t,server:n,detail:r,t:i,titleOf:s}=e,l=t.at,o=[],a=(e,t,n)=>{o.push({id:e,tone:t,text:yw(n)})},d=n.failure;d?a("poll","timeout"===d.kind?"warning":"error",[i(yn[d.kind],{status:d.status??"?"}),yd(l-d.at,i)]):null!==t.pollInFlightSince&&l-t.pollInFlightSince>=2e3&&a("poll","warning",[i("debug.poll.inFlight",{time:ya(l-t.pollInFlightSince,i)})]),t.clientFailed&&a("reader","error",[i("debug.stream.readerFailed")]);let c=t.runningPoll?.last??null;c?.outcome==="error"&&a("runningPoll","warning",[i("debug.page.runningPoll"),i("debug.page.poll.error"),null!==c.httpStatus&&`HTTP ${c.httpStatus}`,yd(l-c.at,i)]);let u=t.sources.filter(e=>"open"===e.state).length;"http/1.1"===t.protocol&&u>=5&&a("pool",u>=6?"error":"warning",[i("debug.issue.pool",{count:u})]);let p=t.client,h=p?.connection??null,f=h?.sessionId??null;for(let e of t.sources)"connecting"===e.state&&0!==e.errors&&("agent"!==e.kind||null===f||e.label!==f)&&a("source","warning",[i(b9[e.kind]),yN(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:yp(h.retryDueAt-l,i)}),t=h.lastError;t&&"connected"!==h.state&&!(h.lastClose&&h.lastClose.at>=t.at)?a("stream","error",[ys(t.reason,b5,i),t.message,yd(l-t.at,i),e]):"retrying"===h.state&&a("stream","warning",[i(b3.retrying),e]);let n=y$(h,l),r=n?yI(n.ageMs,n.staleAfterMs):"dim";n&&"dim"!==r&&a("streamSilent",r,[`${i("debug.stream.lastData")} ${yd(n.ageMs,i)}`])}let m=p?.pageId??null,g=null!==n.receivedAt?n.receivedAt-(n.roundTripMs??0):null;for(let e of(r&&m&&h&&null!==g&&"connected"===h.state&&h.sessionId===r.sessionId&&null!==h.connectedAt&&h.connectedAt<g&&!r.eventStreams.some(e=>e.holder===m)&&a("noServerStream","warning",[i("debug.issue.noServerStream")]),r?.eventStreams??[]))e.droppedEvents>0&&a("dropped","warning",[yk(e.holder,m,i),i("debug.server.dropped",{count:e.droppedEvents})]);let x=p?.lease??null;if(x){let e=x.last;null!==x.inFlightSince&&l-x.inFlightSince>=2e3?a("lease","warning",[i("debug.section.lease"),i("debug.lease.inFlight",{time:ya(l-x.inFlightSince,i)})]):e?.outcome==="error"?a("lease","error",[i("debug.section.lease"),i(ye.error),null!==e.httpStatus&&`HTTP ${e.httpStatus}`,yd(l-e.at,i)]):e?.outcome==="unanswered"&&a("lease","warning",[i("debug.section.lease"),i(ye.unanswered),yd(l-e.at,i)])}let v=r?.wrapper??null;for(let e of(v&&!v.stale&&"failed"===v.extensions&&a("extensions","error",[i("debug.server.extensions"),i("debug.server.extensions.failed")]),r?.providers??[]))"error"===e.active&&a("provider","error",[e.name,i("debug.server.providerError")]);for(let e of r?.mcp?.servers??[])(e.hasError||"failed"===e.state||"conflict"===e.state)&&a("mcp","error",[`MCP ${e.name}`,ys(e.state,fJ,i)]);return o.sort((e,t)=>Number("error"===t.tone)-Number("error"===e.tone))}({page:s,server:l,detail:b,t:p,titleOf:k}):[],C=null===s?{kind:"reading",tone:"dim",count:0}:s.visibility?.state==="hidden"?{kind:"hidden",tone:"dim",count:0}:S.length>0?{kind:"issues",tone:S.some(e=>"error"===e.tone)?"error":"warning",count:S.length}:null===l.receivedAt?{kind:"waiting",tone:"dim",count:0}:{kind:"ok",tone:"ok",count:0},N={t:p,now:f,clock:v,myHolder:y,titleOf:k};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)(yJ,{verdict:C,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:[S.length>0&&(0,r.jsx)(yY,{issues:S}),(0,r.jsxs)("div",{className:"debug-cols",children:[(0,r.jsx)(yQ,{page:s,samples:o,reply:x,ctx:N}),(0,r.jsxs)("div",{className:"debug-col debug-col-server",children:[(0,r.jsx)(y6,{reply:x,ctx:N}),(0,r.jsx)(y9,{reply:x,ctx:N})]}),(0,r.jsx)("div",{className:"debug-col debug-col-sessions",children:(0,r.jsx)(y7,{reply:x,detail:b,groups:j,targetSessionId:g,sources:s.sources,ctx:N})})]})]}),(0,r.jsx)("style",{children:wp})]})}function yO(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 yF(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 yD(e){let{text:t,items:n,cap:i,label:s,plain:l=!1}=e;return 0===n.length?null:(0,r.jsxs)("span",{className:"debug-run",title:s,...l?{}:{role:"img","aria-label":s},children:[n.slice(0,i).map((e,n)=>(0,r.jsx)("span",{className:yF(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 yB={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)(yH,{}),iOS:(0,r.jsx)(yH,{}),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 yH(){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 y_(e){let{client:t}=e,n=t?t.split(" \xb7 ").filter(e=>e in yB):[];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:yB[e]},e))})}function yU(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 yK(e){let{tone:t,children:n,title:i}=e;return(0,r.jsx)("span",{className:`debug-chip is-${t}`,title:i,children:n})}function yq(e){let{fraction:t,tone:n,width:i,height:s=4,notches:l,title:o,className:a}=e;return(0,r.jsxs)("span",{className:`debug-bar is-${n}${a?` ${a}`:""}`,style:{width:i,height:s},title:o,"aria-hidden":"true",children:[(0,r.jsx)("span",{className:"debug-bar-fill",style:{width:`${100*t}%`}}),l?.map(e=>(0,r.jsx)("span",{className:"debug-bar-notch",style:{left:`${100*e}%`}},e))]})}function yV(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(yl(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 yZ(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)(rb,{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 yJ(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)(yO,{kind:"error"===t.tone?"error":"warning"}),"ok"===t.kind&&(0,r.jsx)(yU,{tone:"ok"}),("hidden"===t.kind||"waiting"===t.kind)&&(0,r.jsx)(yU,{tone:"dim",ring:!0}),(0,r.jsx)("span",{className:"debug-panel-status-text",children:i})]})}function yY(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)(yO,{kind:e.tone}),(0,r.jsx)("span",{className:"debug-issue-text",children:e.text})]},`${e.id}:${t}`))})}function yG(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:ya(n.median,t),max:ya(n.max,t)})}function yX(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?"—":ya(i.ms,n)}):(0,r.jsx)("span",{className:"debug-value is-dim",children:"—"})}function yQ(e){let{page:t,samples:n,reply:i,ctx:s}=e,{t:l}=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,l=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":l>=i?"error":l>=i-1?"warning":"dim"}}(t.sources,t.protocol,t.client?.connection?.sessionId??null),a=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:l("debug.section.page")})}),(0,r.jsx)(y0,{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:l("debug.page.debugPoll")})}),(0,r.jsx)(yV,{samples:n.poll,label:yG(n.poll,l)}),(0,r.jsx)(yX,{samples:n.poll,t:l}),(0,r.jsx)("span",{className:"debug-measure-name",children:(0,r.jsx)("span",{className:"debug-label",children:l("debug.page.runningPoll")})}),(0,r.jsx)(yV,{samples:n.running,label:yw([a&&l("debug.page.pollCounts",{count:a.count,failures:a.failures}),yG(n.running,l)])}),(0,r.jsx)(yX,{samples:n.running,t:l}),(0,r.jsx)(y8,{page:t,reply:i,ctx:s}),(0,r.jsx)(y5,{page:t,ctx:s})]})]})}function y0(e){let{pool:t,ctx:n}=e,{t:i,now:s,titleOf:l}=n,o=Object.keys(b9).filter(e=>t.kinds[e]>0).map(e=>`${i(b9[e])} ${t.kinds[e]}`),a=null!==t.cap?yw([`${i("debug.page.http1",{protocol:t.protocol??""})} \xb7 ${t.mine}/${t.cap}`,...o]):yw([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":a,title:a,children:[d.map((e,t)=>e?(0,r.jsx)("span",{className:yF({tone:e.connecting?"warning":e.chat?"accent":"muted",filled:e.chat,dashed:e.connecting},"debug-slot"),title:yw([i(b9[e.kind]),yN(e,l),i(b7[e.connecting?"connecting":"open"]),i("debug.page.sourceCounts",{opens:e.opens,errors:e.errors}),yd(s-e.createdAt,i)]),children:"agent"===e.kind?"SSE":i(y1[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)(yK,{tone:"dim",children:t.protocol})]})}let y1={"file-watch":"debug.box.file",terminal:"debug.box.terminal"},y2={connected:{tone:"ok",ring:!1},connecting:{tone:"warning",ring:!0},retrying:{tone:"warning",ring:!1},idle:{tone:"dim",ring:!0}};function y4(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")} ${yd(i-t.openedAt,r)}`,null!==t.connectedAt&&`${r("debug.stream.connected")} ${yd(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")} ${yw([ys(t.lastError.reason,b5,r),t.lastError.message,yd(i-t.lastError.at,r)])}`,null!==t.lastClose&&`${r("debug.stream.lastClose")} ${yw([t.lastClose.reason?ys(t.lastClose.reason,yi,r):"—",yd(i-t.lastClose.at,r)])}`,`${r("debug.stream.wanted")} ${r(e.wantsStream?"debug.yes":"debug.no")}`],l=n.visibility;return l&&l.hiddenCount>0&&s.push(yw([r("debug.page.hiddenCount",{count:l.hiddenCount}),null!==l.lastHiddenAt&&r("debug.page.lastHidden",{time:yd(i-l.lastHiddenAt,r)})])),e.released.count>0&&s.push(`${r("debug.stream.released")} ${yw([r("debug.times",{count:e.released.count}),null!==e.released.lastAt&&yd(i-e.released.lastAt,r)])}`),e.reattached.count>0&&s.push(`${r("debug.stream.reattached")} ${yw([r("debug.times",{count:e.reattached.count}),null!==e.reattached.lastAt&&yd(i-e.reattached.lastAt,r),e.reattached.lastReason&&r(b6[e.reattached.lastReason])])}`),s.filter(Boolean).join("\n")}function y8(e){let{page:t,reply:n,ctx:i}=e,{t:s,now:l}=i,o=t.client,a=o?.connection??null,d=(0,r.jsx)("span",{className:"debug-measure-name",title:o&&a?y4(o,a,t,s):void 0,children:(0,r.jsx)("span",{className:"debug-label",children:s("debug.section.stream")})});if(!o||!a)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=y$(a,l),u=y2[a.state];return(0,r.jsxs)(r.Fragment,{children:[d,c?(0,r.jsx)(y3,{connection:a,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:y4(o,a,t,s),children:[(0,r.jsx)(yU,{tone:u?.tone??"dim",ring:u?.ring??!0}),yw([s(b3[a.state]??"debug.unknown"),`${s("debug.stream.events")} ${a.events}`,a.retries>0&&`${s("debug.stream.opens")} ${s("debug.stream.opensRetries",{opens:a.opens,retries:a.retries})}`])]}),(o.released.active||null!==o.graceDueAt)&&(0,r.jsxs)("span",{className:"debug-measure-sub debug-chips",children:[o.released.active&&(0,r.jsx)(yK,{tone:"accent",children:s("debug.stream.close.released")}),null!==o.graceDueAt&&(0,r.jsx)(yK,{tone:"accent",children:`${s("debug.stream.grace")} ${yu(o.graceDueAt-l,s)}`})]})]})}function y3(e){let{connection:t,freshness:n,heartbeatMs:i,ctx:s}=e,{t:l,now:o}=s,{ageMs:a,staleAfterMs:d}=n,c=yI(a,d),u=[];if(i>0)for(let e=i;e<d&&u.length<12;e+=i)u.push(e/d);let p=yw([`${l("debug.stream.lastData")} ${yd(a,l)}`,null!==t.lastHeartbeatAt&&l("debug.stream.heartbeat",{time:yd(o-t.lastHeartbeatAt,l)}),l("debug.stream.watchdogArmed",{time:ya(d,l)})]);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(yq,{fraction:yE(a,d)??0,tone:c,width:120,notches:u,title:p}),(0,r.jsx)("span",{className:`debug-value is-${c}`,title:p,children:l("debug.stream.dataAgo",{time:yc(a,l)})})]})}function y5(e){let{page:t,ctx:n}=e,{t:i,now:s}=n,l=t.client?.lease??null,o=t.client?.pageId??null,a=(0,r.jsx)("span",{className:"debug-measure-name",children:(0,r.jsx)("span",{className:"debug-label",children:i("debug.section.lease")})});if(!l||0===l.requests)return(0,r.jsxs)(r.Fragment,{children:[a,(0,r.jsx)("span",{className:"debug-measure-empty",children:l?i("debug.lease.noHolder"):t.clientFailed?"—":i("debug.stream.noChat")})]});let d=l.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}(l.renewStartedAt,l.renewIntervalMs,s),u=null!==l.inFlightSince&&s-l.inFlightSince>=2e3,p=u||d?.outcome==="unanswered"?"warning":d?.outcome==="error"?"error":"dim",h=i("debug.lease.countsValue",{requests:l.requests,unanswered:l.unanswered,errors:l.errors}),f=yw([null!==c&&`${i("debug.lease.next")} ${yu(c-s,i)}`,i("debug.lease.every",{time:ya(l.renewIntervalMs,i)}),h,null!==o&&`${i("debug.holder.thisPage")} ${yh(o)}`]);return(0,r.jsxs)(r.Fragment,{children:[a,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)(yq,{fraction:u?1:1-(yE(c-s,l.renewIntervalMs)??1),tone:p,width:120,title:f}),(0,r.jsx)("span",{className:"debug-value is-muted",title:f,children:c-s>0?i("debug.lease.renewsIn",{time:yc(c-s,i,"ceil")}):i("debug.lease.renewing")})]}),(0,r.jsx)("span",{className:"debug-measure-sub",children:`${i("debug.lease.last")} ${d?yw([i(ye[d.outcome]??"debug.unknown"),ya(d.durationMs,i),"error"===d.outcome&&null!==d.httpStatus&&`HTTP ${d.httpStatus}`,i("debug.time.ago",{time:yc(s-d.at,i)})]):i("debug.notYet")}`}),(l.unanswered>0||l.errors>0)&&(0,r.jsx)("span",{className:"debug-measure-sub",children:h})]})}function y6(e){let{reply:t,ctx:n}=e,{t:i,clock:s}=n,l=(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:[l,(0,r.jsx)("span",{children:i("debug.poll.waiting")})]});let o=t.server,a=i("debug.global.wrappersValue",{...o.wrappers}),d=`${i("debug.global.timers")}: ${i("debug.global.timersValue",{idle:o.idleTimeoutMs>0?ya(o.idleTimeoutMs,i):i("debug.server.idleDisabled"),heartbeat:ya(o.heartbeatMs,i)})}
277
+ ${a}`,c=o.terminals,u=yw([`${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:yp(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}`,f=o.wrappers.starting;return(0,r.jsxs)("div",{className:"debug-col-head debug-server-head",children:[l,(0,r.jsxs)("span",{className:"debug-server-item",title:d,children:[(0,r.jsx)(yO,{kind:"server"}),(0,r.jsx)("span",{children:`${i("debug.global.uptime")} ${ya(s.age(o.startedAt),i)}`})]}),f>0&&(0,r.jsxs)("span",{className:"debug-run",role:"img","aria-label":a,title:a,children:[Array.from({length:Math.min(f,4)},(e,t)=>(0,r.jsx)("span",{className:"debug-status",children:(0,r.jsx)("span",{className:"debug-status-ring is-starting"})},t)),f>4&&(0,r.jsx)("span",{className:"debug-run-more",children:`+${f-4}`})]}),(0,r.jsx)(yD,{text:i("debug.box.file"),items:Array.from({length:o.fileWatches},()=>({tone:"muted",title:h})),cap:4,label:h}),(0,r.jsx)(yD,{text:i("debug.box.terminal"),items:p,cap:4,label:u})]})}function y9(e){let{reply:t,ctx:n}=e,{t:i,myHolder:s}=n;if(!t)return null;let{pages:l,sseTotal:o}=t.server;if(0===o&&0===l.length)return null;let a=yj(l,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")} ${a.length}`}),(0,r.jsx)("span",{className:"debug-page-count",children:`SSE ${i("debug.global.streamTotal",{count:o})}`})]}),a.map((e,t)=>{let n=null!==e.holder&&e.holder===s,l=yk(e.holder,s,i),o=e.agent+e.terminal+e.fileWatch,a=yw([e.agent>0&&`${i(b9.agent)} ${e.agent}`,e.terminal>0&&`${i(b9.terminal)} ${e.terminal}`,e.fileWatch>0&&`${i(b9["file-watch"])} ${e.fileWatch}`]);return(0,r.jsxs)("div",{className:`debug-page-row${n?" is-current":""}`,title:yw([l,e.client,e.address,`SSE ${o}`,a]),children:[(0,r.jsx)("span",{className:"debug-page-icons",children:(0,r.jsx)(y_,{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?yh(e.holder):i("debug.holder.none")}),(0,r.jsx)("span",{className:"debug-page-count",children:o})]},`${e.holder??""}:${t}`)})]})}function y7(e){let{reply:t,detail:n,groups:s,targetSessionId:l,sources:o,ctx:a}=e,{t:d,clock:c}=a;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 l?n?u||(p=(0,r.jsx)(wt,{detail:n,clock:c,ctx:a})):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)(rc,{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)(wc,{row:e,sources:o,idleTimeoutMs:t.server.idleTimeoutMs,clock:c,ctx:a,current:s?function(e,t,n){let{t:i}=n,s=e=>yd(t.age(e),i),l=e.wrapper?.idle??null,o=e.lifecycle;return{badges:(0,r.jsx)(wi,{detail:e,clock:t,ctx:n}),idleTitle:l&&null!==l.nextCheckAt?yw([`${i("debug.server.idle")} ${ya(t.remaining(l.nextCheckAt),i)}`,l.timeoutMs>0&&i("debug.server.idleTimeout",{time:ya(l.timeoutMs,i)}),null!==l.lastResetAt&&i("debug.server.idleReset",{time:s(l.lastResetAt)}),i(l.forcedByStop?"debug.server.idleForced":"debug.server.idleHint")]):void 0,startsTitle:o&&o.starts>1?we(o,s,i):void 0}}(s,c,a):void 0}),s&&(0,r.jsx)(wn,{detail:s,clock:c,ctx:a})]},e.id)})]},e.key))]})}function we(e,t,n){return yw([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 wt(e){var t;let n,{detail:i,clock:s,ctx:l}=e,{t:o,titleOf:a}=l,d=a(i.sessionId)??yh(i.sessionId),c=(n=(t=i).wrapper)?yC({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)(yZ,{state:c,label:o(yS[c])})}),(0,r.jsx)("span",{className:"debug-row-title",children:(0,r.jsx)("span",{className:"debug-row-name",children:d})})]}),(0,r.jsx)(wn,{detail:i,clock:s,ctx:l,unlisted:!0})]})}function wn(e){let{detail:t,clock:n,ctx:i,unlisted:s=!1}=e,{t:l,titleOf:o}=i,a=t.wrapper,d=t.lifecycle,c=e=>yd(n.age(e),l),u=null!==a&&!a.stale,p=a?.state==="closing"?null!==a.closingAt?l("debug.server.closingSince",{time:c(a.closingAt)}):l("debug.state.closing"):null,h=a&&yw([null!=a.startedAt&&`${l("debug.server.started")} ${c(a.startedAt)}`,u&&a.lastEvent&&`${l("debug.server.lastEvent")} ${a.lastEvent.type} ${c(a.lastEvent.at)}`,u&&a.lastCommand&&`${l("debug.server.lastCommand")} ${a.lastCommand.type} ${c(a.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:yh(t.sessionId)}),!a&&(0,r.jsx)("span",{className:"debug-note",children:l(t.starting?"debug.server.starting":"debug.server.noWrapper")}),s&&d&&d.starts>1&&(0,r.jsx)("span",{className:"debug-starts",title:we(d,c,l),children:`↻${d.starts}`}),p&&(0,r.jsx)(yK,{tone:"warning",children:p}),a?.chatOnly&&(0,r.jsx)(yK,{tone:"dim",children:l("debug.server.chatOnly")}),a?.subagent&&(0,r.jsx)(yK,{tone:"dim",children:l("debug.server.subagent")}),a?.stale&&(0,r.jsx)(yK,{tone:"warning",children:l("debug.server.stale")}),(0,r.jsx)(wr,{detail:t,t:l}),u&&(0,r.jsx)(ws,{detail:t,t:l}),h&&(0,r.jsx)("span",{className:"debug-line",children:h})]}),u&&(0,r.jsx)(wa,{detail:t,clock:n,ctx:i}),u&&(0,r.jsx)(wd,{detail:t,clock:n,ctx:i})]})}function wr(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)(yK,{tone:"warning",children:`${n("debug.server.listeners")} ${i.eventListeners}`}):null}function wi(e){var t;let n,{detail:i,clock:s,ctx:l}=e,{t:o,myHolder:a}=l,d=e=>yd(s.age(e),o),c=yj([...i.eventStreams].sort((e,t)=>e.openedAt-t.openedAt),a),u=c.map(e=>{var t;let n,r=null===e.connectedAt;return{tone:r||e.droppedEvents>0?"warning":(t=e.holder,null===t?"dim":t===a?"accent":"muted"),filled:null!==e.holder&&e.holder===a,dashed:r,title:yw([yk(e.holder,a,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=yl(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:yw([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)(yD,{text:"SSE",items:u,cap:3,label:(t=c.map(e=>e.holder),n=t.filter(e=>null!==e&&e===a).length,`SSE: ${t.length} (${o("debug.holder.thisPage")} ${n}, ${o("debug.holder.otherPage")} ${t.length-n})`)}),(0,r.jsx)(yD,{text:o("debug.box.provider"),items:h,cap:1,label:`${o("debug.server.providers")}: ${null===p?o("debug.server.providersUnknown"):p.length}`})]})}function ws(e){let{detail:t,t:n}=e,i=t.wrapper;if(!i)return null;let s=i.run,l=[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:[l.map(e=>(0,r.jsx)(yK,{tone:"dim",children:e},e)),o.map(e=>(0,r.jsx)(yK,{tone:"warning",children:e},e))]})}let wl={completed:"ok",failed:"error",aborted:"warning",interrupted:"warning"};function wo(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)(rb,{size:12})});let n=wl[t];return n?(0,r.jsx)("span",{className:`debug-run-icon is-${n}`,children:(0,r.jsx)(bX,{status:t})}):(0,r.jsx)("span",{className:"debug-run-icon",children:(0,r.jsx)("span",{className:"debug-status-ring is-alive"})})}function wa(e){let{detail:t,clock:n,ctx:i}=e,{t:s,titleOf:l}=i,o=t.subagents;if(!o.active&&0===o.runs.length&&0===o.notifications.length)return null;let a=e=>yd(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)(yK,{tone:"accent",children:s("debug.server.subagentsActive")})]}),o.runs.map((e,t)=>(0,r.jsxs)("div",{className:"debug-run-line",children:[(0,r.jsx)(wo,{status:e.status}),(0,r.jsx)("span",{className:"debug-run-name",children:l(e.sessionId)??e.profile??yh(e.sessionId)}),(0,r.jsx)("span",{className:"debug-line",children:yw([ys(e.status,yr,s),e.background&&s("debug.server.background"),e.resumed&&s("debug.server.resumed"),null!==e.dispatchedAt&&a(e.dispatchedAt)])}),e.abortRequested&&(0,r.jsx)(yK,{tone:"warning",children:s("debug.server.abortRequested")}),e.mcpWaiting&&(0,r.jsx)(yK,{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:yw([s("debug.server.notifying",{parent:yh(e.parentSessionId)}),null!==e.since&&a(e.since)])},`${e.sessionId}:${t}`))]})}function wd(e){let{detail:t,clock:n,ctx:i}=e,{t:s}=i,l=t.mcp;if(!l||0===l.servers.length&&0===l.problems)return null;let o=null!==l.idleReleaseAt&&l.idleMs>0?n.remaining(l.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${l.active?"":" is-dim"}`,children:"MCP"}),l.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},l=ys(e.state,fJ,s),o=yw([`${e.name} (${e.scope})`,l,e.released&&s("debug.server.mcpReleased"),e.hasError&&s("debug.server.mcpError")]),a="connected"!==e.state?l: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)(yU,{tone:n,ring:!i}),(0,r.jsx)("span",{className:e.released?"is-dim":void 0,children:e.name}),a&&(0,r.jsx)("span",{className:"debug-pill-state",children:`\xb7 ${a}`})]},`${e.scope}:${e.name}:${t}`)}),l.problems>0&&(0,r.jsx)(yK,{tone:"warning",children:s("debug.server.mcpProblems",{count:l.problems})}),l.disposed&&(0,r.jsx)(yK,{tone:"dim",children:s("debug.server.mcpDisposed")})]}),null!==o&&(0,r.jsxs)("div",{className:"debug-idle-row",children:[(0,r.jsx)(yq,{fraction:yE(o,l.idleMs)??0,tone:"dim",width:80}),(0,r.jsx)("span",{className:"debug-value is-muted",children:s("debug.server.mcpRelease",{time:yp(o,s)})})]})]})}function wc(e){var t;let n,i,{row:s,sources:l,idleTimeoutMs:o,clock:a,ctx:d,current:c}=e,{t:u}=d,p=s.summary,h=s.info?ry(s.info):yh(s.id),f=p&&null!==p.nextIdleCheckAt?a.remaining(p.nextIdleCheckAt):null,m=p?yC(p):null,g=["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:g,title:yw([s.current&&u("debug.sessions.current"),p?(n=[p.subagent?u("debug.overlay.subagentId",{id:yh(p.sessionId)}):yh(p.sessionId),u(yt[p.state]??yt.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!==f&&n.push(u(p.forcedByStop?"debug.overlay.closesIn":"debug.overlay.idle",{time:(i=yl(f))<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:m&&(0,r.jsx)(yZ,{state:m,label:u(yS[m])})}),(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)(wu,{summary:p,mine:(t=s.id,l.filter(e=>"agent"===e.kind&&e.label===t).length),remaining:f,idleTimeoutMs:o,t:u,badges:c?.badges,idleTitle:c?.idleTitle})]})}function wu(e){let{summary:t,mine:n,remaining:i,idleTimeoutMs:s,t:l,badges:o,idleTitle:a}=e,d=l("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=l("debug.overlay.providers",{count:t.providers}),h=Array.from({length:t.providers},()=>({tone:"muted",title:p})),f=null!==i&&(s>0||t.forcedByStop),m=t.forcedByStop?"warning":"dim",g=null!==i?l("debug.overlay.closesIn",{time:yc(i,l)}):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)(yD,{text:"SSE",items:u,cap:3,label:d}),(0,r.jsx)(yD,{text:l("debug.box.provider"),items:h,cap:1,label:p})]})}),(0,r.jsx)("span",{className:`debug-row-idle is-${m}`,title:a,children:f&&null!==i&&(0,r.jsxs)(r.Fragment,{children:[s>0&&(0,r.jsx)(yq,{fraction:yE(i,s)??0,tone:m,width:36,height:3,className:"debug-row-idle-bar"}),t.forcedByStop&&(0,r.jsx)("span",{className:"debug-row-forced",role:"img","aria-label":g,title:g}),(0,r.jsx)("span",{className:"debug-row-idle-text",children:yc(i,l)})]})})]})}let wp=`
278
+ .debug-panel {
279
+ --dbg-ok: #16a34a;
280
+ --dbg-warn: #d97706;
281
+ --dbg-err: #ef4444;
282
+ container-type: inline-size;
283
+ container-name: debug-panel;
284
+ display: flex;
285
+ max-height: min(720px, 80dvh);
286
+ flex-direction: column;
287
+ background: var(--bg-panel);
288
+ border-bottom: 1px solid var(--border);
289
+ box-shadow: 0 10px 28px rgba(0,0,0,0.10);
290
+ color: var(--text);
291
+ }
292
+ .debug-panel .is-ok { color: var(--dbg-ok); }
293
+ .debug-panel .is-warning { color: var(--dbg-warn); }
294
+ .debug-panel .is-error { color: var(--dbg-err); }
295
+ .debug-panel .is-accent { color: var(--accent); }
296
+ .debug-panel .is-muted { color: var(--text-muted); }
297
+ .debug-panel .is-dim { color: var(--text-dim); }
298
+ .debug-panel-header {
299
+ display: flex;
300
+ flex-shrink: 0;
301
+ align-items: center;
302
+ gap: 12px;
303
+ min-width: 0;
304
+ padding: 8px 16px;
305
+ border-bottom: 1px solid var(--border);
306
+ font-size: 12px;
307
+ }
308
+ .debug-panel-heading {
309
+ flex-shrink: 0;
310
+ color: var(--text);
311
+ cursor: help;
312
+ font-weight: 700;
313
+ }
314
+ .debug-panel-status {
315
+ display: inline-flex;
316
+ min-width: 0;
317
+ align-items: center;
318
+ gap: 6px;
319
+ font-variant-numeric: tabular-nums;
320
+ }
321
+ .debug-panel-status svg {
322
+ flex-shrink: 0;
323
+ }
324
+ .debug-panel-status-text {
325
+ min-width: 0;
326
+ overflow: hidden;
327
+ text-overflow: ellipsis;
328
+ white-space: nowrap;
329
+ }
330
+ .debug-panel-copy {
331
+ flex-shrink: 0;
332
+ margin-left: auto;
333
+ padding: 2px 8px;
334
+ border: 1px solid var(--border);
335
+ border-radius: 4px;
336
+ background: transparent;
337
+ color: var(--text-muted);
338
+ cursor: pointer;
339
+ font-size: 11px;
340
+ }
341
+ .debug-panel-copy:hover {
342
+ background: var(--bg-hover);
343
+ color: var(--text);
344
+ }
345
+ .debug-panel-scroll {
346
+ display: flex;
347
+ min-height: 0;
348
+ flex: 1;
349
+ flex-direction: column;
350
+ gap: 12px;
351
+ overflow: auto;
352
+ padding: 10px 16px 12px;
353
+ font-size: 12px;
354
+ line-height: 1.5;
355
+ }
356
+ .debug-section-title {
357
+ color: var(--text);
358
+ font-size: 11px;
359
+ font-weight: 700;
360
+ }
361
+ .debug-empty,
362
+ .debug-note {
363
+ color: var(--text-dim);
364
+ font-size: 12px;
365
+ }
366
+ .debug-label {
367
+ color: var(--text-dim);
368
+ font-size: 11px;
369
+ white-space: nowrap;
370
+ }
371
+ .debug-value {
372
+ font-family: var(--font-mono);
373
+ font-size: 11px;
374
+ font-variant-numeric: tabular-nums;
375
+ white-space: nowrap;
376
+ }
377
+ .debug-line {
378
+ color: var(--text-dim);
379
+ font-family: var(--font-mono);
380
+ font-size: 11px;
381
+ font-variant-numeric: tabular-nums;
382
+ overflow-wrap: anywhere;
383
+ }
384
+ .debug-panel .debug-line.is-warning {
385
+ color: var(--dbg-warn);
386
+ }
387
+
388
+ .debug-issues {
389
+ display: flex;
390
+ flex-direction: column;
391
+ gap: 4px;
392
+ margin: 0;
393
+ padding: 0;
394
+ list-style: none;
395
+ }
396
+ .debug-issue {
397
+ display: flex;
398
+ align-items: flex-start;
399
+ gap: 6px;
400
+ padding: 4px 8px;
401
+ border-left: 2px solid currentColor;
402
+ border-radius: 4px;
403
+ background: color-mix(in srgb, currentColor 8%, var(--bg-panel));
404
+ }
405
+ .debug-issue > svg {
406
+ flex-shrink: 0;
407
+ margin-top: 3px;
408
+ }
409
+ .debug-issue-text {
410
+ min-width: 0;
411
+ color: var(--text);
412
+ font-size: 12px;
413
+ overflow-wrap: anywhere;
414
+ }
415
+
416
+ /* Three columns when the panel is wide: the page's as wide as its table, the server's and the
417
+ sessions' each capped, so names never stretch and push the badges to the far edge. */
418
+ .debug-cols {
419
+ display: grid;
420
+ grid-template-areas: "page server sessions";
421
+ grid-template-columns: minmax(320px, max-content) minmax(340px, 480px) minmax(360px, 560px);
422
+ gap: 0;
423
+ }
424
+ .debug-col {
425
+ display: flex;
426
+ min-width: 0;
427
+ flex-direction: column;
428
+ gap: 8px;
429
+ }
430
+ .debug-col-page {
431
+ grid-area: page;
432
+ }
433
+ .debug-col-server {
434
+ grid-area: server;
435
+ }
436
+ .debug-col-sessions {
437
+ grid-area: sessions;
438
+ }
439
+ .debug-col-server,
440
+ .debug-col-sessions {
441
+ margin-left: 20px;
442
+ padding-left: 20px;
443
+ border-left: 1px solid var(--border);
444
+ }
445
+ .debug-list,
446
+ .debug-block {
447
+ display: flex;
448
+ min-width: 0;
449
+ flex-direction: column;
450
+ gap: 6px;
451
+ }
452
+ .debug-block {
453
+ gap: 4px;
454
+ }
455
+ .debug-col-head {
456
+ display: flex;
457
+ min-height: 18px;
458
+ align-items: center;
459
+ gap: 8px;
460
+ }
461
+ /* Name, scale, value; a measure's details span the row below it. */
462
+ /* As wide as the column (the details get the room), never so wide a value drifts off its bar. */
463
+ .debug-measures {
464
+ display: grid;
465
+ max-width: 400px;
466
+ grid-template-columns: max-content minmax(max-content, 1fr) max-content;
467
+ align-items: center;
468
+ gap: 4px 10px;
469
+ }
470
+ /* Numbers line up on the right, as the count in the column's head does. */
471
+ .debug-measures > .debug-value {
472
+ justify-self: end;
473
+ text-align: right;
474
+ }
475
+ .debug-measure-name {
476
+ display: inline-flex;
477
+ align-items: center;
478
+ gap: 6px;
479
+ }
480
+ .debug-measure-name[title] {
481
+ cursor: help;
482
+ }
483
+ /* Wrapped to the table's width rather than widening it (a percentage min-width adds nothing to
484
+ the columns' sizes). */
485
+ .debug-measure-sub,
486
+ .debug-measure-empty {
487
+ grid-column: 2 / -1;
488
+ width: 0;
489
+ min-width: 100%;
490
+ color: var(--text-dim);
491
+ font-family: var(--font-mono);
492
+ font-size: 11px;
493
+ font-variant-numeric: tabular-nums;
494
+ overflow-wrap: anywhere;
495
+ }
496
+ .debug-measure-sub {
497
+ margin-top: -4px;
498
+ }
499
+ .debug-measure-sub > .debug-dot {
500
+ margin-right: 6px;
501
+ vertical-align: 0;
502
+ }
503
+ .debug-measure-empty {
504
+ font-family: inherit;
505
+ font-size: 12px;
506
+ }
507
+ .debug-chips {
508
+ display: flex;
509
+ flex-wrap: wrap;
510
+ gap: 4px;
511
+ }
512
+ .debug-chip {
513
+ display: inline-flex;
514
+ align-items: center;
515
+ padding: 0 6px;
516
+ border: 1px solid color-mix(in srgb, currentColor 35%, transparent);
517
+ border-radius: 9px;
518
+ font-family: var(--font-mono);
519
+ font-size: 11px;
520
+ line-height: 16px;
521
+ white-space: nowrap;
522
+ }
523
+
524
+ /* A boxed word: "SSE", a provider's name, File, Term. Filled is this page's own. */
525
+ .debug-badge {
526
+ display: inline-flex;
527
+ height: 16px;
528
+ box-sizing: border-box;
529
+ flex-shrink: 0;
530
+ align-items: center;
531
+ padding: 0 4px;
532
+ border: 1px solid currentColor;
533
+ border-radius: 3px;
534
+ background-clip: padding-box;
535
+ font: 600 10px/14px var(--font-mono);
536
+ white-space: nowrap;
537
+ }
538
+ .debug-panel .debug-badge.is-filled {
539
+ border-color: var(--accent);
540
+ background-color: var(--accent);
541
+ color: var(--accent-contrast);
542
+ }
543
+ /* This page's, amber: a stream of its own still starting or dropping events. */
544
+ .debug-panel .debug-badge.is-filled.is-warning {
545
+ border-color: var(--dbg-warn);
546
+ background-color: var(--dbg-warn);
547
+ color: var(--bg-panel);
548
+ }
549
+ .debug-badge.is-dashed {
550
+ border-style: dashed;
551
+ }
552
+ .debug-badge.is-faded {
553
+ opacity: 0.45;
554
+ }
555
+ /* A provider's name: twelve characters, then an ellipsis (a block, so the ellipsis applies). */
556
+ .debug-badge.is-name {
557
+ display: inline-block;
558
+ max-width: calc(12ch + 10px);
559
+ overflow: hidden;
560
+ text-overflow: ellipsis;
561
+ }
562
+ /* A page's browser and system marks. */
563
+ .debug-client {
564
+ display: inline-flex;
565
+ align-items: center;
566
+ gap: 3px;
567
+ }
568
+ .debug-client svg {
569
+ display: block;
570
+ flex-shrink: 0;
571
+ }
572
+
573
+ /* The connected pages: marks, browser and system, address, page, its stream count. */
574
+ .debug-pages {
575
+ display: flex;
576
+ flex-direction: column;
577
+ }
578
+ .debug-page-row {
579
+ position: relative;
580
+ display: grid;
581
+ min-height: 22px;
582
+ grid-template-columns: 30px minmax(0, 1.2fr) minmax(0, 1fr) minmax(0, 1fr) 32px;
583
+ align-items: center;
584
+ column-gap: 8px;
585
+ padding: 0 4px;
586
+ border-radius: 4px;
587
+ font-size: 11px;
588
+ }
589
+ .debug-page-row.debug-list-head {
590
+ min-height: 18px;
591
+ grid-template-columns: minmax(0, 1fr) auto;
592
+ color: var(--text-dim);
593
+ font-size: 10px;
594
+ }
595
+ .debug-page-row.is-current {
596
+ background: var(--bg-selected);
597
+ }
598
+ .debug-page-row.is-current::before {
599
+ content: "";
600
+ position: absolute;
601
+ top: 4px;
602
+ left: 0;
603
+ width: 3px;
604
+ height: 14px;
605
+ border-radius: 0 2px 2px 0;
606
+ background: var(--accent);
607
+ }
608
+ .debug-page-icons {
609
+ display: inline-flex;
610
+ padding-left: 4px;
611
+ color: var(--text-muted);
612
+ }
613
+ .debug-page-icons svg {
614
+ width: 12px;
615
+ height: 12px;
616
+ }
617
+ .debug-page-client,
618
+ .debug-page-address,
619
+ .debug-page-holder {
620
+ min-width: 0;
621
+ overflow: hidden;
622
+ text-overflow: ellipsis;
623
+ white-space: nowrap;
624
+ }
625
+ .debug-page-client {
626
+ color: var(--text);
627
+ }
628
+ .debug-page-address {
629
+ color: var(--text-muted);
630
+ font-family: var(--font-mono);
631
+ }
632
+ .debug-page-holder {
633
+ color: var(--text-dim);
634
+ }
635
+ .debug-page-count {
636
+ justify-self: end;
637
+ color: var(--text-muted);
638
+ font-family: var(--font-mono);
639
+ font-variant-numeric: tabular-nums;
640
+ white-space: nowrap;
641
+ }
642
+ .debug-list-head .debug-page-count {
643
+ color: var(--text-dim);
644
+ }
645
+ .debug-run {
646
+ display: inline-flex;
647
+ flex-wrap: wrap;
648
+ align-items: flex-start;
649
+ gap: 3px;
650
+ vertical-align: middle;
651
+ }
652
+ .debug-run-more {
653
+ color: var(--text-dim);
654
+ font-family: var(--font-mono);
655
+ font-size: 10px;
656
+ line-height: 16px;
657
+ }
658
+
659
+ .debug-meter-row {
660
+ display: flex;
661
+ flex-wrap: wrap;
662
+ align-items: center;
663
+ gap: 8px;
664
+ }
665
+ .debug-meter {
666
+ display: flex;
667
+ min-height: 18px;
668
+ flex-wrap: wrap;
669
+ align-items: center;
670
+ gap: 3px;
671
+ }
672
+ .debug-slot {
673
+ display: inline-flex;
674
+ min-width: 32px;
675
+ height: 18px;
676
+ box-sizing: border-box;
677
+ align-items: center;
678
+ justify-content: center;
679
+ border-radius: 3px;
680
+ }
681
+ .debug-slot.is-empty {
682
+ border: 1px dotted var(--border);
683
+ }
684
+ .debug-meter.is-inline .debug-slot {
685
+ min-width: 0;
686
+ height: 16px;
687
+ }
688
+ .debug-meter-overflow {
689
+ margin-left: 2px;
690
+ font-family: var(--font-mono);
691
+ font-size: 11px;
692
+ }
693
+
694
+ .debug-spark {
695
+ display: inline-flex;
696
+ width: 120px;
697
+ height: 15px;
698
+ }
699
+ .debug-spark svg {
700
+ display: block;
701
+ }
702
+ .debug-bar {
703
+ position: relative;
704
+ display: inline-block;
705
+ flex-shrink: 0;
706
+ overflow: hidden;
707
+ border-radius: 2px;
708
+ background: var(--border);
709
+ vertical-align: middle;
710
+ }
711
+ .debug-bar-fill {
712
+ position: absolute;
713
+ top: 0;
714
+ bottom: 0;
715
+ left: 0;
716
+ background: currentColor;
717
+ }
718
+ .debug-bar-notch {
719
+ position: absolute;
720
+ top: 0;
721
+ bottom: 0;
722
+ width: 1px;
723
+ background: var(--bg-panel);
724
+ }
725
+ .debug-dot {
726
+ display: inline-block;
727
+ width: 8px;
728
+ height: 8px;
729
+ flex-shrink: 0;
730
+ border-radius: 50%;
731
+ background: currentColor;
732
+ }
733
+ .debug-dot.is-ring {
734
+ background: transparent;
735
+ box-shadow: inset 0 0 0 1.5px currentColor;
736
+ }
737
+
738
+ .debug-status {
739
+ display: inline-flex;
740
+ width: 14px;
741
+ height: 14px;
742
+ flex-shrink: 0;
743
+ align-items: center;
744
+ justify-content: center;
745
+ }
746
+ .debug-status-ring {
747
+ width: 7px;
748
+ height: 7px;
749
+ box-sizing: border-box;
750
+ border: 1.5px solid var(--text-dim);
751
+ border-radius: 50%;
752
+ }
753
+ .debug-status-ring.is-closing {
754
+ border-style: dashed;
755
+ border-color: var(--dbg-warn);
756
+ }
757
+ .debug-status-ring.is-none {
758
+ border-style: dotted;
759
+ border-color: var(--text-dim);
760
+ }
761
+ .debug-status-ring.is-starting {
762
+ border-style: dashed;
763
+ }
764
+
765
+ /* The chat's details under its row, from the title's edge; the row's tint carried down. */
766
+ .debug-detail {
767
+ display: flex;
768
+ min-width: 0;
769
+ flex-direction: column;
770
+ gap: 4px;
771
+ margin-bottom: 2px;
772
+ padding: 0 4px 5px 24px;
773
+ border-radius: 0 0 4px 4px;
774
+ background: var(--bg-selected);
775
+ }
776
+ .debug-detail-line {
777
+ display: flex;
778
+ min-width: 0;
779
+ flex-wrap: wrap;
780
+ align-items: center;
781
+ gap: 2px 6px;
782
+ }
783
+ .debug-detail-id,
784
+ .debug-starts {
785
+ color: var(--text-dim);
786
+ font-family: var(--font-mono);
787
+ font-size: 11px;
788
+ }
789
+ .debug-idle-row {
790
+ display: flex;
791
+ flex-wrap: wrap;
792
+ align-items: center;
793
+ gap: 4px 8px;
794
+ }
795
+ .debug-subhead {
796
+ display: flex;
797
+ align-items: center;
798
+ gap: 6px;
799
+ color: var(--text);
800
+ font-size: 11px;
801
+ font-weight: 700;
802
+ }
803
+ .debug-panel .debug-subhead.is-dim {
804
+ color: var(--text-dim);
805
+ }
806
+ .debug-run-line {
807
+ display: flex;
808
+ flex-wrap: wrap;
809
+ align-items: center;
810
+ gap: 2px 6px;
811
+ }
812
+ .debug-run-icon {
813
+ display: inline-flex;
814
+ width: 12px;
815
+ height: 12px;
816
+ flex-shrink: 0;
817
+ align-items: center;
818
+ justify-content: center;
819
+ }
820
+ .debug-run-icon svg {
821
+ width: 12px;
822
+ height: 12px;
823
+ }
824
+ .debug-run-name {
825
+ min-width: 0;
826
+ overflow: hidden;
827
+ color: var(--text);
828
+ font-size: 12px;
829
+ text-overflow: ellipsis;
830
+ white-space: nowrap;
831
+ }
832
+ .debug-pills {
833
+ display: flex;
834
+ flex-wrap: wrap;
835
+ align-items: center;
836
+ gap: 4px 10px;
837
+ }
838
+ .debug-pill {
839
+ display: inline-flex;
840
+ align-items: center;
841
+ gap: 4px;
842
+ font-size: 11px;
843
+ }
844
+ .debug-pill-state {
845
+ color: var(--text-dim);
846
+ white-space: nowrap;
847
+ }
848
+
849
+ .debug-group {
850
+ display: flex;
851
+ flex-direction: column;
852
+ }
853
+ .debug-group-head {
854
+ display: flex;
855
+ min-height: 22px;
856
+ align-items: center;
857
+ gap: 5px;
858
+ color: var(--text-dim);
859
+ font-size: 11px;
860
+ }
861
+ .debug-group-head svg {
862
+ flex-shrink: 0;
863
+ }
864
+ .debug-group-name {
865
+ min-width: 0;
866
+ overflow: hidden;
867
+ font-weight: 600;
868
+ text-overflow: ellipsis;
869
+ white-space: nowrap;
870
+ }
871
+ .debug-group-count {
872
+ font-family: var(--font-mono);
873
+ font-size: 10px;
874
+ font-variant-numeric: tabular-nums;
875
+ }
876
+ .debug-row {
877
+ display: grid;
878
+ min-height: 24px;
879
+ /* The title keeps room for a few characters; the badges wrap before they take it all. */
880
+ grid-template-columns: 14px minmax(96px, 1fr) auto 104px;
881
+ align-items: center;
882
+ column-gap: 6px;
883
+ padding: 0 4px;
884
+ border-radius: 4px;
885
+ }
886
+ .debug-row.debug-list-head {
887
+ min-height: 18px;
888
+ color: var(--text-dim);
889
+ font-size: 10px;
890
+ }
891
+ /* At the end of their columns, spilling left rather than out of the row when wider. */
892
+ .debug-list-head-holders,
893
+ .debug-list-head-idle {
894
+ justify-self: end;
895
+ white-space: nowrap;
896
+ }
897
+ .debug-row.is-current {
898
+ position: relative;
899
+ background: var(--bg-selected);
900
+ }
901
+ .debug-row.has-detail {
902
+ border-radius: 4px 4px 0 0;
903
+ }
904
+ /* The sidebar's mark of the selected session (app/sidebar.css): a short bar on the left edge,
905
+ on the first line however many lines the row takes. */
906
+ .debug-row.is-current::before {
907
+ content: "";
908
+ position: absolute;
909
+ top: 5px;
910
+ left: 0;
911
+ width: 3px;
912
+ height: 14px;
913
+ border-radius: 0 2px 2px 0;
914
+ background: var(--accent);
915
+ }
916
+ .debug-row-status {
917
+ display: inline-flex;
918
+ width: 14px;
919
+ justify-content: center;
920
+ }
921
+ .debug-row-title {
922
+ position: relative;
923
+ display: flex;
924
+ min-width: 0;
925
+ align-items: center;
926
+ gap: 4px;
927
+ }
928
+ .debug-row.is-sub .debug-row-title {
929
+ padding-left: 16px;
930
+ }
931
+ .debug-row-branch {
932
+ position: absolute;
933
+ top: calc(50% - 8px);
934
+ left: 4px;
935
+ width: 8px;
936
+ height: 8px;
937
+ border-bottom: 1px solid var(--border);
938
+ border-left: 1px solid var(--border);
939
+ }
940
+ .debug-row-name {
941
+ min-width: 0;
942
+ overflow: hidden;
943
+ color: var(--text);
944
+ font-size: 12px;
945
+ text-overflow: ellipsis;
946
+ white-space: nowrap;
947
+ }
948
+ .debug-row.is-sub .debug-row-name {
949
+ color: var(--text-muted);
950
+ }
951
+ .debug-row.is-current .debug-row-name {
952
+ font-weight: 600;
953
+ }
954
+ .debug-row.is-placeholder .debug-row-name {
955
+ color: var(--text-dim);
956
+ }
957
+ .debug-row-starts {
958
+ flex-shrink: 0;
959
+ color: var(--text-dim);
960
+ font-family: var(--font-mono);
961
+ font-size: 10px;
962
+ }
963
+ .debug-row-badges {
964
+ display: flex;
965
+ min-width: 0;
966
+ flex-wrap: wrap;
967
+ justify-content: flex-end;
968
+ align-items: center;
969
+ gap: 3px 8px;
970
+ }
971
+ .debug-row-idle {
972
+ display: flex;
973
+ align-items: center;
974
+ justify-content: flex-end;
975
+ gap: 4px;
976
+ }
977
+ .debug-row-forced {
978
+ width: 6px;
979
+ height: 6px;
980
+ flex-shrink: 0;
981
+ border-radius: 1px;
982
+ background: currentColor;
983
+ }
984
+ .debug-row-idle-text {
985
+ min-width: 3ch;
986
+ font-family: var(--font-mono);
987
+ font-size: 11px;
988
+ font-variant-numeric: tabular-nums;
989
+ text-align: right;
990
+ }
991
+
992
+ /* The server's totals beside its title. */
993
+ .debug-server-head {
994
+ flex-wrap: wrap;
995
+ gap: 4px 14px;
996
+ color: var(--text-dim);
997
+ font-size: 11px;
998
+ }
999
+ .debug-server-item {
1000
+ display: inline-flex;
1001
+ flex-wrap: wrap;
1002
+ align-items: center;
1003
+ gap: 3px 4px;
1004
+ }
1005
+
1006
+ /* Narrower: the sessions under the server's pages, one border down both; the page's column
1007
+ beside them, its height going to the sessions' row rather than opening a gap under the pages. */
1008
+ @container debug-panel (max-width: 1239px) {
1009
+ .debug-cols {
1010
+ grid-template-areas: "page server" "page sessions";
1011
+ grid-template-columns: minmax(320px, max-content) minmax(0, 560px);
1012
+ grid-template-rows: auto 1fr;
1013
+ }
1014
+ .debug-col-sessions {
1015
+ padding-top: 10px;
1016
+ }
1017
+ }
1018
+ @container debug-panel (max-width: 760px) {
1019
+ .debug-cols {
1020
+ grid-template-areas: "page" "server" "sessions";
1021
+ grid-template-columns: minmax(0, 1fr);
1022
+ grid-template-rows: none;
1023
+ }
1024
+ .debug-col-server {
1025
+ margin-top: 10px;
1026
+ padding-top: 10px;
1027
+ border-top: 1px solid var(--border);
1028
+ }
1029
+ .debug-col-server,
1030
+ .debug-col-sessions {
1031
+ margin-left: 0;
1032
+ padding-left: 0;
1033
+ border-left: 0;
1034
+ }
1035
+ }
1036
+ @container debug-panel (max-width: 520px) {
1037
+ .debug-detail-id {
1038
+ display: none;
1039
+ }
1040
+ .debug-row {
1041
+ grid-template-columns: 14px minmax(0, 1fr) 64px;
1042
+ }
1043
+ /* The badges take a line of their own under the title, which keeps its width. */
1044
+ .debug-row-badges {
1045
+ grid-column: 2 / -1;
1046
+ grid-row: 2;
1047
+ flex-wrap: wrap;
1048
+ justify-content: flex-start;
1049
+ padding-bottom: 4px;
1050
+ }
1051
+ .debug-row.is-sub .debug-row-badges {
1052
+ padding-left: 16px;
1053
+ }
1054
+ .debug-row-badges:empty,
1055
+ .debug-list-head-holders,
1056
+ .debug-page-holder {
1057
+ display: none;
1058
+ }
1059
+ .debug-page-row {
1060
+ grid-template-columns: 30px minmax(0, 1fr) minmax(0, 1fr) 24px;
1061
+ }
1062
+ .debug-row-idle-bar {
1063
+ display: none;
1064
+ }
1065
+ .debug-server-head .debug-section-title {
1066
+ flex-basis: 100%;
1067
+ }
1068
+ }
1069
+ `;function wh(e){let{sessionId:t,running:n,...s}=e,{t:l}=(0,t_.s)(),[o,a]=(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 l=await s.json();l.info?a(l.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)(c3,{...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:l("loading"===d||n?"sessionPanel.loading":"missing"===d?"sessionPanel.missing":"sessionPanel.error")})}var wf=n(63606),wm=n(8422);let wg="pi-web:terminal-theme",wx="dark",wv={dark:{background:"#111318",foreground:"#d7dce5",cursor:"#60a5fa",selectionBackground:"#365b8a",black:"#1d222b",red:"#f87171",green:"#4ade80",yellow:"#facc15",blue:"#60a5fa",magenta:"#c084fc",cyan:"#22d3ee",white:"#e5e7eb",brightBlack:"#6b7280",brightRed:"#fca5a5",brightGreen:"#86efac",brightYellow:"#fde047",brightBlue:"#93c5fd",brightMagenta:"#d8b4fe",brightCyan:"#67e8f9",brightWhite:"#ffffff"},light:{background:"#fbfbfc",foreground:"#24292f",cursor:"#2563eb",cursorAccent:"#fbfbfc",selectionBackground:"#bfd7fb",black:"#24292f",red:"#cf222e",green:"#116329",yellow:"#7d4e00",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#6e7781",brightBlack:"#57606a",brightRed:"#a40e26",brightGreen:"#1a7f37",brightYellow:"#633c01",brightBlue:"#218bff",brightMagenta:"#a475f9",brightCyan:"#3192aa",brightWhite:"#8c959f"}};function wb(){try{var e;return e=window.localStorage.getItem(wg),"light"===e?"light":wx}catch{return wx}}let wy=null,ww=new Set;function wk(){return null===wy&&(wy=wb()),wy}function wj(){ww.forEach(e=>e())}function wS(e){if(null!==e.key&&e.key!==wg)return;let t=wb();t!==wy&&(wy=t,wj())}function wC(e){return 0===ww.size&&(window.addEventListener("storage",wS),wy=wb()),ww.add(e),()=>{ww.delete(e),0===ww.size&&window.removeEventListener("storage",wS)}}async function wN(e,t){let n=await fetch(e,{...t,signal:AbortSignal.timeout(15e3)}),r=await n.json().catch(()=>{throw Error(`Terminal request failed (HTTP ${n.status}): server returned an empty or invalid JSON response. Check the pi-web server log.`)});if(!r||"object"!=typeof r)throw Error(`Terminal request failed (HTTP ${n.status}): invalid JSON response. Check the pi-web server log.`);if(!n.ok)throw Error(r.error??`HTTP ${n.status}`);return r}let wE={ctrl:!1,alt:!1},w$=[["Escape","/","-","Home","ArrowUp","End","PageUp"],["Tab","ctrl","alt","ArrowLeft","ArrowDown","ArrowRight","PageDown"]],wI=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","PageUp","PageDown"]),wM={ArrowUp:"A",ArrowDown:"B",ArrowRight:"C",ArrowLeft:"D",Home:"H",End:"F"},wT={PageUp:5,PageDown:6};function wR(e){let{ctrl:t,alt:n}=e;return 1+2*!!n+4*!!t}function wA(e,t){if(!t.ctrl&&!t.alt||1!=[...e].length)return e;let n=t.ctrl?function(e){if(/^[a-z]$/i.test(e))return String.fromCharCode(31&e.toUpperCase().charCodeAt(0));let t=e.charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):" "===e?"\0":"/"===e||"-"===e?"\x1f":"?"===e?"":e}(e):e;return t.alt?`\x1b${n}`:n}let wL={Escape:"ESC","/":"/","-":"-",Home:"HOME",ArrowUp:"↑",End:"END",PageUp:"PGUP",Tab:"TAB",ctrl:"CTRL",alt:"ALT",ArrowLeft:"↓",ArrowDown:"↓",ArrowRight:"↑",PageDown:"PGDN"},wz={ArrowUp:"Up",ArrowDown:"Down",ArrowLeft:"Left",ArrowRight:"Right",PageUp:"Page Up",PageDown:"Page Down"};function wP(e){let t=window.matchMedia("(pointer: coarse)");return t.addEventListener("change",e),window.screen.orientation?.addEventListener("change",e),window.addEventListener("orientationchange",e),window.addEventListener("resize",e),()=>{t.removeEventListener("change",e),window.screen.orientation?.removeEventListener("change",e),window.removeEventListener("orientationchange",e),window.removeEventListener("resize",e)}}let wW=()=>window.matchMedia("(pointer: coarse)").matches&&function(){let e=window.screen.orientation?.type;if(e)return e.startsWith("portrait");let t=window.orientation;return"number"==typeof t?t%180==0:window.innerHeight>=window.innerWidth}();function wO(e){let{modifiers:t,onKey:n,onToggleModifier:s}=e,{t:l}=(0,t_.s)(),o=(0,i.useRef)(null),a=()=>{null!==o.current&&window.clearTimeout(o.current),o.current=null};return(0,i.useEffect)(()=>a,[]),(0,r.jsx)("div",{className:"terminal-extra-keys",role:"toolbar","aria-label":l("terminal.extraKeys"),children:w$.flat().map(e=>{let i="ctrl"===e||"alt"===e;return(0,r.jsx)("button",{type:"button",tabIndex:-1,className:i&&t[e]?"is-active":void 0,"aria-pressed":i?t[e]:void 0,"aria-label":i?void 0:wz[e],onPointerDown:t=>((e,t)=>{if(e.preventDefault(),0!==e.button)return;if(a(),"ctrl"===t||"alt"===t)return void s(t);if(n(t),!wI.has(t))return;let r=()=>{n(t),o.current=window.setTimeout(r,50)};o.current=window.setTimeout(r,400)})(t,e),onPointerUp:a,onPointerCancel:a,onPointerLeave:a,onMouseDown:e=>e.preventDefault(),onContextMenu:e=>e.preventDefault(),children:"ArrowLeft"===e||"ArrowRight"===e?(0,r.jsx)("span",{className:"is-rotated",children:wL[e]}):wL[e]},e)})})}function wF(){return window.matchMedia("(pointer: fine)").matches}function wD(e){let{tab:t,active:n,onRestart:s,onClosed:l,onCloseError:o}=e,{t:a}=(0,t_.s)(),{id:d,cwd:c,restored:u}=t,p=(0,i.useRef)(null),h=(0,i.useRef)(null),f=(0,i.useRef)(Promise.resolve()),m=(0,i.useRef)(null),g=(0,i.useRef)({onClosed:l,onCloseError:o});g.current={onClosed:l,onCloseError:o};let[x,v]=(0,i.useState)("connecting"),[b,y]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(0),[C,N]=(0,i.useState)(wE),E=(0,i.useRef)(C),$=(0,i.useSyncExternalStore)(wP,wW,()=>!1),I=(0,i.useSyncExternalStore)(wC,wk,()=>wx),M=(0,i.useRef)(I);M.current=I;let T=aM(aO().fontSize)-14+13,R=(0,i.useRef)(T);R.current=T;let A=(0,i.useRef)(()=>{}),L=(0,i.useCallback)(()=>{let e=E.current;return(e.ctrl||e.alt)&&(E.current=wE,N(wE)),e},[]);(0,i.useEffect)(()=>{var e;let t,n,r,i,s,l=p.current;if(!l)return;let o=!1,a=null,g=!1,x=!1,b=!1,w=!1,S=0;v("connecting"),y(null),k(null);let C=()=>{let e=getComputedStyle(l);return{fontFamily:e.getPropertyValue("--font-mono").trim()||"monospace",fontWeight:aH(e.getPropertyValue("--font-mono-weight"))}},N=new wm.B({cursorBlink:!0,...C(),fontSize:R.current,lineHeight:1.25,scrollback:8e3,screenReaderMode:!0,disableStdin:!0,theme:wv[M.current]});h.current=N;let E=new wf.Y;N.loadAddon(E),N.open(l),N.attachCustomKeyEventHandler(e=>{if("keydown"!==e.type)return!0;let t=e.key.toLowerCase();return!((e.ctrlKey||e.metaKey)&&"v"===t||(e.ctrlKey||e.metaKey)&&"c"===t&&N.hasSelection())});let $=(e=e=>{o||(b=!0,N.options.disableStdin=!0,y(e.message),v("error"))},n=Promise.resolve(),r=!1,i=null,s=t=>{r||(n=n.then(async()=>{r||(t===i&&(i=null),await wN(`/api/terminal/${encodeURIComponent(d)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}))}).catch(t=>{r=!0,e(t)}))},{write(e){if(!r)for(let t of e.match(/[\s\S]{1,32768}/gu)??[])i&&i.data.length+t.length<=65536?i.data+=t:s(i={type:"input",data:t})},resize(e,t){i=null,s({type:"resize",cols:e,rows:t})},stop:()=>(r=!0,i=null,n)});m.current=$;let I=N.onData(e=>{!g||x||b||S||$.write(wA(e,L()))}),T=()=>{l.offsetWidth&&l.offsetHeight&&E.fit()},z=N.onResize(e=>{let{cols:t,rows:n}=e;!g||x||b||$.resize(Math.max(2,t),Math.max(2,n))});A.current=T;let P=new ResizeObserver(T);P.observe(l);let W=a0(()=>{if(o)return;let e=C();N.options.fontFamily=e.fontFamily,N.options.fontWeight=e.fontWeight,T()}),O=()=>{if(o||x||!navigator.onLine)return;a?.close();let e=new URLSearchParams({holder:td()});void 0!==t&&e.set("after",String(t)),(a=th("terminal",new EventSource(`/api/terminal/${encodeURIComponent(d)}/events?${e}`),c)).onmessage=e=>{let n=JSON.parse(e.data);if("output"===n.type){let e=w;if(w=!1,n.reset)N.reset();else if(void 0!==t&&n.offset<=t)return;e&&n.data?(S+=1,N.write(n.data,()=>{S-=1})):N.write(n.data),t=n.offset}else x=!0,g=!1,N.options.disableStdin=!0,a?.close(),k("exit"===n.type?n.exitCode:null),v("exited")},a.onopen=()=>{w=u||j>0||void 0!==t,g=!0,!b&&(N.options.disableStdin=!1,v("ready"),T(),$.resize(Math.max(2,N.cols),Math.max(2,N.rows)),wF()&&l.offsetWidth&&l.offsetHeight&&N.focus())},a.onerror=()=>{o||x||(g=!1,N.options.disableStdin=!0,v(a?.readyState===EventSource.CLOSED?"error":"connecting"))}};f.current=(async()=>{T(),u||j>0?await wN(`/api/terminal/${encodeURIComponent(d)}`):await wN("/api/terminal",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:d,cwd:c,cols:N.cols,rows:N.rows})}),O()})().catch(e=>{o||(y(e.message),v("error"))});let F=()=>{g=!1,N.options.disableStdin=!0,a?.close(),x||b||v("connecting")},D=e=>{e.persisted&&O()};return window.addEventListener("pagehide",F),window.addEventListener("pageshow",D),window.addEventListener("offline",F),window.addEventListener("online",O),()=>{o=!0,a?.close(),$.stop(),P.disconnect(),W(),I.dispose(),z.dispose(),window.removeEventListener("pagehide",F),window.removeEventListener("pageshow",D),window.removeEventListener("offline",F),window.removeEventListener("online",O),N.dispose(),h.current=null,A.current=()=>{}}},[d,c,u,j,L]),(0,i.useEffect)(()=>{h.current&&(h.current.options.theme=wv[I])},[I]),(0,i.useEffect)(()=>{let e=h.current;e&&e.options.fontSize!==T&&(e.options.fontSize=T,A.current())},[T]),(0,i.useEffect)(()=>{n&&wF()&&h.current?.focus()},[n]),(0,i.useEffect)(()=>{if(!t.closing)return;let e=!1;return h.current&&(h.current.options.disableStdin=!0),(async()=>{await f.current,await m.current?.stop(),await wN(`/api/terminal/${encodeURIComponent(d)}`,{method:"DELETE",keepalive:!0}),e||g.current.onClosed()})().catch(t=>{e||(y(t.message),v("error"),g.current.onCloseError())}),()=>{e=!0}},[d,t.closing]);let z="dark"===I?"light":"dark",P="light"===z?"terminal.lightTheme":"terminal.darkTheme";return(0,r.jsxs)("section",{className:"terminal-panel","data-terminal-theme":I,"aria-label":a("terminal.title"),children:[(0,r.jsxs)("header",{className:"terminal-panel-header",children:[(0,r.jsxs)("div",{className:"terminal-panel-path",children:[(0,r.jsx)("span",{className:`terminal-status-dot is-${x}`,title:a(`terminal.${x}`)}),(0,r.jsx)("span",{title:c,children:c})]}),(0,r.jsxs)("div",{className:"terminal-panel-actions",children:["error"===x&&(0,r.jsx)("button",{type:"button",onClick:()=>S(e=>e+1),disabled:!!t.closing,title:a("terminal.reconnect"),"aria-label":a("terminal.reconnect"),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-2 2M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l2-2"})})}),(0,r.jsx)("button",{type:"button",onClick:()=>(function(e){if(e!==wk()){wy=e;try{window.localStorage.setItem(wg,e)}catch{}wj()}})(z),title:a(P),"aria-label":a(P),children:"light"===z?(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"})]}):(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}),(0,r.jsx)("button",{type:"button",onClick:s,disabled:!!t.closing,title:a("terminal.restart"),"aria-label":a("terminal.restart"),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M20 11a8 8 0 1 0-2.34 5.66"}),(0,r.jsx)("polyline",{points:"20 4 20 11 13 11"})]})})]})]}),(0,r.jsxs)("div",{children:[b&&(0,r.jsx)("div",{className:"terminal-panel-error",role:"alert",children:b}),"exited"===x&&(0,r.jsx)("div",{className:"terminal-panel-exit",role:"status",children:null===w?a("terminal.exited"):a("terminal.exitCode",{code:w})})]}),(0,r.jsx)("div",{className:"terminal-xterm",children:(0,r.jsx)("div",{ref:p,className:"terminal-xterm-host"})}),$&&(0,r.jsx)(wO,{modifiers:C,onKey:e=>{let t=h.current;if(!t)return;let n=function(e,t,n){let r=t.ctrl||t.alt,i=wM[e];if(i)return r?`\x1b[1;${wR(t)}${i}`:n?`\x1bO${i}`:`\x1b[${i}`;let s=wT[e];return s?r?`\x1b[${s};${wR(t)}~`:`\x1b[${s}~`:"Escape"===e?t.alt?"\x1b\x1b":"\x1b":"Tab"===e?t.alt?"\x1b ":" ":wA(e,t)}(e,L(),t.modes.applicationCursorKeysMode);t.input(n,!0)},onToggleModifier:e=>{let t={...E.current,[e]:!E.current[e]};E.current=t,N(t)}})]})}let wB="pi-web:terminal-tabs";function wH(e){return{id:Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join(""),cwd:e}}let w_=e=>`pi-web:side-tabs:${e}`;function wU(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let wK=[48,120,240,420,720];function wq(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document;return"visible"!==e.visibilityState||!e.hasFocus()}async function wV(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 wZ="pi-web:tab-open-session";function wJ(){try{return window.sessionStorage}catch{return null}}function wY(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 wG(e,t){t.setItem(wZ,JSON.stringify(e))}let wX="pi-web:agent-strip-locked";function wQ(e){return dA(wX,e)}let w0="var(--top-bar-height)",w1=new Set(cc.kU);function w2(e){let t=e.at(-1);return t?`agent:${t.sessionId}`:null}function w4(){var e;let t,n,d,p,h,f,g,x,v,b,y,w,k,j=(0,s.useRouter)(),S=(0,s.useSearchParams)(),[C,N]=(0,i.useState)(()=>{let e;return{requestedCwd:e=S.get("cwd")?.trim()||null,sessionId:e?null:S.get("session")||null,sidebarCollapsed:"collapsed"===S.get("sidebar")}});lo(),a3();let{locale:E,t:$}=(0,t_.s)(),I=tQ(),M=(0,i.useSyncExternalStore)(tY,tG,tX);(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:wU(),innerHeight:window.innerHeight,viewportHeight:e.height,viewportScale:e.scale})?(t.style.setProperty("--app-viewport-height",`${e.height}px`),t.dataset.keyboardOpen="true"):(t.style.removeProperty("--app-viewport-height"),delete t.dataset.keyboardOpen);let r=0!==window.scrollX||0!==window.scrollY,i=.01>Math.abs(e.scale-1);r&&i&&window.scrollTo(0,0)},l=()=>{null!==n&&window.cancelAnimationFrame(n),n=window.requestAnimationFrame(s),(()=>{if(i)return;i=!0;let e=0,t=()=>{if(e>=wK.length){i=!1;return}let n=wK[e++],l=window.setTimeout(()=>{r.delete(l),s(),t()},n);r.add(l)};t()})()},o=()=>{wU()&&l()};return l(),e.addEventListener("resize",l),e.addEventListener("scroll",l),window.addEventListener("resize",l),window.addEventListener("focusin",l),window.addEventListener("focusout",l),window.addEventListener("pageshow",l),document.addEventListener("compositionstart",o),document.addEventListener("compositionupdate",o),document.addEventListener("compositionend",o),document.addEventListener("input",o),document.addEventListener("keyup",o),()=>{for(let t of(e.removeEventListener("resize",l),e.removeEventListener("scroll",l),window.removeEventListener("resize",l),window.removeEventListener("focusin",l),window.removeEventListener("focusout",l),window.removeEventListener("pageshow",l),document.removeEventListener("compositionstart",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&&hK(E)},[E]);let{soundEnabled:T,onSoundToggle:A,playDoneSound:z,unlockAudio:P,holdAudio:W,soundEnabledRef:F}=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},[]),l=(0,i.useRef)(0),o=(0,i.useRef)(0),a=(0,i.useRef)(void 0),d=(0,i.useCallback)(e=>{clearTimeout(a.current),a.current=setTimeout(()=>{0===l.current&&0===o.current&&e.suspend().catch(()=>{})},1e3)},[]),c=(0,i.useCallback)((e,t)=>{l.current++,e.resume().then(t).catch(()=>{}).then(()=>{l.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(a.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 l=t+.18*r;s.gain.setValueAtTime(0,l),s.gain.linearRampToValueAtTime(.18,l+.02),s.gain.exponentialRampToValueAtTime(.001,l+.45),i.start(l),i.stop(l+.45)})}catch{}})},[s,c]),unlockAudio:u,holdAudio:h,soundEnabledRef:n}}(),[K,q]=(0,i.useState)(!1);(0,i.useEffect)(()=>{try{q("true"===localStorage.getItem("pi-quote-selection-enabled"))}catch{}},[]);let V=(0,i.useCallback)(e=>{q(e);try{localStorage.setItem("pi-quote-selection-enabled",String(e))}catch{}},[]),Z=(0,i.useRef)(new Set),[J,Y]=(0,i.useState)(new Set),G=(0,i.useCallback)((e,t)=>{F.current&&c0(e,t)&&z()},[z,F]),[X,Q]=(0,i.useState)(null),ee=(0,i.useRef)(X);ee.current=X;let[et,en]=(0,i.useState)([]),[er,ei]=(0,i.useState)(!1),es=(0,i.useCallback)(e=>{en(e),ei(!0),Q(t=>{if(!t)return t;let n=e.find(e=>e.id===t.id);return n?{...t,...n,detailsPending:n.detailsPending,relation:n.relation,branch:n.branch,isWorktree:n.isWorktree}:t})},[]),el=(0,i.useMemo)(()=>X?[...et.filter(e=>e.id!==X.id),X]:et,[X,et]),eo=(0,i.useMemo)(()=>c(el,X?.id),[X?.id,el]),[ea,ed]=(0,i.useState)(()=>new Set),ec=(0,i.useCallback)(e=>{ed(t=>t.size===e.size&&[...e].every(e=>t.has(e))?t:e)},[]),eu=eo?(t=u(e=eo.subagents,ea))>0?{count:t,running:!0}:{count:e.length,running:!1}:null,ep=eu?.running?$("agentSwitcher.titleRunning",{count:eu.count}):$("agentSwitcher.title"),[eh,ef]=(0,i.useState)(wQ),em=(0,i.useMemo)(()=>(function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!e||!t)return null;if(e.root.id===t){if(!n||0===e.subagents.length)return null}else if(!e.subagents.some(e=>e.id===t))return null;return[...e.subagents].sort((e,t)=>e.created.localeCompare(t.created)||e.id.localeCompare(t.id))})(eo,X?.id,eh),[eo,X?.id,eh]),eg=(0,i.useRef)(null),ex=(0,i.useCallback)(()=>{let e=!eh;ef(e),dL(wX,e,void 0),e||requestAnimationFrame(()=>to(document,eg.current))},[eh]),[ev,eb]=(0,i.useState)(null),[ey,ew]=(0,i.useState)("initial"),ek=(0,i.useRef)(null),ej=(0,i.useRef)(null),[eS,eC]=(0,i.useState)(null),eN=(0,i.useRef)(null),eE=(0,i.useCallback)(e=>{e&&e.cwd===eN.current?.cwd&&(eN.current=null),eC(e)},[]),e$=(0,i.useRef)(null),eI=(0,i.useRef)(null),[eM,eT]=(0,i.useState)(null),eR=(0,i.useCallback)(e=>{eI.current=e,eT(null)},[]),[eA,eL]=(0,i.useState)(()=>C.requestedCwd?"validating":"idle"),[ez,eP]=(0,i.useState)(null),[eW,eO]=(0,i.useState)(0),[eF,eD]=(0,i.useState)(0),eB=(0,i.useRef)(new Map),eH=(0,i.useCallback)((e,t)=>{eB.current.set(e,t)},[]),[e_,eU]=(0,i.useState)(null),eK=(0,i.useCallback)(e=>{eU(t=>t===e?null:t)},[]),[eq,eV]=(0,i.useState)(0),[eZ,eJ]=(0,i.useState)(null),[eY,eG]=(0,i.useState)(!1),[eX,eQ]=(0,i.useState)(0),[e0,e1]=(0,i.useState)(null),[e2,e4]=(0,i.useState)(!1),[e8,e3]=(0,i.useState)(!1),[e5,e6]=(0,i.useState)(null),[e9,e7]=(0,i.useState)(()=>!C.sidebarCollapsed),te=(0,i.useRef)(!C.sidebarCollapsed),[tt,tn]=(0,i.useState)(!1),[tr,ti]=(0,i.useState)(!1),ts=tt&&tr&&!I;(0,i.useEffect)(()=>{(!tt||I)&&ti(!1)},[tt,I]);let[tl,ta]=(0,i.useState)(!1),td=tl?$("chat.close"):$("chat.moreControls"),[tc,tu]=(0,i.useState)(!1),tp=(0,i.useRef)(260),th=(0,i.useRef)(560),tf=(0,i.useCallback)(()=>t0(.42*window.innerWidth,360,640),[]),tx=(0,i.useCallback)(()=>(function(e){let{viewportWidth:t,rightPanelOpen:n,rightPanelWidth:r}=e;if(t<=640)return 480;let i=t<960;return Math.min(480,t-(i?320:420)-(!i&&n?r:0))})({viewportWidth:window.innerWidth,rightPanelOpen:tt,rightPanelWidth:th.current}),[tt]),tv=(0,i.useCallback)(()=>(function(e){let{viewportWidth:t,sidebarOpen:n,sidebarWidth:r}=e;return t<960?1200:Math.min(1200,t-420-(n?r:0))})({viewportWidth:window.innerWidth,sidebarOpen:e9,sidebarWidth:tp.current}),[e9]),tb=t2({ariaLabel:$("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:tx,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"pi-sidebar-width",widthRef:tp}),ty=t2({ariaLabel:$("layout.resizeFilePanel"),cssVariable:"--right-panel-width",defaultWidth:560,getDefaultWidth:tf,getMaxWidth:tv,growthDirection:"left",maxWidth:1200,minWidth:300,storageKey:"pi-right-panel-width",widthRef:th}),tw=tb.reclampWidth,tk=ty.reclampWidth;(0,i.useEffect)(()=>{e7(!I&&te.current)},[I]),(0,i.useEffect)(()=>{tu(!0)},[]),(0,i.useEffect)(()=>{tt&&(tw(),tk())},[tk,tw,tt]);let tj=(0,i.useRef)(null),[tS,tC]=(0,i.useState)({}),tN=(0,i.useRef)(null),tE=(0,i.useRef)(null),[t$,tI]=(0,i.useState)([]),[tM,tT]=(0,i.useState)(null),[tR,tA]=(0,i.useState)(!1),tL=(0,i.useRef)(null),tz=bO(t$),tP=(0,i.useCallback)((e,t,n,r)=>{tI(e),tT(t),tA(r),tL.current=n},[]),tW=(0,i.useCallback)(e=>{tL.current?.(e)},[]),[tO,tF]=(0,i.useState)(null),[tD,tB]=(0,i.useState)(null),[tH,tU]=(0,i.useState)(!1),tK=(0,i.useRef)(null),tq=(0,i.useRef)(0),tV=(0,i.useRef)(null),tZ=(0,i.useCallback)(e=>{tF(e),tU(!1)},[]),tJ=(0,i.useCallback)(e=>{tB(e)},[]),t1=(0,i.useCallback)(e=>{tq.current+=1,tK.current=e,tU(!1)},[]),t4=(0,i.useRef)(null),t8=(0,i.useCallback)(e=>{t4.current=e},[]);(0,i.useEffect)(()=>{null===tm.trackingSince&&"u">typeof document&&(tm.trackingSince=Date.now(),document.addEventListener("visibilitychange",tg))},[]);let[t3,t5]=(0,i.useState)(null),[t6,t9]=(0,i.useState)({kind:"idle"}),t7=(0,i.useRef)(null),ne=(0,i.useRef)(X?.id??null);ne.current=X?.id??null;let nt=(0,i.useCallback)(e=>{t5(e)},[]),[nn,nr]=(0,i.useState)(null),ni=(0,i.useRef)(null),ns=(0,i.useCallback)((e,t)=>{i0(t).then(()=>{ni.current&&clearTimeout(ni.current),nr(e),ni.current=setTimeout(()=>nr(null),1400)},()=>{})},[]);(0,i.useEffect)(()=>()=>{ni.current&&clearTimeout(ni.current),t7.current&&clearTimeout(t7.current)},[]);let[nl,no]=(0,i.useState)(null),na=(0,i.useCallback)(e=>{no(e)},[]),[nd,nc]=(0,i.useState)(null),[nu,np]=(0,i.useState)(null);(0,i.useEffect)(()=>{tz||nc(e=>"branches"===e?null:e)},[tz]),(0,i.useEffect)(()=>{eo||nc(e=>"agents"===e?null:e)},[eo]),(0,i.useEffect)(()=>{ts&&nc(null)},[ts]);let nh=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];I&&e7(!1),nc(t=>t===e?null:e),I&&M&&t&&ta(!0)},[I,M]),nf=(0,i.useRef)(null),nm=(0,i.useCallback)(e=>{nc(e=>"debug"===e?null:e),e&&requestAnimationFrame(()=>to(document,nf.current))},[]),ng=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=nd!==e;if(nh(e,t),!n||tH)return;let r=tK.current;if(!r)return;let i=++tq.current;tU(!0),r().catch(e=>{console.error("Failed to load system information:",e)}).finally(()=>{tq.current===i&&tU(!1)})},[nd,tH,nh]),nx=(0,i.useCallback)(()=>{I&&e7(!1),ta(!1),nc("session")},[I]),nv=(0,i.useCallback)(e=>{eG(!1),eJ(e)},[]),ny=(0,i.useCallback)(()=>{I&&(nc(null),ta(!1)),e7(e=>{let t=!e;return I||(te.current=t),t})},[I]),nw=(0,i.useCallback)(()=>{e7(!1),nc(null),ta(e=>!e)},[]),nk=(0,i.useCallback)(()=>{I&&(e7(!1),nc(null),ta(!1)),tn(e=>!e)},[I]),nj=(0,i.useCallback)(()=>{nc(null),ti(e=>!e)},[]);(0,i.useEffect)(()=>{if(!tl)return;let e=e=>{let t=tE.current;t&&e.composedPath().includes(t)||ta(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),ta(!1))};return document.addEventListener("pointerdown",e,!0),document.addEventListener("keydown",t,!0),()=>{document.removeEventListener("pointerdown",e,!0),document.removeEventListener("keydown",t,!0)}},[tl]),(0,i.useEffect)(()=>{ta(!1)},[I,M,X?.id,ey]),(0,i.useEffect)(()=>{if(!nd||!tN.current)return;let e=()=>{let e=tN.current.getBoundingClientRect();"agents"===nd?np({top:e.bottom,left:e.left,width:Math.min(420,e.width)}):np({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(tN.current),()=>t.disconnect()},[nd,I]);let[nS,nC]=(0,i.useState)([]),[nE,n$]=(0,i.useState)(null),nI=(0,i.useRef)(new Map),[nM,nT]=(0,i.useState)(0),nR=(0,i.useRef)(0),[nA,nL]=(0,i.useState)([]),[nz,nP]=(0,i.useState)(!1),[nW,nO]=(0,i.useState)([]),nF=(0,i.useRef)(null),nD=(0,i.useRef)(!1),nB=(0,i.useRef)(!1),[nH,n_]=(0,i.useState)(null),nU=(0,i.useRef)(null),[nK,nq]=(0,i.useState)([]),nV=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()]}([...nS,...nA.map(e=>({id:e.id,label:nb(e.cwd)||e.cwd,filePath:e.cwd,kind:"terminal",closing:!!e.closing})),...nW.map(e=>{let t=e.side?et.find(t=>t.id===e.sessionId):void 0,n=t?o(t,$("agentSwitcher.sideChat"),eo?.subagents??[]):e.label;return{id:`agent:${e.sessionId}`,label:n,filePath:n,kind:e.side?"side":"agent"}})],nK),nZ=nV.map(e=>e.id).join("\n");(0,i.useEffect)(()=>{let e=new Set(nZ.split("\n"));nq(t=>t.every(t=>e.has(t))?t:t.filter(t=>e.has(t)))},[nZ]),(0,i.useEffect)(()=>{try{let e=function(e){try{let t=JSON.parse(e??"null"),n=[];for(let e of Array.isArray(t?.tabs)?t.tabs:[])e&&"string"==typeof e.id&&/^[a-f0-9]{32}$/.test(e.id)&&"string"==typeof e.cwd&&e.cwd.trim()&&!n.some(t=>t.id===e.id||t.cwd===e.cwd)&&n.push({id:e.id,cwd:e.cwd,restored:!0});return{tabs:n,activeId:n.some(e=>e.id===t.activeId)?t.activeId:null,open:t?.open===!0}}catch{return{tabs:[],activeId:null,open:!1}}}(window.sessionStorage.getItem(wB));nL(e.tabs),e.activeId&&(n$(e.activeId),tn(e.open))}catch{}nP(!0)},[]),(0,i.useEffect)(()=>{if(nz)try{window.sessionStorage.setItem(wB,JSON.stringify({tabs:nA.map(e=>{let{id:t,cwd:n}=e;return{id:t,cwd:n}}),activeId:nE,open:tt}))}catch{}},[nA,nE,tt,nz]);let nJ=(0,i.useCallback)(e=>{try{let t=nW.filter(e=>e.side);if(!t.length)return void window.sessionStorage.removeItem(w_(e));window.sessionStorage.setItem(w_(e),JSON.stringify({tabs:t,activeId:t.some(e=>`agent:${e.sessionId}`===nE)?nE:null,open:tt}))}catch{}},[nW,nE,tt]),nY=(0,i.useCallback)((e,t,n,r)=>{e!==nR.current?function(e,t,n,r,i){for(let[s,l]of e)if(l.generation===t)return void e.set(s,{...l,tabs:u0(l.tabs,n,r,i)})}(nI.current,e,t,n,r):nC(e=>u0(e,t,n,r))},[]),nG=(0,i.useCallback)((e,t)=>{if(e===t)return;let n=nE?.startsWith("file:")?nE:null,r=function(e,t,n,r,i){if(t===n)return r;t&&e.set(t,{...r,generation:i});let s=e.get(n);return s?(e.delete(n),{tabs:s.tabs,activeTabId:s.activeTabId,open:s.open}):{tabs:[],activeTabId:null,open:!1}}(nI.current,e,t,{tabs:nS,activeTabId:n,open:tt&&!!n},nR.current);nR.current+=1,nT(nR.current),nC(r.tabs),nO(e=>e.filter(e=>e.side)),nD.current&&nF.current&&(nJ(nF.current),nB.current=!0),(!nE||n||nE.startsWith("agent:"))&&(n$(r.activeTabId),tn(r.open))},[nE,nS,nJ,tt]),nX=(0,i.useCallback)((e,t)=>{tj.current?.insertText(nN(e,t)),I&&(tn(!1),e7(!1))},[I]),nQ=(0,i.useCallback)(e=>{let t=e.map(e=>nN(e,!1)).join("");t&&tj.current?.insertText(t),I&&(tn(!1),e7(!1))},[I]),n0=(0,i.useCallback)((e,t,n)=>{let r,i,s,l;tj.current?.insertText((r=Math.max(1,Math.min(t,n)),i=Math.max(1,Math.max(t,n)),s=e.includes(" ")?`@"${e}"`:`@${e}`,l=r===i?`:${r}`:`:${r}-${i}`,`${s}${l} `)),I&&(tn(!1),e7(!1))},[I]),n1=C.sessionId,n2=C.sessionFromTab?null:C.sessionId,[n4,n8]=(0,i.useState)(()=>!n1),n3=eo?.root.id??null;(0,i.useEffect)(()=>{if(!er||!n4)return;let e=nF.current;if(!nD.current||e!==n3){nD.current&&e&&!nB.current&&nJ(e),nB.current=!1,nD.current=!0,nF.current=n3;let t={tabs:[],activeId:null,open:!1};if(n3)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(w_(n3)),n3,et)}catch{}nO(e=>[...e.filter(e=>!e.side),...t.tabs]);let n=t.activeId===`agent:${X?.id}`?null:t.activeId;(n||nE?.startsWith("agent:")||!nE)&&(n$(n??nS.at(-1)?.id??nA.at(-1)?.id??null),tn(n?t.open:!!(nS.length||nA.length)&&tt));return}n3&&nJ(n3),nB.current=!1},[nE,er,nS,n4,nJ,tt,X?.id,et,n3,nA]),(0,i.useLayoutEffect)(()=>{var e;let t=(e=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:wJ();if(!e)return null;try{return wY(e.getItem(wZ))}catch{return null}}(),C.requestedCwd||C.sessionId||!e?C:"session"===e.kind?{...C,sessionId:e.sessionId,sessionFromTab:!0}:{...C,requestedCwd:e.cwd});t!==C&&(N(t),t.sessionId&&n8(!1))},[C]);let n5=(0,i.useRef)(!1),n6=(0,i.useRef)(!1),n9=(0,i.useRef)(0),n7=(0,i.useCallback)(()=>{n9.current+=1},[]);(0,i.useEffect)(()=>{if(X){!function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:B();if(n)try{let r=H(n);r[e]=t,n.setItem(D,JSON.stringify(r))}catch{}}(X.projectKey??nU.current??U(X),X.id),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:wJ();if(t&&e)try{wG({kind:"session",sessionId:e},t)}catch{}}(X.id);return}ev&&function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:wJ(),n=e.trim();if(t&&n)try{wG({kind:"new",cwd:n},t)}catch{}}(ev)},[ev,X]),(0,i.useEffect)(()=>{let e=C.requestedCwd;if(!e)return;let t=new AbortController;return eL("validating"),eP(null),fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e}),signal:t.signal}).then(async t=>{let n=await t.json().catch(()=>({}));if(!t.ok||!n.cwd)throw Error(n.error??`HTTP ${t.status}`);n5.current=!0;let r=`initial:${e}`;ew(r),ek.current=`new:${r}:${n.cwd}`,eb(n.cwd),eL("ready"),new URLSearchParams(window.location.search).get("cwd")||j.replace(`?cwd=${encodeURIComponent(n.cwd)}`,{scroll:!1})}).catch(e=>{t.signal.aborted||(eP(e instanceof Error?e.message:String(e)),eL("error"))}),()=>t.abort()},[C,j]);let re=(0,i.useCallback)((e,t)=>{let n=++n9.current,r=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:B();if(!t)return null;try{let n=H(t)[e];return"string"==typeof n&&n.length>0?n:null}catch{return null}}(e);if(!r)return;let i=i=>{if(n!==n9.current)return;let s=i?.sessions.find(e=>e.id===r);if(!s){i&&_(e);return}if(U(s)!==e)return void _(e);let l=ek.current;l&&O(l,m(t)),ek.current=null,Q(s),eD(e=>e+1),new URLSearchParams(window.location.search).get("session")!==s.id&&j.replace(`?session=${encodeURIComponent(s.id)}`,{scroll:!1})};et.length>0?i({sessions:et}):fetch("/api/sessions").then(e=>e.ok?e.json():null).then(i).catch(()=>{})},[j,et]),rt=(0,i.useCallback)((e,t,n)=>{n7();let r=ev??nH;if(n_(e),!e)return;let i=n6.current;n6.current=!1;let s=n??t??e,l=nU.current??(X?U(X):null);if(nU.current=s,n5.current){n5.current=!1;return}if(r===e&&l!==s||l===s&&(null!==X||r===e))return;let o=ek.current;o&&r&&O(o,m(r));let a="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,d=`new:${a}:${e}`;O(m(e),d),ew(a),ek.current=d,Q(null),eb(t=>t&&t!==e?null:t),eD(e=>e+1),tI([]),tT(null),tA(!1),tF(null),tB(null),tU(!1),nc(e=>"debug"===e?e:null),l!==s&&(nG(l,s),i||re(s,e)),j.replace(window.location.pathname,{scroll:!1})},[nH,nG,n7,ev,j,X,re]),rn=(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;eU(n?{sessionId:e.id,entryId:n,blockIndex:r}:null),n7();let s=ek.current,l=ev??(null===X?nH:null);s&&l&&O(s,m(l)),ek.current=null;let o=U(e);if(nU.current!==o&&(nG(nU.current,o),nc(e=>"debug"===e?e:null)),nU.current=o,!t&&X){let t=U(X)===U(e);if(X.id===e.id&&t){I&&e7(!1);return}}eb(null),Q(e),eD(e=>e+1),tI([]),tT(null),tA(!1),tL.current=null,tF(null),tB(null),tU(!1),n8(!0),!I||t||i?.keepSidebarOpen||e7(!1),t&&(n5.current=!0),t&&new URLSearchParams(window.location.search).get("session")===e.id||j.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[nH,nG,n7,j,I,ev,X]),rr=(0,i.useCallback)((e,t,n,r)=>{n7();let i=`new:${e}:${t}`,s=ek.current,l=ev??(null===X?nH:null);if(r?.carryComposer&&null===X&&s){let e=tj.current;e?e.rekeyDraft(s,i):O(s,i),eT(eI.current)}else s&&l&&l!==t&&O(s,m(l));let o=n??(t===nH?nU.current:null)??t;nU.current!==o&&nG(nU.current,o),nU.current=o,R(i)||O(m(t),i),ek.current=i,ew(e),Q(null),eb(t),eD(e=>e+1),tI([]),tT(null),tA(!1),tF(null),tB(null),tU(!1),nc(e=>"debug"===e?e:null),I&&e7(!1),j.replace(`?cwd=${encodeURIComponent(t)}`,{scroll:!1}),I||e$.current||requestAnimationFrame(()=>{document.activeElement?.closest("[aria-modal='true']")||tj.current?.focus()})},[nH,nG,n7,I,ev,j,X]);!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||!l)return;let t=e.target?.tagName;"TEXTAREA"!==t&&"INPUT"!==t&&(e.preventDefault(),l())}(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=>rr(`kb-${Date.now()}`,e),activeCwd:nH});let ri=(0,i.useCallback)(e=>{fetch("/api/sessions",{cache:"no-store"}).then(e=>e.ok?e.json():null).then(t=>{let n=t?.sessions.find(t=>t.id===e);n&&Q(t=>t?.id===e?{...t,...n,transient:n.transient??!1}:t)}).catch(()=>{})},[]),rs=(0,i.useCallback)((e,t)=>{eO(e=>e+1),ek.current===t&&(n7(),ek.current=null,eb(null),Q(e),ri(e.id),j.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1}))},[n7,j,ri]),rl=(0,i.useCallback)(e=>{let{targetSession:t,title:n,body:r,tag:i}=e;if(!("Notification"in window))return;let s=()=>{wV({title:n,body:r,sessionUrl:t?`/?session=${encodeURIComponent(t.id)}`:"/",tag:i,onClick:()=>{window.focus(),t&&rn(t)}})};"granted"===Notification.permission?(s(),hK(E)):"default"===Notification.permission&&Notification.requestPermission().then(e=>{"granted"===e&&(s(),hK(E))})},[rn,E]),ro=(0,i.useCallback)(e=>{eO(e=>e+1),eV(e=>e+1),e.aborted||e.subagentsActive||a(X?.relation)||!wq()||(X&&Y(e=>{if(e.has(X.id))return e;let t=new Set(e);return t.add(X.id),t}),rl({targetSession:X,title:X?.name??$("i18n.sessionComplete"),body:$("i18n.taskFinished"),tag:X?`pi-session-complete:${X.id}`:"pi-session-complete"}))},[rl,X,$]);(0,i.useEffect)(()=>{let e=()=>{"visible"===document.visibilityState&&document.hasFocus()&&Y(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 ra=(0,i.useCallback)(e=>{var t;!a(X?.relation)&&wq()&&(t=Z.current,!(!d1(e)||t.has(e.id))&&(t.add(e.id),1)&&rl({targetSession:X,title:$("i18n.attentionNeeded"),body:"custom"===e.method?$("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[rl,X,$]),rd=(0,i.useCallback)(async()=>{let e=X?.id;if(e&&"naming"!==t6.kind){t7.current&&clearTimeout(t7.current),nc(null),t9({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(eO(e=>e+1),ne.current!==e)return;Q(t=>t?.id===e?{...t,name:r}:t),t5(t=>t?.sessionId===e?{...t,sessionName:r}:t),t9({kind:"success"}),t7.current=setTimeout(()=>t9({kind:"idle"}),1800)}catch(t){if(ne.current!==e)return;t9({kind:"error",message:t instanceof Error?t.message:String(t)}),t7.current=setTimeout(()=>t9({kind:"idle"}),5e3)}}},[t6.kind,X?.id]);(0,i.useEffect)(()=>{t7.current&&clearTimeout(t7.current),t9({kind:"idle"})},[X?.id]);let rc=(0,i.useCallback)(()=>{eV(e=>e+1)},[]),ru=(0,i.useRef)(null),rp=(0,i.useCallback)(e=>{w1.has(e)||ru.current||(ru.current=setTimeout(()=>{ru.current=null,eV(e=>e+1)},1e3))},[]);(0,i.useEffect)(()=>()=>{ru.current&&clearTimeout(ru.current)},[]);let rh=(0,i.useCallback)((e,t)=>{if(t){eO(e=>e+1),rn(t);return}n7(),ek.current=null,eO(e=>e+1),eD(e=>e+1),eb(null),Q(t=>({...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1})),ri(e),j.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1})},[rn,n7,j,ri]),rf=(0,i.useCallback)(()=>{n8(!0),n2&&(n6.current=!0)},[n2]),rm=(0,i.useCallback)(e=>{n7(),eO(e=>e+1);let t=ee.current;if(t?.id===e){!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:wJ();if(t&&e)try{let n=wY(t.getItem(wZ));if(n?.kind!=="session"||n.sessionId!==e)return;t.removeItem(wZ)}catch{}}(e);let n=t.cwd,r="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;ew(r),ek.current=n?`new:${r}:${n}`:null,Q(null),eb(n??null),eD(e=>e+1),tI([]),tT(null),tA(!1),tF(null),tB(null),tU(!1),nc(e=>"debug"===e?e:null),j.replace(n?`?cwd=${encodeURIComponent(n)}`:window.location.pathname,{scroll:!1})}},[n7,j]),rg=(0,i.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,i=n?.modeHint,s=n?.page,l=`file:${e}`;nC(n=>(function(e,t){let n=e.find(e=>e.id===t.tabId);if(!n)return[...e,{id:t.tabId,label:t.fileName,filePath:t.filePath,sourceSessionId:t.sourceSessionId,initialDisplayMode:t.modeHint,page:t.page,viewerState:t.modeHint?{displayMode:t.modeHint,scrollTop:0,scrollLeft:0}:void 0,viewerRevision:0}];let r=!!(t.sourceSessionId&&n.sourceSessionId!==t.sourceSessionId),i=n.page!==t.page;return r||t.modeHint||i?e.map(e=>{if(e.id!==t.tabId)return e;let n={...e},s=!1;return r&&(n.sourceSessionId=t.sourceSessionId,s=!0),i&&(n.page=t.page,s=!0),t.modeHint&&(n.initialDisplayMode=t.modeHint,n.viewerState={displayMode:t.modeHint,wrapLines:e.viewerState?.wrapLines,scrollTop:0,scrollLeft:0},s=!0),s&&(n.viewerRevision=(e.viewerRevision??0)+1),n}):e})(n,{fileName:t,filePath:e,modeHint:i,page:s,sourceSessionId:r,tabId:l})),n$(l),tn(!0),I&&e7(!1)},[I]),rx=(0,i.useCallback)((e,t)=>{rg(e,nb(e),{sourceSessionId:X?.id??null,page:t})},[rg,X?.id]),rv=(0,i.useCallback)(e=>{let t=nA.find(t=>t.cwd===e),n=t??wH(e);t||nL(e=>[...e,n]),n$(n.id),tn(!0),I&&e7(!1)},[nA,I]),rb=(0,i.useCallback)((e,t,n)=>{nO(r=>r.some(t=>t.sessionId===e)?r:[...r,{sessionId:e,label:t,...n?{side:!0}:{}}]),n$(`agent:${e}`),tn(!0),I&&e7(!1)},[I]),ry=(0,i.useMemo)(()=>new Set(tt?nW.map(e=>e.sessionId):[]),[nW,tt]),rw=(0,i.useCallback)((e,t)=>{let n=e.relation?.kind==="side"?e.relation.parentSessionId:null;if(!n||n===nF.current)return rb(e.id,t,!0),!0;try{let r=w_(n);window.sessionStorage.setItem(r,function(e,t,n){let r=[];try{let t=JSON.parse(e??"null");Array.isArray(t?.tabs)&&(r=t.tabs)}catch{}return JSON.stringify({tabs:[...r,{sessionId:t,label:n,side:!0}],activeId:`agent:${t}`,open:!0})}(window.sessionStorage.getItem(r),e.id,t))}catch{}return!1},[rb]),rk=(0,i.useCallback)(e=>{let t=rX(e,et,$("agentSwitcher.sideChat")),n=t?et.find(e=>e.id===t.parentSessionId):void 0;t&&n&&(en(t=>t.some(t=>t.id===e.id)?t:[e,...t]),rw(e,t.label)||rn(n))},[rn,rw,et,$]),rj=(0,i.useCallback)((e,t)=>{t&&tC(n=>({...n,[e.id]:t})),en(t=>[e,...t.filter(t=>t.id!==e.id)]),rw(e,$("agentSwitcher.sideChat")),eO(e=>e+1)},[rw,$]),rS=(0,i.useCallback)(async e=>{let t=await cn(e,$);return"error"in t?t.error:(I&&nc(null),rj(t.session,null),null)},[rj,I,$]),rC=nW.filter(e=>e.side&&ea.has(e.sessionId)).map(e=>e.sessionId).join();(0,i.useEffect)(()=>{rC&&eO(e=>e+1)},[rC]);let rN=(0,i.useCallback)(e=>{if(nA.some(t=>t.id===e))return void nL(t=>t.map(t=>t.id!==e||t.closing?t:{...t,closing:"close"}));if(e.startsWith("agent:")){let t=nW.filter(t=>`agent:${t.sessionId}`!==e);nO(t),n$(n=>n!==e?n:nS.at(-1)?.id??nA.at(-1)?.id??w2(t)),0===nS.length&&0===nA.length&&0===t.length&&tn(!1);return}nC(t=>{let n=t.filter(t=>t.id!==e);return 0===n.length&&0===nA.length&&0===nW.length&&tn(!1),n}),n$(t=>{if(t!==e)return t;let n=nS.filter(t=>t.id!==e);return n.at(-1)?.id??nA.at(-1)?.id??w2(nW)})},[nS,nA,nW]),rE=(0,i.useCallback)(e=>{rm(e),rN(`agent:${e}`)},[rm,rN]),r$=(0,i.useCallback)(async(e,t)=>{let n=await cr(e);return n?n.error:(L(e),rN(`agent:${e}`),ee.current?.id===e?(rn(t),eO(e=>e+1)):rm(e),null)},[rN,rn,rm]),rI=X?.id;(0,i.useEffect)(()=>{nW.some(e=>e.sessionId===rI)&&rN(`agent:${rI}`)},[nW,rN,rI]);let rM=(0,i.useCallback)(()=>{X&&window.open(`/api/sessions/${encodeURIComponent(X.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[X]),rT=ev??(null===X&&nH?nH:null),rR=null===X&&rT?`new:${ey}:${rT}`:null;(0,i.useLayoutEffect)(()=>{ek.current=rR},[rR]);let rA=(0,i.useCallback)((e,t)=>{null===X&&rT&&e.cwd!==rT&&(e$.current=t,e.projectKey&&e.projectRoot&&eN.current?.cwd!==e.cwd&&(eN.current={cwd:e.cwd,project:{key:e.projectKey,root:e.projectRoot},branch:null}),ej.current?.startNewSessionIn({...e,carryComposer:!0}))},[rT,X]),rL=(0,i.useRef)(rA);rL.current=rA;let rz=(0,i.useCallback)(e=>{ej.current?.openFolderForNewSession(e=>rL.current(e,"project"),e)},[]),rP=(0,i.useCallback)(()=>{ej.current?.openDefaultDirectoryForNewSession(e=>rL.current(e,"project"))},[]),rW=(0,i.useCallback)(()=>{ej.current?.refreshWorktrees()},[]),rO=(0,i.useCallback)(async(e,t)=>{let n=ej.current;if(!n)throw Error("The session sidebar is not mounted");let r=await n.createWorktree(e,t);return"path"in r&&(eN.current={cwd:r.path,project:e,branch:t}),r},[]),rF=(0,i.useCallback)(()=>{e$.current=null},[]),rD=null===X&&rT?(0,r.jsx)(us,{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},l=s.alias??i.find(e=>e.key===s.key)?.alias;return{cwd:t,project:void 0===l?s:{...s,alias:l},worktrees:null,currentWorktreePath:null,projects:i}}(eS,rT,eN.current),mobile:I,initialFocus:e$.current,onInitialFocusDone:rF,onPick:rA,onUseDefaultDirectory:rP,onOpenFolder:rz,onRefreshWorktrees:rW,onCreateWorktree:rO}):null,rB=null!==X||null!==rT,rH=X?.cwd??rT,r_=n4&&!rB;(0,i.useEffect)(()=>{rB||nc(e=>"debug"===e?null:e)},[rB]),(0,i.useEffect)(()=>{if(e1(null),e4(!1),e6(null),!rH)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(rH)}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);e1(t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[rH]);let rU=(0,i.useCallback)(async()=>{if(rH&&!e8){e3(!0),e6(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:rH})}),t=await e.json();if(!e.ok||t.error)return void e6({error:t.error??`HTTP ${e.status}`,...t.reason?{reason:t.reason}:{}});e1(t),e4(!1),eQ(e=>e+1),eD(e=>e+1)}catch(e){e6({error:e instanceof Error?e.message:String(e)})}finally{e3(!1)}}},[e8,rH]),rK=(0,i.useCallback)(()=>{e6(null),e4(!0)},[]),rq=(0,i.useCallback)((e,t)=>{e===rH&&e1(t)},[rH]),rV=nS.find(e=>e.id===nE)??null,rZ=nW.find(e=>`agent:${e.sessionId}`===nE)??null,rJ=nH?nb(nH)||nH:null,rY=rJ?`${rJ} - Pi Web`:"Pi Web";(0,i.useEffect)(()=>{let e=()=>{document.title!==rY&&(document.title=rY)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[rY]);let rG=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(it,{selectedSessionId:X?.id??null,onSelectSession:rn,onSelectSideChat:rk,onNewSession:rr,controlRef:ej,onNewSessionContextChange:eE,initialSessionId:n1,initialSessionLinked:null!==n2,skipInitialProjectSelection:null!==C.requestedCwd,onInitialRestoreDone:rf,refreshKey:eW,onSessionDeleted:rm,selectedCwd:X?.cwd??ev??null,onCwdChange:rt,onOpenFile:rg,onOpenTerminal:rv,explorerRefreshKey:eq,onExplorerRefresh:rc,onAtMention:nX,onAtMentions:nQ,onBackgroundTaskDone:G,hiddenFinishedSessionIds:J,onRunningSessionIdsChange:ec,onSessionsChange:es}),(0,r.jsxs)("div",{style:{padding:"8px",flexShrink:0,display:"flex",justifyContent:"space-between",gap:4},children:[[["models",$("common.models")],["skills",$("common.skills")]].map(e=>{let[t,n]=e,i=u8(t)&&!rH;return(0,r.jsxs)("button",{type:"button",onClick:()=>nv(t),disabled:i,title:i?$("settings.projectRequired"):n,"aria-label":n,style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",gap:6,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:i?"default":"pointer",fontSize:12,opacity:i?.35:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)(bw,{section:t,size:14,strokeWidth:2}),(0,r.jsx)("span",{children:n})]},t)}),(0,r.jsxs)("button",{type:"button",onClick:()=>{eG(!0),eJ(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:u3();if(!t)return"general";try{let n=u5(t).section;if(!("string"==typeof n&&u1.includes(n)))return"general";return u8(n)&&!e?"general":n}catch{return"general"}}(rH))},title:$("common.settings"),"aria-label":$("common.settings"),style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",gap:6,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)(bw,{section:"general",size:14,strokeWidth:2}),(0,r.jsx)("span",{children:$("common.settings")})]})]})]}),rQ=e=>rB&&e0?.requiresTrust&&!e0.trusted?(0,r.jsxs)("button",{type:"button",onClick:rK,title:$("trust.resourcesNotLoaded"),"aria-label":$("trust.resourcesNotLoaded"),style:{display:"flex",alignItems:"center",justifyContent:e?"flex-start":"center",gap:6,width:e?"100%":void 0,minHeight:e?32:void 0,height:e?void 0:"100%",padding:e?"6px 12px":"0 12px",background:e?"color-mix(in srgb, #d97706 8%, var(--bg-panel))":"none",border:"none",borderRight:e?"none":"1px solid var(--border)",borderBottom:e?"1px solid var(--border)":"none",color:"#d97706",cursor:"pointer",flexShrink:0,fontSize:11,lineHeight:1.35,textAlign:"left"},"data-mobile-trust-banner":e?"true":void 0,children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"M12 8v4"}),(0,r.jsx)("path",{d:"M12 16h.01"})]}),(0,r.jsx)("span",{children:$("trust.resourcesNotLoaded")})]}):null,r0=e=>(0,r.jsxs)("button",{ref:eg,type:"button",onClick:()=>nh("agents",e&&!M),disabled:!eo,title:ep,"aria-label":ep,"aria-pressed":"agents"===nd,style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?w0:void 0,height:"100%",padding:e?0:"0 12px",background:"agents"===nd?"var(--bg-selected)":"none",border:"none",borderTop:"agents"===nd?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"agents"===nd?"var(--text)":eo?"var(--text-muted)":"var(--text-dim)",cursor:eo?"pointer":"not-allowed",opacity:eo?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:$("agentSwitcher.title")}),eu&&eu.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:eu.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:eu.running?600:void 0,...e?{position:"absolute",top:3,right:3,minWidth:13,height:13,padding:"0 3px",fontSize:9}:{}},children:[eu.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"})]}),eu.count]})]}),r1=e=>{let t,n,i,s,l,o;return e||rB?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",height:"100%"},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>{rM(),e&&M&&ta(!0)},disabled:!X,title:X?$("history.full"):$("history.unsaved"),"aria-label":$("history.full"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?w0:void 0,height:"100%",padding:e?0:"0 12px",background:"none",border:"none",borderTop:"2px solid transparent",borderRight:"1px solid var(--border)",color:X?"var(--text-muted)":"var(--text-dim)",cursor:X?"pointer":"not-allowed",opacity:X?1:.45,flexShrink:0,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s, opacity 0.1s"},onMouseEnter:e=>{X&&(e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{e.currentTarget.style.color=X?"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:X?"var(--text-muted)":"var(--text-dim)",flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]}),!e&&(0,r.jsx)("span",{children:$("history.label")})]}),(t=!!(X&&((t3?.userMessages??0)>0||X.messageCount>0)),n=!X||X.transient||!t||"naming"===t6.kind,i="success"===t6.kind,s="error"===t6.kind,l="naming"===t6.kind?$("title.generating"):i?$("title.updated"):s?$("title.failed"):$("title.generate"),o=!X||X.transient?$("title.unsaved"):t?s?t6.message:$("title.generateSession"):$("title.noMessages"),(0,r.jsxs)("button",{type:"button",onClick:()=>{rd(),e&&M&&ta(!0)},disabled:n,title:o,"aria-label":l,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?w0: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"!==t6.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"===t6.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:l})]})),!(e&&M)&&r0(e),tz&&(e?(0,r.jsx)("button",{type:"button",onClick:()=>nh("branches",!0),title:$("i18n.branches"),"aria-label":$("i18n.branches"),"aria-pressed":"branches"===nd,style:{display:"flex",alignItems:"center",justifyContent:"center",width:w0,height:"100%",padding:0,background:"branches"===nd?"var(--bg-selected)":"none",border:"none",borderTop:"branches"===nd?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"branches"===nd?"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:t$.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)(bD,{tree:t$,activeLeafId:tM,onLeafChange:tW,locked:tR,inline:!0,containerRef:tN,open:"branches"===nd,onToggle:()=>nh("branches"),hasSession:!0})),(0,r.jsxs)("button",{ref:tV,type:"button",onClick:()=>ng("system",e),disabled:e&&!rB,title:$("system.prompt"),"aria-label":$("system.prompt"),"aria-pressed":"system"===nd,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?w0:void 0,height:"100%",padding:e?0:"0 12px",background:"system"===nd?"var(--bg-selected)":"none",border:"none",borderTop:"system"===nd?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:e&&!rB?"not-allowed":"pointer",color:"system"===nd?"var(--text)":"var(--text-muted)",opacity:e&&!rB?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||rB)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="system"===nd?"var(--text)":"var(--text-muted)"},"data-mobile-toolbar-action":e?"system":void 0,children:[(0,r.jsxs)("svg",{width:e?16:12,height:e?16:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:tO?"var(--accent)":"var(--text-dim)",flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),(0,r.jsx)("polyline",{points:"14 2 14 8 20 8"}),(0,r.jsx)("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),(0,r.jsx)("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]}),!e&&(0,r.jsx)("span",{children:$("system.label")})]}),(0,r.jsxs)("button",{type:"button",onClick:()=>ng("tools",e),disabled:e&&!rB,title:$("tools.title"),"aria-label":$("tools.title"),"aria-pressed":"tools"===nd,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?w0:void 0,height:"100%",padding:e?0:"0 12px",background:"tools"===nd?"var(--bg-selected)":"none",border:"none",borderTop:"tools"===nd?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:e&&!rB?"not-allowed":"pointer",color:"tools"===nd?"var(--text)":"var(--text-muted)",opacity:e&&!rB?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||rB)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="tools"===nd?"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:tD?.some(e=>e.active)?"var(--accent)":"var(--text-dim)",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.8-3.8a6 6 0 0 1-7.9 7.9l-6.9 6.9a2.1 2.1 0 0 1-3-3l6.9-6.9a6 6 0 0 1 7.9-7.9z"})}),!e&&(0,r.jsx)("span",{children:$("tools.label")})]})]}):null},r2=e=>{if(!e&&(!rB||!t3&&!nl))return null;let t=t3?.tokens,n=t3?.cost??0,i=cg(n),s="var(--text-muted)",l=null,o=null;if(nl?.contextWindow){let e=nl.percent;null!==e&&e>90?s="#ef4444":null!==e&&e>70&&(s="rgba(234,179,8,0.95)"),l=null!==e?`${e.toFixed(0)}% / ${cm(nl.contextWindow)}`:`? / ${cm(nl.contextWindow)}`,o=null!==e?`${e.toFixed(0)}%`:null}let a=[];if(t&&(a.push(`${$("session.input")}: ${t.input.toLocaleString(E)}`),a.push(`${$("session.output")}: ${t.output.toLocaleString(E)}`),a.push(`${$("session.cacheRead")}: ${t.cacheRead.toLocaleString(E)}`),a.push(`${$("session.cacheWrite")}: ${t.cacheWrite.toLocaleString(E)}`),n>0&&a.push(`${$("session.cost")}: $${n.toFixed(4)}`)),nl?.contextWindow){let e=nl.percent;a.push(`${$("session.context")}: ${null!==e?`${e.toFixed(1)}%`:"?"} / ${nl.contextWindow.toLocaleString(E)}`)}let d=a.join(" | "),c=e&&M&&tl,u=!!(t&&(t.input>0||t.output>0)||i||o);return(0,r.jsx)("button",{type:"button",onClick:()=>nh("session"),disabled:!rB||c,tabIndex:c?-1:void 0,title:d||$("session.title"),"aria-label":$("session.title"),"aria-pressed":"session"===nd,"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"===nd?"var(--bg-selected)":"none",border:"none",borderTop:"session"===nd?"2px solid var(--accent)":"2px solid transparent",fontSize:11,color:"var(--text-muted)",whiteSpace:"nowrap",cursor:rB?"pointer":"default",fontVariantNumeric:"tabular-nums",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{rB&&!c&&(e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="session"===nd?"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"})]}),cm(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"})]}),cm(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&&rB&&(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",color:"var(--text-dim)"},children:$("session.title")})]}):(0,r.jsxs)(r.Fragment,{children:[t&&t.input>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"8.5",x2:"5",y2:"1.5"}),(0,r.jsx)("polyline",{points:"2 4 5 1.5 8 4"})]}),cm(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"})]}),cm(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"})]}),cm(t.cacheRead)]}),i&&(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",color:"var(--text)",fontWeight:500},children:i}),l&&(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"})]}),l]})]})})},r4=e=>{if(!rB)return null;let t="debug"===nd;return(0,r.jsx)("button",{ref:nf,type:"button",onClick:()=>nh("debug",e),title:$("debug.title"),"aria-label":$("debug.title"),"aria-pressed":t,style:{marginLeft:e?0:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:w0,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"})]})})},r8=e=>{let t=e&&M&&tl;return(0,r.jsx)("button",{type:"button",onClick:nk,disabled:t,tabIndex:t?-1:void 0,"aria-controls":"file-panel","aria-expanded":tt,"aria-hidden":!!t||void 0,title:tt?$("files.hidePanel"):$("files.showPanel"),"aria-label":tt?$("files.hidePanel"):$("files.showPanel"),"data-mobile-toolbar-file":e?"true":void 0,style:{marginLeft:e||rB?0:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:w0,height:w0,padding:0,visibility:t?"hidden":"visible",pointerEvents:t?"none":"auto",background:tt?"var(--bg-selected)":"none",border:"none",borderLeft:"1px solid var(--border)",color:tt?"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=tt?"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:`
1070
+ @keyframes session-info-pop {
1071
+ 0% {
1072
+ opacity: 0;
1073
+ transform: translateY(-24px);
1074
+ filter: blur(6px);
1075
+ box-shadow: 0 2px 8px rgba(0,0,0,0);
1076
+ }
1077
+ 55% {
1078
+ opacity: 1;
1079
+ transform: translateY(0);
1080
+ filter: blur(0);
1081
+ background: color-mix(in srgb, var(--accent) 8%, var(--bg-panel));
1082
+ box-shadow: 0 18px 44px rgba(37,99,235,0.16);
1083
+ }
1084
+ 100% {
1085
+ opacity: 1;
1086
+ transform: translateY(0);
1087
+ filter: blur(0);
1088
+ background: var(--bg-panel);
1089
+ box-shadow: 0 10px 28px rgba(0,0,0,0.10);
1090
+ }
1091
+ }
1092
+ @keyframes session-info-light-wash {
1093
+ 0% {
1094
+ opacity: 0;
1095
+ transform: translateX(-110%) skewX(-16deg);
1096
+ }
1097
+ 24% {
1098
+ opacity: 0.42;
1099
+ }
1100
+ 100% {
1101
+ opacity: 0;
1102
+ transform: translateX(115%) skewX(-16deg);
1103
+ }
1104
+ }
1105
+ .session-info-popover {
1106
+ position: relative;
1107
+ overflow: hidden;
1108
+ transform-origin: top right;
1109
+ animation: session-info-pop 360ms ease-out both;
1110
+ will-change: transform, opacity, filter, background, box-shadow;
1111
+ }
1112
+ .session-info-popover::after {
1113
+ content: "";
1114
+ position: absolute;
1115
+ top: 0;
1116
+ bottom: 0;
1117
+ left: 0;
1118
+ width: 44%;
1119
+ pointer-events: none;
1120
+ background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--accent) 24%, transparent), transparent);
1121
+ animation: session-info-light-wash 620ms ease-out both;
1122
+ }
1123
+ @media (prefers-reduced-motion: reduce) {
1124
+ .session-info-popover,
1125
+ .session-info-popover::after {
1126
+ animation: none;
1127
+ }
1128
+ }
1129
+ .mobile-session-stats {
1130
+ container-type: inline-size;
1131
+ }
1132
+ @container (max-width: 158px) {
1133
+ .mobile-session-stat-io {
1134
+ display: none !important;
1135
+ }
1136
+ }
1137
+ @container (max-width: 88px) {
1138
+ .mobile-session-stat-cost {
1139
+ display: none !important;
1140
+ }
1141
+ }
1142
+ @media (max-width: 640px) {
1143
+ .sidebar-overlay-backdrop.sidebar-mobile-pending {
1144
+ opacity: 0 !important;
1145
+ pointer-events: none !important;
1146
+ }
1147
+ .sidebar-container.sidebar-mobile-pending.sidebar-open {
1148
+ transform: translateX(calc(-100% - env(safe-area-inset-left)));
1149
+ box-shadow: none;
1150
+ }
1151
+ }
1152
+ `}),(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${tc?"":" sidebar-mobile-pending"}`,onClick:()=>e7(!1),style:{position:"fixed",inset:0,zIndex:199,background:"rgba(0,0,0,0.4)",opacity:+!!e9,pointerEvents:e9?"auto":"none",transition:"opacity 0.25s ease"}}),(0,r.jsx)("div",{ref:tb.panelRef,id:"session-sidebar",inert:ts,className:`sidebar-container${e9?" sidebar-open":" sidebar-closed"}${tc?"":" sidebar-mobile-pending"}${tb.isResizing?" sidebar-resizing":""}`,style:{"--sidebar-width":`${tb.width}px`,background:"var(--bg-panel)",borderRight:"1px solid var(--border)",display:"flex",flexDirection:"column",flexShrink:0,paddingTop:"env(safe-area-inset-top)",paddingBottom:"env(safe-area-inset-bottom)",zIndex:200},children:rG}),e9&&(0,r.jsx)("div",{...tb.separatorProps,inert:ts,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${tb.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${$("layout.resizeSidebar")}: ${$("layout.resizeHint")}`}),(0,r.jsxs)("div",{inert:ts,style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:[(0,r.jsxs)("div",{ref:tN,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:ny,title:e9?$("sidebar.hide"):$("sidebar.show"),"aria-label":e9?$("sidebar.hide"):$("sidebar.show"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:w0,height:w0,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:e9?(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"})]})}),I&&(0,r.jsxs)("div",{ref:tE,"data-mobile-toolbar":"true",style:{position:"relative",display:"flex",alignItems:"stretch",flex:1,minWidth:0,height:"100%"},children:[M&&r0(!0),M&&(0,r.jsx)("button",{type:"button",onClick:nw,title:td,"aria-label":td,"aria-controls":"mobile-toolbar-actions","aria-expanded":tl,"data-mobile-toolbar-more":"true",style:{position:"relative",zIndex:tl?21:void 0,display:"flex",alignItems:"center",justifyContent:"center",width:w0,height:w0,padding:0,background:tl?"var(--bg-selected)":"none",border:"none",borderRight:"1px solid var(--border)",color:tl?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s, background 0.12s"},children:tl?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"5",x2:"19",y2:"19"}),(0,r.jsx)("line",{x1:"19",y1:"5",x2:"5",y2:"19"})]}):(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"5",cy:"12",r:"1.5"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1.5"}),(0,r.jsx)("circle",{cx:"19",cy:"12",r:"1.5"})]})}),!M&&r1(!0),!M&&r4(!0),r2(!0),r8(!0),M&&tl&&(0,r.jsxs)("div",{id:"mobile-toolbar-actions",role:"toolbar","aria-label":$("chat.moreControls"),"data-mobile-toolbar-actions":"true",style:{position:"absolute",top:0,right:0,bottom:0,left:`calc(2 * ${w0})`,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:[r1(!0),r4(!0)]})]}),!I&&(0,r.jsxs)(r.Fragment,{children:[rQ(!1),r1(!1),r4(!1),r2(!1)]}),!I&&r8(!1),I&&tz&&(0,r.jsx)(bD,{tree:t$,activeLeafId:tM,onLeafChange:tW,locked:tR,inline:!0,compact:!0,containerRef:tN,open:"branches"===nd,onToggle:()=>nh("branches"),hasSession:rB,hideInlineButton:!0}),nd&&nu&&(0,r.jsxs)("div",{style:{position:"fixed",top:nu.top,left:nu.left,width:nu.width,maxHeight:`calc(100dvh - ${nu.top}px)`,overflowY:"auto",zIndex:500},children:["agents"===nd&&eo&&X&&(0,r.jsx)(b1,{rootSession:eo.root,subagents:eo.subagents,selectedSessionId:X.id,runningSessionIds:ea,onSelectSession:e=>{nc(null),rn(e),requestAnimationFrame(()=>to(document,eg.current))},openSubagentTabIds:ry,onToggleSubagentTab:(e,t,n)=>{ry.has(e)?rN(`agent:${e}`):(I&&nc(null),rb(e,t,n))},onNewSideChat:()=>rS(eo.root.id),onDeleteSideChat:e=>r$(e,eo.root)}),"system"===nd&&(0,r.jsx)(bB,{loading:tH,prompt:tO,translate:$}),"tools"===nd&&(0,r.jsx)(bU,{loading:tH,tools:tD,translate:$}),"session"===nd&&(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:t3?(n=t3.totalActiveMs??0,d=[...t3.sessionName?[{label:$("session.name"),value:t3.sessionName,copyField:null}]:[],{label:$("session.file"),value:t3.sessionFile??$("session.inMemory"),copyField:"file"},{label:$("session.id"),value:t3.sessionId,copyField:"id"},...n>0?[{label:$("session.totalActive"),value:cx(n),copyField:null}]:[]],p=[...X?[{label:$("session.projectDir"),value:X.projectRoot??X.cwd,copyField:"projectDir"}]:[],...X?.branch?[{label:$("session.gitBranch"),value:X.branch,copyField:"gitBranch"}]:[],...X?.isWorktree?[{label:$("session.gitWorktree"),value:X.cwd,copyField:"gitWorktree"}]:[]],h=[[$("session.user"),t3.userMessages.toLocaleString(E)],[$("session.assistant"),t3.assistantMessages.toLocaleString(E)],[$("session.toolCalls"),t3.toolCalls.toLocaleString(E)],[$("session.toolResults"),t3.toolResults.toLocaleString(E)],[$("session.total"),t3.totalMessages.toLocaleString(E)]],f=[[$("session.input"),t3.tokens.input.toLocaleString(E)],[$("session.output"),t3.tokens.output.toLocaleString(E)],...t3.tokens.cacheRead>0?[[$("session.cacheRead"),t3.tokens.cacheRead.toLocaleString(E)]]:[],...t3.tokens.cacheWrite>0?[[$("session.cacheWrite"),t3.tokens.cacheWrite.toLocaleString(E)]]:[],[$("session.total"),t3.tokens.total.toLocaleString(E)]],g=nl??t3.contextUsage,x=[...t3.cost>0?[[$("session.cost"),`$${t3.cost.toFixed(4)}`]]:[],...g?.contextWindow?[[$("session.context"),`${null!==g.percent?`${g.percent.toFixed(1)}%`:"?"} / ${cm(g.contextWindow)}`]]:[],...t3.tokens.cacheRead+t3.tokens.cacheWrite>0&&t3.tokens.cacheRead+t3.tokens.cacheWrite+t3.tokens.input>0?[[$("session.cacheHitRate"),`${(t3.tokens.cacheRead/(t3.tokens.cacheRead+t3.tokens.cacheWrite+t3.tokens.input)*100).toFixed(1)}%`]]:[]],v=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,l]=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:l})]},`${e}:${s}`)})})]})},b={file:"session.copyFile",id:"session.copyId",projectDir:"session.copyProjectDir",gitBranch:"session.copyGitBranch",gitWorktree:"session.copyGitWorktree"},y=(e,t)=>{let n=nn===e;return(0,r.jsx)("button",{type:"button",title:n?$("session.copied"):$(b[e]),onClick:()=>ns(e,t),style:{alignSelf:"start",display:"inline-flex",alignItems:"center",justifyContent:"center",width:22,height:22,marginTop:-2,color:n?"var(--accent)":"var(--text-dim)",background:"transparent",border:"1px solid var(--border)",borderRadius:4,cursor:"pointer",flex:"0 0 auto",transition:"color 0.12s, border-color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color=n?"var(--accent)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="transparent"},children:n?(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})},w=(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:$("session.infoSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:d.map(e=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,r.jsx)("div",{children:e.copyField?y(e.copyField,e.value):null})]},`session-info:${e.label}`))})]}),k=p.length>0?(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:$("session.projectSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:p.map(e=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,r.jsx)("div",{children:e.copyField?y(e.copyField,e.value):null})]},`project-info:${e.label}`))})]}):null,(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:I?"1fr":"minmax(360px, 1.7fr) minmax(140px, 0.55fr) minmax(190px, 0.75fr)",gap:I?16:24,fontSize:12,lineHeight:1.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:I?16:20},children:[w,k]}),v($("session.messages"),h),v($("session.tokens"),[...f,...x],"right",!0)]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:$("session.load")})}),"debug"===nd&&(0,r.jsx)(yz,{fallback:$("debug.failed"),children:(0,r.jsx)(yP,{readerRef:t4,selectedSessionId:X?.id??null,sessions:el,onClose:nm})})]})]}),em&&eo&&X&&"agents"!==nd&&(0,r.jsx)(b4,{rootSession:eo.root,members:em,selectedSessionId:X.id,runningSessionIds:ea,onSelectSession:rn,locked:eh,onToggleLock:ex}),I&&rQ(!0)]}),(0,r.jsx)("div",{style:{flex:1,overflow:"hidden",position:"relative"},children:rB?(0,r.jsx)(c3,{session:X,searchTarget:e_?.sessionId===X?.id?e_:null,onSearchTargetHandled:eK,initialScrollPosition:X?eB.current.get(X.id)??null:null,onScrollPositionChange:eH,sessionRunning:!!(X&&ea.has(X.id)),newSessionCwd:rT,newSessionDraftKey:rR,newSessionContextBar:rD,initialNewSessionChoices:null===X?eM:null,onNewSessionChoicesChange:eR,onAgentEnd:ro,onSessionEnded:rE,onToolEnd:rp,onAttentionNeeded:ra,onSessionCreated:rs,onSessionForked:rh,onSideSession:rj,modelsRefreshKey:eX,chatInputRef:tj,onBranchDataChange:tP,onSystemPromptChange:tZ,onSystemToolsChange:tJ,onSystemInfoLoaderChange:t1,onDebugSnapshotReaderChange:t8,onSessionStatsChange:nt,onSessionStatsPanelOpen:nx,onOpenSettings:nv,onContextUsageChange:na,onOpenFile:rx,onFilesUploaded:rc,onOpenSubagent:rb,quoteSelectionEnabled:K,soundEnabled:T,onSoundToggle:A,playDoneSound:z,unlockAudio:P,holdAudio:W},eF):"validating"===eA?(0,r.jsxs)("div",{role:"status",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"var(--text)"},children:$("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:C.requestedCwd})]}):"error"===eA?(0,r.jsxs)("div",{role:"alert",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"#dc2626"},children:$("workspace.unable")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:C.requestedCwd}),(0,r.jsx)("div",{style:{maxWidth:720,fontSize:12},children:ez})]}):r_?nH?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:$("workspace.selectSession")}):(0,r.jsxs)("div",{style:{position:"absolute",top:12,left:12,display:"flex",alignItems:"flex-start",gap:8,userSelect:"none",pointerEvents:"none"},children:[(0,r.jsxs)("svg",{width:"44",height:"44",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",style:{opacity:.7,flexShrink:0},children:[(0,r.jsx)("line",{x1:"20",y1:"12",x2:"4",y2:"12"}),(0,r.jsx)("polyline",{points:"10 6 4 12 10 18"})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:18,fontWeight:600,color:"var(--text)",marginBottom:8},children:$("workspace.getStarted")}),(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.8},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"1."}),$("workspace.selectProject"),(0,r.jsx)("br",{}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),$("workspace.addModels")]})]})]}):null})]}),(0,r.jsx)("div",{"aria-hidden":"true",className:`right-panel-overlay-backdrop${tt?" is-open":""}`,onClick:()=>tn(!1)}),tt&&(0,r.jsx)("div",{...ty.separatorProps,inert:ts,"aria-controls":"file-panel",className:`panel-resize-handle right-panel-resize-handle${ty.isResizing?" is-resizing":""}`,"data-resize-handle":"right-panel",title:`${$("layout.resizeFilePanel")}: ${$("layout.resizeHint")}`}),(0,r.jsxs)("div",{ref:ty.panelRef,id:"file-panel",className:`right-panel-container${tt?" right-panel-open":" right-panel-closed"}${ts?" right-panel-full-width":""}${ty.isResizing?" right-panel-resizing":""}`,style:{"--right-panel-width":`${ty.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)(uQ,{tabs:nV,activeTabId:nE??"",onSelectTab:n$,onCloseTab:rN,onReorderTab:(e,t,n)=>nq(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}(nV.map(e=>e.id),e,t,n))})}),(0,r.jsx)("button",{type:"button",className:"file-panel-expand-button",onClick:nj,"aria-controls":"file-panel","aria-pressed":ts,title:$(ts?"files.restorePanelWidth":"files.expandPanel"),"aria-label":$(ts?"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:ts?"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:()=>tn(!1),"aria-controls":"file-panel","aria-expanded":tt,title:$("files.hidePanel"),"aria-label":$("files.hidePanel"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:w0,height:w0,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:[rV?.filePath?(0,r.jsx)(uY,{filePath:rV.filePath,cwd:nH??void 0,sourceSessionId:rV.sourceSessionId,gitRefreshKey:eq,initialDisplayMode:rV.initialDisplayMode,initialPage:rV.page,initialState:rV.viewerState,watchEnabled:tt,onStateChange:e=>nY(nM,rV.id,rV.viewerRevision??0,e),onMentionLines:tt?n0:void 0,onAtMention:nX,onOpenFile:(e,t)=>rg(e,nb(e),{sourceSessionId:rV.sourceSessionId,page:t})},`${nM}:${rV.id}:${rV.viewerRevision??0}`):nA.some(e=>e.id===nE)||rZ?null:(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12},children:$("files.noneOpen")}),nA.map(e=>(0,r.jsx)("div",{hidden:e.id!==nE,style:{width:"100%",height:"100%"},children:(0,r.jsx)(wD,{tab:e,active:tt&&e.id===nE,onRestart:()=>nL(t=>t.map(t=>t.id===e.id?{...t,closing:"restart"}:t)),onClosed:()=>{let t,n;return t="restart"===e.closing?wH(e.cwd):null,n=nA.filter(t=>t.id!==e.id),void(nL(n=>n.flatMap(n=>n.id!==e.id?[n]:t?[t]:[])),n$(r=>r!==e.id?r:t?.id??n.at(-1)?.id??nS.at(-1)?.id??w2(nW)),!t&&!n.length&&!nS.length&&!nW.length&&tn(!1))},onCloseError:()=>nL(t=>t.map(t=>t.id===e.id?{...t,closing:void 0}:t))})},e.id)),rZ&&(0,r.jsx)(wh,{sessionId:rZ.sessionId,onSessionEnded:rE,running:ea.has(rZ.sessionId),initialPrompt:tS[rZ.sessionId],onInitialPromptConsumed:()=>tC(e=>{if(!(rZ.sessionId in e))return e;let t={...e};return delete t[rZ.sessionId],t}),modelsRefreshKey:eX,quoteSelectionEnabled:K,onOpenFile:rx,onOpenSubagent:rb,onSessionForked:(e,t)=>{I&&tn(!1),rh(e,t)},onOpenSettings:nv,onToolEnd:rp,onFilesUploaded:rc,soundEnabled:T,onSoundToggle:A,playDoneSound:z,unlockAudio:P,holdAudio:W},rZ.sessionId)]})]})]}),eZ&&(0,r.jsx)(bN,{cwd:rH,sessionId:X?.id??null,initialSection:eZ,openAtHome:eY,quoteSelectionEnabled:K,onQuoteSelectionChange:V,onClose:()=>{eJ(null),eQ(e=>e+1)},onSessionReloaded:()=>eD(e=>e+1),projectTrust:e0,onOpenTrustDialog:rK,onProjectTrustChanged:rq}),e2&&rH&&(0,r.jsx)(b$,{cwd:rH,busy:e8,error:e5,onCancel:()=>{e8||e4(!1)},onConfirm:()=>void rU(),onStatus:e1})]})}},88576:e=>{e.exports={preview:"ChatMinimap_preview__laAya",earlier:"ChatMinimap_earlier__IxOXN",turn:"ChatMinimap_turn__fZuce",number:"ChatMinimap_number__3C_cY",toolBadge:"ChatMinimap_toolBadge__fzFQn",content:"ChatMinimap_content__C7_ju",user:"ChatMinimap_user__WHJHv",userText:"ChatMinimap_userText__Nj9jo",assistant:"ChatMinimap_assistant__s6JLb",assistantJump:"ChatMinimap_assistantJump__3CM2M",outline:"ChatMinimap_outline__aleIF",heading:"ChatMinimap_heading__djZbv",paragraph:"ChatMinimap_paragraph__EqWlO",lock:"ChatMinimap_lock__9WDY5"}}},e=>{e.O(0,[1177,7330,3888,5772,4908,1278,8441,3794,7358],()=>e(e.s=42927)),_N_E=e.O()}]);