@pricening/pi-web 0.10.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +11 -11
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/required-server-files.js +1 -1
  6. package/.next/required-server-files.json +1 -1
  7. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  8. package/.next/server/app/_global-error.html +1 -1
  9. package/.next/server/app/_global-error.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  13. package/.next/server/app/_not-found/page.js +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 +4 -4
  17. package/.next/server/app/_not-found.segments/_full.segment.rsc +4 -4
  18. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +4 -4
  19. package/.next/server/app/_not-found.segments/_tree.segment.rsc +3 -3
  20. package/.next/server/app/api/app-update/route.js +1 -1
  21. package/.next/server/app/api/files/[...path]/route.js +2 -2
  22. package/.next/server/app/api/git/diff/route.js +1 -1
  23. package/.next/server/app/api/subagents/profiles/route.js +1 -1
  24. package/.next/server/app/index.html +1 -1
  25. package/.next/server/app/index.rsc +6 -6
  26. package/.next/server/app/index.segments/__PAGE__.segment.rsc +6 -6
  27. package/.next/server/app/index.segments/_full.segment.rsc +6 -6
  28. package/.next/server/app/index.segments/_tree.segment.rsc +3 -3
  29. package/.next/server/app/login/page_client-reference-manifest.js +1 -1
  30. package/.next/server/app/login.html +1 -1
  31. package/.next/server/app/login.rsc +5 -5
  32. package/.next/server/app/login.segments/_full.segment.rsc +5 -5
  33. package/.next/server/app/login.segments/_tree.segment.rsc +3 -3
  34. package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +5 -5
  35. package/.next/server/app/page.js +21 -21
  36. package/.next/server/app/page_client-reference-manifest.js +1 -1
  37. package/.next/server/app-paths-manifest.json +11 -11
  38. package/.next/server/chunks/2243.js +1 -1
  39. package/.next/server/chunks/3573.js +1 -1
  40. package/.next/server/chunks/4815.js +1 -1
  41. package/.next/server/chunks/5582.js +4 -4
  42. package/.next/server/chunks/6429.js +15 -4
  43. package/.next/server/middleware-build-manifest.js +1 -1
  44. package/.next/server/pages/404.html +1 -1
  45. package/.next/server/pages/500.html +1 -1
  46. package/.next/server/server-reference-manifest.json +1 -1
  47. package/.next/static/chunks/1278-6ef40c1ca1107675.js +1 -0
  48. package/.next/static/chunks/app/{layout-4fd82463c6a6ce72.js → layout-a64273ce41b09cd9.js} +1 -1
  49. package/.next/static/chunks/app/page-55162cf6bcd5684e.js +284 -0
  50. package/.next/static/css/68dcfd9f73879adb.css +1 -0
  51. package/.next/static/css/{88714c00e109ce28.css → 9bcd6051db4f8890.css} +1 -1
  52. package/.next/trace +86 -86
  53. package/.next/trace-build +1 -1
  54. package/package.json +2 -2
  55. package/.next/static/chunks/1278-ac53b38d14f1e9e0.js +0 -1
  56. package/.next/static/chunks/app/page-2e7b8599b69a38be.js +0 -284
  57. package/.next/static/css/e8f3928dc00ee301.css +0 -1
  58. /package/.next/static/{jEYPBQZndLddtRZ1pDURx → IacmWhIrPnlXerbcRBDZ5}/_buildManifest.js +0 -0
  59. /package/.next/static/{jEYPBQZndLddtRZ1pDURx → IacmWhIrPnlXerbcRBDZ5}/_ssgManifest.js +0 -0
@@ -1,284 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{14755:(e,t,n)=>{"use strict";n.d(t,{Q8:()=>r,YO:()=>p,getPresetFromTools:()=>u,sn:()=>c,xG:()=>h});let r="configured",i=["configured","none","read-only","default","full"],o=[],s=["read","grep","find","ls"],l=["read","bash","edit","write"],a=["bash","read","edit","write","grep","find","ls"],d=new Set([...a,"powershell"]);function c(e){return"string"==typeof e&&i.includes(e)}function u(e){return p(e.filter(e=>e.active).map(e=>e.name))}function p(e){if(0===e.length)return"none";let t=e.map(e=>"powershell"===e?"bash":e).filter(e=>d.has(e)).sort().join(",");return t===[...s].sort().join(",")?"read-only":t===[...l].sort().join(",")?"default":t===[...a].sort().join(",")?"full":"default"}function h(e){if(e!==r)return"none"===e?[...o]:"read-only"===e?[...s]:"full"===e?[...a]:[...l]}},42927:(e,t,n)=>{Promise.resolve().then(n.bind(n,97873)),Promise.resolve().then(n.bind(n,21278))},88576:e=>{e.exports={preview:"ChatMinimap_preview__laAya",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"}},97873:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>hh});var r=n(95155),i=n(12115),o=n(73321);let s=null;function l(){return{sessions:new Set,projects:new Set}}function a(e){return{sessions:new Set(e.sessions),projects:new Set(e.projects)}}function d(e){return e&&"object"==typeof e?{sessions:c(e.sessions),projects:c(e.projects)}:{sessions:[],projects:[]}}function c(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){if("string"!=typeof n)continue;let e=n.trim();e&&t.add(e)}return[...t].sort()}function u(e,t){return!p(e.sessions,t.sessions)||!p(e.projects,t.projects)}function p(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function h(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,o=r.id,s=null;for(;;){if(n.has(o)){s=n.get(o)??null;break}if(i.has(o))break;i.add(o),e.push(o);let r=t.get(o);if(!r)break;if(r.relation?.kind!=="subagent"){s=r.id;break}o=r.relation.parentSessionId}for(let t of e)n.set(t,s)}return n}(e),r=new Map;for(let t of e)t.relation?.kind!=="subagent"&&r.set(t.id,{root:t,subagents:[],latestModified:t.modified});for(let t of e){if(t.relation?.kind!=="subagent")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),(!!t?.has(n.root.id)===r?0:r?-1:1)||n.latestModified.localeCompare(e.latestModified)})}let f="pi-web:file-explorer:open";function m(){try{return window.localStorage}catch{return null}}let g=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function x(e){let t=e.match(g);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}let v="pi-web:last-open-by-workspace";function b(){try{return window.localStorage}catch{return null}}function y(e){let t=e.getItem(v);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function j(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:b();if(t)try{let n=y(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(v):t.setItem(v,JSON.stringify(n))}catch{}}function k(e){return e.projectKey??e.projectRoot??e.cwd}function w(e,t,n){let r=new Map;for(let t of e){let e=t.projectRoot??t.cwd;if(!e)continue;let i=k(t);if(n?.has(i))continue;let o=r.get(i);(!o||t.modified>o.modified)&&r.set(i,{root:e,modified:t.modified})}return[...r.entries()].sort((e,n)=>{var r;return r=!!t?.has(e[0]),(!!t?.has(n[0])===r?0:r?-1:1)||n[1].modified.localeCompare(e[1].modified)}).map(e=>{let[t,{root:n}]=e;return{key:t,root:n}})}function S(e,t){return e.filter(e=>k(e)===t)}var C=n(2730),E=n(21278);function N(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 I(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function $(e){let{ariaLabel:t,axis:n="horizontal",cssVariable:r,defaultWidth:o,getDefaultWidth:s,getMaxWidth:l,growthDirection:a,maxWidth:d,minWidth:c,storageKey:u,widthRef:p}=e,h=(0,i.useRef)(null),f=(0,i.useRef)(null),m=(0,i.useRef)(!1),[g,x]=(0,i.useState)(o),[v,b]=(0,i.useState)(!1),[y,j]=(0,i.useState)(!1);(0,i.useEffect)(()=>{j(!0)},[]);let k=(0,i.useCallback)(()=>Math.min(d,Math.max(c,l())),[l,d,c]),w=(0,i.useCallback)(e=>N(e,c,k()),[k,c]),S=(0,i.useCallback)(e=>{p.current=e,h.current?.style.setProperty(r,`${e}px`)},[r,p]),C=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{forcePersist:n=!1,persist:r=!0}=t,i=w(e),o=i!==p.current;return S(i),x(i),r&&(o||n)&&I(u,i),i},[S,w,u,p]),E=(0,i.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),$=(0,i.useCallback)(e=>{let t=f.current;if(t&&t.pointerId===e){f.current=null,E(t),b(!1),C(p.current,{forcePersist:!0});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[C,E,p]),T=(0,i.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=f.current;t&&$(t.pointerId);let r=e.currentTarget;r.focus({preventScroll:!0}),r.setPointerCapture(e.pointerId),f.current={pointerId:e.pointerId,startPosition:"vertical"===n?e.clientY:e.clientX,startWidth:p.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",b(!0)},[n,$,p]),M=(0,i.useCallback)(e=>{let t=f.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void $(e.pointerId);e.preventDefault();let r="right"===a||"down"===a?1:-1,i="vertical"===n?e.clientY:e.clientX,o=w(t.startWidth+(i-t.startPosition)*r);S(o),e.currentTarget.setAttribute("aria-valuenow",String(o)),e.currentTarget.setAttribute("aria-valuetext",`${o} px`)},[S,n,w,$,a]),R=(0,i.useCallback)(e=>{$(e.pointerId)},[$]),L=(0,i.useCallback)(e=>{$(e.pointerId)},[$]),z=(0,i.useCallback)(e=>{$(e.pointerId)},[$]),A=(0,i.useCallback)(()=>{C(s?.()??o,{forcePersist:!0})},[C,o,s]),W=(0,i.useCallback)(()=>{C(p.current)},[C,p]),P=(0,i.useCallback)(e=>{let t=e.shiftKey?32:12,r="right"===a||"down"===a,i="vertical"===n?"ArrowDown":"ArrowRight",o="vertical"===n?"ArrowUp":"ArrowLeft";e.key===(r?i:o)?(e.preventDefault(),C(p.current+t,{forcePersist:!0})):e.key===(r?o:i)?(e.preventDefault(),C(p.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),C(c,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),C(k(),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),A())},[n,C,k,a,c,A,p]);return(0,i.useEffect)(()=>{if(m.current)return;m.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}}(u),t=C(e??s?.()??o,{persist:!1});null!==e&&e!==t&&I(u,t)},[C,o,s,u]),(0,i.useEffect)(()=>{if(!m.current)return;C(p.current);let e=()=>{C(p.current)};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[C,p]),(0,i.useEffect)(()=>{if(!v)return;let e=()=>{let e=f.current;e&&$(e.pointerId)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[$,v]),(0,i.useEffect)(()=>()=>{let e=f.current;e&&(f.current=null,E(e))},[E]),{isResizing:v,panelRef:h,reclampWidth:W,resetWidth:A,separatorProps:{"aria-label":t,"aria-orientation":"vertical"===n?"horizontal":"vertical","aria-valuemax":y?k():d,"aria-valuemin":c,"aria-valuenow":g,"aria-valuetext":`${g} px`,onDoubleClick:A,onKeyDown:P,onLostPointerCapture:z,onPointerCancel:L,onPointerDown:T,onPointerMove:M,onPointerUp:R,role:"separator",tabIndex:0},width:g}}function T(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,o=null,s=()=>{null!==o&&(clearTimeout(o),o=null)},l=()=>{n&&(s(),n.classList.add("scrollbar-visible"))},a=()=>{n&&(s(),o=setTimeout(()=>{o=null,n?.classList.remove("scrollbar-visible")},500))},d=()=>{l(),a()},c=()=>{if(!i){if(!(n=e.current)){r=requestAnimationFrame(c);return}n.addEventListener("pointerenter",l),n.addEventListener("pointerleave",a),n.addEventListener("scroll",d)}};return c(),()=>{i=!0,null!==r&&cancelAnimationFrame(r),n?.removeEventListener("pointerenter",l),n?.removeEventListener("pointerleave",a),n?.removeEventListener("scroll",d),s(),n?.classList.remove("scrollbar-visible")}},[t,e])}var M=n(47650);let R={overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},L={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},z={padding:"6px 16px",borderRadius:6,fontSize:13},A={...z,border:0,background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600},W={...z,border:"1px solid var(--border)",background:"none",color:"var(--text-muted)"};async function P(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 O(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 F(){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 B(){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 D(e){let{onCancel:t,onSelect:n,initialPath:o,busy:s=!1,error:l}=e,{t:a}=(0,E.s)(),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(""),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(o??""),[x,v]=(0,i.useState)([]),[b,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(null),[w,S]=(0,i.useState)(!0),[C,N]=(0,i.useState)(!1),[I,$]=(0,i.useState)(""),[T,z]=(0,i.useState)(null),[D,H]=(0,i.useState)(!1),_=(0,i.useCallback)(async e=>{S(!0),k(null);try{let t=await P(e),n=t.path??e??"/";p(n),f(t.parentPath??null),g(n),v(t.directories??[]),y(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{c(document.body),_(o||void 0)},[o,_]);let U=()=>{D||(N(!1),$(""),z(null))},q=async()=>{let e=I.trim();if(u&&e&&!D){H(!0),z(null);try{let t=await O(u,e);N(!1),$(""),await _(t)}catch(e){z(e instanceof Error?e.message:String(e))}finally{H(!1)}}},Z=m.trim()!==u,K=!!u&&!Z&&!s,V=K&&!w,J=!!h||/^[a-zA-Z]:[\\/]?$/.test(u);return d?(0,M.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":a("directoryPicker.selectDirectory"),onClick:e=>{e.target!==e.currentTarget||s||t()},onKeyDown:e=>{"Escape"!==e.key||s||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:{...R,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:s,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:s?"default":"pointer",opacity:s?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=m.trim();t&&_(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 _(h??void 0),disabled:w||!J,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:J?"pointer":"default",opacity:J?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",{className:"directory-picker-path",id:"directory-path",type:"text",value:m,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),k(null)},style:{...L,minWidth:0,flex:1}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:w||!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:w||!m.trim()?"default":"pointer",opacity:w||!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:[w?(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 _(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)(B,{}),(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 _(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)(F,{}),(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")}),(j||l)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:j??l})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>{N(!0),z(null)},disabled:!V,style:{...W,marginRight:"auto",opacity:V?1:.6,cursor:V?"pointer":"default"},children:a("directoryPicker.newDirectory")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:t,disabled:s,style:{...W,cursor:s?"default":"pointer"},children:a("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>n(u),disabled:!K,title:a(Z?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{...A,opacity:K?1:.6,cursor:K?"pointer":"default"},children:a(s?"i18n.checking":"directoryPicker.selectThisFolder")})]}),C&&(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:12,background:"rgba(0,0,0,0.35)"},onClick:e=>{e.target===e.currentTarget&&U()},onKeyDown:e=>{e.stopPropagation(),"Escape"===e.key&&U()},children:(0,r.jsxs)("form",{role:"dialog","aria-modal":"true","aria-label":a("directoryPicker.createDirectory"),onSubmit:e=>{e.preventDefault(),q()},style:{...R,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:I,autoFocus:!0,autoComplete:"off",spellCheck:!1,placeholder:a("directoryPicker.directoryNamePlaceholder"),onChange:e=>{$(e.target.value),z(null)},disabled:D,className:"directory-picker-path",style:{...L,width:"100%",boxSizing:"border-box"}}),T&&(0,r.jsx)("div",{style:{marginTop:7,color:"#dc2626",fontSize:11,lineHeight:1.35},children:T}),(0,r.jsxs)("div",{style:{display:"flex",gap:6,marginTop:10},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:D||!I.trim(),style:{...A,flex:1,opacity:D?.65:1,cursor:D||!I.trim()?"default":"pointer"},children:a(D?"directoryPicker.creating":"directoryPicker.create")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:U,disabled:D,style:{...W,flex:1,cursor:D?"default":"pointer"},children:a("i18n.cancel")})]})]})]})})]})}),d):null}function H(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 _="/icons/catppuccin";function U(e){let{name:t,size:n=14}=e,i={width:n,height:n,"--catppuccin-icon-light":`url(${_}/latte/${t}.svg)`,"--catppuccin-icon-dark":`url(${_}/mocha/${t}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:i})}function q(e){let{size:t=14,open:n=!1}=e;return(0,r.jsx)(U,{name:n?"_folder_open":"_folder",size:t})}function Z(e){let{size:t=14}=e;return(0,r.jsx)(U,{name:"_file",size:t})}let K={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 V(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)(U,{name:i,size:t});let o=K[n.split(".").pop()??""];return o?(0,r.jsx)(U,{name:o,size:t}):(0,r.jsx)(Z,{size:t})}function J(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function Y(e){let t=J(e),n=t.split("/").filter(Boolean);return t.startsWith("//")&&n.length>0&&(n[0]=`//${n[0]}`),n.map(encodeURIComponent).join("/")}function G(e){let t=J(e).replace(/\/+$/,"");return t.split("/").pop()??t}function X(e){let t=J(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 Q(e,t){if(!t)return e;let n=J(e),r=J(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}function ee(e,t){return`${J(e).replace(/\/$/,"")}/${t}`}async function et(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 en(e){let t=Y(e),n=await fetch(`/api/files/${t}?type=list`);if(!n.ok)throw await et(n,"Failed to load files");return((await n.json()).entries??[]).map(t=>({name:t.name,fullPath:ee(e,t.name),isDir:t.isDir,size:t.size,children:t.isDir?[]:void 0,loaded:!t.isDir,outsideLinkTarget:t.outsideLinkTarget,outsideLinkEncloses:t.outsideLinkEncloses}))}async function er(e,t){let n=await fetch(`/api/files/${Y(e)}?type=allow-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:t})});if(!n.ok)throw await et(n,"Failed to allow the linked folder")}async function ei(e){let t=new URLSearchParams({cwd:e}),n=await fetch(`/api/git/status?${t.toString()}`);if(!n.ok)throw Error(`Failed to load Git status (HTTP ${n.status})`);return n.json()}let eo={modified:"files.modified",added:"files.added",deleted:"files.deleted",renamed:"files.renamed",untracked:"files.untracked",conflict:"files.conflict"},es={modified:"#d6a84b",added:"#4ade80",deleted:"#f87171",renamed:"#60a5fa",untracked:"#4ade80",conflict:"#f87171"};function el(e){let{status:t,t:n}=e;return(0,r.jsx)("span",{title:n(eo[t.status]),"aria-label":n(eo[t.status]),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:es[t.status],fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600},children:t.code})}function ea(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 ed(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"})]})}function ec(e){let{node:t,depth:n,cwd:o,onOpenFile:s,onAtMention:l,expandedPaths:a,onToggleExpanded:d,refreshToken:c,highlightedPaths:u,gitStatusByPath:p,changedDirectoryPaths:h,t:f}=e,m=a.has(t.fullPath),g=u.has(t.fullPath),x=J(t.fullPath),v=p.get(x),b=t.isDir&&(void 0!==v||h.has(x)),[y,j]=(0,i.useState)(t.children??[]),[k,w]=(0,i.useState)(t.loaded??!1),[S,C]=(0,i.useState)(!1),[E,N]=(0,i.useState)(null),[I,$]=(0,i.useState)(!1),[T,M]=(0,i.useState)(null),[R,L]=(0,i.useState)(!1),[z,A]=(0,i.useState)(null),W=t.outsideLinkTarget&&t.outsideLinkTarget!==T?t.outsideLinkTarget:null;(0,i.useEffect)(()=>{M(null),A(null)},[t.outsideLinkTarget]);let P=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!k||e){C(!0),N(null);try{let e=await en(t.fullPath);j(e),w(!0)}catch(e){N(e instanceof Error?e.message:String(e))}finally{C(!1)}}},[k,t.fullPath]);(0,i.useEffect)(()=>{void 0!==c&&m&&k&&!W&&P(!0)},[c]);let O=(0,i.useCallback)(()=>{if(t.isDir){let e=!m;d(t.fullPath,e),!e||k||W||P()}else s(t.fullPath,t.name)},[t.isDir,t.fullPath,t.name,k,m,W,P,s,d]),F=(0,i.useCallback)(async e=>{if((e.stopPropagation(),W)&&(!t.outsideLinkEncloses||window.confirm(f("files.allowEnclosingLinkConfirm",{target:W})))){L(!0),A(null);try{await er(t.fullPath,W),M(W),await P(!0)}catch(e){A(e instanceof Error?e.message:String(e))}finally{L(!1)}}},[t.fullPath,t.outsideLinkEncloses,W,P,f]);return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{onClick:O,onMouseEnter:()=>$(!0),onMouseLeave:()=>$(!1),style:{position:"relative",display:"flex",alignItems:"center",gap:4,paddingLeft:8+14*n,paddingRight:8,height:24,cursor:"pointer",background:I?"var(--bg-hover)":"transparent",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:m?"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"},children:t.isDir?(0,r.jsx)(q,{size:14,open:m}):V(t.name,14)}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},title:t.fullPath,children:t.name}),!I&&W&&(0,r.jsx)("span",{title:f("files.outsideLink",{target:W}),"aria-label":f("files.outsideLink",{target:W}),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)"},children:(0,r.jsx)(ed,{})}),g&&(0,r.jsx)("span",{title:f("files.newlyUploaded"),"aria-label":f("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"}})}),!I&&!t.isDir&&v&&(0,r.jsx)(el,{status:v,t:f}),!I&&b&&(0,r.jsx)("span",{title:f("files.containsChangedFiles"),"aria-label":f("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"}})}),S&&(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"})}),l&&I&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),l(Q(t.fullPath,o),t.isDir)},title:f("files.insertPath"),style:{position:"absolute",right:t.isDir?4:28,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(ea,{}),f("files.mention")]}),I&&!t.isDir&&(0,r.jsx)("a",{href:`/api/files/${Y(t.fullPath)}?type=download`,download:!0,onClick:e=>e.stopPropagation(),title:f("files.download"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 5px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap",textDecoration:"none"},children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})]}),t.isDir&&m&&W&&(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:f("files.outsideLink",{target:W})}),t.outsideLinkEncloses&&(0,r.jsx)("span",{style:{color:"#f59e0b"},children:f("files.outsideLinkEncloses")}),(0,r.jsx)("button",{type:"button",onClick:F,disabled:R,title:f("files.allowOutsideLinkTitle",{target:W}),style:{height:20,padding:"0 8px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:R?"default":"pointer",opacity:R?.6:1,fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:f("files.allowOutsideLink")}),z&&(0,r.jsx)("span",{role:"alert",style:{color:"#f87171",wordBreak:"break-word"},children:z})]}),t.isDir&&m&&!W&&(0,r.jsxs)("div",{children:[y.map(e=>(0,r.jsx)(ec,{node:e,depth:n+1,cwd:o,onOpenFile:s,onAtMention:l,expandedPaths:a,onToggleExpanded:d,refreshToken:c,highlightedPaths:u,gitStatusByPath:p,changedDirectoryPaths:h,t:f},e.fullPath)),0===y.length&&k&&!E&&(0,r.jsx)("div",{style:{paddingLeft:8+(n+1)*14,fontSize:11,color:"var(--text-dim)",height:22,display:"flex",alignItems:"center"},children:"empty"}),E&&(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:E})]})]})}function eu(e){let{status:t,cwd:n,onOpenFile:o,onAtMention:s,t:l}=e,[a,d]=(0,i.useState)(!1),c=G(t.filePath),u=Q(t.filePath,n),p=u.lastIndexOf("/"),h=p>=0?u.slice(0,p+1):"",f=p>=0?u.slice(p+1):u;return(0,r.jsxs)("div",{onClick:()=>o(t.filePath,c,{modeHint:"diff"}),onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),title:t.filePath,style:{display:"flex",alignItems:"center",gap:6,paddingLeft:10,paddingRight:8,height:24,cursor:"pointer",background:a?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none",position:"relative"},children:[(0,r.jsx)(el,{status:t,t:l}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",opacity:.85},children:V(c,13)}),(0,r.jsxs)("span",{title:t.filePath,style:{fontSize:12,color:"var(--text)",display:"flex",alignItems:"center",minWidth:0,flex:1},children:[h&&(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:"0 1 auto",minWidth:0,color:"var(--text-dim)"},children:h}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:0,maxWidth:"100%"},children:f})]}),s&&a&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),s(u,!1)},title:l("files.insertPath"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(ea,{}),l("files.mention")]})]})}let ep=(0,i.forwardRef)(function(e,t){let{cwd:n,onOpenFile:o,refreshKey:s,onAtMention:l,onAtMentions:a,onUploadBusyChange:d,changesCollapsed:c,onChangesCountChange:u,fileSearchOpen:p=!1,onFileSearchOpenChange:h}=e,{t:f}=(0,E.s)(),[m,g]=(0,i.useState)([]),[x,v]=(0,i.useState)(!0),[b,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(new Set),[w,S]=(0,i.useState)(0),[C,N]=(0,i.useState)(new Set),[I,$]=(0,i.useState)([]),[T,M]=(0,i.useState)({additions:0,deletions:0}),[R,L]=(0,i.useState)("idle"),[z,A]=(0,i.useState)(0),[W,P]=(0,i.useState)(null),[O,F]=(0,i.useState)(null),[B,D]=(0,i.useState)(null),[_,U]=(0,i.useState)(""),[q,Z]=(0,i.useState)([]),[K,V]=(0,i.useState)(!1),[G,et]=(0,i.useState)(!1),[er,eo]=(0,i.useState)(new Set),el=(0,i.useRef)(null),ed=(0,i.useRef)(null),ep=(0,i.useRef)(null),eh=`${s??0}:${w}`,ef="idle"!==R,em=_.trim().length>0;(0,i.useEffect)(()=>{if(!p)return;let e=_.trim();if(!e){Z([]),V(!1),et(!1);return}let t=new AbortController;V(!0),et(!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=>Z((e.matches??[]).filter(e=>!e.isDir).map(e=>e.path))).catch(()=>{t.signal.aborted||(Z([]),et(!0))}).finally(()=>{t.signal.aborted||V(!1)})},150);return()=>{clearTimeout(r),t.abort()}},[n,p,_]),(0,i.useEffect)(()=>{p&&el.current?.focus()},[p]),(0,i.useEffect)(()=>{if(0===q.length)return;let e=new Set;for(let t of q){let r=t.split("/"),i="";for(let t=0;t<r.length-1;t++)i=i?`${i}/${r[t]}`:r[t],e.add(ee(n,i))}eo(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,q]);let eg=(0,i.useMemo)(()=>{let e=t=>({name:t.name,fullPath:ee(n,t.path),isDir:t.isDir,size:0,children:t.children.map(e),loaded:!0});return(function(e){let t=[],n=new Map;for(let r of e){let e=r.split("/"),i=t,o="";for(let t=0;t<e.length;t++){o=o?`${o}/${e[t]}`:e[t];let r=n.get(o);r||(r={name:e[t],path:o,isDir:t<e.length-1,children:[]},n.set(o,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})(q).map(e)},[n,q]),ex=(0,i.useMemo)(()=>new Map(I.map(e=>[J(e.filePath),e])),[I]),ev=(0,i.useMemo)(()=>{let e=new Set,t=J(n).replace(/\/$/,"");for(let n of I){let r=X(J(n.filePath));for(;(r===t||r.startsWith(`${t}/`))&&(e.add(r),r!==t);){let e=X(r);if(e===r)break;r=e}}return e},[n,I]),eb=(0,i.useCallback)((e,t)=>{k(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},[]),ey=(0,i.useCallback)(e=>{let t=e.uploaded??[];F({uploaded:t,skipped:e.skipped??[],errors:e.errors??[]}),t.length>0&&(N(new Set(t.map(e=>ee(n,e)))),S(e=>e+1))},[n]),ej=(0,i.useCallback)(async(e,t)=>{D(null),P(null),A(0),L("uploading");try{let{status:r,data:i}=await new Promise((r,i)=>{let o=new FormData;e.forEach(e=>o.append("files",e,e.name));let s=new XMLHttpRequest;s.open("POST",`/api/files/${Y(n)}?type=upload&conflict=${t}`),s.upload.onprogress=e=>{e.lengthComputable&&e.total>0&&A(Math.round(e.loaded/e.total*100))},s.onerror=()=>i(Error("Network error while uploading files")),s.onabort=()=>i(Error("Upload cancelled")),s.onload=()=>{let e={};try{e=JSON.parse(s.responseText)}catch{s.responseText&&(e.error=s.responseText)}r({status:s.status,data:e})},s.send(o)});if(409===r&&i.conflicts?.length)return void D({files:e,conflicts:i.conflicts,nonReplaceable:i.nonReplaceable??[]});if(r<200||r>=300)throw Error(i.error??`Upload failed (HTTP ${r})`);A(100),ey(i)}catch(e){P(e instanceof Error?e.message:String(e))}finally{L("idle")}},[ey,n]),ek=(0,i.useCallback)(async e=>{if(0!==e.length&&!ef){F(null),N(new Set),D(null),P(null),A(0),L("checking");try{let t=await fetch(`/api/files/${Y(n)}?type=upload-check`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileNames:e.map(e=>e.name)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Error(r.error??`Upload check failed (HTTP ${t.status})`);if(r.conflicts?.length)return void D({files:e,conflicts:r.conflicts,nonReplaceable:r.nonReplaceable??[]});await ej(e,"error")}catch(e){P(e instanceof Error?e.message:String(e))}finally{L("idle")}}},[n,ej,ef]),ew=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",ek(t)},[ek]);(0,i.useImperativeHandle)(t,()=>({openUploadPicker(){ef||ep.current?.click()}}),[ef]),(0,i.useEffect)(()=>{d?.(ef)},[d,ef]),(0,i.useEffect)(()=>()=>d?.(!1),[d]),(0,i.useEffect)(()=>{let e=ed.current!==n;ed.current=n,e&&(k(new Set),N(new Set),F(null),D(null),P(null)),v(e),y(null);let t=!1;return en(n).then(e=>{t||g(e)}).catch(e=>{t||y(e instanceof Error?e.message:String(e))}).finally(()=>{t||v(!1)}),()=>{t=!0}},[n,s,w]),(0,i.useEffect)(()=>{let e=!1;return ei(n).then(t=>{e||($(t.isGitRepository?t.files:[]),M(t.isGitRepository?{additions:t.additions,deletions:t.deletions}:{additions:0,deletions:0}))}).catch(()=>{e||($([]),M({additions:0,deletions:0}))}),()=>{e=!0}},[n,s,w]),(0,i.useEffect)(()=>{u?.(I.length)},[I,u]);let eS=ef||null!==B||null!==W||null!==O,eC=(0,i.useCallback)(()=>{O&&0!==O.uploaded.length&&a?.(O.uploaded.map(e=>Q(ee(n,e),n)))},[n,a,O]);return(0,r.jsxs)("div",{style:{minHeight:"100%"},children:[(0,r.jsx)("input",{ref:ep,type:"file",multiple:!0,hidden:!0,onChange:ew}),eS&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[ef&&(0,r.jsxs)("div",{role:"status","aria-live":"polite","aria-label":"checking"===R?f("files.checking"):f("files.uploading",{progress:z}),children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,minHeight:14,color:"var(--text-muted)"},children:["checking"===R?(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"===R&&(0,r.jsxs)("span",{style:{fontSize:10},children:[z,"%"]})]}),"uploading"===R&&(0,r.jsx)("div",{style:{height:3,marginTop:4,overflow:"hidden",borderRadius:2,background:"var(--border)"},children:(0,r.jsx)("div",{style:{width:`${z}%`,height:"100%",background:"var(--text-muted)",transition:"width 120ms ease"}})})]}),B&&(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:f("files.conflictSummary",{count:B.conflicts.length,countSuffix:1===B.conflicts.length?"":"s",files:B.conflicts.join(", ")})}),B.nonReplaceable.length>0&&(0,r.jsx)("div",{style:{marginTop:3,fontSize:10,color:"#f59e0b",lineHeight:1.35,overflowWrap:"anywhere"},children:f("files.cannotReplace",{files:B.nonReplaceable.join(", ")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:7},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void ej(B.files,"overwrite"),style:{height:22,padding:"0 7px",border:"1px solid #ef4444",borderRadius:4,background:"transparent",color:"#ef4444",cursor:"pointer",fontSize:10},children:f("files.replace")}),(0,r.jsx)("button",{type:"button",onClick:()=>void ej(B.files,"skip"),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:f("files.skipExisting")}),(0,r.jsx)("button",{type:"button",onClick:()=>D(null),style:{height:22,padding:"0 7px",border:"none",borderRadius:4,background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:10},children:f("files.cancel")})]})]}),W&&(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:W}),(0,r.jsx)(H,{onClick:()=>P(null),title:f("files.dismissError")})]}),O&&(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:[O.uploaded.length>0&&(0,r.jsxs)("span",{title:`${O.uploaded.length} uploaded`,"aria-label":`${O.uploaded.length} uploaded`,style:{display:"flex",alignItems:"center",gap:3,color:"#22c55e"},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m5 12 4 4L19 6"})}),(0,r.jsx)("span",{children:O.uploaded.length})]}),O.skipped.length>0&&(0,r.jsxs)("span",{title:`${O.skipped.length} skipped`,"aria-label":`${O.skipped.length} skipped`,style:{display:"flex",alignItems:"center",gap:3,color:"var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M8 12h8"})]}),(0,r.jsx)("span",{children:O.skipped.length})]}),O.errors.length>0&&(0,r.jsxs)("span",{title:`${O.errors.length} failed`,"aria-label":`${O.errors.length} failed`,style:{display:"flex",alignItems:"center",gap:3,color:"#f87171"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 3 2.5 20h19L12 3Z"}),(0,r.jsx)("path",{d:"M12 9v4"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{children:O.errors.length})]})]}),O.uploaded.length>0&&a&&(0,r.jsxs)("button",{type:"button",onClick:eC,title:1===O.uploaded.length?f("files.addUploadedFile"):f("files.addAllUploadedFiles"),"aria-label":1===O.uploaded.length?f("files.addUploadedFile"):f("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)(ea,{}),f("files.mention")]}),(0,r.jsx)(H,{onClick:()=>F(null),title:f("files.dismissUploadResults")})]}),O.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:"6px 8px",borderBottom:"1px solid var(--border)"},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:el,value:_,onChange:e=>U(e.target.value),onKeyDown:e=>{"Escape"===e.key&&h?.(!1)},placeholder:f("sidebar.searchFilesPlaceholder"),"aria-label":f("sidebar.searchFiles"),style:{width:"100%",boxSizing:"border-box",padding:"6px 24px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}}),_&&(0,r.jsx)("button",{type:"button",onClick:()=>U(""),title:f("sidebar.clearSearch"),"aria-label":f("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"})]})})]}),em&&(0,r.jsxs)("div",{style:{paddingTop:3},children:[K&&(0,r.jsx)("div",{role:"status",style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:f("sidebar.searchingFiles")}),!K&&G&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 2px",fontSize:10,color:"#f87171"},children:f("i18n.networkError")}),!K&&!G&&0===q.length&&(0,r.jsx)("div",{style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:f("sidebar.noMatchingFiles")}),!K&&!G&&q.length>0&&(0,r.jsx)("div",{children:eg.map(e=>(0,r.jsx)(ec,{node:e,depth:0,cwd:n,onOpenFile:o,onAtMention:l,expandedPaths:er,onToggleExpanded:(e,t)=>{eo(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},highlightedPaths:C,gitStatusByPath:ex,changedDirectoryPaths:ev,t:f},`${_}:${e.fullPath}`))})]})]}),!c&&I.length>0&&(0,r.jsxs)("div",{style:{padding:"0 4px 2px"},children:[(0,r.jsxs)("div",{"aria-label":f("files.changeStats",{count:I.length,additions:T.additions,deletions:T.deletions}),style:{display:"flex",alignItems:"center",gap:6,height:24,padding:"0 10px",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:f("files.changedCount",{count:I.length})}),(0,r.jsxs)("span",{style:{color:es.added,fontFamily:"var(--font-mono)"},children:["+",T.additions]}),(0,r.jsxs)("span",{style:{color:es.deleted,fontFamily:"var(--font-mono)"},children:["-",T.deletions]})]}),I.map(e=>(0,r.jsx)(eu,{status:e,cwd:n,onOpenFile:o,onAtMention:l,t:f},e.filePath))]}),(c||0===I.length)&&(!p||!em)&&(0,r.jsxs)("div",{style:{padding:"2px 4px"},children:[x?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:"Loading files..."}):b?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"#f87171"},children:b}):m.map(e=>(0,r.jsx)(ec,{node:e,depth:0,cwd:n,onOpenFile:o,onAtMention:l,expandedPaths:j,onToggleExpanded:eb,refreshToken:eh,highlightedPaths:C,gitStatusByPath:ex,changedDirectoryPaths:ev,t:f},e.fullPath)),!x&&!b&&0===m.length&&(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:f("files.noFiles")})]})]})});function eh(e){let{open:t,query:n,children:o,selectedSessionId:s,onSelectSession:l}=e,{t:a,locale:d}=(0,E.s)(),[c,u]=(0,i.useState)({query:""}),p=n.trim(),h=c.query===p?c.response:void 0,f=c.query===p&&c.failed;return(0,i.useEffect)(()=>{if(!t||!p)return;let e=new AbortController;u({query:p});let n=setTimeout(async()=>{try{let t=await fetch(`/api/sessions/search?${new URLSearchParams({q:p})}`,{signal:e.signal});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();e.signal.aborted||u({query:p,response:n})}catch{e.signal.aborted||u({query:p,failed:!0})}},300);return()=>{clearTimeout(n),e.abort()}},[t,p]),t&&p?(0,r.jsxs)("div",{className:"min-h-20 flex-1 overflow-y-auto","aria-busy":!h&&!f,children:[(0,r.jsx)("div",{role:"status",className:"px-3 py-2 text-xs text-text-muted",children:f?a("sidebar.sessionSearchFailed"):h?0===h.results.length?a("sidebar.sessionSearchEmpty"):a("sidebar.sessionSearchCount",{count:h.results.length}):a("sidebar.sessionSearching")}),h?.truncated&&(0,r.jsx)("div",{role:"status",className:"px-3 pb-2 text-xs text-text-muted",children:a("sidebar.sessionSearchPartial")}),h?.results.map(e=>{let{session:t,entryId:n,blockIndex:i,before:o,match:a,after:c}=e;return(0,r.jsxs)("button",{type:"button",onClick:()=>l(t,n,i),"aria-current":t.id===s?"true":void 0,className:`block w-full cursor-pointer border-b border-border px-3 py-2 text-left hover:bg-bg-hover focus-visible:outline-2 focus-visible:outline-accent ${t.id===s?"bg-bg-selected":""}`,children:[(0,r.jsx)("span",{className:"block truncate text-xs font-medium text-text",children:t.name||t.firstMessage}),(0,r.jsxs)("span",{className:"mt-1 flex min-w-0 gap-2 text-[10px] text-text-dim",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate",title:t.cwd,children:t.cwd}),(0,r.jsx)("span",{className:"shrink-0",children:(0,C.fw)(t.modified,d)})]}),(0,r.jsxs)("span",{className:"mt-1 block text-xs leading-relaxed wrap-anywhere text-text-muted",children:[o,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:a}),c]})]},t.id)})]}):o}let ef="(max-width: 640px)",em="(max-width: 480px)";function eg(e,t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)}function ex(e){return!!window.matchMedia&&window.matchMedia(e).matches}let ev=e=>eg(ef,e),eb=()=>ex(ef),ey=e=>eg(em,e),ej=()=>ex(em);function ek(){return!1}function ew(){return(0,i.useSyncExternalStore)(ev,eb,ek)}let eS={en:{pinSession:"Pin session",unpinSession:"Unpin session",pinProject:"Pin project",unpinProject:"Unpin project",pinFailed:"Could not save the pin"},"zh-CN":{pinSession:"置顶会话",unpinSession:"取消置顶会话",pinProject:"置顶项目",unpinProject:"取消置顶项目",pinFailed:"置顶保存失败"},"zh-TW":{pinSession:"釘選工作階段",unpinSession:"取消釘選工作階段",pinProject:"釘選專案",unpinProject:"取消釘選專案",pinFailed:"釘選儲存失敗"}},eC={display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,flexShrink:0,background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:7,color:"var(--text-muted)",cursor:"pointer",transition:"background 0.12s, color 0.12s, border-color 0.12s"},eE={display:"flex",alignItems:"center",justifyContent:"center",width:22,height:22,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",transition:"color 0.12s"};function eN(e){let{filled:t}=e;return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:t?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12",y2:"22"}),(0,r.jsx)("path",{d:"M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24Z"})]})}function eI(e){let{kind:t,id:n,pinned:o,onToggle:s,variant:l="action",as:a="button",hovered:d=!1}=e,{locale:c}=(0,E.s)(),u=ew(),[p,h]=(0,i.useState)(!1),[f,m]=(0,i.useState)(!1),[g,x]=(0,i.useState)(!1),v=(0,i.useRef)(!0);(0,i.useEffect)(()=>(v.current=!0,()=>{v.current=!1}),[]),(0,i.useEffect)(()=>{if(!p)return;let e=setTimeout(()=>h(!1),1600);return()=>clearTimeout(e)},[p]);let b=(0,i.useCallback)(e=>{e.stopPropagation(),e.preventDefault(),f||(m(!0),(async()=>{let e=await s(t,n,!o);v.current&&(m(!1),!1===e&&h(!0))})())},[f,n,t,s,o]),y=(0,i.useCallback)(e=>{("Enter"===e.key||" "===e.key)&&(e.stopPropagation(),e.preventDefault(),b(e))},[b]);if("action"===l&&!(u||d||o))return null;let j=eS[c]??eS.en,k=o?"session"===t?j.unpinSession:j.unpinProject:"session"===t?j.pinSession:j.pinProject,w="action"===l?eC:eE,S="action"===l?{...w,background:g?"var(--bg-selected)":"var(--bg-hover)",color:p?"#ef4444":o||g?"var(--accent)":"var(--text-muted)",borderColor:p||o||g?"rgba(37,99,235,0.35)":"var(--border)"}:{...w,color:p?"#ef4444":o?"var(--accent)":"var(--text-dim)",opacity:o||u?1:.7};return(0,r.jsx)("span"===a?"span":"button",{onClick:b,onMouseEnter:()=>x(!0),onMouseLeave:()=>x(!1),..."span"===a?{role:"button",tabIndex:0,onKeyDown:y}:{},"aria-pressed":o,title:p?j.pinFailed:k,"aria-label":k,style:S,children:(0,r.jsx)(eN,{filled:o})})}let e$={en:{archiveProject:"Archive project",unarchiveProject:"Unarchive project",archiveFailed:"Could not save the archive"},"zh-CN":{archiveProject:"归档项目",unarchiveProject:"取消归档",archiveFailed:"归档保存失败"},"zh-TW":{archiveProject:"封存專案",unarchiveProject:"取消封存",archiveFailed:"封存儲存失敗"}},eT={display:"flex",alignItems:"center",justifyContent:"center",width:22,height:22,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",transition:"color 0.12s"};function eM(e){let{filled:t}=e;return(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:t?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",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"})]})}function eR(e){let{id:t,archived:n,onToggle:o,as:s="button"}=e,{locale:l}=(0,E.s)(),a=ew(),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=(0,i.useRef)(!0);(0,i.useEffect)(()=>(h.current=!0,()=>{h.current=!1}),[]),(0,i.useEffect)(()=>{if(!d)return;let e=setTimeout(()=>c(!1),1600);return()=>clearTimeout(e)},[d]);let f=(0,i.useCallback)(e=>{e.stopPropagation(),e.preventDefault(),u||(p(!0),(async()=>{let e=await o(t,!n);h.current&&(p(!1),!1===e&&c(!0))})())},[n,u,t,o]),m=(0,i.useCallback)(e=>{("Enter"===e.key||" "===e.key)&&(e.stopPropagation(),e.preventDefault(),f(e))},[f]),g=e$[l]??e$.en,x=n?g.unarchiveProject:g.archiveProject,v={...eT,color:d?"#ef4444":n?"var(--accent)":"var(--text-dim)",opacity:n||a?1:.7};return(0,r.jsx)("span"===s?"span":"button",{onClick:f,..."span"===s?{role:"button",tabIndex:0,onKeyDown:m}:{},"aria-pressed":n,title:d?g.archiveFailed:x,"aria-label":x,style:v,children:(0,r.jsx)(eM,{filled:n})})}function eL(e){return new Set(e.projects)}function ez(e){return e&&"object"==typeof e?{projects:function(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){if("string"!=typeof n)continue;let e=n.trim();e&&t.add(e)}return[...t].sort()}(e.projects??e.archives)}:{projects:[]}}function eA(e,t){if(e.size!==t.size)return!0;for(let n of e)if(!t.has(n))return!0;return!1}let eW={remote:"sidebar.openInExplorerRemoteOnly","unsupported-platform":"sidebar.openInExplorerUnsupported"};function eP(e){let{onClick:t,title:n,disabled:i,skipHover:o,color:s,background:l="none",marginRight:a,ariaPressed:d,children:c}=e;return(0,r.jsx)("button",{onClick:t,disabled:i,title:n,"aria-label":n,"aria-pressed":d,style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,marginRight:a,background:l,border:"none",color:s,cursor:i?"default":"pointer",borderRadius:5,flexShrink:0,opacity:i?.6:1,transition:"color 0.3s, background 0.3s"},onMouseEnter:e=>{i||o||(e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||o||(e.currentTarget.style.color=s,e.currentTarget.style.background=l)},children:c})}let eO="pi-web:unread-session-ids",eF="pi-web:last-custom-cwd";function eB(){try{return window.localStorage.getItem(eF)??""}catch{return""}}function eD(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function eH(e){let{text:t,style:n}=e;return(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...n},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:t})})}function e_(e){let{open:t,children:n,style:o}=e,[s,l]=(0,i.useState)(t),[a,d]=(0,i.useState)(t);return((0,i.useEffect)(()=>{let e,n;return t?(l(!0),d(!1),e=window.requestAnimationFrame(()=>{e=window.requestAnimationFrame(()=>d(!0))})):(d(!1),n=setTimeout(()=>l(!1),140)),()=>{void 0!==e&&window.cancelAnimationFrame(e),n&&clearTimeout(n)}},[t]),s)?(0,r.jsx)("div",{style:{...o,opacity:+!!a,transform:a?"translateY(0) scale(1)":"translateY(-8px) scale(0.96)",transformOrigin:"top center",transition:"opacity 140ms ease, transform 140ms ease",pointerEvents:t?"auto":"none"},children:n}):null}let eU="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function eq(){let[e,t]=(0,i.useState)(!1),[n,o]=(0,i.useState)(!1),s=(0,i.useRef)(null),l=function(e,t){let[n,r]=(0,i.useState)(e),o=(0,i.useRef)(null),s=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void r(e);s.current=0;let n=4*e.length,i=()=>{s.current+=1;let t=Math.floor(s.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:eU[Math.floor(Math.random()*eU.length)]).join("")),s.current<n?o.current=requestAnimationFrame(i):r(e)};return o.current=requestAnimationFrame(i),()=>{o.current&&cancelAnimationFrame(o.current)}},[e,t]),n}(e?"0.10.0p1.0.0":"Pi Web",n),a=(0,i.useCallback)(e=>{t(e),o(!0),setTimeout(()=>o(!1),(e?6:8)*4*(1e3/60)+100)},[]),d=(0,i.useCallback)(()=>{s.current&&clearTimeout(s.current);let t=!e;a(t),t&&(s.current=setTimeout(()=>a(!1),3e3))},[e,a]);return(0,i.useEffect)(()=>()=>{s.current&&clearTimeout(s.current)},[]),(0,r.jsx)("button",{onClick:d,style:{background:"none",border:"none",padding:0,cursor:"default",fontWeight:700,fontSize:15,letterSpacing:"-0.01em",color:e?"var(--accent)":"var(--text)",fontFamily:"var(--font-mono)",minWidth:"6ch"},children:l})}function eZ(e){let{selectedSessionId:t,onSelectSession:n,onNewSession:o,initialSessionId:s,skipInitialProjectSelection:c,onInitialRestoreDone:p,refreshKey:g,onSessionDeleted:x,selectedCwd:v,onCwdChange:b,onOpenFile:y,onOpenTerminal:j,explorerRefreshKey:C,onExplorerRefresh:N,onAtMention:I,onAtMentions:M,onBackgroundTaskDone:R,onRunningSessionIdsChange:L,onSessionsChange:z}=e,{t:A}=(0,E.s)(),{sets:W,applyPayload:P,toggle:O}=function(){let[e,t]=(0,i.useState)(l),n=(0,i.useRef)(0),r=(0,i.useCallback)(e=>{let r=a(d(e));n.current+=1,t(e=>u(r,e)?r:e)},[]),o=(0,i.useCallback)(async()=>{let e=n.current;try{let r=await fetch("/api/pins",{cache:"no-store"});if(!r.ok)return;let i=d(await r.json());if(e!==n.current)return;t(e=>{let t=a(i);return u(t,e)?t:e})}catch{}},[]),s=(0,i.useCallback)(async(e,i,s)=>{n.current+=1,t(t=>(function(e,t,n,r){let i="session"===t?e.sessions:e.projects;if(i.has(n)===r)return e;let o=new Set(i);return r?o.add(n):o.delete(n),"session"===t?{...e,sessions:o}:{...e,projects:o}})(t,e,i,s));try{let t=await fetch("/api/pins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({kind:e,key:i,pinned:s}),cache:"no-store"});if(!t.ok)return await o(),!1;return r(await t.json()),!0}catch{return await o(),!1}},[r,o]);return(0,i.useEffect)(()=>{o()},[o]),{sets:e,applyPayload:r,toggle:s,refresh:o}}(),{set:F,applyPayload:B,toggle:_}=function(){let[e,t]=(0,i.useState)(()=>new Set),n=(0,i.useRef)(0),r=(0,i.useCallback)(e=>{let r=eL(ez(e));n.current+=1,t(e=>eA(r,e)?r:e)},[]),o=(0,i.useCallback)(async()=>{let e=n.current;try{let r=await fetch("/api/archives",{cache:"no-store"});if(!r.ok)return;let i=ez(await r.json());if(e!==n.current)return;t(e=>{let t=eL(i);return eA(t,e)?t:e})}catch{}},[]),s=(0,i.useCallback)(async(e,i)=>{n.current+=1,t(t=>{if(t.has(e)===i)return t;let n=new Set(t);return i?n.add(e):n.delete(e),n});try{let t=await fetch("/api/archives",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e,archived:i}),cache:"no-store"});if(!t.ok)return await o(),!1;return r(await t.json()),!0}catch{return await o(),!1}},[r,o]);return(0,i.useEffect)(()=>{o()},[o]),{set:e,applyPayload:r,toggle:s,refresh:o}}(),[U,q]=(0,i.useState)([]),Z=(0,i.useRef)(null),K=(0,i.useRef)(0),[V,J]=(0,i.useState)(!0),[Y,G]=(0,i.useState)(null),[X,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(""),[en,er]=(0,i.useState)(!1),[ei,eo]=(0,i.useState)(""),[es,el]=(0,i.useState)(""),[ea,ed]=(0,i.useState)(!1),[ec,eu]=(0,i.useState)(eB),[ef,em]=(0,i.useState)(null),[eg,ex]=(0,i.useState)(!1),[ev,eb]=(0,i.useState)(null),ey=(0,i.useRef)(null),[ej,ek]=(0,i.useState)(null),[ew,eS]=(0,i.useState)(!1),[eC,eE]=(0,i.useState)(!1),[eN,e$]=(0,i.useState)(""),[eT,eM]=(0,i.useState)(null),[eU,eZ]=(0,i.useState)(!1),[eK,eV]=(0,i.useState)(null),[eY,eG]=(0,i.useState)(null),eX=(0,i.useRef)(null),eQ=(0,i.useRef)(null),[e0,e1]=(0,i.useState)(!0),[e2,e4]=(0,i.useState)(0),[e8,e3]=(0,i.useState)(!1),[e5,e6]=(0,i.useState)(!1),[e9,e7]=(0,i.useState)(!1),[te,tt]=(0,i.useState)(""),tn=e9&&!!te.trim(),[tr,ti]=(0,i.useState)(0),[to,ts]=(0,i.useState)(!0),[tl,ta]=(0,i.useState)(!1),[td,tc]=(0,i.useState)(null),[tu,tp]=(0,i.useState)(null),[th,tf]=(0,i.useState)(()=>new Set),[tm,tg]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(eO);if(!e)return new Set;let t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(e=>"string"==typeof e));return new Set}catch{return new Set}})()),tx=(0,i.useRef)(new Set),tv=(0,i.useRef)(new Set),tb=(0,i.useRef)(new Set),ty=(0,i.useRef)(!1),tj=(0,i.useRef)(null),tk=(0,i.useRef)(null),tw=(0,i.useRef)(null),tS=(0,i.useRef)(null),tC=(0,i.useRef)(null);T(tS),T(tC,e0&&!!(v||X));let tE=(0,i.useRef)(null),tN=(0,i.useRef)(null),tI=(0,i.useRef)(320),t$=(0,i.useCallback)(()=>{if(!e0)return 320;let e=tE.current?.getBoundingClientRect().height,t=tN.current?.getBoundingClientRect().height;return e&&t?Math.round((e+t)/2):320},[e0]),tT=(0,i.useCallback)(()=>e0&&(v||X)?Math.max(80,(tE.current?.getBoundingClientRect().height??320)+(tN.current?.getBoundingClientRect().height??120)-120):1600,[e0,X,v]),tM=$({ariaLabel:A("layout.resizeSidebarSections"),axis:"vertical",cssVariable:"--sidebar-session-pane-height",defaultWidth:320,getDefaultWidth:t$,getMaxWidth:tT,growthDirection:"down",maxWidth:1600,minWidth:80,storageKey:"pi-web:sidebar-session-pane-height",widthRef:tI}),[tR,tL]=(0,i.useState)(0),[tz,tA]=(0,i.useState)(0),[tW,tP]=(0,i.useState)(null),tO=(0,i.useRef)(null),tF=(0,i.useRef)(0),tB=(0,i.useRef)(0),tD=(0,i.useCallback)(e=>{tF.current=e.currentTarget.scrollTop,null==tO.current&&(tO.current=requestAnimationFrame(()=>{tO.current=null;let e=54*Math.floor(tF.current/54);tB.current!==e&&(tB.current=e,tA(e))}))},[]);(0,i.useLayoutEffect)(()=>{let e=tS.current;if(!e)return;let t=new ResizeObserver(e=>{for(let t of e)tL(t.contentRect.height)});return t.observe(e),tL(e.clientHeight),tF.current=e.scrollTop,tB.current=54*Math.floor(e.scrollTop/54),tA(tB.current),()=>t.disconnect()},[tn]);let tH=(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=++K.current;try{e&&J(!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 o=await i.json();if(r!==K.current)return;Z.current=o.sessionListVersion,q(o.sessions),ty.current||(tv.current=new Set(o.completionNotificationSuppressedSessionIds??[]),tf(new Set(o.runningSessionIds??[])));let s=new Set(o.sessions.filter(e=>e.relation?.kind!=="subagent").map(e=>e.id));tg(e=>{if(0===e.size)return e;let t=new Set([...e].filter(e=>s.has(e)));return t.size===e.size?e:t}),G(null)}catch(e){r===K.current&&G(String(e))}finally{r===K.current&&J(!1)}},[]),t_=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!t_.current;t_.current=!0;let t=!0;return e?tH(!0,!1,!0).then(()=>{t&&(tj.current=setTimeout(()=>{tj.current=null,t&&tH(!1,!0)},750))}):tH(!1,!0),()=>{t=!1,tj.current&&(clearTimeout(tj.current),tj.current=null)}},[tH,g]),(0,i.useEffect)(()=>{e1(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m();if(!e)return!0;try{return"false"!==e.getItem(f)}catch{return!0}}())},[]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/open-in-explorer").then(e=>e.ok?e.json():null).then(t=>{!e&&t&&tc(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{tp(null)},[X,v]);let tU=(0,i.useCallback)(async()=>{let e=X??v;if(e)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 void tp(null);let n=await t.json().catch(()=>({}));tp(n.error??`HTTP ${t.status}`)}catch(e){tp(e instanceof Error?e.message:String(e))}},[X,v]),tq=A(td?.platform==="darwin"?"sidebar.openInFinder":td?.platform==="win32"?"sidebar.openInExplorer":"sidebar.openInFileManager"),tZ=td?.supported===!1,tK=tu?A(eW[tu]??tu):null;(0,i.useEffect)(()=>{try{0===tm.size?window.localStorage.removeItem(eO):window.localStorage.setItem(eO,JSON.stringify([...tm]))}catch{}},[tm]),(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 o=new AbortController;n?.abort(),n=o;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:o.signal});if(!t.ok)return;let r=await t.json();if(e||n!==o)return;ty.current=!0,P(r.pins),B(r.archives),tv.current=new Set(r.completionNotificationSuppressedSessionIds??[]),tf(new Set(r.runningSessionIds??[])),r.sessionListVersion!==Z.current&&await tH()}catch{}finally{n===o&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},o=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",o),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",o)}},[B,P,tH]),(0,i.useEffect)(()=>{L?.(th)},[L,th]),(0,i.useEffect)(()=>{z?.(U)},[U,z]),(0,i.useEffect)(()=>{let e=tx.current,n=[...e].filter(e=>!th.has(e)&&e!==t),r=new Set(U.filter(e=>e.relation?.kind==="subagent").map(e=>e.id)),i=n.filter(e=>!tb.current.has(e)&&!r.has(e)),o=[...th].filter(t=>!e.has(t));(i.length>0||o.length>0)&&tg(e=>{let t=new Set(e);return th.forEach(e=>t.delete(e)),i.forEach(e=>t.add(e)),t});let s=o.some(e=>!U.some(t=>t.id===e));(n.length>0||s)&&tH(!1,!0),i.length>0&&R?.(),tx.current=th,tb.current=new Set([...th].filter(e=>tv.current.has(e)||r.has(e)))},[th,t,U,tH,R]),(0,i.useEffect)(()=>{t&&tg(e=>{if(!e.has(t))return e;let n=new Set(e);return n.delete(t),n})},[t]),(0,i.useEffect)(()=>{void 0!==C&&e4(e=>e+1)},[C]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&et(e.home)}).catch(()=>{})},[]);let tV=(0,i.useRef)(!1),tJ=(0,i.useCallback)((e,t)=>({root:e,key:t}),[]),tY=(0,i.useCallback)(e=>{if(!e)return null;if(ev?.cwd===e)return tJ(ev.root,ev.key);if(ej&&ej.forCwd===e||ej?.worktrees.some(t=>t.path===e))return tJ(ej.projectRoot,ej.projectKey);let t=U.find(t=>t.cwd===e||(t.projectRoot??t.cwd)===e);return t?tJ(t.projectRoot??t.cwd,k(t)):tJ(e,e)},[ev,ej,U,tJ]),tG=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tY(X),t=tG.current;(t?.cwd!==X||t.key!==(e?.key??null))&&(tG.current={cwd:X,key:e?.key??null},b?.(X,e?.root??null,e?.key??null))},[X,b,tY]);let tX=(0,i.useRef)(null);(0,i.useEffect)(()=>{v&&v!==tX.current&&(tX.current=v,Q(v))},[v]);let[tQ,t0]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!X){ek(null),eG(null);return}let e=!1;return eG(X),fetch(`/api/worktrees?cwd=${encodeURIComponent(X)}`).then(e=>e.json()).then(t=>{if(!e){if(eG(null),t.error||!t.projectRoot)return void ek(null);ek({forCwd:X,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||(eG(null),ek(null))}),()=>{e=!0}},[X,tQ,g]),(0,i.useEffect)(()=>{if(0!==U.length&&!c&&null===X){if(s&&!tV.current){tV.current=!0;let e=U.find(e=>e.id===s);if(e){Q(e.cwd),n(e,!0);return}p?.()}let e=w(U,void 0,F);e.length>0&&Q(e[0].root)}},[U,F,X,s,c,n,p]);let t1=ej?ej.worktrees.find(e=>e.path===X)??(ej.forCwd===X&&ej.currentWorktreePath?ej.worktrees.find(e=>e.path===ej.currentWorktreePath):void 0)??ej.worktrees.find(e=>e.isMain):void 0,t2=t1?.path??null,t4=(0,i.useCallback)(async function(e){let{remember:t=!0}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=(e??ec).trim();if(n&&!eg){ex(!0),em(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n})}),i=await e.json().catch(()=>({}));if(!e.ok||i.error||!i.cwd||!i.projectRoot||!i.projectKey)return void em(i.error??`HTTP ${e.status}`);if(eb({cwd:i.cwd,root:i.projectRoot,key:i.projectKey}),t){var r=i.cwd;try{window.localStorage.setItem(eF,r)}catch{}eu(i.cwd)}Q(i.cwd),ed(!1),er(!1)}catch(e){em(e instanceof Error?e.message:String(e))}finally{ex(!1)}}},[ec,eg]),t8=(0,i.useCallback)(()=>{ed(!0),em(null),er(!1)},[]),t3=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json();t.cwd&&await t4(t.cwd,{remember:!1})}catch{}},[t4]),t5=(0,i.useCallback)(async()=>{let e=eN.trim();if(e&&!eU&&ej){eZ(!0),eM(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:ej.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void eM(n.error??`HTTP ${t.status}`);eE(!1),e$(""),eS(!1),ek(t=>t?{...t,forCwd:n.path,currentWorktreePath:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),Q(n.path),t0(e=>e+1)}catch(e){eM(e instanceof Error?e.message:String(e))}finally{eZ(!1)}}},[eN,eU,ej]),t6=(0,i.useCallback)(async(e,t)=>{if(ej&&!eU){eZ(!0),eM(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:ej.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void eV(e);eM(r.error??`HTTP ${n.status}`);return}eV(null),t2===e&&Q(ej.projectRoot),t0(e=>e+1)}catch(e){eM(e instanceof Error?e.message:String(e))}finally{eZ(!1)}}},[ej,eU,t2]);(0,i.useEffect)(()=>{let e=e=>{ey.current&&!ey.current.contains(e.target)&&(er(!1),eo("")),eX.current&&!eX.current.contains(e.target)&&(eS(!1),eE(!1),e$(""),eM(null),eV(null),el(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let t9=(0,i.useCallback)((e,t,r)=>{q(t=>t.some(t=>t.id===e.id)?t:[e,...t]),e.cwd&&Q(e.cwd);let i=k(e);i&&F.has(i)&&_(i,!1),n(e,!1,t,r)},[F,n,_]),t7=(0,i.useCallback)(()=>{if(!X)return;let e="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;o?.(e,X)},[o,X]),ne=(0,i.useMemo)(()=>w(U,W.projects,F),[U,W.projects,F]),nt=(0,i.useMemo)(()=>tY(X),[tY,X]),nn=(0,i.useCallback)(e=>{e&&F.has(e)&&_(e,!1)},[F,_]);(0,i.useEffect)(()=>{nn(ev?.key)},[nn,ev?.key]);let nr=(0,i.useCallback)(()=>{nn(nt?.key),t7()},[t7,nt,nn]),ni=ne[0]?.root??null;(0,i.useEffect)(()=>{!nt||F.has(nt.key)&&Q(ni)},[F,ni,nt]);let no=ne.length>8,ns=(0,i.useMemo)(()=>{let e=ei.trim().toLowerCase();return e?ne.filter(t=>t.root.toLowerCase().includes(e)):ne},[ei,ne]),nl=(0,i.useMemo)(()=>(function(e,t,n){let r=new Map;for(let i of e){let e=k(i);if(!e)continue;let o=r.get(e);o||(o={running:0,unread:0},r.set(e,o)),t.has(i.id)&&o.running++,n.has(i.id)&&o.unread++}return r})(U,th,tm),[U,th,tm]),na=(0,i.useMemo)(()=>[...nl.entries()].some(e=>{let[t,{running:n,unread:r}]=e;return t!==nt?.key&&!F.has(t)&&(n>0||r>0)}),[F,nl,nt]),nd=(0,i.useMemo)(()=>nt?S(U,nt.key):U,[U,nt]),nc=!!(ej?.isGit&&ej.isTopLevel&&X&&nt?.key===ej.projectKey),nu=X&&ej&&nt?.key===ej.projectKey&&!nc?ej.isGit?{label:A("sidebar.openRepoRoot"),title:A("sidebar.openRepoRootTitle")}:{label:A("sidebar.gitRepoRootOnly"),title:A("sidebar.gitRepoRootOnlyTitle")}:null,np=!!(X&&eY===X),nh=nu??(np&&!nc?{label:A("sidebar.worktrees"),title:A("sidebar.checkingWorktrees")}:null),nf=(0,i.useMemo)(()=>h(nd,W.sessions),[nd,W.sessions]),nm=(0,i.useMemo)(()=>(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:-1,i=Math.ceil((n||600)/54)+16,o=Math.max(0,Math.min(Math.floor(t/54)-8,e-i)),s=Math.min(e,o+i),l=Array.from({length:s-o},(e,t)=>o+t);return r>=0&&r<o&&l.unshift(r),r>=s&&r<e&&l.push(r),l})(nf.length,tz,tR,nf.findIndex(e=>e.root.id===tW)),[tW,tz,tR,nf]);return(0,r.jsxs)("div",{ref:tM.panelRef,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden","--sidebar-session-pane-height":`${tM.width}px`},children:[ea&&(0,r.jsx)(D,{initialPath:ec,busy:eg,error:ef,onCancel:()=>{ed(!1),em(null)},onSelect:e=>void t4(e)}),(0,r.jsxs)("div",{style:{padding:"12px 10px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10},children:[(0,r.jsx)(eq,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsxs)("button",{onClick:nr,disabled:!X,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,background:"var(--bg-hover)",border:"1px solid var(--border)",color:X?"var(--text-muted)":"var(--text-dim)",cursor:X?"pointer":"not-allowed",height:32,paddingLeft:10,paddingRight:12,borderRadius:7,fontSize:12,fontWeight:500,letterSpacing:"-0.01em",flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},title:X?A("sidebar.newSessionTitle",{path:X}):A("sidebar.selectProject"),onMouseEnter:e=>{X&&(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=X?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,r.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]}),A("sidebar.new")]}),(0,r.jsx)("button",{type:"button",onClick:()=>{e7(e=>!e),eS(!1)},title:A("sidebar.toggleSessionSearch"),"aria-label":A("sidebar.toggleSessionSearch"),"aria-expanded":e9,"aria-controls":"session-search-input",className:`flex h-[32px] w-[32px] shrink-0 cursor-pointer items-center justify-center rounded-[7px] border border-border hover:bg-bg-selected focus-visible:outline-2 focus-visible:outline-accent ${e9?"bg-bg-selected text-accent":"bg-bg-hover text-text-muted"}`,children:(0,r.jsxs)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]})})]})]}),(0,r.jsxs)("div",{ref:ey,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>er(e=>!e),title:nt?.root??X??"",style:{width:"100%",display:"flex",alignItems:"center",padding:"6px 10px",background:X?"var(--bg-hover)":"rgba(37,99,235,0.06)",border:X?"1px solid var(--border)":"1px solid rgba(37,99,235,0.4)",borderRadius:7,cursor:"pointer",fontSize:12,color:"var(--text)",textAlign:"left",transition:"border-color 0.15s, background 0.15s"},children:[X?(0,r.jsx)(eH,{text:eD(nt?.root??X,ee),style:{flex:1,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text)"}}):(0,r.jsx)("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:s&&!tV.current?"":A("sidebar.selectProject")}),na&&(0,r.jsx)("span",{title:A("sidebar.newActivity"),"aria-label":A("sidebar.newActivity"),style:{width:8,height:8,borderRadius:"50%",flexShrink:0,marginLeft:6,background:"var(--accent)"}})]}),(0,r.jsxs)(e_,{open:en,style:{position:"absolute",top:"calc(100% + 4px)",left:0,right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 6px 20px rgba(0,0,0,0.10)",overflow:"hidden"},children:[no&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:ei,onChange:e=>eo(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eo(""),er(!1))},placeholder:A("sidebar.filterProjects"),autoFocus:!0,style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{maxHeight:"min(50vh, 380px)",overflowY:"auto"},children:[ns.map(e=>{var t,n;return(0,r.jsxs)("button",{onClick:()=>{Q(e.root),eo(""),ed(!1),em(null),er(!1)},style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"var(--bg)",border:"none",borderBottom:"1px solid var(--border)",color:e.key===nt?.key?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.root,children:[e.key===nt?.key&&(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"})}),e.key!==nt?.key&&(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)(eH,{text:eD(e.root,ee),style:{flex:1}}),(t=nl.get(e.key),n=A,t&&(0!==t.running||0!==t.unread)?(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,flexShrink:0,marginLeft:6},children:[t.running>0&&(0,r.jsxs)("span",{title:n("sidebar.agentRunning"),"aria-label":`${n("sidebar.agentRunning")} (${t.running})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,r.jsxs)("g",{children:[(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"}),(0,r.jsx)("animateTransform",{attributeName:"transform",type:"rotate",from:"0 12 12",to:"360 12 12",dur:"0.9s",repeatCount:"indefinite"})]})}),t.running]}),t.unread>0&&(0,r.jsxs)("span",{title:n("sidebar.newSessionActivity"),"aria-label":`${n("sidebar.newSessionActivity")} (${t.unread})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"#0891b2",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"currentColor",display:"inline-block"}}),t.unread]})]}):null),(0,r.jsx)(eI,{as:"span",variant:"inline",kind:"project",id:e.key,pinned:W.projects.has(e.key),onToggle:O}),(0,r.jsx)(eR,{as:"span",id:e.key,archived:!1,onToggle:_})]},e.key)}),0===ns.length&&ei.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:A("sidebar.noMatchingProjects")})]}),!ea&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),t3()},style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",borderTop:ns.length>0?"1px solid var(--border)":"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("path",{d:"M1 3A1 1 0 0 1 2 2H4L5 3.5H8.5a.5.5 0 0 1 .5.5v4a.5.5 0 0 1-.5.5h-7A.5.5 0 0 1 1 8V3Z"})}),(0,r.jsx)("span",{children:A("sidebar.useDefaultDirectory")})]}),(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),t8()},style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{children:A("sidebar.customPath")})]})]})]}),e9&&(0,r.jsx)("input",{id:"session-search-input",type:"search",autoFocus:!0,value:te,maxLength:200,"aria-label":A("sidebar.searchSessions"),placeholder:A("sidebar.searchSessions"),onChange:e=>tt(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),tt(""))},className:"mt-[6px] block h-[29px] w-full min-w-0 rounded-[7px] border border-border bg-bg px-[10px] text-xs text-text focus:outline-2 focus:outline-accent"}),!e9&&nc&&(()=>{if(!ej)return null;let e=ej.worktrees.length>=8,t=e&&es.trim()?ej.worktrees.filter(e=>(e.branch??eD(e.path,ee)).toLowerCase().includes(es.trim().toLowerCase())):ej.worktrees;return(0,r.jsxs)("div",{ref:eX,style:{position:"relative",marginTop:6},children:[(0,r.jsxs)("button",{onClick:()=>eS(e=>!e),title:t1?A("sidebar.switchWorktreeTitle",{path:t1.path}):A("sidebar.switchWorktree"),style:{width:"100%",height:29,boxSizing:"border-box",display:"flex",alignItems:"center",gap:6,padding:"0 10px",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:7,cursor:"pointer",fontSize:11,lineHeight:1.35,color:"var(--text-muted)",textAlign:"left"},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,color:t1&&!t1.isMain?"var(--accent)":"var(--text-dim)"},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)(eH,{text:t1?t1.branch??eD(t1.path,ee):"…",style:{flex:1,fontFamily:"var(--font-mono)",color:"var(--text)"}}),t1?.isMain&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:A("sidebar.main")}),ej.worktrees.length>1&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:ej.worktrees.length}),(0,r.jsx)("svg",{width:"9",height:"9",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),(0,r.jsxs)(e_,{open:ew,style:{position:"absolute",top:"calc(100% + 4px)",left:0,right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 6px 20px rgba(0,0,0,0.10)",overflow:"hidden"},children:[e&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:es,onChange:e=>el(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(el(""),eS(!1))},placeholder:A("sidebar.filterWorktrees"),autoFocus:!0,style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[t.map(e=>{let t=e.path===t2;return eK===e.path?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.06)"},children:[(0,r.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:A("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void t6(e.path,!0),disabled:eU,style:{padding:"3px 9px",background:"#ef4444",border:"none",borderRadius:5,color:"#fff",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:A("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>eV(null),style:{padding:"3px 9px",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer",flexShrink:0},children:A("sidebar.cancel")})]},e.path):(0,r.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("button",{onClick:()=>{Q(e.path),eS(!1),eM(null),el("")},title:e.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},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},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)(eH,{text:e.branch??eD(e.path,ee),style:{flex:1}}),e.isMain&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:A("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void t6(e.path,!1),disabled:eU,title:A("sidebar.removeWorktreeTitle",{path:e.path}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:34,height:28,padding:0,marginRight:4,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",borderRadius:5,flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="#ef4444",e.currentTarget.style.background="rgba(239,68,68,0.08)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(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)("polyline",{points:"3 6 5 6 21 6"}),(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"})]})})]},e.path)}),e&&0===t.length&&es.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:A("sidebar.noMatchingWorktrees")})]}),eC?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:eQ,value:eN,onChange:e=>{e$(e.target.value),eM(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),t5()),"Escape"===e.key&&(eE(!1),e$(""),eM(null))},placeholder:A("sidebar.branchName"),style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,r.jsx)("button",{onClick:()=>void t5(),disabled:eU||!eN.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:5,color:"var(--accent-contrast)",fontSize:11,fontWeight:600,cursor:eU||!eN.trim()?"not-allowed":"pointer",opacity:eU||!eN.trim()?.65:1},children:eU?A("sidebar.creating"):A("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{eE(!1),e$(""),eM(null)},style:{flex:1,padding:"4px 0",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer"},children:A("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),eE(!0),eM(null),setTimeout(()=>eQ.current?.focus(),0)},title:A("sidebar.createWorktreeTitle"),style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{children:A("sidebar.newWorktree")})]}),eT&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"#dc2626",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:eT})]})]})})(),!e9&&nh&&(0,r.jsxs)("button",{type:"button","aria-disabled":"true",tabIndex:-1,title:nh.title,style:{width:"100%",height:29,boxSizing:"border-box",marginTop:6,display:"flex",alignItems:"center",gap:6,padding:"0 10px",border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-hover)",color:"var(--text-dim)",fontSize:11,lineHeight:1.35,whiteSpace:"nowrap",textAlign:"left",cursor:"default",opacity:.82},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)("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",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:nh.label})]})]}),(0,r.jsx)("div",{ref:tE,style:{display:"flex",flexDirection:"column",flex:e0&&(v||X)?"0 1 var(--sidebar-session-pane-height, 320px)":"1 1 auto",minHeight:80,overflow:"hidden"},children:(0,r.jsx)(eh,{open:e9,query:te,selectedSessionId:t,onSelectSession:t9,children:(0,r.jsxs)("div",{ref:tS,onScroll:tD,className:"scrollbar-subtle",style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"0"},children:[V&&(0,r.jsx)("div",{style:{padding:"16px 14px",color:"var(--text-muted)",fontSize:12},children:A("sidebar.loading")}),Y&&(0,r.jsx)("div",{style:{padding:"12px 14px",color:"#f87171",fontSize:12},children:Y}),!V&&!Y&&0===nf.length&&(0,r.jsx)("div",{style:{padding:"16px 14px",color:"var(--text-muted)",fontSize:12},children:A("sidebar.noSessions")}),nf.length>0&&(0,r.jsx)("div",{style:{position:"relative",height:54*nf.length},children:nm.map(e=>{let n=nf[e],i=[n.root,...n.subagents],o=n.latestModified===n.root.modified?n.root:{...n.root,modified:n.latestModified};return(0,r.jsx)("div",{onFocus:()=>tP(n.root.id),onBlur:()=>tP(null),style:{position:"absolute",top:54*e,left:0,right:0},children:(0,r.jsx)(eJ,{session:o,isSelected:i.some(e=>e.id===t),isRunning:i.some(e=>th.has(e.id)),isUnread:i.some(e=>tm.has(e.id)),onClick:()=>t9(n.root),onRenamed:tH,onDeleted:e=>{x?.(e),tH()},pinned:W.sessions.has(n.root.id),onTogglePin:O})},n.root.id)})})]})})}),e0&&(v||X)&&(0,r.jsx)("div",{className:`sidebar-section-resize-handle${tM.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar-sections",title:`${A("layout.resizeSidebarSections")}: ${A("layout.resizeHeightHint")}`,style:{position:"relative",zIndex:20,width:"100%",height:12,margin:"-6px 0",flex:"0 0 12px",cursor:"row-resize",touchAction:"none"},...tM.separatorProps}),(v||X)&&(0,r.jsxs)("div",{ref:tN,style:{borderTop:"1px solid var(--border)",display:"flex",flexDirection:"column",flex:e0?"1 1 0":"0 0 auto",minHeight:120*!!e0,overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexShrink:0},children:[(0,r.jsxs)("button",{onClick:()=>e1(e=>{let t=!e;return!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:m();if(t)try{t.setItem(f,String(e))}catch{}}(t),t}),style:{display:"flex",alignItems:"center",gap:6,flex:1,padding:"6px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:600,letterSpacing:"0.05em",textTransform:"uppercase",textAlign:"left"},children:[(0,r.jsx)("svg",{width:"9",height:"9",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:e0?"rotate(90deg)":"none",transition:"transform 0.15s",flexShrink:0},children:(0,r.jsx)("polyline",{points:"3 2 7 5 3 8"})}),A("files.explorer")]}),(0,r.jsx)(eP,{onClick:()=>{tU()},disabled:tZ,title:tZ?A(td?.reason==="remote"?"sidebar.openInExplorerRemoteOnly":"sidebar.openInExplorerUnsupported"):tq,color:"var(--text-dim)",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:"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"})})}),j&&(0,r.jsx)(eP,{onClick:()=>j(X??v),title:A("terminal.open"),color:"var(--text-dim)",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}),e0&&tr>0&&(0,r.jsx)(eP,{onClick:()=>ts(e=>!e),title:A("sidebar.changedFiles",{count:tr}),ariaPressed:!to,color:to?"var(--text-dim)":"var(--accent)",background:to?"none":"var(--bg-selected)",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)("circle",{cx:"12",cy:"12",r:"3"}),(0,r.jsx)("path",{d:"M3 12h6"}),(0,r.jsx)("path",{d:"M15 12h6"})]})}),e0&&(0,r.jsx)(eP,{onClick:()=>{e6(e=>!e)},title:A("sidebar.searchFiles"),ariaPressed:e5,color:e5?"var(--accent)":"var(--text-dim)",background:e5?"var(--bg-selected)":"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",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]})}),e0&&(0,r.jsx)(eP,{onClick:()=>tw.current?.openUploadPicker(),disabled:e8,title:A("sidebar.uploadFilesTitle"),color:"var(--text-dim)",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 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"})]})}),(0,r.jsx)(eP,{onClick:()=>{N?N():e4(e=>e+1),ta(!0),tk.current&&clearTimeout(tk.current),tk.current=setTimeout(()=>ta(!1),2e3)},title:A("sidebar.refreshExplorer"),skipHover:tl,color:tl?"#4ade80":"var(--text-dim)",background:tl?"rgba(74,222,128,0.18)":"none",marginRight:6,children:tl?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",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"})]})})]}),tK&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,padding:"0 10px 6px",fontSize:10,lineHeight:1.35,color:"#f87171"},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflowWrap:"anywhere"},children:tK}),(0,r.jsx)(H,{onClick:()=>tp(null),title:A("files.dismissError")})]}),e0&&(0,r.jsx)("div",{ref:tC,className:"scrollbar-subtle",style:{flex:1,overflowY:"auto",overflowX:"hidden"},children:(0,r.jsx)(ep,{ref:tw,cwd:X??v,onOpenFile:y??(()=>{}),refreshKey:e2,onAtMention:I,onAtMentions:M,onUploadBusyChange:e3,changesCollapsed:to,onChangesCountChange:ti,fileSearchOpen:e5,onFileSearchOpenChange:e6})})]})]})}function eK(){let{t:e}=(0,E.s)();return(0,r.jsx)("span",{title:e("sidebar.agentRunning"),"aria-label":e("sidebar.agentRunning"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,r.jsxs)("g",{children:[(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"}),(0,r.jsx)("animateTransform",{attributeName:"transform",type:"rotate",from:"0 12 12",to:"360 12 12",dur:"0.9s",repeatCount:"indefinite"})]})})})}function eV(){let{t:e}=(0,E.s)();return(0,r.jsx)("span",{title:e("sidebar.newActivity"),"aria-label":e("sidebar.newSessionActivity"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"#0891b2"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",style:{display:"block"},children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"2.5",fill:"currentColor"}),(0,r.jsxs)("circle",{cx:"7",cy:"7",r:"3",stroke:"currentColor",strokeWidth:"1.4",opacity:"0.32",children:[(0,r.jsx)("animate",{attributeName:"r",values:"3;6;3",dur:"1.6s",repeatCount:"indefinite"}),(0,r.jsx)("animate",{attributeName:"opacity",values:"0.32;0;0.32",dur:"1.6s",repeatCount:"indefinite"})]})]})})}function eJ(e){let{session:t,isSelected:n,isRunning:o,isUnread:s,onClick:l,onRenamed:a,onDeleted:d,depth:c=0,hasChildren:u=!1,collapsed:p=!1,onToggleCollapse:h,pinned:f=!1,onTogglePin:m}=e,{locale:g,t:v}=(0,E.s)(),[b,y]=(0,i.useState)(!1),[j,k]=(0,i.useState)(!1),[w,S]=(0,i.useState)(""),[N,I]=(0,i.useState)(!1),[$,T]=(0,i.useState)(!1),M=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(j){let e=requestAnimationFrame(()=>M.current?.select());return()=>cancelAnimationFrame(e)}},[j]);let R=x(t.firstMessage)??t.firstMessage,L=t.name||R.slice(0,50)||t.id.slice(0,12),z=(0,i.useCallback)(e=>{e.stopPropagation(),t.transient||(S(t.name||R.slice(0,50)||t.id.slice(0,12)),k(!0))},[t.name,t.transient,R,t.id]),A=(0,i.useCallback)(async()=>{let e=w.trim();if(k(!1),w!==L&&e!==(t.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(t.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e})}),a?.()}catch{}},[w,t.id,t.name,a,L]),W=(0,i.useCallback)(async()=>{if(!t.transient){I(!1),T(!0);try{await fetch(`/api/sessions/${encodeURIComponent(t.id)}`,{method:"DELETE"}),d?.(t.id)}catch{T(!1)}}},[t.id,t.transient,d]),P=(0,i.useCallback)(e=>{e.stopPropagation(),e.shiftKey?W():I(!0)},[W]),O=(0,i.useCallback)(e=>{e.stopPropagation(),W()},[W]),F=(0,i.useCallback)(e=>{e.stopPropagation(),I(!1)},[]),B=(0,i.useCallback)(e=>{(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:t.id,path:t.path,cwd:t.cwd,name:t.name,clientX:e.clientX,clientY:e.clientY,refresh:()=>{a?.()}})&&(e.preventDefault(),e.stopPropagation())},[a,t.cwd,t.id,t.name,t.path]);return(0,r.jsx)("div",{onClick:N||j?void 0:l,onContextMenu:N||j?void 0:B,onMouseEnter:()=>y(!0),onMouseLeave:()=>{y(!1)},style:{height:54,display:"flex",alignItems:"center",paddingLeft:c>0?12*c+14:14,paddingRight:8,cursor:N||j?"default":"pointer",background:N?"rgba(239,68,68,0.06)":n?"var(--bg-selected)":b?"var(--bg-hover)":"transparent",borderLeft:N?"2px solid #ef4444":n?"2px solid var(--accent)":"2px solid transparent",transition:"background 0.1s",opacity:$?.5:1,gap:6,overflow:"hidden"},children:N?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v("sidebar.deleteSession",{title:L.slice(0,22)+(L.length>22?"…":"")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,r.jsxs)("button",{onClick:O,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,height:30,padding:"0 11px",background:"#ef4444",border:"none",borderRadius:6,color:"#fff",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap"},children:[(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)("polyline",{points:"3 6 5 6 21 6"}),(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"})]}),v("sidebar.delete")]}),(0,r.jsx)("button",{onClick:F,style:{display:"flex",alignItems:"center",justifyContent:"center",height:30,padding:"0 11px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:500,whiteSpace:"nowrap"},children:v("sidebar.cancel")})]})]}):j?(0,r.jsx)("input",{ref:M,value:w,onChange:e=>S(e.target.value),onBlur:A,onKeyDown:e=>{"Enter"===e.key&&A(),"Escape"===e.key&&k(!1)},autoFocus:!0,style:{flex:1,fontSize:12,padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",height:30}}):(0,r.jsxs)(r.Fragment,{children:[c>0&&(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]}),(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:5,minWidth:0,fontSize:12,fontWeight:n?500:400,lineHeight:1.4,color:"var(--text)"},title:L,children:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:L})}),(0,r.jsxs)("div",{style:{marginTop:2,display:"flex",alignItems:"center",gap:8,color:"var(--text-dim)",fontSize:11,minWidth:0},children:[o?(0,r.jsx)(eK,{}):s?(0,r.jsx)(eV,{}):(0,r.jsx)("span",{title:t.modified,children:(0,C.fw)(t.modified,g)}),(0,r.jsx)("span",{children:t.detailsPending?"…":v("sidebar.messagesCount",{count:t.messageCount})}),t.isWorktree&&t.branch&&(0,r.jsxs)("span",{title:`Worktree: ${t.cwd}`,style:{display:"flex",alignItems:"center",gap:3,color:"var(--accent)",minWidth:0,overflow:"hidden"},children:[(0,r.jsxs)("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.branch})]})]})]}),u&&(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),h?.()},title:v(p?"sidebar.expandSubagents":"sidebar.collapseSubagents"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",transform:p?"rotate(-90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),m&&(0,r.jsx)(eI,{kind:"session",id:t.id,pinned:f,hovered:b,onToggle:m}),b&&!t.transient&&(0,r.jsxs)("div",{style:{display:"flex",gap:4,flexShrink:0},children:[(0,r.jsx)("button",{onClick:z,title:v("sidebar.rename"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:7,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"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)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),(0,r.jsx)("button",{onClick:P,title:v("sidebar.deleteWithShiftClick"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:7,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)",e.currentTarget.style.color="#ef4444",e.currentTarget.style.borderColor="rgba(239,68,68,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.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(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"})]})})]})]})})}var eY=n(5772);let eG=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,eX=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,eQ=/\x1B_pi:c\x07/g;function e0(e){return e.replace(eQ,"").replace(eG,"")}function e1(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(eX);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 e2(e,t){let n=e1(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function e4(e){return e1(e)[0]?.char}let e8={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:""},e3={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"};function e5(e){return"user"===e.role||"custom"===e.role&&("compaction"===e.customType||"pi-web:subagent-notification"===e.customType)}function e6(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===e.thinking.trim()}function e9(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return(e.content??[]).filter(e=>!e6(e,t))}function e7(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 te(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return!t.isStreaming&&"length"===e.stopReason}function tt(e){return(e.content??[]).some(e=>"text"===e.type?e.text.trim().length>0:"image"===e.type||"toolCall"===e.type)}function tn(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e9(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 tr(e){return!e.defaultPrevented&&0===e.button&&!e.shiftKey&&!e.altKey}function ti(e){try{return decodeURIComponent(e)}catch{return e}}function to(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function ts(e){let t=to(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),i=t.startsWith("/")&&!n&&!r,o=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){o.length>0&&".."!==o[o.length-1]?o.pop():i||n||r||o.push(e);continue}o.push(e)}let s=o.join("/");return n?s:r?`//${s}`:i?`/${s}`:s}function tl(e,t){let n,r,i,o,s,l=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=ti(a),p=u.startsWith("\\\\"),h=to(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=ti(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)||h.startsWith("/")?(d=h,c="absolute"):t&&!(h.startsWith("#")||h.startsWith("?"))&&(h.startsWith("./")||h.startsWith("../")||h.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(h))&&(d=`${to(t).replace(/\/+$/,"")}/${h}`,c="relative"),!d)return null;let m=ts(d).replace(/:\d+(?::\d+)?$/,"");return"relative"===c&&l&&(n=ts(m).replace(/\/+$/,""),r=ts(l).replace(/\/+$/,""),o=(i=/^[a-zA-Z]:\//.test(n)||/^[a-zA-Z]:\//.test(r))?n.toLowerCase():n,!(o===(s=i?r.toLowerCase():r)||o.startsWith(`${s}/`)))?null:m}let ta=/^page=(\d+)$/i;function td(e){if(!e)return null;let t=e.indexOf("#");if(-1===t)return null;let n=e.slice(t+1).trim().match(ta);if(!n)return null;let r=Number.parseInt(n[1],10);return Number.isInteger(r)&&r>0?r:null}function tc(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 tu(e){let t=e.toLowerCase();return"apply_patch"===t||t.startsWith("apply_patch_")||t.endsWith(".apply_patch")||t.endsWith("_apply_patch")}function tp(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 th(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function tf(e){if(!th(e)||!th(e.result))return!1;let t=e.result.failures;return Array.isArray(t)&&t.length>0}function tm(){let e=[],t=[],n=[],r=()=>({lineNo:null,text:"",type:"empty"}),i=()=>{let i=Math.max(t.length,n.length);for(let o=0;o<i;o++)e.push({type:"line",left:t[o]??r(),right:n[o]??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"})},finish(){i();for(let t=e.length-1;t>=0;t--)"line"!==e[t].type&&e.splice(t,1)}}}function tg(e){if(!e.includes("*** Begin Patch")&&!/\*\*\* (?:Add|Delete|Update) File: /.test(e))return null;let t=[],n=null,r=null,i=null;for(let o of e.split(/\r?\n/)){let e=o.match(/^\*\*\* (Add|Delete|Update) File: (.+)$/);if(e){let o=e[1]?.toLowerCase()??"update",s=(e[2]??"").trim();n?.finish(),i=o,r={oldPath:"add"===o?void 0:s,newPath:"delete"===o?void 0:s,rows:(n=tm()).rows},t.push(r);continue}if(/^\*\*\* Move to: /.test(o)){let e=o.replace(/^\*\*\* Move to: /,"").trim();r&&"update"===i&&(r.newPath=e);continue}if(!n||!r)continue;let s=n;if(!o.startsWith("*** ")&&!("update"===i&&o.startsWith("@@"))){if("update"===i){let e=o[0],t=o.slice(1);"+"===e?s.added(t,null):"-"===e?s.removed(t,null):" "===e?s.context(t,null):""!==o&&s.context(o,null)}else if("add"===i){if(""===o)continue;n.added(o.startsWith("+")?o.slice(1):o,null)}else if("delete"===i){if(""===o)continue;n.removed(o.startsWith("-")?o.slice(1):o,null)}}}n?.finish();let o=t.filter(e=>e.rows.length>0);return o.length>0?o:null}function tx(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=tm();for(let n of e.diff.split(/\r?\n/)){let e=n.match(/^([+\- ])\s*(\d+) (.*)$/);if(!e)continue;let[,r,i,o]=e,s=Number(i);"+"===r?t.added(o,s):"-"===r?t.removed(o,s):t.context(o,s)}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 tv(e){return e?e.map(e=>e.newPath).filter(e=>"string"==typeof e&&e.length>0):[]}function tb(e,t,n){let r=e.trim().split("\n").map(e=>`> ${e}`).join("\n");return`${t}
2
-
3
- ${r}
4
-
5
- ${n}`}var ty=n(32316),tj=n(88374),tk=n(5924),tw=n(94764),tS=n(63835),tC=n(54152),tE=n(31678),tN=n(98164);let tI={...tw.j,attributes:{...tw.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},protocols:{...tw.j.protocols,href:[...tw.j.protocols?.href??[],"file"]},strip:[...tw.j.strip||[],"iframe","object","style","form"]};function t$(e){return/^file:/i.test(e)?e:(0,ty.Lv)(e)}function tT(e,t,n,r,i){let o="",s=0;for(let l=e.indexOf(t);-1!==l;l=e.indexOf(t,l+1)){if(l>0&&n.includes(e[l-1]))continue;r.lastIndex=l;let t=r.exec(e);t&&(o+=e.slice(s,l)+i(t),l=(s=r.lastIndex)-1)}return o+e.slice(s)}let tM=/`((?:[^`\n]|\\`)*?[^\\`\n])`(?!`)/y;function tR(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,o=0,s=null,l=new Map;for(let e=0;e<n.length;e++){var a,d;let t=n[e];if(s){r.push(t),RegExp(`</${s}\\s*>`,"i").test(t)&&(s=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&&(i=null):i={marker:e,size:n},o=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)||(s=e),o=0,r.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){o=0,r.push(t);continue}if(o||(t=tT(t,"`","\\`",tM,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}`})),o||t.includes("`")){o=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,o),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=>tz(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 o=tL(n,e+1,t,l);if(o){r.push(`${t}$$`,`${t}${i}`);for(let i=e+1;i<o.index;i++)r.push(tz(n[i],t));o.content&&r.push(`${t}${o.content}`),r.push(`${t}$$`),e=o.index;continue}}}let x=t.match(/^([ \t]{0,3})\$\$\s*$/);if(x){let t=x[1],i=tL(n,e+1,t,l);if(i&&(i.glued||""!==t)){r.push(`${t}$$`);for(let o=e+1;o<i.index;o++)r.push(tz(n[o],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:tT(d,"\\(","\\",tA,e=>{let[t,n]=e;return n.trim()?`$${n}$`:t})))}return r.join(t)}function tL(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 o,s,l,a;let t=e[i];if(o=t,""===(s=n)?/^ {0,3}\$\$\s*$/.test(o):o.startsWith(s)&&/^\$\$\s*$/.test(o.slice(s.length)))return{index:i,content:"",glued:!1};if(l=t,/^ {0,3}(`{3,}|~{3,})/.test(l)||/^[ \t]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/.test(l)||/^ {0,3}#{1,6}(?:[ \t]+|$)/.test(l)||/^ {0,3}>/.test(l)||/<(code|pre|script|style)\b/i.test(l)||(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 tz(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 tA=/\\\(([^`\r\n$]*?[^`\r\n$\\])\\\)/y,tW={singleTilde:!1},tP=/[\u3001\u3002\u3008-\u3011\u3014-\u301B\uFF01\uFF08\uFF09\uFF0C\uFF1A\uFF1B\uFF1F\u2018\u2019\u201C\u201D\u2013\u2014\u2026\u00B7\uFF5E\u301C]/;function tO(){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 o=n.position?.start,s=n.position?.end;if(o?.offset==null||s?.offset==null||r.slice(o.offset,s.offset)!==i.value)return;let l=i.value,a=l.search(tP);if(a<=0||!n.url.endsWith(l))return;let d=l.slice(0,a),c={line:o.line,column:o.column+a,offset:o.offset+a};n.url=n.url.slice(0,n.url.length-l.length)+d,i.value=d,n.position={start:o,end:c},e.splice(t+1,0,{type:"text",value:l.slice(a),position:{start:c,end:s}})}(t,e,i,n);let o=t[e];"children"in o&&Array.isArray(o.children)&&r(o)}})(e)}}let tF=function(){tN.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),o=null!==e&&e>=48&&e<=57,s=/^\s/.test(n)!==/\s$/.test(n);if(i&&(o||s))return r(e)}return n(e)},r)}}},tB=[[tC.A,["yaml"]],[tE.A,tW],tO,tF],tD=/[ \t]*(?:\r\n|\r|\n)[ \t]*/,tH=new Set(["paragraph","heading","tableCell"]),t_=/^<(?:iframe|noembed|noframes|noscript|plaintext|script|style|textarea|title|xmp)(?=[\s/>]|$)/i;function tU(){return{type:"lineBreak",data:{hName:"br"}}}let tq=[...tB??[],function(){return e=>(function e(t){!t.children||tH.has(t.type)&&function e(t){return"html"===t.type?t_.test(t.value??""):t.children?.some(e)??!1}(t)||(t.children=t.children.flatMap(t=>"break"===t.type?[tU()]:"text"===t.type&&t.value?t.value.split(tD).flatMap((e,t)=>[...t>0?[tU()]:[],...e?[{type:"text",value:e}]:[]]):(e(t),[t])))})(e)}],tZ=[[tC.A,["yaml"]],[tE.A,tW],tO,tF],tK=[tk.A,[tS.A,tI],[tj.A,{throwOnError:!1,strict:!1}]],tV=[tk.A,[tS.A,tI],[tj.A,{throwOnError:!1,strict:!1}]];function tJ(e){let{src:t,alt:n="",children:o,className:s,style:l}=e,{t:a}=(0,E.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:s,style:{display:"block",padding:0,border:"none",background:"none",color:"inherit",cursor:"zoom-in",...l},onClick:()=>p(!0),"aria-label":c,"aria-haspopup":"dialog","aria-expanded":u,title:d,children:o}),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 tY=n(65063),tG=n(7644);let tX=[{id:"light",label:"settings.themeLight"},{id:"dark",label:"settings.themeDark"},{id:"mist",label:"settings.themeMist"},{id:"rose",label:"settings.themeRose"},{id:"pine",label:"settings.themePine"},{id:"auto",label:"settings.themeSystem"}];function tQ(e){return"dark"===e||"pine"===e}let t0="pi-theme",t1={preference:"auto",theme:"light"},t2=new Set,t4=null,t8=!1;function t3(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function t5(e){return"auto"===e?t3():e}function t6(e){"u">typeof document&&(document.documentElement.dataset.theme=e,document.documentElement.classList.toggle("dark",tQ(e)))}function t9(){if(t4)return t4;let e=function(){try{let e=localStorage.getItem(t0);if(tX.some(t=>t.id===e))return e}catch{}return"auto"}(),t=t5(e);return t6(t),t4={preference:e,theme:t}}function t7(e,t,n){if(t6(t),n)try{localStorage.setItem(t0,e)}catch{}t4={preference:e,theme:t},t2.forEach(e=>e())}function ne(){let e=t9();if("auto"!==e.preference)return;let t=t3();t!==e.theme&&t7("auto",t,!1)}function nt(e){return t2.add(e),t9(),t8||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",ne),window.addEventListener("focus",ne),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&ne()}),t8=!0),ne(),()=>{t2.delete(e)}}function nn(){return t9()}function nr(){return t1}function ni(){let e=(0,i.useSyncExternalStore)(nt,nn,nr),t=(0,i.useCallback)((e,t)=>{if(t9().preference===e)return;let n=t5(e),r=()=>{t7(e,n,!0)},i=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||i)return void r();let o=t?.x??window.innerWidth/2,s=t?.y??window.innerHeight/2,l=Math.hypot(Math.max(o,window.innerWidth-o),Math.max(s,window.innerHeight-s));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${o}px ${s}px)`,`circle(${l}px at ${o}px ${s}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:tQ(e.theme)}}function no(e){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);try{let t=document.createElement("textarea");return t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),Promise.resolve()}catch{return Promise.reject()}}function ns(e){let{code:t,isStreaming:o,defaultPreview:s=!1}=e,{isDark:l}=ni(),{t:a}=(0,E.s)(),[d,c]=(0,i.useState)(s),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!1),m=(0,i.useRef)(null),g=`${l?"dark":"light"}
6
- ${t}`,x=d&&!o;(0,i.useEffect)(()=>{if(!x)return;let e=!1;return p({key:g,status:"loading"}),(async()=>{let{default:r}=await Promise.all([n.e(988),n.e(9425),n.e(3308)]).then(n.bind(n,43328));if(r.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:l?"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)}`,o=await r.render(i,t);e||p({key:g,status:"ready",svg:o.svg})})().catch(()=>{e||p({key:g,status:"error"})}),()=>{e=!0}},[t,g,l,x]);let v=(0,i.useMemo)(()=>(0,r.jsx)("button",{type:"button",onClick:()=>c(e=>!e),disabled:o,title:o?a("i18n.previewAfterStreaming"):x?a("i18n.showMermaidSource"):a("i18n.previewMermaid"),className:["markdown-code-action",x?"is-active":""].filter(Boolean).join(" "),children:x?a("i18n.source"):a("i18n.preview")}),[o,x,a]);if(!x)return(0,r.jsx)(na,{code:t,lang:"mermaid",headerAction:v,isStreaming:o});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)(nl,{svg:u.svg,onClose:()=>f(!1)})]});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:"mermaid"}),(0,r.jsxs)("div",{className:"markdown-code-actions",children:[u?.key===g&&"ready"===u.status&&(0,r.jsx)("button",{type:"button",className:"markdown-code-action",title:`${a("i18n.downloadFile")} (SVG)`,"aria-label":`${a("i18n.downloadFile")} (SVG)`,onClick:()=>{let e,t,n,r=m.current?.querySelector("svg");r&&(e=new XMLSerializer().serializeToString(r),t=URL.createObjectURL(new Blob([e],{type:"image/svg+xml;charset=utf-8"})),(n=document.createElement("a")).href=t,n.download="mermaid-diagram.svg",n.click(),setTimeout(()=>URL.revokeObjectURL(t),0))},children:"SVG"}),v]})]}),b]})}function nl(e){let{svg:t,onClose:n}=e,{t:o}=(0,E.s)(),s=(0,i.useRef)(null),[l,a]=(0,i.useState)(1);return(0,i.useEffect)(()=>{let e=s.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:s,className:"mermaid-zoom-dialog","aria-label":o("i18n.mermaidViewer"),onCancel:e=>{e.preventDefault(),n()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),n())},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:o("i18n.mermaidDiagram")}),(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:()=>a(e=>Math.max(.5,e-.25)),disabled:l<=.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*l),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>a(e=>Math.min(3,e+.25)),disabled:l>=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:()=>a(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:n,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&&n()},children:(0,r.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*l}%`},dangerouslySetInnerHTML:{__html:t}})})]})})}let na=(0,i.memo)(function(e){let{code:t,lang:n,headerAction:o,isStreaming:s}=e,{isDark:l}=ni(),{t:a}=(0,E.s)(),[d,c]=(0,i.useState)(!1);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:n||"text"}),(0,r.jsxs)("div",{className:"markdown-code-actions",children:[o,(0,r.jsx)("button",{onClick:()=>{no(t).then(()=>{c(!0),setTimeout(()=>c(!1),1500)})},className:"markdown-code-action",children:a(d?"i18n.copied":"i18n.copy")})]})]}),s?(0,r.jsx)("pre",{style:{margin:0,padding:"11px 13px",fontSize:"calc(12.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.62,overflowX:"auto",background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},children:(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:t})}):(0,r.jsx)(tY.A,{language:n||"text",style:l?tG.xJ:tG.vs,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-dim)",fontStyle:"normal"},customStyle:{margin:0,padding:"11px 13px",fontSize:"calc(12.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.62,border:"none",borderRadius:0,background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:t})]})}),nd=(0,i.createContext)(!1);function nc(e){let{src:t,alt:n,cwd:o,...s}=e,l=(0,i.useContext)(nd);delete s.node;let a="string"==typeof t?t:void 0,d=a?tl(a,o):null,c=d?`/api/files/${Y(d)}?type=read`:a,u=(0,r.jsx)("img",{src:c,alt:n??"",loading:"lazy",...s});return!c||l?u:(0,r.jsx)(tJ,{src:c,alt:n??"",className:"markdown-image",children:u})}function nu(e){let{children:t,className:n,isStreaming:o,cwd:s,onOpenFile:l,keepLineBreaks:a}=e,d=(0,i.useMemo)(()=>tR(t),[t]),c=(0,i.useMemo)(()=>({code(e){let{className:t,children:n,...i}=e,s=t?.replace("language-","").toLowerCase()??"",l=String(n);return t?.includes("language-")||l.includes("\n")?"mermaid"===s?(0,r.jsx)(ns,{code:l.replace(/\n$/,""),isStreaming:o,defaultPreview:!0}):(0,r.jsx)(na,{code:l.replace(/\n$/,""),lang:s,isStreaming:o}):(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;delete i.node;let o=l?tl(t,s):null;return o&&l?(0,r.jsx)(nd.Provider,{value:!0,children:(0,r.jsx)("a",{href:t,...i,onClick:e=>{if(!tr(e))return;let n=e.currentTarget.getAttribute("target");n&&"_self"!==n||(e.preventDefault(),l(o,td(t)??void 0))},children:n})}):(0,r.jsx)(nd.Provider,{value:!0,children:(0,r.jsx)("a",{href:t,...i,target:"_blank",rel:"noopener noreferrer",children:n})})},img:e=>(0,r.jsx)(nc,{cwd:s,...e}),table(e){let{children:t}=e;return(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:t})})}}),[s,o,l]);return(0,r.jsx)("div",{className:["markdown-body",n].filter(Boolean).join(" "),children:(0,r.jsx)(ty.oz,{remarkPlugins:a?tq:tB,rehypePlugins:tK,urlTransform:l?t$:void 0,components:c,children:d})})}function np(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 nh=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,nf=/(?:\r?\n){2,}((?:[ \t]*<(?:read-files|modified-files)>[ \t]*\r?\n[\s\S]*?\r?\n[ \t]*<\/(?:read-files|modified-files)>[ \t]*(?:\r?\n)?)+)\s*$/;function nm(e){let t,n=[],r=null,i=0,o=0,s=0,l=0,a=[],d=[],c=()=>({lineNo:null,text:"",type:"empty"}),u=()=>{if(!r){a=[],d=[];return}let e=Math.max(a.length,d.length);for(let t=0;t<e;t++){let e=a[t]?{lineNo:a[t].lineNo,text:a[t].text,type:"removed"}:c(),n=d[t]?{lineNo:d[t].lineNo,text:d[t].text,type:"added"}:c();r.rows.push({type:"line",left:e,right:n})}a=[],d=[]};for(let c of e.split(/\r?\n/)){if(!(s>0||l>0)){if(c.startsWith("--- ")){u(),t=ng(c.slice(4));continue}if(c.startsWith("+++ ")){u(),r={oldPath:t,newPath:ng(c.slice(4)),rows:[]},n.push(r);continue}}let e=c.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){r||(r={rows:[]},n.push(r)),u(),i=Number(e[1]),o=Number(e[3]),s=void 0===e[2]?1:Number(e[2]),l=void 0===e[4]?1:Number(e[4]),r.rows.push({type:"hunk",text:c});continue}if(!r)continue;if(c.startsWith("\\ ")){u(),r.rows.push({type:"hunk",text:c});continue}let p=c[0],h=c.slice(1);" "===p?(u(),r.rows.push({type:"line",left:{lineNo:i++,text:h,type:"context"},right:{lineNo:o++,text:h,type:"context"}}),s>0&&s--,l>0&&l--):"-"===p?(a.push({lineNo:i++,text:h}),s>0&&s--):"+"===p?(d.push({lineNo:o++,text:h}),l>0&&l--):""!==c&&(u(),r.rows.push({type:"hunk",text:c}))}u();let p=n.filter(e=>e.rows.some(e=>"line"===e.type));return p.length>0?p:null}function ng(e){return e.split(" ")[0].trim()}let nx=new Set,nv="pi-thinking-expanded",nb="pi-thinking-expanded-changed";function ny(){return"true"===window.localStorage.getItem(nv)}function nj(e){let{files:t,onOpenFile:n}=e,{t:i}=(0,E.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,o=G(t);return(0,r.jsxs)("button",{type:"button",title:t,"aria-label":i("chat.openWrittenFile",{name:o}),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:[V(o,12),(0,r.jsx)("span",{children:o})]},t)})})}let nk="codemode",nw=new Set(["running","ok","error","cancelled"]);function nS(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function nC(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function nE(e){if(!nS(e)||!Array.isArray(e.calls))return{calls:[],omitted:0};let t=e.calls.flatMap(e=>{let t=function(e){if(!nS(e)||"string"!=typeof e.name)return null;let t="string"==typeof e.status&&nw.has(e.status)?e.status:"ok",n=nC(e.durationMs),r=nC(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=nC(e.omittedCalls);return{calls:t,omitted:void 0!==n&&n>0?Math.floor(n):0}}let nN=/^Script (completed|failed)\nWall time ([\d.]+) seconds\nOutput:\n$/;function nI(e){return`$${e>=.01?e.toFixed(2):e.toPrecision(2)}`}let n$={running:{icon:"…",color:"#d97706"},ok:{icon:"✓",color:"#16a34a"},error:{icon:"✗",color:"#f87171"},cancelled:{icon:"⊘",color:"var(--text-dim)"}};function nT(e){var t;let{call:n}=e,{t:i}=(0,E.s)(),o=n$[n.status],s=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:o.color,width:12,flexShrink:0,textAlign:"center"},children:o.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}),s&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",flexShrink:0,marginLeft:"auto",fontVariantNumeric:"tabular-nums"},children:s}),void 0!==n.cost&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:nI(n.cost)})]}),n.error&&(0,r.jsx)("div",{style:{color:"#f87171",paddingLeft:18,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n.error})]})}function nM(e){let t,{calls:n,omitted:o,isError:s}=e,{t:l}=(0,E.s)(),[a,d]=(0,i.useState)(!1);if(0===n.length&&0===o)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:s?"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:l("codemode.calls")}),o>0&&(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:l("codemode.omittedCalls",{count:o})}),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:l("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)(nT,{call:e},e.id||`${c+t}`))}),null!==p&&(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:l("codemode.modelCost",{cost:nI(p)})})]})}let nR=/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}\uac00-\ud7af]/u;function nL(e){let t=0,n=0;for(let r of e)nR.test(r)?t++:n++;return t+n/4}let nz=new Map;function nA(e){let{children:t,className:n,...o}=e,{t:s}=(0,E.s)(),[l,a]=(0,i.useState)(!1);if(t.length<=1e5)return(0,r.jsx)(nu,{className:n,...o,children:t});if(!l){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:["⚠ ",s("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 nW(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 o=t.toLocaleDateString([],{month:"short",day:"numeric",year:t.getFullYear()!==n.getFullYear()?"numeric":void 0});return`${o} ${i}`}let nP=(0,i.memo)(function(e){let{message:t,isStreaming:n,toolResults:i,modelNames:o,cwd:s,onOpenFile:l,onOpenSession:a,entryId:d,searchBlock:c,onFork:u,forking:p,onEditContent:h,onCancelEdit:f,isEditing:m,showTimestamp:g,prevTimestamp:x,sessionId:v,writtenFiles:b,onCompact:y,isCompacting:j,compactError:k}=e;return"user"===t.role?(0,r.jsx)(nO,{message:t,cwd:s,onOpenFile:l,entryId:d,onFork:u,forking:p,onEditContent:h,onCancelEdit:f,isEditing:m}):"assistant"===t.role?(0,r.jsx)(nF,{message:t,isStreaming:n,toolResults:i,modelNames:o,cwd:s,onOpenFile:l,onOpenSession:a,showTimestamp:g,prevTimestamp:x,sessionId:v,entryId:d,searchBlock:c,writtenFiles:b,onCompact:y,isCompacting:j,compactError:k}):"toolResult"===t.role?null:"custom"===t.role?"compaction"===t.customType?(0,r.jsx)(nQ,{message:t}):(0,r.jsx)(n2,{message:t,cwd:s,onOpenFile:l}):"bashExecution"===t.role?(0,r.jsx)(n5,{message:t,sessionId:v}):null},(e,t)=>e.message===t.message&&e.isStreaming===t.isStreaming&&function(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}(e.message,e.toolResults,t.toolResults)&&e.modelNames===t.modelNames&&e.cwd===t.cwd&&e.onOpenFile===t.onOpenFile&&e.onOpenSession===t.onOpenSession&&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.sessionId===t.sessionId&&e.onCompact===t.onCompact&&e.isCompacting===t.isCompacting&&e.compactError===t.compactError);function nO(e){let{message:t,cwd:n,onOpenFile:o,entryId:s,onFork:l,forking:a,onEditContent:d,onCancelEdit:c,isEditing:u}=e,{t:p}=(0,E.s)(),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(!1),[v,b]=(0,i.useState)(!1),y=("string"==typeof t.content?t.content:t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")).replace(/\r\n?/g,"\n"),j="string"==typeof t.content?[]:t.content.filter(e=>"image"===e.type),k=x(y),w=k?.search(/\s/)??-1,S=k?-1===w?k:k.slice(0,w):"",C=k&&-1!==w?k.slice(w+1):"",N=nW(t.timestamp),I=!!s&&!!l,$=k??y,T=k?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,k):t,M=j.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!y},children:j.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)(tJ,{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)})}),R=!!s&&!!d,L=!!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:k?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0},children:[M,(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexWrap:"wrap"},children:[(0,r.jsxs)("button",{onClick:()=>b(e=>!e),title:p(v?"i18n.collapse":"i18n.expand"),"aria-expanded":v,style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,padding:0,background:"none",border:"none",cursor:"pointer",color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",textAlign:"left"},children:[(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S}),(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:v?"rotate(180deg)":"none",transition:"transform 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),C&&(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:C})]}),v&&(0,r.jsx)(nu,{className:"markdown-user-message",keepLineBreaks:!0,cwd:n,onOpenFile:o,children:y})]}):(0,r.jsxs)(r.Fragment,{children:[M,y&&(0,r.jsx)(nA,{className:"markdown-user-message",keepLineBreaks:!0,cwd:n,onOpenFile:o,children:y})]})})}),(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:()=>{no($).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"})]}),p(m?"i18n.copied":"i18n.copy")]})}),(I||R||L)&&(0,r.jsxs)("div",{style:{display:"flex",gap:3,opacity:h||a||L?1:0,pointerEvents:h||a||L?"auto":"none",transition:"opacity 0.12s"},children:[R&&!L&&(0,r.jsxs)("button",{onClick:()=>d(T,s),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"})]}),p("i18n.editFromHere")]}),L&&(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"})}),p("i18n.cancel")]}),I&&(0,r.jsxs)("button",{onClick:()=>{l(s)},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"})]}),p(a?"i18n.creating":"i18n.newSession")]})]}),N&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:N})]})]})}function nF(e){var t,n,o;let s,l,a,d,c,u,{message:p,isStreaming:h,toolResults:f,modelNames:m,cwd:g,onOpenFile:x,onOpenSession:v,showTimestamp:b,prevTimestamp:y,sessionId:j,entryId:k,searchBlock:w,writtenFiles:S,onCompact:C,isCompacting:N,compactError:I}=e,{t:$}=(0,E.s)(),T=b?nW(p.timestamp):null,M=(0,i.useMemo)(()=>(p.content??[]).map((e,t)=>({block:e,originalIndex:t})).filter(e=>{let{block:t}=e;return!e6(t,{isStreaming:h})}),[p.content,h]),R=(0,i.useMemo)(()=>M.map(e=>{let{block:t}=e;return t}),[M]),L=e7(p,{isStreaming:h}),z=te(p,{isStreaming:h}),A=z&&!tt(p),[W,P]=(0,i.useState)(!1),[O,F]=(0,i.useState)(!1),B=(0,i.useRef)(null),[D,H]=(0,i.useState)(null),_=(0,i.useRef)(M);_.current=M;let U=(0,i.useRef)(new Map),q=(0,i.useMemo)(()=>{if(!h)return U.current=new Map,0;let e=new Map,t=0;for(let{block:n,originalIndex:r}of M){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 o=function(e,t){var n,r;if(!e||!t.startsWith(e.text))return nL(t);let i=e.tokens,o=e.text.length;return o>0&&o<t.length&&(n=e.text.charCodeAt(o-1))>=55296&&n<=56319&&(r=t.charCodeAt(o))>=56320&&r<=57343&&(i-=1/4,o--),i+nL(t.slice(o))}(U.current.get(r),i);e.set(r,{text:i,tokens:o}),t+=o}return U.current=e,t},[M,h]),Z=(0,i.useRef)(q);Z.current=q;let K=(0,i.useRef)(new Map),[V,J]=(0,i.useState)(new Map),Y=(0,i.useMemo)(()=>{if(!p.timestamp||!y)return;let e=Math.round((p.timestamp-y)/1e3);return e>0?e:void 0},[p.timestamp,y]),G=(0,i.useMemo)(()=>{let e=new Map;if(!f||!p.timestamp)return e;for(let[t,n]of f)if(n.timestamp&&p.timestamp){let r=Math.round((n.timestamp-p.timestamp)/1e3);r>0&&e.set(t,r)}return e},[f,p.timestamp]),X=R.filter(e=>"text"===e.type).map(e=>e.text).join("\n");if((0,i.useEffect)(()=>{if(!h){let e=new Date().getTime();J(t=>{let n=new Map(t);for(let[t,r]of K.current)n.has(t)||n.set(t,Math.round((e-r)/1e3));return n}),B.current=null,H(null);return}let e=setInterval(()=>{let e=_.current,t=Date.now();e.forEach(e=>{let{originalIndex:n}=e;K.current.has(n)||K.current.set(n,t)}),J(n=>{let r=!1,i=new Map(n);for(let n=0;n<e.length-1;n++){let o=e[n].originalIndex,s=e[n+1].originalIndex;if(!i.has(o)&&K.current.has(o)){let e=K.current.get(o),n=K.current.get(s)??t;i.set(o,Math.round((n-e)/1e3)),r=!0}}return r?i:n});let n=Z.current;if(0===n)return;null===B.current&&(B.current=t);let r=(t-B.current)/1e3;r>.5&&H(n/r)},300);return()=>clearInterval(e)},[h]),0===R.length&&!h&&!L&&!z)return null;return(0,r.jsxs)("div",{"data-message-role":"assistant","data-entry-id":k,style:{marginBottom:16},onMouseEnter:()=>P(!0),onMouseLeave:()=>P(!1),children:[(0,r.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)",marginBottom:4,display:"flex",alignItems:"center",gap:6},children:[p.provider&&(0,r.jsx)("span",{children:(t=p.provider,n=p.model,l=t.toLowerCase(),a=n.toLowerCase(),d=Object.entries(m??{}).flatMap(e=>{let[t,n]=e,r=t.indexOf(":");return r>0&&t.slice(0,r).toLowerCase()===l?[{id:t.slice(r+1).toLowerCase(),name:n}]:[]}),d.find(e=>e.id===a)?.name??d.find(e=>a.endsWith(`/${e.id}`))?.name??Object.entries(m??{}).find(e=>{let[t]=e;return t.toLowerCase()===a})?.[1]??`${t}/${n}`)}),h&&(c=Math.round(q),(0,r.jsx)(r.Fragment,{children:c>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4,color:"var(--text)"},title:$("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"})]}),c]}),null!==D&&(u=D>=50?"#53b3cb":D>=30?"#9bc53d":D>=15?"#f9c22e":"#e01a4f",(0,r.jsxs)("span",{style:{marginLeft:6,padding:"1px 6px",borderRadius:4,background:u,color:"#fff",fontSize:11,fontWeight:400},children:[D.toFixed(1)," t/s"]}))]})}))]}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:M.map(e=>{let{block:t,originalIndex:n}=e;return(0,r.jsx)(nB,{block:t,searchTarget:t===w,toolResults:f,isStreaming:h,streamingDuration:V.get(n)??("thinking"===t.type?Y:void 0),toolCallDurations:G,cwd:g,onOpenFile:x,onOpenSession:v,sessionId:j,entryId:k,blockIndex:n},`${k??"stream"}-${n}`)})}),L&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:8*(R.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]}),z&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:R.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:[$(A?"chat.truncatedWithoutAnswer":"chat.truncatedByOutputLimit"),A&&C&&(0,r.jsx)("button",{type:"button",onClick:C,disabled:N,style:{display:"block",marginTop:8,padding:"3px 8px",border:"1px solid currentColor",borderRadius:5,background:"transparent",color:"inherit",cursor:N?"default":"pointer",font:"inherit"},children:$(N?"chat.compacting":"chat.compactContext")}),A&&I&&(0,r.jsx)("div",{style:{marginTop:8,color:"#ef4444",whiteSpace:"pre-wrap"},children:I})]}),S&&S.length>0&&(0,r.jsx)(nj,{files:S,onOpenFile:x}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:4},children:[p.usage&&!h&&(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)"},children:(o=p.usage,s=[],o.input&&s.push(`${o.input.toLocaleString()} in`),o.output&&s.push(`${o.output.toLocaleString()} out`),o.cacheRead&&s.push(`${o.cacheRead.toLocaleString()} cache R`),o.cacheWrite&&s.push(`${o.cacheWrite.toLocaleString()} cache W`),o.cost?.total&&s.push(`$${o.cost.total.toFixed(4)}`),s.join(" \xb7 "))}),X&&!h&&(0,r.jsxs)("button",{onClick:()=>{no(X).then(()=>{F(!0),setTimeout(()=>F(!1),1500)})},title:$("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:O?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:+!!W,pointerEvents:W?"auto":"none",transition:"opacity 0.12s, color 0.12s"},onMouseEnter:e=>{O||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{O||(e.currentTarget.style.color="var(--text-dim)")},children:[O?(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"})]}),$(O?"i18n.copied":"i18n.copy")]}),T&&!h&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginLeft:"auto"},children:T})]})]})}function nB(e){let{block:t,searchTarget:n,toolResults:i,isStreaming:o,streamingDuration:s,toolCallDurations:l,cwd:a,onOpenFile:d,onOpenSession:c,sessionId:u,entryId:p,blockIndex:h}=e;if("text"===t.type)return(0,r.jsx)("div",{"data-message-text":!0,"data-search-target":n||void 0,children:(0,r.jsx)(nD,{block:t,isStreaming:o,cwd:a,onOpenFile:d})});if("thinking"===t.type)return(0,r.jsx)(nH,{block:t,duration:s,sessionId:u,entryId:p,blockIndex:h});if("toolCall"===t.type){let e=i?.get(t.toolCallId),n=l?.get(t.toolCallId);return(0,r.jsx)(n_,{block:t,result:e,duration:n,onOpenSession:c})}return null}function nD(e){let{block:t,isStreaming:n,cwd:i,onOpenFile:o}=e;return(0,r.jsx)(nA,{isStreaming:n,cwd:i,onOpenFile:o,children:t.text})}function nH(e){var t;let{block:n,duration:o,sessionId:s,entryId:l,blockIndex:a}=e,{t:d}=(0,E.s)(),[c,u]=(0,i.useState)(ny),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(!1),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(d);v.current=d;let b=(t=n.thinking,t.trimStart().match(/^[^\r\n]{0,240}/u)?.[0].trimEnd()??"");return(0,i.useEffect)(()=>{let e=()=>u(ny());return window.addEventListener(nb,e),()=>window.removeEventListener(nb,e)},[]),(0,i.useEffect)(()=>{if(!c||!n.deferred||null!==p)return;if(!s||!l)return void x(v.current("i18n.thinkingUnavailable"));let e=!1;return m(!0),x(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=nz.get(r);if(i)return nz.delete(r),nz.set(r,i),i;let o=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 nz.delete(r),e});if(nz.set(r,o),nz.size>100){let e=nz.keys().next().value;e&&nz.delete(e)}return o})(s,l,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,s,l,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")}${b?`: ${b}`:""}`,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)(np,{active:c}),!c&&(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b?(0,r.jsx)(ty.oz,{allowedElements:[],unwrapDisallowed:!0,skipHtml:!0,children:b}):"..."})]}),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??(n.deferred?p:n.thinking)}),void 0!==o&&(0,r.jsxs)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:[o,"s"]})]})}function n_(e){var t,n,o,s;let l,{block:a,result:d,duration:c,onOpenSession:u}=e,{t:p}=(0,E.s)(),[h,f]=(0,i.useState)(()=>{var e;return void 0!==(e=a.toolCallId)&&nx.has(e)}),m=(o=a).rawInput??JSON.stringify(o.input,null,2),g=void 0!==a.rawInput,x=tc(a.toolName),v=d&&!d.isError?function(e){let t=e.details;if(!nY(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,b=function(e,t){if(!tu(e.toolName))return null;let n=tg(tp(e.input,e.rawInput));if(n)return n;let r=t&&!t.isError?t.details:void 0;if(nY(r)){let e=tx(r.preview);if(e)return e}return null}(a,d),y=tu(a.toolName)?0===(l=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}(tp((s=a).input,s.rawInput))).length?null:l.join(", ").slice(0,120):null,j=a.toolName!==nk||g?null:nS(t=a.input)&&"string"==typeof t.code?t.code:null,k=null===j?null:{code:j,...nE(d?.details)},w=null!==k&&void 0!==d&&0===d.content.length,S=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),C=d?k?function(e){let[t,...n]=e;return t?.type==="text"&&"string"==typeof t.text&&nN.test(t.text)?n:[...e]}(d.content):d.content:[],N=d?C.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,I=S&&null!==N?function(e){let t=e.trim();if(t.length>2e5||!/^[[{]/.test(t))return e;try{return JSON.stringify(JSON.parse(t),null,2)}catch{return e}}(N):N,$=n8(C),T=null!==I&&("(no output)"===I.trim()||""===I.trim()),M=(d?.isError??!1)||tu(a.toolName)&&tf(d?.details),R=(n=d?.details)&&"object"==typeof n&&"pi-web-subagent"===n.kind&&"string"==typeof n.sessionId?d.details:null,L=k?k.calls.length+k.omitted:0;return(0,r.jsxs)("div",{style:{borderRadius:7,overflow:"hidden",fontSize:12,border:M?"1px solid rgba(248,113,113,0.45)":"1px solid rgba(34,197,94,0.25)",background:M?"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=!h;e=a.toolCallId,e&&(t?nx.add(e):nx.delete(e)),f(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:S?a.toolName:void 0,style:{color:M?"#f87171":"#16a34a",fontFamily:"var(--font-mono)",fontWeight:600,fontSize:11,flexShrink:0},children:S?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{style:{fontWeight:500,opacity:.75},children:[S.server,"/"]}),S.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:g?p("chat.generatingToolInput"):y??(k?function(e){for(let t of e.split(/\r?\n/)){let e=t.trim();if(e&&!e.startsWith("// @options:"))return e}return""}(k.code):function(e){let t=e.input;if(!t||"object"!=typeof t)return"";let n=Object.keys(t);return 0===n.length?"":"command"in t?String(t.command).slice(0,120):"path"in t?String(t.path).slice(0,120):"file_path"in t?String(t.file_path).slice(0,120):"pattern"in t?String(t.pattern).slice(0,120):"query"in t?String(t.query).slice(0,120):String(t[n[0]]).slice(0,120)}(a))}),L>0&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:1===L?p("codemode.callCountOne"):p("codemode.callCount",{count:L})}),void 0!==c&&(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:[c,"s"]}),(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:h?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),R&&u&&(0,r.jsx)("button",{type:"button",onClick:()=>u(R.sessionId),title:p("subagent.open"),"aria-label":p("subagent.open"),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)("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"})]})})]}),h&&(g||!x)&&!b&&(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:M?"1px solid rgba(248,113,113,0.25)":"1px solid rgba(34,197,94,0.2)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:k?k.code.replace(/\r/g,"").trimEnd():m}),h&&k&&(0,r.jsx)(nM,{calls:k.calls,omitted:k.omitted,isError:M}),$.length>0&&(0,r.jsx)(nG,{images:$,isError:M}),h&&b&&(0,r.jsx)("div",{style:{borderTop:"1px solid rgba(34,197,94,0.15)",background:"var(--bg)"},children:(0,r.jsx)(nZ,{files:b})}),h&&d&&b&&M&&(0,r.jsx)(nX,{text:I??"",isEmpty:T,isError:M}),h&&d&&!b&&!w&&(v?(0,r.jsx)(nU,{diff:v}):(!T||0===$.length)&&(0,r.jsx)(nX,{text:I??"",isEmpty:T,isError:M}))]})}function nU(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)(nq,{text:t.text})})}function nq(e){let{text:t}=e,n=(0,i.useMemo)(()=>nm(t),[t]);return n?(0,r.jsx)(nZ,{files:n}):(0,r.jsx)(nJ,{text:t})}function nZ(e){let{files:t}=e,{t:n}=(0,E.s)(),i=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)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.55},children:[i&&(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)(nK,{title:e.oldPath||n("i18n.before"),side:"left"}),(0,r.jsx)(nK,{title:e.newPath||n("i18n.after"),side:"right"})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)"},children:e.rows.map((e,t)=>"hunk"===e.type?null:(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)(nV,{cell:e.left,side:"left"}),(0,r.jsx)(nV,{cell:e.right,side:"right"})]},t))})]},t))})}function nK(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 nV(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",o="added"===t.type?"+":"removed"===t.type?"-":" ",s="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:s,userSelect:"none",fontWeight:"context"===t.type||"empty"===t.type?400:700,flexShrink:0},children:o}),(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 nJ(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)",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 nY(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function nG(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=n3(e);return n?(0,r.jsx)(tJ,{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 nX(e){let{text:t,isEmpty:n,isError:i}=e,{t:o}=(0,E.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?o("i18n.noOutput"):t})})}function nQ(e){let{message:t}=e,{t:n}=(0,E.s)(),o=n4(t.content),s=(0,i.useMemo)(()=>{let e,t,n,r,i;return e=[],t=[],n=o.match(nf),r=n?.[1]??"",i=n?.index===void 0?o:o.slice(0,n.index),r.replace(nh,(n,r,i)=>{let o=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...o):t.push(...o),""}),{body:i.trim(),readFiles:e,modifiedFiles:t}},[o]),l=nW(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.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"}),l&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:l})]}),(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"calc(15px + var(--chat-font-size-offset, 0px))",fontWeight:700,lineHeight:1.35},children:n("i18n.conversationCompacted")}),(0,r.jsx)("div",{style:{marginTop:3,marginBottom:10,color:"var(--text)",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:n("i18n.compactionDescription")}),s.body?(0,r.jsx)(nu,{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)(n0,{readFiles:s.readFiles,modifiedFiles:s.modifiedFiles})]})]})})}function n0(e){let{readFiles:t,modifiedFiles:n}=e,{t:i}=(0,E.s)();if(0===t.length+n.length)return null;let o=[];return t.length>0&&o.push(`${t.length} read`),n.length>0&&o.push(`${n.length} modified`),(0,r.jsxs)("details",{className:"compaction-file-details",children:[(0,r.jsx)("summary",{children:i("i18n.fileContext",{details:o.join(", ")})}),n.length>0&&(0,r.jsx)(n1,{title:i("i18n.modifiedFiles"),files:n}),t.length>0&&(0,r.jsx)(n1,{title:i("i18n.readFiles"),files:t})]})}function n1(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 n2(e){let t,{message:n,cwd:o,onOpenFile:s}=e,{t:l}=(0,E.s)(),a=!1===n.display,[d,c]=(0,i.useState)(!a),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(!1),m=n4(n.content),g=n8(n.content),x=void 0!==n.details,v=x?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(n.details):"",b=n.customType||"extension",y=nW(n.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:a?"var(--bg-subtle)":"var(--bg)",opacity:a&&!d?.82:1},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)",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:b}),a&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:l("i18n.hiddenExtensionMessage")}),y&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:y})]}),d?(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[g.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!m},children:g.map((e,t)=>{let n=n3(e);return n?(0,r.jsx)(tJ,{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})}),m?(0,r.jsx)(nu,{className:"markdown-custom-message",cwd:o,onOpenFile:s,children:m}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:l("i18n.noMessage")})]}):(0,r.jsx)("button",{onClick:()=>c(!0),style:{display:"block",width:"100%",padding:"8px 10px",border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:12,textAlign:"left"},children:m?(t=m.replace(/\s+/g," ").trim())?t.length>140?`${t.slice(0,140)}...`:t:"Show extension message":l("i18n.showExtensionMessage")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[m||v?(0,r.jsx)("button",{onClick:()=>{no(m||v).then(()=>{f(!0),setTimeout(()=>f(!1),1500)})},style:{padding:"3px 7px",border:"none",background:"none",color:h?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:l(h?"i18n.copied":"i18n.copy")}):null,(x||a)&&(0,r.jsx)("button",{onClick:()=>{a?c(e=>!e):p(e=>!e)},style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:l(a?d?"i18n.collapse":"i18n.expand":u?"i18n.hideDetails":"i18n.showDetails")})]}),x&&(a&&d||!a&&u)&&(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:v})]})})}function n4(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function n8(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)}function n3(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}`:""}function n5(e){let{message:t,sessionId:n}=e,[o,s]=(0,i.useState)(null),[l,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(null),u=!t.output&&void 0===t.exitCode&&!t.cancelled,p=t.cancelled||void 0!==t.exitCode&&0!==t.exitCode,h=n&&t.fullOutputPath?`/api/agent/${encodeURIComponent(n)}/bash-output?path=${encodeURIComponent(t.fullOutputPath)}`:null,f=t.truncated&&h&&null===o,m=o??t.output;async function g(){if(h){a(!0),c(null);try{let e=await fetch(h),t=await e.json();t.success?s(t.data?.output??""):c(t.error??"failed")}catch(e){c(String(e))}finally{a(!1)}}}let x=t.excludeFromContext?"bash (local)":"bash",v={type:"toolCall",toolCallId:`bash-${t.timestamp??""}`,toolName:x,input:{command:t.command}},b=u?void 0:{role:"toolResult",toolCallId:v.toolCallId,toolName:x,content:m?[{type:"text",text:m}]:[],isError:p,timestamp:t.timestamp};return(0,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(n_,{block:v,result:b}),t.truncated&&h&&(0,r.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[f&&(0,r.jsx)("button",{onClick:g,disabled:l,style:{background:"none",border:"none",color:"var(--accent)",cursor:l?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:l?"loading…":"view full output"}),(0,r.jsx)("a",{href:`${h}&download=1`,style:{marginLeft:10*!!f,color:"var(--accent)",fontSize:11,textDecoration:"underline"},children:"download full output"}),d&&(0,r.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:["(",d,")"]})]})]})}function n6(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 n9=new Map;function n7(e){return{value:e.value,images:e.images.map(e=>({...e}))}}function re(e){return!e.value&&0===e.images.length}function rt(e){let t=n9.get(e);return t?n7(t):null}function rn(e,t){re(t)?n9.delete(e):n9.set(e,n7(t))}function rr(e){n9.delete(e)}function ri(e,t){return e.trim()?t.trim()?`${e}
7
-
8
- ${t}`:e:t}function ro(e,t,n,r){let i=[...t??[],...r].filter(n6).slice(0,10).map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});return{value:ri(e,n),images:i}}function rs(e,t,n){if(e===t)return n?n7(n):rt(t);let r=rt(e),i=n&&!re(n)?n7(n):r??(n?n7(n):null),o=rt(t);if(rr(e),!i)return o;let s=o?ro(o.value,o.images,i.value,i.images):i;return rn(t,s),n7(s)}function rl(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 ra(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function rd(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 rc(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}let ru=/^([ \t]*)([-*+])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,rp=/^([ \t]*)(\d{1,9})([.)])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,rh=/^([ \t]*)(\d{1,3})(、)([ \t]*)/,rf=/^[ \t]*([-*_])(?:[ \t]*\1){2,}[ \t]*$/,rm=/^[ \t]{0,3}(`{3,}|~{3,})/;function rg(e){return"mcp"===e.name&&e.sourceInfo?.path==="builtin:mcp"}function rx(e){return"/mcp"===e.trim()}let rv="pi-enter-send-mode",rb="enter",ry=null,rj=new Set;function rk(){return null===ry&&(ry=function(){try{let e=window.localStorage.getItem(rv);return"ctrlEnter"===e?"ctrlEnter":"enter"}catch{return rb}}()),ry}function rw(e){return rj.add(e),()=>{rj.delete(e)}}function rS(e){ry=e;try{window.localStorage.setItem(rv,e)}catch{}rj.forEach(e=>e())}function rC(){return(0,i.useSyncExternalStore)(rw,rk,()=>rb)}let rE="pi-chat-content-width",rN="pi-chat-content-font-size",rI={width:820,fontSize:14},r$=null,rT=new Set;function rM(e){let t=Number(e);return Number.isFinite(t)?Math.max(820,Math.min(2e3,Math.round(t))):820}function rR(e){let t=Number(e??14);return Number.isFinite(t)?Math.max(12,Math.min(24,Math.round(t))):14}function rL(e){try{return window.localStorage.getItem(e)}catch{return null}}function rz(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 rA(){return r$||rz(r$={width:rM(rL(rE)),fontSize:rR(rL(rN))}),r$}function rW(e){return rT.add(e),()=>{rT.delete(e)}}function rP(e,t){let n="width"===e?rM(t):rR(t);rz(r$={...rA(),[e]:n});try{window.localStorage.setItem("width"===e?rE:rN,String(n))}catch{}rT.forEach(e=>e())}let rO=e=>rP("width",e),rF=e=>rP("fontSize",e);function rB(){return{...(0,i.useSyncExternalStore)(rW,rA,()=>rI),setWidth:rO,setFontSize:rF}}function rD(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 rH(e){let{active:t,onSelect:n,star:o,gutter:s=!!o,children:l}=e,a=ew(),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=!!(o&&!o.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:s?"7px 36px 7px 12px":"7px 12px",border:"none",background:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:t?600:400,textAlign:"left",whiteSpace:"nowrap"},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),l]}),o?.isDefault&&(0,r.jsx)("span",{role:"img","aria-label":o.defaultLabel,title:o.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)(rD,{filled:!0,size:10})}),o&&h&&(0,r.jsx)("button",{type:"button",title:o.saveLabel,"aria-label":o.saveLabel,tabIndex:f?0:-1,onClick:e=>{e.stopPropagation(),o.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)(rD,{filled:!1,size:12})})]})}let r_=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function rU(e,t){return r_.compare(e.name||e.modelId,t.name||t.modelId)||r_.compare(e.provider,t.provider)||r_.compare(e.modelId,t.modelId)}function rq(e){let t,n,o,s,l,a,d,c,u,{options:p,value:h,onChange:f,onClear:m,emptyLabel:g,selectedLabel:x,disabled:v=!1,busy:b=!1,isAutoSelection:y=!1,ariaLabel:j,variant:k="toolbar",placement:w="up",defaultValue:S,onSetDefault:C}=e,{t:N}=(0,E.s)(),I=ew(),$=(0,i.useRef)(null),T=(0,i.useRef)(null),[M,R]=(0,i.useState)(!1),[L,z]=(0,i.useState)(null),[A,W]=(0,i.useState)(""),P=v||b,O=(0,i.useMemo)(()=>[...p].sort(rU),[p]),F=(t=A.trim().toLocaleLowerCase())?O.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(t)):O,B=O.length>8,D=[];for(let e of F){let t=D.find(t=>t.provider===e.provider);t?t.options.push(e):D.push({provider:e.provider,options:[e]})}let H=x??(h?O.find(e=>e.modelId===h.modelId&&e.provider===h.provider)?.name??h.modelId:g??(O.length>0?"Select model":"No models"));(0,i.useEffect)(()=>{let e=e=>{$.current&&!$.current.contains(e.target)&&T.current&&!T.current.contains(e.target)&&(R(!1),W(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{P&&(R(!1),W(""))},[P]);let _="field"===k?{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:P?"var(--bg-panel)":"var(--bg)",color:P?"var(--text-dim)":"var(--text)",cursor:P?"default":"pointer",fontSize:12,textAlign:"left"}:{display:"flex",alignItems:"center",justifyContent:I?"flex-start":void 0,gap:6,width:I?"100%":void 0,maxWidth:I?"100%":220,height:32,padding:I?"8px 10px":"8px 12px",overflow:"hidden",border:"none",borderRadius:9,background:M?"var(--bg-hover)":"none",color:"var(--text-muted)",cursor:P?"not-allowed":"pointer",fontSize:12,opacity:P?.5:1,transition:"background 0.12s, color 0.12s"};return(0,r.jsxs)("div",{ref:$,className:`model-selector is-${k}${P?" is-disabled":""}`,style:{position:"relative",width:"field"===k||I?"100%":void 0,minWidth:0,flex:"toolbar"===k&&I?"1 1 auto":void 0},onKeyDown:e=>{"Escape"===e.key&&M&&(e.preventDefault(),e.stopPropagation(),W(""),R(!1))},children:[(0,r.jsxs)("button",{type:"button","aria-label":j,"aria-haspopup":"listbox","aria-expanded":M,"aria-busy":b||void 0,disabled:P,title:b?"Switching model":P?H:O.length>0||m?"Change model":"No available models",style:_,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();z({top:t.top,right:t.right,bottom:t.bottom,left:t.left,width:t.width}),R(e=>(e&&W(""),!e))},onMouseEnter:e=>{P||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{if(P){e.currentTarget.style.background="field"===k?"var(--bg-panel)":"none",e.currentTarget.style.color="field"===k?"var(--text-dim)":"var(--text-muted)";return}e.currentTarget.style.background=M?"var(--bg-hover)":"field"===k?"var(--bg)":"none",e.currentTarget.style.color="field"===k?"var(--text)":"var(--text-muted)"},children:[b?(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:H}),"field"===k&&(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"})})]}),M&&L&&(n=window.visualViewport?.height??window.innerHeight,o=window.visualViewport?.width??window.innerWidth,s=L.top-8,l=n-L.bottom-8,d=Math.max(120,Math.min((a="up"===w||s>l)?s:l,.6*n)),c=a?{bottom:n-L.top+6}:{top:L.bottom+6},u=I?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:L.left,width:"max-content",minWidth:L.width,maxWidth:Math.max(L.width,o-L.left-8)},(0,r.jsxs)("div",{ref:T,role:"listbox","aria-label":j,style:{position:"fixed",...c,...u,zIndex:500,display:"flex",flexDirection:"column",maxHeight:d,overflow:"hidden",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:a?"0 -4px 16px rgba(0,0,0,0.10)":"0 4px 16px rgba(0,0,0,0.10)"},children:[B&&(0,r.jsx)("div",{style:{flexShrink:0,padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:A,onChange:e=>W(e.target.value),placeholder:N("chat.filterModels"),"aria-label":N("chat.filterModels"),autoFocus:!I,autoComplete:"off",spellCheck:!1,style:{boxSizing:"border-box",width:"100%",minWidth:220*!I,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:[m&&!A.trim()&&(0,r.jsx)(rH,{active:!h,gutter:!!C,onSelect:()=>{R(!1),W(""),m()},children:(0,r.jsx)(rZ,{label:g??"Default"})}),0===D.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:A.trim()?N("chat.noMatchingModels"):"No available models"}):D.map((e,t)=>(0,r.jsxs)("div",{children:[D.length>1&&(0,r.jsx)("div",{style:{padding:"6px 12px 4px",borderTop:t>0||m?"1px solid var(--border)":"none",color:"var(--text-dim)",fontSize:10,fontWeight:600,letterSpacing:0,textTransform:"uppercase"},children:e.provider}),e.options.map(e=>(0,r.jsx)(rH,{active:e.modelId===h?.modelId&&e.provider===h?.provider,onSelect:()=>{let t;return t=e.modelId===h?.modelId&&e.provider===h?.provider,void(R(!1),W(""),(!t||y)&&f(e.provider,e.modelId))},star:C?{isDefault:e.modelId===S?.modelId&&e.provider===S?.provider,saveLabel:N("chat.saveDefaultModel"),defaultLabel:N("chat.defaultModel"),onSave:()=>{R(!1),W(""),C?.(e.provider,e.modelId)}}:void 0,children:(0,r.jsx)(rZ,{label:e.name})},`${e.provider}:${e.modelId}`))]},e.provider))]})]}))]})}function rZ(e){let{label:t}=e;return(0,r.jsx)("span",{title:t,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})}let rK=["configured","chat-only","read-only","default","full"],rV={configured:"configured","chat-only":"none","read-only":"read-only",default:"default",full:"full"},rJ=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function rY(e,t,n){return t<=0?0:((e+n)%t+t)%t}function rG(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 o=e.parentElement,s=o?.parentElement,l="u">typeof ResizeObserver&&o?new ResizeObserver(i):null;o&&l?.observe(o),s&&l?.observe(s);let a=window.visualViewport;return a?.addEventListener("resize",i),a?.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("scroll",i,!0),()=>{l?.disconnect(),a?.removeEventListener("resize",i),a?.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("scroll",i,!0),null!==n&&cancelAnimationFrame(n)}}let rX=["auto","off","minimal","low","medium","high","xhigh","max"],rQ={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 r0(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let r1=[{name:"compact",description:"chat.commandCompact",source:"builtin"},{name:"auto-compact",description:"chat.commandAutoCompact",source:"builtin"},{name:"reload",description:"chat.commandReload",source:"builtin"},{name:"name",description:"chat.commandName",source:"builtin"},{name:"session",description:"chat.commandSession",source:"builtin",availableWhileStreaming:!0},{name:"copy",description:"chat.commandCopy",source:"builtin",availableWhileStreaming:!0},{name:"clone",description:"chat.commandClone",source:"builtin"}];function r2(e){return function(e){let t=e.trim().match(/^\/([^\s]+)(?:\s|$)/);if(t)return r1.find(e=>e.name===t[1])}(e)?.availableWhileStreaming===!0}let r4=["builtin","extension","prompt","skill"],r8={builtin:"chat.builtIn",extension:"chat.extensions",prompt:"chat.prompts",skill:"chat.skills"},r3={builtin:0,extension:1,prompt:2,skill:3};function r5(e,t,n){let r=e.name.toLowerCase(),i=r6(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function r6(e,t){return"builtin"===e.source?t(e.description):e.description??""}function r9(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}async function r7(e){let t=()=>{var t;return t=e.type,new Promise((n,r)=>{let i=new FileReader;i.onload=()=>{let e="string"==typeof i.result?i.result.split(",")[1]:void 0;e?n({data:e,mimeType:t}):r(Error("Failed to read image"))},i.onerror=r,i.readAsDataURL(e)})};if(!(e.size>1048576&&"image/gif"!==e.type)||"function"!=typeof createImageBitmap)return t();let n=await createImageBitmap(e).catch(()=>null);if(!n)return t();try{let r=Math.min(1,1024/Math.max(n.width,n.height)),i=document.createElement("canvas");i.width=Math.max(1,Math.round(n.width*r)),i.height=Math.max(1,Math.round(n.height*r));let o=i.getContext("2d");if(!o)return t();o.fillStyle="#fff",o.fillRect(0,0,i.width,i.height),o.drawImage(n,0,0,i.width,i.height);let s=i.toDataURL("image/jpeg",.85).split(",")[1];return s&&s.length<4*Math.ceil(e.size/3)?{data:s,mimeType:"image/jpeg"}:t()}catch{return t()}finally{n.close()}}function ie(e){return{data:e.data,mimeType:e.mimeType}}function it(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function ir(e){return(e??[]).filter(n6).slice(0,10).map(it)}function ii(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function io(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 is(e){let{tone:t,title:n,body:i,onClose:o}=e,s="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(${s},0.3)`,borderRadius:6,background:`rgba(${s},0.07)`,color:`rgb(${s})`,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})]}),o&&(0,r.jsx)("button",{type:"button",onClick:o,"aria-label":"Dismiss",style:{flexShrink:0,background:"none",border:"none",padding:"0 2px",cursor:"pointer",color:"inherit",opacity:.7,fontSize:13,lineHeight:1},children:"\xd7"})]})}function il(e){let{error:t}=e,{t:n}=(0,E.s)();return t?(0,r.jsx)(is,{tone:"error",title:n("chat.modelError"),body:t}):null}function ia(e){let{warnings:t}=e,{t:n}=(0,E.s)();return t&&0!==t.length?(0,r.jsx)(is,{tone:"warning",title:n(t.length>1?"chat.modelScopeWarnings":"chat.modelScopeWarning"),body:t.join("\n")}):null}let id=(0,i.forwardRef)(function(e,t){let n,o,s,l,a,d,c,{onSend:u,onAbort:p,onSteer:h,onFollowUp:f,isStreaming:m,model:g,isAutoModelSelection:x,modelNames:v,modelList:b,modelError:y,modelScopeWarnings:j,onModelChange:k,modelSwitching:w,defaultModel:S,onSetDefaultModel:C,onCompact:N,onAbortCompaction:I,isCompacting:$,compactError:T,compactResult:M,toolPreset:R,onToolPresetChange:L,thinkingLevel:z,isAutoThinkingSelection:A=!1,onThinkingLevelChange:W,availableThinkingLevels:P,thinkingLevelMap:O,savedDefaultThinkingLevel:F,onSetDefaultThinkingLevel:B,retryInfo:D,queuedMessages:H,inputHistory:_=[],onRecallQueue:U,slashCommands:Z,slashCommandsLoading:K,onLoadSlashCommands:J,onBuiltinCommand:Y,soundEnabled:G,onSoundToggle:X,onAudioUnlock:Q,onPromptWithStreamingBehavior:ee,draftKey:et,cwd:en,compact:er=!1}=e,{t:ei}=(0,E.s)(),{fontSize:eo}=rB(),es=ew(),el=rC(),[ea,ed]=(0,i.useState)(()=>et?rt(et)?.value??"":""),[ec,eu]=(0,i.useState)(!1),[ep,eh]=(0,i.useState)(!1),[ef,em]=(0,i.useState)(!1),[eg,ex]=(0,i.useState)(()=>et?ir(rt(et)?.images):[]),ev=ea.trimStart(),eb=0===eg.length&&ev.startsWith("!"),ey=eb&&ev.startsWith("!!"),[ej,ek]=(0,i.useState)(!1),[eS,eC]=(0,i.useState)(0),[eE,eN]=(0,i.useState)(null),[eI,e$]=(0,i.useState)(null),[eT,eM]=(0,i.useState)(!1),[eR,eL]=(0,i.useState)(null),[ez,eA]=(0,i.useState)(0),[eW,eP]=(0,i.useState)(!1),[eO,eF]=(0,i.useState)(!1),[eB,eD]=(0,i.useState)(0),[eH,e_]=(0,i.useState)(!1),eU=(0,i.useRef)(!1),[eq,eZ]=(0,i.useState)(null),[eK,eV]=(0,i.useState)(!1),[eJ,eY]=(0,i.useState)(null),[eG,eX]=(0,i.useState)(null),eQ=en&&eG?.cwd===en?eG.values:{},e0=(0,i.useRef)(null),e1=(0,i.useRef)(null),e2=(0,i.useRef)(null),e4=(0,i.useRef)(null),e8=(0,i.useRef)(null),e3=(0,i.useRef)(null),e5=(0,i.useRef)(!1),e6=(0,i.useRef)(0),e9=(0,i.useRef)(!1),e7=(0,i.useRef)(null),te=(0,i.useRef)([]),tt=(0,i.useRef)(null),tn=(0,i.useRef)([]),tr=(0,i.useRef)([]),ti=(0,i.useRef)(null),to=(0,i.useRef)(null),ts=(0,i.useRef)(et),tl=(0,i.useRef)(ea),ta=(0,i.useRef)(eg),td=(0,i.useRef)(0);tl.current=ea,ta.current=eg,(0,i.useImperativeHandle)(t,()=>({insertIfEmpty(e){let t=e0.current;(t?t.value:ea).trim()||(tl.current=e,ed(e),e$(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){var t,n,r;let i=e0.current;if(t=i?i.value:ea,n=ta.current.length,r=td.current,t.trim()||0!==n||0!==r)return;let o="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),s=ir("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 n6(r)?[r]:[]}));tl.current=o,ta.current=s,ed(o),e$(null),eF(!1),ex(e=>(e.forEach(ii),s)),requestAnimationFrame(()=>{i&&(i.focus(),i.style.height="auto",i.style.height=`${Math.min(i.scrollHeight,200)}px`)})},prependText(e){if(!e.trim())return;let t=e0.current,n=[e,t?t.value:ea].filter(e=>e.trim()).join("\n\n");tl.current=n,ed(n),e$(null),requestAnimationFrame(()=>{t&&(t.focus(),t.setSelectionRange(n.length,n.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(ts.current!==e)return void rs(e,t);let n={value:tl.current,images:ta.current.map(ie)},r=rs(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(ts.current=t,i)return;let o=ir(r.images);tl.current=r.value,ta.current=o,ed(r.value),ex(e=>(e.forEach(ii),o)),e$(null),eF(!1)},restoreSubmission(e,t,n){if(!e.trim()&&!t?.length)return;let r=ts.current,i=n??r,o=i===r,s=!o&&i?rt(i):null,l=ro(e,t,o?tl.current:s?.value??"",o?ta.current.map(ie):s?.images??[]);if(i&&rn(i,l),!o)return;let a=t?.length?[...ir(t).slice(0,Math.max(0,10-ta.current.length)),...ta.current].slice(0,10):ta.current;tl.current=l.value,ta.current=a,ed(t=>{let n=ri(e,t);return tl.current=n,n}),e$(null),eF(!1),t?.length&&ex(e=>{let n=Math.max(0,10-e.length),r=ir(t).slice(0,n),i=r.length>0?[...r,...e]:e;return ta.current=i,i}),requestAnimationFrame(()=>{let e=e0.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},insertText(e){let t=e0.current;if(!t)return void ed(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n),o=t.value.slice(r),s=i.length>0&&!i.endsWith(" ")?" ":"",l=i+s+e+o;tl.current=l,ed(l),e$(null),requestAnimationFrame(()=>{if(!t)return;let r=n+s.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addImages(e){tc(e)}}));let tc=(0,i.useCallback)(async e=>{if(er)return;let t=Math.max(0,10-ta.current.length-td.current),n=e.filter(e=>e.type.startsWith("image/")&&e.size<=0xa00000).slice(0,t);if(n.length){td.current+=n.length;try{let e=await Promise.all(n.map(async e=>({...await r7(e),previewUrl:URL.createObjectURL(e)})));ex(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(ii);let r=[...t,...n];return ta.current=r,r})}finally{td.current-=n.length}}},[er]),tu=(0,i.useCallback)(e=>{ex(t=>{let n=[...t],[r]=n.splice(e,1);return r&&ii(r),ta.current=n,n})},[]),tp=(0,i.useCallback)(()=>{ta.current=[],ex(e=>(e.forEach(ii),[]))},[]),th=(0,i.useCallback)(()=>{tl.current="",ed(""),e$(null),eF(!1),et&&rr(et),ts.current&&ts.current!==et&&rr(ts.current),tp(),e0.current&&(e0.current.style.height="auto")},[tp,et]);(0,i.useEffect)(()=>{et&&ts.current===et&&rn(et,{value:ea,images:eg.map(ie)})},[eg,et,ea]),(0,i.useEffect)(()=>{let e=ts.current;if(e===et)return;e&&rn(e,{value:tl.current,images:ta.current.map(ie)});let t=et?rt(et):null;ts.current=et;let n=t?.value??"",r=ir(t?.images);tl.current=n,ta.current=r,ed(n),e$(null),eF(!1),ex(e=>(e.forEach(ii),r))},[et]);let tf=(0,i.useCallback)(()=>{let e=e0.current;e&&(e.style.height="auto",e.value&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[]);(0,i.useLayoutEffect)(tf,[ea,eo,tf]),(0,i.useEffect)(()=>{let e=e0.current;if(!e)return;let t=-1,n=new ResizeObserver(e=>{let[n]=e;n.contentRect.width!==t&&(t=n.contentRect.width,tf())});return n.observe(e),()=>n.disconnect()},[tf]),(0,i.useEffect)(()=>{let e=e0.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,o=e.indexOf("\n",t),s=-1===o?e.length:o,l=e.slice(i,s),a=function(e){if(rf.test(e))return null;let t=ru.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=rp.exec(e)??rh.exec(e);return n?{indent:n[1],marker:"",number:n[2],delimiter:n[3],spacing:n[4],task:void 0!==n[5],length:n[0].length}:null}(l);return!a||t-i<a.length||function(e){let t=null;for(let n of e.split("\n")){let e=rm.exec(n)?.[1];e&&(null===t?t=e:e[0]===t[0]&&e.length>=t.length&&n.trim()===e&&(t=null))}return null!==t}(e.slice(0,i))?null:""===l.slice(a.length).trim()?{start:i,end:s,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)(()=>()=>{ta.current.forEach(ii)},[]);let tm=(0,i.useCallback)(async e=>{if(eg.length||!e.startsWith("/")||!Y)return!1;if(eU.current)return!0;eU.current=!0,e_(!0);try{var t,n;let r=await Y(e);if(!r.handled)return!1;return r.error||(t=tl.current,n=ta.current.length,0!==n||t.trim()!==e)||th(),!0}finally{eU.current=!1,e_(!1)}},[eg.length,th,Y]),tg=(0,i.useCallback)(async()=>{var e;let t=ea.trim();(t||eg.length)&&(Q?.(),(!m||r2(e=t)||rx(e))&&await tm(t)||m||(th(),u(t,eg.length?eg:void 0)))},[ea,eg,m,tm,u,th,Q]),tx=!er&&ea.startsWith("/")&&!/\s/.test(ea.slice(1))?ea.slice(1).toLowerCase():null,tv=null===tx?[]:[...m?r1.filter(e=>e.availableWhileStreaming):r1,...Z??[]].filter(e=>{let t=e.name.toLowerCase(),n=r6(e,ei).toLowerCase();return t.includes(tx)||n.includes(tx)}).sort((e,t)=>{let n=r5(e,tx,ei)-r5(t,tx,ei);return 0!==n?n:r3[e.source]-r3[t.source]||rJ.compare(e.name,t.name)}),{commands:tb,groups:ty}=(n=0,{commands:(o=r4.map(e=>{let t=tv.filter(t=>t.source===e),r="skill"===e?[...t.filter(e=>!r9(e,eQ)),...t.filter(e=>r9(e,eQ))]:t;return{source:e,items:r.map(e=>({command:e,index:n++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(e=>{let{command:t}=e;return t})),groups:o}),tj=1===tv.length?ei(tx?"chat.match":"chat.command"):ei(tx?"chat.matches":"chat.commands",{count:tv.length}),tk=!!ea.trim()||eg.length>0,tw=eg.length>0&&!function(e,t){if(!e)return!0;let n=t?.find(t=>t.provider===e.provider&&t.id===e.modelId);return!n||!n.input||n.input.includes("image")}(g,b)&&!eW;(0,i.useEffect)(()=>{0===eg.length&&eP(!1)},[eg.length]);let tS=(0,i.useCallback)((e,t)=>{if(!en)return void e$(null);let n=t??e.length;e$(rl(e.slice(0,n)))},[en]),tC=eI?.query??null,tE=i.useMemo(()=>null!==tC&&eq&&eq.cwd===en?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:rd(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:rd(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||ra(e.entry.path)-ra(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(eq.entries,tC):[],[tC,eq,en]),tN=!!(tC&&eq?.truncated&&eq.cwd===en);(0,i.useEffect)(()=>{if(!tN||!en||!tC)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(en)}&q=${encodeURIComponent(tC)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>eY({cwd:en,query:tC,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tN,tC,en]);let tI=tN&&null!==eJ&&eJ.cwd===en&&eJ.query===tC,t$=tI?eJ.matches:tE,tT=null===eI?null:`${eI.start}:${+!!eI.quoted}:${eI.query}`;(0,i.useEffect)(()=>{if(null===tT){eM(!1),eA(0);return}eM(!0),eA(0)},[tT]);let tM=null!==eI;(0,i.useEffect)(()=>{if(!tM||!en)return;let e=ti.current;e&&e.cwd===en&&Date.now()-e.fetchedAt<1e4||to.current===en||(to.current=en,eV(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(en)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{eZ({cwd:en,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)=>ra(e.path)-ra(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),ti.current={cwd:en,fetchedAt:Date.now()}}).catch(()=>{ti.current=null}).finally(()=>{to.current=null,eV(!1)}))},[tM,en]);let tR=(0,i.useCallback)(e=>{if(!eI)return;let t=e0.current,n=t?.selectionStart??ea.length,r=ea.slice(0,eI.start),i=ea.slice(n);eI.quoted&&i.startsWith('"')&&(i=i.slice(1));let o=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 o=i?`@"${r}" `:`@${r} `;return{text:o,cursorOffset:o.length}}(e.path,e.isDir,eI.quoted),s=r+o.text+i,l=r.length+o.cursorOffset;ed(s),e$(rl(s.slice(0,l))),requestAnimationFrame(()=>{let e=e0.current;e&&(e.focus(),e.setSelectionRange(l,l),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[eI,ea]);(0,i.useEffect)(()=>{ez>=t$.length&&eA(Math.max(0,t$.length-1))},[t$.length,ez]),(0,i.useEffect)(()=>{tn.current.length=t$.length},[t$.length]),(0,i.useEffect)(()=>{eT&&tn.current[ez]?.scrollIntoView({block:"nearest",inline:"nearest"})},[ez,eT]),(0,i.useEffect)(()=>{eB>=_.length&&eD(Math.max(0,_.length-1))},[_.length,eB]),(0,i.useEffect)(()=>{tr.current.length=_.length},[_.length]),(0,i.useEffect)(()=>{eO&&tr.current[eB]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eB,eO]);let tL=(0,i.useCallback)(e=>{ed(e),eF(!1),eD(0),e$(null),requestAnimationFrame(()=>{let t=e0.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),tz=(0,i.useCallback)(e=>{let t=`/${e.name} `;ed(t),ek(!1),eC(0),requestAnimationFrame(()=>{let e=e0.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),tA=(0,i.useCallback)(e=>{let t=ea.trim();if(!t&&!eg.length)return;Q?.();let n=eg.length?eg:void 0,r=()=>{if(t.startsWith("/")&&ee){th(),ee(t,"steer"===e?"steer":"followUp",n);return}th(),"steer"===e&&h?h(t,n):"followup"===e&&f&&f(t,n)};!eg.length&&Y&&r2(t)?tm(t):!eg.length&&Y&&rx(t)?tm(t).then(e=>{e||r()},()=>r()):r()},[ea,eg,Y,ee,h,f,th,Q,tm]),tW=(0,i.useCallback)(e=>{let t=tb.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eS-1);if("right"===e)return Math.min(t,eS+1);let n=te.current[eS];if(!n)return"down"===e?Math.min(t,eS+1):Math.max(0,eS-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,o=r.top+r.height/2,s=-1,l=1/0;for(let n=0;n<=t;n+=1){if(n===eS)continue;let t=te.current[n];if(!t)continue;let r=t.getBoundingClientRect(),a=r.top+r.height/2-o;if("down"===e?a<=4:a>=-4)continue;let d=1e3*Math.abs(a)+Math.abs(r.left+r.width/2-i);d<l&&(s=n,l=d)}return s>=0?s:"down"===e?Math.min(t,eS+1):Math.max(0,eS-1)},[tb.length,eS]),tP=(0,i.useCallback)(e=>{let t=e.nativeEvent,n="Enter"===e.key&&!e.shiftKey,r=es||"ctrlEnter"===el?n&&(e.ctrlKey||e.metaKey):n,i=es?r:n,o=Date.now()-e6.current<100,s=e5.current||t.isComposing||229===t.keyCode;if(i&&(s||o)){o&&e.preventDefault();return}if(eO&&!s){if("ArrowDown"===e.key){e.preventDefault(),eD(e=>Math.min(Math.max(0,_.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eD(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),eF(!1);return}if(("Tab"===e.key||i)&&_[eB]){e.preventDefault(),tL(_[eB]);return}}if(ej&&null!==tx){if("ArrowDown"===e.key){e.preventDefault(),eC(tW("down"));return}if("ArrowUp"===e.key){e.preventDefault(),eC(tW("up"));return}if("ArrowRight"===e.key){e.preventDefault(),eC(tW("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),eC(tW("left"));return}if("Escape"===e.key){e.preventDefault(),ek(!1);return}let t=tb[eS];if("Tab"===e.key&&t){e.preventDefault(),tz(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 rg(t)&&rx(e)}(ea,t,m)?(ek(!1),tg()):tz(t);return}}if(eT&&null!==eI&&!s){if("ArrowDown"===e.key){e.preventDefault(),eA(e=>rY(e,t$.length,1));return}if("ArrowUp"===e.key){e.preventDefault(),eA(e=>rY(e,t$.length,-1));return}if("Escape"===e.key){e.preventDefault(),eM(!1);return}if(("Tab"===e.key||i)&&t$[ez]){e.preventDefault(),tR(t$[ez]);return}}if("ArrowUp"===e.key&&!s&&!m&&_.length>0&&0===ea.trim().length){e.preventDefault(),ek(!1),eM(!1),eD(_.length-1),eF(!0);return}if("Escape"===e.key&&!s&&m&&p){e.preventDefault(),p();return}r&&(e.preventDefault(),m&&(h||f)?tA(e.altKey&&f||!h?"followup":"steer"):tg())},[es,el,m,h,f,p,ej,tx,tb,eS,tz,tA,tg,tW,eT,eI,t$,ez,tR,eO,_,eB,tL,ea]),tO=(0,i.useCallback)(()=>{let e=e0.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),tF=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!er&&t.length){e.preventDefault(),tc(t.map(e=>e.getAsFile()).filter(e=>null!==e));return}let n=e.clipboardData.getData("text/html"),r=e.clipboardData.getData("text/plain");if(!n||!r)return;let i=new DOMParser().parseFromString(n,"text/html"),o=function(e,t){let n="",r=0,i=!1;for(let{label:o,href:s,occurrence:l}of t){if(!o||!s)continue;let t=0;for(let n=0;n<=l&&!((t=e.indexOf(o,n?t+o.length:0))<0);n++);if(t<r)continue;let a=o.replace(/([\\[\]])/g,"\\$1"),d=s.replace(/([\\()])/g,"\\$1");n+=`${e.slice(r,t)}[${a}](${d})`,r=t+o.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===o)return;let s=e.currentTarget,l=s.selectionStart,a=s.value.slice(0,l)+o+s.value.slice(s.selectionEnd);e.preventDefault(),tl.current=a,ed(a),eF(!1),tS(a,l+o.length),requestAnimationFrame(()=>{s.focus(),s.setSelectionRange(l+o.length,l+o.length)})},[er,tc,tS]);(0,i.useEffect)(()=>{if(null===tx){ek(!1),eC(0),e9.current=!1;return}ek(!0),eC(0),!e9.current&&J&&(e9.current=!0,Promise.resolve(J()).catch(()=>{e9.current=!1}))},[tx,J]),(0,i.useEffect)(()=>{if(!ej||!en)return;let e=!1;return eX({cwd:en,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(en)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;eX({cwd:en,values:n})}).catch(()=>{e||eX({cwd:en,values:{}})}),()=>{e=!0}},[ej,en]),(0,i.useEffect)(()=>{eS>=tb.length&&eC(Math.max(0,tb.length-1))},[tb.length,eS]),(0,i.useEffect)(()=>{te.current.length=tb.length},[tb.length]),(0,i.useEffect)(()=>{ej&&te.current[eS]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eS,ej]),(0,i.useLayoutEffect)(()=>{if(!ej||null===tx)return void eN(null);let e=e7.current;if(e)return rG(e,e=>{eN(t=>t===e?t:e)})},[ej,tx]),(0,i.useLayoutEffect)(()=>{if(!eT||null===eI)return void eL(null);let e=tt.current;if(e)return rG(e,e=>{eL(t=>t===e?t:e)})},[eT,eI]);let tB=b&&b.length>0?b.map(e=>({provider:e.provider,modelId:e.id,name:e.name})):Object.entries(v??{}).map(e=>{let[t,n]=e;return{provider:g?.provider??"unknown",modelId:t,name:n}}),tD=M?Math.max(0,M.tokensBefore-M.estimatedTokensAfter):0,tH=M?`${M.reason&&"manual"!==M.reason?`${M.reason[0].toUpperCase()}${M.reason.slice(1)} `:ei("chat.compacted")} ${r0(M.tokensBefore)} -> ${r0(M.estimatedTokensAfter)} tokens (${ei("chat.tokensSaved",{saved:r0(tD)})})`:null,t_=z&&"auto"!==z?z:null,tU="auto"!==(s=t_??"auto")&&O?O[s]??s:s,tq=Object.entries(rV).find(e=>{let[,t]=e;return t===(R??"configured")})?.[0]??"configured",tZ="chat-only"===tq?ei("chat.chatOnly"):tq;return(0,i.useEffect)(()=>{let e=e=>{e1.current&&!e1.current.contains(e.target)&&eu(!1),e2.current&&!e2.current.contains(e.target)&&eh(!1),e4.current&&!e4.current.contains(e.target)&&em(!1),!e8.current||e8.current.contains(e.target)||e0.current?.contains(e.target)||eF(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{m&&eu(!1)},[m]),(0,i.useEffect)(()=>{es||em(!1)},[es]),(0,r.jsxs)("fieldset",{disabled:eH,"aria-busy":eH,className:er?void 0:"chat-input-shell",style:{flexShrink:0,minWidth:0,margin:0,border:0,background:"transparent",padding:er?0:"0 16px 8px",paddingRight:er?0:es?16:52,opacity:eH?.5:1,transition:"opacity 0.15s"},children:[!er&&(0,r.jsx)("input",{ref:e3,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:e=>{tc(Array.from(e.target.files??[])),e.target.value=""}}),(0,r.jsxs)("div",{style:{maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(0,r.jsx)(il,{error:y}),(0,r.jsx)(ia,{warnings:j}),tw&&(l=b?.find(e=>e.provider===g?.provider&&e.id===g?.modelId),(0,r.jsx)(is,{tone:"warning",title:ei("chat.imageNotSupportedTitle"),body:ei("chat.imageNotSupportedBody",{model:l?.name||g?.modelId||""}),onClose:()=>eP(!0)})),(H?.steering.length??0)+(H?.followUp.length??0)>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:ei("chat.queued",{count:(H?.steering.length??0)+(H?.followUp.length??0)})}),U&&(0,r.jsxs)("button",{onClick:U,title:ei("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"})]}),ei("chat.recall")]})]}),H?.steering.map((e,t)=>(0,r.jsx)(io,{kind:"steer",text:e},`steer-${t}`)),H?.followUp.map((e,t)=>(0,r.jsx)(io,{kind:"follow-up",text:e},`followup-${t}`))]}),D&&(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"})]}),ei("chat.retrying",{attempt:D.attempt,max:D.maxAttempts}),D.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",D.errorMessage]})]}),tH&&(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"})}),tH]}),T&&(0,r.jsx)("div",{role:"alert",style:{marginBottom:8,padding:"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,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:T}),eg.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:eg.map((e,t)=>(0,r.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,r.jsx)(tJ,{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:()=>tu(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:[eO&&_.length>0&&(0,r.jsxs)("div",{ref:e8,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:ei("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:_.map((e,t)=>{let n=t===eB;return(0,r.jsxs)("button",{ref:e=>{tr.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tL(e)},onMouseEnter:()=>eD(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}`)})})]}),ej&&null!==tx&&(0,r.jsxs)("div",{ref:e7,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eE?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${eE}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:K?ei("chat.loadingCommands"):ei("chat.slashCommands",{label:tj})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ei("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:10},children:K||0!==tv.length?ty.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:ei(r8[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(e=>{let{command:t,index:n}=e,i=n===eS,o=r9(t,eQ);return(0,r.jsxs)("button",{ref:e=>{te.current[n]=e},type:"button",onMouseDown:e=>{e.preventDefault(),tz(t)},onMouseEnter:()=>eC(n),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${i?"var(--accent)":"var(--border)"}`,borderRadius:7,background:i?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:i?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:o?"var(--text-dim)":void 0},children:["/",t.name,o&&(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:ei("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:r6(t,ei)})]},`${t.source}:${t.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:ei("chat.noCommands")})})]}),eT&&null!==eI&&(a=eK&&(!eq||eq.cwd!==en),d=1===t$.length?ei("chat.match"):ei("chat.matches",{count:t$.length}),c=eq?.truncated&&!tI?eI.query?ei("chat.searchingAll"):ei("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:tt,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eR?"min(48vh, 400px)":`min(48vh, 400px, ${eR}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:a?ei("chat.loadingFiles"):ei("chat.files",{label:d,hint:c})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ei("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:a||0!==t$.length?t$.map((e,t)=>{let n=t===ez,i=e.path.split("/").pop()??e.path,o=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tn.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tR(e)},onMouseEnter:()=>eA(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)(q,{size:14}):V(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[o&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:o}),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:tN&&!tI?ei("chat.searching"):ei("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{style:{minWidth:0,display:"flex",flexDirection:er?"column":"row",gap:8,alignItems:er?"stretch":"center",background:"var(--bg)",border:er?"none":`1px solid ${eb?"var(--tool-bg)":m&&(h||f)?"rgba(234,179,8,0.4)":"color-mix(in srgb, var(--border) 70%, transparent)"}`,borderRadius:14*!er,padding:er?0:es?"6px 6px 6px 12px":"10px 10px 10px 14px",boxShadow:er?"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:e0,className:"chat-input-textarea","aria-label":er?ei("chat.quoteQuestion"):void 0,value:ea,onChange:e=>{tl.current=e.target.value,ed(e.target.value),eF(!1),tS(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;tS(t.value,t.selectionStart)},onKeyDown:tP,onCompositionStart:()=>{e5.current=!0},onCompositionEnd:e=>{e5.current=!1,e6.current=Date.now();let t=e.currentTarget;tS(t.value,t.selectionStart)},onInput:tO,onPaste:tF,placeholder:m&&(h||f)?ei("chat.steerPlaceholder"):m?ei("chat.agentPlaceholder"):ei("chat.messagePlaceholder"),rows:1,style:{flex:er?"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:er?96:24,maxHeight:200,overflow:"auto"}}),m?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[h&&(0,r.jsxs)("button",{onClick:()=>tA("steer"),disabled:!tk,title:ei("chat.steerHint"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tk?"rgba(234,179,8,0.12)":"none",border:"1px solid rgba(234,179,8,0.35)",borderRadius:8,color:tk?"rgba(180,130,0,1)":"var(--text-dim)",cursor:tk?"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"})]}),ei("chat.steer")]}),f&&(0,r.jsxs)("button",{onClick:()=>tA("followup"),disabled:!tk,title:`${ei("chat.followUpHint")} (${es?"Ctrl/Cmd+":""}Alt/Option+Enter)`,"aria-keyshortcuts":es?"Control+Alt+Enter Meta+Alt+Enter":"Alt+Enter",style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tk?"rgba(129,140,248,0.12)":"none",border:"1px solid rgba(129,140,248,0.35)",borderRadius:8,color:tk?"rgba(99,102,241,1)":"var(--text-dim)",cursor:tk?"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"})]}),ei("chat.followUp")]})]}):(0,r.jsxs)("button",{onClick:tg,disabled:!ea.trim()&&!eg.length,title:ei("chat.send"),"aria-label":ei("chat.send"),style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,...es?{width:36,height:36,padding:0}:{padding:"7px 14px"},background:ea.trim()||eg.length?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:ea.trim()||eg.length?"var(--accent-contrast)":"var(--text-dim)",cursor:ea.trim()||eg.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:ea.trim()||eg.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"})]}),!es&&ei("chat.send")]})]})]}),eb&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:ey?"var(--text-muted)":"var(--accent)",marginTop:4},children:[ei("chat.shell")," \xb7 ",ey?ei("chat.outputLocal"):ei("chat.outputModel")]}),!er&&(0,r.jsxs)("div",{className:"chat-input-controls",style:{marginTop:es?4:8,display:es?"grid":"flex",gridTemplateColumns:es?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:es?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2},children:[(0,r.jsx)("button",{onClick:()=>e3.current?.click(),title:ei("chat.attachImage"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:eg.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=eg.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=eg.length?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),(tB.length>0||g||y)&&k&&(0,r.jsx)(rq,{options:tB,value:g,onChange:k,disabled:m,busy:w,isAutoSelection:x,defaultValue:S,onSetDefault:C})]}),!es&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsxs)("div",{ref:e4,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:es?0:"auto"},children:[es&&(0,r.jsx)("button",{type:"button",title:ef?void 0:ei("chat.moreControls"),"aria-label":ei("chat.moreControls"),"aria-expanded":ef,"aria-hidden":ef||void 0,tabIndex:ef?-1:void 0,onClick:()=>{em(!0)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:32,padding:"8px 10px",background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:ef?"default":"pointer",fontSize:12,fontWeight:500,visibility:ef?"hidden":"visible",pointerEvents:ef?"none":"auto",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{ef||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{ef||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:ei("chat.moreControls")}),(0,r.jsxs)("div",{style:{display:es?ef?"flex":"none":"flex",alignItems:"center",gap:es?1:2,...es?{position:"absolute",right:0,bottom:0,zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"nowrap",justifyContent:"flex-end",border:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:10,background:"color-mix(in srgb, var(--bg-panel) 92%, var(--bg))",boxShadow:"0 8px 24px rgba(0,0,0,0.14)",backdropFilter:"blur(10px)"}:null},children:[W&&(0,r.jsxs)("div",{ref:e2,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>eh(e=>!e),title:m?ei("chat.currentReasoning",{level:tU}):ei("chat.changeReasoning",{level:tU}),"aria-label":ei("chat.changeReasoningLabel"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:es?"0 6px":"8px 12px",width:es?"auto":void 0,height:32,background:ep?"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=ep?"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"})]}),(!es||ef)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:tU})]}),ep&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",...es?{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:rX.filter(e=>!P||"auto"===e||P.includes(e)).map(e=>{let t="auto"===e?A:!A&&t_===e,n=ei(rQ[e]),i="auto"!==e&&O?O[e]:void 0,o=null!=i&&i!==e?i:e,s=null!=i&&i!==e;return(0,r.jsxs)(rH,{active:t,onSelect:()=>{if(eh(!1),"auto"===e){A||W("auto");return}(!t||A)&&W(e)},gutter:!!B,star:B&&"auto"!==e?{isDefault:F===e,saveLabel:ei("chat.saveDefaultThinking"),defaultLabel:ei("chat.defaultThinking"),onSave:()=>{eh(!1),B(e)}}:void 0,children:[(0,r.jsxs)("span",{style:{flex:1},children:[o,s&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",e,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:n})]},e)})})]}),!m&&L&&(0,r.jsxs)("div",{ref:e1,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>!m&&eu(e=>!e),disabled:m,title:ei("chat.changeToolPreset")+`: ${tZ}`,"aria-label":ei("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:es?"0 6px":"8px 12px",width:es?"auto":void 0,height:32,background:ec?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:m?"not-allowed":"pointer",fontSize:12,opacity:m?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{m||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ec?"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"})}),(!es||ef)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:tZ})]}),ec&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:es?void 0:0,left:es?0:void 0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:120},children:rK.map(e=>{let t,n=rV[e],i=(R??"configured")===n;return t="configured"===e?ei("chat.configuredTools"):"chat-only"===e?ei("chat.chatOnly"):"read-only"===e?ei("chat.readOnlyTools",{count:4}):"default"===e?ei("chat.builtInTools",{count:4}):ei("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{eu(!1),i||L(n)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:t})]},e)})})]}),(!m||$)&&N&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{onClick:$?I:N,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:es?"0 6px":"8px 12px",width:es?"auto":void 0,height:32,background:$?"rgba(239,68,68,0.08)":"none",border:"none",borderRadius:9,color:$?"#ef4444":"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=$?"rgba(239,68,68,0.16)":"var(--bg-hover)",e.currentTarget.style.color=$?"#ef4444":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=$?"rgba(239,68,68,0.08)":"none",e.currentTarget.style.color=$?"#ef4444":"var(--text-muted)"},title:$?ei("chat.stopCompaction"):ei("chat.compactContext"),"aria-label":$?ei("chat.stopCompaction"):ei("chat.compactContext"),children:$?(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"})}),(!es||ef)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:ei("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"})]}),(!es||ef)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:ei("chat.compact")})]})})}),m&&(0,r.jsxs)("button",{onClick:p,title:ei("chat.stopAgent"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:32,background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:9,color:"#ef4444",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.16)"},onMouseLeave:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),ei("chat.stop")]}),void 0!==X&&(0,r.jsx)("button",{onClick:X,title:G?ei("chat.disableSound"):ei("chat.enableSound"),"aria-label":G?ei("chat.disableSound"):ei("chat.enableSound"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:G?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",opacity:G?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=G?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.opacity=G?"1":"0.55"},children:G?(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"})]})}),es&&ef&&(0,r.jsx)("button",{type:"button",title:ei("chat.collapseControls"),"aria-label":ei("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eu(!1),eh(!1),em(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]})]})]})]})});var ic=n(88576),iu=n.n(ic);function ip(e){let{level:t,children:n,headingIndex:i,onClick:o}=e;return(0,r.jsx)("button",{type:"button",className:iu().heading,"data-level":t,"data-preview-heading-index":i??void 0,disabled:null===i||!o,onClick:e=>{e.stopPropagation(),null!==i&&o?.(i)},children:n})}let ih=[...tZ??[],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]:[]}}],im=[[tj.A,{throwOnError:!1,strict:!1}]];function ig(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 ix=(0,i.memo)(function(e){let{markdown:t,onHeadingClick:n,onAnswerClick:o}=e,s=(0,i.useMemo)(()=>tR(t),[t]);return t?(0,r.jsx)("div",{className:iu().outline,children:(0,r.jsx)(ty.oz,{remarkPlugins:ih,rehypePlugins:im,components:{h1:e=>{let{children:t,node:i}=e;return(0,r.jsx)(ip,{level:1,headingIndex:ig(i),onClick:n,children:t})},h2:e=>{let{children:t,node:i}=e;return(0,r.jsx)(ip,{level:2,headingIndex:ig(i),onClick:n,children:t})},h3:e=>{let{children:t,node:i}=e;return(0,r.jsx)(ip,{level:3,headingIndex:ig(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:iu().paragraph,onClick:o,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:s})}):null});function iv(e){let{messages:t,streamingMessage:n,scrollContainer:o,messageRefs:s,onRevealHistory:l}=e,{t:a}=(0,E.s)(),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)([]),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(600),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(null),j=(0,i.useRef)(!1),k=(0,i.useRef)(null),w=(0,i.useRef)([]),S=(0,i.useRef)({nodes:[],gap:50,fillsHeight:!1}),C=(0,i.useRef)(null),N=(0,i.useRef)(new Map),I=(0,i.useRef)(null),$=(0,i.useRef)(null),T=(0,i.useRef)(null),M=(0,i.useMemo)(()=>n?[...t,n]:t,[t,n]),R=(0,i.useRef)(M);R.current=M;let L=(0,i.useMemo)(()=>(function(e,t){if(0===e.length)return{nodes:[],gap:50,fillsHeight:!1};let n=Math.max(1,t),r=Math.max(0,n-24);if(1===e.length)return{nodes:[{...e[0],topRatio:12/n}],gap:50,fillsHeight:!1};let i=r/(e.length-1),o=Math.min(50,i);return{nodes:e.map((e,t)=>({...e,topRatio:(12+t*o)/n})),gap:o,fillsHeight:i<=50}})(u,m),[u,m]),{nodes:z,gap:A}=L;S.current=L;let W=(0,i.useCallback)(e=>{$.current={index:e,until:Date.now()+1600},f(e)},[]),P=(0,i.useCallback)((e,t)=>{let n=$.current;if(n&&Date.now()<n.until)return void f(n.index);$.current=null;let r=t.filter(e=>null!==e.targetTurn.scrollTop);if(0===r.length)return void f(null);let i=e.scrollTop+.3*e.clientHeight;f(r.reduce((e,t)=>Math.abs((t.targetTurn.scrollTop??0)-i)<Math.abs((e.targetTurn.scrollTop??0)-i)?t:e,r[0]).index)},[]),O=(0,i.useCallback)(()=>{let e=o.current;if(!e)return;let t=e.scrollHeight-e.clientHeight,n=w.current;c(t>20),P(e,n)},[o,P]),F=(0,i.useRef)(null),B=(0,i.useCallback)(()=>{F.current||(F.current=setTimeout(()=>{F.current=null;let e=o.current,t=k.current;if(!e||!t)return;let n=s.current,r=e.getBoundingClientRect(),i=[],l=0,a=null;for(let t of R.current){let o=e5(t);if(!o&&"assistant"!==t.role)continue;let s=n?.[l];if(l++,o){a=null;let n=s?.getBoundingClientRect();a={userMessage:t,assistantPreviews:[],scrollTop:n?n.top-r.top+e.scrollTop:null,toolCount:0},i.push(a);continue}if(!a)continue;a.toolCount+="assistant"===t.role&&Array.isArray(t.content)?t.content.reduce((e,t)=>e+ +("toolCall"===t.type),0):0;let d=function(e){if("assistant"!==e.role)return"";let{answerBlocks:t}=tn(e);return t.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n").trim()}(t);d&&a.assistantPreviews.push({markdown:d,element:s})}let d=i.map((e,t)=>({topRatio:0,targetTurn:e,index:t}));g(t.clientHeight),w.current=d,p(d),c(e.scrollHeight-e.clientHeight>20),P(e,d);let u=T.current,h=u?d[u.nodeIndex]:null;if(u&&h){let t=void 0===u.assistantIndex?null:h.targetTurn.assistantPreviews[u.assistantIndex],n=h.targetTurn.scrollTop;if("assistant"===u.target){let i=t?.element?.getBoundingClientRect();n=i?i.top-r.top+e.scrollTop:null}else if("heading"===u.target){let i=void 0===u.headingIndex?null:t?.element?.querySelectorAll("h1, h2, h3").item(u.headingIndex),o=i?.getBoundingClientRect();n=o?o.top-r.top+e.scrollTop:null}if(null===n)return;T.current=null,W(h.index);let i=.3*e.clientHeight;e.scrollTo({top:Math.max(0,n-i),behavior:"smooth"})}},150))},[W,s,o,P]);(0,i.useEffect)(()=>{let e=o.current;if(e)return e.addEventListener("scroll",O,{passive:!0}),()=>e.removeEventListener("scroll",O)},[o,O]),(0,i.useEffect)(()=>{let e=o.current;if(!e)return;let t=()=>{B(),O()},n=new ResizeObserver(t);return n.observe(e),e.firstElementChild&&n.observe(e.firstElementChild),t(),()=>{n.disconnect(),F.current&&(clearTimeout(F.current),F.current=null)}},[B,o,O]),(0,i.useEffect)(()=>{let e=setTimeout(()=>{B(),O()},50);return()=>clearTimeout(e)},[t.length,B,O]);let D=(0,i.useCallback)((e,t)=>{let n=o.current;if(!n)return;if(W(e.index),null===e.targetTurn.scrollTop){T.current={nodeIndex:e.index,target:"user"},l();return}let r=Math.max(0,e.targetTurn.scrollTop-.3*n.clientHeight);n.scrollTo({top:r,behavior:t})},[W,l,o]),H=(0,i.useCallback)((e,t)=>{let n=o.current;if(!n)return;let r=e.targetTurn.assistantPreviews[t]?.element;if(!r){T.current={nodeIndex:e.index,target:"assistant",assistantIndex:t},l();return}let i=n.getBoundingClientRect(),s=r.getBoundingClientRect().top-i.top+n.scrollTop-.3*n.clientHeight;W(e.index),n.scrollTo({top:Math.max(0,s),behavior:"smooth"})},[W,l,o]),_=(0,i.useCallback)(e=>{let{nodes:t,gap:n,fillsHeight:r}=S.current,i=k.current?.clientHeight??0;if(0===t.length||i<=0)return null;let o=Math.max(0,Math.min(i,e*i)),s=t[0].topRatio*i,l=n>0?Math.round((o-s)/n):0,a=Math.max(0,Math.min(t.length-1,l)),d=t[a];if(!r&&Math.abs(o-d.topRatio*i)>Math.max(10,n/2))return null;return d},[]),U=(0,i.useCallback)((e,t,n)=>{let r=o.current;if(!r)return;let i=e.targetTurn.assistantPreviews[t]?.element;if(!i){T.current={nodeIndex:e.index,target:"heading",assistantIndex:t,headingIndex:n},l();return}let s=i.querySelectorAll("h1, h2, h3").item(n);if(!s)return;let a=r.getBoundingClientRect(),d=s.getBoundingClientRect().top-a.top+r.scrollTop-.3*r.clientHeight;W(e.index),r.scrollTo({top:Math.max(0,d),behavior:"smooth"})},[W,l,o]),q=(0,i.useCallback)(()=>{I.current&&(clearTimeout(I.current),I.current=null)},[]),Z=(0,i.useCallback)(()=>{q(),v(!0)},[q]),K=(0,i.useCallback)(()=>{q(),I.current=setTimeout(()=>{I.current=null,v(!1),y(null)},250)},[q]);(0,i.useEffect)(()=>()=>q(),[q]);let V=(0,i.useCallback)(e=>{if(!d)return;j.current=!0,Z();let t=e.currentTarget.getBoundingClientRect();y(Math.max(0,Math.min(1,(e.clientY-t.top)/t.height)));let n=(e,n)=>{let r=_(Math.max(0,Math.min(1,(e-t.top)/t.height)));r&&D(r,n)};n(e.clientY,"smooth");let r=e=>{j.current&&n(e.clientY,"auto")},i=()=>{j.current=!1,window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",i)};window.addEventListener("mousemove",r),window.addEventListener("mouseup",i)},[_,D,Z,d]),J=null===b?null:_(b),Y=J?.index??null;if((0,i.useEffect)(()=>{if(!x||null===Y)return;let e=C.current,t=N.current.get(Y);if(!e||!t)return;let n=t.offsetTop-(e.clientHeight-t.offsetHeight)/2;e.scrollTop=Math.max(0,n)},[u,x,Y]),!d)return null;let G=Math.max(1,(z.length>0?z[z.length-1].topRatio*m:12)-12);return(0,r.jsxs)("div",{ref:k,onMouseDown:V,onMouseEnter:Z,onMouseLeave:K,onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();y((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:[(0,r.jsx)("div",{style:{position:"absolute",left:"50%",top:12,height:G,width:1,background:"var(--border)",transform:"translateX(-50%)",zIndex:0}}),z.map(e=>{let t=x&&J?.index===e.index,n=h===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,A),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)}),x&&u.length>0&&(0,r.jsx)("div",{ref:C,className:iu().preview,"data-minimap-preview-box":"",onMouseEnter:Z,onMouseDown:e=>e.stopPropagation(),onMouseMove:e=>e.stopPropagation(),children:u.map(e=>{var t;let n=Y===e.index;return(0,r.jsxs)("div",{ref:t=>{t?N.current.set(e.index,t):N.current.delete(e.index)},className:iu().turn,"data-minimap-preview-index":e.index,"data-located":n?"true":void 0,children:[(0,r.jsxs)("span",{className:iu().number,children:[(0,r.jsx)("span",{"aria-hidden":"true",children:String(e.index+1).padStart(2,"0")}),e.targetTurn.toolCount>0&&(0,r.jsx)("span",{className:iu().toolBadge,role:"img",title:a("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),"aria-label":a("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),children:e.targetTurn.toolCount>99?"99+":e.targetTurn.toolCount})]}),(0,r.jsxs)("div",{className:iu().content,children:[(0,r.jsx)("button",{type:"button",className:iu().user,"data-minimap-preview-user":e.index,onClick:()=>{D(e,"smooth")},children:(0,r.jsx)("span",{className:iu().userText,children:"string"==typeof(t=e.targetTurn.userMessage).content?t.content.trim():t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim()})}),e.targetTurn.assistantPreviews.map((t,n)=>(0,r.jsxs)("div",{className:iu().assistant,children:[(0,r.jsx)("button",{type:"button",className:iu().assistantJump,"data-minimap-preview-assistant":`${e.index}-${n}`,onClick:()=>H(e,n),"aria-label":a("chatMinimap.locateAssistant"),title:a("chatMinimap.locateAssistant"),children:"A"}),(0,r.jsx)(ix,{markdown:t.markdown,onAnswerClick:()=>H(e,n),onHeadingClick:t=>U(e,n,t)})]},n))]})]},e.index)})})]})}var ib=n(42790);function iy(e){let{text:t}=e,n=(0,i.useMemo)(()=>new ib.v().ansi_to_html(t),[t]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:n}})}function ij(e){let t,n,o,{widgets:s}=e,{t:l}=(0,E.s)(),a=(0,i.useId)(),d=(0,i.useRef)(null),c=(0,i.useRef)(new Map),[u,p]=(0,i.useState)(()=>s.find(e=>{let t=e.lines.length;return t>1&&t<=3})?.key??null),[h,f]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{var e;let t=new Map(s.map(e=>[e.key,[...e.lines]])),n=(e=d.current,e?Array.from(t,t=>{let[n,r]=t,i=e.get(n);return i&&i.length===r.length?r.some((e,t)=>e!==i[t])?n:null:i?n:null}).filter(e=>null!==e):[]);for(let[e,n]of(d.current=t,c.current))t.has(e)||(clearTimeout(n),c.current.delete(e));for(let e of(f(e=>{let r=new Set(Array.from(e).filter(e=>t.has(e)));for(let e of n)r.add(e);return r.size===e.size&&Array.from(r).every(t=>e.has(t))?e:r}),n)){let t=c.current.get(e);t&&clearTimeout(t),c.current.set(e,setTimeout(()=>{c.current.delete(e),f(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},1100))}},[s]),(0,i.useEffect)(()=>()=>{for(let e of c.current.values())clearTimeout(e);c.current.clear()},[]),0===s.length)return null;let m=s.find(e=>e.key===u&&e.lines.length>0);return(0,r.jsxs)(r.Fragment,{children:[m&&(0,r.jsx)("div",{className:"extension-widget-panels",children:(t=s.indexOf(m),n=`${a}-trigger-${t}`,o=`${a}-panel-${t}`,(0,r.jsxs)("section",{id:o,className:"extension-widget-panel","aria-labelledby":n,children:[(0,r.jsx)("div",{className:"extension-widget-panel-heading",children:m.key}),(0,r.jsx)("pre",{className:"extension-widget-content",children:(0,r.jsx)(iy,{text:m.lines.join("\n")})})]},m.key))}),(0,r.jsx)("div",{className:"extension-widget-triggers","aria-label":l("chat.extensionWidgets"),children:s.map((e,t)=>{let n=e.lines.length>0,i=n&&e.key===m?.key,o=h.has(e.key),s=l(1===e.lines.length?"chat.extensionWidgetLine":"chat.extensionWidgetLines",{count:e.lines.length}),d=l("belowEditor"===e.placement?"chat.extensionWidgetBelow":"chat.extensionWidgetAbove"),c=`${a}-trigger-${t}`,u=`${a}-panel-${t}`,f=(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":""}${o?" is-updating":""}`,"aria-controls":u,"aria-expanded":i,"aria-label":`${d}: ${e.key}, ${s}`,title:`${e.key} - ${d} - ${i?l("i18n.collapse"):l("i18n.expand")}`,onClick:()=>{p(t=>{var n;return t===(n=e.key)?null:n})},children:f},e.key):(0,r.jsx)("div",{className:`extension-widget-trigger${o?" is-updating":""}`,"aria-label":`${d}: ${e.key}, ${s}`,title:`${e.key} - ${d}`,children:f},e.key)})})]})}function ik(e){let{statuses:t,widgets:n=[]}=e;if(0===t.length&&0===n.length)return null;let i=[...t].sort((e,t)=>e.key.localeCompare(t.key)).map(e=>{let{text:t}=e;return t.replace(/\r\n?/g,"\n").split("\n").map(e=>e.replace(/\t/g," ").replace(/ +/g," ").trim()).join("\n").trim()}).join(" "),o=e0(i);return(0,r.jsxs)("div",{className:`extension-status-shelf${n.length>0?" has-widgets":""}${t.length>0?" has-status":""}`,children:[n.length>0&&(0,r.jsx)(ij,{widgets:n}),t.length>0&&(0,r.jsx)("div",{role:"status",className:"extension-status-line","aria-label":o,title:o,children:(0,r.jsx)("span",{className:"extension-status-text",children:(0,r.jsx)(iy,{text:i})})})]})}function iw(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document;return"visible"!==e.visibilityState||!e.hasFocus()}function iS(e){switch(e.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==e.closed;default:return!1}}async function iC(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null},n={body:e.body,...e.tag?{tag:e.tag,renotify:!0}:{}};if(t.getServiceWorkerRegistration)try{let r=await t.getServiceWorkerRegistration();if(r)return await r.showNotification(e.title,{...n,data:{url:e.sessionUrl}}),"service-worker"}catch{}try{let r=t.createWindowNotification(e.title,n);return r.onclick=()=>{r.close(),e.onClick()},"window"}catch{return null}}function iE(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function iN(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(!iE(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=iE(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=iE(e.arguments)?e.arguments:null;return n&&r&&"string"==typeof r[n]?r[n]:void 0}(e):void 0;return void 0===r?n:{...n,rawInput:r}})(e,t)??e);return{...e,content:r}}class iI extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}function i$(e){return e instanceof iI&&"prompt_rejected"===e.code&&!1===e.accepted}async function iT(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 iI(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}function iM(){return globalThis.__piSessionViewCache||(globalThis.__piSessionViewCache=new Map),globalThis.__piSessionViewCache}function iR(e){try{return JSON.stringify(e).length}catch{return Number.MAX_SAFE_INTEGER}}function iL(e){let t=iM().get(e);return t?Date.now()-t.savedAt>6e5?(iM().delete(e),null):(iM().delete(e),iM().set(e,t),t):null}function iz(e){if(!e.sessionId||!e.revision)return!1;let t=iM();t.delete(e.sessionId);let n={...e,savedAt:Date.now()};return!(iR(n)>0x2000000)&&(t.set(n.sessionId,n),!function(){let e=iM();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+=iR(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-=iR(r))}}(),iM().has(n.sessionId))}function iA(e){iM().delete(e)}var iW=n(14755);let iP="pi-tool-preset";function iO(){try{return window.localStorage}catch{return null}}function iF(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 iB(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,iF(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),iF(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function iD(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 iH(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(iD).filter(Boolean)}):JSON.stringify({text:"",images:[]})}class i_ 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 iU{constructor(e){this.options=e,this.current=null,this.retry=null,this.retryGeneration=0}close(){this.stopRetrying(),this.current&&this.discard(this.current,new i_("closed"))}maintain(e){if(!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof i_?"startup_error"===n.status?this.stopRetrying():this.scheduleRetry(e):this.options.onUnexpectedError?.(n))})}async ensureConnected(e){for(;;){let t=this.current;if(t&&t.sessionId===e){if(t.attempt.ready&&1===t.source.readyState)return}else t=this.open(e);if(await t.attempt.promise,this.current!==t){if(this.current?.sessionId===e)continue;throw new i_("closed")}if(1===t.source.readyState)return;this.discard(t,new i_("closed"))}}open(e){let t,n,r;this.current&&this.discard(this.current,new i_("closed"));try{t=this.options.createSource(e)}catch(e){throw new i_("closed",e instanceof Error?e.message:String(e))}let i=!1,o=new Promise((e,t)=>{n=e,r=t}),s=setTimeout(()=>{this.fail(a,new i_("ready_timeout"))},this.options.readinessTimeoutMs),l={promise:o,ready:!1,succeed(){i||(i=!0,clearTimeout(s),n())},fail(e){i||(i=!0,clearTimeout(s),r(e))}},a={sessionId:e,source:t,attempt:l};return this.current=a,t.onmessage=e=>{let t;if(this.current===a){try{t=JSON.parse(e.data)}catch{return}if("connected"===t.type)l.ready=!0,l.succeed(),this.stopRetrying();else if("startup_error"===t.type){let e="string"==typeof t.errorMessage?t.errorMessage:void 0;this.fail(a,new i_("startup_error",e));return}this.options.onEvent(t)}},t.onerror=()=>{this.fail(a,new i_("closed"))},a}fail(e,t){this.current===e&&(this.discard(e,t),"startup_error"===t.status?this.stopRetrying():this.scheduleRetry(e.sessionId))}discard(e,t){e.attempt.fail(t),e.source.close(),this.current===e&&(this.current=null)}scheduleRetry(e){if(!this.options.shouldMaintain(e)||this.retry?.sessionId===e)return;this.clearRetry();let t=setTimeout(()=>{this.retry?.timer===t&&(this.retry=null,this.maintain(e))},this.options.reconnectDelayMs);this.retry={sessionId:e,timer:t}}stopRetrying(){this.retryGeneration+=1,this.clearRetry()}clearRetry(){this.retry&&clearTimeout(this.retry.timer),this.retry=null}}function iq(e){return("tool_execution_start"===e.type||"tool_execution_update"===e.type||"tool_execution_end"===e.type)&&"string"==typeof e.parentToolCallId&&""!==e.parentToolCallId}function iZ(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 iK(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function iV(e,t){return e.every(e=>t.has(e.id))?e:e.filter(e=>t.has(e.id))}function iJ(e,t){return e.some(e=>e.id===t)?e.filter(e=>e.id!==t):e}function iY(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return e+t>=n-r}let iG={isStreaming:!1,streamingMessage:null};function iX(e,t,n){let r=e.streamingMessage;if(!r||!Number.isInteger(t)||t<0)return e;let i=[...r.content],o=n(i[t]);return o?(i[t]=o,{isStreaming:!0,streamingMessage:{...r,content:i}}):e}function iQ(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"resume":return{...e,isStreaming:!0};case"snapshot":{let n=iN(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 iX(e,n.contentIndex,()=>({type:"text",text:""}));case"text_delta":return iX(e,n.contentIndex,e=>e?.type==="text"?{...e,text:e.text+n.delta}:null);case"text_end":return iX(e,n.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:n.content}));case"thinking_start":return iX(e,n.contentIndex,()=>({type:"thinking",thinking:""}));case"thinking_delta":return iX(e,n.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+n.delta}:null);case"thinking_end":return iX(e,n.contentIndex,e=>({...e?.type==="thinking"?e:{},type:"thinking",thinking:n.content}));case"toolcall_start":return iX(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 iX(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 iX(e,n.contentIndex,()=>({type:"toolCall",toolCallId:n.toolCall.id,toolName:n.toolCall.name,input:n.toolCall.arguments}));default:return e}case"end":return iG;default:return e}}function i0(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function i1(e){return e&&"auto"!==e?e:null}let i2=new Map,i4=[2e3,5e3,1e4];function i8(e){return new Promise(t=>setTimeout(t,e))}function i3(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function i5(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:i3(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:i3(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=i3(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function i6(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 i9(e){let{label:t}=e,[n,o]=(0,i.useState)(null);if((0,i.useEffect)(()=>{let e=new AbortController;return fetch("/api/app-update",{signal:e.signal}).then(async e=>e.ok?e.json():null).then(e=>{e?.updateAvailable&&e.latestVersion&&e.releaseUrl&&o(e)}).catch(()=>{}),()=>e.abort()},[]),!n)return null;let s=t(n.latestVersion);return(0,r.jsxs)("a",{href:n.releaseUrl,target:"_blank",rel:"noopener noreferrer",title:s,"aria-label":s,onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent"},style:{display:"inline-flex",alignItems:"center",alignSelf:"center",gap:3,minHeight:32,minWidth:0,padding:"0 4px",background:"transparent",borderRadius:5,color:"var(--accent)",fontSize:12,fontWeight:600,lineHeight:1.2,textDecoration:"none",transition:"background 0.12s",whiteSpace:"nowrap"},children:[(0,r.jsxs)("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:["v",n.latestVersion]}),(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:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M7 17 17 7"}),(0,r.jsx)("path",{d:"M7 7h10v10"})]})]})}function i7(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={...e,content:t};return n.omitUsage&&(r.usage=void 0),r}function oe(e){let{messageCount:t,toolCallCount:n,defaultExpanded:o=!1,reveal:s=!1,children:l,t:a}=e,[d,c]=(0,i.useState)(o);(0,i.useLayoutEffect)(()=>{s&&c(!0)},[s]);let u=[a("chat.processDetails"),`${t} ${a(1===t?"chat.message":"chat.messages")}`];return n>0&&u.push(`${n} ${a(1===n?"chat.toolCall":"chat.toolCalls")}`),(0,r.jsxs)("div",{style:{marginBottom:14},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":d||s,onClick:()=>c(e=>!e),style:{display:"flex",alignItems:"center",gap:8,width:"auto",minHeight:24,padding:"2px 0",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},title:a(d?"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:d?"rotate(90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"4 2.5 7.5 6 4 9.5"})}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:u.join(" \xb7 ")})]}),(d||s)&&(0,r.jsx)("div",{style:{marginTop:8},children:l})]})}function ot(e){var t;let o,{session:l,searchTarget:a,onSearchTargetHandled:d,initialScrollPosition:c,onScrollPositionChange:u,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:f,onAgentEnd:m,onAttentionNeeded:g,onSessionCreated:x,onSessionForked:v,modelsRefreshKey:b,chatInputRef:y,onBranchDataChange:j,onSystemPromptChange:k,onSystemToolsChange:w,onSystemInfoLoaderChange:S,onSessionStatsChange:C,onSessionStatsPanelOpen:N,onOpenSettings:I,onContextUsageChange:$,onOpenFile:R,onOpenSession:L,onAskInNewChat:z,quoteSelectionEnabled:A=!1,initialPrompt:W,onInitialPromptConsumed:P,soundEnabled:O=!0,onSoundToggle:F,playDoneSound:B=()=>{},unlockAudio:D}=e,{t:H}=(0,E.s)(),_=ew(),U=l?.relation?.kind!=="subagent",q=(0,i.useRef)(B);q.current=B;let Z=(0,i.useRef)(O);Z.current=O;let K=(0,i.useRef)(!1),V=(0,i.useCallback)(()=>{U&&Z.current&&q.current(),m?.()},[U,m]),J=(0,i.useRef)(a?null:c??null),[Y,G]=(0,i.useState)(()=>{let e=J.current;return e&&!e.atBottom?e:null}),[X,Q]=(0,i.useState)(!1),{loading:ee,error:et,messages:en,activeToolResults:er,entryIds:ei,historyCursor:eo,hasEarlierMessages:es,streamState:el,agentRunning:ea,bashRunning:ed,pendingBash:ec,modelNames:eu,modelList:ep,modelError:eh,modelScopeWarnings:ef,modelThinkingLevels:em,modelThinkingLevelMaps:eg,toolPreset:ex,thinkingLevel:ev,retryInfo:eb,contextUsage:ey,forkingEntryId:ej,isCompacting:ek,compactError:eS,compactResult:eC,displayModel:eE,modelSwitching:eN,sessionStats:eI,slashCommands:e$,slashCommandsLoading:eT,queuedMessages:eM,notices:eR,extensionDialog:eL,waitingExtensionDialogCount:ez,extensionCustomUi:eA,waitingExtensionCustomUiCount:eW,extensionStatuses:eP,extensionWidgets:eO,respondToExtensionUi:eF,sendExtensionCustomInput:eB,setNoticePaused:eD,isAutoModelSelection:eH,isAutoThinkingSelection:e_,defaultModel:eU,savedDefaultThinkingLevel:eq,agentPhase:eZ,isNew:eK,editEntryId:eV,showScrollToBottom:eJ,sessionIdRef:eG,scrollContainerRef:eX,lastUserMsgRef:eQ,promptAnchorActive:e0,handleSend:e1,handleAbort:e2,handleFork:e4,handleEditContent:e8,cancelEdit:e3,handleModelChange:e6,handleCompact:tr,handleSteer:ti,handleFollowUp:to,handlePromptWithStreamingBehavior:tl,handleAbortCompaction:ta,handleRecallQueue:td,handleBuiltinSlashCommand:tm,handleToolPresetChange:ty,handleThinkingLevelChange:tj,handleSetDefaultModel:tk,handleSetDefaultThinkingLevel:tw,loadSlashCommands:tS,scrollUserMsgToTop:tC,loadContext:tE,activeLeafId:tN,scrollToBottom:tI,scrollToMessage:t$}=function(e){let{session:t,newSessionCwd:r,newSessionDraftKey:o,onAgentEnd:s,onAttentionNeeded:l,onSessionCreated:a,onSessionForked:d,modelsRefreshKey:c,onBranchDataChange:u,onSystemPromptChange:p,onSystemToolsChange:h,onSystemInfoLoaderChange:f,onSessionStatsPanelOpen:m,onOpenSettings:g}=e,x=null===t&&null!==r,[v,b]=(0,i.useState)(null),[y,j]=(0,i.useState)(!x),[k,w]=(0,i.useState)(null),[S,C]=(0,i.useState)(null),[E,N]=(0,i.useState)([]),[I,$]=(0,i.useState)(new Map),[T,M]=(0,i.useState)([]),[R,L]=(0,i.useState)(null),[z,A]=(0,i.useState)(!1),[W,P]=(0,i.useReducer)(iQ,iG),[O,F]=(0,i.useState)(!1),[B,D]=(0,i.useState)(!1),[H,_]=(0,i.useState)(null),[U,q]=(0,i.useState)({}),[Z,K]=(0,i.useState)([]),[V,J]=(0,i.useState)(null),[Y,G]=(0,i.useState)([]),[X,Q]=(0,i.useState)({}),[ee,et]=(0,i.useState)({}),[en,er]=(0,i.useState)(null),[ei,eo]=(0,i.useState)(null),[es,el]=(0,i.useState)(iW.Q8),[ea,ed]=(0,i.useState)(null),[ec,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(null),[ef,em]=(0,i.useState)(null),[eg,ex]=(0,i.useState)(null),[ev,eb]=(0,i.useState)(null),[ey,ej]=(0,i.useState)(null),[ek,ew]=(0,i.useState)(null),[eS,eC]=(0,i.useState)(null),[eE,eN]=(0,i.useState)(null),[eI,e$]=(0,i.useState)(null),[eT,eM]=(0,i.useState)(null),[eR,eL]=(0,i.useState)(!1),[ez,eA]=(0,i.useState)(!1),[eW,eP]=(0,i.useState)(!0),[eO,eF]=(0,i.useState)(null),[eB,eD]=(0,i.useState)(null),[eH,e_]=(0,i.useState)(null),[eU,eq]=(0,i.useState)(!1),[eZ,eK]=(0,i.useState)(!1),[eV,eJ]=(0,i.useState)([]),[eY,eG]=(0,i.useState)(!1),[eX,eQ]=(0,i.useReducer)(i5,{visible:[],pending:[]}),[e0,e1]=(0,i.useState)(null),[e2,e4]=(0,i.useState)([]),[e8,e3]=(0,i.useState)([]),[e5,e6]=(0,i.useState)([]),[e9,e7]=(0,i.useState)([]),[te,tt]=(0,i.useState)({steering:[],followUp:[]}),tn=(0,i.useRef)(null),tr=(0,i.useRef)(null),ti=(0,i.useRef)(0),to=(0,i.useRef)(!1),ts=(0,i.useRef)(t?.id??null),tl=(0,i.useRef)(t?.id??null),ta=(0,i.useRef)(!1),td=(0,i.useRef)(!1),tc=(0,i.useRef)(!1),tu=(0,i.useRef)(!1),tp=(0,i.useRef)(-1),th=(0,i.useRef)(!1),tf=(0,i.useRef)(0),tm=(0,i.useRef)(null),tg=(0,i.useRef)(!!e.deferInitialScroll),tx=(0,i.useRef)(null),tv=(0,i.useRef)(!1),tb=(0,i.useRef)(!0),ty=(0,i.useRef)(0),tj=(0,i.useRef)(null),tk=(0,i.useRef)(void 0),tw=(0,i.useRef)(void 0),tS=(0,i.useRef)(null),tC=(0,i.useRef)(null),tE=(0,i.useRef)([]),tN=(0,i.useRef)(null),tI=(0,i.useRef)(0),t$=(0,i.useRef)(!1),tT=(0,i.useRef)(null),tM=(0,i.useRef)(null),tR=(0,i.useRef)({}),tL=(0,i.useRef)(null),tz=(0,i.useRef)(0),tA=(0,i.useRef)(null),tW=(0,i.useRef)(!1),tP=(0,i.useRef)(new Map),tO=(0,i.useRef)(!0),tF=(0,i.useRef)(new Map),tB=(0,i.useRef)(null),tD=(0,i.useRef)([]),tH=(0,i.useRef)([]),t_=(0,i.useRef)(null),tU=(0,i.useRef)(null),tq=(0,i.useRef)(!1);tl.current=t?.id??null,tB.current=v,tD.current=E,tH.current=T,t_.current=S,tU.current=R,tq.current=z,tn.current||(tn.current=new iU({createSource:e=>new EventSource(`/api/agent/${encodeURIComponent(e)}/events`),onEvent:e=>tm.current?.(e),shouldMaintain:e=>tO.current&&ts.current===e&&(td.current||to.current||tl.current===e),readinessTimeoutMs:6e4,reconnectDelayMs:1e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let tZ=e.setToolPreset??el,tK=t?.id;(0,i.useLayoutEffect)(()=>{(tK||x&&!ts.current)&&tZ(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:iO();if(!e)return iW.Q8;try{let t=e.getItem(iP);return(0,iW.sn)(t)?t:iW.Q8}catch{return iW.Q8}}())},[tK,x,tZ]);let tV=(0,i.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"smooth",t=tS.current;t&&(t.scrollTo({top:t.scrollHeight,behavior:e}),ty.current=t.scrollTop)},[]),tJ=eE??eI??v?.context.model??eT??null,tY=x?en??ei:tJ??(v?.context.messages.length===0?ei:null),tG=i1(v?.context.thinkingLevel&&"off"!==v.context.thinkingLevel?v.context.thinkingLevel:null),tX=x?ea??ec:ef??eg??tG??(v?.context.messages.length===0?ec:null),tQ=t?.id??o??void 0,t0=(0,i.useCallback)(e=>{e$(e?.model?{provider:e.model.provider,modelId:e.model.id}:null),e?.thinkingLevel!==void 0&&ex(i1(e.thinkingLevel))},[]),t1=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=tP.current.get(t);if(!e)break;t=e}return t},[]),t2=(0,i.useCallback)((t,n,r)=>{let i=n?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}}),s=t1(r);if(!tO.current&&!t$.current&&r===o)return;let l=e.chatInputRef?.current;if(l)l.restoreSubmission(t,i,s);else{let e,n;s&&(n=ro(t,i,(e=rt(s)??{value:"",images:[]}).value,e.images),rn(s,n))}},[o,e.chatInputRef,t1]),[t4,t8]=(0,i.useState)(()=>{let e=t?.id;return e&&!rt(e)&&i2.delete(e),e&&i2.get(e)||null}),t3=(0,i.useCallback)(e=>{t?.id&&(e?i2.set(t.id,e):i2.delete(t.id),t8(e))},[t?.id]),t5=(0,i.useCallback)((n,r)=>{t?.id&&(e.chatInputRef?.current?.replaceMessage(n),t3(r))},[e.chatInputRef,t?.id,t3]),t6=(0,i.useCallback)(()=>t3(null),[t3]),t9=(0,i.useMemo)(()=>{if(e0)return{...e0,totalActiveMs:v?.totalActiveMs,...ey?{contextUsage:ey}:{}};let e=v?.stats,n=function(e,t,n){let r=iB(n);if(!e)return r;let i=iB(t),o=(e,t)=>Math.max(0,e-t),s={input:e.tokens.input+o(r.tokens.input,i.tokens.input),output:e.tokens.output+o(r.tokens.output,i.tokens.output),cacheRead:e.tokens.cacheRead+o(r.tokens.cacheRead,i.tokens.cacheRead),cacheWrite:e.tokens.cacheWrite+o(r.tokens.cacheWrite,i.tokens.cacheWrite),total:0};return s.total=s.input+s.output+s.cacheRead+s.cacheWrite,{userMessages:e.userMessages+o(r.userMessages,i.userMessages),assistantMessages:e.assistantMessages+o(r.assistantMessages,i.assistantMessages),toolCalls:e.toolCalls+o(r.toolCalls,i.toolCalls),toolResults:e.toolResults+o(r.toolResults,i.toolResults),totalMessages:e.totalMessages+o(r.totalMessages,i.totalMessages),tokens:s,cost:e.cost+o(r.cost,i.cost)}}(e,v?.context.messages??[],E);return 0!==n.tokens.total||0!==E.length||e?{sessionFile:v?.filePath||void 0,sessionId:ts.current??t?.id??"",sessionName:t?.name,...n,totalActiveMs:v?.totalActiveMs,...ey?{contextUsage:ey}:{}}:null},[E,e0,ey,v?.context.messages,v?.filePath,v?.totalActiveMs,v?.stats,t?.id,t?.name]),t7=(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,o=r?.force?void 0:tF.current.get(i);if(o)return await o;let s=(async()=>{let i=!1;try{t&&j(!0);let o=new URLSearchParams({deferThinking:"1",deferMedia:"1",tree:"summary"});r?.force&&o.set("force","1");let s=await fetch(`/api/sessions/${encodeURIComponent(e)}?${o}`);if(404===s.status)return t&&(b(null),C(null),N([]),M([]),L(null),A(!1),w(null)),iA(e),null;if(!s.ok)throw Error(`HTTP ${s.status}`);let l=await s.json();if(ts.current!==e)return null;let a=iL(e),d=!!(l.snapshotRevision&&a?.revision===l.snapshotRevision&&a.entryIds.length>=(l.context.entryIds??[]).length),c=d?tD.current:l.context.messages;if(b(d?{...l,context:{...l.context,messages:tD.current,entryIds:tH.current,oldestEntryId:tU.current,hasMore:tq.current}}:l),C(l.leafId),d?iz({sessionId:e,revision:l.snapshotRevision,messages:tD.current,entryIds:tH.current,leafId:l.leafId,oldestEntryId:tU.current,hasMore:tq.current,summaryTree:l.tree,thinkingLevel:l.context.thinkingLevel,model:l.context.model,stats:l.stats,totalActiveMs:l.totalActiveMs,loadedEntryIds:tH.current}):(N(c),M(l.context.entryIds??[]),L(l.context.oldestEntryId),A(l.context.hasMore)),ta.current=void 0!==l.toolNames,tZ(void 0!==l.toolNames?(0,iW.YO)(l.toolNames):iW.Q8),eN(e=>tW.current?e:null),em(null),w(null),"summary"===l.treeFormat&&l.snapshotRevision&&iz({sessionId:e,revision:l.snapshotRevision,messages:c,entryIds:l.context.entryIds??[],leafId:l.leafId,oldestEntryId:l.context.oldestEntryId,hasMore:l.context.hasMore,summaryTree:l.tree,thinkingLevel:l.context.thinkingLevel,model:l.context.model,stats:l.stats,totalActiveMs:l.totalActiveMs,loadedEntryIds:l.context.entryIds??[]}),l.wrapperRebuilt&&(tn.current?.close(),tn.current?.maintain(e)),!n&&l.context.thinkingLevel&&"off"!==l.context.thinkingLevel&&ex(i1(l.context.thinkingLevel)),i=!0,t&&j(!1),!n)return null;try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();if(ts.current!==e)return null;let r=n.state;return t0(r),r?(void 0!==r.contextUsage&&ej(r.contextUsage??null),void 0!==r.systemPrompt&&ew(r.systemPrompt??null),void 0!==r.extensionStatuses&&e6(r.extensionStatuses??[]),void 0!==r.extensionWidgets&&e7(r.extensionWidgets??[]),void 0!==r.queuedMessages&&tt(i0(r.queuedMessages)),void 0!==r.autoCompactionEnabled&&eP(r.autoCompactionEnabled??!0)):n.running||tt({steering:[],followUp:[]}),n}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),"error"}finally{t&&!i&&j(!1)}})();return r?.force||tF.current.set(i,s),s.finally(()=>{tF.current.get(i)===s&&tF.current.delete(i)}),await s},[tZ,t0]),ne=(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 o=`/api/sessions/${encodeURIComponent(e)}/context?${i}`,s=await fetch(o,{signal:r?.signal});if(!s.ok)throw Error(`HTTP ${s.status}`);let l=await s.json();if(ts.current!==e||r?.signal?.aborted||!tO.current)return;return L(l.context.oldestEntryId),A(l.context.hasMore),b(t=>{if(!t||t.sessionId!==e)return t;let r=n?{...t.context,messages:[...l.context.messages,...t.context.messages],entryIds:[...l.context.entryIds,...t.context.entryIds],oldestEntryId:l.context.oldestEntryId,hasMore:l.context.hasMore}:l.context;return{...t,context:r}}),n?(N(e=>[...l.context.messages,...e]),M(e=>[...l.context.entryIds,...e])):(N(l.context.messages),M(l.context.entryIds??[])),l.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),nt=(0,i.useCallback)(async e=>{try{let t=await iT(e,{type:"get_tools"});if(!t||!tO.current||ts.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return tZ(ta.current?r(t):iW.Q8),h?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[h,tZ]),nn=(0,i.useCallback)(function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"(no messages)",i=ts.current;if(x&&r&&i&&!t$.current&&(t$.current=!0,o)){if(o!==i){tP.current.set(o,i);let t=e.chatInputRef?.current;t?t.rekeyDraft(o,i):rs(o,i)}a?.({id:i,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0},o)}},[x,r,o,a,e.chatInputRef]),nr=(0,i.useCallback)(async()=>{if(ts.current||!x||!r)return ts.current;if(tC.current)return tC.current;let e=(async()=>{let e=tT.current,t=tM.current;e&&eM(e);let n=(0,iW.xG)(es);ta.current=void 0!==n;let i=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r,type:"ensure_session",...void 0!==n?{toolNames:n}:{},...e?{provider:e.provider,modelId:e.modelId}:{},...t?{thinkingLevel:t}:{}})});if(!i.ok)throw Error(`HTTP ${i.status}`);let o=await i.json(),s=o.sessionId;return ts.current=s,o.model&&tT.current===e&&(eM(o.model),e||eo(o.model)),o.thinkingLevel&&tM.current===t&&(ex(i1(o.thinkingLevel)),t||eu(i1(o.thinkingLevel))),s})();tC.current=e;try{return await e}finally{tC.current=null}},[x,r,es]),ni=(0,i.useCallback)(async()=>{let e=ts.current??await nr();if(!e)return;let[t]=await Promise.all([iT(e,{type:"get_state"}),nt(e)]);tO.current&&ts.current===e&&(t0(t),ew(t.systemPrompt??""))},[nr,nt,t0]),no=(0,i.useCallback)(e=>{tE.current=e,eJ(e)},[]),ns=(0,i.useCallback)(()=>{tI.current+=1,tN.current=null,no([])},[no]),nl=(0,i.useCallback)(()=>{let e=++tI.current,t=(async()=>{let t=ts.current??await nr();if(!t)return tI.current===e&&no([]),[];eG(!0);try{let n=await iT(t,{type:"get_commands"}),r=n?.commands??[];return tI.current===e&&no(r),r}catch(t){return console.error("Failed to load slash commands:",t),tI.current===e&&no([]),null}finally{tI.current!==e&&tN.current||eG(!1)}})();tN.current=t;let n=()=>{tN.current===t&&(tN.current=null)};return t.then(n,n),t},[nr,no]),na=(0,i.useCallback)(async()=>await nl()??[],[nl]),nd=(0,i.useCallback)(async()=>{let e=tN.current,t=tE.current;return!e&&t.length>0?t:await (e??nl()).catch(()=>null)??(t.length>0?t:null)},[nl]),nc=(0,i.useCallback)(()=>{ti.current+=1,to.current=!1,tr.current&&(clearTimeout(tr.current),tr.current=null)},[]),nu=(0,i.useCallback)(()=>{tn.current?.close()},[]),np=(0,i.useCallback)(e=>tn.current.ensureConnected(e),[]),nh=(0,i.useCallback)(e=>{tn.current.maintain(e)},[]);(0,i.useEffect)(()=>{let e=t?.id;if(e)return tO.current=!0,nh(e),()=>{ts.current===e&&tn.current?.close()}},[nh,t?.id]),(0,i.useEffect)(()=>{let e=t?.id;if(!e)return;let n=!1,r=!1,i=async()=>{if(!n&&!r){r=!0;try{let t=await fetch(`/api/agent/${encodeURIComponent(e)}/lease`,{method:"POST",cache:"no-store"});if(!t.ok||n)return;let r=await t.json();n||0!==r.renewed||ts.current!==e||tl.current!==e||(nu(),nh(e))}catch{}finally{r=!1}}},o=setInterval(()=>void i(),3e4),s=()=>{"visible"===document.visibilityState&&i()};return document.addEventListener("visibilitychange",s),()=>{n=!0,clearInterval(o),document.removeEventListener("visibilitychange",s)}},[nu,nh,t?.id]);let nf=(0,i.useCallback)(async(e,t)=>{let n=ts.current;if(e4(t=>iJ(t,e.id)),n)try{await iT(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e)}},[]),nm=(0,i.useCallback)(async(e,t)=>{let n=ts.current;if(n)try{await iT(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),ng=(0,i.useCallback)(e=>{let t=e.message.trim();t&&eQ({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"}})},[]),nx=(0,i.useCallback)(t=>{switch(iS(t)&&l?.(t),t.method){case"select":case"confirm":case"input":case"editor":e4(e=>e.some(e=>e.id===t.id)?e:[...e,t]);break;case"notify":ng({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":e6(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":e7(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},o=e.findIndex(e=>e.key===t);return -1===o?[...e,i]:e.map((e,t)=>t===o?i:e)})(e,t.widgetKey,t.widgetLines,t.widgetPlacement));break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":e3(e=>{let n;return t.closed?iJ(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)})}},[ng,l,e.chatInputRef]),nv=(0,i.useCallback)(()=>{let e=td.current;return td.current=!1,F(!1),e_(null),eb(null),$(new Map),P({type:"end"}),e},[]),nb=(0,i.useCallback)(e=>tp.current!==e&&(tp.current=e,s?.(),!0),[s]),ny=(0,i.useCallback)(e=>{if(tl.current===e)return void nc();nc(),to.current=!0;let t=ti.current,n=async()=>{if(t===ti.current&&ts.current===e&&to.current)try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(t!==ti.current||ts.current!==e||!to.current)return;let o=i.state;if(t0(o),i.running&&o&&(o.isStreaming||o.isPromptRunning)){to.current=!1,tr.current=null,tc.current=!!o?.isStreaming,tu.current=!!o?.isPromptRunning,td.current=!0,F(!0),e_(o?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(i.running&&o?.isCompacting){eA(!0),tr.current=setTimeout(()=>void n(),600);return}to.current=!1,tr.current=null,nu()}catch{if(t!==ti.current||ts.current!==e||!to.current)return;tr.current=setTimeout(()=>void n(),600)}};tr.current=setTimeout(()=>void n(),3e4)},[nc,nu,t0]),nj=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ts.current,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tz.current;if(tz.current===t)try{e&&await t7(e)}finally{if(tz.current!==t)return;let n=tu.current,r=tc.current;tu.current=!1,tc.current=!1,tA.current=null;let i=nv();n?nb(t):r&&i&&s?.(),e&&ny(e)}},[t7,nb,s,ny,nv]),nw=(0,i.useCallback)(async(e,t)=>{await i8(800);let n=Date.now();for(;td.current&&Date.now()-n<2e4;){if(void 0!==t&&tz.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(t0(i),!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await nj(e,t)}}catch{}await i8(600)}},[nj,t0]),nC=(0,i.useCallback)(async e=>{let t=tf.current+1;for(tf.current=t;th.current&&tf.current===t&&ts.current===e;){await i8(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(t0(r.state),r.state?.isBashRunning)continue;if(await t7(e),tf.current!==t||ts.current!==e)return;th.current=!1,D(!1),_(null);return}catch{}}},[t7,t0]),nN=(0,i.useCallback)(async e=>{if(!td.current||ts.current!==e)return;let t=tz.current;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)return;let r=await n.json();if(ts.current!==e||tz.current!==t)return;let i=r.state;if(t0(i),eA(i?.isCompacting??!1),eP(i?.autoCompactionEnabled??!0),tt(i0(i?.queuedMessages)),r.running&&i&&(i.isStreaming||i.isPromptRunning||i.isCompacting)){tc.current=!!i.isStreaming,tu.current=!!i.isPromptRunning;return}if(!td.current)return;i&&(void 0!==i.contextUsage&&ej(i.contextUsage??null),void 0!==i.systemPrompt&&ew(i.systemPrompt??null),void 0!==i.extensionStatuses&&e6(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&e7(i.extensionWidgets??[])),await nj(e,t)}catch{}},[nj,t0]);(0,i.useEffect)(()=>{if(!O)return;let e=()=>{let e=ts.current;e&&nN(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)}},[O,nN]),(0,i.useEffect)(()=>{td.current=O},[O]),tm.current=(0,i.useCallback)(e=>{switch(e.type){case"connected":if(P({type:"end"}),Array.isArray(e.pendingExtensionUiIds)){let t=new Set(e.pendingExtensionUiIds);e4(e=>iV(e,t)),e3(e=>iV(e,t))}!0===e.isStreaming&&(nc(),tc.current=!0,td.current=!0,F(!0),e_({kind:"waiting_model"}));break;case"agent_start":nc(),tc.current=!0,td.current=!0,F(!0),e_({kind:"waiting_model"}),P({type:"start"});break;case"agent_end":if(!td.current)break;e_(null),eb(null),P({type:"end"}),ts.current&&(t7(ts.current),fetch(`/api/agent/${encodeURIComponent(ts.current)}`).then(e=>e.json()).then(e=>{t0(e.state),e.state?.contextUsage!==void 0&&ej(e.state.contextUsage??null),e.state?.systemPrompt!==void 0&&ew(e.state.systemPrompt??null),e.state?.extensionStatuses!==void 0&&e6(e.state.extensionStatuses??[]),e.state?.extensionWidgets!==void 0&&e7(e.state.extensionWidgets??[]),tt(i0(e.state?.queuedMessages))}).catch(()=>{}));break;case"agent_settled":{let e=tc.current;if(tc.current=!1,!e||tu.current)break;let t=ts.current,n=nv();eA(!1),t&&(t7(t),ny(t)),n&&s?.();break}case"prompt_done":{let e=tz.current,t=tu.current;tu.current=!1,tA.current=null;let n=nb(e);if(!t&&!n)break;let r=ts.current;r&&t7(r),!tc.current&&(nv(),r&&ny(r))}break;case"prompt_error":ng({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":ng({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":if(!td.current||iZ(e))break;if("message_start"===e.type){let t=e.message;if(t?.role==="user")break;t?.role==="assistant"?(P({type:"snapshot",message:t}),t.content.length>0&&e_(null)):t&&e_(null)}else{let t=e.assistantMessageEvent;t&&(P({type:"delta",event:t}),"toolcall_start"!==t.type&&"toolcall_delta"!==t.type&&e_(null))}!tv.current&&tb.current&&null===tj.current&&(tj.current=requestAnimationFrame(()=>{tj.current=null,tb.current&&tV("auto")}));break;case"message_end":{if(!td.current||iZ(e))break;let t=e.message;if(t&&"user"===t.role){let e=iN(t),n=iH(e),r=tA.current;tA.current=null,N(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&iH(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]})}else t&&N(e=>[...e,iN(t)]);P({type:"end"}),e_({kind:"waiting_model"});break}case"tool_execution_start":{if(iq(e))break;let t=e.toolCallId,n=e.toolName;e_(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[];return r.some(e=>e.id===t)||r.push({id:t,name:n}),{kind:"running_tools",tools:r}});break}case"tool_execution_update":{if(iq(e))break;let t=e.toolCallId,n=e.toolName,r=e.partialResult,i=r?.content;("bash"===n||"powershell"===n||n===nk)&&Array.isArray(i)&&$(e=>{let o=new Map(e);return o.set(t,{role:"toolResult",toolCallId:t,toolName:n,content:i,isError:r?.isError,details:r?.details}),o});let o=n===nk?function(e){if(!nS(e))return null;let{calls:t}=nE(e.details),n=t.findLast(e=>"running"===e.status)??t.at(-1);if(!n)return null;let r=n.args.length>120?`${n.args.slice(0,117)}...`:n.args;return r?`${n.name} ${r}`:n.name}(e.partialResult):function(e){if(!iK(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>iK(e)&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n").split(/\r?\n/),r="";for(let e=n.length-1;e>=0&&!(r=n[e].trim());e-=1);if(!r)return null;let i=r.replace(/\s+/g," ");return i.length<=500?i:`...${i.slice(-497)}`}(e.partialResult);e_(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[],i=r.find(e=>e.id===t),s={id:t,name:n||i?.name||"tool",progress:o??i?.progress};return{kind:"running_tools",tools:[...r.filter(e=>e.id!==t),s]}});break}case"tool_execution_end":{if(iq(e))break;let t=e.toolCallId;$(e=>{if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}),e_(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"queue_update":tt({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":eb({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":eb(null);break;case"auto_compaction_start":case"compaction_start":eA(!0),eF(null),eD(null);break;case"auto_compaction_end":case"compaction_end":eA(!1),e.errorMessage?(eF(e.errorMessage),eD(null)):!e.aborted&&(eD(i6(e.result,e.reason??"auto")),ts.current&&t7(ts.current));break;case"extension_ui_request":nx(e);break;case"extension_ui_closed":e4(t=>iJ(t,e.id))}},[ng,nc,nx,t7,nb,s,ny,tV,nv,t0]);let nI=(0,i.useCallback)(async(e,n)=>{let i=e.trim();if(!i&&!n?.length)return;if(td.current||th.current)return void t2(e,n,tQ);if(t4&&(t3(null),!await tw.current?.(t4))){t3(t4),t2(e,n,tQ);return}let o=!n?.length&&i.startsWith("/");if(!n?.length&&i.startsWith("!")){let t=i.startsWith("!!"),r=(t?i.slice(2):i.slice(1)).trim();return r?void await tk.current?.(r,t):void t2(e,n,tQ)}let s=tz.current+1;nc(),tu.current=!0;let l=n?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),a={role:"user",content:l?.length?[...e.trim()?[{type:"text",text:e}]:[],...l]:e,timestamp:Date.now()};N(e=>[...e,a]),tA.current=iH(a),tz.current=s,td.current=!0,F(!0),e_(o?{kind:"running_command"}:{kind:"waiting_model"}),P({type:"start"}),tv.current=!0,eq(!0);let d=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),c=null,u=!1;try{if(x&&r){let t=ts.current??await tC.current,n=t??await nr();if(!n)throw Error("Unable to create a session for the prompt");c=n,en&&(eM(en),t&&await iT(n,{type:"set_model",provider:en.provider,modelId:en.modelId})),await np(n),u=!0,await iT(n,{type:"prompt",message:e,...d?.length?{images:d}:{}}),nn(1,e)}else if(t)c=t.id,await np(t.id),u=!0,await iT(t.id,{type:"prompt",message:e,...d?.length?{images:d}:{}});else throw Error("No active session for the prompt");o&&c&&nw(c,s)}catch(t){if(console.error("Failed to send message:",t),!(!u||i$(t))&&c)return void nw(c,s);if(tu.current=!1,N(e=>{let t=e.lastIndexOf(a);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),ng({type:"error",message:t instanceof Error?t.message:String(t)}),t2(e,n,tQ),tA.current=null,c)return void nN(c);td.current=!1,nu(),F(!1),e_(null),P({type:"end"})}},[x,r,en,t,nr,np,nn,nw,ng,nc,nu,tQ,nN,t2,t4,t3]);tk.current=(0,i.useCallback)(async(e,n)=>{if(td.current||th.current)return;let r=`${n?"!!":"!"}${e}`;th.current=!0,_({command:e,excludeFromContext:n}),D(!0);try{let i=ts.current??t?.id??await nr();if(!i)throw Error("Unable to create a session for the shell command");await iT(i,{type:"bash",command:e,excludeFromContext:n}),await t7(i),nn(1,r)}catch(e){console.error("Failed to execute shell command:",e),ng({type:"error",message:e instanceof Error?e.message:String(e)}),t2(r,void 0,tQ)}finally{th.current=!1,_(null),D(!1)}},[ng,tQ,nr,t7,nn,t2,t]);let n$=(0,i.useCallback)(async()=>{let e=ts.current;if(e){if(th.current){try{await iT(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await iT(e,{type:"abort"})}catch(e){console.error("Failed to abort:",e)}}},[]),nT=(0,i.useCallback)(async e=>{if(th.current)return;let t=ts.current;if(t){eC(e);try{let{cancelled:n,newSessionId:r}=await iT(t,{type:"fork",entryId:e})??{};!n&&r&&d?.(r)}catch(e){console.error("Fork failed:",e),ng({type:"error",message:e instanceof Error?e.message:String(e)})}finally{eC(null)}}},[ng,d]),nM=(0,i.useCallback)(async e=>{if(th.current)return!1;let t=ts.current;if(!t)return!1;try{let n=await iT(t,{type:"navigate_tree",targetId:e});if(n?.cancelled||ts.current!==t)return!1;return await t7(t),ts.current===t}catch(e){return console.error("Failed to navigate:",e),!1}},[t7]);tw.current=nM;let nR=(0,i.useCallback)(async e=>{if(th.current||td.current||ez)return;C(e);let t=ts.current;t&&(await ne(t,e),e&&iT(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[ez,ne]),nL=(0,i.useCallback)(async(e,t)=>{if(x){let n={provider:e,modelId:t};tT.current=n,er(n),eM(n),null===tM.current&&eu(i1(tR.current[`${e}/${t}`])??tL.current);let r=ts.current??await tC.current;if(!r)return;try{await iT(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=ts.current;if(n&&!tW.current){tW.current=!0,eN({provider:e,modelId:t}),eL(!0);try{let r=await iT(n,{type:"set_model",provider:e,modelId:t});e$({provider:r.provider,modelId:r.id}),tW.current=!1,await t7(n)}catch(e){console.error("Failed to set model:",e),tW.current=!1,eN(eE),ng({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await t7(n,!1,!0)}finally{tW.current=!1,eL(!1)}}},[ng,eE,x,t7,er]),nz=(0,i.useCallback)(async()=>{let e=ts.current;if(e&&!ez){eA(!0),eF(null),eD(null);try{let t=await iT(e,{type:"compact"});eD(i6(t,"manual")),await t7(e,!0)}catch(e){eF(e instanceof Error?e.message:String(e)),eD(null)}finally{eA(!1)}}},[ez,t7]),nA=(0,i.useCallback)(async e=>{let n,i=r??t?.cwd??"",o=i?`/api/models?cwd=${encodeURIComponent(i)}`:"/api/models";try{let t=await fetch(o,e?{signal:e}:void 0);if(!t.ok){let e="";try{let n=await t.json();n&&"object"==typeof n&&"error"in n&&"string"==typeof n.error&&(e=n.error)}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw e}throw Error(e||`Failed to load models (HTTP ${t.status})`)}n=await t.json(),e?.throwIfAborted()}catch(t){throw e?.aborted||t instanceof DOMException&&"AbortError"===t.name||J(t instanceof Error?t.message:String(t)),t}q(n.models),J(n.modelError??null),G(n.modelScopeWarnings??[]),Q(n.thinkingLevels??{}),et(n.thinkingLevelMaps??{});let s=n.modelList??[];K(s);let l=n.defaultModel?s.find(e=>e.id===n.defaultModel?.modelId&&e.provider===n.defaultModel?.provider):void 0;if(eo(l?{provider:l.provider,modelId:l.id}:null),tR.current=n.thinkingLevelPins??{},tL.current=i1(n.defaultThinkingLevel),eh(i1(n.savedDefaultThinkingLevel)),x&&!ts.current){let e=l&&n.thinkingLevelPins?.[`${l.provider}/${l.id}`];null===tM.current&&eu(i1(e)??tL.current)}},[x,r,t?.cwd]),nW=(0,i.useCallback)(async e=>{let n=r??t?.cwd,i=await fetch("/api/models/default",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...n?{cwd:n}:{},...e})});if(i.ok)return;let o="";try{let e=await i.json();e&&"object"==typeof e&&"error"in e&&"string"==typeof e.error&&(o=e.error)}catch{}throw Error(o||`HTTP ${i.status}`)},[r,t?.cwd]),nP=(0,i.useCallback)(()=>{nA().catch(()=>{})},[nA]),nO=(0,i.useCallback)(async(e,t)=>{try{await nW({provider:e,modelId:t})}catch(e){ng({type:"error",message:`Failed to save default model: ${e instanceof Error?e.message:String(e)}`});return}ng({type:"success",message:`Default model: ${e}/${t}`}),eo({provider:e,modelId:t}),(tY?.provider!==e||tY?.modelId!==t)&&await nL(e,t),nP()},[ng,tY,nL,nP,nW]),nF=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,n,r=""]=t,i=r.trim(),o=ts.current??await nr(),s=e=>(e.handled&&(e.error?ng({type:"error",message:e.error}):e.action||ng({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!o||ez)return s({handled:!0,error:"No active session to compact"});eA(!0),eF(null),eD(null);let e=await iT(o,{type:"compact",...i?{customInstructions:i}:{}});return eD(i6(e,"manual")),await t7(o,!0)&&nn(),s({handled:!0,message:"Compacted context"})}case"auto-compact":{if(!o)return s({handled:!0,error:"No active session"});let e=await iT(o,{type:"get_state"}),t=!(e?.autoCompactionEnabled??!0);return await iT(o,{type:"set_auto_compaction",enabled:t}),eP(t),s({handled:!0,message:t?"Auto-compaction enabled":"Auto-compaction disabled"})}case"reload":if(!o)return s({handled:!0,error:"No active session to reload"});return await iT(o,{type:"reload"}),await Promise.all([t7(o,!1,!0),nt(o),na(),nA()]),s({handled:!0,message:"Reloaded session resources"});case"name":if(!o)return s({handled:!0,error:"No active session to name"});if(!i)return s({handled:!0,error:"Usage: /name <name>"});return await iT(o,{type:"set_session_name",name:i}),await t7(o)&&nn(),s({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!o)return s({handled:!0,error:"No active session"});let e=await iT(o,{type:"get_session_stats"});return e&&e1(e),m?.(),s({handled:!0,action:"openSessionStats"})}case"mcp":{if(i||!g)return{handled:!1};let e=await nd();if(!e||!(e.some(rg)||!e.some(e=>"mcp"===e.name)))return{handled:!1};return g("mcp"),s({handled:!0,action:"openSettings"})}case"copy":{if(!o)return s({handled:!0,error:"No active session"});let e=await iT(o,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return s({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),s({handled:!0,message:"Copied last assistant message"})}case"clone":{if(!o)return s({handled:!0,error:"No active session to clone"});if(td.current||th.current)return s({handled:!0,error:"Cannot clone while the session is running"});let e=await iT(o,{type:"clone",leafId:S});if(e?.cancelled||!e?.newSessionId)return s({handled:!0,error:"Cannot clone an empty or unsaved session"});let t=s({handled:!0,message:"Cloned current session branch"});return d?.(e.newSessionId),t}default:return{handled:!1}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&eA(!1)}},[S,ng,nr,ez,nA,t7,na,nt,nn,g,d,m,nd]),nB=(0,i.useCallback)(async(e,t,n)=>{let r=ts.current;if(t4)return void t2(e,n,tQ);if(!r){t2(e,n,tQ),ng({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 iT(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){console.error("Failed to submit streaming prompt:",t),i$(t)&&t2(e,n,tQ),ng({type:"error",message:t instanceof Error?t.message:String(t)})}},[ng,tQ,t4,t2]),nD=(0,i.useCallback)(async(e,t)=>{await nB(e,"steer",t)},[nB]),nH=(0,i.useCallback)(async(e,t,n)=>{await nB(e,t,n)},[nB]),n_=(0,i.useCallback)(async(e,t)=>{await nB(e,"followUp",t)},[nB]),nU=(0,i.useCallback)(async()=>{let e=ts.current;if(e)try{await iT(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),nq=(0,i.useCallback)(async()=>{let t=ts.current;if(t)try{let n=await iT(t,{type:"clear_queue"});tt({steering:[],followUp:[]});let r=[...n?.steering??[],...n?.followUp??[]];r.length>0&&e.chatInputRef?.current?.prependText(r.join("\n\n"))}catch(e){console.error("Failed to recall queued messages:",e),ng({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,ng]),nZ=(0,i.useCallback)(async e=>{if("auto"===e){tM.current=null,ed(null),em(null);return}x?(tM.current=e,ed(e)):em(e);let t=ts.current??await tC.current;if(t)try{await iT(t,{type:"set_thinking_level",level:e}),tO.current&&ts.current===t&&(ex(e),em(null))}catch(e){console.error("Failed to set thinking level:",e),em(null)}},[x]),nK=(0,i.useCallback)(async e=>{try{await nW({thinkingLevel:e})}catch(e){ng({type:"error",message:`Failed to save default reasoning level: ${e instanceof Error?e.message:String(e)}`});return}ng({type:"success",message:`Default reasoning level: ${e}`}),eh(e),tX!==e&&await nZ(e),nP()},[ng,tX,nZ,nP,nW]),nV=(0,i.useCallback)(async e=>{let t=(0,iW.xG)(e);!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:iO();if(t)try{t.setItem(iP,e)}catch{}}(e),tZ(e);let n=ts.current??await tC.current;if(!n){ta.current=void 0!==t;return}try{let e=await iT(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});ta.current=void 0!==t;let r=e?.sessionId??n;(r!==n||e?.recreated)&&(nc(),nu(),e4([]),e3([]),ts.current=r,e?.recreated&&tl.current===r&&nh(r)),ns(),e6([]),e7([]);let[i]=await Promise.all([iT(r,{type:"get_state"}),nt(r)]);tO.current&&ts.current===r&&(ew(i.systemPrompt??""),t0(i))}catch(e){console.error("Failed to set tools:",e)}},[nc,ns,nu,nt,nh,tZ,t0]),nJ=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=tS.current;n&&(null!==tj.current&&(cancelAnimationFrame(tj.current),tj.current=null),tg.current=!0,tv.current=!1,tb.current=!1,eq(!1),n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),ty.current=n.scrollTop)},[]),nY=(0,i.useCallback)(()=>{let e=tS.current,t=tx.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!==tj.current&&(cancelAnimationFrame(tj.current),tj.current=null),tb.current=!0,ty.current=n,e.scrollTo({top:n,behavior:"auto"})},[]),nG=(0,i.useCallback)(()=>{let e=tS.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=td.current,o=tb.current,s=function(e,t,n,r,i){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:96;return!!iY(n,r,i)||!(n<t)&&(!!(!e&&n>t&&iY(n,r,i,o))||e)}(o,ty.current,t,n,r,i?96:8);tb.current=s,ty.current=t;let l=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return!(n<=t)&&!iY(e,t,n,r)}(t,n,r);eK(e=>e===l?e:l),!o&&s&&i?tV("auto"):s||null===tj.current||(cancelAnimationFrame(tj.current),tj.current=null)}},[tV]);(0,i.useEffect)(()=>{if(tO.current=!0,t){ts.current=t.id;let e=iL(t.id);e&&(b({sessionId:t.id,filePath:"",totalActiveMs:e.totalActiveMs??0,tree:e.summaryTree,leafId:e.leafId,context:{messages:e.messages,entryIds:e.entryIds,oldestEntryId:e.oldestEntryId,hasMore:e.hasMore,thinkingLevel:e.thinkingLevel,model:e.model},stats:e.stats}),C(e.leafId),N(e.messages),M(e.entryIds),L(e.oldestEntryId),A(e.hasMore),w(null),j(!1)),t7(t.id,!e,!0,{force:!0}).then(e=>{e?.running&&(nt(t.id),(e.state?.isStreaming||e.state?.isPromptRunning)&&(tc.current=!!e.state.isStreaming,tu.current=!!e.state.isPromptRunning,td.current=!0,F(!0),e_(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),P({type:"resume"}),!e.state.isStreaming&&e.state.isPromptRunning&&nw(t.id)),e.state?.isBashRunning&&(th.current=!0,D(!0),nC(t.id))),e?.state&&(void 0!==e.state.isCompacting&&eA(e.state.isCompacting),void 0!==e.state.contextUsage&&ej(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&ew(e.state.systemPrompt??null),void 0!==e.state.extensionStatuses&&e6(e.state.extensionStatuses??[]),void 0!==e.state.extensionWidgets&&e7(e.state.extensionWidgets??[]),void 0!==e.state.queuedMessages&&tt(i0(e.state.queuedMessages)))})}return()=>{tO.current=!1;let e=x?o:null;e&&queueMicrotask(()=>{tO.current||t$.current||rr(e)});let t=ts.current,n=tB.current;if(t&&n&&n.sessionId===t&&n.snapshotRevision){let e=iL(t),r=tH.current;!e||r.every(t=>e.entryIds.includes(t)||(e.loadedEntryIds??[]).includes(t))?iz({sessionId:t,revision:n.snapshotRevision,messages:tD.current,entryIds:tH.current,leafId:t_.current,oldestEntryId:tU.current,hasMore:tq.current,summaryTree:n.tree,thinkingLevel:n.context.thinkingLevel,model:n.context.model,stats:n.stats,totalActiveMs:n.totalActiveMs,loadedEntryIds:tH.current}):iA(t)}null!==tj.current&&(cancelAnimationFrame(tj.current),tj.current=null),tf.current+=1,nc(),nu()}},[]),(0,i.useEffect)(()=>{p?.(ek)},[ek,p]),(0,i.useEffect)(()=>(f?.(ni),()=>f?.(null)),[ni,f]);let nX=O||B||ez;(0,i.useEffect)(()=>{u&&u(v?.tree??[],S,nR,nX)},[v?.tree,S,nR,nX,u]),(0,i.useEffect)(()=>{let e=tS.current;if(e)return ty.current=e.scrollTop,e.addEventListener("scroll",nG,{passive:!0}),()=>{e.removeEventListener("scroll",nG)}},[E.length,y,nG]),(0,i.useEffect)(()=>{O||eq(!1)},[O]),(0,i.useLayoutEffect)(()=>{E.length>0&&(tv.current?(tv.current=!1,tg.current=!0,nY()):tg.current?!td.current&&tb.current&&tV("auto"):(tg.current=!0,tV("instant")))},[E.length,O,tV,nY]),(0,i.useEffect)(()=>{let e=new AbortController;return(async()=>{for(let t=0;;t++)try{await nA(e.signal);return}catch(n){if(e.signal.aborted||n instanceof DOMException&&"AbortError"===n.name||t>=i4.length||(await i8(i4[t]),e.signal.aborted))return}})(),()=>e.abort()},[nA,c]),(0,i.useEffect)(()=>{if(!eB)return;let e=setTimeout(()=>eD(null),6e3);return()=>clearTimeout(e)},[eB]);let[nQ,n0]=(0,i.useState)(null),n1=(0,i.useRef)(5e3),n2=(0,i.useRef)(null),n4=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(0===eX.visible.length){n4.current=null;return}let e=eX.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{eQ({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=eX.visible[0];if(!t||(n4.current!==t.id&&(n4.current=t.id,n1.current=5e3),eX.visible.some(e=>e.id===nQ)))return;n2.current=Date.now();let n=setTimeout(()=>{eQ({type:"mark_oldest_exiting"})},n1.current);return()=>{clearTimeout(n),null!==n2.current&&(n1.current=Math.max(0,n1.current-(Date.now()-n2.current)),n2.current=null)}},[eX.visible,nQ]),(0,i.useEffect)(()=>{e1(null)},[E.length,ey?.tokens,ey?.percent,ey?.contextWindow]);let n8=tX??"auto",n3=e2[0]??null,n5=Math.max(0,e2.length-1),n6=e8[0]??null,n9=Math.max(0,e8.length-1);return{data:v,loading:y,error:k,activeLeafId:S,messages:E,activeToolResults:I,entryIds:T,historyCursor:R,hasEarlierMessages:z,streamState:W,agentRunning:O,modelNames:U,modelList:Z,modelError:V,modelScopeWarnings:Y,modelThinkingLevels:X,modelThinkingLevelMaps:ee,newSessionModel:en,toolPreset:es,thinkingLevel:n8,retryInfo:ev,contextUsage:ey,systemPrompt:ek,forkingEntryId:eS,isCompacting:ez,compactError:eO,compactResult:eB,currentModel:tJ,displayModel:tY,modelSwitching:eR,sessionStats:t9,autoCompactionEnabled:eW,slashCommands:eV,slashCommandsLoading:eY,queuedMessages:te,notices:eX.visible,extensionDialog:n3,waitingExtensionDialogCount:n5,extensionCustomUi:n6,waitingExtensionCustomUiCount:n9,extensionStatuses:e5,extensionWidgets:e9,respondToExtensionUi:nf,sendExtensionCustomInput:nm,isAutoModelSelection:x&&null===en,isAutoThinkingSelection:x&&null===ea,defaultModel:ei,savedDefaultThinkingLevel:ep,agentPhase:eH,isNew:x,editEntryId:t4,promptAnchorActive:eU,showScrollToBottom:eZ,sessionIdRef:ts,scrollContainerRef:tS,lastUserMsgRef:tx,pendingScrollToUserRef:tv,initialScrollDoneRef:tg,handleSend:nI,handleAbort:n$,handleFork:nT,handleNavigate:nM,handleModelChange:nL,handleCompact:nz,handleSteer:nD,handleFollowUp:n_,handlePromptWithStreamingBehavior:nH,handleAbortCompaction:nU,handleRecallQueue:nq,handleBuiltinSlashCommand:nF,handleEditContent:t5,cancelEdit:t4?t6:void 0,setNoticePaused:n0,handleToolPresetChange:nV,handleThinkingLevelChange:nZ,handleSetDefaultModel:nO,handleSetDefaultThinkingLevel:nK,loadTools:nt,loadSlashCommands:na,setActiveLeafId:C,setData:b,setMessages:N,loadContext:ne,scrollToBottom:tV,scrollUserMsgToTop:nY,scrollToMessage:nJ,dispatch:P,setAgentRunning:F,setForkingEntryId:eC,bashRunning:B,pendingBash:H,handleAgentEventRef:tm}}({session:l,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:f,onAgentEnd:V,onAttentionNeeded:g,onSessionCreated:x,onSessionForked:v,modelsRefreshKey:b,chatInputRef:y,onBranchDataChange:j,onSystemPromptChange:k,onSystemToolsChange:w,onSystemInfoLoaderChange:S,onSessionStatsPanelOpen:N,onOpenSettings:I,deferInitialScroll:!!Y}),tT=ea||ed,[tM,tR]=(0,i.useState)(null),[tL,tz]=(0,i.useState)(!1),[tA,tW]=(0,i.useState)(!1),[tP,tO]=(0,i.useState)(null),tF=(0,i.useRef)(null),tB=(0,i.useRef)(null),tD=(0,i.useCallback)(()=>{tR(null),tz(!1),tO(null)},[]);(0,i.useEffect)(()=>{A||tD()},[A,tD]);let tH=(0,i.useCallback)(()=>{if(!A||tL)return;let e=window.getSelection(),t=e?.rangeCount?e.getRangeAt(0):null,n=tJ.current;if(!e||e.isCollapsed||!t||!n||!n.contains(t.commonAncestorContainer))return void tR(null);let r=e.toString().trim();if(!r)return void tR(null);let i=t.getBoundingClientRect(),o=[t.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?t.commonAncestorContainer:t.commonAncestorContainer.parentElement,t.startContainer.nodeType===Node.ELEMENT_NODE?t.startContainer:t.startContainer.parentElement,t.endContainer.nodeType===Node.ELEMENT_NODE?t.endContainer:t.endContainer.parentElement].map(e=>e?.closest('[data-message-role="assistant"]')?.dataset.entryId).find(e=>!!e);tR({text:r,top:Math.min(window.innerHeight-44,i.bottom+8),left:Math.max(64,Math.min(window.innerWidth-64,i.left+i.width/2)),sourceEntryId:o})},[A,tL]);(0,i.useEffect)(()=>{tL&&tM&&tB.current?.insertIfEmpty(tb(tM.text,H("chat.quoteIntro"),H("chat.quoteQuestion")))},[tL,tM,H]),(0,i.useLayoutEffect)(()=>{let e=tF.current;if(!e||!tM)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(tM.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(tM.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)}},[tM,tL,tP]),(0,i.useEffect)(()=>{if(!tM)return;let e=e=>{tL||tF.current?.contains(e.target)||tD()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),tA||tD())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[tM,tL,tA,tD]);let t_=(0,i.useCallback)(()=>{tM&&(y?.current?.insertText(tb(tM.text,H("chat.quoteIntro"),H("chat.quoteQuestion"))),window.getSelection()?.removeAllRanges(),tD())},[y,tM,tD,H]),tU=(0,i.useCallback)(async e=>{let t=eG.current??l?.id;if(!tA&&e.trim()&&tM?.sourceEntryId&&t&&z){tW(!0),tO(null),D?.();try{await z(e,t,tM.sourceEntryId),tD()}catch(t){tB.current?.restoreSubmission(e),tO(t instanceof Error?t.message:String(t))}finally{tW(!1)}}},[z,tM,tA,l?.id,eG,tD,D]),tq=(0,i.useRef)(!1);(0,i.useEffect)(()=>{ee||et||!W||tq.current||(tq.current=!0,P?.(),e1(W))},[W,ee,et,e1,P]),(0,i.useEffect)(()=>{let e=!!eL&&!K.current;K.current=!!eL,U&&e&&q.current()},[U,eL]),(0,i.useEffect)(()=>{s=tT?e2:null},[tT,e2]);let[tZ,tK]=(0,i.useState)(50),tV=(0,i.useRef)(null),tJ=(0,i.useRef)(null),tY=(0,i.useRef)(null),tG=(0,i.useRef)(!1),tX=(0,i.useRef)(!1),tQ=(0,i.useRef)(Y);tQ.current=Y;let[t0,t1]=(0,i.useState)(null),t2=en[ei.indexOf(t0?.entryId??"")],t4=t2?.role==="assistant"?t0?.blockIndex===void 0?t2.content.find(e=>"text"===e.type):t2.content[t0.blockIndex]:void 0,t8=(0,i.useRef)({entryIds:ei,historyCursor:eo,hasEarlierMessages:es});t8.current={entryIds:ei,historyCursor:eo,hasEarlierMessages:es},(0,i.useLayoutEffect)(()=>{let e=l?.id,t=eX.current,n=tJ.current;if(e&&u&&t&&n)return()=>{if(tQ.current)return;if(iY(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:t8.current.historyCursor})}},[ee,u,eX,l?.id]),(0,i.useEffect)(()=>{a&&G(null)},[a]),(0,i.useEffect)(()=>{let e=l?.id;if(!Y||!e||ee||a||tX.current)return;tX.current=!0;let t=new AbortController;return(async()=>{let n=t8.current;if(n.entryIds.includes(Y.anchorEntryId)){tK(e=>Math.max(e,2*n.entryIds.length)),Q(!0);return}tG.current=!0;let r=n.historyCursor,i=n.hasEarlierMessages;try{for(;i&&r&&!t.signal.aborted;){let n=await tE(e,tN,r,{signal:t.signal});if(t.signal.aborted)return;if(!n){tI("instant"),G(null);return}if(tK(e=>e+Math.max(50,2*n.messages.length)),n.entryIds.includes(Y.anchorEntryId))return void Q(!0);if(n.oldestEntryId===Y.oldestEntryId)break;r=n.oldestEntryId,i=n.hasMore}t.signal.aborted||(tI("instant"),G(null))}finally{tG.current=!1}})(),()=>{t.abort(),G(null)}},[tN,tE,ee,Y,tI,a,l?.id]),(0,i.useLayoutEffect)(()=>{let e=tJ.current;if(!Y||!e||a)return;let t=Array.from(e.children).find(e=>e instanceof HTMLElement&&e.dataset.entryId===Y.anchorEntryId);if(t instanceof HTMLElement){t$(t,Y.anchorOffset),G(null);return}X&&(tI("instant"),G(null))},[ei,Y,X,tI,t$,a,tZ]),(0,i.useEffect)(()=>{if(!a||ee)return;let e=new AbortController;return(async()=>{let t=t8.current,n=t.entryIds.includes(a.entryId);if(!n&&!tT&&t.hasEarlierMessages&&t.historyCursor&&!tG.current){tG.current=!0;let r=eX.current;r&&(tY.current=r.scrollHeight-r.scrollTop);let i=await tE(a.sessionId,tN,t.historyCursor,{tail:200,signal:e.signal});tG.current=!1,n=!!i?.entryIds.includes(a.entryId)}e.signal.aborted||(n?(tY.current=null,tK(e=>Math.max(e,(t8.current.entryIds.length+200)*2)),t1(a)):d?.(a))})(),()=>e.abort()},[a,ee,tN,tT,tE,d,eX]),(0,i.useLayoutEffect)(()=>{if(!t0||t0!==a)return;let e=`[data-entry-id="${CSS.escape(t0.entryId)}"]`,t=eX.current?.querySelector(t2?.role==="user"?e:`${e} [data-search-target]`);t&&(t$(t),t.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500})),t1(null),d?.(t0)},[t0,a,t2,eX,t$,d]),(0,i.useEffect)(()=>{let e=tV.current,t=eX.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{if(!e[0]?.isIntersecting||tG.current||!es||!eo)return;let n=l?.id??eG.current;n&&(tG.current=!0,tY.current=t.scrollHeight-t.scrollTop,tE(n,tN,eo).finally(()=>{tG.current=!1}))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[eo,es,l,tN,tE,eG,eX]),(0,i.useEffect)(()=>{tK(e=>Math.max(e,en.length))},[en.length]),(0,i.useEffect)(()=>{if(null==tY.current)return;let e=eX.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-tY.current),tY.current=null}},[tZ,eX]);let t3=eI?[eI.sessionId,eI.sessionFile??"",eI.sessionName??"",eI.userMessages,eI.assistantMessages,eI.toolCalls,eI.toolResults,eI.totalMessages,eI.tokens.input,eI.tokens.output,eI.tokens.cacheRead,eI.tokens.cacheWrite,eI.tokens.total,eI.cost??0,eI.totalActiveMs??0].join("|"):null,t5=(0,i.useRef)(eI);t5.current=eI,(0,i.useEffect)(()=>{C?.(t5.current)},[t3,C]),(0,i.useEffect)(()=>()=>{C?.(null)},[C]);let t6=ey?`${ey.percent??"null"}|${ey.contextWindow}|${ey.tokens??"null"}`:null,t9=(0,i.useRef)(ey);t9.current=ey,(0,i.useEffect)(()=>{$?.(t9.current)},[t6,$]),(0,i.useEffect)(()=>()=>{$?.(null)},[$]);let{isDragOver:t7,handleDragEnter:ne,handleDragOver:nt,handleDragLeave:nn,handleDrop:nr}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),o=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>e.type.startsWith("image/"))&&(e.preventDefault(),r.current+=1,n(!0))},[]),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>e.type.startsWith("image/"))&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:o,handleDragOver:s,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(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{y?.current?.addImages(e)},[y])),ni=en.filter(e=>e5(e)||"assistant"===e.role),no=(0,i.useMemo)(()=>{let e=new Map(er);for(let t of en)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[er,en]),ns=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=en.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}(en[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[en]),nl=(t=ni.length,(o=(0,i.useRef)([])).current=Array(t).fill(null).map((e,t)=>o.current[t]??null),o),na=(0,i.useCallback)(()=>{tK(e=>Math.max(e,2*en.length))},[en.length]),nd=eK&&0===en.length&&!el.isStreaming&&!tT;T(eX,!!l?.id||!nd);let nc=!!el.streamingMessage?.content.length,nu=l?.cwd??h??void 0,np=(0,i.useRef)(null),nh=(0,i.useRef)(0),nf=(0,i.useRef)(null),nm=(0,i.useRef)(!1),ng=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=np.current;if(!ea||!e0){ng.current=null,nh.current=0,nm.current=!1,e&&(e.style.height="");return}let t=eX.current,n=tJ.current,r=eQ.current;if(!t||!n||!r||!e)return;let i=!1,o=()=>{var o;let s;if(i||eX.current!==t||tJ.current!==n||eQ.current!==r||np.current!==e)return;let l=t.getBoundingClientRect().top,a=Math.max(0,r.getBoundingClientRect().top-l+t.scrollTop-16),d=e.getBoundingClientRect().top-l+t.scrollTop,c=(o=t.clientHeight,0===(s=Math.max(0,a))?0:Math.max(0,Math.ceil(s+o-Math.max(0,d)))),u=!nm.current;u&&(nm.current=!0),c!==nh.current&&(nh.current=c,e.style.height=c>0?`${c}px`:"",u&&c>0&&tC())};ng.current=o,o();let s="u"<typeof ResizeObserver?null:new ResizeObserver(()=>{i||null!==nf.current||(nf.current=requestAnimationFrame(()=>{nf.current=null,o()}))});return s?.observe(t),s?.observe(n),s?.observe(r),()=>{i=!0,ng.current===o&&(ng.current=null),s?.disconnect(),null!==nf.current&&(cancelAnimationFrame(nf.current),nf.current=null)}},[ea,eQ,en.length,e0,eX,tC]),(0,i.useLayoutEffect)(()=>{ng.current?.()},[el.streamingMessage]);let nx=eE?em[`${eE.provider}:${eE.modelId}`]??null:null,nv=eE?eg[`${eE.provider}:${eE.modelId}`]??null:null,nb=(0,r.jsx)(id,{ref:y,onSend:e1,onAbort:e2,onSteer:ea?ti:void 0,onFollowUp:ea?to:void 0,onPromptWithStreamingBehavior:ea?tl:void 0,isStreaming:tT,model:eE,isAutoModelSelection:eH,modelNames:eu,modelList:ep,modelError:eh,modelScopeWarnings:ef,onModelChange:e6,modelSwitching:eN,defaultModel:eU,onSetDefaultModel:tk,onCompact:l||eK?tr:void 0,onAbortCompaction:ta,isCompacting:ek,compactError:eS,compactResult:eC,toolPreset:ex,onToolPresetChange:l||eK?ty:void 0,thinkingLevel:ev,isAutoThinkingSelection:e_,onThinkingLevelChange:l||eK?tj:void 0,availableThinkingLevels:nx,thinkingLevelMap:nv,savedDefaultThinkingLevel:eq,onSetDefaultThinkingLevel:l||eK?tw:void 0,retryInfo:eb,queuedMessages:eM,inputHistory:ns,onRecallQueue:td,slashCommands:e$,slashCommandsLoading:eT,onLoadSlashCommands:tS,onBuiltinCommand:tm,soundEnabled:O,onSoundToggle:F,onAudioUnlock:D,draftKey:l?.id??f??void 0,cwd:l?.cwd??h});return ee?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:H("chat.loadingSession")}):et?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:et}):(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:ne,onDragOver:nt,onDragLeave:nn,onDrop:nr,children:[t7&&(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*!_,zIndex:40,display:"flex",justifyContent:"flex-end",padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)(on,{notices:eR,floating:!0,onPauseChange:eD})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[eL&&(0,r.jsx)(oi,{request:eL,waitingCount:ez,onRespond:eF},eL.id),eA&&(0,r.jsx)(oo,{request:eA,waitingCount:eW,onInput:eB},eA.id),!nd&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:eX,className:"scrollbar-subtle min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-gutter:stable]",style:{visibility:Y?"hidden":void 0},children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{ref:tJ,onPointerUp:tH,style:{width:"100%",minWidth:0,maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(()=>{var e;let t,n,i=-1;for(let e=en.length-1;e>=0;e--)if("user"===en[e].role){i=e;break}let o=-1;for(let e=en.length-1;e>=0;e--)if(e5(en[e])){o=e;break}let s=new Map,a=0;en.forEach((e,t)=>{(e5(e)||"assistant"===e.role)&&s.set(t,a++)});let d=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.messageOverride??en[e],o=e5(n)||"assistant"===n.role,a=s.get(e),d=t.keyPrefix??"message",c=ei[e]??e,u=!1;if("assistant"===n.role){u=!0;for(let t=e+1;t<en.length;t++){let e=en[t].role;if("user"===e)break;if("assistant"===e){u=!1;break}}u&&el.isStreaming&&e===en.length-1&&(u=!1)}void 0!==t.showTimestamp&&(u=t.showTimestamp);let p=(0,r.jsx)(nP,{message:n,toolResults:no,modelNames:eu,cwd:nu,onOpenFile:R,onOpenSession:L,entryId:ei[e],searchBlock:ei[e]===t0?.entryId?t4:void 0,onFork:ed||eK?void 0:e4,forking:ej===ei[e],onEditContent:tT?void 0:e8,onCancelEdit:e3,isEditing:eV===ei[e],showTimestamp:u,prevTimestamp:e>0?en[e-1].timestamp:void 0,sessionId:l?.id??eG.current??void 0,writtenFiles:t.writtenFiles,onCompact:t.recoverTruncation?tr:void 0,isCompacting:t.recoverTruncation?ek:void 0,compactError:t.recoverTruncation?eS:void 0},`${d}-view-${c}`);return o&&void 0!==a?(0,r.jsx)("div",{"data-entry-id":ei[e],ref:!1===t.attachRef?void 0:t=>{nl.current[a]=t,e===i&&(eQ.current=t)},children:p},`${d}-${c}`):p},c=[];for(let e=0;e<en.length;){let t,n=e5(en[e]);if(!n&&0!==e){c.push(d(e)),e+=1;continue}let i=n?e:-1,l=n?e:0,a=e+1;for(;a<en.length&&!e5(en[a]);)a+=1;let u=function(e,t,n){for(let i=n-1;i>t;i--){var r;if("assistant"===(r=e[i]).role&&tn(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}(en,i,a);if(-1===u||(tT||el.isStreaming)&&a===en.length&&i===o){for(let e=l;e<a;e++)c.push(d(e));e=a;continue}n&&c.push(d(i));let p=en[u],h=tn(p),f=h.answerBlocks.length>0||e7(p)||te(p)?i7(p,h.answerBlocks):null,m=p.content.indexOf(h.answerBlocks[0]),g=p.content.slice(0,m<0?void 0:m),x=[],v=0,b=!1;for(let e=i+1;e<=u;e++){let n=en[e];if("custom"===n.role){b||=!!(t0&&t0.entryId===ei[e]),x.push(d(e,{attachRef:!1,keyPrefix:"process"}));continue}if("assistant"!==n.role)continue;let r=e===u?i7(n,g,{omitUsage:!!f}):n,i=e9(r);0!==i.length&&(t??=s.get(e),v+=i.filter(e=>"toolCall"===e.type).length,b||=!!(t0&&ei[e]===t0.entryId&&(!t4||i.includes(t4))),x.push(d(e,{attachRef:!1,keyPrefix:"process",messageOverride:r,showTimestamp:!1})))}if(x.length>0&&c.push((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{nl.current[t]=e},children:(0,r.jsx)(oe,{messageCount:x.length,toolCallCount:v,defaultExpanded:!f,reveal:b,t:H,children:x},f?"answered":"unanswered")},`process-group-${ei[l]??l}`)),f){let e=[];for(let t=i+1;t<=u;t++){let n=en[t];if(n?.role==="assistant")for(let t of n.content??[])e.push(t)}let t=function(e,t,n){let r=new Set,i=[];for(let o of e){if("toolCall"!==o.type||!function(e){let t;return"write"===(t=e.toLowerCase())||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")||tc(e)}(o.toolName)&&!tu(o.toolName))continue;let e=t?.get(o.toolCallId);if(e&&!e.isError)for(let t of tu(o.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 tp(e).matchAll(/^\*\*\* Delete File: (.+)$/gm)){let e=(t[1]??"").trim();e&&n.add(e)}return n}(e,n),i=function(e){if(!th(e)||!th(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(tf(n))return[];if(n&&"object"==typeof n&&!Array.isArray(n)){let e=tv(tx(n.preview));if(e.length>0)return e}return tv(tg(tp(e)))}(o.input,e):[function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(o.input)]){if(!t)continue;let e=function(e,t){let n;if(!e)return null;let r=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),i=e=>r?e.replace(/\\/g,"/"):e,o=i(e),s=t?i(t).replace(/\/+$/,""):void 0,l=/^[a-zA-Z]:\//.test(o),a=o.startsWith("//");if(l||a)n=o;else if(o.startsWith("/")){let e=s?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??s?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${o}`:o}else{if(!s)return null;n=`${s}/${o}`}return ts(n)}(t,n);e&&(r.has(e)||(r.add(e),i.push({filePath:e})))}}return i}(e,no,nu);c.push(d(u,{messageOverride:f,writtenFiles:t,recoverTruncation:a===en.length&&!el.isStreaming&&!tt(f)}))}for(let e=u+1;e<a;e++)c.push(d(e));e=a}let{startIndex:u}=(t=Math.min(Math.max(tZ,0),Math.max(e=c.length,0)),{startIndex:n=Math.max(0,e-t),hasMore:n>0}),p=u>0||es;return(0,r.jsxs)(r.Fragment,{children:[p&&(0,r.jsx)("div",{ref:tV,className:"py-3 text-center text-xs text-text-muted",children:H("chat.loadEarlier")}),c.slice(u)]})})(),el.isStreaming&&nc&&el.streamingMessage&&(0,r.jsx)(nP,{message:el.streamingMessage,toolResults:no,isStreaming:!0,modelNames:eu,cwd:nu,onOpenFile:R,onOpenSession:L}),ea&&!nc&&(eZ||ek)&&(0,r.jsx)("div",{className:"break-words py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:function(e,t,n){if(n)return t("chat.compacting");if(e?.kind==="running_tools"){let n=e.tools[e.tools.length-1];if(n?.progress)return`${t("chat.runningNamedTool",{name:n.name})} ${n.progress}`;let r=e.tools.map(e=>e.name);return 0===r.length?t("chat.runningTool"):1===r.length?t("chat.runningNamedTool",{name:r[0]}):r.length<=3?t("chat.runningTools",{names:r.join(", ")}):t("chat.runningToolsMore",{names:r.slice(0,2).join(", "),count:r.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(eZ,H,ek)})}),ed&&!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:H("chat.runningCommand")})}),ec&&(0,r.jsx)(nP,{message:{role:"bashExecution",command:ec.command,output:"",excludeFromContext:ec.excludeFromContext},sessionId:l?.id??eG.current??void 0,onOpenSession:L}),(0,r.jsx)("div",{ref:np,"aria-hidden":"true"})]})})}),_||Y?null:(0,r.jsx)(iv,{messages:en,streamingMessage:el.streamingMessage,scrollContainer:eX,messageRefs:nl,onRevealHistory:na})]})]}),A&&tM&&(0,M.createPortal)((0,r.jsx)("div",{ref:tF,role:tL?"dialog":"toolbar","aria-label":H(tL?"chat.newQuoteChat":"chat.askSelection"),style:{position:"fixed",top:tM.top,left:tM.left,zIndex:260,display:"flex",flexWrap:"wrap",gap:3,width:tL?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:tL?12:3,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",boxShadow:"0 2px 10px rgba(0,0,0,0.12)"},children:tL?(0,r.jsxs)("fieldset",{disabled:tA,"aria-busy":tA,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:H("chat.askInNewChat")}),(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button",title:H("i18n.close"),"aria-label":H("i18n.close"),disabled:tA,onClick:tD,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)(id,{ref:tB,compact:!0,onSend:tU,onAbort:tD,isStreaming:!1}),tP&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:tP})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:H("chat.askInCurrent"),"aria-label":H("chat.askInCurrent"),onPointerDown:e=>e.preventDefault(),onClick:t_,style:{width:"auto",height:35,flex:"0 0 auto",gap:5,padding:"0 10px",border:"none",fontSize:12,fontWeight:500},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{fontSize:15},children:"@"}),(0,r.jsx)("span",{children:H("chat.askInCurrent")})]}),z&&tM.sourceEntryId&&!ed&&(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:H("chat.askInNewChat"),"aria-label":H("chat.askInNewChat"),onPointerDown:e=>e.preventDefault(),onClick:()=>{tz(!0),window.getSelection()?.removeAllRanges()},style:{width:"auto",height:35,flex:"0 0 auto",gap:5,padding:"0 10px",border:"none",fontSize:12,fontWeight:500},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M6 3v12M18 9a9 9 0 0 1-9 9"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"})]}),(0,r.jsx)("span",{children:H("chat.askInNewChat")})]})]})}),document.body),(0,r.jsxs)("div",{className:"relative shrink-0",children:[!nd&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"100%",left:0,right:36*!_,display:"flex",justifyContent:"center",paddingBottom:10,pointerEvents:"none",zIndex:20},children:(0,r.jsx)("button",{type:"button",className:`chat-scroll-to-bottom${eJ&&!Y?" is-visible":""}`,title:H("chat.scrollToLatest"),"aria-label":H("chat.scrollToLatest"),onClick:()=>tI("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"})})})}),nd&&(0,r.jsx)("div",{className:"mb-3 w-full",style:{paddingLeft:16,paddingRight:_?16:52},children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto",fontFamily:"var(--font-mono)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:_?7:10,minWidth:0,flex:1,lineHeight:1.4,overflow:"hidden"},children:[(0,r.jsx)(eY.default,{src:"/icons/apple-touch-icon.png",width:32,height:32,alt:"",priority:!0,style:{flexShrink:0}}),(0,r.jsx)("span",{style:{fontSize:22,color:"var(--text)",fontWeight:700,flexShrink:0,whiteSpace:"nowrap"},children:"Pi Web"}),(0,r.jsx)(i9,{label:e=>H("appUpdate.releaseNotes",{version:e})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.10.0"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["pi ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","1.0.0"]})]})]})]})}),nb,(0,r.jsx)(ik,{statuses:eP,widgets:eO})]}),nd&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}function on(e){let{notices:t,floating:n=!1,onPauseChange:i}=e;return 0===t.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",marginBottom:10*!n},children:t.map((e,o)=>{let s="error"===e.type?"#ef4444":"warning"===e.type?"#d97706":"success"===e.type?"#10b981":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",onMouseEnter:()=>i?.(e.id),onMouseLeave:e=>{e.currentTarget.contains(document.activeElement)||i?.(null)},onFocus:()=>i?.(e.id),onBlur:e=>{e.currentTarget.matches(":hover")||i?.(null)},style:{display:"flex",alignItems:"flex-start",gap:10,minHeight:60,height:"auto",maxHeight:500,pointerEvents:"auto",marginBottom:6*(o!==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:s,flexShrink:0,marginTop:21}}),(0,r.jsx)("span",{tabIndex:0,style:{padding:"14px 0",minWidth:0,maxWidth:"100%",maxHeight:470,overflowY:"auto",scrollbarWidth:"thin",whiteSpace:"pre-line",wordBreak:"break-word"},children:e.message})]},e.id)})})}function or(e){let{count:t}=e,{t:n}=(0,E.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 oi(e){let{request:t,waitingCount:n,onRespond:o}=e,{t:s}=(0,E.s)(),[l,a]=(0,i.useState)("editor"===t.method?t.prefill??"":""),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(()=>Date.now()),h=(0,i.useCallback)(e=>e?.focus(),[]),f=function(e){if("select"===e.method&&e.options.length>0)return e.options[0];if("confirm"===e.method){let t=e.message.split("\n").find(e=>e.trim());return t?.trim()}}(t),m=void 0===t.expiresAt?null:Math.max(0,Math.ceil((t.expiresAt-u)/1e3));(0,i.useEffect)(()=>{if(void 0===t.expiresAt)return;let e=setInterval(()=>p(Date.now()),1e3);return()=>clearInterval(e)},[t.expiresAt]);let g=null!==m&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:s("chat.extensionExpiresIn",{seconds:m})}),x=()=>{"confirm"===t.method?o(t,{confirmed:!0}):o(t,{value:l})};return(0,r.jsx)("div",{onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),e.stopPropagation(),o(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:s("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:t.title}),f&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:f}),(0,r.jsx)(or,{count:n}),g,(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:s("chat.extensionExpand")})]}):(0,r.jsxs)("div",{role:"dialog","aria-label":t.title,style:{pointerEvents:"auto",width:"min(560px, 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"},children:[(0,r.jsxs)("div",{style:{flexShrink:1,minHeight:0,display:"flex",alignItems:"flex-start",gap:8,padding:"12px 14px",borderBottom:"1px solid var(--border)",maxHeight:"50vh",overflowY:"auto"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:650,lineHeight:1.45,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:t.title}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:8,marginTop:3,color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{children:s("chat.extensionRequest")}),(0,r.jsx)(or,{count:n}),g]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:s("chat.extensionCollapse"),"aria-label":s("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",{style:{padding:14,flex:"1 1 auto",minHeight:0,overflowY:"auto"},children:["confirm"===t.method&&(0,r.jsx)(nu,{children:t.message}),"select"===t.method&&(0,r.jsx)("div",{onKeyDown:e=>{if(!["ArrowDown","ArrowRight","ArrowUp","ArrowLeft","Home","End"].includes(e.key))return;let t=Array.from(e.currentTarget.querySelectorAll("[data-extension-option]")),n=t.indexOf(e.target);if(n<0)return;e.preventDefault();let r="Home"===e.key?0:"End"===e.key?t.length-1:(n+("ArrowDown"===e.key||"ArrowRight"===e.key?1:-1)+t.length)%t.length;t[r].focus({preventScroll:!0}),t[r].scrollIntoView({block:"nearest"})},style:{display:"grid",gap:8},children:t.options.map((e,n)=>(0,r.jsx)("div",{role:"button",tabIndex:0,"data-extension-option":!0,"aria-label":e,ref:0===n?h:void 0,onClick:()=>o(t,{value:e}),onKeyDown:n=>{("Enter"===n.key||" "===n.key)&&(n.preventDefault(),o(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)(nu,{children:e})})},e))}),"input"===t.method&&(0,r.jsx)("input",{autoFocus:!0,value:l,placeholder:t.placeholder,onChange:e=>a(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||x()},style:{width:"100%",padding:"9px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",fontSize:13}}),"editor"===t.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:l,onChange:e=>a(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&!e.nativeEvent.isComposing&&x()},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:()=>o(t,{cancelled:!0}),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),"confirm"===t.method?(0,r.jsx)("button",{onClick:x,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:s("chat.confirm")}):"select"!==t.method?(0,r.jsx)("button",{onClick:x,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:s("chat.submit")}):null]})]})})}function oo(e){let{request:t,waitingCount:n,onInput:o}=e,{t:s}=(0,E.s)(),l=(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(eQ,""),i=e0(e).trimEnd();if(t.test(i))continue;let o=e,s=e4(o);("│"===s||"┃"===s)&&" "===e4(o=e2(o,0))&&(o=e2(o,0));let l=function(e){let t=e1(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(o),a=l>=0?e1(o)[l]?.char:void 0;("│"===a||"┃"===a)&&(o=e2(o,l)),n.push(function(e){let t=e;for(;;){let e=e1(t),n=e[e.length-1];if(!n||""!==n.char.trim())return t;t=t.slice(0,n.start)+t.slice(n.end)}}(o))}for(;n.length>0&&""===e0(n[0]).trim();)n.shift();for(;n.length>0&&""===e0(n[n.length-1]).trim();)n.pop();return n.length?n:e}(t.lines),p=u.find(e=>e.trim())?.trim();return(0,i.useEffect)(()=>{d||l.current?.focus()},[d]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:d?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:d?(0,r.jsxs)("button",{type:"button",onClick:()=>c(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(920px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:s("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:s("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)(or,{count:n}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:s("chat.extensionExpand")})]}):(0,r.jsxs)("div",{role:"dialog",onClick:e=>{e.target.closest("button")||l.current?.focus()},style:{pointerEvents:"auto",position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:l,"aria-label":s("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:e=>{if(a.current||e.nativeEvent.isComposing)return;let n=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=e3[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":" ":e8[e.key]??null}(e);n&&(e.preventDefault(),e.stopPropagation(),o(t,n))},onInput:e=>{if(a.current||e.nativeEvent.isComposing)return;let n=e.currentTarget.value;e.currentTarget.value="",n&&o(t,n)},onCompositionStart:()=>{a.current=!0},onCompositionEnd:e=>{a.current=!1;let n=e.currentTarget;queueMicrotask(()=>{let e=n.value;n.value="",e&&o(t,e)})},onPaste:e=>{e.preventDefault();let n=e.clipboardData.getData("text");n&&o(t,`\x1b[200~${n}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:s("chat.extensionPanel")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)(or,{count:n}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:s("chat.extensionCollapse"),"aria-label":s("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:()=>o(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:s("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)(iy,{text:u.join("\n")})})]})})}var os=n(50640);let ol={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"},oa={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"},od={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",mov:"video/quicktime",ogv:"video/ogg"};function oc(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}var ou=n(73620);let op=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function oh(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 of=["tags","categories","keywords","tag","category"];function om(e){var t;let{data:n}=e;if(!n)return null;let i=Object.entries(n);if(0===i.length)return null;let o="string"==typeof(t=n.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,s=of.find(e=>Array.isArray(n[e])),l=s?n[s].map(oh).filter(Boolean):[],a=i.filter(e=>{let[t]=e;return t!==s&&("title"!==t||!o)});return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[o&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:o}),l.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:l.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=oh(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 og={source:"Source",preview:"Preview",diff:"Diff"},ox={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},ov={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)",fontSize:11,fontStyle:"normal",fontVariantNumeric:"tabular-nums",lineHeight:"20.8px",userSelect:"none",flexShrink:0,verticalAlign:"top"};function ob(){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 oy(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function oj(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=oy(n.startContainer),i=oy(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let o=Number(r.dataset.lineNumber),s=Number(i.dataset.lineNumber);if(!Number.isInteger(o)||!Number.isInteger(s))return null;if(o<s){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]")&&(o=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]")&&(s=Number((i=e).dataset.lineNumber))}}}return o>s?null:{startLine:o,endLine:s}}function ok(e){let{rows:t,stylesheet:n,useInlineStyles:i,wrapLines:o}=e;return t.map((e,t)=>{let s=e.children??[],l=s[0]?.properties?.className,a=Array.isArray(l)&&l.includes("react-syntax-highlighter-line-number"),d=a?s[0]:null,c=a?s.slice(1):s;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":t+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,os.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:o?"anywhere":"normal",whiteSpace:o?"pre-wrap":"pre"},children:c.map((e,r)=>(0,os.Ay)({node:e,stylesheet:n,useInlineStyles:i,key:`source-token-${t}-${r}`}))})]},`source-line-${t}`)})}function ow(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=Y(e),o=new URLSearchParams({type:t});for(let[e,t]of(n&&o.set("sessionId",n),Object.entries(r)))void 0!==t&&o.set(e,String(t));return`/api/files/${i}?${o.toString()}`}function oS(e){let{filePath:t,sourceSessionId:n}=e,{t:i}=(0,E.s)();return(0,r.jsx)("a",{href:ow(t,"download",n),download:G(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 oC(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function oE(e){let t,{patch:n}=e,{t:i}=(0,E.s)(),o=(t=nm(n))?t.flatMap(e=>e.rows.flatMap(e=>{if("hunk"===e.type)return[];if("context"===e.left.type&&"context"===e.right.type)return[{type:"unchanged",text:e.right.text,oldLineNo:e.left.lineNo,newLineNo:e.right.lineNo}];let t=[];return"removed"===e.left.type&&t.push({type:"removed",text:e.left.text,oldLineNo:e.left.lineNo,newLineNo:null}),"added"===e.right.type&&t.push({type:"added",text:e.right.text,oldLineNo:null,newLineNo:e.right.lineNo}),t})):[];if(!o.some(e=>"unchanged"!==e.type))return(0,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:i("i18n.noChanges")});let s=new Set(o.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),l=new Set;for(let e of s)for(let t=Math.max(0,e-3);t<=Math.min(o.length-1,e+3);t++)l.add(t);let a=[],d=0;for(;d<o.length;)if(l.has(d)){let e=[];for(;d<o.length&&l.has(d);)e.push(o[d]),d++;a.push({hidden:!1,lines:e})}else{let e=0;for(;d<o.length&&!l.has(d);)e++,d++;a.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...ox},children:a.map((e,t)=>{if(e.hidden)return(0,r.jsxs)("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:["... ",e.count," unchanged lines ..."]},t);let n=e.lines.map((e,t)=>{let n="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",o="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:ov,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:o,userSelect:"none",flexShrink:0,fontWeight:600},children:i}),(0,r.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},t)});return(0,r.jsx)("div",{children:n},t)})})}function oN(e){let{filePath:t,cwd:n,sourceSessionId:o,watchEnabled:s=!0}=e,{t:l}=(0,E.s)(),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(0),y=G(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),m(null),x(null),d(!1)},[t,o]),(0,i.useEffect)(()=>{if(d(!1),v.current&&(v.current.close(),v.current=null),!s)return;let e=!0,n=new EventSource(ow(t,"watch",o));v.current=n,n.addEventListener("connected",()=>{let n;d(!0),n=++b.current,fetch(ow(t,"meta",o)).then(e=>e.json()).then(t=>{if(e&&n===b.current){if(t.error)return void x(t.error);"number"==typeof t.size&&h(t.size),m(null),x(null),u(e=>e+1)}}).catch(t=>{e&&n===b.current&&x(String(t))})}),n.addEventListener("change",e=>{b.current+=1;try{let t=JSON.parse(e.data);"number"==typeof t.size&&h(t.size)}catch{}m(null),x(null),u(e=>e+1)});let r=()=>{d(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,o,s]);let j=ow(t,"read",o,c?{v:c}:void 0),k=null!=p?oC(p):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:t,children:Q(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"image"}),f&&(0,r.jsxs)("span",{children:[f.w," \xd7 ",f.h]}),k&&(0,r.jsx)("span",{children:k}),(0,r.jsxs)("span",{title:l(a?"i18n.liveSync":"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)(oS,{filePath:t,sourceSessionId:o})]}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:g?(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13},children:g}):(0,r.jsx)("img",{src:j,alt:t,onLoad:e=>{let t=e.currentTarget;m({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>x("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function oI(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 o$(e){let{filePath:t,cwd:n,sourceSessionId:o,watchEnabled:s=!0}=e,{t:l}=(0,E.s)(),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(0),y=G(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),m(null),x(null),d(!1)},[t,o]),(0,i.useEffect)(()=>{if(d(!1),v.current&&(v.current.close(),v.current=null),!s)return;let e=!0,n=new EventSource(ow(t,"watch",o));v.current=n,n.addEventListener("connected",()=>{let n;d(!0),n=++b.current,fetch(ow(t,"meta",o)).then(e=>e.json()).then(t=>{if(e&&n===b.current){if(t.error)return void x(t.error);"number"==typeof t.size&&h(t.size),m(null),x(null),u(e=>e+1)}}).catch(t=>{e&&n===b.current&&x(String(t))})}),n.addEventListener("change",e=>{b.current+=1;try{let t=JSON.parse(e.data);"number"==typeof t.size&&h(t.size)}catch{}m(null),x(null),u(e=>e+1)});let r=()=>{d(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,o,s]);let j=ow(t,"read",o,c?{v:c}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:t,children:Q(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"audio"}),null!=f&&(0,r.jsx)("span",{children:oI(f)}),null!=p&&(0,r.jsx)("span",{children:oC(p)}),(0,r.jsxs)("span",{title:l(a?"i18n.liveSync":"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)(oS,{filePath:t,sourceSessionId:o})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,r.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[g&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:g}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:j,onLoadedMetadata:e=>m(e.currentTarget.duration),onError:()=>x("Failed to load audio"),style:{width:"100%"}},j)]})})]})}function oT(e){let{filePath:t,cwd:n,sourceSessionId:o,watchEnabled:s=!0}=e,{t:l}=(0,E.s)(),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(0),y=G(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),m(null),x(null),d(!1)},[t,o]),(0,i.useEffect)(()=>{if(d(!1),v.current&&(v.current.close(),v.current=null),!s)return;let e=!0,n=new EventSource(ow(t,"watch",o));v.current=n,n.addEventListener("connected",()=>{let n;d(!0),n=++b.current,fetch(ow(t,"meta",o)).then(e=>e.json()).then(t=>{if(e&&n===b.current){if(t.error)return void x(t.error);"number"==typeof t.size&&h(t.size),m(null),x(null),u(e=>e+1)}}).catch(t=>{e&&n===b.current&&x(String(t))})}),n.addEventListener("change",e=>{b.current+=1;try{let t=JSON.parse(e.data);"number"==typeof t.size&&h(t.size)}catch{}m(null),x(null),u(e=>e+1)});let r=()=>{d(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,o,s]);let j=ow(t,"read",o,c?{v:c}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:t,children:Q(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"video"}),null!=f&&(0,r.jsx)("span",{children:oI(f)}),null!=p&&(0,r.jsx)("span",{children:oC(p)}),(0,r.jsxs)("span",{title:l(a?"i18n.liveSync":"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)(oS,{filePath:t,sourceSessionId:o})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)",minHeight:0},children:(0,r.jsxs)("div",{style:{width:"min(960px, 100%)",height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:0},children:[g&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:g}),(0,r.jsx)("video",{controls:!0,playsInline:!0,preload:"metadata",src:j,onLoadedMetadata:e=>m(e.currentTarget.duration),onError:()=>x("Failed to load video"),style:{maxWidth:"100%",maxHeight:"100%"}},j)]})})]})}function oM(e){let{filePath:t,cwd:n,sourceSessionId:o,initialPage:s,watchEnabled:l=!0}=e,{t:a}=(0,E.s)(),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(0),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(0),b=oc(t),y="pdf"===b,j=y&&s&&s>0?`#page=${s}`:"",k=y?`${ow(t,"read",o,u?{v:u}:void 0)}${j}`:ow(t,"preview",o,u?{v:u}:void 0);return(0,i.useEffect)(()=>{p(0),f(null),g(null),c(!1);let e=!0,n=++v.current;return fetch(ow(t,"meta",o)).then(e=>e.json()).then(t=>{e&&n===v.current&&(t.error&&g(t.error),"number"==typeof t.size&&(f(t.size),!y&&t.size>0xa00000&&g("DOCX too large for preview (>10MB)")))}).catch(t=>{e&&n===v.current&&g(String(t))}),()=>{e=!1}},[t,y,o]),(0,i.useEffect)(()=>{if(c(!1),x.current&&(x.current.close(),x.current=null),!l)return;let e=!0,n=new EventSource(ow(t,"watch",o));x.current=n,n.addEventListener("connected",()=>{let n;c(!0),n=++v.current,fetch(ow(t,"meta",o)).then(e=>e.json()).then(t=>{if(e&&n===v.current){if(t.error)return void g(t.error);if("number"==typeof t.size&&(f(t.size),!y&&t.size>0xa00000))return void g("DOCX too large for preview (>10MB)");g(null),p(e=>e+1)}}).catch(t=>{e&&n===v.current&&g(String(t))})}),n.addEventListener("change",e=>{v.current+=1;try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(f(t.size),!y&&t.size>0xa00000))return void g("DOCX too large for preview (>10MB)")}catch{}g(null),p(e=>e+1)});let r=()=>{c(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),x.current===n&&(x.current=null)}},[t,y,o,l]),(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:Q(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===b?"docx preview":"pdf"}),null!=h&&(0,r.jsx)("span",{children:oC(h)}),(0,r.jsx)(oS,{filePath:t,sourceSessionId:o}),(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:m?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:m}):(0,r.jsx)("iframe",{src:k,sandbox:y?void 0:"allow-same-origin",title:a("i18n.previewFile",{file:G(t)}),style:{width:"100%",height:"100%",border:"none",background:y?"var(--bg)":"#eef1f5"}},k)})]})}function oR(e){let t,{filePath:n,cwd:i,sourceSessionId:o,onOpenFile:s,onMentionLines:l,onAtMention:a,gitRefreshKey:d,initialDisplayMode:c,initialState:u,initialPage:p,onStateChange:h,watchEnabled:f=!0}=e;return null!==(ol[oc(n)]??null)?(0,r.jsx)(oN,{filePath:n,cwd:i,sourceSessionId:o,watchEnabled:f}):null!==(oa[oc(n)]??null)?(0,r.jsx)(o$,{filePath:n,cwd:i,sourceSessionId:o,watchEnabled:f}):null!==(od[oc(n)]??null)?(0,r.jsx)(oT,{filePath:n,cwd:i,sourceSessionId:o,watchEnabled:f}):null!==("pdf"===(t=oc(n))||"docx"===t?t:null)?(0,r.jsx)(oM,{filePath:n,cwd:i,sourceSessionId:o,initialPage:p,watchEnabled:f}):(0,r.jsx)(oL,{filePath:n,cwd:i,sourceSessionId:o,onOpenFile:s,onMentionLines:l,onAtMention:a,gitRefreshKey:d,initialDisplayMode:c,initialState:u,onStateChange:h,watchEnabled:f})}function oL(e){let{filePath:t,cwd:n,sourceSessionId:o,onOpenFile:s,onMentionLines:l,onAtMention:a,gitRefreshKey:d,initialDisplayMode:c,initialState:u,onStateChange:p,watchEnabled:h=!0}=e,{isDark:f}=ni(),{t:m}=(0,E.s)(),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(null),[y,j]=(0,i.useState)(!1),[k,w]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!0),[N,I]=(0,i.useState)(!1),[$,T]=(0,i.useState)(null),M=u?.displayMode??c??"source",R=u?.wrapLines??!1,L=u?.scrollTop??0,z=u?.scrollLeft??0,[A,W]=(0,i.useState)(M),[P,O]=(0,i.useState)(R),[F,B]=(0,i.useState)(!1),D=(0,i.useRef)(null),H=(0,i.useRef)(0),_=(0,i.useRef)(0),U=(0,i.useRef)(null),q=(0,i.useRef)(!1),Z=(0,i.useRef)(void 0===u&&void 0===c),K=(0,i.useRef)(!0),V=(0,i.useRef)({displayMode:M,wrapLines:R,scrollTop:L,scrollLeft:z}),J=(0,i.useRef)(p),[Y,G]=(0,i.useState)(null);J.current=p;let ee=(0,i.useCallback)(e=>{V.current.displayMode=e,W(e)},[]),et=(0,i.useCallback)(()=>{O(e=>{let t=!e;return V.current.wrapLines=t,t})},[]);(0,i.useEffect)(()=>(V.current={displayMode:M,wrapLines:R,scrollTop:L,scrollLeft:z},K.current=!0,q.current=!1,W(M),O(R),()=>{J.current?.({...V.current})}),[t,o,M,R,L,z]);let en=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=++H.current;return fetch(ow(e,"read",o,{offset:t||void 0})).then(e=>e.json()).then(e=>n!==H.current?null:e.error?(T(e.error),null):(T(null),x(n=>t&&n?{...e,content:n.content+e.content}:e),e)).catch(e=>(n!==H.current||T(String(e)),null))},[o]),er=(0,i.useCallback)(async e=>{let t=++_.current;if(j(!0),!n){b(null),j(!1),w(!0);return}try{let r=new URLSearchParams({cwd:n,path:e}),i=await fetch(`/api/git/diff?${r.toString()}`),o=await i.json();if(t!==_.current)return;b(i.ok&&o.supported&&"string"==typeof o.patch?o:null)}catch{t===_.current&&b(null)}finally{t===_.current&&(j(!1),w(!0))}},[n]);(0,i.useEffect)(()=>{let e=!0;return C(!0),T(null),x(null),b(null),w(!1),B(!1),en(t).finally(()=>{e&&C(!1)}),()=>{e=!1}},[t,en,o]),(0,i.useEffect)(()=>{if(B(!1),D.current&&(D.current.close(),D.current=null),!h)return;let e=()=>{en(t),er(t)},n=new EventSource(ow(t,"watch",o));D.current=n,n.addEventListener("connected",()=>{B(!0),e()}),n.addEventListener("change",e);let r=()=>{B(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{n.close(),D.current===n&&(D.current=null)}},[t,en,er,o,h]),(0,i.useEffect)(()=>{er(t)},[er,t,d]),(0,i.useEffect)(()=>{Z.current&&!g?.truncated&&(g?.language==="markdown"||g?.language==="html")&&(Z.current=!1,ee("preview"))},[g?.language,g?.truncated,ee]);let ei=v?.supported===!0&&"string"==typeof v.patch,eo=ei&&"deleted"===v.status;(0,i.useEffect)(()=>{k&&!ei&&"diff"===A&&ee("source")},[A,k,ei,ee]),(0,i.useEffect)(()=>{"diff"===M&&ei&&!q.current&&(q.current=!0,ee("diff"))},[M,ei,ee]);let es=(0,i.useMemo)(()=>g?.language==="markdown"?tR(g.content):"",[g]),el=(0,i.useMemo)(()=>g?.language==="markdown"?function(e){let t=function(e){let t=op.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,ou.Hh)(t.yaml);if(e&&"object"==typeof e&&!Array.isArray(e))return{data:e,rest:t.rest}}catch{}return{data:null,rest:t.rest}}(g.content):null,[g]),ea=g?.content??"",ed=(0,i.useMemo)(()=>ea.split("\n"),[ea]),ec=g?.language??"text",eu="html"===ec,ep="markdown"===ec,eh=!g?.truncated&&(eu||ep),ef=eo?"diff":A,em=ed.length>1e3&&!("diff"===ef&&ei)&&!("preview"===ef&&eh),eg=(0,i.useMemo)(()=>(0,r.jsx)(tY.A,{className:P?"file-source-view is-wrapped":"file-source-view",language:"text"===ec?"plaintext":ec,style:f?tG.xJ:tG.vs,showLineNumbers:!0,lineNumberStyle:{...ov},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...ox,width:P?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",overflowWrap:P?"anywhere":"normal"}},renderer:e=>(0,r.jsx)(ok,{...e,wrapLines:P}),wrapLongLines:P,children:ea}),[f,ec,ea,P]),ex=(0,i.useMemo)(()=>em?ed.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:ov,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,[ed,em,P]);(0,i.useEffect)(()=>{let e=()=>{let e=U.current;G(t=>{let n=l&&"source"===A&&e?oj(e,window.getSelection()):null;return null===t&&null===n||t&&n&&t.startLine===n.startLine&&t.endLine===n.endLine?t:n})};if(e(),l&&"source"===A)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[g?.content,A,l]);let ev=(0,i.useCallback)(e=>{l&&e&&l(Q(t,n),e.startLine,e.endLine)},[n,t,l]);if((0,i.useEffect)(()=>{if(!l||"source"!==A)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let n=U.current,r=n?oj(n,window.getSelection()):null;r&&(e.preventDefault(),ev(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[A,ev,l]),(0,i.useEffect)(()=>{if(!K.current||S||$&&!eo||"diff"===M&&!k||"diff"===M&&ei&&"diff"!==A)return;let e=U.current;e&&(e.scrollTop=V.current.scrollTop,e.scrollLeft=V.current.scrollLeft,K.current=!1)},[g?.content,A,$,k,ei,eo,S,M]),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($&&!eo)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:$});if(!g&&!eo)return null;let eb=X(t),ey=eo?["diff"]:["source",...eh?["preview"]:[],...ei?["diff"]:[]],ej=eo?m("files.deleted"):`${ec} \xb7 ${ed.length} lines \xb7 ${oC(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:Q(t,n)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:ej,children:ej}),!eo&&(0,r.jsx)("span",{title:F?m("i18n.liveSync"):m("i18n.notWatching"),"aria-label":F?m("i18n.liveSync"):m("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:F?"#4ade80":"var(--border)",boxShadow:F?"0 0 4px #4ade80":"none"}}),(0,r.jsxs)("div",{className:"file-viewer-controls",children:[ey.length>1&&(0,r.jsx)("div",{className:"file-viewer-mode-switch","aria-label":m("i18n.fileViewMode"),children:ey.map(e=>{let t=ef===e;return(0,r.jsx)("button",{type:"button",onClick:()=>ee(e),title:"diff"===e?m("i18n.compareHead"):void 0,"aria-pressed":t,className:"file-viewer-mode-button",style:{background:t?"var(--bg-selected)":"transparent",color:t?"var(--text)":"var(--text-muted)"},children:og[e]},e)})}),(0,r.jsxs)("div",{className:"file-viewer-actions",children:[(a||l)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{Y&&l?ev(Y):a?.(Q(t,n),!1)},title:Y&&l?`${m("i18n.mentionSelectedLines")} (L${Y.startLine}${Y.startLine!==Y.endLine?`-L${Y.endLine}`:""})`:m("files.insertPath"),"aria-label":m("files.mention"),disabled:!a&&!l,className:"file-viewer-icon-button",children:(0,r.jsx)(ob,{})}),"source"===ef&&(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("button",{type:"button",onClick:et,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"})]})})})]}),!eo&&(0,r.jsx)(oS,{filePath:t,sourceSessionId:o})]})]}),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:[oC(g.nextOffset)," / ",oC(g.size)]}),(0,r.jsx)("button",{type:"button",className:"file-viewer-mode-button",disabled:N,onClick:()=>{I(!0),en(t,g.nextOffset).finally(()=>I(!1))},children:N?m("i18n.loading"):m("i18n.loadMore")})]}),(0,r.jsx)("div",{ref:U,className:"file-viewer-content",onScroll:e=>{V.current.scrollTop=e.currentTarget.scrollTop,V.current.scrollLeft=e.currentTarget.scrollLeft},style:{flex:1,overflow:"auto",background:"var(--bg)",paddingBottom:g?.truncated?48:void 0},children:"diff"===ef&&ei?(0,r.jsx)(oE,{patch:v.patch}):eu&&"preview"===ef?(0,r.jsx)("iframe",{srcDoc:ea,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:m("i18n.htmlPreview")}):ep&&"preview"===ef?(0,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[el?.data&&(0,r.jsx)(om,{data:el.data}),(0,r.jsx)(ty.oz,{remarkPlugins:tZ,rehypePlugins:tV,urlTransform:s?t$:void 0,components:{code(e){let{className:t,children:n,...i}=e,o=t?.replace("language-","").toLowerCase()??"",s=String(n);return t?.includes("language-")||s.includes("\n")?"mermaid"===o?(0,r.jsx)(ns,{code:s.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(na,{code:s.replace(/\n$/,""),lang:o}):(0,r.jsx)("code",{className:t,...i,children:n})},pre(e){let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})},a(e){let{href:t,children:i,...o}=e;delete o.node;let l=s?tl(t,eb,n??eb):null;return l&&s?(0,r.jsx)("a",{href:t,...o,onClick:e=>{tr(e)&&(e.preventDefault(),s(l,td(t)??void 0))},children:i}):(0,r.jsx)("a",{href:t,...o,children:i})},img(e){let{src:t,alt:i,...s}=e;delete s.node;let l="string"==typeof t?tl(t,eb,n??eb):null,a=l?ow(l,"read",o):t;return(0,r.jsx)("img",{src:a,alt:i??"",loading:"lazy",...s})}},children:es})]}):em?(0,r.jsx)("div",{className:"file-source-view is-lightweight",style:{width:P?"100%":"max-content",minWidth:"100%",minHeight:"100%",background:"var(--bg)",...ox},children:ex}):eg})]})}function oz(e){let{tabs:t,activeTabId:n,onSelectTab:o,onCloseTab:s}=e,{t:l}=(0,E.s)(),[a,d]=(0,i.useState)(null);return(0,r.jsx)("div",{role:"tablist",style:{display:"flex",alignItems:"flex-end",background:"var(--bg-panel)",overflowX:"auto",flexShrink:0,height:36},children:t.map(e=>{let i=e.id===n;return(0,r.jsxs)("div",{role:"tab","aria-label":"terminal"===e.kind?l("terminal.tabLabel",{name:e.label}):e.label,"aria-selected":i,tabIndex:i||!n&&t[0].id===e.id?0:-1,onKeyDown:n=>{if(n.target===n.currentTarget){if("Enter"===n.key||" "===n.key)n.preventDefault(),o(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;o(t[i].id),n.currentTarget.parentElement?.children[i]?.focus()}}},onClick:()=>o(e.id),onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:t=>{1===t.button&&(t.preventDefault(),t.stopPropagation(),e.closing||s(e.id))},style:{display:"flex",alignItems:"center",gap:6,height:36,paddingLeft:12,paddingRight:6,borderRight:"1px solid var(--border)",background:i?"var(--bg)":"var(--bg-panel)",cursor:"pointer",fontSize:12,color:i?"var(--text)":"var(--text-muted)",whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,r.jsx)("span",{style:{flexShrink:0,opacity:i?1:.7,display:"flex",alignItems:"center"},children:"terminal"===e.kind?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]}):V(e.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:i?500:400},title:e.filePath,children:e.label}),(0,r.jsx)("button",{disabled:e.closing,onClick:t=>{t.stopPropagation(),s(e.id)},onMouseEnter:()=>d(e.id),onMouseLeave:()=>d(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:a===e.id?"var(--bg-hover)":"transparent",border:"none",borderRadius:4,color:a===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:l("terminal"===e.kind?"terminal.close":"i18n.close"),"aria-label":`${l("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 oA(e){let{preference:t,size:n=17}=e,i={width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0};return"light"===t?(0,r.jsxs)("svg",{...i,children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M12 2v2M12 20v2M4.93 4.93l1.42 1.42M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.42-1.41M17.66 6.34l1.41-1.41"})]}):"dark"===t?(0,r.jsx)("svg",{...i,children:(0,r.jsx)("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79Z"})}):"mist"===t?(0,r.jsxs)("svg",{...i,children:[(0,r.jsx)("path",{d:"M12 3S6 10 6 14a6 6 0 0 0 12 0c0-4-6-11-6-11Z"}),(0,r.jsx)("path",{d:"M9 15c.5 1.4 1.5 2.2 3 2.5"})]}):"rose"===t?(0,r.jsxs)("svg",{...i,children:[(0,r.jsx)("path",{d:"M12 13.5c-3.2 0-5.5-1.8-5.5-4.6S8.6 4.2 11.8 4.2c2.7 0 4.8 1.7 4.8 4.2 0 2.2-1.6 3.7-3.8 3.7-1.8 0-3-1-3-2.4 0-1.2.9-2 2-2 1 0 1.6.5 1.6 1.3"}),(0,r.jsx)("path",{d:"M12 13.5v7.5M12 18c-1.7-1.8-3.6-2.2-5.2-1.2 1.1 1.9 3.1 2.6 5.2 1.2ZM12 17c1.3-2 3.3-2.4 5-1.5-1.1 1.8-3 2.4-5 1.5Z"})]}):"pine"===t?(0,r.jsxs)("svg",{...i,children:[(0,r.jsx)("path",{d:"M12 3c-.9 2.5-2.3 4.2-4.5 6h3c-1 2.1-2.6 3.7-5 5.3h4c-.7 2-1.9 3.8-3.7 5.4h12.4c-1.8-1.6-3-3.4-3.7-5.4h4c-2.4-1.6-4-3.2-5-5.3h3c-2.2-1.8-3.6-3.5-4.5-6Z"}),(0,r.jsx)("path",{d:"M12 20v2"})]}):(0,r.jsxs)("svg",{...i,children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"13",rx:"2"}),(0,r.jsx)("path",{d:"M8 21h8M12 17v4"})]})}let oW=["general","models","archives","skills","agents","plugins","mcp"],oP="pi-web:settings-navigation",oO=new Set(["skills","agents","plugins"]);function oF(e){return oO.has(e)}function oB(){try{return window.localStorage}catch{return null}}function oD(e){let t=e.getItem(oP);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 oH(e,t){return"models"===e?e:t?JSON.stringify([e,t]):"mcp"===e?e:null}function o_(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:oB();if(t)try{let n=oD(t);n.section=e,t.setItem(oP,JSON.stringify(n))}catch{}}function oU(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:oB();if(!n)return null;let r=oH(e,t);if(!r)return null;try{let e=oD(n).selections?.[r];return"string"==typeof e&&e.length>0?e:null}catch{return null}}function oq(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:oB();if(!r||!t)return;let i=oH(e,n);if(i)try{let e=oD(r);e.selections={...e.selections,[i]:t},r.setItem(oP,JSON.stringify(e))}catch{}}function oZ(e){return e.isComposing||229===e.keyCode}function oK(e,t){let n=e.activeElement;return!!t&&(!n||n===e.body)&&(t.focus({preventScroll:!0}),!0)}let oV=["input","output","cacheRead","cacheWrite"];function oJ(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 oY(e){if(!oG(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),o=t(e.cacheWrite);if(void 0!==n&&void 0!==r&&void 0!==i&&void 0!==o)return{input:n,output:r,cacheRead:i,cacheWrite:o}}function oG(e){return oV.some(t=>""!==e[t].trim())}function oX(e){return new Map(Object.entries(e.providers??{}).map(e=>{let[t,n]=e;return[t,(n.models??[]).map(e=>e.id)]}))}function oQ(e,t,n){if(n<=0)return;let r=e.get(t)??[];e.set(t,[...r,...Array.from({length:n},()=>null)])}function o0(e){let{embedded:t,title:n,subtitle:i,closeLabel:o="Close",onClose:s,children:l,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||s()},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:s,title:o,"aria-label":o,children:"\xd7"})]}),l]})})}function o1(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-split-view",children:t})}function o2(e){let{children:t}=e;return(0,r.jsx)("aside",{className:"config-sidebar",children:t})}function o4(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-sidebar-list",children:t})}function o8(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 o3(e){let{enabled:t,total:n,checked:i,label:o,disabled:s=!1,loading:l=!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)(sy,{checked:i??(n>0&&t===n),disabled:s,loading:l,label:o,describedBy:a,onChange:d})]})}function o5(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 o6(e){let{active:t=!1,className:n,children:i,...o}=e;return(0,r.jsx)("button",{type:"button",...o,"aria-current":t?"page":void 0,className:["config-sidebar-item",n].filter(Boolean).join(" "),children:i})}function o9(e){let{className:t,...n}=e;return(0,r.jsx)("span",{...n,className:["config-sidebar-text",t].filter(Boolean).join(" ")})}function o7(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-stack",t].filter(Boolean).join(" ")})}function se(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header",t].filter(Boolean).join(" ")})}function st(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header-info",t].filter(Boolean).join(" ")})}function sn(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-actions",t].filter(Boolean).join(" ")})}function sr(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-title",children:t})}function si(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-section-title",children:t})}function so(e){let{label:t,children:n,style:i}=e;return(0,r.jsxs)("div",{className:"config-field",style:i,children:[(0,r.jsx)("span",{className:"config-field-label",children:t}),n]})}function ss(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-grid",children:t})}function sl(e){let{label:t,tone:n="muted",mono:i=!1,className:o,style:s,children:l}=e;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-detail-grid-label",children:t}),(0,r.jsx)("div",{className:["config-detail-grid-value","plain"===n?null:`is-${n}`,i?"is-mono":null,o].filter(Boolean).join(" "),style:s,children:l})]})}function sa(e){let{scope:t,children:n}=e;return(0,r.jsx)("span",{className:`config-scope-tag${"project"===t?" is-project":""}`,children:n})}function sd(e){let{value:t,options:n,label:o,disabledReason:s,size:l="default",onChange:a,children:d}=e,c=(0,i.useId)(),u=s&&n.some(e=>e.disabled)?s: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":o,className:`config-scope-switch${"small"===l?" is-small":""}`,children:n.map(e=>(0,r.jsx)("button",{type:"button","aria-pressed":e.value===t,"aria-describedby":e.disabled&&u?c:void 0,disabled:e.disabled,className:"config-scope-switch-option",onClick:()=>{e.disabled||a(e.value)},children:e.label},e.value))}),d]}),u&&(0,r.jsx)("span",{id:c,className:"config-scope-switch-reason",children:u})]})}function sc(e){let{value:t,options:n,label:o,path:s,disabledReason:l,onChange:a,children:d}=e;return(0,r.jsxs)("div",{className:"config-save-target",children:[(0,r.jsx)(sd,{value:t,options:n,label:o,disabledReason:l,size:"small",onChange:a,children:(0,r.jsx)("span",{className:"config-save-target-path",children:"string"==typeof s?s.split(/([\\/])/).map((e,t)=>"/"===e||"\\"===e?(0,r.jsxs)(i.Fragment,{children:[e,(0,r.jsx)("wbr",{})]},t):e):s})}),d]})}function su(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)(sr,{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 sp(e){let{title:t,catalogs:n,target:o,inputLabel:s,inputId:l,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 j=e=>{if(!u)return;let t=e.clipboardData.getData("text"),n=u(t);n!==t&&(e.preventDefault(),p(n))};return(0,r.jsxs)(o7,{className:"is-fill",children:[(0,r.jsx)(su,{title:t,catalogs:n,target:o}),(0,r.jsx)(so,{label:s,children:x?(0,r.jsx)("textarea",{id:l,ref:y,value:d,"aria-label":s,className:"config-add-source-input is-multiline",placeholder:a,rows:5,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>p(e.target.value),onPaste:j,onBlur:e=>{u&&p(u(e.currentTarget.value))},onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&e.nativeEvent?.isComposing!==!0&&229!==e.keyCode&&(e.preventDefault(),c&&h())}}):(0,r.jsx)("input",{id:l,ref:b,value:d,"aria-label":s,className:"config-add-source-input",placeholder:a,onChange:e=>p(e.target.value),onPaste:j,onBlur:e=>{u&&p(u(e.currentTarget.value))},onKeyDown:e=>{"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 sh(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 sf(e){let{id:t,message:n,trustLabel:i,trusting:o=!1,onTrust:s}=e;return(0,r.jsx)(sh,{id:t,action:s&&i?(0,r.jsx)(sb,{size:"small",onClick:s,disabled:o,children:i}):void 0,children:n})}function sm(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-empty-state",children:t})}function sg(e){let{children:t,style:n}=e;return(0,r.jsx)("div",{className:"config-detail",style:n,children:t})}function sx(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 sv(e){let{summary:t,tone:n="default",details:i}=e,o=`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:o,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:o,children:t})}function sb(e){let{variant:t="secondary",size:n="default",className:i,children:o,...s}=e;return(0,r.jsx)("button",{type:"button",...s,className:["config-button",`config-button-${t}`,`config-button-${n}`,i].filter(Boolean).join(" "),children:o})}function sy(e){let{checked:t,disabled:n=!1,loading:i=!1,size:o="default",label:s,describedBy:l,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":s,"aria-describedby":l,title:s,disabled:d,className:`config-switch${"small"===o?" is-small":""}${i?" is-loading":""}`,onClick:()=>a(!t),children:(0,r.jsx)("span",{className:"config-switch-knob","aria-hidden":"true"})})}function sj(e){let{active:t=!1,children:n,className:i,...o}=e;return(0,r.jsx)("div",{className:"config-list-action",children:(0,r.jsxs)("button",{type:"button",...o,"aria-current":t?"page":void 0,className:["config-list-action-button",i].filter(Boolean).join(" "),children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})}),n]})})}function sk(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 sw(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 sS(e,t){let n=sw(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 sC(e,t){return t.enabled&&(e?.enabledTotal??0)<=1}function sE(e,t){return e?.providers.find(e=>e.id===t)}let sN={"last-model":"models.enabledLastModel","project-scope":"models.enabledProjectScope"};function sI(e){let{controller:t}=e,{t:n}=(0,E.s)(),{view:i,pending:o}=t;if(!i)return null;let s=!i.allEnabled,l=i.stalePatterns.length;return s||0!==l?(0,r.jsxs)("div",{className:"enabled-models-banner",children:[(0,r.jsxs)("span",{className:"enabled-models-banner-text",...l>0?{title:n("models.enabledStaleHint")}:{},children:[(0,r.jsx)("code",{className:"enabled-models-banner-key",title:i.settingsPath,children:i.settingsPath}),(0,r.jsxs)("code",{className:"enabled-models-banner-facts",children:[`\xb7 enabledModels ${i.enabledTotal}/${i.availableTotal}`,l>0&&` \xb7 ${n("models.enabledStale",{count:l})}`]})]}),i.editable&&l>0&&(0,r.jsx)(sb,{size:"small",onClick:t.pruneStale,disabled:null!==o,title:n("models.enabledPruneHint"),children:n("models.enabledPrune")}),i.editable&&s&&(0,r.jsx)(sb,{size:"small",onClick:t.clearScope,disabled:null!==o,title:n("models.enabledClearHint"),children:n("models.enabledClear")})]}):null}function s$(e){let{providerId:t,controller:n,noteId:i}=e,{t:o}=(0,E.s)(),{view:s,loading:l,pending:a,failure:d}=n,c=sE(s,t),u=d?d.messageKey?o(d.messageKey):d.message:null,p=sT(n,t)?i:void 0;if(l&&!s)return null;if(!c)return(0,r.jsx)(sy,{checked:!1,disabled:!0,label:o("models.enabledProviderToggle",{provider:t}),describedBy:p,onChange:()=>{}});let h=sS(s,c);return(0,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("span",{className:"enabled-models-switch-error",children:u}),(0,r.jsx)(sy,{checked:h.checked,loading:a===`provider:${c.id}`,disabled:null!==a||h.blocked,label:o("models.enabledProviderToggle",{provider:c.name}),describedBy:p,onChange:e=>n.setProvider(c.id,e)})]})}function sT(e,t){let{view:n,loading:r}=e;if(r&&!n)return null;let i=sE(n,t);if(!i)return"models.enabledCustomEmpty";let{reason:o}=sS(n,i);return o?sN[o]:null}function sM(e){let{providerId:t,controller:n,id:i}=e,{t:o}=(0,E.s)(),s=sT(n,t);return s?(0,r.jsx)("div",{id:i,className:"config-detail-heading-note",children:o(s)}):null}function sR(e){var t;let n,{providerId:o,controller:s}=e,{t:l}=(0,E.s)(),[a,d]=(0,i.useState)(""),{view:c,loading:u,pending:p,failure:h}=s,f=sE(c,o),m=function(e,t){let[n,r]=(0,i.useState)(!1),[o,s]=(0,i.useState)(null);return(0,i.useEffect)(()=>s(null),[e]),{refreshing:n,note:o,refresh:(0,i.useCallback)(()=>{r(!0),s(null),(async()=>{try{let n=await fetch("/api/models/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);"offline"===r.reason?s("models.catalogOffline"):r.completed?s(r.changed?"models.catalogUpdated":"models.catalogUnchanged"):s("models.catalogUnreachable"),r.changed&&t()}catch{s("models.catalogUnreachable")}finally{r(!1)}})()},[e,t])}}(o,s.refresh),g=(0,i.useId)();if((0,i.useEffect)(()=>d(""),[o]),u&&!c)return(0,r.jsx)("div",{className:"enabled-models-empty",children:l("agents.modelsLoading")});if(!f)return h?.message?(0,r.jsx)("div",{className:"enabled-models-error",children:h.message}):(0,r.jsx)("div",{className:"enabled-models-empty",children:l("models.enabledUnavailable")});let x=(t=f.models,(n=a.trim().toLowerCase())?t.filter(e=>e.id.toLowerCase().includes(n)||e.name.toLowerCase().includes(n)):[...t]),v=sw(c,x),b=x.length!==f.models.length,y=null!==p,j=`provider:${f.id}`,k=c?.editable===!0,w=`${g}-scope`,S=`${g}-last`,C=k&&!v.canDisable&&v.disableRefs.length>0,N=C||k&&x.some(e=>sC(c,e)),I=(e,t)=>{b?s.setModels(j,t,e):s.setProvider(f.id,e)};return(0,r.jsxs)("div",{className:"enabled-models-section",children:[(0,r.jsxs)("div",{className:"enabled-models-header",children:[(0,r.jsx)("span",{className:"enabled-models-title",children:l("models.enabledSection")}),(0,r.jsx)("span",{className:"enabled-models-count",children:l("models.enabledCount",{enabled:f.enabledCount,total:f.models.length})}),(0,r.jsx)(sb,{size:"small",disabled:y||!v.canEnable,"aria-describedby":k?void 0:w,onClick:()=>I(!0,v.enableRefs),children:b?l("models.enableShown"):l("models.enableAll")}),(0,r.jsx)(sb,{size:"small",disabled:y||!v.canDisable,"aria-describedby":k?C?S:void 0:w,onClick:()=>I(!1,v.disableRefs),children:b?l("models.disableShown"):l("models.disableAll")}),(0,r.jsx)(sb,{size:"small",disabled:y||m.refreshing,title:l("models.refreshCatalogHint"),onClick:m.refresh,children:m.refreshing?l("models.refreshingCatalog"):l("models.refreshCatalog")})]}),m.note&&(0,r.jsx)("div",{className:"enabled-models-note",children:l(m.note)}),!k&&(0,r.jsx)("div",{id:w,className:"enabled-models-note",children:l("models.enabledProjectScope")}),N&&(0,r.jsx)("div",{id:S,className:"enabled-models-note",children:l("models.enabledLastModel")}),h&&(0,r.jsx)("div",{className:"enabled-models-error",children:h.messageKey?l(h.messageKey):h.message}),f.models.length>8&&(0,r.jsx)("input",{value:a,onChange:e=>d(e.target.value),placeholder:l("models.enabledFilterPlaceholder",{count:f.models.length}),"aria-label":l("models.enabledFilter"),className:"enabled-models-filter"}),(0,r.jsx)("div",{className:"enabled-models-list",children:0===x.length?(0,r.jsx)("div",{className:"enabled-models-empty",children:l("models.enabledNoMatches")}):x.map(e=>{let t=sC(c,e);return(0,r.jsxs)("div",{className:"enabled-models-row",children:[(0,r.jsxs)("span",{className:"enabled-models-row-text",children:[(0,r.jsx)("span",{className:"enabled-models-row-name",children:e.name}),(0,r.jsx)("code",{className:"enabled-models-row-id",children:e.id})]}),e.thinkingPin&&(0,r.jsx)("span",{className:"enabled-models-pin",title:l("models.enabledPinHint"),children:e.thinkingPin}),(0,r.jsx)(sy,{checked:e.enabled,loading:p===e.ref,disabled:y||!c?.editable||t,label:l("models.enabledToggle",{model:e.name}),describedBy:k?t?S:void 0:w,onChange:t=>s.setModels(e.ref,[e.ref],t)})]},e.ref)})})]})}function sL(e){let{message:t,hint:n,value:i,placeholder:o,submitLabel:s,inputLabel:l,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:o,"aria-label":l,disabled:a||void 0,onChange:e=>u(e.target.value),onKeyDown:e=>{var t;t={key:e.key,metaKey:e.metaKey,ctrlKey:e.ctrlKey,isComposing:e.nativeEvent.isComposing,keyCode:e.keyCode},"Enter"===t.key&&!t.isComposing&&229!==t.keyCode&&(d||t.metaKey||t.ctrlKey)&&h&&p()}}),(0,r.jsx)("button",{type:"button",className:"oauth-paste-submit",onClick:p,disabled:!h,children:s})]})]})}let sz={anthropic:{symbol:"anthropic",color:!1},openai:{symbol:"openai",color:!1},"openai-codex":{symbol:"openai",color:!1},google:{symbol:"google",color:!0},"google-vertex":{symbol:"google",color:!0},"ant-ling":{symbol:"antgroup",color:!0},deepseek:{symbol:"deepseek",color:!0},groq:{symbol:"groq",color:!1},mistral:{symbol:"mistral",color:!0},moonshotai:{symbol:"moonshot",color:!1},"moonshotai-cn":{symbol:"moonshot",color:!1},moonshot:{symbol:"moonshot",color:!1},minimax:{symbol:"minimax",color:!0},"minimax-cn":{symbol:"minimax",color:!0},fireworks:{symbol:"fireworks",color:!0},huggingface:{symbol:"huggingface",color:!0},cerebras:{symbol:"cerebras",color:!0},openrouter:{symbol:"openrouter",color:!1},xai:{symbol:"xai",color:!1},"cloudflare-ai-gateway":{symbol:"cloudflare",color:!0},"cloudflare-workers-ai":{symbol:"cloudflare",color:!0},"vercel-ai-gateway":{symbol:"vercel",color:!1},"github-copilot":{symbol:"githubcopilot",color:!1},"amazon-bedrock":{symbol:"aws",color:!0},"azure-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 sA(e){let{id:t,size:n}=e,i=sz[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 o=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:o})}let sW=["openai-codex","deepseek","openrouter","moonshotai","moonshotai-cn","minimax","minimax-cn","vercel-ai-gateway","opencode-go"],sP="pi-web:provider-usage:";function sO(e){let{providerId:t,enabled:n}=e;return sW.includes(t)?(0,r.jsx)(sF,{providerId:t,enabled:n}):null}function sF(e){let{providerId:t,enabled:n}=e,[o,s]=(0,i.useState)(null),[l,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,E.s)();(0,i.useEffect)(()=>{h.current&&clearTimeout(h.current),p(!1),s(null);try{let e=localStorage.getItem(`${sP}${t}`);if(e){let t=JSON.parse(e);t?.status==="ready"&&t.report&&Array.isArray(t.report.buckets)&&Array.isArray(t.report.metrics)&&s(t)}}catch{try{localStorage.removeItem(`${sP}${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){s(n);try{localStorage.setItem(`${sP}${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=o?.status==="ready"?o.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||l,title:m(l?"providerUsage.refreshing":"providerUsage.refresh"),"aria-label":m(l?"providerUsage.refreshing":"providerUsage.refresh"),style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:32,height:30,padding:0,background:"none",border:"none",color:u?"#4ade80":"var(--text-dim)",cursor:n&&!l?"pointer":"default",borderRadius:5,flexShrink:0,opacity:n?1:.6,transition:"color 0.3s"},children:u?(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:l?{animation:"spin 0.8s linear infinite"}:void 0,"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}),x&&(0,r.jsx)("span",{title:new Date(x.capturedAt).toLocaleString(f),style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap"},children:m("providerUsage.updated",{time:(0,C.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 ":"$"}${sB(e.remaining??e.limit)}`:void 0!==e.remaining&&void 0!==e.limit?`${sB(e.remaining)} / ${sB(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 sB(e){return void 0===e?"-":Number.isInteger(e)?String(e):e.toFixed(2)}function sD(){let e=oU("models");if(!e)return null;try{let t=JSON.parse(e);if(null===t||"object"!=typeof t)return null;if("provider"===t.type&&"string"==typeof t.name)return{type:"provider",name:t.name};if("model"===t.type&&"string"==typeof t.providerName&&"number"==typeof t.index&&Number.isInteger(t.index)&&t.index>=0)return{type:"model",providerName:t.providerName,index:t.index};if(("oauth"===t.type||"apikey"===t.type)&&"string"==typeof t.providerId)return{type:t.type,providerId:t.providerId}}catch{}return null}let sH=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function s_(e){let{label:t,children:n}=e;return(0,r.jsx)(so,{label:t,children:n})}let sU={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 sq(e){let{value:t,onChange:n,placeholder:i,mono:o}=e;return(0,r.jsx)("input",{value:t,onChange:e=>n(e.target.value),placeholder:i,style:{...sU,fontFamily:o?"var(--font-mono)":"inherit"}})}function sZ(e){let{value:t,onChange:n,placeholder:o,mono:s,onKeyDown:l,autoComplete:a="off",spellCheck:d=!1,style:c}=e,[u,p]=(0,i.useState)(!1),{t:h}=(0,E.s)();return(0,i.useEffect)(()=>{t||p(!1)},[t]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...c},children:[(0,r.jsx)("input",{type:u?"text":"password",value:t,onChange:e=>n(e.target.value),onKeyDown:l,placeholder:o,style:{...sU,paddingRight:34,fontFamily:s?"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 sK(e){let{value:t,onChange:n,placeholder:i}=e;return(0,r.jsx)("input",{type:"number",value:t,onChange:e=>n(e.target.value),placeholder:i,style:sU})}function sV(e){let{value:t,onChange:n,options:i,required:o}=e,{t:s}=(0,E.s)();return(0,r.jsxs)("select",{value:t,onChange:e=>n(e.target.value),style:{...sU,color:t?"var(--text)":"var(--text-dim)"},children:[!o&&(0,r.jsxs)("option",{value:"",children:["— ",s("i18n.default")," / none —"]}),i.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]})}function sJ(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 sY(e){let{children:t}=e;return(0,r.jsx)(si,{children:t})}function sG(e){let{name:t,editingName:n,provider:o,onChange:s,onEditingNameChange:l,onRename:a,onDelete:d,onAddModels:c,enabledModels:u}=e,{t:p}=(0,E.s)(),[h,f]=(0,i.useState)({phase:"idle"}),[m,g]=(0,i.useState)(""),[x,v]=(0,i.useState)([]),b=(0,i.useRef)(0),y=(0,i.useRef)(null),j=(0,i.useId)(),k=(e,t)=>s({...o,[e]:t});(0,i.useEffect)(()=>{o.api||s({...o,api:"openai-completions"})},[o.api]),(0,i.useEffect)(()=>{b.current+=1,f({phase:"idle"}),g(""),v([])},[t,o.baseUrl,o.api,o.apiKey]);let w=(0,i.useCallback)(async()=>{if("loading"===h.phase)return;let e=++b.current;f({phase:"loading"}),v([]);try{let n=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:t,provider:{...o,models:void 0}})}),r=await n.json();if(e!==b.current)return;if(!n.ok||r.error||!r.models)return void f({phase:"error",message:r.error??`HTTP ${n.status}`});f({phase:"success",models:r.models,endpoint:r.endpoint??o.baseUrl??""})}catch(t){if(e!==b.current)return;f({phase:"error",message:t instanceof Error?t.message:String(t)})}},[h.phase,t,o]),S=new Set((o.models??[]).map(e=>e.id)),C="success"===h.phase?h.models:[],N=m.trim().toLocaleLowerCase(),I=C.filter(e=>!N||e.id.toLocaleLowerCase().includes(N)||e.name?.toLocaleLowerCase().includes(N)),$=I.slice(0,300),T=$.filter(e=>!S.has(e.id)).map(e=>e.id),M=x.filter(e=>!S.has(e)).length,R=T.length>0&&T.every(e=>x.includes(e)),L=!R&&T.some(e=>x.includes(e));return(0,i.useEffect)(()=>{y.current&&(y.current.indeterminate=L)},[L]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(se,{children:[(0,r.jsx)(st,{children:(0,r.jsx)(sY,{children:p("i18n.provider")})}),(0,r.jsxs)(sn,{children:[(0,r.jsx)(s$,{providerId:t,controller:u,noteId:j}),(0,r.jsx)(sb,{variant:"danger",size:"small",onClick:d,children:p("i18n.delete")})]})]}),(0,r.jsx)(sM,{providerId:t,controller:u,id:j})]}),(0,r.jsxs)(s_,{label:p("i18n.providerName"),children:[(0,r.jsx)(sq,{value:n,onChange:l,placeholder:"provider-name",mono:!0}),n!==t&&n.trim()&&(0,r.jsx)("button",{onClick:()=>a(n.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--accent)",border:"none",borderRadius:4,color:"var(--accent-contrast)",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:p("i18n.rename")})]}),(0,r.jsxs)(s_,{label:"Base URL",children:[(0,r.jsx)(sq,{value:o.baseUrl??"",onChange:e=>k("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Leave empty for a built-in provider to use the endpoint pi ships"})]}),(0,r.jsxs)(s_,{label:"API Key",children:[(0,r.jsx)(sZ,{value:o.apiKey??"",onChange:e=>k("apiKey",e||void 0),placeholder:"ENV_VAR_NAME, !shell-command, or literal key",mono:!0}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:["Prefix with ",(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:"!"})," to run a shell command, or use an env var name"]})]}),(0,r.jsx)(s_,{label:"API",children:(0,r.jsx)(sV,{value:o.api??"openai-completions",onChange:e=>k("api",e),options:sH,required:!0})}),(0,r.jsxs)(s_,{label:"Headers",children:[(0,r.jsx)(s4,{headers:o.headers,onChange:e=>k("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to every request from this provider (e.g. User-Agent). Useful for gateways with bot detection."})]}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==h.phase&&(0,r.jsx)("button",{onClick:w,disabled:"loading"===h.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:"loading"===h.phase?"var(--text-dim)":"var(--text-muted)",cursor:"loading"===h.phase?"not-allowed":"pointer",fontSize:11},children:"loading"===h.phase?p("models.discoveryFetching"):p("models.discoveryFetch")}),"error"===h.phase&&(0,r.jsx)("div",{style:{padding:"7px 9px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",fontSize:11,lineHeight:1.4},children:h.message}),"success"===h.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:m,onChange:e=>g(e.target.value),placeholder:p("models.discoveryFilterPlaceholder",{count:h.models.length}),"aria-label":p("models.discoveryFilter"),style:{...sU,width:"100%",minWidth:0}}),(0,r.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,r.jsxs)("label",{style:{minHeight:32,padding:"5px 9px",display:"flex",alignItems:"center",gap:8,position:"sticky",top:0,zIndex:1,borderBottom:"1px solid var(--border)",background:"var(--bg)",cursor:T.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:y,type:"checkbox",checked:R,disabled:0===T.length,onChange:()=>{let e=new Set(T);v(t=>R?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...T])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),p("models.discoverySelectShown")]}),0===$.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:p("models.discoveryNoMatches")}):$.map((e,t)=>{let n=S.has(e.id),i=x.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:i||n,disabled:n,onChange:()=>{var t;return t=e.id,void v(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),n&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:p("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:h.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:I.length>$.length?p("models.discoveryShowing",{shown:$.length,total:I.length}):p("models.discoveryFetched",{count:h.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==h.phase)return;let e=new Set(x),t=h.models.filter(t=>e.has(t.id)&&!S.has(t.id));0!==t.length&&(c(t),v([]))},disabled:0===M,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:M?"var(--accent)":"var(--bg-panel)",color:M?"var(--accent-contrast)":"var(--text-dim)",cursor:M?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:M?p("models.discoveryAddSelectedCount",{count:M}):p("models.discoveryAddSelected")})]})]})]})]})}let sX=["off","minimal","low","medium","high","xhigh","max"],sQ={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function s0(e){let{value:t,onChange:n}=e,i=t??{},o=(e,t)=>{let r={...i};"omit"===t?delete r[e]:r[e]=t,n(Object.keys(r).length?r:void 0)};return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:sX.map(e=>{let t=i[e],n=e in i?null===t?"null":"string":"omit",s="string"==typeof t?t:"",l=sQ[e],a={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)"},d={background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600};return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:l,flexShrink:0,opacity:"null"===n?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===n?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===n?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>o(e,"omit"),style:{...a,..."omit"===n?d:{}},children:"Default"}),(0,r.jsx)("button",{onClick:()=>o(e,null),style:{...a,borderLeft:"1px solid var(--border)",..."null"===n?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===n?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>o(e,s||e),style:{...a,..."string"===n?d:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,r.jsx)("input",{value:s,onChange:t=>o(e,t.target.value),onFocus:()=>{"string"!==n&&o(e,s||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 s1={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function s2(e){return e.compat?.thinkingFormat==="deepseek"}function s4(e){let{headers:t,onChange:n}=e,[o,s]=(0,i.useState)(()=>Object.entries(t??{}).map((e,t)=>{let[n,r]=e;return{id:t,name:n,value:r}})),l=(0,i.useRef)(o.length),a=e=>{s(e),n(function(e){let t={};for(let n of e){let e=n.name.trim();e&&(t[e]=n.value)}return Object.keys(t).length?t:void 0}(e))},d=(e,t)=>{a(o.map(n=>n.id===e?{...n,...t}:n))},c={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[o.map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{value:e.name,onChange:t=>d(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...sU,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>d(e.id,{value:t.target.value}),placeholder:"value",style:{...sU,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void a(o.filter(e=>e.id!==t))},style:c,children:"✕"})]},e.id)),(0,r.jsx)("button",{onClick:()=>s(e=>[...e,{id:l.current++,name:"",value:""}]),style:{padding:"5px 9px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,alignSelf:"flex-start"},children:"+ Add header"})]})}function s8(e){let{providerName:t,provider:n,model:o,onChange:s,onDelete:l}=e,[a,d]=(0,i.useState)({phase:"idle"}),{t:c}=(0,E.s)(),[u,p]=(0,i.useState)({phase:"idle"}),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(()=>oJ(o.cost)),x=(0,i.useRef)(m),[v,b]=(0,i.useState)(!1),y=(0,i.useRef)(0),j=(0,i.useRef)(null),k=(0,i.useRef)(o.cost),w=(e,t)=>s({...o,[e]:t}),S=(()=>{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)(()=>{d({phase:"idle"})},[t,n.baseUrl,n.api,n.apiKey,o.id,o.api]),(0,i.useEffect)(()=>{y.current+=1,p({phase:"idle"}),j.current=null},[t,n.baseUrl,o.id]);let C=(0,i.useCallback)(async()=>{if(o.id.trim()&&"testing"!==a.phase){d({phase:"testing"});try{let e=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:t,provider:n,model:o})}),r=await e.json();if(!e.ok||!r.ok)return void d({phase:"error",message:r.error??`HTTP ${e.status}`,latencyMs:r.latencyMs,status:r.status});d({phase:"success",latencyMs:r.latencyMs,status:r.status,responseText:r.responseText})}catch(e){d({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[o,n,t,a.phase]),N=(0,i.useCallback)(async()=>{let e=o.id.trim();if(!e||"loading"===u.phase)return;let r=++y.current;p({phase:"loading"});try{let i=new URLSearchParams({q:e,provider:t,limit:"50"});n.baseUrl?.trim()&&i.set("baseUrl",n.baseUrl.trim());let l=await fetch(`/api/models-config/catalog?${i}`),a=await l.json();if(r!==y.current)return;if(!l.ok||a.error||!a.recommendation)return void p({phase:"error",message:a.error??`HTTP ${l.status}`});let d=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??{}},o=0;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],o+=1);let s=oY(oJ(i));o>0&&s&&(n.cost={...i,...s},r+=o)}return{model:n,appliedCount:r}}(o,a.recommendation.preset);d.appliedCount>0&&(j.current=o,s(d.model)),f(!1),p({phase:"success",recommendation:a.recommendation,appliedCount:d.appliedCount})}catch(e){if(r!==y.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,o,s,n.baseUrl,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}`})(),$="error"===u.phase?u.message:I,T="error"===u.phase?"#ef4444":"success"===u.phase&&"unreliable"===u.recommendation.price.status?"#d97706":"var(--text-dim)",M=[{key:"input",label:c("models.costInput")},{key:"output",label:c("models.costOutput")},{key:"cacheRead",label:c("models.costCacheRead")},{key:"cacheWrite",label:c("models.costCacheWrite")}],R=new Set(Object.keys(o.compat??{})),L=0;s2(o)&&(L+=1,R.delete("thinkingFormat"),R.delete("requiresReasoningContentOnAssistantMessages")),Object.prototype.hasOwnProperty.call(o.compat??{},"supportsDeveloperRole")&&(L+=1,R.delete("supportsDeveloperRole")),L+=R.size;let z=[o.api?`API: ${o.api}`:null,Object.keys(o.headers??{}).length?c("models.headersSummary",{count:Object.keys(o.headers??{}).length}):null,L?c("models.compatSummary",{count:L}):null,Object.keys(o.thinkingLevelMap??{}).length?c("models.thinkingSummary",{count:Object.keys(o.thinkingLevelMap??{}).length}):null].filter(e=>!!e),A=z.length?z.join(" \xb7 "):c("models.providerDefaults");return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(se,{children:[(0,r.jsx)(st,{children:(0,r.jsx)(sY,{children:c("i18n.model")})}),(0,r.jsxs)(sn,{children:[S&&(0,r.jsx)("span",{title:S,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:S}),(0,r.jsxs)(sb,{size:"small",variant:"success"===a.phase?"primary":"secondary",onClick:"success"===a.phase?()=>d({phase:"idle"}):C,disabled:!o.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)(sb,{variant:"danger",size:"small",onClick:l,children:c("i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(s_,{label:"ID *",children:(0,r.jsx)(sq,{value:o.id,onChange:e=>w("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(s_,{label:"Name",children:(0,r.jsx)(sq,{value:o.name??"",onChange:e=>w("name",e||void 0),placeholder:"Display name"})})]}),(0,r.jsxs)("div",{style:{padding:"2px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>void N(),disabled:!o.id.trim()||"loading"===u.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:o.id.trim()&&"loading"!==u.phase?"var(--text-muted)":"var(--text-dim)",cursor:o.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")})]}),$&&(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:$,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:$}),j.current&&(0,r.jsx)("button",{onClick:()=>{let e=j.current;e&&(j.current=null,s(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)(sY,{children:c("models.capabilities")}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginTop:8},children:[(0,r.jsx)(sJ,{label:c("models.reasoning"),checked:o.reasoning??!1,onChange:e=>w("reasoning",e||void 0)}),(0,r.jsx)(sJ,{label:c("models.imageInput"),checked:o.input?.includes("image")??!1,onChange:e=>w("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)(sY,{children:c("models.modelSpecs")}),(0,r.jsx)("button",{type:"button",onClick:()=>{if(h)return void f(!1);k.current=o.cost;let e=oJ(o.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)(s_,{label:c("models.contextWindow"),children:(0,r.jsx)(sK,{value:void 0!==o.contextWindow?String(o.contextWindow):"",onChange:e=>w("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(s_,{label:c("models.maxOutputTokens"),children:(0,r.jsx)(sK,{value:void 0!==o.maxTokens?String(o.maxTokens):"",onChange:e=>w("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:[M.map(e=>{let{key:t,label:n}=e;return(0,r.jsx)(s_,{label:n,children:(0,r.jsx)(sK,{value:m[t],onChange:e=>{let n,r,i;return r=oY(n={...x.current,[t]:e}),i={...o},void(x.current=n,g(n),r?(i.cost={...k.current??{},...r},k.current=i.cost):delete i.cost,s(i))},placeholder:"0"})},t)}),oG(m)&&!oY(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:M.map(e=>{let t,{key:n,label:i}=e,s=o.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:s?"var(--text-dim)":"var(--text)",fontSize:12,fontFamily:"var(--font-mono)",fontVariantNumeric:"tabular-nums"},children:void 0===(t=o.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:A})]}),(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)(s_,{label:c("models.apiOverride"),children:(0,r.jsx)(sV,{value:o.api??"",onChange:e=>w("api",e||void 0),options:sH})}),(0,r.jsxs)(s_,{label:c("models.headers"),children:[(0,r.jsx)(s4,{headers:o.headers,onChange:e=>w("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:c("models.headersHelp")})]}),o.reasoning&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsx)(sY,{children:c("models.compatibility")}),(0,r.jsx)(sJ,{label:c("models.deepSeekThinkingCompat"),checked:s2(o),onChange:e=>s(function(e,t){if(t)return{...e,compat:{...e.compat??{},...s1}};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}}(o,e))}),(0,r.jsx)(sJ,{label:c("models.developerRole"),checked:!1!==({...n.compat??{},...o.compat??{}}).supportsDeveloperRole,onChange:e=>s({...o,compat:{...o.compat??{},supportsDeveloperRole:e}})}),(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)(sY,{children:c("models.thinkingLevelMap")}),o.thinkingLevelMap&&(0,r.jsx)("button",{type:"button",onClick:()=>w("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)(s0,{value:o.thinkingLevelMap,onChange:e=>w("thinkingLevelMap",e)})]})]})]})]})]})}function s3(e){let{provider:t,onRefresh:n,enabledModels:o}=e,[s,l]=(0,i.useState)({phase:"idle"}),{t:a}=(0,E.s)(),[d,c]=(0,i.useState)(""),u=(0,i.useRef)(null),p=(0,i.useRef)(null);(0,i.useEffect)(()=>{("auth"===s.phase||"prompt"===s.phase)&&setTimeout(()=>p.current?.focus(),50)},[s.phase]),(0,i.useEffect)(()=>{l({phase:"idle"}),c(""),u.current?.close(),u.current=null},[t.id]),(0,i.useEffect)(()=>()=>{u.current?.close()},[]);let h=(0,i.useCallback)(()=>{u.current?.close(),l({phase:"connecting"}),c("");let e=new EventSource(`/api/auth/login/${encodeURIComponent(t.id)}`);u.current=e,e.onmessage=t=>{let r=JSON.parse(t.data);"auth"===r.type?(l({phase:"auth",url:r.url,instructions:r.instructions??null,token:r.token}),window.open(r.url,"_blank","noopener,noreferrer")):"device_code"===r.type?(l({phase:"device_code",userCode:r.userCode,verificationUri:r.verificationUri,intervalSeconds:r.intervalSeconds??null,expiresInSeconds:r.expiresInSeconds??null}),window.open(r.verificationUri,"_blank","noopener,noreferrer")):"prompt_request"===r.type?l({phase:"prompt",message:r.message,placeholder:r.placeholder??null,token:r.token}):"select_request"===r.type?l({phase:"select",message:r.message,options:r.options??[],token:r.token}):"progress"===r.type?l({phase:"progress",message:r.message}):"success"===r.type?(e.close(),l({phase:"success"}),n()):"error"===r.type?(e.close(),l({phase:"error",message:r.message})):"cancelled"===r.type&&(e.close(),l({phase:"idle"}))},e.onerror=()=>{e.close(),l(e=>"success"===e.phase?e:{phase:"error",message:"Connection lost"})}},[t.id,n]),f=(0,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(t.id)}`,{method:"POST"}),l({phase:"idle"}),n()},[t.id,n]),m=(0,i.useCallback)(async(e,n)=>{if(n.trim()){l({phase:"progress",message:"Verifying…"});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,code:n.trim()})});if(!r.ok){let e=await r.json().catch(()=>({}));l({phase:"error",message:e.error??`Server error ${r.status}`});return}c("")}catch(e){l({phase:"error",message:e instanceof Error?e.message:"Network error"})}}},[t.id]),g=(0,i.useCallback)(async(e,n)=>{l({phase:"progress",message:"Continuing…"});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,code:n})});if(!r.ok){let e=await r.json().catch(()=>({}));l({phase:"error",message:e.error??`Server error ${r.status}`})}}catch(e){l({phase:"error",message:e instanceof Error?e.message:"Network error"})}},[t.id]),x="connecting"===s.phase||"progress"===s.phase||"auth"===s.phase||"device_code"===s.phase||"prompt"===s.phase||"select"===s.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:t.loggedIn&&"idle"===s.phase?0:16},children:[(0,r.jsxs)(se,{children:[(0,r.jsx)(st,{children:(0,r.jsx)(sY,{children:a("i18n.subscription")})}),(0,r.jsxs)(sn,{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:a(t.loggedIn?"i18n.connected":"i18n.notConnected")})]}),x?(0,r.jsx)(sb,{size:"small",onClick:()=>{u.current?.close(),l({phase:"idle"})},children:a("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(sb,{variant:"primary",size:"small",onClick:h,children:a(t.loggedIn?"i18n.relogin":"i18n.login")}),t.loggedIn&&(0,r.jsx)(sb,{variant:"danger",size:"small",onClick:f,children:a("i18n.disconnect")})]})]})]}),(0,r.jsxs)("div",{style:{minHeight:t.loggedIn&&"idle"===s.phase?0:48},children:["idle"===s.phase&&!t.loggedIn&&(0,r.jsxs)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:["Connect your ",t.name," account."]}),"connecting"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:a("i18n.openingBrowser")}),"select"===s.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:s.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s.options.map(e=>(0,r.jsx)("button",{onClick:()=>g(s.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),("auth"===s.phase||"prompt"===s.phase)&&(0,r.jsx)(sL,{message:"auth"===s.phase?"Complete sign-in in the browser, then copy the redirect URL from the address bar and paste it below.":s.message,hint:"auth"===s.phase?(0,r.jsxs)(r.Fragment,{children:["If the browser window did not open,"," ",(0,r.jsx)("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",children:"click here to open the login page"}),"."]}):void 0,value:d,placeholder:"auth"===s.phase?"http://localhost:1455/auth/callback?code=…":s.placeholder??"Enter value…",submitLabel:a("i18n.submit"),inputRef:p,onValueChange:c,onSubmit:()=>void m(s.token,d)}),"device_code"===s.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:s.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:s.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:s.verificationUri}),s.expiresInSeconds?` Expires in ${Math.ceil(s.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:s.message}),"success"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:a("i18n.connectedSuccessfully")}),"error"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:s.message})]}),(0,r.jsx)(sO,{providerId:t.id,enabled:t.loggedIn}),t.loggedIn&&(0,r.jsx)(sR,{providerId:t.id,controller:o})]})}function s5(e){let{provider:t,onRefresh:n,enabledModels:o}=e,[s,l]=(0,i.useState)(""),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(!1),{t:g}=(0,E.s)();(0,i.useEffect)(()=>{l(""),h(null),m(!1)},[t.id]);let x=(0,i.useCallback)(async()=>{if(s.trim()){d(!0),h(null),m(!1);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:s.trim()})}),r=await e.json();!e.ok||r.error?h(r.error??`HTTP ${e.status}`):(l(""),m(!0),setTimeout(()=>m(!1),2e3),n())}catch(e){h(String(e))}finally{d(!1)}}},[s,t.id,n]),v=(0,i.useCallback)(async()=>{u(!0),h(null);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"DELETE"}),r=await e.json();!e.ok||r.error?h(r.error??`HTTP ${e.status}`):n()}catch(e){h(String(e))}finally{u(!1)}},[t.id,n]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(se,{children:[(0,r.jsx)(st,{children:(0,r.jsx)(sY,{children:"API Key"})}),(0,r.jsxs)(sn,{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:g(t.configured?"i18n.configured":"i18n.notConfigured")})]}),t.configured&&(0,r.jsx)(sb,{variant:"danger",size:"small",onClick:v,disabled:c,children:g(c?"i18n.removing":"i18n.disconnect")})]})]}),!t.configured&&(0,r.jsxs)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:["Enter your ",t.displayName," API key to enable ",t.modelCount," model",1!==t.modelCount?"s":"","."]}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(sZ,{value:s,onChange:l,onKeyDown:e=>{"Enter"===e.key&&s.trim()&&x()},placeholder:t.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:x,disabled:a||!s.trim()||f,style:{padding:"6px 12px",background:f?"#16a34a":s.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:f?"#fff":s.trim()?"var(--accent-contrast)":"var(--text-dim)",cursor:a||!s.trim()||f?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[f&&(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"})}),g(f?"i18n.saved":a?"i18n.saving":"i18n.save")]})]}),p&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:p}),(0,r.jsx)(sO,{providerId:t.id,enabled:t.configured}),t.configured&&(0,r.jsx)(sR,{providerId:t.id,controller:o})]})}function s6(e){let{oauthProviders:t,apiKeyProviders:n,onSelectOAuth:o,onSelectApiKey:s,onAddCustom:l,onClose:a}=e,[d,c]=(0,i.useState)(""),{t:u}=(0,E.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&&(!h||e.name.toLowerCase().includes(h))),m=n.filter(e=>!e.configured&&(!h||e.displayName.toLowerCase().includes(h)||e.id.toLowerCase().includes(h))),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.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:()=>{l(),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:()=>{o(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)(sA,{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:()=>{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.displayName}),(0,r.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[e.modelCount," models"]})]}),(0,r.jsx)(sA,{id:e.id,size:28})]},e.id))]})})]})})}function s9(e){let{onClose:t,embedded:n=!1,cwd:o=null}=e,{t:s}=(0,E.s)(),l=function(e){let[t,n]=(0,i.useState)(null),[r,o]=(0,i.useState)(!0),[s,l]=(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;o(!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||o(!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,l(t),d(null),(async()=>{try{let t=await fetch("/api/models/enabled",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...e?{cwd:e}:{}})}),i=await t.json();if(!t.ok||i.error){let e=i.reason?sN[i.reason]:void 0;d(e?{messageKey:e}:{message:i.error??`HTTP ${t.status}`});return}n(i)}catch(e){d({message:e instanceof Error?e.message:String(e)})}finally{c.current=null,l(null);let e=u.current;u.current=null,e&&p.current?.(e.key,e.body)}})()},[e]);p.current=m;let g=(0,i.useCallback)((e,t,n)=>{m(e,{op:"models",refs:t,enabled:n})},[m]),x=(0,i.useCallback)((e,t)=>{m(`provider:${e}`,{op:"provider",provider:e,enabled:t})},[m]),v=(0,i.useCallback)(()=>m("clear",{op:"clear"}),[m]),b=(0,i.useCallback)(()=>m("prune",{op:"prune"}),[m]),y=(0,i.useCallback)(()=>f(e=>e+1),[]),j=(0,i.useCallback)((e,n)=>{m("resync",{op:"resync",renames:e,modelRenames:n,fullyEnabled:(t?.providers??[]).filter(e=>e.models.length>0&&e.enabledCount===e.models.length).map(e=>e.id)})},[m,t]);return{view:t,loading:r,pending:s,failure:a,setModels:g,setProvider:x,clearScope:v,pruneStale:b,refresh:y,resync:j}}(o),[a,d]=(0,i.useState)({providers:{}}),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(!1),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(!1),[y,j]=(0,i.useState)(sD),[k,w]=(0,i.useState)([]),[S,C]=(0,i.useState)([]),[N,I]=(0,i.useState)(!1),$=(0,i.useRef)(new Set),T=(0,i.useRef)(new Map),M=(0,i.useRef)(new Map),[R,L]=(0,i.useState)(null),z=(0,i.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>{Array.isArray(e.oauthProviders)&&w(e.oauthProviders),Array.isArray(e.apiKeyProviders)&&C(e.apiKeyProviders)}).catch(()=>{})},[]);(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:{}};d(t),$.current=new Set(Object.keys(t.providers??{})),M.current=oX(t);let n=Object.keys(t.providers??{});j(e=>e&&("provider"===e.type?t.providers?.[e.name]:"model"!==e.type||t.providers?.[e.providerName]?.models?.[e.index])?e:n[0]?{type:"provider",name:n[0]}:null)}).catch(e=>x(e instanceof Error?e.message:String(e))).finally(()=>u(!1)),z()},[z]),(0,i.useEffect)(()=>{y&&oq("models",JSON.stringify(y))},[y]);let A=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;a.providers?.[e];)e=`new-provider-${t++}`;d(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),j({type:"provider",name:e})},[a.providers]),W=(0,i.useCallback)((e,t)=>{d(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),P=(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:o,savedProviders:s,slots:l}=t,a=n;for(let[e,t]of o)if(t===n){a=e;break}a===r?o.delete(a):s.has(a)&&o.set(a,r);let d=l.get(n);d&&(l.delete(n),l.set(r,d));let c=Object.entries(i),u=c.findIndex(e=>{let[t]=e;return t===n});return c[u]=[r,c[u][1]],{...e,providers:Object.fromEntries(c)}}(e,{savedProviders:$.current,renames:T.current,slots:M.current},t,n);return r?(d(r),L(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},[]),O=(0,i.useCallback)((e,t)=>{P(a,e,t)?m(null):m(s("models.providerNameTaken",{name:t}))},[P,a,s]),F=(0,i.useCallback)(e=>{M.current.delete(e),L(t=>t?.provider===e?null:t),d(t=>{let n={...t.providers??{}};return delete n[e],{...t,providers:n}}),d(e=>{let t=Object.keys(e.providers??{});return j(t.length>0?{type:"provider",name:t[0]}:null),e})},[]),B=(0,i.useCallback)(e=>{oQ(M.current,e,1),d(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),d(t=>{let n=(t.providers?.[e]?.models?.length??1)-1;return j({type:"model",providerName:e,index:n}),t})},[]),D=(0,i.useCallback)((e,t)=>{d(n=>{let r=new Set((n.providers?.[e]?.models??[]).map(e=>e.id));oQ(M.current,e,t.filter(e=>!r.has(e.id)).length);let i=n.providers?.[e]??{},o=[...i.models??[]],s=new Set(o.map(e=>e.id));for(let e of t)s.has(e.id)||(s.add(e.id),o.push({id:e.id,name:e.name}));return{...n,providers:{...n.providers??{},[e]:{...i,models:o}}}})},[]),H=(0,i.useCallback)((e,t,n)=>{d(r=>{let i=r.providers?.[e]??{},o=[...i.models??[]];return o[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:o}}}})},[]),_=(0,i.useCallback)((e,t)=>{M.current.get(e)?.splice(t,1),d(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})},[]),U=(0,i.useCallback)(async()=>{if(g)return;h(!0),m(null),b(!1);let e=a,t=R?.name.trim();if(R&&t&&a.providers?.[R.provider]){let n=P(a,R.provider,t);if(!n){m(s("models.providerNameTaken",{name:t})),h(!1);return}e=n}try{let t=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json();if(!t.ok||n.error)m(n.error??`HTTP ${t.status}`);else{b(!0),setTimeout(()=>b(!1),2e3);let t=[...T.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,o]of Object.entries(e.providers??{})){let e=t.get(n);e&&(o.models??[]).forEach((t,o)=>{let s=e[o];s&&t.id&&s!==t.id&&i.push({from:`${r(n)}/${s}`,to:`${n}/${t.id}`})})}return i}(e,M.current,T.current);$.current=new Set(Object.keys(e.providers??{})),M.current=oX(e),T.current.clear(),l.resync(t,n)}}catch(e){m(String(e))}finally{h(!1)}},[P,a,l,g,R,s]),q=Object.entries(a.providers??{}),Z=e=>{let t=function(e,t){if(!e||e.allEnabled)return null;let n=sE(e,t);return n?`${n.enabledCount}/${n.models.length}`:null}(l.view,e);return t?(0,r.jsx)("span",{className:"models-sidebar-badge",children:t}):null},K=k.filter(e=>e.loggedIn),V=S.filter(e=>e.configured),J=(()=>{if(!y)return null;if("oauth"===y.type){let e=k.find(e=>e.id===y.providerId);return e?(0,r.jsx)(s3,{provider:e,onRefresh:z,enabledModels:l},e.id):null}if("apikey"===y.type){let e=S.find(e=>e.id===y.providerId);return e?(0,r.jsx)(s5,{provider:e,onRefresh:z,enabledModels:l},e.id):null}if("provider"===y.type){let e=a.providers?.[y.name];return e?(0,r.jsx)(sG,{name:y.name,editingName:R?.provider===y.name?R.name:y.name,provider:e,onChange:e=>W(y.name,e),onEditingNameChange:e=>L(e===y.name?null:{provider:y.name,name:e}),onRename:e=>O(y.name,e),onDelete:()=>F(y.name),onAddModels:e=>D(y.name,e),enabledModels:l},y.name):null}let e=a.providers?.[y.providerName],t=e?.models?.[y.index];return t?(0,r.jsx)(s8,{providerName:y.providerName,provider:e,model:t,onChange:e=>H(y.providerName,y.index,e),onDelete:()=>_(y.providerName,y.index)},`${y.providerName}-${y.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(o0,{embedded:n,title:s("common.models"),subtitle:"~/.pi/agent/models.json",closeLabel:s("i18n.close"),onClose:t,children:[(0,r.jsx)(sI,{controller:l}),(0,r.jsxs)(o1,{children:[(0,r.jsxs)(o2,{children:[(0,r.jsxs)(o4,{children:[K.map(e=>{let t=y?.type==="oauth"&&y.providerId===e.id;return(0,r.jsxs)(o6,{active:t,onClick:()=>j({type:"oauth",providerId:e.id}),children:[(0,r.jsx)(sA,{id:e.id,size:16}),(0,r.jsx)(o9,{className:"is-grow",children:e.name}),Z(e.id)]},e.id)}),V.map(e=>{let t=y?.type==="apikey"&&y.providerId===e.id;return(0,r.jsxs)(o6,{active:t,onClick:()=>j({type:"apikey",providerId:e.id}),children:[(0,r.jsx)(sA,{id:e.id,size:16}),(0,r.jsx)(o9,{className:"is-grow",children:e.displayName}),Z(e.id)]},e.id)}),(K.length>0||V.length>0)&&q.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),c?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:s("i18n.loading")}):q.map(e=>{let[t,n]=e,i=y?.type==="provider"&&y.name===t,o=n.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)(o6,{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)(o9,{className:"is-grow",children:t}),Z(t)]}),o.map((e,n)=>{let i=y?.type==="model"&&y.providerName===t&&y.index===n;return(0,r.jsxs)(o6,{active:i,className:"models-sidebar-indented-item",onClick:()=>j({type:"model",providerName:t,index:n}),children:[(0,r.jsx)(o9,{className:"is-grow",style:{color:e.id?"var(--text-muted)":"var(--text-dim)"},children:e.id||s("i18n.newModel")}),e.reasoning&&(0,r.jsx)("span",{style:{fontSize:9,padding:"1px 4px",background:"rgba(99,102,241,0.12)",color:"rgba(99,102,241,0.8)",borderRadius:3,flexShrink:0},children:"T"})]},n)}),(0,r.jsx)(o6,{className:"models-sidebar-indented-item models-sidebar-add-item",onClick:e=>{e.stopPropagation(),B(t)},children:(0,r.jsxs)(o9,{children:["+ ",s("i18n.model")]})})]},t)})]}),(0,r.jsx)(sj,{onClick:()=>I(!0),children:s("i18n.addProvider")})]}),(0,r.jsx)(sg,{children:(0,r.jsx)(o7,{className:"is-fill",children:c?null:J??(0,r.jsx)(sm,{children:s("i18n.selectProviderModel")})})})]}),(0,r.jsxs)(sx,{status:(g||f)&&(0,r.jsx)("span",{style:{color:"#f87171"},children:g?s("models.configUnreadable",{error:g}):f}),children:[!n&&(0,r.jsx)(sb,{onClick:t,children:s("i18n.cancel")}),(0,r.jsxs)(sb,{variant:"primary",onClick:U,disabled:p||v||null!==g,className:v?"is-success":void 0,children:[v&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:v?s("i18n.saved"):p?s("i18n.saving"):s("i18n.save")})]})]})]}),N&&(0,r.jsx)(s6,{oauthProviders:k,apiKeyProviders:S,onSelectOAuth:e=>j({type:"oauth",providerId:e}),onSelectApiKey:e=>j({type:"apikey",providerId:e}),onAddCustom:A,onClose:()=>I(!1)})]})}let s7=null;async function le(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(s7)return s7;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 s7=null,!1}})();return s7=t,t.then(e=>{e||s7!==t||(s7=null)}),t}function lt(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function ln(e,t){let n=t.replace(/[/\\]+$/,"");return n&&(e===n||e.startsWith(`${n}/`)||e.startsWith(`${n}\\`))?`./${e.slice(n.length).replace(/^[/\\]/,"")}`:lt(e)}function lr(e,t,n,r){return e.filter(e=>n(e)!==t&&(t||!r?.(e)))}function li(e){return e?JSON.stringify([e.requiresTrust,e.trusted,e.decision,e.decisionPath??null,e.inherited]):""}function lo(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function ls(e,t){return t("project"===e?"skills.scope.project":"global"===e?"skills.scope.global":"skills.scope.path")}function ll(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function la(e,t){return e?e.slice(0,8):t}function ld(e){let{skill:t,cwd:n,onToggle:i,toggling:o,saveError:s,updateStatus:l,checkingUpdate:a,updating:d,updateError:c,onCheckUpdate:u,onUpdate:p}=e,{t:h}=(0,E.s)(),f=lo(t),m=!t.disableModelInvocation;return(0,r.jsxs)(o7,{children:[(0,r.jsxs)("div",{className:"skill-detail-heading",children:[(0,r.jsxs)(se,{children:[(0,r.jsxs)(st,{children:[(0,r.jsx)(sa,{scope:f,children:ls(f,h)}),(0,r.jsx)("span",{className:"config-detail-path",children:"project"===f?ln(t.filePath,n):lt(t.filePath)})]}),(0,r.jsx)(sn,{children:(0,r.jsx)(sy,{checked:m,loading:o,label:h(m?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),onChange:()=>i(t)})})]}),(0,r.jsxs)("div",{className:"skill-detail-status-row",children:[!m&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:h("i18n.hiddenButInvocable")}),s&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:s})]})]}),t.install?.skillsShUrl&&(0,r.jsx)(so,{label:h("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)(so,{label:h("i18n.version"),children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:la(l?.currentVersion??t.install.versionHash,h("i18n.unknown"))}),t.install.canCheckForUpdates&&(0,r.jsx)(sb,{size:"small",onClick:u,disabled:a||d,children:h("i18n.check")}),l?.state==="update-available"&&(0,r.jsx)("span",{className:"skill-version-value is-update",children:la(l.latestVersion,h("i18n.unknown"))}),(a||l&&"update-available"!==l.state)&&(0,r.jsx)("span",{className:`skill-update-status ${a?"is-checking":l?.state==="up-to-date"?"is-success":l?.state==="error"?"is-error":"is-muted"}`,children:a?h("i18n.checking"):l?.state==="up-to-date"?h("i18n.upToDate"):l?.state==="unsupported"?h("i18n.automaticChecksUnavailable"):l?.message||h("i18n.checkFailed")}),l?.state==="update-available"&&(0,r.jsx)(sb,{variant:"primary",size:"small",onClick:p,disabled:d||a,children:h(d?"i18n.updating":"i18n.update")})]}),c&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:c})]}),(0,r.jsx)(so,{label:h("config.name"),children:(0,r.jsx)("span",{className:"skill-name-value",children:t.name})}),(0,r.jsx)(so,{label:h("i18n.description"),children:(0,r.jsx)("span",{className:"skill-description",children:t.description})})]})}function lc(e){let{cwd:t,installedPackages:n,projectResourcesLoaded:o,onInstalled:s}=e,{t:l}=(0,E.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,j]=(0,i.useState)(new Set),[k,w]=(0,i.useState)("global"),S=(0,i.useRef)(null);(0,i.useEffect)(()=>{S.current?.focus()},[]);let C=(0,i.useCallback)(async e=>{if(e.trim()){h(!0),m(null),u([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),n=await t.json();if(n.error)return void m(n.error);u(n.results??[]),0===(n.results??[]).length&&m(l("i18n.noSkills"))}catch(e){m(String(e))}finally{h(!1)}}},[l]),N=(0,i.useCallback)(async e=>{x(e),b(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:e,scope:k,cwd:t})}),r=await n.json();if(!n.ok||r.error)return void b(r.error??`HTTP ${n.status}`);j(t=>new Set(t).add(`${k}:${e}`)),s()}catch(e){b(String(e))}finally{x(null)}},[s,k,t]),I="global"===k?"~/.pi/agent/skills/":`${lt(t)}/.pi/skills/`;return(0,r.jsxs)(o7,{className:"is-full-height",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)(su,{title:l("i18n.addSkill"),catalogs:[{href:"https://skills.sh",label:"skills.sh"}],target:(0,r.jsx)(sc,{value:k,label:l("config.saveTo"),options:[{value:"global",label:ls("global",l)},{value:"project",label:ls("project",l),disabled:!o}],path:I,disabledReason:l("trust.projectScopeUnavailable"),onChange:w})}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:S,value:a,onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&C(a)},placeholder:l("i18n.skillSearchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:12,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",outline:"none"}}),(0,r.jsx)(sb,{variant:"primary",onClick:()=>C(a),disabled:p||!a.trim(),children:p?l("i18n.searching"):l("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,o=e.package.indexOf("@"),s=o>-1?e.package.slice(0,o):e.package,a=o>-1?e.package.slice(o+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??s}),(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:s}),(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)(sb,{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?`✓ ${l("i18n.installed")}`:i?l("i18n.installing"):l("i18n.install")})]},e.package)})})]})}function lu(e){let{cwd:t,onClose:n,embedded:o=!1,trust:s}=e,{t:l}=(0,E.s)(),[a,d]=(0,i.useState)([]),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(()=>oU("skills",t)),[g,x]=(0,i.useState)(new Set),[v,b]=(0,i.useState)(null),[y,j]=(0,i.useState)(null),[k,w]=(0,i.useState)(null),[S,C]=(0,i.useState)(!1),[N,I]=(0,i.useState)({}),[$,T]=(0,i.useState)(new Set),[M,R]=(0,i.useState)(!1),[L,z]=(0,i.useState)(null),[A,W]=(0,i.useState)(null),[P,O]=(0,i.useState)(!0),F=(0,i.useCallback)(async()=>{u(!0),h(null);try{let e=await fetch(`/api/skills?cwd=${encodeURIComponent(t)}`),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);let r=n.skills??[];return d(r),O(n.projectResourcesLoaded??!0),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)(()=>{I({}),W(null),F()},[t]);let B=li(s),D=(0,i.useRef)(B);(0,i.useEffect)(()=>{D.current!==B&&(D.current=B,F())},[B,F]),(0,i.useEffect)(()=>{f&&oq("skills",f,t)},[t,f]);let H=(0,i.useCallback)(async e=>{let n=(e?[e]:a.filter(e=>!!e.install)).map(ll).filter(e=>!!e);if(0!==n.length){W(null),T(e=>new Set([...e,...n])),e||R(!0);try{let n=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,package:e?.install?.package,scope:e?.install?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);I(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){W(e instanceof Error?e.message:String(e))}finally{T(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),e||R(!1)}}},[t,a]),_=(0,i.useCallback)(async e=>{if(!e.install)return;let n=ll(e);z(n),W(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 F();let o=i.skill?.install?.versionHash;I(t=>({...t,[n]:{package:e.install.package,scope:e.install.scope,state:"up-to-date",currentVersion:o,latestVersion:o}}))}catch(e){W(e instanceof Error?e.message:String(e))}finally{z(null)}},[t,F]),U=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;x(t=>new Set(t).add(e.filePath)),b(null),w(null);try{let n=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),r=await n.json();if(!n.ok||r.error)return void b(r.error??`HTTP ${n.status}`);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})}},[]),q=(0,i.useCallback)(async(e,t,n)=>{let r=lr(t,n,e=>!e.disableModelInvocation);if(0===r.length)return;let i=r.map(e=>e.filePath),o=!n;x(e=>new Set([...e,...i])),j(e),b(null),w(null);try{let t=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePaths:i,disableModelInvocation:o})}),n=await t.json();if(!t.ok||n.error||!n.results)throw Error(n.error??`HTTP ${t.status}`);let s=n.results;d(e=>{let t;return t=new Set(s.filter(e=>!e.error).map(e=>e.filePath)),e.map(e=>t.has(e.filePath)?{...e,disableModelInvocation:o}:e)});let a=s.filter(e=>e.error);if(a.length>0){let t=new Map(r.map(e=>[e.filePath,e.name]));w({group:e,error:[l("skills.bulkFailed",{count:a.length,total:s.length}),...a.map(e=>`${t.get(e.filePath)??e.filePath}: ${e.error}`)].join("\n")})}}catch(t){w({group:e,error:t instanceof Error?t.message:String(t)})}finally{j(null),x(e=>{let t=new Set(e);for(let e of i)t.delete(e);return t})}},[l]),Z=a.find(e=>e.filePath===f)??null,K=c||g.size>0||null!==L;return(0,r.jsxs)(o0,{embedded:o,title:l("common.skills"),subtitle:lt(t),closeLabel:l("i18n.close"),onClose:n,children:[!P&&(0,r.jsx)(sf,{message:l("trust.skillsNotLoaded")}),(0,r.jsxs)(o1,{children:[(0,r.jsxs)(o2,{children:[(0,r.jsx)(o4,{children:c?(0,r.jsx)("div",{className:"config-sidebar-message",children:l("i18n.loading")}):p?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:p}):0===a.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:l("i18n.noSkills")}):(()=>{let e=[],t={project:l("skills.scope.project"),global:l("skills.scope.global"),path:l("skills.scope.path")};for(let{label:n,matches:r}of[{label:`${t.project} / skills.sh`,matches:e=>"project"===lo(e)&&!!e.install?.skillsShUrl},{label:t.project,matches:e=>"project"===lo(e)&&!e.install?.skillsShUrl},{label:`${t.global} / skills.sh`,matches:e=>"global"===lo(e)&&!!e.install?.skillsShUrl},{label:t.global,matches:e=>"global"===lo(e)&&!e.install?.skillsShUrl},{label:t.path,matches:e=>"path"===lo(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,o=e.disableModelInvocation;return(0,r.jsxs)(o6,{active:i,onClick:()=>{m(e.filePath),C(!1)},children:[(0,r.jsx)(sk,{active:!o}),(0,r.jsx)(o9,{className:`is-grow${o?" is-muted":""}`,children:e.name}),(n=(t=ll(e))?N[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:l("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"}))]},e.filePath)};return e.map(e=>{let{label:t,skills:i}=e,o=i.filter(e=>!e.disableModelInvocation).length,s=o===i.length;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(o8,{aside:(0,r.jsx)(o3,{enabled:o,total:i.length,disabled:K,loading:y===t,label:l(s?"skills.groupSwitchOn":"skills.groupSwitchOff",{group:t}),onChange:e=>void q(t,i,e)}),children:t}),k?.group===t&&(0,r.jsx)(o5,{error:k.error}),[...i.filter(e=>!e.disableModelInvocation),...i.filter(e=>e.disableModelInvocation)].map(n)]},t)})})()}),(0,r.jsx)(sj,{onClick:()=>C(!0),active:S,children:l("i18n.addSkill")})]}),(0,r.jsx)(sg,{children:(0,r.jsx)(o7,{className:"is-fill",children:S?(0,r.jsx)(lc,{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:()=>{F()}}):c?null:Z?(0,r.jsx)(ld,{skill:Z,cwd:t,onToggle:U,toggling:g.has(Z.filePath),saveError:v,updateStatus:ll(Z)?N[ll(Z)]:void 0,checkingUpdate:!!ll(Z)&&$.has(ll(Z)),updating:L===ll(Z),updateError:A,onCheckUpdate:()=>void H(Z),onUpdate:()=>void _(Z)},Z.filePath):(0,r.jsx)(sm,{children:l("i18n.selectSkill")})})})]}),(0,r.jsxs)(sx,{status:Object.values(N).filter(e=>"update-available"===e.state).length>0&&(0,r.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(N).filter(e=>"update-available"===e.state).length," ",1===Object.values(N).filter(e=>"update-available"===e.state).length?l("i18n.update"):l("i18n.updates")]}),children:[!o&&(0,r.jsx)(sb,{onClick:n,children:l("i18n.close")}),a.some(e=>!!e.install)&&(0,r.jsx)(sb,{variant:"secondary",onClick:()=>void H(),disabled:M||null!==L,children:M?l("i18n.checking"):l("i18n.checkUpdates")})]})]})}let lp={builtin:0,global:1,workspace:2,project:3},lh=["read","bash","edit","write","grep","find","ls"],lf=["","off","minimal","low","medium","high","xhigh","max"],lm={name:"custom-agent",displayName:"Custom agent",description:"",systemPrompt:"",tools:["read","bash","edit","write","grep","find","ls"],loadSkills:!1,loadExtensions:!1,promptMode:"append",inheritContext:!1,runInBackground:!1,enabled:!0},lg={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"},lx={background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"default"};function lv(e){return{name:e.name,displayName:e.displayName,description:e.description,systemPrompt:e.systemPrompt,tools:[...e.tools],loadSkills:e.loadSkills,loadExtensions:e.loadExtensions,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 lb(e){return`${e.scope}:${e.name}`}function ly(e){return"global"===e||"project"===e}function lj(e){return ly(e)||"builtin"===e}function lk(e){let{label:t,children:n}=e;return(0,r.jsx)(so,{label:t,children:n})}function lw(e){let{checked:t,disabled:n,label:i,onChange:o}=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=>o(e.target.checked)}),i]})}function lS(e){let{cwd:t,sessionId:n=null,onClose:o,onReloaded:s,embedded:l=!1,trust:a}=e,d=ew(),{t:c}=(0,E.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)(()=>oU("agents",t)),[j,k]=(0,i.useState)(lm),[w,S]=(0,i.useState)("view"),[C,N]=(0,i.useState)("global"),[I,$]=(0,i.useState)(!0),[T,M]=(0,i.useState)(!1),[R,L]=(0,i.useState)(!1),[z,A]=(0,i.useState)(!1),[W,P]=(0,i.useState)(null),[O,F]=(0,i.useState)(!1),[B,D]=(0,i.useState)(10),[H,_]=(0,i.useState)(!0),[U,q]=(0,i.useState)(!1),[Z,K]=(0,i.useState)(null),[V,J]=(0,i.useState)(!1),[Y,G]=(0,i.useState)(!1),X=(0,i.useMemo)(()=>u.find(e=>lb(e)===b)??null,[u,b]),Q=(0,i.useMemo)(()=>h.map(e=>({provider:e.provider,modelId:e.id,name:e.name})),[h]),ee=(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 o=e??oU("agents",t),s=i.find(e=>lb(e)===o)??i.find(e=>"project"===e.scope)??i.find(e=>"global"===e.scope)??i[0]??null;y(s?lb(s):null),s&&(k(lv(s)),S(ly(s.scope)?"edit":"view"),ly(s.scope)&&N(s.scope))}catch(e){P(e instanceof Error?e.message:String(e))}finally{$(!1)}},[t]);(0,i.useEffect)(()=>{ee()},[ee]),(0,i.useEffect)(()=>{let e=new AbortController;return _(!0),K(null),(async()=>{try{let t=await fetch("/api/subagents/settings",{cache:"no-store",signal:e.signal}),n=await t.json();if(!t.ok||n.error||"boolean"!=typeof n.enabled)throw Error(n.error??`HTTP ${t.status}`);F(n.enabled),"number"==typeof n.maxConcurrent&&D(n.maxConcurrent)}catch(t){if(e.signal.aborted)return;K(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||_(!1)}})(),()=>e.abort()},[]),(0,i.useEffect)(()=>{b&&oq("agents",b,t)},[t,b]);let et=li(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,et]);let en=async()=>{M(!0),P(null),L(!1);try{let e=await fetch("/api/subagents/profiles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:C,profile:j})}),n=await e.json();if(!e.ok||n.error||!n.profile)throw Error(n.error??`HTTP ${e.status}`);await ee(lb(n.profile)),L(!0),setTimeout(()=>L(!1),2e3)}catch(e){P(e instanceof Error?e.message:String(e))}finally{M(!1)}},er=async()=>{if(X&&ly(X.scope)&&window.confirm(c("agents.deleteConfirm",{name:X.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:X.scope,name:X.name})}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);await ee()}catch(e){P(e instanceof Error?e.message:String(e))}finally{M(!1)}}},ei="view"!==w,eo="create"===w,es=!ei||T||z,el=eo?C:X?.scope,ea=eo?"global"===C?`~/.pi/agent/agents/${j.name||"..."}.md`:`./.pi/agents/${j.name||"..."}.md`:X?(X.filePath?"project"===X.scope||"workspace"===X.scope?ln(X.filePath,t):lt(X.filePath):null)??c("agents.builtinPath"):"",ed=eo?ea:X?.filePath??ea,ec=!j.model||h.some(e=>`${e.provider}/${e.id}`===j.model),eu=(()=>{if(!j.model)return null;let e=j.model.indexOf("/");return e<0?{provider:"",modelId:j.model}:{provider:j.model.slice(0,e),modelId:j.model.slice(e+1)}})(),ep=es?{...lg,...lx}:lg,eh=eo?es:!X||!lj(X.scope)||T||z,ef=(e,t)=>{k(n=>({...n,[e]:t}))},em=async e=>{if(eo)return void ef("enabled",e);if(X&&lj(X.scope)){A(!0),P(null);try{let n=await fetch("/api/subagents/profiles",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:X.scope,name:X.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=>lb(e)===lb(i)?i:e)),k(e=>({...e,enabled:i.enabled}))}catch(e){P(e instanceof Error?e.message:String(e))}finally{A(!1)}}},eg=async e=>{q(!0),K(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),r=await t.json();if(!t.ok||r.error||"boolean"!=typeof r.enabled)throw Error(r.error??`HTTP ${t.status}`);F(r.enabled),J(!!n)}catch(e){K(e instanceof Error?e.message:String(e))}finally{q(!1)}},ex=async e=>{D(e),K(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxConcurrent:e})}),n=await t.json();if(!t.ok||n.error||"number"!=typeof n.maxConcurrent)throw Error(n.error??`HTTP ${t.status}`);D(n.maxConcurrent)}catch(e){K(e instanceof Error?e.message:String(e))}},ev=async()=>{if(n){G(!0),K(null);try{await iT(n,{type:"reload"}),J(!1),s?.()}catch(e){K(e instanceof Error?e.message:String(e))}finally{G(!1)}}};return(0,r.jsxs)(o0,{embedded:l,title:c("common.agents"),subtitle:lt(t),closeLabel:c("agents.close"),onClose:o,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)(sb,{size:"small",onClick:()=>void ev(),disabled:Y||U,children:Y?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:B,disabled:H||U,onChange:e=>D(Number(e.target.value)),onBlur:()=>void ex(B)})]}),(0,r.jsx)(sy,{checked:O,disabled:H||Y,loading:U,label:c("agents.builtInTitle"),onChange:e=>void eg(e)})]})]}),(0,r.jsxs)(o1,{children:[(0,r.jsxs)(o2,{children:[(0,r.jsx)(o4,{children:I?(0,r.jsx)("div",{style:{padding:10,color:"var(--text-dim)",fontSize:12},children:c("agents.loading")}):["project","global","workspace","builtin"].map(e=>{let t=u.filter(t=>t.scope===e);return 0===t.length?null:(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(o8,{children:c(`agents.scope.${e}`)}),t.map(e=>{let t,n,i=(t=e.name.toLowerCase(),n=lp[e.scope],u.some(e=>e.name.toLowerCase()===t&&lp[e.scope]>n));return(0,r.jsxs)(o6,{active:b===lb(e)&&!eo,onClick:()=>{y(lb(e)),k(lv(e)),S(ly(e.scope)?"edit":"view"),ly(e.scope)&&N(e.scope),P(null)},children:[(0,r.jsx)(sk,{active:e.enabled}),(0,r.jsx)(o9,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.displayName}),i&&(0,r.jsx)("span",{className:"agents-overridden-label",children:c("agents.overridden")})]},lb(e))})]},e)})}),(0,r.jsx)(sj,{active:eo,onClick:()=>{let e="custom-agent",t=2;for(;u.some(t=>t.name===e);)e=`custom-agent-${t++}`;y(null),k({...lm,name:e,displayName:e}),S("create"),N("global"),P(null)},children:c("agents.new")})]}),(0,r.jsx)(sg,{children:(0,r.jsx)(o7,{className:"is-fill",children:X||eo?(0,r.jsxs)(o7,{children:[(0,r.jsxs)(se,{children:[(0,r.jsx)(st,{children:eo?(0,r.jsx)(sc,{value:C,label:c("config.saveTo"),options:["global","project"].map(e=>({value:e,label:c(`agents.scope.${e}`),disabled:T})),path:ea,onChange:N}):(0,r.jsxs)(r.Fragment,{children:[el&&(0,r.jsx)(sa,{scope:el,children:c(`agents.scope.${el}`)}),(0,r.jsx)("span",{title:ed,className:"config-detail-path",children:ea})]})}),(0,r.jsxs)(sn,{children:[X&&("view"===w||"edit"===w)&&(0,r.jsx)(sb,{size:"small",onClick:()=>{if(!X)return;let e=function(e,t){let n=new Set(t.map(e=>e.name.toLowerCase())),r=`${e}-copy`,i=r,o=2;for(;n.has(i.toLowerCase());)i=`${r}-${o++}`;return i}(X.name,u);y(null),k({...lv(X),name:e,displayName:c("agents.copyName",{name:X.displayName})}),S("create"),N(ly(X.scope)?X.scope:"global"),P(null)},disabled:T||z,children:c("agents.duplicate")}),X&&ly(X.scope)&&"edit"===w&&(0,r.jsx)(sb,{variant:"danger",size:"small",onClick:()=>void er(),disabled:T||z,children:c("agents.delete")}),(0,r.jsx)(sy,{checked:j.enabled,disabled:eh,label:j.enabled?c("agents.disable"):c("agents.enable"),onChange:e=>void em(e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:d?"1fr":"minmax(0, 1fr) minmax(0, 1fr)",gap:12},children:[(0,r.jsx)(lk,{label:c("agents.name"),children:eo?(0,r.jsx)("input",{"aria-label":c("agents.name"),value:j.name,disabled:es,onChange:e=>ef("name",e.target.value),style:lg}):(0,r.jsx)("code",{style:{minHeight:34,display:"flex",alignItems:"center",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:j.name})}),(0,r.jsx)(lk,{label:c("agents.displayName"),children:(0,r.jsx)("input",{"aria-label":c("agents.displayName"),value:j.displayName,disabled:es,onChange:e=>ef("displayName",e.target.value),style:ep})})]}),(0,r.jsx)(lk,{label:c("agents.description"),children:(0,r.jsx)("input",{"aria-label":c("agents.description"),value:j.description,disabled:es,onChange:e=>ef("description",e.target.value),style:ep})}),(0,r.jsx)(lk,{label:c("agents.prompt"),children:(0,r.jsx)("textarea",{className:"agents-system-prompt","aria-label":c("agents.prompt"),value:j.systemPrompt,disabled:es,onChange:e=>ef("systemPrompt",e.target.value),style:{...ep,height:195,minHeight:195,maxHeight:"60vh",padding:9,overflow:"auto",resize:es?"none":"vertical",lineHeight:1.5}})}),(0,r.jsx)(lk,{label:c("agents.tools"),children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 16px"},children:lh.map(e=>(0,r.jsx)(lw,{label:e,disabled:es,checked:j.tools.includes(e),onChange:t=>ef("tools",t?[...j.tools,e]:j.tools.filter(t=>t!==e))},e))})}),(0,r.jsx)(lk,{label:c("agents.resources"),children:(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 20px"},children:[(0,r.jsx)(lw,{label:c("agents.loadSkills"),disabled:es,checked:j.loadSkills,onChange:e=>ef("loadSkills",e)}),(0,r.jsx)(lw,{label:c("agents.loadExtensions"),disabled:es,checked:j.loadExtensions,onChange:e=>ef("loadExtensions",e)})]})}),(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)(lk,{label:c("agents.model"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(rq,{options:Q,value:eu,onChange:(e,t)=>ef("model",`${e}/${t}`),onClear:()=>ef("model",void 0),emptyLabel:m?c("agents.modelsLoading"):c("agents.inherit"),selectedLabel:j.model&&!ec?c("agents.modelUnavailable",{model:j.model}):void 0,disabled:es||m||0===h.length&&!j.model,ariaLabel:c("agents.model"),variant:"field",placement:"auto"}),x&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:10},children:x})]})}),(0,r.jsx)(lk,{label:c("agents.thinking"),children:(0,r.jsx)("select",{"aria-label":c("agents.thinking"),value:j.thinking??"",disabled:es,onChange:e=>ef("thinking",e.target.value||void 0),style:ep,children:lf.map(e=>(0,r.jsx)("option",{value:e,children:e||c("agents.inherit")},e||"default"))})}),(0,r.jsx)(lk,{label:c("agents.maxTurns"),children:(0,r.jsx)("input",{"aria-label":c("agents.maxTurns"),type:"number",min:1,value:j.maxTurns??"",disabled:es,onChange:e=>ef("maxTurns",e.target.value?Number(e.target.value):void 0),style:ep})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"10px 20px"},children:[(0,r.jsx)(lw,{label:c("agents.inheritContext"),disabled:es,checked:j.inheritContext,onChange:e=>ef("inheritContext",e)}),(0,r.jsx)(lw,{label:c("agents.background"),disabled:es,checked:j.runInBackground,onChange:e=>ef("runInBackground",e)})]})]}):(0,r.jsx)(sm,{children:c("agents.empty")})})})]}),(0,r.jsx)(sx,{status:(Z||W)&&(0,r.jsx)("span",{role:"alert",style:{color:"#ef4444"},children:Z||W}),children:ei&&(0,r.jsxs)(sb,{variant:"primary",onClick:()=>void en(),disabled:T||R||z||!j.name.trim(),className:R?"is-success":void 0,children:[R&&(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:R?c("i18n.saved"):T?c("agents.saving"):c("agents.save")})]})})]})}let lC=["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"];function lE(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function lN(e){return`${e.scope}\0${e.source}`}function lI(e){return`extension\0${e.path}`}function l$(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function lT(e,t){return t(`plugins.status.${e}`)}function lM(e){return`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`}function lR(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function lL(e){let{pkg:t}=e,{t:n}=(0,E.s)(),i=[["extension",n("i18n.extensions")],["skill",n("i18n.skills")],["prompt",n("i18n.prompts")],["theme",n("i18n.themes")]].map(e=>{let[n,r]=e;return{kind:n,label:r,resources:t.resources.filter(e=>e.kind===n)}}).filter(e=>e.resources.length>0);return 0===i.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:n(t.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:i.map((e,t)=>(0,r.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function lz(e){let{cwd:t,source:n,scope:i,projectResourcesLoaded:o,busy:s,actionError:l,onSourceChange:a,onScopeChange:d,onInstall:c}=e,{t:u}=(0,E.s)();return(0,r.jsx)(sp,{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)(sc,{value:i,label:u("config.saveTo"),options:[{value:"global",label:l$("global",u)},{value:"project",label:l$("project",u),disabled:!o}],path:"project"===i?`${lt(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:!s&&!!n.trim(),normalizeValue:lE,onValueChange:a,onSubmit:c,examplesLabel:u("config.examples"),examples:lC,error:l,children:(0,r.jsx)(sb,{variant:"primary",onClick:c,disabled:s||!n.trim(),className:"is-pushed-right",children:u(s?"i18n.installing":"i18n.install")})})}function lA(e){let t,{pkg:n,cwd:o,busyKey:s,actionError:l,actionMessage:a,sessionId:d,updateStatus:c,checkingUpdate:u,updateError:p,onAction:h,onCheckUpdate:f,onReloadSession:m}=e,{t:g}=(0,E.s)(),x=lN(n),v=(s?.endsWith(x)||s?.startsWith("bulk:"))??!1,b="reload"===s,y=!n.disabled,j=n.canCheckForUpdates,k=c?.state==="update-available",w=n.description?.trim(),S=(0,i.useId)();return(0,r.jsxs)(o7,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(se,{className:"is-top-aligned",children:[(0,r.jsxs)(st,{children:[(0,r.jsx)(sa,{scope:n.scope,children:l$(n.scope,g)}),n.disabled?(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:g("i18n.disabled")}):n.filtered&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:g("i18n.filtered")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.source})]}),(0,r.jsxs)(sn,{children:[(0,r.jsx)(sb,{size:"small",variant:k?"primary":void 0,onClick:k||!j?()=>h("update",n):f,disabled:v||b||u,title:k?g("i18n.updateAvailable"):void 0,children:g(s===`update:${x}`?"i18n.updating":u?"i18n.checking":k||!j?"i18n.update":"i18n.check")}),(0,r.jsx)(sb,{size:"small",onClick:m,disabled:!d||b||v,"aria-describedby":d?void 0:S,children:g(b?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)(sb,{variant:"danger",size:"small",onClick:()=>h("remove",n),disabled:v||b,children:g(s===`remove:${x}`?"i18n.removing":"i18n.remove")}),(0,r.jsx)(sy,{checked:y,loading:v||b,onChange:()=>h(n.disabled?"enable":"disable",n),label:g(n.disabled?"i18n.enablePackage":"i18n.disablePackage")})]})]}),!d&&(0,r.jsx)("div",{id:S,className:"config-detail-heading-note",children:g("i18n.openSessionToReload")})]}),(0,r.jsxs)(ss,{children:[w&&(0,r.jsx)(sl,{label:g("i18n.description"),children:w}),(0,r.jsx)(sl,{label:g("i18n.status"),tone:"plain",style:{color:lR(n.status),textTransform:"capitalize"},children:lT(n.status,g)}),(0,r.jsxs)(sl,{label:g("i18n.version"),tone:"plain",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:(t=[],n.version&&t.push(g("i18n.installedVersion",{version:n.version})),n.configuredVersion&&t.push(g("i18n.configuredVersion",{version:n.configuredVersion})),t.length?t.join(" \xb7 "):g("i18n.unknown"))}),k&&(0,r.jsx)("span",{className:"skill-version-value is-update",title:c.displayName,children:g("i18n.updateAvailable")}),j&&(u||c&&!k)&&(0,r.jsx)("span",{className:`skill-update-status ${u?"is-checking":c?.state==="up-to-date"?"is-success":c?.state==="error"?"is-error":"is-muted"}`,children:u?g("i18n.checking"):c?.state==="up-to-date"?g("i18n.upToDate"):c?.state==="unsupported"?g("i18n.automaticChecksUnavailable"):c?.message||g("i18n.checkFailed")})]}),p&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:p})]}),(0,r.jsx)(sl,{label:g("i18n.package"),mono:!0,children:n.packageName??g("i18n.unknown")}),(0,r.jsx)(sl,{label:g("i18n.resources"),children:function(e,t){if(e.disabled)return t("i18n.disabled");let n=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t("i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t("i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t("i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t("i18n.themeShort")}):""].filter(Boolean);return n.length?n.join(" \xb7 "):t("i18n.noResources")}(n,g)}),(0,r.jsx)(sl,{label:g("i18n.installedPath"),tone:n.installedPath?"muted":"error",mono:!0,children:n.installedPath?lt(n.installedPath):g("i18n.notFound")}),(0,r.jsx)(sl,{label:g("i18n.cwd"),tone:"dim",mono:!0,children:lt(o)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)(si,{children:g("i18n.resolvedResources")}),(0,r.jsx)(lL,{pkg:n})]}),a&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:a}),l&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:l})]})}function lW(e){let{extension:t}=e,{t:n}=(0,E.s)(),i=t.enabled?"loaded":"disabled";return(0,r.jsxs)(o7,{children:[(0,r.jsx)(se,{children:(0,r.jsxs)(st,{children:[(0,r.jsx)(sa,{scope:t.scope,children:l$(t.scope,n)}),(0,r.jsx)(sr,{children:t.name})]})}),(0,r.jsxs)(ss,{children:[(0,r.jsx)(sl,{label:n("i18n.status"),tone:"plain",style:{color:t.enabled?"var(--accent)":"var(--text-dim)"},children:lT(i,n)}),(0,r.jsx)(sl,{label:n("i18n.installedPath"),mono:!0,children:lt(t.path)})]})]})}function lP(e){var t;let{cwd:n,sessionId:o,onClose:s,onReloaded:l,embedded:a=!1,trust:d}=e,{t:c}=(0,E.s)(),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!0),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(()=>oU("plugins",n)),[b,y]=(0,i.useState)(!1),[j,k]=(0,i.useState)(""),[w,S]=(0,i.useState)("global"),[C,N]=(0,i.useState)(null),[I,$]=(0,i.useState)(null),[T,M]=(0,i.useState)(null),[R,L]=(0,i.useState)(null),[z,A]=(0,i.useState)({}),[W,P]=(0,i.useState)(new Set),[O,F]=(0,i.useState)(!1),[B,D]=(0,i.useState)(null),[H,_]=(0,i.useState)(!1),U=(0,i.useMemo)(()=>u?.packages??[],[u?.packages]),q=(0,i.useMemo)(()=>u?.standaloneExtensions??[],[u?.standaloneExtensions]),Z=U.find(e=>lN(e)===x)??null,K=q.find(e=>lI(e)===x)??null,V=u?.projectResourcesLoaded??!0,J=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:U.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[U]),Y=(0,i.useCallback)(async()=>{f(!0),g(null),L(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=>lN(t)===e)||t.standaloneExtensions.some(t=>lI(t)===e))?e:t.packages[0]?lN(t.packages[0]):t.standaloneExtensions[0]?lI(t.standaloneExtensions[0]):null)}catch(e){g(e instanceof Error?e.message:String(e))}finally{f(!1)}},[n]);(0,i.useEffect)(()=>{A({}),D(null),Y()},[n]);let G=li(d),X=(0,i.useRef)(G);(0,i.useEffect)(()=>{X.current!==G&&(X.current=G,Y())},[G,Y]),(0,i.useEffect)(()=>{x&&oq("plugins",x,n)},[n,x]);let Q=(0,i.useCallback)(async e=>{let t=(e?[e]:U.filter(e=>e.canCheckForUpdates)).map(lN);if(0!==t.length){D(null),P(e=>new Set([...e,...t])),e||F(!0);try{let t=await fetch("/api/plugins/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n,source:e?.source,scope:e?.scope})}),r=await t.json();if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);A(e=>{let t={...e};for(let e of r.updates??[])t[lN(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||F(!1)}}},[n,U]),ee=(0,i.useCallback)(async()=>{_(!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),A({}),M(c("i18n.packagesUpdated")),o&&M(`${c("i18n.packagesUpdated")} ${c("agents.reloadRequired")}`)}catch(e){$(e instanceof Error?e.message:String(e))}finally{_(!1)}},[n,o,c]),et=(0,i.useCallback)(async(e,t)=>{let r=lN(t);N(`${e}:${r}`),$(null),M(null),L(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})}),o=await i.json();if(!i.ok||o.error)throw Error(o.error??`HTTP ${i.status}`);if(p(o),"remove"===e)v(o.packages[0]?lN(o.packages[0]):o.standaloneExtensions[0]?lI(o.standaloneExtensions[0]):null),0===o.packages.length&&0===o.standaloneExtensions.length&&y(!0),M(c("i18n.packageRemoved")),A(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&&A(e=>{let t={...e};return delete t[r],t})}}catch(e){$(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,c]),en=(0,i.useCallback)(async(e,t,r)=>{let i=lr(t,r,e=>!e.disabled,e=>e.filtered),s=r?0:t.filter(e=>!e.disabled&&e.filtered).length,l=s>0?c("plugins.bulkKeptFiltered",{count:s}):void 0;if($(null),M(null),L(l?{scope:e,note:l}: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}})})}),s=await t.json();if(!t.ok||s.error||!s.results)throw Error(s.error??`HTTP ${t.status}`);let{results:d,...u}=s;p(u);let h=d.filter(e=>e.error);if(h.length<d.length){let e=r?c("plugins.bulkEnabled"):c("plugins.bulkDisabled");M(o?`${e} ${c("agents.reloadRequired")}`:e)}h.length>0&&L({scope:e,note:l,error:[c("plugins.bulkFailed",{count:h.length,total:d.length}),...h.map(e=>`${e.source}: ${e.error}`)].join("\n")})}catch(t){L({scope:e,note:l,error:t instanceof Error?t.message:String(t)})}finally{N(null)}},[n,o,c]),er=(0,i.useCallback)(async()=>{let e=lE(j).trim();if(!e)return;k(e);let t=`${w}\0${e}`;N(`install:${t}`),$(null),M(null),L(null);try{var r;let i,o,s=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:e,scope:w,cwd:n})}),l=await s.json();if(!s.ok||l.error)throw Error(l.error??`HTTP ${s.status}`);p(l);let a=(r=l.packages,o=(i=e.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===w&&e.source===i)??r.find(e=>e.scope===w&&e.source===`npm:${o}`)??r.find(e=>e.scope===w&&e.source.endsWith(i)));v(a?lN(a):t),y(!1),k(""),M(c("i18n.packageInstalled"))}catch(e){$(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,w,j,c]),ei=(0,i.useCallback)(async()=>{if(o){N("reload"),$(null),M(null),L(null);try{await iT(o,{type:"reload"}),l?.(),await Y(),M(c("i18n.sessionReloaded"))}catch(e){$(e instanceof Error?e.message:String(e))}finally{N(null)}}},[Y,l,o,c]),eo=C?.startsWith("install:")??!1,es=Object.values(z).filter(e=>"update-available"===e.state).length,el=U.some(e=>e.canCheckForUpdates),ea=h||null!==C||W.size>0||H;return(0,r.jsxs)(o0,{embedded:a,title:c("common.plugins"),subtitle:lt(n),closeLabel:c("i18n.close"),onClose:s,children:[!V&&(0,r.jsx)(sf,{message:c("trust.pluginsNotLoaded")}),(0,r.jsxs)(o1,{children:[(0,r.jsxs)(o2,{children:[(0,r.jsx)(o4,{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===U.length&&0===q.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:c("i18n.noPlugins")}):(0,r.jsxs)(r.Fragment,{children:[q.length>0&&(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(o8,{children:c("i18n.extensions")}),q.map(e=>{let t=lI(e);return(0,r.jsxs)(o6,{active:!b&&x===t,title:e.path,onClick:()=>{v(t),y(!1),$(null),M(null)},children:[(0,r.jsx)(sk,{active:e.enabled}),(0,r.jsx)(o9,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.name})]},t)})]}),J.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)(o8,{aside:(0,r.jsx)(o3,{enabled:t,total:e.packages.length,disabled:ea,loading:C===`bulk:${e.scope}`,label:c(n?"plugins.groupSwitchOn":"plugins.groupSwitchOff",{group:l$(e.scope,c)}),onChange:t=>void en(e.scope,e.packages,t)}),children:l$(e.scope,c)}),R?.scope===e.scope&&(0,r.jsx)(o5,{error:R.error,note:R.note}),e.packages.map(e=>{let t=lN(e),n=!b&&x===t;return(0,r.jsxs)(o6,{active:n,title:e.description??e.source,onClick:()=>{v(t),y(!1),$(null),M(null)},children:[(0,r.jsx)(sk,{active:!e.disabled,color:lR(e.status)}),(0,r.jsx)(o9,{className:`is-grow${e.disabled?" is-muted":""}`,children:e.source}),z[lN(e)]?.state==="update-available"&&(0,r.jsx)("span",{title:c("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"})]},t)})]},e.scope)})]})}),(0,r.jsx)(sj,{active:b,onClick:()=>{y(!0),$(null),M(null)},children:c("i18n.addPlugin")})]}),(0,r.jsx)(sg,{children:(0,r.jsx)(o7,{className:"is-fill",children:b?(0,r.jsx)(lz,{cwd:n,source:j,scope:w,projectResourcesLoaded:V,busy:eo,actionError:I,onSourceChange:k,onScopeChange:S,onInstall:er}):h?null:K?(0,r.jsx)(lW,{extension:K}):Z?(0,r.jsx)(lA,{pkg:Z,cwd:n,busyKey:C,actionError:I,actionMessage:T,sessionId:o,updateStatus:z[lN(Z)],checkingUpdate:W.has(lN(Z)),updateError:B,onAction:et,onCheckUpdate:()=>void Q(Z),onReloadSession:ei},lN(Z)):(0,r.jsx)(sm,{children:c("i18n.selectPackage")})})})]}),(0,r.jsxs)(sx,{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)(sv,{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(lM)}):(0,r.jsx)(sv,{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)(sb,{onClick:s,children:c("i18n.close")}),el&&(0,r.jsx)(sb,{variant:es>0?"primary":"secondary",onClick:()=>void(es>0?ee():Q()),disabled:ea,title:es>0?c("i18n.updateAllPluginsHint"):void 0,children:H?c("i18n.updating"):O?c("i18n.checking"):es>0?`${c("i18n.updateAllPlugins")} (${es})`:c("i18n.checkUpdates")}),(0,r.jsx)(sb,{variant:"secondary",onClick:()=>void Y(),disabled:ea,children:c("i18n.refresh")})]})]})}let lO={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} 則訊息"}};function lF(e,t){return e.replace(/\{(\w+)\}/g,(e,n)=>void 0===t[n]?e:String(t[n]))}function lB(e){let t=e.replace(/[\\/]+$/,""),n=t.split(/[\\/]/);return n[n.length-1]||t}function lD(e){var t;let n,{onClose:o,embedded:s=!1}=e,{locale:l}=(0,E.s)(),a=lO[l]??lO.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),[j,k]=(0,i.useState)(""),[w,N]=(0,i.useState)(null),I=(0,i.useCallback)(async()=>{g(!1);try{let[e,t,n]=await Promise.all([fetch("/api/archives",{cache:"no-store"}),fetch("/api/sessions",{cache:"no-store"}),fetch("/api/home",{cache:"no-store"})]);if(!e.ok||!t.ok)throw Error("load failed");let r=ez(await e.json()),i=await t.json(),o=Array.isArray(i.sessions)?i.sessions:[],s=await n.json().catch(()=>({}));"string"==typeof s.home&&f(s.home);let l=eL(r),a=[];for(let e of l){let t=S(o,e).filter(e=>e.relation?.kind!=="subagent").sort((e,t)=>t.modified.localeCompare(e.modified));a.push({key:e,root:t[0]?.projectRoot??t[0]?.cwd??e,modified:t[0]?.modified??"",sessions:t})}a.sort((e,t)=>t.modified.localeCompare(e.modified)),c(a),p(e=>e&&a.some(t=>t.key===e)?e:a[0]?.key??null)}catch{g(!0)}},[]);(0,i.useEffect)(()=>{I()},[I]);let $=d.find(e=>e.key===u)??null,T=async e=>{v(!0),N(null);try{if(!(await fetch("/api/archives",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e,archived:!1})})).ok)throw Error("unarchive failed");y(!1),k(""),c(t=>t.filter(t=>t.key!==e)),p(t=>t===e?null:t)}catch{N(a.loadFailed)}finally{v(!1)}},M=async e=>{v(!0),N(null);try{let t=await fetch("/api/archives/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectKey:e.key,confirm:j.trim()})}),n=await t.json().catch(()=>({}));if(409===t.status&&n.runningSessionIds?.length)return void N(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{N(a.deleteFailed)}finally{v(!1)}};return(0,r.jsx)(o0,{embedded:s,title:a.title,onClose:o,children:m?(0,r.jsx)(sm,{children:a.loadFailed}):0===d.length?(0,r.jsx)(sm,{children:a.empty}):(0,r.jsxs)(o1,{children:[(0,r.jsx)(o2,{children:(0,r.jsx)(o4,{children:d.map(e=>(0,r.jsx)(o6,{active:e.key===u,onClick:()=>{p(e.key),y(!1),k(""),N(null)},children:(0,r.jsx)(o9,{title:e.root,children:lB(e.root)})},e.key))})}),(0,r.jsx)(sg,{children:$?(0,r.jsxs)(o7,{children:[(0,r.jsxs)(se,{children:[(0,r.jsx)(st,{children:(0,r.jsx)(sr,{children:lB($.root)})}),(0,r.jsxs)(sn,{children:[(0,r.jsx)(sb,{variant:"secondary",size:"small",disabled:x,onClick:()=>void T($.key),children:x?a.busy:a.unarchive}),!b&&(0,r.jsx)(sb,{variant:"danger",size:"small",disabled:x||0===$.sessions.length,onClick:()=>{y(!0),k(""),N(null)},children:a.deleteSessions})]})]}),(0,r.jsx)(so,{label:a.path,children:(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",wordBreak:"break-all"},children:(t=$.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:lF(a.deleteConfirmLead,{count:$.sessions.length})}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:a.deleteConfirmHint}),(0,r.jsx)("input",{value:j,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)(sb,{variant:"danger",size:"small",disabled:x||"confirm"!==(n=j.trim().toLowerCase())&&"确认"!==n&&"確認"!==n,onClick:()=>void M($),children:x?a.busy:a.deleteSessions}),(0,r.jsx)(sb,{variant:"ghost",size:"small",disabled:x,onClick:()=>{y(!1),k("")},children:a.cancel})]})]}),(0,r.jsx)(si,{children:lF(a.sessions,{count:$.sessions.length})}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2,minHeight:0,overflowY:"auto"},children:$.sessions.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.jsx)("div",{style:{fontSize:12,fontWeight:500,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:t,children:t}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,fontSize:11,color:"var(--text-muted)"},children:[(0,r.jsx)("span",{children:(0,C.fw)(e.modified,l)}),(0,r.jsx)("span",{children:lF(a.messages,{count:e.messageCount})})]})]},e.id)})}),w&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:w})]}):(0,r.jsx)(sm,{children:a.empty})})]})})}let lH="\\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",l_=RegExp(`[${lH}]`,"gu"),lU=RegExp(`[${lH}]`,"u");function lq(e){return e.replace(l_,e=>{let t=e.codePointAt(0)??0;return`\\u{${t.toString(16).toUpperCase().padStart(4,"0")}}`})}let lZ=/[\s"'`$|&;<>()*?#~]/;function lK(e){let t=lU.test(e),n=lq(e);return""===n||t||lZ.test(n)?`"${n.replace(/"/g,'\\"')}"`:n}function lV(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return[e,...t].map(lK).join(" ")}function lJ(e){let t=void 0!==e.command?lV(e.command,e.args):void 0,n=void 0!==e.url?lq(e.url):void 0;return"http"===e.transport?n:"stdio"===e.transport?t:n??t}function lY(e){return[e.name,e.command,e.cwd,e.url,...e.args??[],...e.envNames,...e.headerNames].some(e=>void 0!==e&&lU.test(e))}function lG(e){return"oauth-client-secret"===e.kind?{key:"mcp.field.oauthClientSecret"}:{key:"env"===e.kind?"mcp.field.env":"mcp.field.header",params:{name:lq(e.name??"")}}}function lX(e){return"http"===e.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables"}function lQ(e){return e.flatMap(e=>{let{variables:t,...n}=e;return t.map(e=>({variable:e,field:n}))})}function l0(e,t){return"unparsable"===e.reason||"unreadable"===e.reason?lq(e.error):"link-outside"===e.reason?void 0===t?void 0:lq(t):void 0}let l1="codemode";function l2(e){return`${e.scope}\0${e.name}`}function l4(e){return e?.trust?.decision===!0}function l8(e,t){var n;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":t.mcpAvailable?e.status?"test"===(n=e.status).origin?n.state:void 0!==n.closedAt||"not-trusted"===n.state?"on":n.state:"on":"mcp-off":"not-trusted":"disabled"}let l3={invalid:"mcp.state.invalid","web-password":"mcp.state.web-password",disabled:"mcp.state.disabled","not-trusted":"mcp.state.not-trusted",replaced:"mcp.state.replaced","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"},l5={connected:"mcp.state.session.connected",failed:"mcp.state.session.failed"};function l6(e,t){return(t?.origin==="session"?l5[e]:void 0)??l3[e]}let l9={disabled:"mcp.server.disabled","not-trusted":"mcp.stateDetail.not-trusted",replaced:"mcp.server.shadowedByProject","mcp-off":"mcp.stateDetail.mcp-off",disconnected:"mcp.stateDetail.disconnected",conflict:"mcp.stateDetail.conflict"},l7={invalid:"mcp.stateShort.invalid","web-password":"mcp.stateShort.web-password",disabled:"mcp.stateShort.disabled","not-trusted":"mcp.stateShort.not-trusted",replaced:"mcp.stateShort.replaced","needs-auth":"mcp.stateShort.needs-auth",failed:"mcp.stateShort.failed",connecting:"mcp.stateShort.connecting",disconnected:"mcp.stateShort.disconnected",conflict:"mcp.stateShort.conflict"};function ae(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 at(e){return"on"===e?{active:!0}:"off"===e?{active:!1}:{color:"error"===e?"#ef4444":"#f59e0b"}}function an(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 ar={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"},ai={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"},ao={connecting:"off",connected:"on","needs-auth":"warning",failed:"error",disconnected:"warning",conflict:"error","not-trusted":"warning"},as={codemode:"mcp.exposure.codemode",deferred:"mcp.exposure.deferred",direct:"mcp.exposure.direct",hidden:"mcp.exposure.hidden"},al=["codemode","deferred","direct","hidden"],aa={codemode:"mcp.exposureShort.codemode",deferred:"mcp.exposureShort.deferred",direct:"mcp.exposureShort.direct",hidden:"mcp.exposureShort.hidden"};function ad(e){return"auto-enable-codemode-invalid"!==e.reason}function ac(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 au(e){return{enabled:e.filter(e=>e.enabled).length,total:e.length}}function ap(e,t){let n=e.flatMap(e=>e.servers.map(l2));return t===l1||null!==t&&n.includes(t)?t:n[0]??null}function ah(e){let t=e?.trust;return void 0!==t&&t.requiresTrust&&!t.trusted}function af(e){return e.projectOverride?.preference??e.preference}let am={always:"mcp.codemode.projectOverride.always",automatic:"mcp.codemode.projectOverride.automatic"},ag={on:"mcp.codemode.toolMode.onDescription",only:"mcp.codemode.toolMode.onlyDescription"},ax={on:"mcp.codemode.toolMode.projectOverride.on",only:"mcp.codemode.toolMode.projectOverride.only"},av={automatic:"mcp.codemode.automatic",always:"mcp.codemode.always",unavailable:"mcp.codemode.unavailable",unknown:"i18n.unknown"};function ab(e){return"unavailable"===e?"error":"unknown"===e?"off":"on"}let ay=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e);function aj(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}:{},...ay(n.names)?{names:n.names}:{},...ay(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 ak(e,t,n,r){let i,{abortAtDeadline:o=!0}=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},s=new AbortController,l=()=>s.abort();r?.aborted?s.abort():r?.addEventListener("abort",l,{once:!0});let a=new Promise(e=>{i=setTimeout(()=>{e(t()),o&&s.abort()},n)});try{return await Promise.race([e(s.signal),a])}finally{clearTimeout(i),r?.removeEventListener("abort",l)}}function aw(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 aS(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&&aw(i)?{ok:!0,data:i}:{ok:!1,error:aj(i,r.status)}}let aC=new Set(["cwd-invalid","cwd-denied","cwd-not-directory"]);async function aE(e,t,n){let r=await aS(e,t,n);if(r.ok||!e||!r.error.reason||!aC.has(r.error.reason))return r;let i=await aS(null,t,n);return i.ok?{...i,projectError:r.error}:i}async function aN(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 ak(n=>aE(e,t,n),()=>({ok:!1,error:{error:`GET /api/mcp did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function aI(e,t,n,r){let i,o;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{o=await i.json()}catch{return{ok:!1,error:{error:`HTTP ${i.status}`}}}let s=i.ok&&null!==o&&"object"==typeof o?t(o):void 0;return void 0!==s?{ok:!0,stored:s}:{ok:!1,error:aj(o,i.status)}}async function a$(e,t,n){let r=await aI({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 aT(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 ak(n=>a$(e,t,n),()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function aM(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 ak(async n=>{let r=await aI({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 aR(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 ak(async n=>{let r=await aI({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 aL(e){return!e.available&&"builtin-disabled"!==e.reason}function az(e,t){if(aL(t.mcp))return"mcp-off";if("project"===e){if(!t.project?.trust)return"trust-unreadable";if(!l4(t.project))return"project-untrusted"}}let aA={"mcp-off":"mcp.readOnly.mcp-off","project-untrusted":"mcp.readOnly.project-untrusted","trust-unreadable":"mcp.readOnly.trust-unreadable"};function aW(e){return!0!==e.notAnObject}function aP(e){return aW(e)&&void 0===e.webPasswordField}async function aO(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&&aw(i)?{ok:!0,data:i}:{ok:!1,error:aj(i,r.status)}}async function aF(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,o={...e,...t?{cwd:t}:{}};return ak(e=>aO(o,n,e),()=>({ok:!1,error:{error:`POST /api/mcp did not answer within ${i} ms`,timedOut:!0}}),i,r)}let aB={"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 aD(e,t){let n=az(e.scope,t);return n||(void 0===e.invalidError&&e.validated?e.webPasswordField?"web-password":void 0:"invalid")}let aH={"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"},a_={connected:"mcp.test.state.connected","needs-auth":"mcp.test.state.needs-auth",failed:"mcp.test.state.failed",timedOut:"mcp.test.state.timedOut"},aU={connected:"mcp.test.summary.connected","needs-auth":"mcp.test.summary.needs-auth",failed:"mcp.test.summary.failed",timedOut:"mcp.test.summary.timedOut"},aq={connected:"mcp.signIn.summary.connected","needs-auth":"mcp.signIn.summary.needs-auth",failed:"mcp.signIn.summary.failed",timedOut:"mcp.signIn.summary.timedOut"};function aZ(e){return(Math.max(0,e)/1e3).toFixed(1)}async function aK(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:aj(i,r.status)}}async function aV(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,o={scope:e.scope,name:e.name,...t?{cwd:t}:{}};return ak(e=>aK(o,n,e),()=>({ok:!1,error:{error:`POST /api/mcp/test did not answer within ${i} ms`,timedOut:!0}}),i,r,{abortAtDeadline:!1})}let aJ="•••",aY=new Set(["key","apikey","token","secret","password","passwd","passphrase","pwd","pass","credential","credentials","authorization","bearer","jwt","cookie","signature","pat"]),aG=new Set([...aY,"auth","sig","code","pw"]),aX=["token","secret","password","passwd","apikey"],aQ=new Set(["file","path","dir","url","uri","endpoint","id","name","type","header","env","var","length","ttl","expiry","expires","timeout","mode","format"]),a0=new Set(["-k"]);function a1(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 a2(e,t){let n=a1(e);return!(n.length>1&&aQ.has(n[n.length-1]))&&n.some(e=>t.has(e)||aX.some(t=>e.length>t.length&&e.endsWith(t)))}function a4(e){return a2(e,aY)}let a8=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,})"),a3=/^eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*$/,a5=/^[A-Za-z0-9_\-+/=.~]+$/;function a6(e){return!(/\s/.test(e)||dn(e))&&(!!(a8.test(e)||a3.test(e))||!(e.length<24||!a5.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 a9=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Za-z_][A-Za-z0-9_]*/,a7=RegExp(a9.source,"g"),de=/^(?:bearer|basic|token)\s+/i;function dt(e,t,n){let r=e.replace(de,"");return t.test(r)&&/^[^A-Za-z0-9]*$/.test(r.replace(n,""))}function dn(e){return dt(e.replace(/\$[$!]/g,"_x"),a9,a7)}let dr=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Z_][A-Z0-9_]*(?![A-Za-z0-9_])/,di=RegExp(dr.source,"g");function ds(e){return dt(e,dr,di)}function dl(e,t){if(!e||""===t)return;e.push(t);let n=dc(t);n!==t&&e.push(n)}let da=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#]*)/;function dd(e,t,n){let r=!1,i=e,o="",s=da.exec(e);if(s){let[l,a,d]=s,c=d.lastIndexOf("@");if(c>=0&&!t(dc(d.slice(0,c)))){o=`${a}${aJ}${d.slice(c)}`,r=!0;let e=d.slice(0,c);dl(n,e);let t=e.indexOf(":");t>=0&&dl(n,e.slice(t+1))}else o=l;i=e.slice(l.length)}let l=i.search(/[?#]/),a=l<0?i:i.slice(0,l),d=l<0?"":i.slice(l),c=a.split("/").map(e=>a6(dc(e))?(r=!0,dl(n,e),aJ):e).join("/");return d=d.replace(/([?&#;])([^&#;]*)/g,(e,i,o)=>{let s=o.indexOf("=");if(s<0){let s=dc(o);return!a6(s)||t(s)?e:(r=!0,dl(n,o),`${i}${aJ}`)}let l=o.slice(0,s),a=dc(o.slice(s+1));return""===a||t(a)||!function(e){let t=e;try{t=decodeURIComponent(e)}catch{}return a2(t,aG)}(l)&&!a6(a)?e:(r=!0,dl(n,o.slice(s+1)),`${i}${l}=${aJ}`)}),{value:`${o}${c}${d}`,masked:r}}function dc(e){try{return decodeURIComponent(e)}catch{return e}}let du=/^(\s*[A-Za-z][A-Za-z0-9 _.-]*=)([\s\S]*)$/;function dp(e,t,n){let r=/^([A-Za-z0-9_-]+):(\s*)([\s\S]*)$/.exec(e);if(r&&""!==r[3]&&!r[3].startsWith("//")&&a4(r[1])){let[,i,o,s]=r;return t(s)?{value:e,masked:!1}:(dl(n,s.trim()),{value:`${i}:${o}${aJ}`,masked:!0})}let i=e.includes(";")?function(e,t,n){let r=e.split(";");if(r.length<2||!r.every(e=>""===e.trim()||du.test(e)))return;let i=!1;return{value:r.map(e=>{let r=du.exec(e);if(!r)return e;let[,o,s]=r;if(""===s.trim()||t(s))return e;if(a4(o.slice(0,-1).trim()))return i=!0,dl(n,s.trim()),`${o}${aJ}`;let l=dp(s,t,n);return i||=l.masked,`${o}${l.value}`}).join(";"),masked:i}}(e,t,n):void 0;if(i)return i;let o=/^([A-Za-z_][A-Za-z0-9_]*)=([\s\S]*)$/.exec(e);if(o&&""!==o[2]&&a4(o[1]))return t(o[2])?{value:e,masked:!1}:(dl(n,o[2]),{value:`${o[1]}=${aJ}`,masked:!0});if(/\s/.test(e)){var s,l,a;let r,i;return s=e,l=t,a=n,i=dm((r=s.split(/(\s+)/)).filter((e,t)=>t%2==0),l,!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 dd(e,t,n);if(o&&""!==o[2]){let e=dp(o[2],t,n);return{value:`${o[1]}=${e.value}`,masked:e.masked}}return a6(e)&&!t(e)?(dl(n,e),{value:aJ,masked:!0}):{value:e,masked:!1}}function dh(e){if(a0.has(e))return!0;if(!/^--?[A-Za-z]/.test(e))return!1;let t=e.replace(/^-+/,"");return a4(t)||"auth"===a1(t).at(-1)}let df=/^(?:bearer|basic|token)$/i;function dm(e,t,n,r){let i=!1,o=!1;return{values:e.map(e=>{if(""===e)return e;if(o){if(n&&df.test(e))return e;if(o=!1,!/^-[A-Za-z-]/.test(e))return t(e)?e:(i=!0,dl(r,e),aJ)}let s=/^(--?[A-Za-z][A-Za-z0-9_.-]*)=([\s\S]*)$/.exec(e);if(s){let[,e,n]=s;if(""!==n&&dh(e)&&!t(n))return i=!0,dl(r,n),`${e}=${aJ}`;let o=dp(n,t,r);return i||=o.masked,`${e}=${o.value}`}if(/^--?[A-Za-z][A-Za-z0-9_.-]*$/.test(e))return o=dh(e),e;if(n){let t=/^([A-Za-z0-9_-]+):$/.exec(e);if(df.test(e)||t&&a4(t[1]))return o=!0,e}let l=dp(e,t,r);return i||=l.masked,l.value}),masked:i}}function dg(e){let{values:t,masked:n}=dm(e,ds,!1);return{args:t,masked:n}}function dx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function dv(e){return!e.startsWith("!")&&!dn(e)}function db(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 dy={"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(dy);let dj={dollarBrace:!1,bareDollar:!1,percent:!1,braceEnv:!1},dk={dollarBrace:!0,bareDollar:!1,percent:!0,braceEnv:!0},dw={...dk,bareDollar:!0},dS={...dj,braceEnv:!0},dC=/^[A-Za-z_][A-Za-z0-9_]*$/,dE=/\$\{([^{}]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)|%([A-Za-z_][A-Za-z0-9_]*)%|\{(env|file):([^{}]*)\}/g;function dN(e,t){if(!t)return;let n=e[e.length-1];n?.kind==="text"?n.text+=t:e.push({kind:"text",text:t})}function dI(e,t,n){let r=[],i=0;dE.lastIndex=0;for(let o=dE.exec(e);o;o=dE.exec(e)){let[s,l,a,d,c,u]=o,p=s;if(void 0!==l&&t.dollarBrace)p=function(e,t){let n=/^env:([A-Za-z_][A-Za-z0-9_]*)$/.exec(e);if(n)return{kind:"env",name:n[1],from:t};let r=/^input:(.+)$/.exec(e);if(r)return{kind:"input",id:r[1],from:t};if("userHome"===e)return{kind:"home",from:t};if("workspaceFolder"===e||"workspaceRoot"===e||"CLAUDE_PROJECT_DIR"===e)return{kind:"workspace",from:t};if("workspaceFolderBasename"===e)return{kind:"workspace-basename",from:t};if("pathSeparator"===e||"/"===e)return"/";if("CLAUDE_PLUGIN_ROOT"===e||"CLAUDE_PLUGIN_DATA"===e)return{kind:"unsupported",from:t};if(dC.test(e))return{kind:"env",name:e,from:t};let i=/^([A-Za-z_][A-Za-z0-9_]*):?-([\s\S]*)$/.exec(e);return i?{kind:"env",name:i[1],from:t,fallback:i[2]}:/^[A-Za-z]+:/.test(e)?{kind:"unsupported",from:t}:t}(l,s);else if(void 0!==a&&t.bareDollar)p={kind:"env",name:a,from:s};else if(void 0!==d&&t.percent&&n)p={kind:"env",name:d,from:s};else if(void 0!==c&&t.braceEnv)p="env"===c&&dC.test(u)?{kind:"env",name:u,from:s}:{kind:"unsupported",from:s};else if(void 0!==d||void 0!==c){dN(r,e.slice(i,o.index+1)),i=o.index+1,dE.lastIndex=o.index+1;continue}dN(r,e.slice(i,o.index)),"string"==typeof p?dN(r,p):r.push(p),i=o.index+s.length}return dN(r,e.slice(i)),r}function d$(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 dT(e){return e.startsWith("!")}function dM(e){if(dT(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);dC.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 dR=/<[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,dL=/^(?:\.\.\.|…|\*{3,}|x{3,}|TODO|FIXME|changeme|change[-_]me|replace[-_]?me|placeholder|redacted|\[[^\]]+\])$/i,dz=/(?:^|[\\/])(?:path[\\/]to(?:[\\/]|$)|Users[\\/](?:username|yourname|your[-_][A-Za-z_-]+|user[-_]?name|<[^>]+>)(?:[\\/]|$)|home[\\/](?:username|yourname|your[-_][A-Za-z_-]+|<[^>]+>)(?:[\\/]|$))/i,dA=/^(Bearer|Basic|Token|Bot|ApiKey|Api-Key)\s+(.+)$/i;function dW(e){return e.join("\0")}function dP(e){return"args"===e[0]?`args[${e[1]}]`:e.join(".")}function dO(e){return"env"===e[0]||"headers"===e[0]||"oauth"===e[0]&&"clientSecret"===e[1]}function dF(e){return"command"===e[0]||"args"===e[0]||"cwd"===e[0]}let dB=new Set(["HOME","USERPROFILE"]);class dD{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 dH(e){return e.map(e=>"text"in e?e.text:e.from).join("")}let d_=/\$\{[^{}]*\}/g,dU=new Set(["variable","home","workspace-basename","unsupported-variable","input"]);class dq{constructor(e){this.draft=e,this.fields=new Map,this.argTexts=e.args.map(dH),this.urlText=dH(e.url??[])}encode(e,t){let n,r=dO(e),i=dP(e),o=dH(t),s=[],l=!1,a=()=>s.every(e=>""===e),d=e=>{if(!r)return void s.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=d$(e,{atStart:a()});n!==e&&(l=!0),s.push(n)},c=e=>s.push(e),u=e=>s.push({field:e});if(!r&&dF(e)&&1===t.length&&"text"in t[0]&&dz.test(o)){let t="args"===e[0]?/^(?:--?[A-Za-z][A-Za-z0-9_.-]*|[A-Za-z_][A-Za-z0-9_]*)=/.exec(o)?.[0]??"":"",n=o.slice(t.length);if(dz.test(n))return t&&c(t),u(this.field(e,"placeholder-path",n,n,"text")),this.target(e,s,void 0)}let p=0;return t.forEach((s,l)=>{let h=t[l+1],f=void 0===h||"text"in h&&/^[\\/]/.test(h.text),m=(t,r,i)=>{let s=0;for(let[d,c]of function(e){let t=e.trim();if(dL.test(t)){let n=e.indexOf(t);return[[n,n+t.length]]}let n=dA.exec(t);if(n&&dL.test(n[2].trim())){let t=e.lastIndexOf(n[2].trim());return[[t,t+n[2].trim().length]]}let r=[];dR.lastIndex=0;for(let t=dR.exec(e);t;t=dR.exec(e))/^your[-_]/.test(t[0])&&/[@/]/.test(e[t.index-1]??"")||r.push([t.index,t.index+t[0].length]);return r}(t)){var l,a;if(i.some(e=>{let[t,n]=e;return d<n&&c>t}))continue;d>s&&r(t.slice(s,d)),"url"===e[0]&&dZ(o,p+d)&&(n="uri-component");let h=t.slice(d,c);u(this.field(e,"placeholder",(l=e,a=h,"env"===l[0]||"headers"===l[0]?l[1]:a.replace(/^[<{\s]+|[>}\s]+$/g,"")||dP(l)),h)),s=c}s<t.length&&r(t.slice(s))};switch(s.kind){case"text":m(s.text,d,[]);break;case"pi":{var g;let e=h?(g=s.text,(/\$+$/.exec(g)?.[0].length??0)%2==1?`${g}$`:g):s.text;if(r&&a()&&dT(e)){this.draft.note("shell-command-value",{field:i}),c(e);break}let t=[...e.matchAll(d_)].map(e=>[e.index,e.index+e[0].length]);m(e,c,t);break}case"env":r?(c(`\${${s.name}}`),void 0!==s.fallback&&this.draft.note("variable-fallback-dropped",{field:i,name:s.name,fallback:s.fallback}),s.shell?this.draft.note("shell-variable",{field:i,name:s.name}):s.from!==`\${${s.name}}`&&this.draft.note("variable-translated",{field:i,from:s.from,to:`\${${s.name}}`})):dF(e)&&a()&&dB.has(s.name)&&f?(c("~"),this.draft.note("home-translated",{field:i,from:s.from})):(u(this.field(e,"variable",s.name,s.from,void 0,s.fallback)),this.draft.note(s.shell?"shell-variable":"variable-unsupported-here",{field:i,name:s.name}));break;case"input":u(this.inputField(e,s));break;case"home":r?(c("${HOME}"),this.draft.note("home-variable-translated",{field:i,from:s.from,to:"${HOME}"})):dF(e)&&a()&&f?(c("~"),this.draft.note("home-translated",{field:i,from:s.from})):u(this.field(e,"home","userHome",s.from,"text"));break;case"workspace":"url"===e[0]||"oauth"===e[0]?u(this.field(e,"variable","workspaceFolder",s.from,"text")):(c("."),this.draft.note("workspace-folder-relative",{field:i,from:s.from}));break;case"workspace-basename":u(this.field(e,"workspace-basename","workspaceFolderBasename",s.from,"text"));break;case"unsupported":u(this.field(e,"unsupported-variable",s.from,s.from)),this.draft.note("unsupported-variable",{field:i,variable:s.from});break;case"prompt":"url"===e[0]&&dZ(o,p)&&(n="uri-component"),u(this.promptField(e,s))}p+=("text"in s?s.text:s.from).length}),l&&this.draft.note("escaped-value",{field:i}),this.target(e,s,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=>dW(t.path)===dW(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,o){let s=dU.has(t)?`${t}.${n}`:dP(e);if(dU.has(t)){if(this.fields.has(s))return s}else for(let t=2;this.fields.has(s);t++)s=`${dP(e)}#${t}`;let l=this.isSecretContext(e,r)||a4(n),a="headers"===e[0]&&"authorization"===e[1].toLowerCase();return this.fields.set(s,{id:s,kind:i??(l?"password":"text"),reason:t,label:n,placeholder:r,...void 0!==o?{defaultValue:o}:{},..."placeholder"===t&&a?{optional:!0}:{},targets:[]}),s}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,o=r?.password===!0||this.isSecretContext(e,t.from);return this.fields.set(n,{id:n,kind:i?"select":o?"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 a4(e[1]);case"oauth":return"clientSecret"===e[1];case"args":{if(dg([this.argTexts[e[1]]??""]).masked)return!0;let t=this.argTexts[e[1]-1];return void 0!==t&&dg([t,"x"]).args[1]===aJ}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,dd(`https://host.invalid/?${n}=x`,ds).masked)}default:return!1}}}function dZ(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 dK(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 dV=/^[A-Za-z0-9_-]+$/;function dJ(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 dY=new Set(["mcp","server","mcp-server","mcpserver","cli","index","main","app","src","dist","build","bin","lib"]);function dG(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 o=dQ(t);return o&&!dY.has(o.toLowerCase())?o:dQ(r)||r||o||t}let dX=[/^mcp[-_]server[-_]/i,/^server[-_]/i,/^mcp[-_]/i,/[-_]mcp[-_]server$/i,/[-_]mcp$/i,/[-_]server$/i];function dQ(e){let t=e;for(let e=!0;e;)for(let n of(e=!1,dX)){let r=t.replace(n,"");r!==t&&r&&(t=r,e=!0)}return t}let d0=new Set(["mcp","www","api","app","server","servers","remote","gateway"]);function d1(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=>!d0.has(e.toLowerCase()));return r[r.length-1]??n[n.length-1]??""}let d2=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 d4(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 d8(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(!dY.has(n.toLowerCase())&&"."!==n&&".."!==n)return dQ(n.replace(/_/g,"-"))||n}return""}function d3(e,t){d5(e,t)&&d6(e,Math.ceil(t/1e3),t)}function d5(e,t){return!!("number"==typeof t&&Number.isFinite(t))&&t>0||(void 0!==t&&e.note("timeout-dropped",{value:String(t)}),!1)}function d6(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 d9=["codemode","deferred","direct","hidden"],d7={"codemode-deferred":"codemode"},ce=["localhost","127.0.0.1","[::1]"];function ct(e){return"string"==typeof e&&d9.includes(e)?e:"string"==typeof e&&Object.hasOwn(d7,e)?d7[e]:void 0}function cn(e){try{return new URL(e)}catch{return}}function cr(e){let t=cn(e);return void 0!==t&&"http:"===t.protocol&&ce.includes(t.hostname)&&""===t.search&&""===t.hash}function ci(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function co(e){return ci(e)&&Object.values(e).every(e=>"string"==typeof e)}function cs(e,t){if(!dV.test(e))return{problem:"name",name:e};if(!ci(t))return{problem:"not-an-object"};let{type:n,exposure:r,enabled:i,timeout:o,toolExposure:s,description:l}=t;if(void 0!==r&&!ct(r))return{problem:"exposure",value:String(r)};if(void 0!==s){if(!ci(s))return{problem:"tool-exposure"};for(let[e,t]of Object.entries(s))if(!ct(t))return{problem:"tool-exposure",tool:e}}if(void 0!==i&&"boolean"!=typeof i)return{problem:"enabled"};if(void 0!==l&&"string"!=typeof l)return{problem:"description"};if(void 0!==o&&("number"!=typeof o||!(o>0)))return{problem:"timeout",value:String(o)};if("sse"===n)return{problem:"sse"};if("string"==typeof t.url&&(void 0===n||"http"===n||"streamable-http"===n)){let e=cn(t.url);if(!e||!/^https?:$/.test(e.protocol))return{problem:"url",url:t.url};if(void 0!==t.headers&&!co(t.headers))return{problem:"headers"};let n=function(e){var t;let n;if(void 0===e)return;if(!ci(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||!cr(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}}return void 0!==e.scope&&"string"!=typeof e.scope?{problem:"oauth-scope"}:void 0===e.clientName||"string"==typeof e.clientName&&e.clientName.trim()?void 0===e.authServerMetadataUrl||void 0!==(n="string"==typeof(t=e.authServerMetadataUrl)?cn(t):void 0)&&("https:"===n.protocol||"http:"===n.protocol&&ce.includes(n.hostname))?void 0:{problem:"auth-server-metadata-url",value:String(e.authServerMetadataUrl)}:{problem:"oauth-client-name"}}(t.oauth);if(n)return n;let r=t.auth;if(void 0!==r){if(!ci(r)||"string"!=typeof r.provider||!r.provider)return{problem:"auth"};if("https:"!==e.protocol&&!ce.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||co(t.env)?void 0!==t.cwd&&"string"!=typeof t.cwd?{problem:"cwd"}:void 0:{problem:"env"}:{problem:"args"}:{problem:"no-command-or-url"}}let cl=/[A-Za-z_]/,ca=/[A-Za-z0-9_]/,cd=/^[A-Za-z_][A-Za-z0-9_]*$/,cc=new Set([..." \n'\"\\$`|&;<>()#*?[]{}!~="]),cu=new Set([..."|&;<>()"]),cp=/[0-9@*#?$!-]/,ch={n:"\n",t:" ",r:"\r",a:"\x07",b:"\b",e:"\x1b",E:"\x1b",f:"\f",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function cf(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 cm(e,t){return/^(?:[A-Za-z]:\\|\\\\[A-Za-z0-9.$_-])/.test(e.slice(t,t+4))}class cg{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 cx)return{ok:!1,error:e.detail};throw e}return{ok:!0,words:this.words}}fail(e){throw new cx(e)}startWord(){return this.parts||(this.lineBreak&&this.fail({code:"multiple-commands"}),this.parts=[],this.windowsWord=cm(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)&&cf(e,this.index)>0)this.index+=cf(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:"`"}):cu.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||!cc.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=cm(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 ch?(t+=ch[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&&cl.test(n)){let n=this.index+1;for(;n<t.length&&ca.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&&cp.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}),cd.test(i)){this.startWord().push({type:"variable",name:i,raw:r,quote:e}),this.index=n+1;return}let o=/^([A-Za-z_][A-Za-z0-9_]*):?-([\s\S]*)$/.exec(i);if(o&&!/[$`{}\\'"]/.test(o[2])){this.startWord().push({type:"variable",name:o[1],raw:r,quote:e,fallback:o[2]}),this.index=n+1;return}this.fail({code:"unsupported-expansion",expansion:r})}}class cx extends Error{constructor(e){super(e.code),this.detail=e}}function cv(e){return new cg(e).run()}function cb(e){return e.parts.every(e=>"text"===e.type)?e.text:void 0}function cy(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let cj=["httpUrl","trust","includeTools","excludeTools","authProviderType","targetAudience","targetServiceAccount","tcp"];function ck(e){if(cj.some(t=>t in e))return!0;let t=e.oauth;return cy(t)&&["redirectUri","authorizationUrl","tokenUrl","audiences","tokenParamName"].some(e=>e in t)}function cw(e){if(!cy(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]||cy(t)&&"string"==typeof t.path||"string"==typeof n||"string"==typeof r||"string"==typeof i}function cS(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 cC(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 cE(e,t){let n=t?cC(t):void 0;return{code:"sse-transport",params:{...e?{server:e}:{},...t?{url:t}:{},...n?{suggestedUrl:n}:{}}}}function cN(e){return e?{server:e}:{}}function cI(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?String(e):void 0}function c$(e,t,n){let r;if(!cy(t))return{note:{code:"no-command-or-url",params:cN(e)}};let i=new Set,o=e=>(i.add(e),t[e]),s=n.rawPi,l=function(e,t){switch(e.flavor){case"zed":return dj;case"opencode":return dS;case"vscode":return dk;default:return ck(t)?dw:dk}}(n,t),a=o("name"),d=e??("string"==typeof a?a:void 0),c=new dD(n.source,s),u=(e,t)=>{if(s)return e?[{kind:"pi",text:e}]:[];return t&&"mcp-servers"===n.flavor&&/^!|\$\$|\$!/.test(e)&&c.note("looks-like-pi-config"),dI(e,l,t)};c.name=d,c.inputs=n.inputs;let p=o("inputs");Array.isArray(p)&&(c.inputs=new Map([...n.inputs??[],...cR(p)]));let h=o("type"),f=o("command"),m=[o("httpUrl"),o("url"),o("serverUrl")].find(e=>"string"==typeof e);if("tcp"in t)return{note:{code:"websocket-transport",params:cN(d)}};if(void 0!==h&&"unknown"===(r="string"==typeof h?cS(h):"unknown"))return{note:{code:"unsupported-transport",params:{...cN(d),type:String(h)}}};let g="string"==typeof f&&""!==f||Array.isArray(f)||cy(f),x=void 0!==m;if("sse"===r)return{note:cE(d,m)};if("ws"===r)return{note:{code:"websocket-transport",params:{...cN(d),...m?{url:m}:{}}}};if(void 0===r){if(g&&x)return{note:{code:"ambiguous-command-and-url",params:cN(d)}};if(x){if(void 0!==cC(m))return{note:cE(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:cN(d)}};r="stdio"}}if("stdio"!==r&&"http"!==r)return{note:{code:"unsupported-transport",params:{...cN(d),type:String(h)}}};if("stdio"===r&&!g||"http"===r&&!x)return{note:{code:"no-command-or-url",params:cN(d)}};if(c.transport=r,"stdio"===r){let e=function(e,t,n,r,i,o){let s,l=r("args"),a=r("opencode"===o.flavor?"environment":"env");if("opencode"===o.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:{...cN(e.name),problem:"args"}};s=n[0],l=[...n.slice(1),...Array.isArray(l)?l:[]]}else if(cy(n))for(let t of(s="string"==typeof n.path?n.path:void 0,void 0===l&&(l=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&&(s=n);if(!s)return{code:"no-command-or-url",params:cN(e.name)};let d=Array.isArray(l)?[...l]:[];if(void 0!==l&&!Array.isArray(l))return{code:"invalid-config",params:{...cN(e.name),problem:"args"}};if(0===d.length&&/\s/.test(s.trim())&&!/^(?:[A-Za-z]:[\\/]|[\\/]|~[\\/]|\.{1,2}[\\/])/.test(s.trim())){let t=cv(s.trim()),n=t.ok?t.words.map(cb):void 0;n&&n.length>1&&n.every(e=>void 0!==e)&&(e.note("command-split",{command:s}),s=n[0],d.push(...n.slice(1)))}for(let[t,n]of(e.command=i(s,!1),d.entries())){let r=cI(n);if(void 0===r)return{code:"invalid-config",params:{...cN(e.name),problem:"args",index:t}};e.args.push(i(r,!1))}if(void 0!==a){if(!cy(a))return{code:"invalid-config",params:{...cN(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=cI(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&&a4(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,o,u,n);if(e)return{note:e}}else!function(e,t,n,r,i){let o=r("headers"),s=i(n,!1),l=cy(o)&&Object.keys(o).some(e=>"authorization"===e.toLowerCase());if(1===s.length&&"text"in s[0]?dK(e,n,l):e.url=s,cy(o))for(let[t,n]of Object.entries(o)){let r=cI(n);if(void 0===r){e.note("dropped-key",{key:`headers.${t}`});continue}if(""===r.trim()){"authorization"===t.toLowerCase()?e.note("empty-authorization-dropped"):a4(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!==o&&e.note("dropped-key",{key:"headers"});let a=r("oauth"),d=r("auth");if(!1===a?e.note("oauth-disable-unsupported"):cy(a)?cT(e,a,i):void 0!==a&&e.note("dropped-key",{key:"oauth"}),cy(d))for(let t of(cT(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,o,u);let v=o("timeout");if(void 0!==v)if(s)"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(ck(t))d3(c,v);else["autoApprove","alwaysAllow","transportType"].some(e=>e in t)||"streamableHttp"===t.type?d5(c,v)&&d6(c,Math.ceil(v),void 0):!function(e,t){if(!d5(e,t))return;let n=t>=1e3;e.note("timeout-unit-guessed",{value:t,unit:n?"milliseconds":"seconds"}),n?d6(e,Math.ceil(t/1e3),t):d6(e,Math.ceil(t),void 0)}(c,v);let b=o("enabled"),y=o("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 j=o("exposure");if(void 0!==j){let e=ct(j);e?c.exposure=e:c.note("invalid-exposure-dropped",{value:String(j)})}let k=o("toolExposure");if(void 0!==k){let e=cy(k)?Object.entries(k).map(e=>{let[t,n]=e;return[t,ct(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(s||void 0===j&&void 0===k||c.note("looks-like-pi-config"),s){let e=o("description");"string"==typeof e?c.description=e:void 0!==e&&c.note("dropped-key",{key:"description"})}for(let e of(cM(c,o("includeTools"),o("excludeTools")),Object.keys(t)))i.has(e)||c.note("dropped-key",{key:e});return{draft:c}}function cT(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"oauth.";for(let[i,o]of Object.entries(t))switch(i){case"clientId":"string"==typeof o&&""!==o&&(e.oauth.clientId=n(o,!1));break;case"clientSecret":"string"==typeof o&&""!==o&&(e.oauth.clientSecret=n(o,!0));break;case"callbackPort":"number"==typeof o&&Number.isInteger(o)&&o>=1&&o<=65535?e.oauth.callbackPort=o:e.note("callback-port-dropped",{value:String(o)});break;case"clientName":"string"==typeof o&&o.trim()?e.oauth.clientName=n(o,!1):e.note("oauth-option-dropped",{key:`${r}${i}`});break;case"authServerMetadataUrl":"string"==typeof o&&""!==o?e.oauth.authServerMetadataUrl=n(o,!1):e.note("oauth-option-dropped",{key:`${r}${i}`});break;case"callbackUrl":case"redirectUri":"string"==typeof o&&cr(o)?e.oauth.callbackUrl=n(o,!1):e.note("callback-url-dropped",{value:String(o)});break;case"scope":case"scopes":{let t=Array.isArray(o)?o.filter(e=>"string"==typeof e).join(" "):"string"==typeof o?o:"";t&&(e.oauth.scope=n(t,!1));break}case"enabled":!1===o&&e.note("oauth-disable-unsupported");break;default:e.note("oauth-option-dropped",{key:`${r}${i}`})}let{callbackPort:i,callbackUrl:o}=e.oauth;if(void 0!==i&&o){let t=o.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 cM(e,t,n){let r=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e&&""!==e):[],i=r(t),o=r(n);if(0===i.length&&0===o.length)return;let s={...e.toolExposure??{}};if(i.length>0){let t=e.exposure??"codemode";for(let n of(e.exposure="hidden",i))s[n]=t;e.note("tool-filter-imported",{mode:"include",tools:i.join(", ")})}for(let e of o)s[e]="hidden";o.length>0&&e.note("tool-filter-imported",{mode:"exclude",tools:o.join(", ")}),e.toolExposure=s}function cR(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e)cy(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=>cy(e)?e.value:e).filter(e=>"string"==typeof e)}:{}});return t}function cL(e,t,n,r){let i=[],o=0;for(let s of e.matchAll(/\{([A-Za-z_][A-Za-z0-9_-]*)\}/g)){s.index>o&&i.push({kind:"text",text:e.slice(o,s.index)});let l=cy(t)&&cy(t[s[1]])?t[s[1]]:{};i.push(cz(`${n}${s[1]}`,s[1],s[0],l,r)),o=s.index+s[0].length}return o<e.length&&i.push({kind:"text",text:e.slice(o)}),i}function cz(e,t,n,r,i){let o=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},...o.length>0?{options:o}:{}}}function cA(e,t,n){let r=[],i="",o=()=>{i&&("pi"===t?r.push({kind:"pi",text:i}):r.push(...dI(i,t,n)),i="")};for(let t of e)"variable"===t.type?(o(),r.push({kind:"env",name:t.name,from:t.raw,shell:!0,...void 0!==t.fallback?{fallback:t.fallback}:{}})):i+=t.value;return o(),r}function cW(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 o=i.value.indexOf(t);if(o<0){n+=i.value;continue}n+=i.value.slice(0,o);let s=i.value.slice(o+t.length);return[n,[...s?[{...i,value:s}]:[],...e.slice(r+1)]]}}let cP=/^https?:\/\//i,cO=/^wss?:\/\//i,cF={"@earendil-works/pi-coding-agent":"pi","@anthropic-ai/claude-code":"claude","@openai/codex":"codex","@google/gemini-cli":"gemini"},cB=new Set(["pi","claude","codex","gemini"]),cD=new Set(["install","remove","uninstall","update","list","config"]);function cH(e){return"error"in e?{error:e.error}:{entries:[e],notes:[]}}let c_={local:"flag",url:"value",env:"list",cwd:"value",header:"list","bearer-token-env-var":"value","oauth-client-id":"value","oauth-client-secret":"value","oauth-callback-port":"value","oauth-client-name":"value",exposure:"value",description:"value"},cU=new Map([["-l","--local"]]),cq=["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name"],cZ=["env","cwd"];function cK(e,t,n,r){let i={positional:[],afterDashDash:[],values:new Map,lists:new Map,seen:new Map};for(let o=0;o<t.length;o++){let s=t[o],l=s.text;if("--"===l){i.afterDashDash.push(...t.slice(o+1));break}if(void 0!==r.stopAfter&&i.positional.length>=r.stopAfter){i.positional.push(...t.slice(o));break}if(!l.startsWith("-")||"-"===l){i.positional.push(s);continue}let a=l.startsWith("--")?l.indexOf("="):-1,d=a>0?l.slice(0,a):l,c=n[d];if(!c){if(i.positional.length>=r.asArgAfter){i.positional.push(s),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?cV(s,a+1):void 0;if("value"===c.kind||"list"===c.kind){let n=u??t[++o];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(;o+1<t.length&&r.variadic(c.name,t[o+1]);)p.push(t[++o]);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 cV(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 cJ=/^[A-Za-z_][A-Za-z0-9_]*=/,cY=/^[^\s:]+:/;function cG(e,t,n,r){for(let i of t??[]){let t=cW(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],cA(t[1],n,!0)])}}function cX(e,t,n,r){for(let i of t??[]){let t=cW(i.parts,":"),o=t?.[0].trim();if(!t||!o)return{code:"cli-invalid-pair",params:{cli:r,option:"--header",value:i.text}};let s=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"===o.toLowerCase()&&s.every(e=>"text"===e.type&&""===e.value)){e.note("empty-authorization-dropped");continue}e.headers.push([o,cA(s,n,!0)])}}function cQ(e){if(void 0!==e&&!0!==e){if("user"===e.text)return"global";if("project"===e.text)return"project"}}function c0(e,t,n,r,i){let o,[s,l,...a]=r;if(!s||!l)return{code:"cli-usage",params:{cli:t}};e.name=s.text;let d=void 0===n||!0===n?void 0:n.text.toLowerCase();if(void 0===d){if("http"==(o=cP.test(l.text)?"http":cO.test(l.text)?"ws":"stdio")&&void 0!==cC(l.text))return cE(s.text,l.text);"http"===o&&"gemini"===t&&e.note("transport-assumed-http")}else o="streamable-http"===d?"http":d;return"sse"===o?cE(s.text,l.text):"ws"===o?{code:"websocket-transport",params:{server:s.text,url:l.text}}:"http"===o?(e.transport="http",e.url=cA(l.parts,i,!1),a.length>0&&e.note("cli-extra-arguments",{cli:t,arguments:a.map(e=>e.text).join(" ")}),"http"):"stdio"!==o?{code:"unsupported-transport",params:{server:s.text,type:o}}:(e.transport="stdio",e.command=cA(l.parts,i,!1),e.args=a.map(e=>cA(e.parts,i,!1)),"stdio")}let c1={"-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 c2(e,t){return"env"===e?cJ.test(t.text):cY.test(t.text)&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(t.text)}function c4(e){e.oauth.clientSecret=[{kind:"prompt",id:"oauth.clientSecret",reason:"client-secret",label:"clientSecret",from:"",secret:!0}],e.note("client-secret-prompt")}let c8={"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"--client-secret":{name:"client-secret",kind:"flag"}};function c3(e){let t,n=cb(e)??e.text;try{t=db(n)}catch(e){return{error:{code:"invalid-json",params:{detail:e instanceof Error?e.message:String(e)}}}}return cy(t)?{value:t}:{error:{code:"no-servers-found"}}}let c5={"--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"}},c6={"-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 c9(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(c7(r),c7(i))}return t}function c7(e){try{return decodeURIComponent(e)}catch{return e}}function ue(e){let t=e.trim();for(let e=0;e<4;e++)try{return db(t)}catch{let e=c7(t);if(e===t)break;t=e.trim()}}function ut(e){return{error:{code:"install-link-invalid",params:{detail:e}}}}function un(e){let t=e.get("config");if(!t)return ut("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:ue(n);return cy(r)?{entries:[c$(e.get("name")||void 0,r,{source:"cursor-install-link",flavor:"mcp-servers",rawPi:!1})],notes:[]}:ut("config")}function ur(e,t,n,r){return cy(e)?{entries:[c$(n,e,{source:t,flavor:"vscode",rawPi:!1,inputs:cR(r)})],notes:[]}:ut("config")}function ui(e){return{error:{code:"by-name-link",params:{name:e}}}}function uo(e){let t=e.indexOf("?");return t<0?"":e.slice(t+1)}function us(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:[ua(void 0,r)],notes:[]};return{error:{code:"unrecognized-input"}}}if(n>3)return ut("nesting");let i=t.protocol.replace(/:$/,"").toLowerCase();switch(i){case"cursor":if(/\/mcp\/install\/?$/.test(t.pathname))return un(c9(t.search));return ut("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 ui(c7(t[1]));if(/^mcp\/api\.mcp\.github\.com\//.test(e))return ui(e.replace(/^mcp\//,""));if(/^mcp\/install\?/.test(e))return ur(ue(uo(r)),"vscode-install-link");return ut(i)}case"vsweb+mcp":return ur(ue(uo(r)),"visual-studio-install-link");case"ghapp":if(/^\/\/mcp\/install/.test(r.slice(r.indexOf(":")+1)))return ur(ue(uo(r)),"copilot-app-install-link");return ut(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 un(c9(e.search));if("vscode.dev"===r||"insiders.vscode.dev"===r){let t=c9(e.search);if(/^\/redirect\/?$/.test(i)&&t.get("url"))return us(t.get("url"),n+1);if(/^\/redirect\/mcp\/install\/?$/.test(i)){let e=t.get("config");return e?ur(ue(e),"vscode-install-link",t.get("name")||void 0,ue(t.get("inputs")??"[]")):ut("config")}}if("aka.ms"===r&&/^\/vs\/mcp-install\/?$/i.test(i))return ur(ue(e.search.slice(1)),"visual-studio-install-link");if("github.com"===r&&/^\/copilot\/app\/launch\/?$/.test(i)){let t=c9(e.search).get("open");return t?us(t,n+1):ut("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:[ua(e,t)],notes:[]}}(t,r,n);default:return{error:{code:"unsupported-url-scheme",params:{scheme:i}}}}}let ul=new Set(["localhost","127.0.0.1","[::1]"]);function ua(e,t){let n=d1(t)||void 0;if(void 0!==cC(t))return{note:cE(n,t)};let r=new dD("url",!1);return r.transport="http",dK(r,t,!1),e?.protocol!=="http:"||ul.has(e.hostname)||r.note("insecure-http",{host:e.hostname}),{draft:r}}let ud=/[\u200B-\u200D\u2060\uFEFF]/g,uc=/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]\S*)?$/i,uu={"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 up(e){return new Set(e.fields.flatMap(e=>e.targets.map(e=>dW(e.path))))}function uh(e){var t;let n,r,i,o,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},l=(n=e.replace(ud,"").replace(/\u00A0/g," ").trim(),(r=/```[^\n]*\n([\s\S]*?)(?:```|$)/.exec(n))?n=r[1].trim():/^`[^`\n]+`$/.test(n)&&(n=n.slice(1,-1).trim()),(i=n.startsWith("[")?/\]\(([^()\s]+)\)\s*$/.exec(n):null)&&(n=i[1]),/^<\S+>$/.test(n)&&(n=n.slice(1,-1)),n);if(!l)return{ok:!1,notes:[{code:"empty-input"}]};if(l.startsWith("{")||l.startsWith("[")||/^"[^"\n]+"\s*:/.test(l))o=function(e,t){let n;try{n=db(e)}catch(t){try{n=db(`{${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 c$(n,r,t)});if(Array.isArray(e)){let r=e.filter(cw);return 0===r.length?{error:{code:"no-servers-found"}}:{entries:r.map(e=>c$(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})),notes:n}}if(!cy(e))return{error:{code:"no-servers-found"}};let i=cy(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?dG(t.split("/").pop()??t):void 0,r=Array.isArray(e.remotes)?e.remotes.filter(cy):[],i=r.filter(e=>"string"==typeof e.type&&"http"===cS(e.type)&&"string"==typeof e.url);if(0===i.length){let e=r.find(e=>"sse"===e.type);return e?[{note:cE(n,"string"==typeof e.url?e.url:void 0)}]:[{note:{code:"registry-packages-unsupported",params:cN(n)}}]}return i.map(e=>{let r=new dD("registry-server-json",!1);for(let i of(r.name=n,t&&n!==t&&(r.originalName=t),r.transport="http",r.url=cL(e.url,e.variables,"url.","registry-variable"),Array.isArray(e.headers)?e.headers.filter(cy):[])){if("string"!=typeof i.name||""===i.name)continue;let e=i.name;"string"==typeof i.value&&""!==i.value?r.headers.push([e,cL(i.value,i.variables,`headers.${e}.`,"registry-header")]):r.headers.push([e,[cz(`headers.${e}`,e,"",i,"registry-header")]])}return{draft:r}})}(i),notes:n};if(cy(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(cy(e.servers)){let t=cR(e.inputs);return{entries:r(e.servers,{source:"vscode-json",flavor:"vscode",rawPi:!1,inputs:t}),notes:n}}if(cy(e.mcp)){let t=e.mcp;if(cy(t.servers)){let e=cR(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(cy(e.context_servers))return{entries:Object.entries(e.context_servers).map(e=>{let t,[n,r]=e;return cy(r)&&("extension"===r.source||!cw(r))?{note:{code:"zed-extension-server",params:{server:n}}}:c$(n,cy(r)?(t={...r},delete t.source,t):r,{source:"zed-json",flavor:"zed",rawPi:!1})}),notes:n};if(cw(e))return{entries:[c$(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})],notes:n};let o=Object.values(e);return o.length>0&&o.every(cy)&&o.some(cw)?{entries:r(e,{source:"server-map",flavor:"mcp-servers",rawPi:t}),notes:n}:{error:{code:"no-servers-found"}}}(n,t)}(l,!0===s.rawPi);else if(uc.test(l)){if(!("error"in(o=us(`http://${l}`))))for(let e of o.entries)"draft"in e&&e.draft.note("scheme-assumed",{url:`http://${l}`})}else{let e;o=!/\s/.test(l)&&/^[A-Za-z][A-Za-z0-9+.-]+:/.test(l)?us(l):(e=cv(l.replace(/^(?:\$|%|>|❯|PS [^\n>]*>)[ \t]+/,"").replace(/[\u201C\u201D\u201E\u201F\u2033]/g,'"').replace(/[\u2018\u2019\u201A\u201B\u2032]/g,"'").replace(/(^|\s)[\u2013\u2014](?=\S)/g,"$1--").replace(/(^|\s)[\u2013\u2014](?=\s|$)/g,"$1--"))).ok?0===e.words.length?{error:{code:"empty-input"}}:function(e){var t;let n=0,r=(t=e[0],(t?.text.split(/[\\/]/).pop()??"").replace(/\.(?:cmd|exe|ps1)$/i,"").toLowerCase());if(["npx","bunx","pnpx"].includes(r)){let t=1;for(;e[t]?.text.startsWith("-");)t++;let i=e[t]?.text.replace(/^(@?[^@]+)@.*$/,"$1");i&&cF[i]&&e[t+1]?.text==="mcp"&&(n=t,r=cF[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 cH(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 o=cU.get(e[t].text)??e[t].text;if("--"===o||n.length>=2){n.push(...e.slice("--"===o?t+1:t));break}if(!o.startsWith("--")){n.push(e[t]);continue}let s=o.slice(2),l=c_[s];if(!l)return{error:{code:"cli-unknown-option",params:{cli:"pi",option:o}}};if("flag"===l){r.set(s,!0);continue}let a=e[++t];if(void 0===a)return{error:{code:"cli-option-needs-value",params:{cli:"pi",option:o}}};"list"===l?i.set(s,[...i.get(s)??[],a]):r.set(s,a)}let[o,...s]=n,l=r.get("url");if(!o||""===o.text||void 0===l==(0===s.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===l?cq:cZ).find(e=>r.has(e)||i.has(e));if(d)return{error:{code:"cli-option-wrong-transport",params:{cli:"pi",option:`--${d}`,transport:void 0===l?"stdio":"http"}}};let c=new dD("pi-mcp-add",!0);c.name=o.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=cW(r.parts,t);if(!i||""===i[0])return{error:{code:"cli-invalid-pair",params:{cli:"pi",option:`--${e}`,value:r.text}}};let o=n.findIndex(e=>{let[t]=e;return t===i[0]});o>=0?n[o]=i:n.push(i)}return n},p={};if(void 0!==l&&!0!==l){c.transport="http",c.url=cA(l.parts,"pi",!1);let e=u("header");if("error"in e)return e;for(let[t,n]of e)c.headers.push([t,cA(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"),o=a("oauth-client-name");n&&(c.oauth.clientId=cA(n.parts,"pi",!1)),r&&(c.oauth.clientSecret=cA(r.parts,"pi",!0)),i&&(c.oauth.callbackPort=Number(i.text)),o&&(c.oauth.clientName=cA(o.parts,"pi",!1)),p.url=l.parts.some(e=>"variable"===e.type)?"https://placeholder.invalid/":l.text,(i||o)&&(p.oauth={...i?{callbackPort:Number(i.text)}:{},...o?{clientName:o.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,cA(n,"pi",!0)]);let[t,...n]=s;c.command=cA(t.parts,"pi",!1),c.args=n.map(e=>cA(e.parts,"pi",!1));let r=a("cwd");r&&(c.cwd=cA(r.parts,"pi",!1)),p.command=t.text}let h=a("exposure");void 0!==h&&(p.exposure=h.text,c.exposure=ct(h.text)??h.text);let f=a("description");void 0!==f&&(p.description=f.text,c.description=f.text);let m=cs("server",p);return m?{note:{code:"invalid-config",params:{server:o.text,...m}}}:{draft:c}}(t,i.slice(1)));if("claude"===r&&"add"===e)return cH(function(e){let t=cK("claude",e,c1,{asArgAfter:2,variadic:c2});if("error"in t)return{error:t.error};let n=new dD("claude-mcp-add",!1),r=c0(n,"claude",t.values.get("transport"),[...t.positional,...t.afterDashDash],dk);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=cQ(t.values.get("scope")),"http"===r){var i,o;let e;t.lists.has("env")&&n.note("cli-option-wrong-transport",{cli:"claude",option:"--env",transport:"http"});let r=cX(n,t.lists.get("header"),dk,"claude");if(r)return{error:r};let s=t.values.get("client-id");s&&!0!==s&&(n.oauth.clientId=cA(s.parts,dk,!1)),t.values.has("client-secret")&&c4(n);let l=t.values.get("callback-port");l&&!0!==l&&(i=n,Number.isInteger(e=Number(o=l.text))&&e>=1&&e<=65535?i.oauth.callbackPort=e:i.note("callback-port-dropped",{value:o}))}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=cG(n,t.lists.get("env"),dk,"claude");if(e)return{error:e}}return{draft:n}}(t));if("claude"===r&&"add-json"===e)return cH(function(e){let t=cK("claude",e,c8,{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 o=c3(r);if("error"in o)return o;let s=c$(n.text,o.value,{source:"claude-mcp-add-json",flavor:"mcp-servers",rawPi:!1});return"note"in s||(s.draft.scopeHint=cQ(t.values.get("scope")),t.values.has("client-secret")&&"http"===s.draft.transport&&!s.draft.oauth.clientSecret&&c4(s.draft)),s}(t));if("claude"===r&&"add-from-claude-desktop"===e)return{error:{code:"claude-desktop-import"}};if("codex"===r&&"add"===e)return cH(function(e){let t=cK("codex",e,c5,{asArgAfter:1/0,stopAfter:2});if("error"in t)return{error:t.error};let n=t.afterDashDash,r=t.lists.get("env")??[],[i,...o]=t.positional,s=n.length>0?n:o,l=t.values.get("url");if(!i||void 0===l==(0===s.length)||n.length>0&&o.length>0)return{error:{code:"cli-usage",params:{cli:"codex"}}};let a=new dD("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!==l&&!0!==l){if(r.length>0)return{error:{code:"cli-option-wrong-transport",params:{cli:"codex",option:"--env",transport:"http"}}};if(void 0!==cC(l.text))return{note:cE(i.text,l.text)};a.transport="http",a.url=cA(l.parts,dj,!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=cA(n.parts,dj,!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=cG(a,r,dj,"codex");if(e)return{error:e};a.command=cA(s[0].parts,dj,!1),a.args=s.slice(1).map(e=>cA(e.parts,dj,!1))}return{draft:a}}(t));if("gemini"===r&&"add"===e)return cH(function(e){let t=cK("gemini",e,c6,{asArgAfter:2});if("error"in t)return{error:t.error};let n=new dD("gemini-mcp-add",!1),r=c0(n,"gemini",t.values.get("transport"),[...t.positional,...t.afterDashDash],dw);if("string"!=typeof r)return"cli-usage"===r.code?{error:r}:{note:r};if(n.scopeHint=cQ(t.values.get("scope")),"http"===r){t.lists.has("env")&&n.note("cli-option-wrong-transport",{cli:"gemini",option:"--env",transport:"http"});let e=cX(n,t.lists.get("header"),dw,"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=cG(n,t.lists.get("env"),dw,"gemini");if(e)return{error:e}}let i=t.values.get("timeout");for(let e of(i&&!0!==i&&d3(n,Number(i.text)),["trust","description"]))t.values.has(e)&&n.note("cli-option-ignored",{cli:"gemini",option:`--${e}`});let o=e=>{let n=t.values.get(e);return n&&!0!==n?n.text.split(",").map(e=>e.trim()).filter(Boolean):void 0};return cM(n,o("include-tools"),o("exclude-tools")),{draft:n}}(t));if("add"===e||"install"===e)return{error:{code:"cli-unsupported",params:{cli:r}}};if(cB.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]&&cD.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=cV(e[n],10)}if(!r)return{error:{code:"cli-option-needs-value",params:{cli:"code",option:"--add-mcp"}}};let o=c3(r);if("error"in o)return o;t.push(c$(void 0,o.value,{source:"vscode-add-mcp",flavor:"vscode",rawPi:!1}))}return{entries:t,notes:[]}}(e.slice(1)):cH(function(e){let t=new dD("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,cA(r.value,dj,!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=cA(i.parts,dj,!1),t.args=e.slice(n+1).map(e=>cA(e.parts,dj,!1));let o=e.slice(n+1).map(e=>e.text),s=o.some(e=>/^mcp-remote(?:@|$)/.test(e))?o.find(e=>cP.test(e)):void 0;return s&&t.note("mcp-remote-bridge",{url:s}),{draft:t}}(e))}(e.words):{error:function(e){let{code:t,...n}=e;return Object.keys(n).length>0?{code:uu[t],params:n}:{code:uu[t]}}(e.error)}}if("error"in o)return{ok:!1,notes:[o.error]};let a=[...o.notes],d=[],c=[...s.takenNames??[]],u=new Set;for(let e of o.entries){if("note"in e){a.push(e.note);continue}let n=function(e){let t,n=new dq(e);if("stdio"===e.transport&&e.command&&""!==dH(e.command)){let r=n.encode(["command"],e.command),i=e.args.map((e,t)=>n.encode(["args",t],e)),o={};for(let[t,r]of e.env)o[t]=n.encode(["env",t],r);t={command:r,...i.length>0?{args:i}:{},...Object.keys(o).length>0?{env:o}:{},...e.cwd?{cwd:n.encode(["cwd"],e.cwd)}:{}}}else{if("http"!==e.transport||!e.url||""===dH(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 o={},{clientId:s,clientSecret:l,callbackPort:a,clientName:d,callbackUrl:c,scope:u,authServerMetadataUrl:p}=e.oauth;s&&(o.clientId=n.encode(["oauth","clientId"],s)),l&&(o.clientSecret=n.encode(["oauth","clientSecret"],l)),void 0!==a&&(o.callbackPort=a),d&&(o.clientName=n.encode(["oauth","clientName"],d)),c&&(o.callbackUrl=n.encode(["oauth","callbackUrl"],c)),u&&(o.scope=n.encode(["oauth","scope"],u)),p&&(o.authServerMetadataUrl=n.encode(["oauth","authServerMetadataUrl"],p)),t={url:r,...Object.keys(i).length>0?{headers:i}:{},...Object.keys(o).length>0?{oauth:o}:{}}}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,o=!i;o&&(i=function(e){if("url"in e)return d1(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&&d1(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=d4(t,new Set(["-p","--package","-c","--call"]));return e?dG(e):""}case"pnpm":case"yarn":case"bun":case"npm":{let e=t.findIndex(e=>"dlx"===e||"exec"===e||"x"===e),n=e>=0?d4(t.slice(e+1),new Set(["-p","--package"])):void 0;return n?dG(n):""}case"uvx":case"pipx":{let e=d4("pipx"===n&&"run"===t[0]?t.slice(1):t,new Set(["--from","--with","--python","-p","--index-url","--spec"]));return e?dG(e):""}case"uv":{let e=t.indexOf("run"),n=e>=0?d4(t.slice(e+1),new Set(["--with","--directory","--python","-p","--from","--project"])):void 0;return n?d8(n):""}case"docker":case"podman":{let e=t.indexOf("run"),n=e>=0?d4(t.slice(e+1),d2):void 0;if(!n)return"";let r=n.split("/").pop().replace(/[:@].*$/,"");return dQ(r)||r}case"python":case"python3":case"py":{let e=t.indexOf("-m");if(e>=0&&t[e+1])return dG(t[e+1].replace(/_/g,"-"));let n=d4(t,new Set(["-X","-W"]));return n?d8(n):""}case"node":case"deno":case"tsx":case"ts-node":{let e=d4("deno"===n&&"run"===t[0]?t.slice(1):t,new Set(["-r","--require","--import","--loader"]));return e?d8(e):""}default:return dQ(n.replace(/_/g,"-"))||n}}(e.command,t)}(r.config))&&r.notes.push({code:"name-derived",params:{name:i}});let s=(t=i,dV.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";s!==i&&i&&(r.originalName=r.originalName??i,r.notes.push({code:"name-sanitized",params:{original:i,name:s}}));let l=dJ(s,o?[...c,...u]:u);l!==s&&(r.notes.push({code:"name-deduplicated",params:{original:s,name:l}}),s=l),!o&&c.includes(s)&&r.notes.push({code:"name-taken",params:{name:s,suggestedName:dJ(s,[...c,...u])}}),r.name=s;let p=cs(s,function(e){let t=up(e),n=JSON.parse(JSON.stringify(e.config));t.has(dW(["url"]))&&(n.url="https://placeholder.invalid/");let r=n.oauth;return r&&t.has(dW(["oauth","callbackUrl"]))&&delete r.callbackUrl,n}(r));if(p){a.push({code:"invalid-config",params:{server:s,...p}});continue}!function(e){let t=up(e);for(let n of uj(e.config))t.has(dW(n))||e.notes.push({code:"literal-secret",params:{field:dP(n)}});let n=e.config;if("url"in n){for(let[t,r]of Object.entries(n.headers??{})){let n=dM(r);n.length>0&&e.notes.push({code:"header-env-reference",params:{header:t,names:n.join(", ")}})}let t=dM(n.oauth?.clientSecret??"");t.length>0&&e.notes.push({code:"client-secret-env-reference",params:{names:t.join(", ")}})}}(r),u.add(s),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 uf=/^[A-Za-z_][A-Za-z0-9_]*$/;function um(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 o={...e[r]??{}};void 0===n?delete o[i]:o[i]=n,0===Object.keys(o).length?delete e[r]:e[r]=o}function ug(e){let t=up(e);return uj(e.config).filter(e=>dO(e)&&!t.has(dW(e)))}function ux(e){return"string"==typeof e&&""===e.trim()?"missing":"name"}let uv=/^(?:bearer|basic|token)\s+/i;function ub(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.parse(JSON.stringify(e.config)),i=new Map,o=[],s=new Map(ug(e).map(e=>[dP(e),e])),l=[];for(let[e,t]of Object.entries(n)){let n="string"==typeof t?t.trim():"",r=s.get(e);r?uf.test(n)?l.push([r,n]):o.push({code:"field-reference-invalid",params:{field:e,problem:ux(t)}}):o.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():"";uf.test(r)?"select"!==n.kind&&n.targets.every(e=>dO(e.path)&&void 0===e.encoding)?i.set(n.id,{reference:r}):o.push({code:"field-reference-invalid",params:{field:n.id,problem:"target"}}):o.push({code:"field-reference-invalid",params:{field:n.id,problem:ux(t)}});continue}let r=("string"==typeof e?e:n.defaultValue??"").trim();""===r?n.optional?i.set(n.id,void 0):o.push({code:"field-required",params:{field:n.id}}):"select"===n.kind&&n.options&&!n.options.includes(r)?o.push({code:"field-invalid-option",params:{field:n.id}}):i.set(n.id,{text:r})}if(o.length>0)return{ok:!1,notes:o};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(dP(e.path));let o=dW(e.path);if(d.has(o))continue;if(d.add(o),e.parts.some(e=>"string"!=typeof e&&void 0===i.get(e.field))){um(r,e.path,void 0);continue}let s="";for(let t of e.parts){var c,u,p,h;s+="string"==typeof t?t:(c=i.get(t.field),u=e.path,p=""===s,h=e.encoding,"reference"in c?`\${${c.reference}}`:"uri-component"===h?encodeURIComponent(c.text):dO(u)?d$(c.text,{atStart:p}):c.text)}um(r,e.path,s)}for(let[e,t]of l){let n=function(e,t){let[n,r]=t,i=e[n];return void 0===r||"object"!=typeof i||null===i?void 0===r?i:void 0:i[r]}(r,e),i="headers"===e[0]&&"string"==typeof n?n.match(uv)?.[0]??"":"";um(r,e,`${i}\${${t}}`)}for(let e of uj(r))a.add(dP(e));return{ok:!0,config:r,secretPaths:[...a]}}let uy=["command","args","env","cwd","url","headers","oauth"];function uj(e){let t=[];for(let n of function(e){if(!dx(e))return[];let t=[];for(let n of["env","headers"]){let r=e[n];if(dx(r))for(let[e,i]of Object.entries(r))"string"==typeof i&&dv(i)&&""!==i&&(a4(e)||/^(?:bearer|basic|token)\s+\S/i.test(i)||dp(i,dn).masked)&&t.push({kind:"env"===n?"env":"header",name:e})}let n=dx(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&""!==n&&dv(n)&&t.push({kind:"oauth-client-secret"}),"string"==typeof e.url&&dd(e.url,ds).masked&&t.push({kind:"url"}),"string"==typeof e.command&&dp(e.command,ds).masked&&t.push({kind:"command"}),Array.isArray(e.args)&&dg(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:""):[];dg(n).args.forEach((e,r)=>{e!==n[r]&&t.push(["args",r])})}}return t.sort((e,t)=>uy.indexOf(e[0])-uy.indexOf(t[0]))}let uk="PI_WEB_PASSWORD";function uw(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function uS(e){return uw(e)?Object.entries(e).filter(e=>"string"==typeof e[1]):[]}function uC(e){if(!uw(e))return[];if(!("url"in e))return uS(e.env).map(e=>{let[t,n]=e;return{kind:"env",name:t,value:n}});let t=uS(e.headers).map(e=>{let[t,n]=e;return{kind:"header",name:t,value:n}}),n=uw(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&t.push({kind:"oauth-client-secret",value:n}),t}let uE={text:"",rawPi:!1,server:0,values:{},references:{},secretReferences:{}};function uN(e,t,n){let r=uh(e,{rawPi:t});if(!r.ok)return;let i=r.servers[Math.min(n,r.servers.length-1)],{config:o}=i,s="url"in o?["url",o.url]:["command",o.command,o.args??[]];return JSON.stringify([i.source,i.originalName??i.name,s])}function uI(e,t){let n={...e,...t},r=uN(e.text,e.rawPi,e.server);if(void 0!==r&&r===uN(n.text,n.rawPi,e.server))return n;let i={...n,server:0,values:{},references:{},secretReferences:{}};return delete i.name,i}function u$(e){return dy[e.code]??"warning"}function uT(e,t){let n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=e.params??{},o={};for(let[e,t]of Object.entries(i))o[e]="string"==typeof t?lq(t):t;if("string"==typeof i.field&&e.code.startsWith("field-")){let e=r.find(e=>e.id===i.field);e&&(o.field=lq(e.label))}"invalid-config"===e.code&&(o.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}`,o)),"cli-option-wrong-transport"===e.code&&("stdio"===i.transport||"http"===i.transport)&&(o.transport=t(`mcp.transport.${i.transport}`));let s=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),o);return"string"==typeof o.server?t("mcp.importNote.forServer",{server:o.server,note:s}):s}let uM={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"},uR={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"},uL=JSON.stringify({command:"uvx",args:["mcp-server-fetch"]}),uz=JSON.stringify({name:"fetch",command:"uvx",args:["mcp-server-fetch"]}),uA=[{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 '${uz}'`},{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(uL)}`},{source:"vscode-install-link",text:`vscode:mcp/install?${encodeURIComponent(uz)}`},{source:"visual-studio-install-link",text:`vsweb+mcp:/install?${encodeURIComponent(uz)}`},{source:"copilot-app-install-link",text:`ghapp://mcp/install?${encodeURIComponent(uz)}`}];function uW(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?lq(r):r.field===e.id?n:`‹${lq(t.find(e=>{let{id:t}=e;return t===r.field})?.label??r.field)}›`).join("")}))].join(", ")}function uP(e){return"select"!==e.kind&&e.targets.every(e=>dO(e.path)&&void 0===e.encoding)}let uO=/^[A-Za-z_][A-Za-z0-9_]*$/;function uF(){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 uO.test(r)?r:void 0}let uB=/^(?:proxy-)?authorization$/i;function uD(e,t){let n=function(e,t){if(e.startsWith("env.")){let t=e.slice(4);return uO.test(t)?t:uF(t)}let n=function(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];return uF(t,...n)??uF(...n)};if(e.startsWith("headers.")){let t=e.slice(8);return n(uB.test(t)?"TOKEN":t.replace(/^x-/i,""))}if("oauth.clientSecret"===e)return n("CLIENT_SECRET")}(e,t);return n===uk?void 0:n}function uH(e){return e.startsWith("env.")||e.startsWith("headers.")||"oauth.clientSecret"===e}function u_(e,t){let n=e;for(let e of t)n=n.split(e).join(aJ);return{text:n,masked:n!==e}}function uU(e){let{kind:t,name:n}=e;return void 0===n?{kind:t}:{kind:t,name:n}}function uq(e,t){let n=t.files.find(t=>t.scope===e),r=n?.problems.find(ad);return n&&r?{kind:"file-problem",path:n.path,reason:r.reason}:void 0}function uZ(e,t){return e.servers.filter(e=>e.scope===t).map(e=>e.name)}function uK(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 uV(e,t,n){switch(e.kind){case"trust-too-broad":return t(uY[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(uJ[e.kind])}}let uJ={"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"},uY={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 uG(e){return lq(lt(e))}function uX(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}let uQ=[{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"}],u0=new Set(["name-derived","name-sanitized","name-deduplicated","name-taken"]);function u1(e){let{notes:t,fields:n=[]}=e,{t:i}=(0,E.s)();if(0===t.length)return null;let o={error:0,warning:1,info:2},s=[...t].sort((e,t)=>o[u$(e)]-o[u$(t)]);return(0,r.jsx)("ul",{className:"mcp-add-notes",children:s.map((e,t)=>(0,r.jsx)("li",{className:`mcp-add-note is-${u$(e)}`,children:uT(e,i,n)},`${t}\0${e.code}`))})}let u2={"server-invalid":"mcp.add.refused.server-invalid","web-password":"mcp.add.blocked.web-password"};function u4(e){let{data:t,cwd:n,draft:o,busy:s,controlsBusy:l,failure:a,onDraftChange:d,onSubmit:c,onTrustProject:u}=e,{t:p}=(0,E.s)(),h=(0,i.useId)(),f=(0,i.useId)(),m=(0,i.useMemo)(()=>(function e(t,n,r){let i,o=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:ah(r)});let o=r.trustFolder;return o?o.allowed?{kind:"trust-and-write",folder:r.cwd}:n("trust-too-broad"===o.reason?{kind:"trust-too-broad",breadth:o.breadth}:{kind:"folder-not-fresh"}):n({kind:"project-untrusted",trustable:!1})}(n,r),s=e=>uh(t.text,{rawPi:t.rawPi,takenNames:uZ(n,e)}),l=s(t.scope??"global"),a=l.ok?l.servers[Math.min(t.server,l.servers.length-1)]:void 0,d=t.scope??(a?.scopeHint==="project"&&"write"===o.kind?"project":"global");d!==(t.scope??"global")&&(a=(l=s(d)).ok?l.servers[Math.min(t.server,l.servers.length-1)]:void 0);let c={parsed:l,name:t.name??"",scope:d,projectMode:o,..."blocked"===o.kind?{projectBlock:o.block}:{},values:{},pasteSecrets:[],secretReferences:{},fieldProblems:{},secretPaths:[],trustFolder:!1},u=aL(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&&uP(r)?n[r.id]={reference:e}:void 0!==t.values[r.id]&&(n[r.id]=t.values[r.id])}return n}(a,t),f=ug(a).map(dP),m=Object.fromEntries(f.flatMap(e=>{let n=t.secretReferences[e];return void 0===n?[]:[[e,n]]})),g=ub(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]=uO.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=ub(e,r,Object.fromEntries(Object.entries(n).map(e=>{let[t,n]=e;return[t,uO.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):[],o=!1!==r.enabled,s={source:e.source,commandFields:uC(r).filter(e=>{let{value:t}=e;return dT(t)}).map(uU),variableReferences:uC(r).map(e=>({...uU(e),variables:dM(e.value)})).filter(e=>{let{variables:t}=e;return t.length>0}),...r.exposure?{exposure:r.exposure}:{},enabled:o,unfilled:!n?.ok&&e.fields.length>0};if("url"in r){let e=u_(r.url,i);return{...s,transport:"http",target:lq(e.text),envNames:[],headerNames:Object.keys(r.headers??{}),masked:e.masked}}let l=u_(lV(r.command,r.args??[]),i);return{...s,transport:"stdio",target:l.text,...void 0!==r.cwd?{cwd:lq(r.cwd)}:{},envNames:Object.keys(r.env??{}),headerNames:[],masked:l.masked}}(a,h,g),y=g.ok?cs(p,g.config):void 0,j="blocked"===o.kind?o.block:v.length>0?{kind:"secret",fields:v,fixed:!v.every(uH)}:uq("project",n),k=uZ(n,d),w=n.files.find(e=>e.scope===d);if(u)i={kind:"mcp-off"};else if(dV.test(p))if(k.includes(p))i={kind:"name-taken",name:p,suggestedName:dJ(p,k),...w?{path:w.path}:{}};else if(g.ok)if(y)i={kind:"config-invalid",note:{code:"invalid-config",params:"url"===y.problem?{...y,url:b.target}:y}};else if(void 0!==function(e,t){for(let{value:n,...r}of uC(e))if(t.isCommandConfigValue(n)?n.toUpperCase().includes(uk):t.getConfigValueEnvVarNames(n).some(e=>e.toUpperCase()===uk))return r}(g.config,{isCommandConfigValue:dT,getConfigValueEnvVarNames:dM}))i={kind:"web-password"};else if("project"===d&&j)i={kind:"scope",block:j};else{let e=uq(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&&j?e({...t,scope:"global"},n,r):{parsed:l,server:a,name:p,scope:d,projectMode:o,...j?{projectBlock:j}:{},values:h,pasteSecrets:f,secretReferences:m,fill:g,fieldProblems:x,secretPaths:v,preview:b,...i?{submitBlock:i}:{},trustFolder:"project"===d&&"trust-and-write"===o.kind}})(o,t,n),[o,t,n]),g=(0,i.useMemo)(()=>(function(e){let t=uh(e,{rawPi:!0});if(!t.ok)return!1;let n=uh(e,{rawPi:!1});return t.servers.some((e,t)=>e.rawPi&&!(n.ok&&n.servers[t]?.rawPi))})(o.text),[o.text]),{parsed:x,server:v,preview:b,projectBlock:y,submitBlock:j}=m,k=v?[...v.notes,...x.notes].filter(e=>"literal-secret"!==e.code||!m.pasteSecrets.includes(String(e.params?.field))):[],w=void 0!==o.name&&o.name!==v?.name?[]:k.filter(e=>u0.has(e.code)),S=k.filter(e=>!u0.has(e.code)),C=!s&&!l&&void 0===j,N=()=>{C&&c(uK(o,m))},I=e=>d({...o,...e}),$=t.files.find(e=>e.scope===m.scope)?.path??("project"===m.scope&&n?`${n.replace(/[\\/]+$/,"")}/.pi/mcp.json`:"mcp.json"),T=j&&(""!==o.text.trim()||"mcp-off"===j.kind)?function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];switch(e.kind){case"mcp-off":return t("mcp.reason.mcp-off");case"nothing":return t("mcp.add.blocked.nothing");case"name-invalid":return t("mcp.add.nameInvalid");case"name-taken":return t("mcp.add.nameTaken",{name:lq(e.name),path:e.path?uG(e.path):"mcp.json"});case"fields":return t("mcp.add.blocked.fields",{fields:e.fields.map(lq).join(", ")});case"field-invalid":return t("mcp.add.blocked.fieldsInvalid",{fields:e.fields.map(lq).join(", ")});case"config-invalid":return uT(e.note,t,n);case"web-password":return t("mcp.add.blocked.web-password");case"scope":return uV(e.block,t,uG)}}(j,p,v?.fields):void 0,M=y?.kind==="project-untrusted"&&y.trustable&&u,R=b?"http"===b.transport?b.headerNames:b.envNames:[];return(0,r.jsxs)(sp,{title:p("mcp.add.title"),catalogs:uQ,target:(0,r.jsxs)(sc,{value:m.scope,label:p("config.saveTo"),options:[{value:"global",label:uX("global",p)},{value:"project",label:uX("project",p),disabled:void 0!==y&&"project"!==m.scope}],path:uG($),disabledReason:y?uV(y,p,uG):null,onChange:e=>I({scope:e}),children:[M&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(sb,{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:uG(m.projectMode.folder)})})]}),inputLabel:p("mcp.add.inputLabel"),inputId:"mcp-add-source",placeholder:p("mcp.add.placeholder"),value:o.text,canSubmit:C,onValueChange:e=>d(uI(o,{text:e})),onSubmit:N,examplesLabel:p("mcp.add.examples"),examples:""===o.text.trim()?uA.map(e=>{let{source:t,text:n}=e;return{label:p(uR[t]),value:n}}):[],multiline:!0,children:[g&&(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:o.rawPi,onChange:e=>d(uI(o,{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")}),o.rawPi&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.rawPiOn")})]})]}),!x.ok&&""!==o.text.trim()&&(0,r.jsx)(u1,{notes:x.notes}),x.ok&&x.servers.length>1&&(0,r.jsxs)(so,{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=>I({server:Number(e.target.value),name:void 0,values:{},references:{},secretReferences:{}}),children:x.servers.map((e,t)=>(0,r.jsx)("option",{value:t,children:lq(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)(so,{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=>I({name:e.target.value})})}),(0,r.jsx)(u1,{notes:w,fields:v.fields}),j?.kind==="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(sb,{size:"small",onClick:()=>I({name:j.suggestedName}),children:p("mcp.add.useName",{name:lq(j.suggestedName)})})})]}),v&&b&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(si,{children:p("mcp.add.preview")}),(0,r.jsxs)(ss,{children:[(0,r.jsx)(sl,{label:p("mcp.add.readAs"),children:p(uR[b.source])}),(0,r.jsx)(sl,{label:p("mcp.detail.transport"),children:p(`mcp.transport.${b.transport}`)}),(0,r.jsx)(sl,{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)(sl,{label:p("mcp.detail.cwd"),mono:!0,children:b.cwd}),R.length>0&&(0,r.jsx)(sl,{label:"http"===b.transport?p("mcp.detail.headers"):p("mcp.detail.env"),children:(0,r.jsx)(u8,{names:R})}),b.commandFields.length>0&&(0,r.jsx)(sl,{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=lG(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)(sl,{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:lQ(b.variableReferences).map(e=>{let{variable:t,field:n}=e,i=lG(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p("mcp.server.variableIn",{variable:lq(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)(u1,{notes:S,fields:v.fields}),v.fields.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(si,{children:p("mcp.add.fields")}),v.fields.map(e=>{var t;let n;return(0,r.jsx)(u3,{field:e,fields:v.fields,draft:o,suggestedName:(t=m.name,(n=e.targets[0])?uD(dP(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)(si,{children:p("mcp.add.secrets")}),m.pasteSecrets.map(e=>{var t,n;let i;return(0,r.jsx)(u5,{label:e,draft:o,suggestedName:uD(e,m.name),stored:m.fill?.ok?(t=m.fill.config,void 0!==(i="oauth.clientSecret"===(n=e)?"url"in t?t.oauth?.clientSecret:void 0:n.startsWith("headers.")?"url"in t?t.headers?.[n.slice("headers.".length)]:void 0:n.startsWith("env.")&&"command"in t?t.env?.[n.slice("env.".length)]:void 0)&&dn(i)?i:void 0):void 0,problem:m.fieldProblems[e],onDraftChange:d},e)})]})]}),(0,r.jsx)(sb,{variant:"primary",className:"is-pushed-right",disabled:!C,"aria-busy":s||void 0,"aria-describedby":T?h:void 0,onClick:N,children:s?p("mcp.add.adding"):m.trustFolder?p("mcp.add.buttonTrust"):p("mcp.add.button")}),T&&(0,r.jsx)("p",{id:h,className:`mcp-config-line ${j?.kind==="scope"?"is-warning":"is-dim"}`,children:T}),v&&!j&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:p("mcp.add.afterAdd")}),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(uY[e.breadth.kind],{path:uG(e.breadth.path)});if("secret-global-only"===e.reason&&e.fields)return t(e.fields.every(uH)?"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:lq(e.name),path:e.path?uG(e.path):"mcp.json"});let n=e.reason?u2[e.reason]:void 0;return n?t(n,{error:lq(e.error)}):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):lq(e.error)}(a,p)]}),a.trustKept&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.trustKept",{folder:uG(a.trust?.decisionPath??n??"")})}),a.notes&&a.notes.length>0&&(0,r.jsx)(u1,{notes:a.notes,fields:v?.fields}),"name-taken"===a.reason&&a.suggestedName&&j?.kind!=="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(sb,{size:"small",onClick:()=>I({name:a.suggestedName}),children:p("mcp.add.useName",{name:lq(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(lq).join(", ")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(sb,{variant:"danger",size:"small",disabled:s||l||void 0!==j,onClick:()=>c(uK(o,m,a.names)),children:p("mcp.add.hostEnv.confirm")})})]})]})]})}function u8(e){let{names:t}=e,{t:n}=(0,E.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:lq(e)},e))}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.detail.valuesHidden")})]})}function u3(e){let t,{field:n,fields:o,draft:s,suggestedName:l,problem:a,onDraftChange:d}=e,{t:c}=(0,E.s)(),u=(0,i.useId)(),p=a?{"aria-invalid":!0,"aria-describedby":u}:{},h=uP(n),f=h?s.references[n.id]:void 0,m=void 0!==f,g=lq(n.label),x=s.values[n.id]??n.defaultValue??"",v=uM[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?uW(n,o,"${"+f+"}",!0):void 0:uW(n,o,`‹${c("mcp.add.field.slot")}›`),j=e=>d({...s,values:{...s.values,[n.id]:e}}),k=e=>{let t={...s.references};void 0===e?delete t[n.id]:t[n.id]=e,d({...s,references:t})};return(0,r.jsxs)("div",{className:"mcp-add-field",children:[(0,r.jsx)(so,{label:g,children:m?(0,r.jsx)("input",{className:"mcp-add-input","aria-label":c("mcp.add.field.variableName",{field:g}),value:f,placeholder:l??"GITHUB_TOKEN",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...p,onChange:e=>k(e.target.value)}):"select"===n.kind?(0,r.jsxs)("select",{className:"mcp-add-input","aria-label":g,value:x,...p,onChange:e=>j(e.target.value),children:[!n.options?.includes(x)&&(0,r.jsx)("option",{value:"",children:c("mcp.add.field.choose")}),(n.options??[]).map(e=>(0,r.jsx)("option",{value:e,children:lq(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?lq(n.placeholder):void 0,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...p,onChange:e=>j(e.target.value)})}),a&&(0,r.jsx)("span",{id:u,className:"mcp-config-line is-error",children:uT(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:lq(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:lq(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?l??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:c("mcp.add.field.useVariable")})]})]})}function u5(e){let{label:t,draft:n,suggestedName:o,stored:s,problem:l,onDraftChange:a}=e,{t:d}=(0,E.s)(),c=(0,i.useId)(),u=n.secretReferences[t],p=void 0!==u,h=lq(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?o??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("mcp.add.field.useVariable")})]}),p&&(0,r.jsx)(so,{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:o??"API_TOKEN",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...l?{"aria-invalid":!0,"aria-describedby":c}:{},onChange:e=>f(e.target.value)})}),l&&(0,r.jsx)("span",{id:c,className:"mcp-config-line is-error",children:uT(l,d)}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p?void 0!==s?d("mcp.add.secret.storedAs",{value:lq(s)}):d("mcp.add.field.variableHint"):d("mcp.add.secret.asPasted")})]})}let u6=new Set(["done","failed","cancelled","expired"]);function u9(e){var t;return e?.flow!==void 0&&!e.gone&&(t=e.flow.phase,!u6.has(t))}let u7={"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"},pe={"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"},pt={connecting:"mcp.signIn.phase.connecting",starting:"mcp.signIn.phase.starting",finishing:"mcp.signIn.phase.finishing"},pn={"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 pr(e,t,n){var r;let i={...e,flow:t,deadlineAt:n+t.expiresInMs,gone:!1};return r=t.phase,u6.has(r)&&(delete i.pasteError,delete i.cancelError,i.pasting&&(i.pasting=!1),i.cancelling&&(i.cancelling=!1)),i}function pi(e){return"sign-in-unknown"===e.reason}async function po(e,t,n,r){var i;let o,s;try{o=await n(e,{...t,cache:"no-store",signal:r})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{s=await o.json()}catch{return{ok:!1,error:{error:`HTTP ${o.status}`}}}return o.ok&&null!==(i=s)&&"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:s}:{ok:!1,error:aj(s,o.status)}}function ps(e,t,n,r,i){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},s=t.method??"GET";return ak(r=>po(e,t,n,r),()=>({ok:!1,error:{error:`${s} ${e} did not answer within ${i} ms`,timedOut:!0}}),i,r,o)}function pl(e){return`/api/mcp/sign-in/${encodeURIComponent(e)}`}function pa(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?pe[e.reason]:void 0;return r?t(r):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function pd(e){let{server:t,run:n,block:o,signOutBlock:s,controlsBusy:l,signingOut:a,onSignIn:d,onSignOut:c,onPaste:u,onCancel:p}=e,{t:h}=(0,E.s)(),f=(0,i.useId)(),m=(0,i.useId)(),g=(0,i.useId)(),x=(0,i.useRef)(null),v=(0,i.useRef)(null),b=u9(n),y=(0,i.useRef)(b);if((0,i.useEffect)(()=>{let e=y.current;y.current=b,!e&&b?oK(document,v.current):e&&!b&&oK(document,x.current)},[b]),!t.usesOAuth)return(0,r.jsx)(sl,{label:h("mcp.detail.signIn"),children:void 0!==t.authProvider?h("mcp.signIn.provider",{provider:lq(t.authProvider)}):h("mcp.signIn.header")});let j=n?.flow,k=n?.starting===!0,w=void 0!==j&&(j.scope!==t.scope||j.name!==t.name),S=(t.oauthStateStored??t.signedIn)!==!1,C=k||a||void 0!==o,N=l||k||void 0!==s,I=j?.phase==="finishing";return(0,r.jsx)(sl,{label:h("mcp.detail.signIn"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line",children:h(!0===t.signedIn?"mcp.signIn.signedIn":!1===t.signedIn?t.oauthStateStored?"mcp.signIn.registrationOnly":"mcp.signIn.notSignedIn":"mcp.signIn.unknown")}),j&&b&&w&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.shared",{name:lq(j.name)})}),j&&b&&("authorize"===j.phase?(0,r.jsx)(pc,{flow:j,pasting:n?.pasting===!0,pasteError:n?.pasteError,onPaste:e=>u(t,j.flowId,e)},j.flowId):(0,r.jsx)("span",{role:"status",className:"mcp-config-line",children:h(pt[j.phase]??"mcp.signIn.phase.connecting")})),j&&b&&I&&(0,r.jsx)("span",{id:g,className:"mcp-config-line is-dim",children:h("mcp.signIn.phase.noCancel")}),j&&!b&&!n?.gone&&(0,r.jsx)(pu,{flow:j,shared:w}),n?.gone&&(0,r.jsx)("span",{role:"alert",className:"mcp-config-line is-warning",children:h("mcp.signIn.gone")}),n?.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.requestFailed")," ",pa(n.error,h)]}),b&&n?.cancelError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.cancelFailed")," ",pa(n.cancelError,h,"mcp.signIn.cancelTimedOut")]}),n?.signOutError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.signOutFailed")," ",pa(n.signOutError,h,"mcp.actionTimedOut")]}),n?.signedOut&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line",children:h(n.signedOut.removed?"mcp.signIn.signedOutDone":"mcp.signIn.signedOutNothing")}),o&&(0,r.jsx)("span",{id:f,className:"mcp-config-line is-dim",children:h(u7[o])}),!o&&s&&S&&!b&&(0,r.jsx)("span",{id:m,className:"mcp-config-line is-dim",children:h(u7[s])}),(0,r.jsxs)("div",{className:"mcp-sign-in-actions",children:[b&&j?(0,r.jsx)(sb,{ref:v,size:"small",disabled:n?.cancelling===!0||I,"aria-busy":n?.cancelling===!0||void 0,"aria-describedby":I?g:void 0,onClick:()=>p(t,j.flowId),children:h(n?.cancelling?"mcp.signIn.cancelling":"mcp.signIn.cancel")}):(0,r.jsx)(sb,{ref:x,size:"small",variant:"primary",disabled:C,"aria-busy":k||void 0,"aria-describedby":o?f:void 0,onClick:()=>d(t),children:h(k?"mcp.signIn.starting":"mcp.signIn.button")}),S&&!b&&(0,r.jsx)(sb,{size:"small",disabled:N,"aria-busy":a||void 0,"aria-describedby":s?o?f:m:void 0,onClick:()=>c(t),children:h(a?"mcp.signIn.signingOut":"mcp.signIn.signOut")})]}),!o&&!b&&S&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.replaces")}),S&&!s&&!b&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.signOutExplain")})]})})}function pc(e){let{flow:t,pasting:n,pasteError:o,onPaste:s}=e,{t:l}=(0,E.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&&oK(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)(sL,{message:l("mcp.signIn.authorize.message"),hint:p?(0,r.jsxs)(r.Fragment,{children:[l("mcp.signIn.authorize.link")," ",(0,r.jsx)("a",{href:p,target:"_blank",rel:"noopener noreferrer",children:lq(p)})]}):(0,r.jsxs)(r.Fragment,{children:[l("mcp.signIn.authorize.notALink")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:lq(t.authorizationUrl??"")})]}),value:a,placeholder:l("mcp.signIn.paste.placeholder"),inputLabel:l("mcp.signIn.paste.label"),submitLabel:l(n?"mcp.signIn.paste.checking":"mcp.signIn.paste.submit"),disabled:n,plainEnterSubmits:!1,inputRef:c,onValueChange:d,onSubmit:()=>s(a)}),o&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[l("mcp.signIn.paste.refused")," ",pa(o,l,"mcp.signIn.paste.timedOut"),"redirect-denied"===o.reason&&o.error&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:lq(o.error)})]})]}),t.redirectUrl&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:l("mcp.signIn.authorize.redirect",{url:lq(t.redirectUrl)})}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:l("mcp.signIn.authorize.wait")})]})}function pu(e){let{flow:t,shared:n}=e,{t:i}=(0,E.s)(),o=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 pn[e.failure??"internal"];case"cancelled":return"mcp.signIn.cancelled";case"expired":return"mcp.signIn.expired";default:return}}(t,n);if(!o)return null;let s=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return"done"===e.phase?!t&&e.result&&"connected"!==e.result.state?"warning":"on":"failed"===e.phase?"error":"expired"===e.phase?"warning":"off"}(t,n);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{role:"status",className:"error"===s?"mcp-config-line is-error":"warning"===s?"mcp-config-line is-warning":"mcp-config-line",children:i(o,{name:lq(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:lq(t.error)})]})]})}function pp(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function ph(e){return lq(lt(e))}function pf(e,t){let{key:n,params:r}=e;return r?t(n,void 0===r.path?r:{...r,path:ph(r.path)}):t(n)}function pm(e,t){return e.timedOut?t("mcp.loadTimedOut"):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function pg(e,t){return e.timedOut?t("mcp.actionTimedOut"):pm(e,t)}function px(){if("u"<typeof document)return null;let e=document.activeElement;return e instanceof HTMLButtonElement||e instanceof HTMLSelectElement?e:null}function pv(e){let{cwd:t,onClose:n,embedded:o=!1,trust:s,onTrustProject:l,onProjectTrustChanged:a}=e,[d,c]=(0,i.useState)({state:"loading"}),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(()=>oU("mcp",t)),[m,g]=(0,i.useState)({saving:!1,error:null}),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(null),[w,S]=(0,i.useState)(null),[C,E]=(0,i.useState)(null),[N,I]=(0,i.useState)({}),$=(0,i.useRef)(0),T=(0,i.useRef)(null),M=(0,i.useRef)(null),R=(0,i.useRef)(null),L=(0,i.useRef)(new Map),[z,A]=(0,i.useState)({}),W=(0,i.useRef)(z);W.current=z;let[P,O]=(0,i.useState)(0),[F,B]=(0,i.useState)(!1),[D,H]=(0,i.useState)(uE),_=(0,i.useRef)(D);_.current=D;let[U,q]=(0,i.useState)(null),[Z,K]=(0,i.useState)(null),V=(0,i.useRef)(!0),J=(0,i.useRef)(d);J.current=d;let Y=(0,i.useCallback)(async()=>{let e=++$.current;T.current?.abort();let n=new AbortController;T.current=n,p(!0);let r=await aN(t,void 0,n.signal);if(e===$.current){if(p(!1),!r.ok)return void c({state:"failed",error:r.error});c({state:"loaded",data:r.data,...r.projectError?{projectError:r.projectError}:{}}),f(e=>ap(ac(r.data,!!t),e))}},[t]),G=li(s);(0,i.useEffect)(()=>(Y(),()=>{$.current+=1,T.current?.abort()}),[Y,G]);let X=(0,i.useCallback)(async e=>{let t=new AbortController;M.current=t,g({saving:!0,error:null,target:"preference"});let n=await aT(e,void 0,t.signal);M.current===t&&(M.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;M.current=t,g({saving:!0,error:null,target:"mode"});let n=await aM(e,void 0,t.signal);M.current===t&&(M.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;M.current=t,g({saving:!0,error:null,target:"inlineBudget"});let n=await aR(e,void 0,t.signal);M.current===t&&(M.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=L.current;return V.current=!0,()=>{V.current=!1,M.current?.abort(),M.current=null,R.current?.abort(),R.current=null,e.clear()}},[]);let et=(0,i.useCallback)(async e=>{let n=l2(e);if(L.current.has(n))return;let r={};L.current.set(n,r),I(e=>({...e,[n]:{...e[n],running:!0,startedAt:Date.now(),error:void 0,queueTimedOut:void 0,configKey:void 0}}));let i=J.current,o="loaded"===i.state&&i.data.project?t:null,s=await aV({scope:e.scope,name:e.name},o);if(L.current.get(n)!==r)return;L.current.delete(n),I(t=>({...t,[n]:function(e,t,n){let r=e?.signedOutAt,i={...e?.startedAt!==void 0?{startedAt:e.startedAt}:{},...void 0!==r?{signedOutAt:r}:{}};if(void 0!==r&&(e?.startedAt??0)<=r)return{running:!1,...i};let o=e?.response?{response:e.response}:{};return t.ok?t.data.result.queueTimedOut?{running:!1,...i,...o,queueTimedOut:!0,configKey:t.data.configKey}:{running:!1,...i,response:t.data}:{running:!1,...i,...o,error:t.error,...void 0!==n?{configKey:n}:{}}}(t[n],s,e.configKey)}));let l=J.current,a="loaded"===l.state?l.data.servers.find(e=>l2(e)===n):void 0;(s.ok?a?.configKey===s.data.configKey:void 0===s.error.reason||s.error.timedOut)||Y()},[t,Y]),en=(0,i.useCallback)((e,n)=>{$.current+=1,T.current?.abort(),p(!1),c(t=>({state:"loaded",data:e,..."loaded"===t.state&&t.projectError?{projectError:t.projectError}:{}})),f(r=>ap(ac(e,!!t),n??r))},[t]),er=(0,i.useCallback)(async e=>{let n=l2(e),r=W.current[n];if(r?.starting||u9(r))return;A(e=>({...e,[n]:{starting:!0}}));let i=J.current,o="loaded"===i.state&&i.data.project?t:null,s=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 ps("/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},o);V.current&&(A(e=>({...e,[n]:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();return e.ok?pr({},e.data,t):{error:e.error}}(s)})),s.ok||void 0===s.error.reason||s.error.timedOut||Y())},[t,Y]),ei=(0,i.useCallback)(async(e,t,n)=>{let r=l2(e);A(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 ps(pl(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirectUrl:t})},n,r,i)}(t,n);V.current&&A(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?{...pr(i,n.data,r),pasteError:void 0}:pi(n.error)?{...i,gone:!0}:{...i,pasteError:n.error}}(e[r],t,i);return void 0===n||n===e[r]?e:{...e,[r]:n}})},[]),eo=(0,i.useCallback)(async(e,t)=>{let n=l2(e);A(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 ps(pl(e),{method:"DELETE"},t,n,r)}(t);V.current&&A(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?pr(i,n.data,r):pi(n.error)?{...i,gone:!0}:{...i,cancelError:n.error}}(e[n],t,r);return void 0===i||i===e[n]?e:{...e,[n]:i}})},[]),es=Object.entries(z).flatMap(e=>{let[t,n]=e;return u9(n)&&n.flow?[`${t}\u0001${n.flow.flowId}`]:[]}).join("\x02");(0,i.useEffect)(()=>{if(!es)return;let e=new AbortController,t=setTimeout(async()=>{for(let t of es.split("\x02")){let[n,r]=t.split("\x01"),i=W.current[n]?.version??0,o=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 ps(pl(e),{},t,n,r)}(r,void 0,e.signal);if(e.signal.aborted)return;A(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?pr(e,n.data,r):pi(n.error)||void 0!==e.deadlineAt&&r>e.deadlineAt+5e3?{...e,gone:!0}:e:e}(e[n],r,o,Date.now(),i);return void 0===t||t===e[n]?e:{...e,[n]:t}})}O(e=>e+1)},1e3);return()=>{clearTimeout(t),e.abort()}},[es,P]);let el=(0,i.useRef)(z);(0,i.useEffect)(()=>{let e=el.current;el.current=z,Object.keys(z).some(t=>{var n,r;return n=e[t],r=z[t],u9(n)&&!u9(r)})&&Y()},[z,Y]);let ea=(0,i.useCallback)(async(e,n,r)=>{R.current?.abort();let i=new AbortController;R.current=i,v(n);let o=J.current,s="loaded"===o.state&&o.data.project?t:null,l=await aF(e,s,void 0,i.signal);if(R.current===i)return R.current=null,v(null),l.ok?en(l.data,r?.(l.data)):Y(),l},[en,t,Y]),ed=(0,i.useCallback)(async(e,t)=>{let n=l2(e),r=px();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}),E({control:r}))},[ea]),ec=(0,i.useCallback)(async(e,t)=>{let n=l2(e),r=px();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}),E({control:r}))},[ea]),eu=(0,i.useCallback)(async e=>{let t=l2(e),n=px();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}),E({control:n});return}let i=r.data.undo;i&&S({...i,undoing:!1})},[ea]),ep=(0,i.useCallback)(async()=>{if(!w)return;let e=px();y(null),k(null),S({...w,undoing:!0,error:void 0});let t=await ea({action:"undo",token:w.token},"undo",e=>e.restored?l2(e.restored):void 0);t&&(S(e=>e?.token!==w.token?e:t.ok?null:{...e,undoing:!1,error:t.error}),t.ok||E({control:e}))},[ea,w]),eh=(0,i.useCallback)(async e=>{let t=l2(e),n=px();y(null),k(null),A(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(A(e=>({...e,[t]:r.ok?{signedOut:{removed:r.data.signedOut?.removed===!0}}:{...e[t],signOutError:r.error}})),r.ok){let e=Date.now();I(n=>{let r=function(e,t){if(e)return{running:e.running,...void 0!==e.startedAt?{startedAt:e.startedAt}:{},signedOutAt:t}}(n[t],e);return r?{...n,[t]:r}:n})}E({control:n})}},[ea]),ef=(0,i.useCallback)(async e=>{let n=px(),r=_.current;y(null),k(null),q(null);let i=await ea(e,"add",e=>e.added?l2(e.added):void 0);if(!i)return;let o=_.current!==r;if(!i.ok){o||q(i.error),i.error.trust&&t&&a?.(t,i.error.trust),E({control:n});return}let{added:s,trust:l,trustedFolder:d}=i.data;if(B(!1),o||H(uE),E({control:null,toSelectedRow:!0}),!s)return;K({...s,key:l2(s),...d&&t?{trustedFolder:t}:{}}),l&&t&&a?.(t,l);let c=i.data.servers.find(e=>l2(e)===l2(s));c&&!aD(c,i.data)&&et(c)},[t,a,ea,et]),em=w?.token,eg=w?.expiresInMs;(0,i.useEffect)(()=>{if(void 0===em||void 0===eg)return;let e=setTimeout(()=>S(e=>e?.token===em?null:e),eg);return()=>clearTimeout(e)},[em,eg]);let ex=(0,i.useCallback)(async(e,t,n)=>{let{targets:r,keptOff:i}={targets:lr(t,n,e=>e.enabled).filter(n?aP:aW),keptOff:n?t.filter(e=>!e.enabled&&aW(e)&&!aP(e)).length:0},o=px();if(y(null),k(i>0?{scope:e,keptOff:i,failures:[],total:0}:null),0===r.length)return;let s=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(!s)return;if(E({control:o}),!s.ok)return void k({scope:e,keptOff:i,failures:[],total:r.length,error:s.error});let l=s.data.results??[],a=l.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:l.length}:null)},[ea]);return(0,i.useEffect)(()=>{h&&oq("mcp",h,t)},[t,h]),(0,r.jsx)(pb,{cwd:t,load:d,selected:h,refreshing:u,embedded:o,codemodeSave:m,busy:x,actionError:b,groupStatus:j,undo:w,focusBack:C,tests:N,signIns:z,adding:F,addDraft:D,addFailure:U,added:Z,onAddOpen:()=>{B(!0),K(null),y(null)},onAddDraftChange:e=>{_.current=e,H(e),q(null)},onAddSubmit:e=>void ef(e),onTest:e=>void et(e),onSignIn:e=>void er(e),onSignOut:e=>void eh(e),onSignInPaste:(e,t,n)=>void ei(e,t,n),onSignInCancel:(e,t)=>void eo(e,t),onSelect:e=>{f(e),y(null),B(!1),K(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),onExposureChange:(e,t)=>void ec(e,t),onGroupSwitch:(e,t,n)=>void ex(e,t,n),onRemove:e=>void eu(e),onUndo:()=>void ep(),onTrustProject:l,onClose:n})}function pb(e){var t,n,o,s;let l,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:j={},signIns:k={},adding:w=!1,addDraft:S=uE,addFailure:C=null,added:N=null,onAddOpen:I=()=>{},onAddDraftChange:$=()=>{},onAddSubmit:T=()=>{},onSelect:M,onRefresh:R,onCodemodeChange:L,onCodemodeModeChange:z=()=>{},onCodemodeInlineBudgetSave:A=()=>{},onServerSwitch:W=()=>{},onExposureChange:P=()=>{},onGroupSwitch:O=()=>{},onRemove:F=()=>{},onUndo:B=()=>{},onTest:D=()=>{},onSignIn:H=()=>{},onSignOut:_=()=>{},onSignInPaste:U=()=>{},onSignInCancel:q=()=>{},onTrustProject:Z,onClose:K}=e,{t:V}=(0,E.s)(),J=(0,i.useId)(),Y=(0,i.useId)(),G="loaded"===u.state?(t=u.data,l=!1,a=t.servers.map(e=>{var t;let n=j[l2(e)]?.response;if(!n||n.configKey!==e.configKey||e.status&&("test"===(t=e.status).origin?t.testedAt:t.closedAt??t.updatedAt)>=n.result.testedAt)return e;l=!0;let r={...n.result,origin:"test"};return{...e,status:r}}),l?{...t,servers:a}:t):void 0,X=G?ac(G,!!c):[],Q=G?{mcpAvailable:G.mcp.available,projectServersLoad:l4(G.project)}:void 0,ee=X.flatMap(e=>e.servers),et=ee.find(e=>l2(e)===p),en=N?ee.find(e=>l2(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,eo=G?.files.find(e=>"project"===e.scope),es=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,eo):void 0,el=Z&&ah(G?.project)?Z:void 0,ea=es?.kind==="untrusted"&&void 0!==el,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&&oK(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?oK(document,ep.current):void 0!==e&&void 0===eh&&oK(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=au(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&&l4(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,o=G.files,n>0?"mcp.selectItem":o.some(e=>e.problems.some(ad))?"mcp.emptyFileProblem":"mcp.empty"):void 0,ey=null!==g||h||m.saving,ej=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(y&&!ey&&ej.current!==y)if(ej.current=y,y.toSelectedRow)oK(document,ed.current??ec.current);else{var e,t,n;e=document,t=y.control,n=ed.current??ec.current,t&&oK(e,t.isConnected&&!t.disabled?t:n)}},[y,ey]);let ek=e=>G?az(e,G):void 0,ew=!!G&&aL(G.mcp),eS=X.find(e=>"project"===e.scope)?.servers??[],eC=ek("project"),eE=es?.kind==="untrusted"?[pf(es,V),eC&&"mcp-off"!==eC&&eS.length>0?V(aA[eC]):null].filter(Boolean).join(" "):"";return(0,r.jsxs)(o0,{embedded:f,title:V("settings.mcp"),subtitle:c?lt(c):void 0,closeLabel:V("i18n.close"),onClose:K,children:[(0,r.jsxs)("div",{className:"mcp-config-notices",children:[er&&(0,r.jsxs)(sh,{id:J,children:[pf(er,V),ew&&(0,r.jsxs)(r.Fragment,{children:[" ",V(aA["mcp-off"])]}),G&&!G.mcp.available&&G.mcp.detail&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:lq(G.mcp.detail)})]})]}),ei&&(0,r.jsx)(sh,{children:V("mcp.hostInactive",{path:ph(ei.cwd),owner:ph(ei.owner)})}),"loaded"===u.state&&u.projectError&&(0,r.jsx)(sh,{children:V("mcp.projectNotListed",{reason:pm(u.projectError,V)})}),es?.kind==="untrusted"&&(0,r.jsx)(sf,{id:Y,message:eE,trustLabel:V("mcp.trust.trustButton"),onTrust:el}),es?.kind==="inherited"&&(0,r.jsx)(sh,{children:pf(es,V)}),b&&(0,r.jsxs)(sh,{action:b.error?.reason==="undo-unavailable"?void 0:(0,r.jsx)(sb,{ref:ep,size:"small",onClick:B,disabled:b.undoing||ey,children:b.undoing?V("mcp.undoing"):V("mcp.undo")}),children:[V("mcp.removed",{name:lq(b.name),path:ph(b.path)}),b.error&&(0,r.jsxs)(r.Fragment,{children:[" ",V("mcp.undoFailed")," ",pg(b.error,V)]})]}),N&&G&&en&&(0,r.jsx)(py,{added:N,cwd:c,server:en,testing:j[N.key]?.running===!0,signIn:k[N.key],signingOut:g===`sign-out:${N.key}`,signInBlock:en?aD(en,G):void 0,onSignIn:H})]}),(0,r.jsxs)(o1,{children:[(0,r.jsxs)(o2,{children:[(0,r.jsx)(o4,{children:"loading"===u.state?(0,r.jsx)("div",{className:"config-sidebar-message",children:V("i18n.loading")}):"failed"===u.state?(0,r.jsxs)("div",{role:"alert",className:"config-sidebar-message is-error",children:[V("mcp.loadFailed")," ",pm(u.error,V)]}):G&&Q?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-sidebar-group",children:(0,r.jsx)(pj,{codemode:G.codemode,active:!w&&p===l1,rowRef:ed,onSelect:M})}),X.map(e=>{let t=ek(e.scope);return(0,r.jsx)(pk,{group:e,context:Q,selected:w?null:p,selectedRowRef:ed,block:t,blockNoticeId:"mcp-off"===t?er?J:void 0:t&&es?.kind==="untrusted"?Y:void 0,busy:g,controlsBusy:ey,status:v?.scope===e.scope?v:null,onSelect:M,onGroupSwitch:O},e.scope)})]}):null}),G&&(0,r.jsx)(sj,{ref:ec,active:w,onClick:I,children:V("mcp.add.action")})]}),(0,r.jsx)(sg,{children:(0,r.jsx)(o7,{className:"is-fill",children:G&&Q&&ev&&eb?w?(0,r.jsx)(u4,{data:G,cwd:c,draft:S,busy:"add"===g,controlsBusy:ey,failure:C,onDraftChange:$,onSubmit:T,onTrustProject:el}):p===l1?(0,r.jsx)(pz,{codemode:G.codemode,autoEnable:ev,save:m,serverBusy:null!==g,onChange:L,onModeChange:z,onInlineBudgetSave:A}):et?(0,r.jsx)(pE,{server:et,context:Q,codemode:G.codemode,toolSearchDisabled:G.toolSearchDisabled,autoEnable:ev,block:ek(et.scope),savedWhileOff:!G.mcp.available&&!ew,busy:g,controlsBusy:ey,actionError:x?.key===l2(et)?x.failure:null,test:(s=j[l2(et)],s&&void 0!==s.configKey&&s.configKey!==et.configKey?{running:s.running,...s.response?{response:s.response}:{}}:s),testBlock:aD(et,G),signIn:k[l2(et)],signInBlock:aD(et,G),signOutBlock:(d=az(et.scope,G))||(void 0===et.invalidError&&et.validated?void 0:"invalid"),onSwitch:W,onExposureChange:P,onRemove:F,onTest:D,onSignIn:H,onSignOut:_,onSignInPaste:U,onSignInCancel:q},l2(et)):(0,r.jsx)(sm,{children:"mcp.empty"===eb?V(eb,{globalPath:ph(ex?.path??"~/.pi/agent/mcp.json")}):V(eb)}):null})})]}),(0,r.jsxs)(sx,{status:em.length>0?(0,r.jsx)(sv,{tone:em.some(e=>{let{problem:t}=e;return ad(t)})?"error":"warning",summary:1===em.length?V("mcp.footer.fileProblem"):V("mcp.footer.fileProblems",{count:em.length}),details:em.map(e=>{let{file:t,problem:n}=e,i=l0(n,t.realPath);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:ph(t.path)})," ",V(`mcp.fileProblem.${n.reason}`),i&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:i})]})]})})}):(0,r.jsx)(sv,{summary:eg.total>0?V("mcp.serverCount",{enabled:eg.enabled,total:eg.total}):""}),children:[!f&&(0,r.jsx)(sb,{onClick:K,children:V("i18n.close")}),(0,r.jsx)(sb,{variant:"secondary",onClick:R,disabled:ey,children:V("i18n.refresh")})]})]})}function py(e){let{added:t,cwd:n,server:i,testing:o,signIn:s,signingOut:l,signInBlock:a,onSignIn:d}=e,{t:c}=(0,E.s)(),u=lq(t.name),p="project"===t.scope&&n?lq(ln(t.path,n)):ph(t.path),h=i.status,f=!o&&h?.origin==="test"&&"needs-auth"===h.state&&i.usesOAuth,m=s?.starting===!0||u9(s);return(0,r.jsxs)(sh,{action:!f||m||l||a?void 0:(0,r.jsx)(sb,{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:ph(t.trustedFolder)}),o&&(0,r.jsxs)(r.Fragment,{children:[" ",c("mcp.add.testing")]}),f&&(0,r.jsxs)(r.Fragment,{children:[" ",c("mcp.add.needsSignIn")]})]})}function pj(e){let{codemode:t,active:n,rowRef:i,onSelect:o}=e,{t:s}=(0,E.s)(),l=t.builtinDisabled||"unavailable"===t.sandbox.state?"unavailable":t.preference??"unknown",a=s(av[l]);return(0,r.jsxs)(o6,{ref:n?i:void 0,active:n,"aria-label":s("mcp.codemode.rowLabel",{state:a}),onClick:()=>o(l1),children:[(0,r.jsx)(sk,{...at(ab(l))}),(0,r.jsx)(o9,{className:"is-grow",children:s("mcp.codemode.title")}),(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${ab(l)}`,children:a})]})}function pk(e){var t;let n,i,{group:o,context:s,selected:l,selectedRowRef:a,block:d,blockNoticeId:c,busy:u,controlsBusy:p,status:h,onSelect:f,onGroupSwitch:m}=e,{t:g}=(0,E.s)(),{enabled:x,total:v}=au(o.servers),b=(t=o.servers).some(e=>e.enabled&&aW(e))&&t.every(e=>e.enabled||!aP(e)),y=function(e){if(!(e.servers.length>0))return e.file?e.file.problems.some(ad)?"mcp.group.fileProblem":"mcp.group.empty":"mcp.group.notListed"}(o),j=h?(n=h.keptOff>0?g("mcp.groupKeptOff",{count:h.keptOff}):void 0,i=h.error?`${g("mcp.actionFailed")} ${pg(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`${lq(t)}: ${pg(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)(o8,{aside:v>0?(0,r.jsx)(o3,{enabled:x,total:v,checked:b,disabled:p||void 0!==d,loading:u===`group:${o.scope}`,describedBy:d?c:void 0,label:g(b?"mcp.groupSwitchOn":"mcp.groupSwitchOff",{group:pp(o.scope,g)}),onChange:e=>m(o.scope,o.servers,e)}):void 0,children:pp(o.scope,g)}),j&&(0,r.jsx)(o5,{note:j.note,error:j.error}),y&&(0,r.jsx)("div",{className:"mcp-sidebar-group-empty",children:g(y)}),o.servers.map(e=>{let t=l2(e),n=l8(e,s),i=ae(n),o=l7[n],d=lq(e.name);return(0,r.jsxs)(o6,{ref:l===t?a:void 0,active:l===t,"aria-label":g("mcp.rowLabel",{name:d,state:g(l6(n,e.status))}),onClick:()=>f(t),children:[(0,r.jsx)(sk,{...at(i)}),(0,r.jsx)(o9,{className:`is-grow${"on"===i?"":" is-muted"}`,children:d}),o&&(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${i}`,children:g(o)})]},t)})]})}function pw(e){let{fields:t}=e,{t:n}=(0,E.s)();return(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>{let t=lG(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function pS(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:lq(e)},e))})}function pC(e){let{server:t,state:n}=e,{t:i}=(0,E.s)();if("invalid"===n)return(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[i("mcp.server.invalid")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:lq(t.invalidError??"")})]});let o=l9[n];return o?(0,r.jsx)("span",{className:"mcp-config-line",children:i(o)}):null}function pE(e){let{server:t,context:n,codemode:o,toolSearchDisabled:s,autoEnable:l,block:a,savedWhileOff:d,busy:c,controlsBusy:u,actionError:p,test:h,testBlock:f,signIn:m,signInBlock:g,signOutBlock:x,onSwitch:v,onExposureChange:b,onRemove:y,onTest:j,onSignIn:k,onSignOut:w,onSignInPaste:S,onSignInCancel:C}=e,{t:N}=(0,E.s)(),I=(0,i.useId)(),$=(0,i.useId)(),T=l8(t,n),M=ae(T),R=lJ(t),L=void 0===t.invalidError,z="http"===t.transport||void 0===t.transport&&void 0!==t.url,A=!z&&("stdio"===t.transport||void 0!==t.command),W=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"===af(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:o,toolSearchDisabled:s},l):void 0,P=(0,i.useId)(),O=l2(t),F=lq(t.name),B=!t.enabled&&void 0!==t.webPasswordField,D=!0===t.notAnObject,H=a?N(`mcp.reason.${a}`):D?N("mcp.reason.entry-not-object"):B?N("mcp.reason.web-password"):d?N("mcp.write.savedWhileOff"):void 0;return(0,r.jsxs)(o7,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(se,{children:[(0,r.jsxs)(st,{children:[(0,r.jsx)(sa,{scope:t.scope,children:pp(t.scope,N)}),(0,r.jsx)(sr,{children:F})]}),(0,r.jsxs)(sn,{children:[(0,r.jsx)(pR,{server:t,test:h,testBlock:f,describedBy:$,onTest:j}),(0,r.jsx)(sb,{variant:"danger",size:"small",disabled:u||void 0!==a,"aria-describedby":a?I:void 0,onClick:()=>y(t),children:c===`remove:${O}`?N("i18n.removing"):N("i18n.remove")}),(0,r.jsx)(sy,{checked:t.enabled,disabled:u||void 0!==a||D||B,loading:c===`switch:${O}`,describedBy:H?I:void 0,label:N(t.enabled?"mcp.server.switchOff":"mcp.server.switchOn",{name:F}),onChange:e=>v(t,e)})]})]}),H&&(0,r.jsx)("div",{id:I,className:"config-detail-heading-note",children:H})]}),p&&(0,r.jsxs)("p",{role:"alert",className:"mcp-config-line is-error",children:[N("mcp.actionFailed")," ",pg(p,N)]}),(0,r.jsxs)(ss,{children:[(0,r.jsx)(sl,{label:N("i18n.status"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:`mcp-config-state is-${M}`,children:N(l6(T,t.status))}),(0,r.jsx)(pC,{server:t,state:T}),t.webPasswordField&&(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[N("mcp.server.webPassword")," ",(0,r.jsx)(pw,{fields:[t.webPasswordField]})]})]})}),(0,r.jsx)(pL,{server:t,test:h,testBlock:f,testBlockId:$}),void 0!==t.description&&(0,r.jsx)(sl,{label:N("mcp.detail.description"),tone:"plain",children:lq(t.description)}),t.transport&&(0,r.jsx)(sl,{label:N("mcp.detail.transport"),children:N(`mcp.transport.${t.transport}`)}),void 0!==R&&(0,r.jsx)(sl,{label:z?N("mcp.detail.url"):N("mcp.detail.command"),tone:"plain",mono:!0,children:R}),A&&void 0!==t.cwd&&(0,r.jsx)(sl,{label:N("mcp.detail.cwd"),mono:!0,children:lq(t.cwd)}),A&&t.envNames.length>0&&(0,r.jsx)(sl,{label:N("mcp.detail.env"),children:(0,r.jsx)(pS,{names:t.envNames})}),z&&t.headerNames.length>0&&(0,r.jsx)(sl,{label:N("mcp.detail.headers"),children:(0,r.jsx)(pS,{names:t.headerNames})}),L&&t.commandFields.length>0&&(0,r.jsx)(sl,{label:N("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:N("mcp.server.commandFields")}),(0,r.jsx)(pw,{fields:t.commandFields})]})}),L&&t.variableReferences.length>0&&(0,r.jsx)(sl,{label:N("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:N(lX(t))}),(0,r.jsx)("span",{className:"mcp-config-chips",children:lQ(t.variableReferences).map(e=>{let{variable:t,field:n}=e,i=lG(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:N("mcp.server.variableIn",{variable:t,field:N(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})}),z&&L&&(0,r.jsx)(pd,{server:t,run:m,block:g,signOutBlock:x,controlsBusy:u,signingOut:c===`sign-out:${O}`,onSignIn:k,onSignOut:w,onPaste:S,onCancel:C}),t.exposure&&(0,r.jsx)(sl,{label:N("mcp.detail.exposure"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsxs)("span",{className:"mcp-exposure-choice",children:[(0,r.jsx)("select",{className:"mcp-add-input mcp-exposure-select","aria-label":N("mcp.exposure.label",{name:F}),"aria-describedby":[P,a?I:null].filter(Boolean).join(" "),value:t.exposure,disabled:u||void 0!==a,onChange:e=>{let n=e.target.value;n!==t.exposure&&b(t,n)},children:al.map(e=>(0,r.jsx)("option",{value:e,children:"codemode"===e?N("mcp.exposure.optionDefault",{label:N(aa[e])}):N(aa[e])},e))}),c===`exposure:${O}`&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:N("i18n.saving")})]}),(0,r.jsx)("span",{id:P,className:"mcp-config-line",children:N(as[t.exposure])}),void 0!==t.toolExposureCount&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:N("mcp.exposure.toolOverrides",{count:t.toolExposureCount})}),W&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:pf(W,N)})]})}),(0,r.jsx)(sl,{label:N("mcp.detail.file"),tone:"dim",mono:!0,children:ph(t.sourcePath)})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[lY(t)&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:N("mcp.server.hiddenCharacters")}),!t.validated&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:N("mcp.server.unchecked")}),t.replacesGlobal&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:N("mcp.server.replacesGlobal")}),t.shadowedByProject&&"replaced"!==T&&(0,r.jsx)("p",{className:"mcp-config-line",children:N("mcp.server.shadowedByProject")}),t.masked&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:N("mcp.server.masked")})]})]})}function pN(e){let{error:t,stderr:n}=e,{t:i}=(0,E.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:lq(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(lq).join("\n")})]})]})}function pI(e){let{status:t}=e;return"session"===t.origin?(0,r.jsx)(pT,{status:t}):(0,r.jsx)(p$,{status:t})}function p$(e){let{status:t}=e,{t:n,locale:i}=(0,E.s)(),o=t.timedOut?{key:a_.timedOut,tone:"error"}:{key:a_[t.state],tone:ae(t.state)},s=an(t.testedAt,i),l=t.serverInfo;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[(0,r.jsx)("span",{className:`mcp-config-state is-${o.tone}`,children:n(o.key)})," ",n((t.afterSignIn?aq:aU)[t.timedOut?"timedOut":t.state],{count:t.toolCount,seconds:aZ(t.durationMs),time:s})]}),(0,r.jsx)(pN,{error:t.error,stderr:t.stderr}),l&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.test.serverInfo",{name:lq(l.title??l.name),version:lq(l.version)})}),void 0!==t.resources&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.test.resources",{resources:t.resources,templates:t.resourceTemplates??0})}),void 0!==t.cwd&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.test.ranIn",{path:ph(t.cwd)})}),void 0!==t.queuedMs&&t.queuedMs>=500&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.test.queued",{seconds:aZ(t.queuedMs)})})]})}function pT(e){let{status:t}=e,{t:n,locale:i}=(0,E.s)(),o=void 0!==t.closedAt?{key:"mcp.session.state.closed",tone:"off"}:{key:ar[t.state],tone:ao[t.state]},s=an(t.updatedAt,i),l=void 0===t.closedAt?void 0:an(t.closedAt,i);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[(0,r.jsx)("span",{className:`mcp-config-state is-${o.tone}`,children:n(o.key)})," ",n(void 0!==t.closedAt?"mcp.session.summary.closed":ai[t.state],{path:ph(t.cwd),time:s,...void 0===l?{}:{closedTime:l}})]}),void 0!==t.conflict&&(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[n("mcp.session.conflictOwner")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:ph(t.conflict)})]}),(0,r.jsx)(pN,{error:t.error,stderr:t.stderr})]})}function pM(e){let{status:t,serverExposure:n}=e,{t:i}=(0,E.s)(),o=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:lq(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(aa[e.exposure])})]}),e.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:lq(e.description)})]},`${t}\0${e.name}`))}),o>0&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:i("mcp.test.moreTools",{count:o})})]})}function pR(e){let{server:t,test:n,testBlock:o,describedBy:s,onTest:l}=e,{t:a}=(0,E.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&&oK(document,d.current)},[c]),(0,r.jsx)(sb,{ref:d,size:"small",disabled:c||void 0!==o,"aria-busy":c||void 0,"aria-describedby":o?s:void 0,onClick:()=>l(t),children:a(c?"mcp.test.testing":"mcp.test.button")})}function pL(e){let{server:t,test:n,testBlock:i,testBlockId:o}=e,{t:s}=(0,E.s)(),l=t.status;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(sl,{label:s("mcp.detail.connection"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[l?(0,r.jsx)(pI,{status:l}):(0,r.jsx)("span",{className:"mcp-config-line",children:s("mcp.test.never")}),n?.queueTimedOut&&(0,r.jsx)("span",{role:"alert",className:"mcp-config-line is-error",children:s("mcp.test.queueTimedOut")}),n?.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[s("mcp.test.requestFailed")," ",function(e,t){if(e.timedOut)return t("mcp.test.requestTimedOut");let n=e.reason?aH[e.reason]:void 0;return n?t(n):pm(e,t)}(n.error,s)]}),i&&(0,r.jsx)("span",{id:o,className:"mcp-config-line is-dim",children:s(aB[i])}),!i&&t.commandFields.length>0&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.serial")})]})}),l?.origin==="test"&&"connected"===l.state&&l.toolCount>0&&(0,r.jsx)(sl,{label:s("mcp.detail.listedTools"),tone:"plain",children:(0,r.jsx)(pM,{status:l,serverExposure:t.exposure})})]})}function pz(e){let{codemode:t,autoEnable:n,save:i,serverBusy:o,onChange:s,onModeChange:l,onInlineBudgetSave:a}=e,{t:d}=(0,E.s)(),c=t.sandbox,u=t.preference,p=i.saving||o,h=void 0===i.target||"preference"===i.target?i:{saving:!1,error:null},f=function(e,t){if("automatic"===af(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:am[t.preference],params:{path:t.settingsPath}}}(t);return(0,r.jsxs)(o7,{children:[(0,r.jsx)(se,{children:(0,r.jsx)(st,{children:(0,r.jsx)(sr,{children:d("mcp.codemode.title")})})}),(0,r.jsx)("p",{className:"mcp-config-line",children:d("mcp.codemode.intro")}),(0,r.jsxs)(ss,{children:[(0,r.jsx)(sl,{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)(sd,{value:u,label:d("mcp.codemode.title"),options:[{value:"automatic",label:d(av.automatic),disabled:p},{value:"always",label:d(av.always),disabled:p||void 0!==m}],disabledReason:m?pf(m,d):null,onChange:e=>{e!==u&&s(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:lq(t.preferenceError??"")})]}),h.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[d("mcp.codemode.saveFailed")," ",(0,r.jsx)(pA,{error:h.error})]}),x&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:pf(x,d)}),f&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:pf(f,d)})]})}),t.mode?(0,r.jsx)(pW,{mode:t.mode,codemode:t,save:i,waiting:p,onChange:l}):void 0!==t.modeError&&(0,r.jsx)(sl,{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:lq(t.modeError)})]})}),t.inlineBudget?(0,r.jsx)(pP,{budget:t.inlineBudget,save:i,waiting:p,onSave:a}):void 0!==t.inlineBudgetError&&(0,r.jsx)(sl,{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:lq(t.inlineBudgetError)})]})}),(0,r.jsx)(sl,{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:lq(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)(sl,{label:d("mcp.codemode.builtin"),tone:"error",children:pf(g,d)})]})]})}function pA(e){let{error:t}=e,{t:n}=(0,E.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:lq(t.error)})}function pW(e){let{mode:t,codemode:n,save:i,waiting:o,onChange:s}=e,{t:l}=(0,E.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:ax[r.value],params:{path:r.settingsPath}}),"only"===(r??t).value&&"automatic"===af(e)&&n.push({key:"mcp.codemode.toolMode.automaticNote"}),n}(n);return(0,r.jsx)(sl,{label:l("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)(sd,{value:t.value,label:l("mcp.codemode.toolMode"),options:[{value:"on",label:l("mcp.codemode.toolMode.on"),disabled:o},{value:"only",label:l("mcp.codemode.toolMode.only"),disabled:o}],onChange:e=>{(e!==t.value||void 0!==t.invalid)&&s(e)},children:a&&i.saving&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:l("i18n.saving")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:l(ag[t.value])}),d.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:pf(e,l)},e.key)),a&&i.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[l("mcp.codemode.toolMode.saveFailed")," ",(0,r.jsx)(pA,{error:i.error})]})]})})}function pP(e){let t,n,{budget:o,save:s,waiting:l,onSave:a}=e,{t:d}=(0,E.s)(),c=(0,i.useRef)(null),u=(0,i.useId)(),p=void 0===o.value?"":String(o.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,o.max),g=!!m.ok&&(null===m.value?void 0!==o.value||void 0!==o.invalid:m.value!==o.value),x="inlineBudget"===s.target,v=x&&s.saving,b=(0,i.useRef)(v);(0,i.useEffect)(()=>{let e=b.current;b.current=v,e&&!v&&oK(document,c.current)},[v]);let y=(t=[],void 0!==o.invalid&&t.push({key:"mcp.codemode.inlineBudget.invalid",params:{path:o.settingsPath,value:o.invalid,default:String(o.default)}}),(n=o.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(o.default)}}),t);return(0,r.jsx)(sl,{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&&!l&&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(o.default),readOnly:l,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)(sb,{type:"submit",size:"small",disabled:!g||l,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(o.max)})}),(0,r.jsx)("span",{id:u,className:"mcp-config-line",children:d("mcp.codemode.inlineBudget.description",{default:String(o.default)})}),y.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:pf(e,d)},e.key)),x&&s.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[d("mcp.codemode.inlineBudget.saveFailed")," ",(0,r.jsx)(pA,{error:s.error})]})]})})}function pO(e){let{section:t,size:n=16,strokeWidth:i=1.8}=e,o={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",{...o,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",{...o,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",{...o,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",{...o,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",{...o,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",{...o,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",{...o,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 pF(e){let{sessionId:t,onSessionReloaded:n,quoteSelectionEnabled:o,onQuoteSelectionChange:s}=e,{locale:l,setLocale:a,supportedLocales:d,t:c}=(0,E.s)(),{preference:u,setThemePreference:p}=ni(),{width:h,setWidth:f,fontSize:m,setFontSize:g}=rB(),x=rC(),[v,b]=(0,i.useState)(null),[y,j]=(0,i.useState)(!1),[k,w]=(0,i.useState)(null),[S,C]=(0,i.useState)(!1),[N,I]=(0,i.useState)(!1),[$,T]=(0,i.useState)(null),[M,R]=(0,i.useState)(!1),[L,z]=(0,i.useState)(!1),[A,W]=(0,i.useState)("");(0,i.useEffect)(()=>{C(ny()),fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>R(e?.enabled===!0)).catch(()=>{})},[]);let P=async()=>{z(!0),W("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.replace("/login")}catch{W(c("auth.logoutFailed"))}finally{z(!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||b(n)}).catch(t=>{e||w(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]);let O=async e=>{j(!0),w(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}`);b(i),t&&(await iT(t,{type:"reload"}),n())}catch(e){w(e instanceof Error?e.message:String(e))}finally{j(!1)}},F=async()=>{if(!N){I(!0),T(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 le(l))throw Error("unsupported or not permitted");T({kind:"ok",message:c("settings.pushRegistered")})}catch(e){T({kind:"error",message:`${c("settings.pushRegisterFailed")} ${e instanceof Error?e.message:String(e)}`})}finally{I(!1)}}};return(0,r.jsxs)("div",{className:"settings-general",children:[(0,r.jsx)("h2",{className:"settings-general-title",children:c("settings.general")}),(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:tX.map(e=>{let t=u===e.id;return(0,r.jsxs)("label",{className:"settings-theme-option",children:[(0,r.jsx)("input",{type:"radio",name:"theme",value:e.id,checked:t,onChange:()=>p(e.id),className:"sr-only"}),(0,r.jsx)(oA,{preference:e.id}),(0,r.jsx)("span",{className:"settings-theme-option-label",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.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)(sy,{checked:S,label:c("settings.thinkingExpandedDefault"),onChange:e=>{window.localStorage.setItem(nv,String(e)),window.dispatchEvent(new Event(nb)),C(e)}})]}),(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)(sb,{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)("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)(sb,{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-switch-option",children:[(0,r.jsx)("span",{children:c("settings.quoteSelection")}),(0,r.jsx)(sy,{checked:o,label:c("settings.quoteSelection"),onChange:s})]}),(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:()=>rS("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:()=>rS("ctrlEnter"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:c("settings.enterSendModeCtrlEnter")})]})]})]})]})]}),v?.isWindows&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.shellTool")}),(0,r.jsx)("p",{className:"settings-general-description",children:c("settings.shellToolDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:c("settings.usePowerShell")}),(0,r.jsx)(sy,{checked:v.powerShellEnabled,loading:y,label:c("settings.usePowerShell"),onChange:e=>void O(e)})]}),k&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:k})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.pushPermission")}),(0,r.jsx)("p",{className:"settings-general-description",children:c("settings.pushPermissionDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:c("settings.pushPermission")}),(0,r.jsx)("button",{type:"button",className:"config-button config-button-small config-button-secondary",disabled:N,onClick:()=>void F(),children:N?c("settings.pushRegisterLoading"):c("settings.pushRegister")})]}),$&&(0,r.jsx)("p",{role:"status",className:"settings-general-error",style:"ok"===$.kind?{color:"var(--accent)"}:void 0,children:$.message})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("common.language")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":c("common.language"),className:"settings-language-options",children:d.map(e=>{let t=l===e.id;return(0,r.jsxs)("button",{type:"button",role:"radio","aria-checked":t,onClick:()=>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)})})]}),M&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsxs)(sb,{variant:"secondary",disabled:L,onClick:()=>void P(),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"})}),L?c("auth.loggingOut"):c("auth.logOut")]}),A&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:A})]})]})}let pB={en:"Archives","zh-CN":"归档","zh-TW":"封存"};function pD(e){let{cwd:t,sessionId:n,initialSection:o,onClose:s,onSessionReloaded:l,quoteSelectionEnabled:a,onQuoteSelectionChange:d,projectTrust:c,onOpenTrustDialog:u,onProjectTrustChanged:p}=e,{t:h,locale:f}=(0,E.s)(),[m,g]=(0,i.useState)(o),[x,v]=(0,i.useState)(()=>new Set([m])),b=[{id:"general",label:h("settings.general")},{id:"models",label:h("common.models")},{id:"archives",label:pB[f]??pB.en},{id:"skills",label:h("common.skills")},{id:"agents",label:h("common.agents")},{id:"plugins",label:h("common.plugins")},{id:"mcp",label:h("settings.mcp")}].map(e=>({...e,requiresProject:oF(e.id)})),y=oF(m);(0,i.useEffect)(()=>o_(o),[o]),(0,i.useEffect)(()=>{var e;let t;return e=document,t=e=>{"Escape"!==e.key||e.defaultPrevented||oZ(e)||(e.preventDefault(),s())},e.addEventListener("keydown",t,!1),()=>e.removeEventListener("keydown",t,!1)},[s]);let j=(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)),o=r&&r!==e.body&&!i?r:null;return t&&!i&&t.focus({preventScroll:!0}),()=>{if(!o||!o.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())}(o))return;let r=e.activeElement;r&&r!==e.body&&!(t&&t.contains(r))||"function"==typeof o.focus&&o.focus({preventScroll:!0})}})(document,j.current,{restoreTextEntry:!window.matchMedia?.("(pointer: coarse)").matches}),[]),(0,i.useEffect)(()=>{!t&&y&&(g("general"),v(e=>new Set(e).add("general")),o_("general"))},[t,y]);let k=e=>{v(t=>new Set(t).add(e)),g(e),o_(e)},w=(e,t)=>x.has(e)?(0,r.jsx)("div",{hidden:m!==e,className:"settings-section-host",children:t},e):null;return(0,r.jsx)("div",{ref:j,role:"dialog","aria-modal":"true","aria-label":h("settings.title"),tabIndex:-1,onClick:e=>{e.target===e.currentTarget&&s()},className:"settings-dialog-backdrop",children:(0,r.jsxs)("div",{className:"settings-dialog-surface",children:[(0,r.jsxs)("div",{className:"settings-dialog-header",children:[(0,r.jsx)("strong",{className:"settings-dialog-title",children:h("settings.title")}),(0,r.jsx)("select",{"aria-label":h("settings.title"),value:m,onChange:e=>k(e.target.value),className:"settings-mobile-section-picker",children:b.map(e=>(0,r.jsx)("option",{value:e.id,disabled:e.requiresProject&&!t,children:e.label},e.id))}),(0,r.jsx)("nav",{"aria-label":h("settings.title"),className:"settings-section-tabs",children:b.map(e=>{let n=m===e.id,i=e.requiresProject&&!t;return(0,r.jsxs)("button",{type:"button",className:"settings-section-tab",disabled:i,title:i?h("settings.projectRequired"):e.label,"aria-current":n?"page":void 0,onClick:()=>k(e.id),children:[(0,r.jsx)(pO,{section:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id)})}),(0,r.jsx)("button",{type:"button",onClick:s,title:h("i18n.close"),"aria-label":h("i18n.close"),className:"config-close-button settings-dialog-close",children:"\xd7"})]}),(0,r.jsxs)("main",{className:"settings-dialog-main",children:[w("general",(0,r.jsx)(pF,{sessionId:n,onSessionReloaded:l,quoteSelectionEnabled:a,onQuoteSelectionChange:d})),w("models",(0,r.jsx)(s9,{embedded:!0,cwd:t,onClose:s})),w("archives",(0,r.jsx)(lD,{embedded:!0,onClose:s})),t&&w("skills",(0,r.jsx)(lu,{embedded:!0,cwd:t,trust:c,onClose:s},t)),t&&w("agents",(0,r.jsx)(lS,{embedded:!0,cwd:t,sessionId:n,trust:c,onClose:s,onReloaded:l},t)),t&&w("plugins",(0,r.jsx)(lP,{embedded:!0,cwd:t,sessionId:n,trust:c,onClose:s,onReloaded:l},t)),w("mcp",(0,r.jsx)(pv,{embedded:!0,cwd:t,trust:c,onTrustProject:u,onProjectTrustChanged:p,onClose:s},t??""))]})]})})}let pH="project-trust-mcp-status";function p_(e){let{cwd:t,busy:n,error:o,onCancel:s,onConfirm:l,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)(pU,{cwd:t,busy:n,error:o,listing:d,onCancel:s,onConfirm:l})}function pU(e){let{cwd:t,busy:n,error:o,listing:s,onCancel:l,onConfirm:a}=e,{t:d}=(0,E.s)(),c="loading"===s.state,u="loaded"===s.state?function(e){if(e){if(!e.requiresTrust)return"mcp.reason.trust-not-required";if(e.trusted)return"trust.alreadyTrusted"}}(s.status):void 0,p=(0,i.useRef)(null),h=(0,i.useRef)(n),f=(0,i.useRef)(l);return(0,i.useEffect)(()=>{h.current=n,f.current=l},[n,l]),(0,i.useEffect)(()=>{var e,t,n;let r,i,o;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(),oZ(e)||(e.preventDefault(),n()))},e.addEventListener("keydown",i,!0),o=()=>e.removeEventListener("keydown",i,!0),()=>{o(),r&&r.isConnected&&"function"==typeof r.focus&&r.focus({preventScroll:!0})}},[]),(0,r.jsx)("div",{role:"presentation",className:"project-trust-backdrop",onClick:e=>{n||e.target!==e.currentTarget||l()},children:(0,r.jsxs)("div",{ref:p,role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title","aria-describedby":"project-trust-description",tabIndex:-1,className:"project-trust-dialog",children:[(0,r.jsxs)("div",{className:"project-trust-body",children:[(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"project-trust-icon",children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,r.jsxs)("div",{className:"project-trust-content",children:[(0,r.jsx)("div",{id:"project-trust-title",className:"project-trust-title",children:d("trust.dialogTitle")}),(0,r.jsx)("div",{id:"project-trust-description",className:"project-trust-text",children:d("trust.dialogBody")}),(0,r.jsx)("code",{className:"project-trust-path",children:lq(t)}),u&&(0,r.jsx)("p",{id:"project-trust-notice",role:"status",className:"project-trust-notice",children:d(u)}),"loaded"===s.state&&void 0!==s.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:lq(s.statusError)})]}),(0,r.jsx)(pZ,{listing:s})]})]}),o&&(0,r.jsx)(pq,{error:o}),(0,r.jsxs)("div",{className:"project-trust-footer",children:[(0,r.jsx)("button",{type:"button",className:"project-trust-button",onClick:l,disabled:n,children:d(u?"trust.close":"trust.cancel")}),!u&&(0,r.jsx)("button",{type:"button",className:"project-trust-button is-primary",onClick:a,disabled:n||c,"aria-busy":n||void 0,"aria-describedby":c?pH:void 0,children:d(n?"trust.trusting":"trust.trustProject")})]})]})})}function pq(e){let{error:t}=e,{t:n}=(0,E.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:lq(t.error)})]})}function pZ(e){let{listing:t}=e,{t:n}=(0,E.s)();if("loading"===t.state)return(0,r.jsx)("p",{id:pH,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:lq(e)})]})}let{mcpFile:i,mcpServers:o}=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")}),o.length>0&&(0,r.jsx)("p",{className:"project-trust-mcp-intro",children:n("trust.mcp.intro")}),(0,r.jsx)(pK,{file:i}),0===o.length&&0===i.problems.length&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:n("trust.mcp.none")}),o.some(e=>!e.validated)&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:n("trust.mcp.unchecked")}),o.length>0&&(0,r.jsx)("ul",{className:"project-trust-mcp-list",children:o.map(e=>(0,r.jsx)(pY,{server:e},e.name))})]}):null}function pK(e){let{file:t}=e,{t:n}=(0,E.s)();return(0,r.jsx)(r.Fragment,{children:t.problems.map(e=>{let i=l0(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 pV(e){let{fields:t}=e,{t:n}=(0,E.s)();return(0,r.jsx)(r.Fragment,{children:t.map(e=>{let t=lG(e);return(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function pJ(e){let{server:t}=e,{t:n}=(0,E.s)();return(0,r.jsx)(r.Fragment,{children:lQ(t.variableReferences).map(e=>{let{variable:t,field:i}=e,o=lG(i);return(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:n("mcp.server.variableIn",{variable:t,field:n(o.key,o.params)})},`${t}\0${i.kind}\0${i.name??""}`)})})}function pY(e){let{server:t}=e,{t:n}=(0,E.s)(),i=lJ(t),o=void 0===t.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:lq(t.name)}),t.transport&&(0,r.jsx)("span",{className:"project-trust-mcp-tag",children:n(`mcp.transport.${t.transport}`)})]}),void 0!==i&&(0,r.jsx)("code",{className:"project-trust-mcp-target",children:i}),void 0!==t.cwd&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:n("trust.mcp.cwd",{path:lq(t.cwd)})}),lY(t)&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:n("mcp.server.hiddenCharacters")}),void 0!==t.invalidError&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[n("mcp.server.invalid")," ",(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:lq(t.invalidError)})]}),t.webPasswordField&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[n("mcp.server.webPassword")," ",(0,r.jsx)(pV,{fields:[t.webPasswordField]})]}),!t.enabled&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:n("mcp.server.disabled")}),o&&t.commandFields.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[n("mcp.server.commandFields")," ",(0,r.jsx)(pV,{fields:t.commandFields})]}),o&&t.variableReferences.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[n(lX(t))," ",(0,r.jsx)(pJ,{server:t})]}),t.replacesGlobal&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:n("mcp.server.replacesGlobal")}),t.masked&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-dim",children:n("mcp.server.masked")})]})}function pG(e){return"message"===e.type&&"message"in e&&"system"!==e.message.role}function pX(e){let t=e,n=t.branchPreview,r=pG(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&pG(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function pQ(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 p0(e){let{node:t,activePathIds:n,depth:i,isLast:o,parentLines:s,onSelect:l}=e,{node:a,skipped:d,branchPreview:c,labelEntry:u}=pX(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&&pG(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:pG(u)?u.message.role:null;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:l?"pointer":"default"},onClick:l?()=>l(a.entry.id):void 0,children:[s.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:o?"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)(p0,{node:e,activePathIds:n,depth:i+1,isLast:t===a.children.length-1,parentLines:[...s,!o],onSelect:l},e.entry.id))]})}function p1(e){let{tree:t,activeLeafId:n,onLeafChange:o,inline:s,containerRef:l,open:a,onToggle:d,hasSession:c,compact:u,hideInlineButton:p,locked:h=!1}=e,{t:f}=(0,E.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||!s)return;let e=l?.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,s,l]);let j=(0,i.useMemo)(()=>(function(e,t){if(!t)return new Set;let n=e.map(e=>({node:e,path:[e.entry.id]}));for(;n.length>0;){let{node:e,path:r}=n.pop();if(e.entry.id===t||e.compressedEntryIds?.includes(t))return new Set(r);for(let t of e.children)n.push({node:t,path:[...r,t.entry.id]})}return new Set})(t,n),[t,n]),k=(0,i.useCallback)(e=>{o(e)},[o]),w=h?void 0:k,S=h&&(0,r.jsx)("div",{style:{padding:"2px 0 4px",fontSize:11,color:"var(--text-dim)",fontStyle:"italic"},children:f("i18n.branchesLockedWhileRunning")}),C=c?pQ(t)?null:f("i18n.noBranches"):f("i18n.noActiveSession"),N=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=pX(e[0]).node;return t.children.length>1?t.children:[]}(t),I=!C&&N.length>0,$=(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:I?"var(--accent)":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),T=(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{marginLeft:2,transform:x?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})});return s?(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:I?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(p0,{node:e,activePathIds:j,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:w},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C})})]}):(0,r.jsxs)("div",{style:{borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>g(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"5px 12px",background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",fontSize:11,textAlign:"left"},children:[$,(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:f("i18n.branches")}),T]}),x&&(0,r.jsx)("div",{style:{position:"absolute",top:"100%",left:0,right:0,background:"var(--bg)",borderBottom:"1px solid var(--border)",boxShadow:"0 4px 12px rgba(0,0,0,0.1)",zIndex:100},children:I?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(p0,{node:e,activePathIds:j,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:w},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C??f("i18n.noBranches")})})]})}function p2(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:`
10
- .system-prompt-panel {
11
- display: flex;
12
- height: min(600px, 75dvh);
13
- min-height: 220px;
14
- flex-direction: column;
15
- background: var(--bg-panel);
16
- border-bottom: 1px solid var(--border);
17
- }
18
- .system-prompt-scroll {
19
- min-height: 0;
20
- flex: 1;
21
- overflow: auto;
22
- padding: 12px 16px;
23
- }
24
- .system-prompt-text {
25
- color: var(--text-muted);
26
- font-family: var(--font-mono);
27
- font-size: 12px;
28
- line-height: 1.6;
29
- overflow-wrap: anywhere;
30
- white-space: pre-wrap;
31
- }
32
- .system-prompt-empty {
33
- padding: 10px 0;
34
- color: var(--text-muted);
35
- font-size: 12px;
36
- font-style: italic;
37
- }
38
- `})]})}function p4(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e)}catch{return String(e)}}function p8(e){let{children:t}=e;return(0,r.jsx)("div",{className:"tool-definitions-empty",children:t})}function p3(e){let{loading:t,tools:n,translate:o}=e,s=(0,i.useMemo)(()=>n?.filter(e=>e.active&&!e.declarationHidden)??null,[n]),[l,a]=(0,i.useState)(null);(0,i.useEffect)(()=>{a(e=>s?.some(t=>t.name===e)?e:s?.[0]?.name??null)},[s]);let d=s?.find(e=>e.name===l)??s?.[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 p4(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(p4).join(", "):void 0,defaultValue:void 0===i.default?void 0:p4(i.default)}})}(d.parameters):[];return(0,r.jsxs)("div",{className:"tool-definitions-panel",children:[(0,r.jsx)("nav",{className:"tool-definitions-sidebar","aria-label":o("tools.title"),children:(0,r.jsx)("div",{className:"tool-definitions-list",children:s&&s.length>0?s.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)}):s?(0,r.jsx)(p8,{children:o("tools.noTools")}):(0,r.jsx)(p8,{children:t?o("tools.loading"):o("tools.load")})})}),(0,r.jsx)("section",{className:"tool-definition-detail","aria-label":o("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:o("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:o("tools.parameters")}),(0,r.jsx)("span",{children:o("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:o(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:[o("tools.allowedValues"),": ",(0,r.jsx)("code",{children:e.allowedValues})]}),void 0!==e.defaultValue&&(0,r.jsxs)("div",{className:"tool-definition-meta",children:[o("tools.defaultValue"),": ",(0,r.jsx)("code",{children:e.defaultValue})]})]})]},e.name))}):(0,r.jsx)("div",{className:"tool-definition-no-parameters",children:o("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:o("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)(p8,{children:s?o("tools.noTools"):t?o("tools.loading"):o("tools.load")})}),(0,r.jsx)("style",{children:`
39
- .tool-definitions-panel {
40
- display: grid;
41
- grid-template-columns: clamp(112px, 26%, 220px) minmax(0, 1fr);
42
- height: min(600px, 75dvh);
43
- min-height: 240px;
44
- overflow: hidden;
45
- background: var(--bg-panel);
46
- border-bottom: 1px solid var(--border);
47
- }
48
- .tool-definitions-sidebar,
49
- .tool-definition-detail {
50
- display: flex;
51
- min-width: 0;
52
- min-height: 0;
53
- flex-direction: column;
54
- }
55
- .tool-definitions-sidebar {
56
- border-right: 1px solid var(--border);
57
- background: color-mix(in srgb, var(--bg-panel) 94%, var(--bg));
58
- }
59
- .tool-definitions-list,
60
- .tool-definition-scroll {
61
- min-height: 0;
62
- flex: 1;
63
- overflow: auto;
64
- }
65
- .tool-definitions-item {
66
- display: flex;
67
- width: 100%;
68
- min-height: 38px;
69
- align-items: center;
70
- padding: 8px 12px;
71
- border: none;
72
- border-bottom: 1px solid var(--border);
73
- background: transparent;
74
- color: var(--text-muted);
75
- cursor: pointer;
76
- text-align: left;
77
- }
78
- .tool-definitions-item:hover {
79
- background: var(--bg-hover);
80
- color: var(--text);
81
- }
82
- .tool-definitions-item.selected {
83
- background: var(--bg-selected);
84
- box-shadow: inset 2px 0 0 var(--accent);
85
- color: var(--text);
86
- }
87
- .tool-definitions-item code {
88
- max-width: 100%;
89
- color: inherit;
90
- font-size: 11px;
91
- font-weight: 600;
92
- overflow-wrap: anywhere;
93
- }
94
- .tool-definition-scroll {
95
- padding: 14px 16px 20px;
96
- }
97
- .tool-definition-section + .tool-definition-section {
98
- margin-top: 18px;
99
- }
100
- .tool-definition-section-label {
101
- display: flex;
102
- align-items: center;
103
- justify-content: space-between;
104
- gap: 8px;
105
- margin-bottom: 7px;
106
- color: var(--text-dim);
107
- font-size: 11px;
108
- font-weight: 600;
109
- }
110
- .tool-definition-section-label > span:last-child {
111
- font-weight: 400;
112
- white-space: nowrap;
113
- }
114
- .tool-definition-description {
115
- color: var(--text-muted);
116
- font-size: 12px;
117
- line-height: 1.55;
118
- overflow-wrap: anywhere;
119
- white-space: pre-wrap;
120
- }
121
- .tool-definition-fields {
122
- border-top: 1px solid var(--border);
123
- }
124
- .tool-definition-field {
125
- display: grid;
126
- grid-template-columns: minmax(88px, 0.75fr) minmax(0, 1.5fr);
127
- gap: 12px;
128
- padding: 9px 0;
129
- border-bottom: 1px solid var(--border);
130
- font-size: 11px;
131
- line-height: 1.45;
132
- }
133
- .tool-definition-field-name {
134
- display: flex;
135
- min-width: 0;
136
- flex-direction: column;
137
- gap: 3px;
138
- color: var(--text);
139
- }
140
- .tool-definition-field-name code {
141
- overflow-wrap: anywhere;
142
- }
143
- .tool-definition-field-name span {
144
- color: var(--text-dim);
145
- font-size: 10px;
146
- }
147
- .tool-definition-field-name span.required {
148
- color: var(--accent);
149
- }
150
- .tool-definition-field-value {
151
- min-width: 0;
152
- color: var(--text-muted);
153
- overflow-wrap: anywhere;
154
- }
155
- .tool-definition-type {
156
- display: block;
157
- margin-bottom: 3px;
158
- color: var(--text);
159
- }
160
- .tool-definition-meta {
161
- margin-top: 4px;
162
- color: var(--text-dim);
163
- }
164
- .tool-definition-meta code {
165
- color: var(--text-muted);
166
- }
167
- .tool-definition-no-parameters {
168
- padding: 2px 0 10px;
169
- color: var(--text-dim);
170
- font-size: 11px;
171
- }
172
- .tool-definition-guidelines {
173
- margin: 0;
174
- padding-left: 18px;
175
- color: var(--text-muted);
176
- font-size: 11px;
177
- line-height: 1.5;
178
- }
179
- .tool-definitions-empty {
180
- padding: 14px 12px;
181
- color: var(--text-muted);
182
- font-size: 12px;
183
- font-style: italic;
184
- overflow-wrap: anywhere;
185
- }
186
- @media (max-width: 640px) {
187
- .tool-definitions-panel {
188
- grid-template-columns: 112px minmax(0, 1fr);
189
- }
190
- .tool-definitions-item {
191
- padding: 8px 10px;
192
- }
193
- .tool-definition-scroll {
194
- padding: 12px;
195
- }
196
- .tool-definition-field {
197
- grid-template-columns: minmax(74px, 0.7fr) minmax(0, 1.3fr);
198
- gap: 9px;
199
- }
200
- }
201
- `})]})}function p5(e){return e.name||e.firstMessage||e.id.slice(0,12)}function p6(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 p9(e){let{session:t,main:n,selected:i,running:o,onSelect:s}=e,{locale:l,t:a}=(0,E.s)(),d=t.relation?.kind==="subagent"?t.relation:null,c=o?"running":d?.status??"completed",u=n?a("agentSwitcher.main"):d?.description||p5(t),p=n?p5(t):`${d?.profile??a("agentSwitcher.subagent")} \xb7 ${function(e,t){let n=new Date(e).getTime();if(!Number.isFinite(n))return"";let r=Math.round((n-Date.now())/1e3),i=new Intl.RelativeTimeFormat(t,{numeric:"auto"});if(60>Math.abs(r))return i.format(r,"second");let o=Math.round(r/60);if(60>Math.abs(o))return i.format(o,"minute");let s=Math.round(o/60);return 24>Math.abs(s)?i.format(s,"hour"):i.format(Math.round(s/24),"day")}(t.modified,l)}`;return(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":i,onClick:s,style:{width:"100%",minHeight:56,display:"grid",gridTemplateColumns:"28px minmax(0, 1fr) auto",alignItems:"center",gap:9,padding:"7px 12px",border:"none",borderBottom:"1px solid var(--border)",borderLeft:i?"2px solid var(--accent)":"2px solid transparent",background:i?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="transparent")},children:[(0,r.jsx)("span",{style:{width:28,height:28,display:"grid",placeItems:"center",color:n?"var(--text-muted)":"var(--accent)"},children:n?(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"8",r:"4"}),(0,r.jsx)("path",{d:"M4 21a8 8 0 0 1 16 0"})]}):(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]})}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12,fontWeight:i?600:500},title:u,children:u}),(0,r.jsx)("span",{style:{display:"block",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11},title:p,children:p})]}),(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",gap:6,color:n&&!o?"var(--text-dim)":"running"===c||"starting"===c?"var(--accent)":"completed"===c?"#16a34a":"failed"===c?"#dc2626":"aborted"===c?"#d97706":"var(--text-dim)",fontSize:11,whiteSpace:"nowrap"},children:n&&!o?i?a("agentSwitcher.current"):null:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(p6,{status:c}),(0,r.jsx)("span",{children:a(`agentSwitcher.status.${c}`)})]})})]})}function p7(e){let{rootSession:t,subagents:n,selectedSessionId:o,runningSessionIds:s,onSelectSession:l}=e,{t:a}=(0,E.s)(),[d,c]=(0,i.useState)(""),u=(0,i.useMemo)(()=>[...n].sort((e,t)=>{let n=s.has(e.id);return n!==s.has(t.id)?n?-1:1:t.modified.localeCompare(e.modified)}),[s,n]),p=d.trim().toLowerCase(),h=p?u.filter(e=>{let t=e.relation?.kind==="subagent"?e.relation:null;return[t?.description,t?.profile,e.name,e.firstMessage].some(e=>e?.toLowerCase().includes(p))}):u,f=n.filter(e=>s.has(e.id)).length;return(0,r.jsx)("div",{role:"listbox","aria-label":a("agentSwitcher.title"),style:{background:"var(--bg-panel)",borderLeft:"1px solid var(--border)",borderRight:"1px solid var(--border)",borderBottom:"1px solid var(--border)",borderRadius:"0 0 6px 6px",boxShadow:"0 10px 28px rgba(0,0,0,0.10)",overflow:"hidden"},children:(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{minHeight:44,display:"flex",alignItems:"center",gap:8,padding:"7px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("strong",{style:{fontSize:12,fontWeight:600},children:a("agentSwitcher.title")}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:a("agentSwitcher.count",{count:n.length})}),f>0&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--accent)",fontSize:11},children:a("agentSwitcher.runningCount",{count:f})})]}),n.length>8&&(0,r.jsx)("div",{style:{padding:8,borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{type:"search",value:d,onChange:e=>c(e.target.value),placeholder:a("agentSwitcher.search"),"aria-label":a("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)(p9,{session:t,main:!0,selected:t.id===o,running:s.has(t.id),onSelect:()=>l(t)}),h.map(e=>(0,r.jsx)(p9,{session:e,selected:e.id===o,running:s.has(e.id),onSelect:()=>l(e)},e.id)),0===h.length&&(0,r.jsx)("div",{style:{padding:"22px 12px",color:"var(--text-dim)",fontSize:12,textAlign:"center"},children:a("agentSwitcher.noMatches")})]})]})})}var he=n(63606),ht=n(8422);async function hn(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}function hr(e){let{tab:t,active:n,onRestart:o,onClosed:s,onCloseError:l}=e,{t:a}=(0,E.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:s,onCloseError:l});g.current={onClosed:s,onCloseError:l};let[x,v]=(0,i.useState)("connecting"),[b,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(null),[w,S]=(0,i.useState)(0);return(0,i.useEffect)(()=>{var e;let t,n,r,i,o,s=p.current;if(!s)return;let l=!1,a=null,g=!1,x=!1,b=!1;v("connecting"),y(null),k(null);let j=new ht.B({cursorBlink:!0,fontFamily:getComputedStyle(s).getPropertyValue("--font-mono").trim()||"monospace",fontSize:13,lineHeight:1.25,scrollback:8e3,screenReaderMode:!0,disableStdin:!0,theme:{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"}});h.current=j;let S=new he.Y;j.loadAddon(S),j.open(s),j.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&&j.hasSelection())});let C=(e=e=>{l||(b=!0,j.options.disableStdin=!0,y(e.message),v("error"))},n=Promise.resolve(),r=!1,i=null,o=t=>{r||(n=n.then(async()=>{r||(t===i&&(i=null),await hn(`/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:o(i={type:"input",data:t})},resize(e,t){i=null,o({type:"resize",cols:e,rows:t})},stop:()=>(r=!0,i=null,n)});m.current=C;let E=j.onData(e=>{!g||x||b||C.write(e)}),N=()=>{s.offsetWidth&&s.offsetHeight&&S.fit()},I=j.onResize(e=>{let{cols:t,rows:n}=e;!g||x||b||C.resize(t,n)}),$=new ResizeObserver(N);$.observe(s);let T=()=>{l||x||!navigator.onLine||(a?.close(),(a=new EventSource(`/api/terminal/${encodeURIComponent(d)}/events${void 0===t?"":`?after=${t}`}`)).onmessage=e=>{let n=JSON.parse(e.data);if("output"===n.type){if(n.reset)j.reset();else if(void 0!==t&&n.offset<=t)return;j.write(n.data),t=n.offset}else x=!0,g=!1,j.options.disableStdin=!0,a?.close(),k("exit"===n.type?n.exitCode:null),v("exited")},a.onopen=()=>{g=!0,!b&&(j.options.disableStdin=!1,v("ready"),N(),C.resize(j.cols,j.rows),s.offsetWidth&&s.offsetHeight&&j.focus())},a.onerror=()=>{l||x||(g=!1,j.options.disableStdin=!0,v(a?.readyState===EventSource.CLOSED?"error":"connecting"))})};f.current=(async()=>{N(),u||w>0?await hn(`/api/terminal/${encodeURIComponent(d)}`):await hn("/api/terminal",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:d,cwd:c,cols:j.cols,rows:j.rows})}),T()})().catch(e=>{l||(y(e.message),v("error"))});let M=()=>{g=!1,j.options.disableStdin=!0,a?.close(),x||b||v("connecting")},R=e=>{e.persisted&&T()};return window.addEventListener("pagehide",M),window.addEventListener("pageshow",R),window.addEventListener("offline",M),window.addEventListener("online",T),()=>{l=!0,a?.close(),C.stop(),$.disconnect(),E.dispose(),I.dispose(),window.removeEventListener("pagehide",M),window.removeEventListener("pageshow",R),window.removeEventListener("offline",M),window.removeEventListener("online",T),j.dispose(),h.current=null}},[d,c,u,w]),(0,i.useEffect)(()=>{n&&h.current?.focus()},[n]),(0,i.useEffect)(()=>{if(!t.closing)return;let e=!1;return h.current&&(h.current.options.disableStdin=!0),(async()=>{await f.current,await m.current?.stop(),await hn(`/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]),(0,r.jsxs)("section",{className:"terminal-panel","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})]}),"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:o,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===j?a("terminal.exited"):a("terminal.exitCode",{code:j})})]}),(0,r.jsx)("div",{className:"terminal-xterm",children:(0,r.jsx)("div",{ref:p,className:"terminal-xterm-host"})})]})}let hi="pi-web:terminal-tabs";function ho(e){return{id:Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join(""),cwd:e}}function hs(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let hl=[48,120,240,420,720],ha="pi-web:tab-open-session";function hd(){try{return window.sessionStorage}catch{return null}}function hc(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 hu(e,t){t.setItem(ha,JSON.stringify(e))}function hp(e){return`parked-new:${e}`}function hh(){let e,t,n,l,a,d,c,u,p,f,m,g,x,w=(0,o.useRouter)(),S=(0,o.useSearchParams)(),[C,I]=(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")}});ni();let{locale:T,t:M}=(0,E.s)(),R=ew(),L=(0,i.useSyncExternalStore)(ey,ej,ek);(0,i.useEffect)(()=>{let e=window.visualViewport;if(!e)return;let t=document.documentElement,n=null,r=new Set,i=!1,o=()=>{n=null,function(e){let{hasFocusedEditable:t,innerHeight:n,viewportHeight:r,viewportScale:i}=e;return!!t&&n/(i>0?i:1)-r>60}({hasFocusedEditable:hs(),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)},s=()=>{null!==n&&window.cancelAnimationFrame(n),n=window.requestAnimationFrame(o),(()=>{if(i)return;i=!0;let e=0,t=()=>{if(e>=hl.length){i=!1;return}let n=hl[e++],s=window.setTimeout(()=>{r.delete(s),o(),t()},n);r.add(s)};t()})()},l=()=>{hs()&&s()};return s(),e.addEventListener("resize",s),e.addEventListener("scroll",s),window.addEventListener("resize",s),window.addEventListener("focusin",s),window.addEventListener("focusout",s),window.addEventListener("pageshow",s),document.addEventListener("compositionstart",l),document.addEventListener("compositionupdate",l),document.addEventListener("compositionend",l),document.addEventListener("input",l),document.addEventListener("keyup",l),()=>{for(let t of(e.removeEventListener("resize",s),e.removeEventListener("scroll",s),window.removeEventListener("resize",s),window.removeEventListener("focusin",s),window.removeEventListener("focusout",s),window.removeEventListener("pageshow",s),document.removeEventListener("compositionstart",l),document.removeEventListener("compositionupdate",l),document.removeEventListener("compositionend",l),document.removeEventListener("input",l),document.removeEventListener("keyup",l),null!==n&&window.cancelAnimationFrame(n),r))window.clearTimeout(t);r.clear(),t.style.removeProperty("--app-viewport-height"),delete t.dataset.keyboardOpen}},[]),(0,i.useEffect)(()=>{"Notification"in window&&"granted"===Notification.permission&&le(T)},[T]);let{soundEnabled:z,onSoundToggle:A,playDoneSound:W,unlockAudio:P,soundEnabledRef:O}=function(){let[e,t]=(0,i.useState)(()=>{let e=localStorage.getItem("pi-sound-enabled");return null===e||"true"===e}),n=(0,i.useRef)(e);(0,i.useEffect)(()=>{n.current=e},[e]);let r=(0,i.useRef)(null),o=(0,i.useCallback)(()=>{if(r.current&&"closed"!==r.current.state)return r.current;try{r.current=new AudioContext}catch{return null}return r.current},[]),s=(0,i.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!e&&!n.current)return;let t=o();t&&"suspended"===t.state&&t.resume().catch(()=>{})},[o]);return{soundEnabled:e,onSoundToggle:(0,i.useCallback)(()=>{let e=!n.current;e&&s(!0),n.current=e,localStorage.setItem("pi-sound-enabled",String(e)),t(e)},[s]),playDoneSound:(0,i.useCallback)(()=>{if(!n.current)return;let e=o();if(!e)return;let t=()=>{try{let t;t=e.currentTime,[523.25,659.25].forEach((n,r)=>{let i=e.createOscillator(),o=e.createGain();i.connect(o),o.connect(e.destination),i.type="sine",i.frequency.value=n;let s=t+.18*r;o.gain.setValueAtTime(0,s),o.gain.linearRampToValueAtTime(.18,s+.02),o.gain.exponentialRampToValueAtTime(.001,s+.45),i.start(s),i.stop(s+.45)})}catch{}};"suspended"===e.state?e.resume().then(t).catch(()=>{}):t()},[o]),unlockAudio:s,soundEnabledRef:n}}(),[F,B]=(0,i.useState)(!1);(0,i.useEffect)(()=>{try{B("true"===localStorage.getItem("pi-quote-selection-enabled"))}catch{}},[]);let D=(0,i.useCallback)(e=>{B(e);try{localStorage.setItem("pi-quote-selection-enabled",String(e))}catch{}},[]),H=(0,i.useRef)(new Set),_=(0,i.useCallback)(()=>{O.current&&W()},[W,O]),[U,q]=(0,i.useState)(null),[Z,K]=(0,i.useState)([]),V=(0,i.useCallback)(e=>{K(e),q(t=>{if(!t)return t;let n=e.find(e=>e.id===t.id);return n?{...t,...n,detailsPending:n.detailsPending,relation:n.relation,branch:n.branch,isWorktree:n.isWorktree}:t})},[]),J=(0,i.useMemo)(()=>U?[...Z.filter(e=>e.id!==U.id),U]:Z,[U,Z]),Y=(0,i.useMemo)(()=>{var e;return(e=U?.id)?h(J).find(t=>t.root.id===e||t.subagents.some(t=>t.id===e))??null:null},[U?.id,J]),X=!!Y?.subagents.length,[Q,ee]=(0,i.useState)(()=>new Set),et=(0,i.useCallback)(e=>{ee(t=>t.size===e.size&&[...e].every(e=>t.has(e))?t:e)},[]),[en,er]=(0,i.useState)(null),[ei,eo]=(0,i.useState)("initial"),es=(0,i.useRef)(null),[el,ea]=(0,i.useState)(()=>C.requestedCwd?"validating":"idle"),[ed,ec]=(0,i.useState)(null),[eu,ep]=(0,i.useState)(0),[eh,ef]=(0,i.useState)(0),em=(0,i.useRef)(new Map),eg=(0,i.useCallback)((e,t)=>{em.current.set(e,t)},[]),[ex,ev]=(0,i.useState)(null),eb=(0,i.useCallback)(e=>{ev(t=>t===e?null:t)},[]),[eS,eC]=(0,i.useState)(0),[eE,eN]=(0,i.useState)(null),[eI,e$]=(0,i.useState)(0),[eT,eM]=(0,i.useState)(null),[eR,eL]=(0,i.useState)(!1),[ez,eA]=(0,i.useState)(!1),[eW,eP]=(0,i.useState)(null),[eO,eF]=(0,i.useState)(()=>!C.sidebarCollapsed),[eB,eD]=(0,i.useState)(!1),[eH,e_]=(0,i.useState)(!1),eU=eB&&eH&&!R;(0,i.useEffect)(()=>{(!eB||R)&&e_(!1)},[eB,R]);let[eq,eK]=(0,i.useState)(!1),[eV,eJ]=(0,i.useState)(!1),eY=(0,i.useRef)(260),eG=(0,i.useRef)(560),eX=(0,i.useCallback)(()=>N(.42*window.innerWidth,360,640),[]),eQ=(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:eB,rightPanelWidth:eG.current}),[eB]),e0=(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:eO,sidebarWidth:eY.current}),[eO]),e1=$({ariaLabel:M("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:eQ,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"pi-sidebar-width",widthRef:eY}),e2=$({ariaLabel:M("layout.resizeFilePanel"),cssVariable:"--right-panel-width",defaultWidth:560,getDefaultWidth:eX,getMaxWidth:e0,growthDirection:"left",maxWidth:1200,minWidth:300,storageKey:"pi-right-panel-width",widthRef:eG}),e4=e1.reclampWidth,e8=e2.reclampWidth;(0,i.useEffect)(()=>{R&&eF(!1)},[R]),(0,i.useEffect)(()=>{eJ(!0)},[]),(0,i.useEffect)(()=>{eB&&(e4(),e8())},[e8,e4,eB]);let e3=(0,i.useRef)(null),[e5,e6]=(0,i.useState)(null),e9=(0,i.useRef)(null),e7=(0,i.useRef)(null),[te,tt]=(0,i.useState)([]),[tn,tr]=(0,i.useState)(null),[ti,to]=(0,i.useState)(!1),ts=(0,i.useRef)(null),tl=pQ(te),ta=(0,i.useCallback)((e,t,n,r)=>{tt(e),tr(t),to(r),ts.current=n},[]),td=(0,i.useCallback)(e=>{ts.current?.(e)},[]),[tc,tu]=(0,i.useState)(null),[tp,th]=(0,i.useState)(null),[tf,tm]=(0,i.useState)(!1),tg=(0,i.useRef)(null),tx=(0,i.useRef)(0),tv=(0,i.useRef)(null),tb=(0,i.useCallback)(e=>{tu(e),tm(!1)},[]),ty=(0,i.useCallback)(e=>{th(e)},[]),tj=(0,i.useCallback)(e=>{tx.current+=1,tg.current=e,tm(!1)},[]),[tk,tw]=(0,i.useState)(null),[tS,tC]=(0,i.useState)({kind:"idle"}),tE=(0,i.useRef)(null),tN=(0,i.useRef)(U?.id??null);tN.current=U?.id??null;let tI=(0,i.useCallback)(e=>{tw(e)},[]),[t$,tT]=(0,i.useState)(null),tM=(0,i.useRef)(null),tR=(0,i.useCallback)((e,t)=>{no(t).then(()=>{tM.current&&clearTimeout(tM.current),tT(e),tM.current=setTimeout(()=>tT(null),1400)})},[]);(0,i.useEffect)(()=>()=>{tM.current&&clearTimeout(tM.current),tE.current&&clearTimeout(tE.current)},[]);let[tL,tz]=(0,i.useState)(null),tA=(0,i.useCallback)(e=>{tz(e)},[]),[tW,tP]=(0,i.useState)(null),[tO,tF]=(0,i.useState)(null);(0,i.useEffect)(()=>{tl||tP(e=>"branches"===e?null:e)},[tl]),(0,i.useEffect)(()=>{X||tP(e=>"agents"===e?null:e)},[X]),(0,i.useEffect)(()=>{eU&&tP(null)},[eU]);let tB=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];R&&eF(!1),tP(t=>t===e?null:e),R&&L&&t&&eK(!0)},[R,L]),tD=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=tW!==e;if(tB(e,t),!n||tf)return;let r=tg.current;if(!r)return;let i=++tx.current;tm(!0),r().catch(e=>{console.error("Failed to load system information:",e)}).finally(()=>{tx.current===i&&tm(!1)})},[tW,tf,tB]),tH=(0,i.useCallback)(()=>{R&&eF(!1),eK(!1),tP("session")},[R]),t_=(0,i.useCallback)(e=>{eN(e)},[]),tU=(0,i.useCallback)(()=>{R&&(tP(null),eK(!1)),eF(e=>!e)},[R]),tq=(0,i.useCallback)(()=>{eF(!1),tP(null),eK(e=>!e)},[]),tZ=(0,i.useCallback)(()=>{R&&(eF(!1),tP(null),eK(!1)),eD(e=>!e)},[R]),tK=(0,i.useCallback)(()=>{tP(null),e_(e=>!e)},[]);(0,i.useEffect)(()=>{if(!eq)return;let e=e=>{let t=e7.current;t&&e.composedPath().includes(t)||eK(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),eK(!1))};return document.addEventListener("pointerdown",e,!0),document.addEventListener("keydown",t,!0),()=>{document.removeEventListener("pointerdown",e,!0),document.removeEventListener("keydown",t,!0)}},[eq]),(0,i.useEffect)(()=>{eK(!1)},[R,L,U?.id,ei]),(0,i.useEffect)(()=>{if(!tW||!e9.current)return;let e=()=>{let e=e9.current.getBoundingClientRect();"agents"===tW?tF({top:e.bottom,left:e.left,width:Math.min(420,e.width)}):tF({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(e9.current),()=>t.disconnect()},[tW,R]);let[tV,tJ]=(0,i.useState)([]),[tY,tG]=(0,i.useState)(null),[tX,tQ]=(0,i.useState)([]),[t0,t1]=(0,i.useState)(!1),t2=[...tV,...tX.map(e=>({id:e.id,label:G(e.cwd)||e.cwd,filePath:e.cwd,kind:"terminal",closing:!!e.closing}))];(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(hi));tQ(e.tabs),e.activeId&&(tG(e.activeId),eD(e.open))}catch{}t1(!0)},[]),(0,i.useEffect)(()=>{if(t0)try{window.sessionStorage.setItem(hi,JSON.stringify({tabs:tX.map(e=>{let{id:t,cwd:n}=e;return{id:t,cwd:n}}),activeId:tY,open:eB}))}catch{}},[tX,tY,eB,t0]);let t4=(0,i.useCallback)((e,t,n)=>{tJ(r=>(function(e,t,n,r){let i=e.findIndex(e=>e.id===t);if(-1===i||(e[i].viewerRevision??0)!==n)return e;let o=[...e];return o[i]={...o[i],viewerState:r},o})(r,e,t,n))},[]),t8=(0,i.useCallback)((e,t)=>{e3.current?.insertText(rc(e,t)),R&&(eD(!1),eF(!1))},[R]),t3=(0,i.useCallback)(e=>{let t=e.map(e=>rc(e,!1)).join("");t&&e3.current?.insertText(t),R&&(eD(!1),eF(!1))},[R]),t5=(0,i.useCallback)((e,t,n)=>{let r,i,o,s;e3.current?.insertText((r=Math.max(1,Math.min(t,n)),i=Math.max(1,Math.max(t,n)),o=e.includes(" ")?`@"${e}"`:`@${e}`,s=r===i?`:${r}`:`:${r}-${i}`,`${o}${s} `)),R&&(eD(!1),eF(!1))},[R]),t6=C.sessionId,[t9,t7]=(0,i.useState)(null),ne=(0,i.useRef)(null),[nt,nn]=(0,i.useState)(()=>!t6);(0,i.useLayoutEffect)(()=>{var e;let t=(e=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:hd();if(!e)return null;try{return hc(e.getItem(ha))}catch{return null}}(),C.requestedCwd||C.sessionId||!e?C:"session"===e.kind?{...C,sessionId:e.sessionId}:{...C,requestedCwd:e.cwd});t!==C&&(I(t),t.sessionId&&nn(!1))},[C]);let nr=(0,i.useRef)(!1),ns=(0,i.useRef)(0),nl=(0,i.useCallback)(()=>{ns.current+=1},[]);(0,i.useEffect)(()=>{if(U){!function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:b();if(n)try{let r=y(n);r[e]=t,n.setItem(v,JSON.stringify(r))}catch{}}(U.projectKey??ne.current??k(U),U.id),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:hd();if(t&&e)try{hu({kind:"session",sessionId:e},t)}catch{}}(U.id);return}en&&function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:hd(),n=e.trim();if(t&&n)try{hu({kind:"new",cwd:n},t)}catch{}}(en)},[en,U]),(0,i.useEffect)(()=>{let e=C.requestedCwd;if(!e)return;let t=new AbortController;return ea("validating"),ec(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}`);nr.current=!0;let r=`initial:${e}`;eo(r),es.current=`new:${r}:${n.cwd}`,er(n.cwd),ea("ready"),new URLSearchParams(window.location.search).get("cwd")||w.replace(`?cwd=${encodeURIComponent(n.cwd)}`,{scroll:!1})}).catch(e=>{t.signal.aborted||(ec(e instanceof Error?e.message:String(e)),ea("error"))}),()=>t.abort()},[C,w]);let na=(0,i.useCallback)((e,t)=>{let n=++ns.current,r=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:b();if(!t)return null;try{let n=y(t)[e];return"string"==typeof n&&n.length>0?n:null}catch{return null}}(e);if(!r)return;let i=i=>{if(n!==ns.current)return;let o=i?.sessions.find(e=>e.id===r);if(!o){i&&j(e);return}if(k(o)!==e)return void j(e);let s=es.current;s&&rs(s,hp(t)),es.current=null,q(o),ef(e=>e+1),new URLSearchParams(window.location.search).get("session")!==o.id&&w.replace(`?session=${encodeURIComponent(o.id)}`,{scroll:!1})};Z.length>0?i({sessions:Z}):fetch("/api/sessions").then(e=>e.ok?e.json():null).then(i).catch(()=>{})},[w,Z]),nd=(0,i.useCallback)((e,t,n)=>{nl();let r=en??t9;if(t7(e),!e)return;let i=n??t??e,o=ne.current??(U?k(U):null);if(ne.current=i,nr.current){nr.current=!1;return}if(r===e&&o!==i||o===i&&(null!==U||r===e))return;let s=es.current;s&&r&&rs(s,hp(r));let l="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,a=`new:${l}:${e}`;rs(hp(e),a),eo(l),es.current=a,q(null),er(t=>t&&t!==e?null:t),ef(e=>e+1),tt([]),tr(null),to(!1),tu(null),th(null),tm(!1),tP(null),o!==i&&(tJ([]),(!tY||tY.startsWith("file:"))&&(tG(null),eD(!1)),na(i,e)),w.replace(window.location.pathname,{scroll:!1})},[t9,tY,nl,en,w,U,na]),nc=(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;ev(n?{sessionId:e.id,entryId:n,blockIndex:r}:null),nl();let i=es.current,o=en??(null===U?t9:null);i&&o&&rs(i,hp(o)),es.current=null;let s=k(e);if(ne.current!==s&&(tJ([]),(!tY||tY.startsWith("file:"))&&(tG(null),eD(!1)),tP(null)),ne.current=s,!t&&U){let t=k(U)===k(e);if(U.id===e.id&&t){R&&eF(!1);return}}er(null),q(e),ef(e=>e+1),tt([]),tr(null),to(!1),ts.current=null,tu(null),th(null),tm(!1),nn(!0),R&&!t&&eF(!1),t&&(nr.current=!0),t&&new URLSearchParams(window.location.search).get("session")===e.id||w.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[t9,tY,nl,w,R,en,U]),nu=(0,i.useCallback)((e,t)=>{nl();let n=`new:${e}:${t}`;rs(hp(t),n),es.current=n,eo(e),q(null),er(t),ef(e=>e+1),tt([]),tr(null),to(!1),tu(null),th(null),tm(!1),tP(null),R&&eF(!1),w.replace(`?cwd=${encodeURIComponent(t)}`,{scroll:!1})},[nl,w,R]);!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||!s)return;let t=e.target?.tagName;"TEXTAREA"!==t&&"INPUT"!==t&&(e.preventDefault(),s())}(e);if("n"===e.key&&e.ctrlKey&&e.altKey){if(!n||!t)return;e.preventDefault(),t(n)}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[n,t])}({onNewSession:e=>nu(`kb-${Date.now()}`,e),activeCwd:t9});let np=(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(()=>{})},[]),nh=(0,i.useCallback)(async e=>{let t=Z.find(t=>t.id===e);if(t&&!t.transient)return void nc(t);try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}`,{cache:"no-store"}),n=await t.json();if(!t.ok||!n.info)throw Error(n.error??`HTTP ${t.status}`);nc(n.info)}catch(e){console.error("[pi-web] failed to open session:",e instanceof Error?e.message:e)}},[nc,Z]),nf=(0,i.useCallback)((e,t)=>{ep(e=>e+1),es.current===t&&(nl(),es.current=null,er(null),q(e),np(e.id),w.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1}))},[nl,w,np]),nm=(0,i.useCallback)(e=>{let{targetSession:t,title:n,body:r,tag:i}=e;if(!("Notification"in window))return;let o=()=>{iC({title:n,body:r,sessionUrl:t?`/?session=${encodeURIComponent(t.id)}`:"/",tag:i,onClick:()=>{window.focus(),t&&nc(t)}})};"granted"===Notification.permission?(o(),le(T)):"default"===Notification.permission&&Notification.requestPermission().then(e=>{"granted"===e&&(o(),le(T))})},[nc,T]),ng=(0,i.useCallback)(()=>{ep(e=>e+1),eC(e=>e+1),U&&np(U.id),U?.relation?.kind!=="subagent"&&iw()&&nm({targetSession:U,title:U?.name??M("i18n.sessionComplete"),body:M("i18n.taskFinished"),tag:U?`pi-session-complete:${U.id}`:"pi-session-complete"})},[nm,np,U,M]),nx=(0,i.useCallback)(e=>{var t;U?.relation?.kind!=="subagent"&&iw()&&(t=H.current,!(!iS(e)||t.has(e.id))&&(t.add(e.id),1)&&nm({targetSession:U,title:M("i18n.attentionNeeded"),body:"custom"===e.method?M("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[nm,U,M]),nv=(0,i.useCallback)(async()=>{let e=U?.id;if(e&&"naming"!==tS.kind){tE.current&&clearTimeout(tE.current),tP(null),tC({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(ep(e=>e+1),tN.current!==e)return;q(t=>t?.id===e?{...t,name:r}:t),tw(t=>t?.sessionId===e?{...t,sessionName:r}:t),tC({kind:"success"}),tE.current=setTimeout(()=>tC({kind:"idle"}),1800)}catch(t){if(tN.current!==e)return;tC({kind:"error",message:t instanceof Error?t.message:String(t)}),tE.current=setTimeout(()=>tC({kind:"idle"}),5e3)}}},[tS.kind,U?.id]);(0,i.useEffect)(()=>{tE.current&&clearTimeout(tE.current),tC({kind:"idle"})},[U?.id]);let nb=(0,i.useCallback)(()=>{eC(e=>e+1)},[]),ny=(0,i.useCallback)(e=>{nl(),es.current=null,ep(e=>e+1),ef(e=>e+1),er(null),q(t=>({...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1})),np(e),w.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1})},[nl,w,np]),nj=(0,i.useCallback)(async(e,t,n)=>{let r=await iT(t,{type:"fork_branch",entryId:n});if(!r?.newSessionId)throw Error(M("chat.quoteForkFailed"));e6({sessionId:r.newSessionId,text:e}),ny(r.newSessionId)},[ny,M]),nk=(0,i.useCallback)(()=>{nn(!0)},[]),nw=(0,i.useCallback)(e=>{if(nl(),ep(e=>e+1),U?.id===e){!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:hd();if(t&&e)try{let n=hc(t.getItem(ha));if(n?.kind!=="session"||n.sessionId!==e)return;t.removeItem(ha)}catch{}}(e);let t=U.cwd,n="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;eo(n),es.current=t?`new:${n}:${t}`:null,q(null),er(t??null),ef(e=>e+1),tt([]),tr(null),to(!1),tu(null),th(null),tm(!1),tP(null),w.replace(t?`?cwd=${encodeURIComponent(t)}`:window.location.pathname,{scroll:!1})}},[nl,U,w]),nS=(0,i.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,i=n?.modeHint,o=n?.page,s=`file:${e}`;tJ(n=>(function(e,t){let n=e.find(e=>e.id===t.tabId);if(!n)return[...e,{id:t.tabId,label:t.fileName,filePath:t.filePath,sourceSessionId:t.sourceSessionId,initialDisplayMode:t.modeHint,page:t.page,viewerState:t.modeHint?{displayMode:t.modeHint,wrapLines:!1,scrollTop:0,scrollLeft:0}:void 0,viewerRevision:0}];let r=!!(t.sourceSessionId&&n.sourceSessionId!==t.sourceSessionId),i=n.page!==t.page;return r||t.modeHint||i?e.map(e=>{if(e.id!==t.tabId)return e;let n={...e},o=!1;return r&&(n.sourceSessionId=t.sourceSessionId,o=!0),i&&(n.page=t.page,o=!0),t.modeHint&&(n.initialDisplayMode=t.modeHint,n.viewerState={displayMode:t.modeHint,wrapLines:e.viewerState?.wrapLines??!1,scrollTop:0,scrollLeft:0},o=!0),o&&(n.viewerRevision=(e.viewerRevision??0)+1),n}):e})(n,{fileName:t,filePath:e,modeHint:i,page:o,sourceSessionId:r,tabId:s})),tG(s),eD(!0),R&&eF(!1)},[R]),nC=(0,i.useCallback)((e,t)=>{nS(e,G(e),{sourceSessionId:U?.id??null,page:t})},[nS,U?.id]),nE=(0,i.useCallback)(e=>{let t=tX.find(t=>t.cwd===e),n=t??ho(e);t||tQ(e=>[...e,n]),tG(n.id),eD(!0),R&&eF(!1)},[tX,R]),nN=(0,i.useCallback)(e=>{tX.some(t=>t.id===e)?tQ(t=>t.map(t=>t.id!==e||t.closing?t:{...t,closing:"close"})):(tJ(t=>{let n=t.filter(t=>t.id!==e);return 0===n.length&&0===tX.length&&eD(!1),n}),tG(t=>{if(t!==e)return t;let n=tV.filter(t=>t.id!==e);return n.at(-1)?.id??tX.at(-1)?.id??null}))},[tV,tX]),nI=(0,i.useCallback)(()=>{U&&window.open(`/api/sessions/${encodeURIComponent(U.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[U]),n$=en??(null===U&&t9?t9:null),nT=null===U&&n$?`new:${ei}:${n$}`:null;(0,i.useLayoutEffect)(()=>{es.current=nT},[nT]);let nM=null!==U||null!==n$,nR=U?.cwd??n$,nL=nt&&!nM;(0,i.useEffect)(()=>{if(eM(null),eL(!1),eP(null),!nR)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(nR)}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);eM(t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[nR]);let nz=(0,i.useCallback)(async()=>{if(nR&&!ez){eA(!0),eP(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:nR})}),t=await e.json();if(!e.ok||t.error)return void eP({error:t.error??`HTTP ${e.status}`,...t.reason?{reason:t.reason}:{}});eM(t),eL(!1),e$(e=>e+1),ef(e=>e+1)}catch(e){eP({error:e instanceof Error?e.message:String(e)})}finally{eA(!1)}}},[ez,nR]),nA=(0,i.useCallback)(()=>{eP(null),eL(!0)},[]),nW=(0,i.useCallback)((e,t)=>{e===nR&&eM(t)},[nR]),nP=tV.find(e=>e.id===tY)??null,nO=t9?G(t9)||t9:null,nF=nO?`${nO} - Pi Web`:"Pi Web";(0,i.useEffect)(()=>{let e=()=>{document.title!==nF&&(document.title=nF)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[nF]);let nB=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(eZ,{selectedSessionId:U?.id??null,onSelectSession:nc,onNewSession:nu,initialSessionId:t6,skipInitialProjectSelection:null!==C.requestedCwd,onInitialRestoreDone:nk,refreshKey:eu,onSessionDeleted:nw,selectedCwd:U?.cwd??en??null,onCwdChange:nd,onOpenFile:nS,onOpenTerminal:nE,explorerRefreshKey:eS,onExplorerRefresh:nb,onAtMention:t8,onAtMentions:t3,onBackgroundTaskDone:_,onRunningSessionIdsChange:et,onSessionsChange:V}),(0,r.jsxs)("div",{style:{padding:"8px",flexShrink:0,display:"flex",justifyContent:"space-between",gap:4},children:[[["models",M("common.models")],["skills",M("common.skills")]].map(e=>{let[t,n]=e,i=oF(t)&&!nR;return(0,r.jsxs)("button",{type:"button",onClick:()=>eN(t),disabled:i,title:i?M("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)(pO,{section:t,size:14,strokeWidth:2}),(0,r.jsx)("span",{children:n})]},t)}),(0,r.jsxs)("button",{type:"button",onClick:()=>eN(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:oB();if(!t)return"general";try{let n=oD(t).section;if(!("string"==typeof n&&oW.includes(n)))return"general";return oF(n)&&!e?"general":n}catch{return"general"}}(nR)),title:M("common.settings"),"aria-label":M("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)(pO,{section:"general",size:14,strokeWidth:2}),(0,r.jsx)("span",{children:M("common.settings")})]})]})]}),nD=e=>nM&&eT?.requiresTrust&&!eT.trusted?(0,r.jsxs)("button",{type:"button",onClick:nA,title:M("trust.resourcesNotLoaded"),"aria-label":M("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:M("trust.resourcesNotLoaded")})]}):null,nH=e=>{let t,n,i,o,s,l;return e||nM?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",height:"100%"},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>{nI(),e&&L&&eK(!0)},disabled:!U,title:U?M("history.full"):M("history.unsaved"),"aria-label":M("history.full"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"none",border:"none",borderTop:"2px solid transparent",borderRight:"1px solid var(--border)",color:U?"var(--text-muted)":"var(--text-dim)",cursor:U?"pointer":"not-allowed",opacity:U?1:.45,flexShrink:0,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s, opacity 0.1s"},onMouseEnter:e=>{U&&(e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{e.currentTarget.style.color=U?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.background="none"},"data-mobile-toolbar-action":e?"history":void 0,children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:U?"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:M("history.label")})]}),(t=!!(U&&((tk?.userMessages??0)>0||U.messageCount>0)),n=!U||U.transient||!t||"naming"===tS.kind,i="success"===tS.kind,o="error"===tS.kind,s="naming"===tS.kind?M("title.generating"):i?M("title.updated"):o?M("title.failed"):M("title.generate"),l=!U||U.transient?M("title.unsaved"):t?o?tS.message:M("title.generateSession"):M("title.noMessages"),(0,r.jsxs)("button",{type:"button",onClick:()=>{nv(),e&&L&&eK(!0)},disabled:n,title:l,"aria-label":s,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"none",border:"none",borderTop:"2px solid transparent",borderRight:"1px solid var(--border)",color:o?"#dc2626":i?"var(--accent)":n?"var(--text-dim)":"var(--text-muted)",cursor:n?"not-allowed":"pointer",opacity:n&&"naming"!==tS.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=o?"#dc2626":"var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{e.currentTarget.style.color=o?"#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"===tS.kind?(0,r.jsxs)("svg",{className:"animate-spin",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2",opacity:"0.25"}),(0,r.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):i?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m15 4 5 5L7 22l-5-5Z"}),(0,r.jsx)("path",{d:"m14 5 5 5"}),(0,r.jsx)("path",{d:"M6 4V2M5 3H3M19 19v3M17.5 20.5h3"})]}),!e&&(0,r.jsx)("span",{children:s})]})),X&&(0,r.jsxs)("button",{type:"button",onClick:()=>tB("agents",e),title:M("agentSwitcher.title"),"aria-label":M("agentSwitcher.title"),"aria-pressed":"agents"===tW,style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"agents"===tW?"var(--bg-selected)":"none",border:"none",borderTop:"agents"===tW?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"agents"===tW?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},"data-mobile-toolbar-action":e?"agents":void 0,children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]}),!e&&(0,r.jsx)("span",{children:M("agentSwitcher.title")}),(0,r.jsx)("span",{"aria-hidden":"true",style:{minWidth:15,height:15,padding:"0 4px",display:"grid",placeItems:"center",borderRadius:7,background:"var(--bg-selected)",color:"var(--accent)",fontSize:10,lineHeight:1,fontVariantNumeric:"tabular-nums",...e?{position:"absolute",top:2,right:2,minWidth:13,height:13,padding:"0 3px",fontSize:9}:{}},children:Y.subagents.length})]}),tl&&(e?(0,r.jsx)("button",{type:"button",onClick:()=>tB("branches",!0),title:M("i18n.branches"),"aria-label":M("i18n.branches"),"aria-pressed":"branches"===tW,style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:"100%",padding:0,background:"branches"===tW?"var(--bg-selected)":"none",border:"none",borderTop:"branches"===tW?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"branches"===tW?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0},"data-mobile-toolbar-action":"branches",children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:te.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)(p1,{tree:te,activeLeafId:tn,onLeafChange:td,locked:ti,inline:!0,containerRef:e9,open:"branches"===tW,onToggle:()=>tB("branches"),hasSession:!0})),(0,r.jsxs)("button",{ref:tv,type:"button",onClick:()=>tD("system",e),disabled:e&&!nM,title:M("system.prompt"),"aria-label":M("system.prompt"),"aria-pressed":"system"===tW,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"system"===tW?"var(--bg-selected)":"none",border:"none",borderTop:"system"===tW?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:e&&!nM?"not-allowed":"pointer",color:"system"===tW?"var(--text)":"var(--text-muted)",opacity:e&&!nM?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||nM)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="system"===tW?"var(--text)":"var(--text-muted)"},"data-mobile-toolbar-action":e?"system":void 0,children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:tc?"var(--accent)":"var(--text-dim)",flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),(0,r.jsx)("polyline",{points:"14 2 14 8 20 8"}),(0,r.jsx)("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),(0,r.jsx)("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]}),!e&&(0,r.jsx)("span",{children:M("system.label")})]}),(0,r.jsxs)("button",{type:"button",onClick:()=>tD("tools",e),disabled:e&&!nM,title:M("tools.title"),"aria-label":M("tools.title"),"aria-pressed":"tools"===tW,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"tools"===tW?"var(--bg-selected)":"none",border:"none",borderTop:"tools"===tW?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:e&&!nM?"not-allowed":"pointer",color:"tools"===tW?"var(--text)":"var(--text-muted)",opacity:e&&!nM?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||nM)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="tools"===tW?"var(--text)":"var(--text-muted)"},"data-mobile-toolbar-action":e?"tools":void 0,children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:tp?.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:M("tools.label")})]})]}):null},n_=e=>{if(!e&&(!nM||!tk&&!tL))return null;let t=tk?.tokens,n=tk?.cost??0,i=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e),o=n>0?n>=.01?`$${n.toFixed(2)}`:"<$0.01":null,s="var(--text-muted)",l=null,a=null;if(tL?.contextWindow){let e=tL.percent;null!==e&&e>90?s="#ef4444":null!==e&&e>70&&(s="rgba(234,179,8,0.95)"),l=null!==e?`${e.toFixed(0)}% / ${i(tL.contextWindow)}`:`? / ${i(tL.contextWindow)}`,a=null!==e?`${e.toFixed(0)}%`:null}let d=[];if(t&&(d.push(`in: ${t.input.toLocaleString(T)}`),d.push(`out: ${t.output.toLocaleString(T)}`),d.push(`cache read: ${t.cacheRead.toLocaleString(T)}`),d.push(`cache write: ${t.cacheWrite.toLocaleString(T)}`),n>0&&d.push(`cost: $${n.toFixed(4)}`)),tL?.contextWindow){let e=tL.percent;d.push(`context: ${null!==e?e.toFixed(1)+"%":"unknown"} of ${tL.contextWindow.toLocaleString()} tokens`)}let c=d.join(" | "),u=e&&L&&eq,p=!!(t&&(t.input>0||t.output>0)||o||a);return(0,r.jsx)("button",{type:"button",onClick:()=>tB("session"),disabled:!nM||u,tabIndex:u?-1:void 0,title:c||M("session.title"),"aria-label":M("session.title"),"aria-pressed":"session"===tW,"aria-hidden":!!u||void 0,className:e?"mobile-session-stats":void 0,"data-mobile-toolbar-stats":e?"true":void 0,style:{marginLeft:e?0:"auto",display:"flex",alignItems:"center",justifyContent:"flex-end",flex:e?1:void 0,minWidth:0,gap:e?7:10,paddingLeft:e?6:12,paddingRight:e?6:12,height:"100%",overflow:"hidden",visibility:u?"hidden":"visible",pointerEvents:u?"none":"auto",background:"session"===tW?"var(--bg-selected)":"none",border:"none",borderTop:"session"===tW?"2px solid var(--accent)":"2px solid transparent",fontSize:11,color:"var(--text-muted)",whiteSpace:"nowrap",cursor:nM?"pointer":"default",fontVariantNumeric:"tabular-nums",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{nM&&!u&&(e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="session"===tW?"var(--text)":"var(--text-muted)"},children:e?(0,r.jsxs)(r.Fragment,{children:[t&&t.input>0&&(0,r.jsxs)("span",{className:"mobile-session-stat-io",style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"8.5",x2:"5",y2:"1.5"}),(0,r.jsx)("polyline",{points:"2 4 5 1.5 8 4"})]}),i(t.input)]}),t&&t.output>0&&(0,r.jsxs)("span",{className:"mobile-session-stat-io",style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"1.5",x2:"5",y2:"8.5"}),(0,r.jsx)("polyline",{points:"2 6 5 8.5 8 6"})]}),i(t.output)]}),o&&(0,r.jsx)("span",{className:"mobile-session-stat-cost",style:{color:"var(--text)",fontWeight:500,flexShrink:0},children:o}),a&&(0,r.jsx)("span",{style:{color:s,flexShrink:0},children:a}),!p&&nM&&(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",color:"var(--text-dim)"},children:M("session.title")})]}):(0,r.jsxs)(r.Fragment,{children:[t&&t.input>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"8.5",x2:"5",y2:"1.5"}),(0,r.jsx)("polyline",{points:"2 4 5 1.5 8 4"})]}),i(t.input)]}),t&&t.output>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"1.5",x2:"5",y2:"8.5"}),(0,r.jsx)("polyline",{points:"2 6 5 8.5 8 6"})]}),i(t.output)]}),t&&t.cacheRead>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M8.5 5a3.5 3.5 0 1 1-1-2.45"}),(0,r.jsx)("polyline",{points:"6.5 1.5 8.5 2.5 7.5 4.5"})]}),i(t.cacheRead)]}),o&&(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",color:"var(--text)",fontWeight:500},children:o}),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]})]})})},nU=e=>{let t=e&&L&&eq;return(0,r.jsx)("button",{type:"button",onClick:tZ,disabled:t,tabIndex:t?-1:void 0,"aria-controls":"file-panel","aria-expanded":eB,"aria-hidden":!!t||void 0,title:eB?M("files.hidePanel"):M("files.showPanel"),"aria-label":eB?M("files.hidePanel"):M("files.showPanel"),"data-mobile-toolbar-file":e?"true":void 0,style:{marginLeft:e||tk||tL?0:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,visibility:t?"hidden":"visible",pointerEvents:t?"none":"auto",background:eB?"var(--bg-selected)":"none",border:"none",borderLeft:"1px solid var(--border)",color:eB?"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=eB?"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:`
202
- @keyframes session-info-pop {
203
- 0% {
204
- opacity: 0;
205
- transform: translateY(-24px);
206
- filter: blur(6px);
207
- box-shadow: 0 2px 8px rgba(0,0,0,0);
208
- }
209
- 55% {
210
- opacity: 1;
211
- transform: translateY(0);
212
- filter: blur(0);
213
- background: color-mix(in srgb, var(--accent) 8%, var(--bg-panel));
214
- box-shadow: 0 18px 44px rgba(37,99,235,0.16);
215
- }
216
- 100% {
217
- opacity: 1;
218
- transform: translateY(0);
219
- filter: blur(0);
220
- background: var(--bg-panel);
221
- box-shadow: 0 10px 28px rgba(0,0,0,0.10);
222
- }
223
- }
224
- @keyframes session-info-light-wash {
225
- 0% {
226
- opacity: 0;
227
- transform: translateX(-110%) skewX(-16deg);
228
- }
229
- 24% {
230
- opacity: 0.42;
231
- }
232
- 100% {
233
- opacity: 0;
234
- transform: translateX(115%) skewX(-16deg);
235
- }
236
- }
237
- .session-info-popover {
238
- position: relative;
239
- overflow: hidden;
240
- transform-origin: top right;
241
- animation: session-info-pop 360ms ease-out both;
242
- will-change: transform, opacity, filter, background, box-shadow;
243
- }
244
- .session-info-popover::after {
245
- content: "";
246
- position: absolute;
247
- top: 0;
248
- bottom: 0;
249
- left: 0;
250
- width: 44%;
251
- pointer-events: none;
252
- background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--accent) 24%, transparent), transparent);
253
- animation: session-info-light-wash 620ms ease-out both;
254
- }
255
- @media (prefers-reduced-motion: reduce) {
256
- .session-info-popover,
257
- .session-info-popover::after {
258
- animation: none;
259
- }
260
- }
261
- .mobile-session-stats {
262
- container-type: inline-size;
263
- }
264
- @container (max-width: 158px) {
265
- .mobile-session-stat-io {
266
- display: none !important;
267
- }
268
- }
269
- @container (max-width: 88px) {
270
- .mobile-session-stat-cost {
271
- display: none !important;
272
- }
273
- }
274
- @media (max-width: 640px) {
275
- .sidebar-overlay-backdrop.sidebar-mobile-pending {
276
- opacity: 0 !important;
277
- pointer-events: none !important;
278
- }
279
- .sidebar-container.sidebar-mobile-pending.sidebar-open {
280
- transform: translateX(calc(-100% - env(safe-area-inset-left)));
281
- box-shadow: none;
282
- }
283
- }
284
- `}),(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${eV?"":" sidebar-mobile-pending"}`,onClick:()=>eF(!1),style:{position:"fixed",inset:0,zIndex:199,background:"rgba(0,0,0,0.4)",opacity:+!!eO,pointerEvents:eO?"auto":"none",transition:"opacity 0.25s ease"}}),(0,r.jsx)("div",{ref:e1.panelRef,id:"session-sidebar",inert:eU,className:`sidebar-container${eO?" sidebar-open":" sidebar-closed"}${eV?"":" sidebar-mobile-pending"}${e1.isResizing?" sidebar-resizing":""}`,style:{"--sidebar-width":`${e1.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:nB}),eO&&(0,r.jsx)("div",{...e1.separatorProps,inert:eU,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${e1.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${M("layout.resizeSidebar")}: ${M("layout.resizeHint")}`}),(0,r.jsxs)("div",{inert:eU,style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:[(0,r.jsxs)("div",{ref:e9,style:{flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",position:"relative",borderBottom:"1px solid var(--border)",height:"calc(36px + env(safe-area-inset-top))",paddingTop:"env(safe-area-inset-top)"},children:[(0,r.jsx)("button",{onClick:tU,title:eO?M("sidebar.hide"):M("sidebar.show"),"aria-label":eO?M("sidebar.hide"):M("sidebar.show"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:"none",border:"none",borderRight:"1px solid var(--border)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},children:eO?(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"})]})}),R&&(0,r.jsxs)("div",{ref:e7,"data-mobile-toolbar":"true",style:{position:"relative",display:"flex",alignItems:"stretch",flex:1,minWidth:0,height:"100%"},children:[L&&(0,r.jsx)("button",{type:"button",onClick:tq,title:eq?M("chat.close"):M("chat.moreControls"),"aria-label":eq?M("chat.close"):M("chat.moreControls"),"aria-controls":"mobile-toolbar-actions","aria-expanded":eq,"data-mobile-toolbar-more":"true",style:{position:"relative",zIndex:eq?21:void 0,display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:eq?"var(--bg-selected)":"none",border:"none",borderRight:"1px solid var(--border)",color:eq?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s, background 0.12s"},children:eq?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"5",x2:"19",y2:"19"}),(0,r.jsx)("line",{x1:"19",y1:"5",x2:"5",y2:"19"})]}):(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"5",cy:"12",r:"1.5"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1.5"}),(0,r.jsx)("circle",{cx:"19",cy:"12",r:"1.5"})]})}),!L&&nH(!0),n_(!0),nU(!0),L&&eq&&(0,r.jsx)("div",{id:"mobile-toolbar-actions",role:"toolbar","aria-label":M("chat.moreControls"),"data-mobile-toolbar-actions":"true",style:{position:"absolute",top:0,right:0,bottom:0,left:36,zIndex:20,display:"flex",alignItems:"stretch",background:"color-mix(in srgb, var(--bg-panel) 94%, var(--bg))",boxShadow:"4px 0 18px rgba(0,0,0,0.12)",backdropFilter:"blur(10px)"},children:nH(!0)})]}),!R&&(0,r.jsxs)(r.Fragment,{children:[nD(!1),nH(!1),n_(!1)]}),!R&&nU(!1),R&&tl&&(0,r.jsx)(p1,{tree:te,activeLeafId:tn,onLeafChange:td,locked:ti,inline:!0,compact:!0,containerRef:e9,open:"branches"===tW,onToggle:()=>tB("branches"),hasSession:nM,hideInlineButton:!0}),tW&&tO&&(0,r.jsxs)("div",{style:{position:"fixed",top:tO.top,left:tO.left,width:tO.width,maxHeight:`calc(100dvh - ${tO.top}px)`,overflowY:"auto",zIndex:500},children:["agents"===tW&&Y&&U&&(0,r.jsx)(p7,{rootSession:Y.root,subagents:Y.subagents,selectedSessionId:U.id,runningSessionIds:Q,onSelectSession:nc}),"system"===tW&&(0,r.jsx)(p2,{loading:tf,prompt:tc,translate:M}),"tools"===tW&&(0,r.jsx)(p3,{loading:tf,tools:tp,translate:M}),"session"===tW&&(0,r.jsx)("div",{className:"session-info-popover",style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",boxShadow:"0 10px 28px rgba(0,0,0,0.10)",padding:"12px 16px"},children:tk?(e=tk.totalActiveMs??0,t=[...tk.sessionName?[{label:M("session.name"),value:tk.sessionName,copyField:null}]:[],{label:M("session.file"),value:tk.sessionFile??M("session.inMemory"),copyField:"file"},{label:M("session.id"),value:tk.sessionId,copyField:"id"},...e>0?[{label:M("session.totalActive"),value:(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`})(e),copyField:null}]:[]],n=[...U?[{label:M("session.projectDir"),value:U.projectRoot??U.cwd,copyField:"projectDir"}]:[],...U?.branch?[{label:M("session.gitBranch"),value:U.branch,copyField:"gitBranch"}]:[],...U?.isWorktree?[{label:M("session.gitWorktree"),value:U.cwd,copyField:"gitWorktree"}]:[]],l=[[M("session.user"),tk.userMessages.toLocaleString(T)],[M("session.assistant"),tk.assistantMessages.toLocaleString(T)],[M("session.toolCalls"),tk.toolCalls.toLocaleString(T)],[M("session.toolResults"),tk.toolResults.toLocaleString(T)],[M("session.total"),tk.totalMessages.toLocaleString(T)]],a=[[M("session.input"),tk.tokens.input.toLocaleString(T)],[M("session.output"),tk.tokens.output.toLocaleString(T)],...tk.tokens.cacheRead>0?[[M("session.cacheRead"),tk.tokens.cacheRead.toLocaleString(T)]]:[],...tk.tokens.cacheWrite>0?[[M("session.cacheWrite"),tk.tokens.cacheWrite.toLocaleString(T)]]:[],[M("session.total"),tk.tokens.total.toLocaleString(T)]],d=tL??tk.contextUsage,u=[...tk.cost>0?[[M("session.cost"),`$${tk.cost.toFixed(4)}`]]:[],...d?.contextWindow?[[M("session.context"),`${null!==d.percent?`${d.percent.toFixed(1)}%`:"?"} / ${(c=d.contextWindow)>=1e6?`${(c/1e6).toFixed(1)}M`:c>=1e3?`${(c/1e3).toFixed(0)}k`:String(c)}`]]:[],...tk.tokens.cacheRead+tk.tokens.cacheWrite>0&&tk.tokens.cacheRead+tk.tokens.cacheWrite+tk.tokens.input>0?[[M("session.cacheHitRate"),`${(tk.tokens.cacheRead/(tk.tokens.cacheRead+tk.tokens.cacheWrite+tk.tokens.input)*100).toFixed(1)}%`]]:[]],p=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[o,s]=t;return(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:o}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:i?"normal":"anywhere",textAlign:n,whiteSpace:"right"===n?"nowrap":"normal"},children:s})]},`${e}:${o}`)})})]})},f={file:"session.copyFile",id:"session.copyId",projectDir:"session.copyProjectDir",gitBranch:"session.copyGitBranch",gitWorktree:"session.copyGitWorktree"},m=(e,t)=>{let n=t$===e;return(0,r.jsx)("button",{type:"button",title:n?M("session.copied"):M(f[e]),onClick:()=>tR(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"})]})})},g=(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:M("session.infoSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:t.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?m(e.copyField,e.value):null})]},`session-info:${e.label}`))})]}),x=n.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:M("session.projectSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:n.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?m(e.copyField,e.value):null})]},`project-info:${e.label}`))})]}):null,(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:R?"1fr":"minmax(360px, 1.7fr) minmax(140px, 0.55fr) minmax(190px, 0.75fr)",gap:R?16:24,fontSize:12,lineHeight:1.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:R?16:20},children:[g,x]}),p(M("session.messages"),l),p(M("session.tokens"),[...a,...u],"right",!0)]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:M("session.load")})})]})]}),R&&nD(!0)]}),(0,r.jsx)("div",{style:{flex:1,overflow:"hidden",position:"relative"},children:nM?(0,r.jsx)(ot,{session:U,searchTarget:ex?.sessionId===U?.id?ex:null,onSearchTargetHandled:eb,initialScrollPosition:U?em.current.get(U.id)??null:null,onScrollPositionChange:eg,sessionRunning:!!(U&&Q.has(U.id)),newSessionCwd:n$,newSessionDraftKey:nT,onAgentEnd:ng,onAttentionNeeded:nx,onSessionCreated:nf,onSessionForked:ny,modelsRefreshKey:eI,chatInputRef:e3,onBranchDataChange:ta,onSystemPromptChange:tb,onSystemToolsChange:ty,onSystemInfoLoaderChange:tj,onSessionStatsChange:tI,onSessionStatsPanelOpen:tH,onOpenSettings:t_,onContextUsageChange:tA,onOpenFile:nC,onOpenSession:nh,onAskInNewChat:nj,quoteSelectionEnabled:F,initialPrompt:e5?.sessionId===U?.id?e5?.text:void 0,onInitialPromptConsumed:()=>e6(null),soundEnabled:z,onSoundToggle:A,playDoneSound:W,unlockAudio:P},eh):"validating"===el?(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:M("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:C.requestedCwd})]}):"error"===el?(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:M("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:ed})]}):nL?t9?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:M("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:M("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."}),M("workspace.selectProject"),(0,r.jsx)("br",{}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),M("workspace.addModels")]})]})]}):null})]}),(0,r.jsx)("div",{"aria-hidden":"true",className:`right-panel-overlay-backdrop${eB?" is-open":""}`,onClick:()=>eD(!1)}),eB&&(0,r.jsx)("div",{...e2.separatorProps,inert:eU,"aria-controls":"file-panel",className:`panel-resize-handle right-panel-resize-handle${e2.isResizing?" is-resizing":""}`,"data-resize-handle":"right-panel",title:`${M("layout.resizeFilePanel")}: ${M("layout.resizeHint")}`}),(0,r.jsxs)("div",{ref:e2.panelRef,id:"file-panel",className:`right-panel-container${eB?" right-panel-open":" right-panel-closed"}${eU?" right-panel-full-width":""}${e2.isResizing?" right-panel-resizing":""}`,style:{"--right-panel-width":`${e2.width}px`,display:"flex",flexDirection:"column",borderLeft:"1px solid var(--border)",background:"var(--bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexShrink:0,height:"calc(36px + env(safe-area-inset-top))",paddingTop:"env(safe-area-inset-top)",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{flex:1,overflow:"hidden"},children:(0,r.jsx)(oz,{tabs:t2,activeTabId:tY??"",onSelectTab:tG,onCloseTab:nN})}),(0,r.jsx)("button",{type:"button",className:"file-panel-expand-button",onClick:tK,"aria-controls":"file-panel","aria-pressed":eU,title:M(eU?"files.restorePanelWidth":"files.expandPanel"),"aria-label":M(eU?"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:eU?"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:()=>eD(!1),"aria-controls":"file-panel","aria-expanded":eB,title:M("files.hidePanel"),"aria-label":M("files.hidePanel"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:"var(--bg-selected)",border:"none",borderLeft:"1px solid var(--border)",color:"var(--text)",cursor:"pointer",flexShrink:0,transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text)"},children:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"15",y1:"3",x2:"15",y2:"21"})]})})]}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflow:"hidden",paddingBottom:"env(safe-area-inset-bottom)"},children:[nP?.filePath?(0,r.jsx)(oR,{filePath:nP.filePath,cwd:t9??void 0,sourceSessionId:nP.sourceSessionId,gitRefreshKey:eS,initialDisplayMode:nP.initialDisplayMode,initialPage:nP.page,initialState:nP.viewerState,watchEnabled:eB,onStateChange:e=>t4(nP.id,nP.viewerRevision??0,e),onMentionLines:eB?t5:void 0,onAtMention:t8,onOpenFile:(e,t)=>nS(e,G(e),{sourceSessionId:nP.sourceSessionId,page:t})},`${nP.id}:${nP.viewerRevision??0}`):tX.some(e=>e.id===tY)?null:(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12},children:M("files.noneOpen")}),tX.map(e=>(0,r.jsx)("div",{hidden:e.id!==tY,style:{width:"100%",height:"100%"},children:(0,r.jsx)(hr,{tab:e,active:eB&&e.id===tY,onRestart:()=>tQ(t=>t.map(t=>t.id===e.id?{...t,closing:"restart"}:t)),onClosed:()=>{let t,n;return t="restart"===e.closing?ho(e.cwd):null,n=tX.filter(t=>t.id!==e.id),void(tQ(n=>n.flatMap(n=>n.id!==e.id?[n]:t?[t]:[])),tG(r=>r!==e.id?r:t?.id??n.at(-1)?.id??tV.at(-1)?.id??null),!t&&!n.length&&!tV.length&&eD(!1))},onCloseError:()=>tQ(t=>t.map(t=>t.id===e.id?{...t,closing:void 0}:t))})},e.id))]})]})]}),eE&&(0,r.jsx)(pD,{cwd:nR,sessionId:U?.id??null,initialSection:eE,quoteSelectionEnabled:F,onQuoteSelectionChange:D,onClose:()=>{eN(null),e$(e=>e+1)},onSessionReloaded:()=>ef(e=>e+1),projectTrust:eT,onOpenTrustDialog:nA,onProjectTrustChanged:nW}),eR&&nR&&(0,r.jsx)(p_,{cwd:nR,busy:ez,error:eW,onCancel:()=>{ez||eL(!1)},onConfirm:()=>void nz(),onStatus:eM})]})}}},e=>{e.O(0,[7523,7330,3888,5772,7005,1278,8441,3794,7358],()=>e(e.s=42927)),_N_E=e.O()}]);