@pricening/pi-web 0.10.1 → 0.10.2
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.
- package/.next/BUILD_ID +1 -1
- package/.next/app-path-routes-manifest.json +10 -10
- package/.next/build-manifest.json +2 -2
- package/.next/prerender-manifest.json +3 -3
- package/.next/required-server-files.js +1 -1
- package/.next/required-server-files.json +1 -1
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +4 -4
- package/.next/server/app/_not-found.segments/_full.segment.rsc +4 -4
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +4 -4
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +3 -3
- package/.next/server/app/api/app-update/route.js +1 -1
- package/.next/server/app/api/auth/api-key/[provider]/route.js +1 -1
- package/.next/server/app/api/auth/login/[provider]/route.js +2 -2
- package/.next/server/app/api/auth/logout/[provider]/route.js +1 -1
- package/.next/server/app/api/auth/providers/route.js +1 -1
- package/.next/server/app/api/mcp/route.js +1 -1
- package/.next/server/app/api/models/default/route.js +1 -1
- package/.next/server/app/api/models/default/route.js.nft.json +1 -1
- package/.next/server/app/api/models/enabled/route.js +1 -1
- package/.next/server/app/api/models/enabled/route.js.nft.json +1 -1
- package/.next/server/app/api/models/refresh/route.js +1 -1
- package/.next/server/app/api/models/route.js +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +6 -6
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +6 -6
- package/.next/server/app/index.segments/_full.segment.rsc +6 -6
- package/.next/server/app/index.segments/_tree.segment.rsc +3 -3
- package/.next/server/app/login/page_client-reference-manifest.js +1 -1
- package/.next/server/app/login.html +1 -1
- package/.next/server/app/login.rsc +5 -5
- package/.next/server/app/login.segments/_full.segment.rsc +5 -5
- package/.next/server/app/login.segments/_tree.segment.rsc +3 -3
- package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +5 -5
- package/.next/server/app/page.js +21 -21
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app-paths-manifest.json +10 -10
- package/.next/server/chunks/2243.js +1 -1
- package/.next/server/chunks/27.js +1 -0
- package/.next/server/chunks/3573.js +1 -1
- package/.next/server/chunks/3757.js +1 -1
- package/.next/server/chunks/6429.js +2 -2
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/chunks/1278-efc45c56766dfb9e.js +1 -0
- package/.next/static/chunks/3298-67d510dd5eefea7b.js +7 -0
- package/.next/static/chunks/app/{layout-a64273ce41b09cd9.js → layout-b443c6bf63e2119b.js} +1 -1
- package/.next/static/chunks/app/page-45e40373d5a8ac1a.js +284 -0
- package/.next/static/css/37802f9958c09c58.css +1 -0
- package/.next/static/css/{2da826216fd8066e.css → a4227f38b1abed42.css} +1 -1
- package/.next/trace +86 -86
- package/.next/trace-build +1 -1
- package/bin/pi-web.js +10 -0
- package/bin/rotate-preview-secrets.js +105 -0
- package/package.json +3 -2
- package/public/sw.js +20 -4
- package/public/sw.test.mjs +48 -4
- package/.next/server/chunks/436.js +0 -1
- package/.next/static/chunks/1278-6ef40c1ca1107675.js +0 -1
- package/.next/static/chunks/7005-327c123cad9d0daa.js +0 -7
- package/.next/static/chunks/app/page-55162cf6bcd5684e.js +0 -284
- package/.next/static/css/68dcfd9f73879adb.css +0 -1
- /package/.next/static/{IacmWhIrPnlXerbcRBDZ5 → KOelKxgKy8Fd8scUKNriY}/_buildManifest.js +0 -0
- /package/.next/static/{IacmWhIrPnlXerbcRBDZ5 → KOelKxgKy8Fd8scUKNriY}/_ssgManifest.js +0 -0
|
@@ -0,0 +1,284 @@
|
|
|
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,59682)),Promise.resolve().then(n.bind(n,21278))},59682:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>hU});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 $(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function I(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)&&$(u,i),i},[S,w,u,p]),E=(0,i.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),I=(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&&I(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,I,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 I(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,I,a]),R=(0,i.useCallback)(e=>{I(e.pointerId)},[I]),L=(0,i.useCallback)(e=>{I(e.pointerId)},[I]),z=(0,i.useCallback)(e=>{I(e.pointerId)},[I]),W=(0,i.useCallback)(()=>{C(s?.()??o,{forcePersist:!0})},[C,o,s]),A=(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(),W())},[n,C,k,a,c,W,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&&$(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&&I(e.pointerId)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[I,v]),(0,i.useEffect)(()=>()=>{let e=f.current;e&&(f.current=null,E(e))},[E]),{isResizing:v,panelRef:h,reclampWidth:A,resetWidth:W,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:W,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},W={...z,border:0,background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600},A={...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),I(""),z(null))},q=async()=>{let e=$.trim();if(u&&e&&!D){H(!0),z(null);try{let t=await O(u,e);N(!1),I(""),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:{...A,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:{...A,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:{...W,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:$,autoFocus:!0,autoComplete:"off",spellCheck:!1,placeholder:a("directoryPicker.directoryNamePlaceholder"),onChange:e=>{I(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||!$.trim(),style:{...W,flex:1,opacity:D?.65:1,cursor:D||!$.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:{...A,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}`}function et(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 en(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function er(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 ei(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function eo(e,t,n,r){return new Promise((i,o)=>{let s=new FormData;t.forEach(e=>s.append("files",e,e.name));let l=new XMLHttpRequest;l.open("POST",`/api/files/${Y(e)}?type=upload&conflict=${n}`),l.upload.onprogress=e=>{r&&e.lengthComputable&&e.total>0&&r(Math.round(e.loaded/e.total*100))},l.onerror=()=>o(Error("Network error while uploading files")),l.onabort=()=>o(Error("Upload cancelled")),l.onload=()=>{let e={};try{e=JSON.parse(l.responseText)}catch{l.responseText&&(e.error=l.responseText)}i({status:l.status,data:e})},l.send(s)})}async function es(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 el(e){let t=Y(e),n=await fetch(`/api/files/${t}?type=list`);if(!n.ok)throw await es(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 ea(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 es(n,"Failed to allow the linked folder")}async function ed(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 ec={modified:"files.modified",added:"files.added",deleted:"files.deleted",renamed:"files.renamed",untracked:"files.untracked",conflict:"files.conflict"},eu={modified:"#d6a84b",added:"#4ade80",deleted:"#f87171",renamed:"#60a5fa",untracked:"#4ade80",conflict:"#f87171"};function ep(e){let{status:t,t:n}=e;return(0,r.jsx)("span",{title:n(ec[t.status]),"aria-label":n(ec[t.status]),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:eu[t.status],fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600},children:t.code})}function eh(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 ef(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 em(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,W]=(0,i.useState)(null),A=t.outsideLinkTarget&&t.outsideLinkTarget!==T?t.outsideLinkTarget:null;(0,i.useEffect)(()=>{M(null),W(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 el(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&&!A&&P(!0)},[c]);let O=(0,i.useCallback)(()=>{if(t.isDir){let e=!m;d(t.fullPath,e),!e||k||A||P()}else s(t.fullPath,t.name)},[t.isDir,t.fullPath,t.name,k,m,A,P,s,d]),F=(0,i.useCallback)(async e=>{if((e.stopPropagation(),A)&&(!t.outsideLinkEncloses||window.confirm(f("files.allowEnclosingLinkConfirm",{target:A})))){L(!0),W(null);try{await ea(t.fullPath,A),M(A),await P(!0)}catch(e){W(e instanceof Error?e.message:String(e))}finally{L(!1)}}},[t.fullPath,t.outsideLinkEncloses,A,P,f]);return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{onClick:O,onMouseEnter:()=>I(!0),onMouseLeave:()=>I(!1),style:{position:"relative",display:"flex",alignItems:"center",gap:4,paddingLeft:8+14*n,paddingRight:8,height:24,cursor:"pointer",background:$?"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}),!$&&A&&(0,r.jsx)("span",{title:f("files.outsideLink",{target:A}),"aria-label":f("files.outsideLink",{target:A}),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)"},children:(0,r.jsx)(ef,{})}),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"}})}),!$&&!t.isDir&&v&&(0,r.jsx)(ep,{status:v,t:f}),!$&&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&&$&&(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)(eh,{}),f("files.mention")]}),$&&!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&&A&&(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:A})}),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:A}),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&&!A&&(0,r.jsxs)("div",{children:[y.map(e=>(0,r.jsx)(em,{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 eg(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)(ep,{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)(eh,{}),l("files.mention")]})]})}let ex=(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,W]=(0,i.useState)(0),[A,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),[en,er]=(0,i.useState)(new Set),ei=(0,i.useRef)(null),es=(0,i.useRef)(null),ea=(0,i.useRef)(null),ec=`${s??0}:${w}`,ep="idle"!==R,ef=_.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&&ei.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))}er(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 ex=(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]),ev=(0,i.useMemo)(()=>new Map($.map(e=>[J(e.filePath),e])),[$]),eb=(0,i.useMemo)(()=>{let e=new Set,t=J(n).replace(/\/$/,"");for(let n of $){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,$]),ey=(0,i.useCallback)((e,t)=>{k(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},[]),ej=(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]),ek=(0,i.useCallback)(async(e,t)=>{D(null),P(null),W(0),L("uploading");try{let{status:r,data:i}=await eo(n,e,t,W);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})`);W(100),ej(i)}catch(e){P(e instanceof Error?e.message:String(e))}finally{L("idle")}},[ej,n]),ew=(0,i.useCallback)(async e=>{if(0!==e.length&&!ep){F(null),N(new Set),D(null),P(null),W(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 ek(e,"error")}catch(e){P(e instanceof Error?e.message:String(e))}finally{L("idle")}}},[n,ek,ep]),eS=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",ew(t)},[ew]);(0,i.useImperativeHandle)(t,()=>({openUploadPicker(){ep||ea.current?.click()}}),[ep]),(0,i.useEffect)(()=>{d?.(ep)},[d,ep]),(0,i.useEffect)(()=>()=>d?.(!1),[d]),(0,i.useEffect)(()=>{let e=es.current!==n;es.current=n,e&&(k(new Set),N(new Set),F(null),D(null),P(null)),v(e),y(null);let t=!1;return el(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 ed(n).then(t=>{e||(I(t.isGitRepository?t.files:[]),M(t.isGitRepository?{additions:t.additions,deletions:t.deletions}:{additions:0,deletions:0}))}).catch(()=>{e||(I([]),M({additions:0,deletions:0}))}),()=>{e=!0}},[n,s,w]),(0,i.useEffect)(()=>{u?.($.length)},[$,u]);let eC=ep||null!==B||null!==A||null!==O,eE=(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:ea,type:"file",multiple:!0,hidden:!0,onChange:eS}),eC&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[ep&&(0,r.jsxs)("div",{role:"status","aria-live":"polite","aria-label":"checking"===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 ek(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 ek(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")})]})]}),A&&(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:A}),(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:eE,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)(eh,{}),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:ei,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"})]})})]}),ef&&(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:ex.map(e=>(0,r.jsx)(em,{node:e,depth:0,cwd:n,onOpenFile:o,onAtMention:l,expandedPaths:en,onToggleExpanded:(e,t)=>{er(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},highlightedPaths:C,gitStatusByPath:ev,changedDirectoryPaths:eb,t:f},`${_}:${e.fullPath}`))})]})]}),!c&&$.length>0&&(0,r.jsxs)("div",{style:{padding:"0 4px 2px"},children:[(0,r.jsxs)("div",{"aria-label":f("files.changeStats",{count:$.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:$.length})}),(0,r.jsxs)("span",{style:{color:eu.added,fontFamily:"var(--font-mono)"},children:["+",T.additions]}),(0,r.jsxs)("span",{style:{color:eu.deleted,fontFamily:"var(--font-mono)"},children:["-",T.deletions]})]}),$.map(e=>(0,r.jsx)(eg,{status:e,cwd:n,onOpenFile:o,onAtMention:l,t:f},e.filePath))]}),(c||0===$.length)&&(!p||!ef)&&(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)(em,{node:e,depth:0,cwd:n,onOpenFile:o,onAtMention:l,expandedPaths:j,onToggleExpanded:ey,refreshToken:ec,highlightedPaths:C,gitStatusByPath:ev,changedDirectoryPaths:eb,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 ev(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 eb="(max-width: 640px)",ey="(max-width: 480px)";function ej(e,t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)}function ek(e){return!!window.matchMedia&&window.matchMedia(e).matches}let ew=e=>ej(eb,e),eS=()=>ek(eb),eC=e=>ej(ey,e),eE=()=>ek(ey);function eN(){return!1}function e$(){return(0,i.useSyncExternalStore)(ew,eS,eN)}let eI={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:"釘選儲存失敗"}},eT={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"},eM={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 eR(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 eL(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=e$(),[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=eI[c]??eI.en,k=o?"session"===t?j.unpinSession:j.unpinProject:"session"===t?j.pinSession:j.pinProject,w="action"===l?eT:eM,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)(eR,{filled:o})})}let ez={en:{archiveProject:"Archive project",unarchiveProject:"Unarchive project",archiveFailed:"Could not save the archive"},"zh-CN":{archiveProject:"归档项目",unarchiveProject:"取消归档",archiveFailed:"归档保存失败"},"zh-TW":{archiveProject:"封存專案",unarchiveProject:"取消封存",archiveFailed:"封存儲存失敗"}},eW={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 eA(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 eP(e){let{id:t,archived:n,onToggle:o,as:s="button"}=e,{locale:l}=(0,E.s)(),a=e$(),[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=ez[l]??ez.en,x=n?g.unarchiveProject:g.archiveProject,v={...eW,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)(eA,{filled:n})})}function eO(e){return new Set(e.projects)}function eF(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 eB(e,t){if(e.size!==t.size)return!0;for(let n of e)if(!t.has(n))return!0;return!1}let eD={remote:"sidebar.openInExplorerRemoteOnly","unsupported-platform":"sidebar.openInExplorerUnsupported"};function eH(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 e_="pi-web:unread-session-ids",eU="pi-web:last-custom-cwd";function eq(){try{return window.localStorage.getItem(eU)??""}catch{return""}}function eZ(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function eK(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 eV(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 eJ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function eY(){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:eJ[Math.floor(Math.random()*eJ.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.2p1.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 eG(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:$,onAtMentions:M,onBackgroundTaskDone:R,onRunningSessionIdsChange:L,onSessionsChange:z}=e,{t:W}=(0,E.s)(),{sets:A,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=eO(eF(e));n.current+=1,t(e=>eB(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=eF(await r.json());if(e!==n.current)return;t(e=>{let t=eO(i);return eB(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)(eq),[ep,eh]=(0,i.useState)(null),[ef,em]=(0,i.useState)(!1),[eg,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)(""),[eI,eT]=(0,i.useState)(null),[eM,eR]=(0,i.useState)(!1),[ez,eW]=(0,i.useState)(null),[eA,eJ]=(0,i.useState)(null),eG=(0,i.useRef)(null),eX=(0,i.useRef)(null),[eQ,e1]=(0,i.useState)(!0),[e2,e4]=(0,i.useState)(0),[e8,e5]=(0,i.useState)(!1),[e3,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(e_);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,eQ&&!!(v||X));let tE=(0,i.useRef)(null),tN=(0,i.useRef)(null),t$=(0,i.useRef)(320),tI=(0,i.useCallback)(()=>{if(!eQ)return 320;let e=tE.current?.getBoundingClientRect().height,t=tN.current?.getBoundingClientRect().height;return e&&t?Math.round((e+t)/2):320},[eQ]),tT=(0,i.useCallback)(()=>eQ&&(v||X)?Math.max(80,(tE.current?.getBoundingClientRect().height??320)+(tN.current?.getBoundingClientRect().height??120)-120):1600,[eQ,X,v]),tM=I({ariaLabel:W("layout.resizeSidebarSections"),axis:"vertical",cssVariable:"--sidebar-session-pane-height",defaultWidth:320,getDefaultWidth:tI,getMaxWidth:tT,growthDirection:"down",maxWidth:1600,minWidth:80,storageKey:"pi-web:sidebar-session-pane-height",widthRef:t$}),[tR,tL]=(0,i.useState)(0),[tz,tW]=(0,i.useState)(0),[tA,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,tW(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),tW(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=W(td?.platform==="darwin"?"sidebar.openInFinder":td?.platform==="win32"?"sidebar.openInExplorer":"sidebar.openInFileManager"),tZ=td?.supported===!1,tK=tu?W(eD[tu]??tu):null;(0,i.useEffect)(()=>{try{0===tm.size?window.localStorage.removeItem(e_):window.localStorage.setItem(e_,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(eg?.cwd===e)return tJ(eg.root,eg.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)},[eg,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),eJ(null);return}let e=!1;return eJ(X),fetch(`/api/worktrees?cwd=${encodeURIComponent(X)}`).then(e=>e.json()).then(t=>{if(!e){if(eJ(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||(eJ(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&&!ef){em(!0),eh(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 eh(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(eU,r)}catch{}eu(i.cwd)}Q(i.cwd),ed(!1),er(!1)}catch(e){eh(e instanceof Error?e.message:String(e))}finally{em(!1)}}},[ec,ef]),t8=(0,i.useCallback)(()=>{ed(!0),eh(null),er(!1)},[]),t5=(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]),t3=(0,i.useCallback)(async()=>{let e=eN.trim();if(e&&!eM&&ej){eR(!0),eT(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 eT(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){eT(e instanceof Error?e.message:String(e))}finally{eR(!1)}}},[eN,eM,ej]),t6=(0,i.useCallback)(async(e,t)=>{if(ej&&!eM){eR(!0),eT(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 eW(e);eT(r.error??`HTTP ${n.status}`);return}eW(null),t2===e&&Q(ej.projectRoot),t0(e=>e+1)}catch(e){eT(e instanceof Error?e.message:String(e))}finally{eR(!1)}}},[ej,eM,t2]);(0,i.useEffect)(()=>{let e=e=>{ey.current&&!ey.current.contains(e.target)&&(er(!1),eo("")),eG.current&&!eG.current.contains(e.target)&&(eS(!1),eE(!1),e$(""),eT(null),eW(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,A.projects,F),[U,A.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(eg?.key)},[nn,eg?.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:W("sidebar.openRepoRoot"),title:W("sidebar.openRepoRootTitle")}:{label:W("sidebar.gitRepoRootOnly"),title:W("sidebar.gitRepoRootOnlyTitle")}:null,np=!!(X&&eA===X),nh=nu??(np&&!nc?{label:W("sidebar.worktrees"),title:W("sidebar.checkingWorktrees")}:null),nf=(0,i.useMemo)(()=>h(nd,A.sessions),[nd,A.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===tA)),[tA,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:ef,error:ep,onCancel:()=>{ed(!1),eh(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)(eY,{}),(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?W("sidebar.newSessionTitle",{path:X}):W("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"})]}),W("sidebar.new")]}),(0,r.jsx)("button",{type:"button",onClick:()=>{e7(e=>!e),eS(!1)},title:W("sidebar.toggleSessionSearch"),"aria-label":W("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)(eK,{text:eZ(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?"":W("sidebar.selectProject")}),na&&(0,r.jsx)("span",{title:W("sidebar.newActivity"),"aria-label":W("sidebar.newActivity"),style:{width:8,height:8,borderRadius:"50%",flexShrink:0,marginLeft:6,background:"var(--accent)"}})]}),(0,r.jsxs)(eV,{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:W("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),eh(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)(eK,{text:eZ(e.root,ee),style:{flex:1}}),(t=nl.get(e.key),n=W,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",className:"animate-spin",style:{display:"block"},children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})}),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)(eL,{as:"span",variant:"inline",kind:"project",id:e.key,pinned:A.projects.has(e.key),onToggle:O}),(0,r.jsx)(eP,{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:W("sidebar.noMatchingProjects")})]}),!ea&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),t5()},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:W("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:W("sidebar.customPath")})]})]})]}),e9&&(0,r.jsx)("input",{id:"session-search-input",type:"search",autoFocus:!0,value:te,maxLength:200,"aria-label":W("sidebar.searchSessions"),placeholder:W("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??eZ(e.path,ee)).toLowerCase().includes(es.trim().toLowerCase())):ej.worktrees;return(0,r.jsxs)("div",{ref:eG,style:{position:"relative",marginTop:6},children:[(0,r.jsxs)("button",{onClick:()=>eS(e=>!e),title:t1?W("sidebar.switchWorktreeTitle",{path:t1.path}):W("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)(eK,{text:t1?t1.branch??eZ(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:W("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)(eV,{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:W("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 ez===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:W("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void t6(e.path,!0),disabled:eM,style:{padding:"3px 9px",background:"#ef4444",border:"none",borderRadius:5,color:"#fff",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:W("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>eW(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:W("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),eT(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)(eK,{text:e.branch??eZ(e.path,ee),style:{flex:1}}),e.isMain&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:W("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void t6(e.path,!1),disabled:eM,title:W("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:W("sidebar.noMatchingWorktrees")})]}),eC?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:eX,value:eN,onChange:e=>{e$(e.target.value),eT(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),t3()),"Escape"===e.key&&(eE(!1),e$(""),eT(null))},placeholder:W("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 t3(),disabled:eM||!eN.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:5,color:"var(--accent-contrast)",fontSize:11,fontWeight:600,cursor:eM||!eN.trim()?"not-allowed":"pointer",opacity:eM||!eN.trim()?.65:1},children:eM?W("sidebar.creating"):W("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{eE(!1),e$(""),eT(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:W("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),eE(!0),eT(null),setTimeout(()=>eX.current?.focus(),0)},title:W("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:W("sidebar.newWorktree")})]}),eI&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"#dc2626",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:eI})]})]})})(),!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:eQ&&(v||X)?"0 1 var(--sidebar-session-pane-height, 320px)":"1 1 auto",minHeight:80,overflow:"hidden"},children:(0,r.jsx)(ev,{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:W("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:W("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)(e0,{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:A.sessions.has(n.root.id),onTogglePin:O})},n.root.id)})})]})})}),eQ&&(v||X)&&(0,r.jsx)("div",{className:`sidebar-section-resize-handle${tM.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar-sections",title:`${W("layout.resizeSidebarSections")}: ${W("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:eQ?"1 1 0":"0 0 auto",minHeight:120*!!eQ,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:eQ?"rotate(90deg)":"none",transition:"transform 0.15s",flexShrink:0},children:(0,r.jsx)("polyline",{points:"3 2 7 5 3 8"})}),W("files.explorer")]}),(0,r.jsx)(eH,{onClick:()=>{tU()},disabled:tZ,title:tZ?W(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)(eH,{onClick:()=>j(X??v),title:W("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"})]})}),eQ&&tr>0&&(0,r.jsx)(eH,{onClick:()=>ts(e=>!e),title:W("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"})]})}),eQ&&(0,r.jsx)(eH,{onClick:()=>{e6(e=>!e)},title:W("sidebar.searchFiles"),ariaPressed:e3,color:e3?"var(--accent)":"var(--text-dim)",background:e3?"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"})]})}),eQ&&(0,r.jsx)(eH,{onClick:()=>tw.current?.openUploadPicker(),disabled:e8,title:W("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)(eH,{onClick:()=>{N?N():e4(e=>e+1),ta(!0),tk.current&&clearTimeout(tk.current),tk.current=setTimeout(()=>ta(!1),2e3)},title:W("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:W("files.dismissError")})]}),eQ&&(0,r.jsx)("div",{ref:tC,className:"scrollbar-subtle",style:{flex:1,overflowY:"auto",overflowX:"hidden"},children:(0,r.jsx)(ex,{ref:tw,cwd:X??v,onOpenFile:y??(()=>{}),refreshKey:e2,onAtMention:$,onAtMentions:M,onUploadBusyChange:e5,changesCollapsed:to,onChangesCountChange:ti,fileSearchOpen:e3,onFileSearchOpenChange:e6})})]})]})}function eX(){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",className:"animate-spin",style:{display:"block"},children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})})})}function eQ(){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.jsx)("circle",{cx:"7",cy:"7",r:"4.5",stroke:"currentColor",strokeWidth:"1.4",opacity:"0.16",className:"unread-ping"})]})})}function e0(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,$]=(0,i.useState)(!1),[I,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]),W=(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]),A=(0,i.useCallback)(async()=>{if(!t.transient){$(!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?A():$(!0)},[A]),O=(0,i.useCallback)(e=>{e.stopPropagation(),A()},[A]),F=(0,i.useCallback)(e=>{e.stopPropagation(),$(!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:I?.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:W,onKeyDown:e=>{"Enter"===e.key&&W(),"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)(eX,{}):s?(0,r.jsx)(eQ,{}):(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)(eL,{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 e1=n(5772);let e2=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,e4=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,e8=/\x1B_pi:c\x07/g;function e5(e){return e.replace(e8,"").replace(e2,"")}function e3(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(e4);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 e6(e,t){let n=e3(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function e9(e){return e3(e)[0]?.char}let e7={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:""},te={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"};function tt(e){return"user"===e.role||"custom"===e.role&&("compaction"===e.customType||"pi-web:subagent-notification"===e.customType)}function tn(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===e.thinking.trim()}function tr(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return(e.content??[]).filter(e=>!tn(e,t))}function ti(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 to(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return!t.isStreaming&&"length"===e.stopReason}function ts(e){return(e.content??[]).some(e=>"text"===e.type?e.text.trim().length>0:"image"===e.type||"toolCall"===e.type)}function tl(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=tr(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 ta(e){return!e.defaultPrevented&&0===e.button&&!e.shiftKey&&!e.altKey}function td(e){try{return decodeURIComponent(e)}catch{return e}}function tc(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function tu(e){let t=tc(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 tp(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=td(a),p=u.startsWith("\\\\"),h=tc(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=td(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=`${tc(t).replace(/\/+$/,"")}/${h}`,c="relative"),!d)return null;let m=tu(d).replace(/:\d+(?::\d+)?$/,"");return"relative"===c&&l&&(n=tu(m).replace(/\/+$/,""),r=tu(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 th=/^page=(\d+)$/i;function tf(e){if(!e)return null;let t=e.indexOf("#");if(-1===t)return null;let n=e.slice(t+1).trim().match(th);if(!n)return null;let r=Number.parseInt(n[1],10);return Number.isInteger(r)&&r>0?r:null}function tm(e){let t=e.toLowerCase();return"write"===t||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")}function tg(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 tx(e){let t=e.toLowerCase();return"apply_patch"===t||t.startsWith("apply_patch_")||t.endsWith(".apply_patch")||t.endsWith("_apply_patch")}function tv(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 tb(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ty(e){if(!tb(e)||!tb(e.result))return!1;let t=e.result.failures;return Array.isArray(t)&&t.length>0}function tj(){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 tk(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=tj()).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 tw(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=tj();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 tS(e){return e?e.map(e=>e.newPath).filter(e=>"string"==typeof e&&e.length>0):[]}function tC(e,t,n){let r=e.trim().split("\n").map(e=>`> ${e}`).join("\n");return`${t}
|
|
2
|
+
|
|
3
|
+
${r}
|
|
4
|
+
|
|
5
|
+
${n}`}var tE=n(32316),tN=n(88374),t$=n(5924),tI=n(94764),tT=n(63835),tM=n(54152),tR=n(31678),tL=n(6796),tz=n(98164);let tW={...tI.j,attributes:{...tI.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},protocols:{...tI.j.protocols,href:[...tI.j.protocols?.href??[],"file"]},strip:[...tI.j.strip||[],"iframe","object","style","form"]};function tA(e){return/^file:/i.test(e)?e:(0,tE.Lv)(e)}function tP(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 tO=/`((?:[^`\n]|\\`)*?[^\\`\n])`(?!`)/y;function tF(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=tP(t,"`","\\`",tO,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=>tD(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=tB(n,e+1,t,l);if(o){r.push(`${t}$$`,`${t}${i}`);for(let i=e+1;i<o.index;i++)r.push(tD(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=tB(n,e+1,t,l);if(i&&(i.glued||""!==t)){r.push(`${t}$$`);for(let o=e+1;o<i.index;o++)r.push(tD(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:tP(d,"\\(","\\",tH,e=>{let[t,n]=e;return n.trim()?`$${n}$`:t})))}return r.join(t)}function tB(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 tD(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 tH=/\\\(([^`\r\n$]*?[^`\r\n$\\])\\\)/y,t_={singleTilde:!1},tU=/[\u3001\u3002\u3008-\u3011\u3014-\u301B\uFF01\uFF08\uFF09\uFF0C\uFF1A\uFF1B\uFF1F\u2018\u2019\u201C\u201D\u2013\u2014\u2026\u00B7\uFF5E\u301C]/;function tq(){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(tU);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 tZ=function(){tz.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)}}},tK=[[tM.A,["yaml"]],[tR.A,t_],tL.A,tq,tZ],tV=/[ \t]*(?:\r\n|\r|\n)[ \t]*/,tJ=new Set(["paragraph","heading","tableCell"]),tY=/^<(?:iframe|noembed|noframes|noscript|plaintext|script|style|textarea|title|xmp)(?=[\s/>]|$)/i;function tG(){return{type:"lineBreak",data:{hName:"br"}}}let tX=[...tK??[],function(){return e=>(function e(t){!t.children||tJ.has(t.type)&&function e(t){return"html"===t.type?tY.test(t.value??""):t.children?.some(e)??!1}(t)||(t.children=t.children.flatMap(t=>"break"===t.type?[tG()]:"text"===t.type&&t.value?t.value.split(tV).flatMap((e,t)=>[...t>0?[tG()]:[],...e?[{type:"text",value:e}]:[]]):(e(t),[t])))})(e)}],tQ=[[tM.A,["yaml"]],[tR.A,t_],tL.A,tq,tZ],t0=[t$.A,[tT.A,tW],[tN.A,{throwOnError:!1,strict:!1}]],t1=[t$.A,[tT.A,tW],[tN.A,{throwOnError:!1,strict:!1}]];function t2(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 t4=n(65063),t8=n(7644);let t5=[{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 t3(e){return"dark"===e||"pine"===e}let t6="pi-theme",t9={preference:"auto",theme:"light"},t7=new Set,ne=null,nt=!1;function nn(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function nr(e){return"auto"===e?nn():e}function ni(e){"u">typeof document&&(document.documentElement.dataset.theme=e,document.documentElement.classList.toggle("dark",t3(e)))}function no(){if(ne)return ne;let e=function(){try{let e=localStorage.getItem(t6);if(t5.some(t=>t.id===e))return e}catch{}return"auto"}(),t=nr(e);return ni(t),ne={preference:e,theme:t}}function ns(e,t,n){if(ni(t),n)try{localStorage.setItem(t6,e)}catch{}ne={preference:e,theme:t},t7.forEach(e=>e())}function nl(){let e=no();if("auto"!==e.preference)return;let t=nn();t!==e.theme&&ns("auto",t,!1)}function na(e){return t7.add(e),no(),nt||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",nl),window.addEventListener("focus",nl),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&nl()}),nt=!0),nl(),()=>{t7.delete(e)}}function nd(){return no()}function nc(){return t9}function nu(){let e=(0,i.useSyncExternalStore)(na,nd,nc),t=(0,i.useCallback)((e,t)=>{if(no().preference===e)return;let n=nr(e),r=()=>{ns(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:t3(e.theme)}}function np(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 nh(e){let{code:t,isStreaming:o,defaultPreview:s=!1}=e,{isDark:l}=nu(),{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)(ng,{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)(nf,{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 nf(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 nm={...t8.xJ,'pre[class*="language-"]':{...t8.xJ['pre[class*="language-"]']}};delete nm['pre[class*="language-"]'].background;let ng=(0,i.memo)(function(e){let{code:t,lang:n,headerAction:o,isStreaming:s}=e,{isDark:l}=nu(),{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:()=>{np(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",backgroundColor:"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)(t4.A,{language:n||"text",style:l?nm:t8.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,fontWeight:"var(--font-mono-weight)",border:"none",borderRadius:0,backgroundColor:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},codeTagProps:{style:{fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)"}},children:t})]})}),nx=(0,i.createContext)(!1);function nv(e){let{src:t,alt:n,cwd:o,...s}=e,l=(0,i.useContext)(nx);delete s.node;let a="string"==typeof t?t:void 0,d=a?tp(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)(t2,{src:c,alt:n??"",className:"markdown-image",children:u})}function nb(e){let{children:t,className:n,isStreaming:o,cwd:s,onOpenFile:l,keepLineBreaks:a}=e,d=(0,i.useMemo)(()=>tF(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)(nh,{code:l.replace(/\n$/,""),isStreaming:o,defaultPreview:!0}):(0,r.jsx)(ng,{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?tp(t,s):null;return o&&l?(0,r.jsx)(nx.Provider,{value:!0,children:(0,r.jsx)("a",{href:t,...i,onClick:e=>{if(!ta(e))return;let n=e.currentTarget.getAttribute("target");n&&"_self"!==n||(e.preventDefault(),l(o,tf(t)??void 0))},children:n})}):(0,r.jsx)(nx.Provider,{value:!0,children:(0,r.jsx)("a",{href:t,...i,target:"_blank",rel:"noopener noreferrer",children:n})})},img:e=>(0,r.jsx)(nv,{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)(tE.oz,{remarkPlugins:a?tX:tK,rehypePlugins:t0,urlTransform:l?tA:void 0,components:c,children:d})})}function ny(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 nj=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,nk=/(?:\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 nw(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=nS(c.slice(4));continue}if(c.startsWith("+++ ")){u(),r={oldPath:t,newPath:nS(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 nS(e){return e.split(" ")[0].trim()}let nC=new Set,nE="pi-thinking-expanded",nN="pi-thinking-expanded-changed";function n$(){return"true"===window.localStorage.getItem(nE)}function nI(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 nT="codemode",nM=new Set(["running","ok","error","cancelled"]);function nR(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function nL(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function nz(e){if(!nR(e)||!Array.isArray(e.calls))return{calls:[],omitted:0};let t=e.calls.flatMap(e=>{let t=function(e){if(!nR(e)||"string"!=typeof e.name)return null;let t="string"==typeof e.status&&nM.has(e.status)?e.status:"ok",n=nL(e.durationMs),r=nL(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=nL(e.omittedCalls);return{calls:t,omitted:void 0!==n&&n>0?Math.floor(n):0}}let nW=/^Script (completed|failed)\nWall time ([\d.]+) seconds\nOutput:\n$/;function nA(e){return`$${e>=.01?e.toFixed(2):e.toPrecision(2)}`}let nP={running:{icon:"…",color:"#d97706"},ok:{icon:"✓",color:"#16a34a"},error:{icon:"✗",color:"#f87171"},cancelled:{icon:"⊘",color:"var(--text-dim)"}};function nO(e){var t;let{call:n}=e,{t:i}=(0,E.s)(),o=nP[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:nA(n.cost)})]}),n.error&&(0,r.jsx)("div",{style:{color:"#f87171",paddingLeft:18,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n.error})]})}function nF(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)(nO,{call:e},e.id||`${c+t}`))}),null!==p&&(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:l("codemode.modelCost",{cost:nA(p)})})]})}let nB=/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}\uac00-\ud7af]/u;function nD(e){let t=0,n=0;for(let r of e)nB.test(r)?t++:n++;return t+n/4}let nH=new Map;function n_(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)(nb,{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 nU(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 nq=(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)(nZ,{message:t,cwd:s,onOpenFile:l,entryId:d,onFork:u,forking:p,onEditContent:h,onCancelEdit:f,isEditing:m}):"assistant"===t.role?(0,r.jsx)(nK,{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)(n6,{message:t}):(0,r.jsx)(re,{message:t,cwd:s,onOpenFile:l}):"bashExecution"===t.role?(0,r.jsx)(ro,{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 nZ(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=nU(t.timestamp),$=!!s&&!!l,I=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)(t2,{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)(nb,{className:"markdown-user-message",keepLineBreaks:!0,cwd:n,onOpenFile:o,children:y})]}):(0,r.jsxs)(r.Fragment,{children:[M,y&&(0,r.jsx)(n_,{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:()=>{np(I).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")]})}),($||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")]}),$&&(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 nK(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:$}=e,{t:I}=(0,E.s)(),T=b?nU(p.timestamp):null,M=(0,i.useMemo)(()=>(p.content??[]).map((e,t)=>({block:e,originalIndex:t})).filter(e=>{let{block:t}=e;return!tn(t,{isStreaming:h})}),[p.content,h]),R=(0,i.useMemo)(()=>M.map(e=>{let{block:t}=e;return t}),[M]),L=ti(p,{isStreaming:h}),z=to(p,{isStreaming:h}),W=z&&!ts(p),[A,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 nD(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+nD(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:I("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)(nV,{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:[I(W?"chat.truncatedWithoutAnswer":"chat.truncatedByOutputLimit"),W&&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:I(N?"chat.compacting":"chat.compactContext")}),W&&$&&(0,r.jsx)("div",{style:{marginTop:8,color:"#ef4444",whiteSpace:"pre-wrap"},children:$})]}),S&&S.length>0&&(0,r.jsx)(nI,{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:()=>{np(X).then(()=>{F(!0),setTimeout(()=>F(!1),1500)})},title:I("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:+!!A,pointerEvents:A?"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"})]}),I(O?"i18n.copied":"i18n.copy")]}),T&&!h&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginLeft:"auto"},children:T})]})]})}function nV(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)(nJ,{block:t,isStreaming:o,cwd:a,onOpenFile:d})});if("thinking"===t.type)return(0,r.jsx)(nY,{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)(nG,{block:t,result:e,duration:n,onOpenSession:c})}return null}function nJ(e){let{block:t,isStreaming:n,cwd:i,onOpenFile:o}=e;return(0,r.jsx)(n_,{isStreaming:n,cwd:i,onOpenFile:o,children:t.text})}function nY(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)(n$),[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(n$());return window.addEventListener(nN,e),()=>window.removeEventListener(nN,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=nH.get(r);if(i)return nH.delete(r),nH.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 nH.delete(r),e});if(nH.set(r,o),nH.size>100){let e=nH.keys().next().value;e&&nH.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)(ny,{active:c}),!c&&(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b?(0,r.jsx)(tE.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 nG(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)&&nC.has(e)}),m=function(e){if(void 0!==e.rawInput||!tm(e.toolName))return null;let{content:t}=e.input;return"string"!=typeof t||""===t?null:Object.keys(e.input).every(e=>ri.has(e))?t:null}(a)??(o=a).rawInput??JSON.stringify(o.input,null,2),g=void 0!==a.rawInput,x=tg(a.toolName),v=d&&!d.isError?function(e){let t=e.details;if(!n8(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(!tx(e.toolName))return null;let n=tk(tv(e.input,e.rawInput));if(n)return n;let r=t&&!t.isError?t.details:void 0;if(n8(r)){let e=tw(r.preview);if(e)return e}return null}(a,d),y=tx(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}(tv((s=a).input,s.rawInput))).length?null:l.join(", ").slice(0,120):null,j=a.toolName!==nT||g?null:nR(t=a.input)&&"string"==typeof t.code?t.code:null,k=null===j?null:{code:j,...nz(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&&nW.test(t.text)?n:[...e]}(d.content):d.content:[],N=d?C.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,$=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,I=rn(C),T=null!==$&&("(no output)"===$.trim()||""===$.trim()),M=(d?.isError??!1)||tx(a.toolName)&&ty(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?nC.add(e):nC.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)(nF,{calls:k.calls,omitted:k.omitted,isError:M}),I.length>0&&(0,r.jsx)(n5,{images:I,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)(n0,{files:b})}),h&&d&&b&&M&&(0,r.jsx)(n3,{text:$??"",isEmpty:T,isError:M}),h&&d&&!b&&!w&&(v?(0,r.jsx)(nX,{diff:v}):(!T||0===I.length)&&(0,r.jsx)(n3,{text:$??"",isEmpty:T,isError:M}))]})}function nX(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)(()=>nw(t),[t]);return n?(0,r.jsx)(n0,{files:n}):(0,r.jsx)(n4,{text:t})}function n0(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)",fontWeight:"var(--font-mono-weight)",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)(n1,{title:e.oldPath||n("i18n.before"),side:"left"}),(0,r.jsx)(n1,{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)(n2,{cell:e.left,side:"left"}),(0,r.jsx)(n2,{cell:e.right,side:"right"})]},t))})]},t))})}function n1(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 n2(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 n4(e){let{text:t}=e,n=t.split(/\r?\n/);return(0,r.jsx)("div",{style:{maxHeight:520,overflowY:"auto",overflowX:"hidden",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.55,minWidth:0},children:n.map((e,t)=>{let n=e.startsWith("@@")?"hunk":e.startsWith("+")&&!e.startsWith("+++")?"added":e.startsWith("-")&&!e.startsWith("---")?"removed":"context";return(0,r.jsxs)("div",{style:{display:"flex",background:"added"===n?"rgba(34,197,94,0.12)":"removed"===n?"rgba(248,113,113,0.13)":"hunk"===n?"rgba(96,165,250,0.12)":"transparent",borderLeft:"added"===n?"3px solid #22c55e":"removed"===n?"3px solid #f87171":"hunk"===n?"3px solid var(--accent)":"3px solid transparent"},children:[(0,r.jsx)("span",{style:{width:48,padding:"0 8px",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",textAlign:"right",userSelect:"none",flexShrink:0},children:t+1}),(0,r.jsx)("span",{style:{padding:"0 10px",whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:"added"===n?"#22c55e":"removed"===n?"#f87171":"hunk"===n?"var(--accent)":"var(--text)"},children:e||"\xa0"})]},t)})})}function n8(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function n5(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=rr(e);return n?(0,r.jsx)(t2,{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 n3(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 n6(e){let{message:t}=e,{t:n}=(0,E.s)(),o=rt(t.content),s=(0,i.useMemo)(()=>{let e,t,n,r,i;return e=[],t=[],n=o.match(nk),r=n?.[1]??"",i=n?.index===void 0?o:o.slice(0,n.index),r.replace(nj,(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=nU(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)(nb,{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)(n9,{readFiles:s.readFiles,modifiedFiles:s.modifiedFiles})]})]})})}function n9(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)(n7,{title:i("i18n.modifiedFiles"),files:n}),t.length>0&&(0,r.jsx)(n7,{title:i("i18n.readFiles"),files:t})]})}function n7(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 re(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=rt(n.content),g=rn(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=nU(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=rr(e);return n?(0,r.jsx)(t2,{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)(nb,{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:()=>{np(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 rt(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function rn(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)}function rr(e){return e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:""}let ri=new Set(["path","file_path","content"]);function ro(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)(nG,{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 rs(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 rl=new Map;function ra(e){return{value:e.value,images:e.images.map(e=>({...e}))}}function rd(e){return!e.value&&0===e.images.length}function rc(e){let t=rl.get(e);return t?ra(t):null}function ru(e,t){rd(t)?rl.delete(e):rl.set(e,ra(t))}function rp(e){rl.delete(e)}function rh(e,t){return e.trim()?t.trim()?`${e}
|
|
7
|
+
|
|
8
|
+
${t}`:e:t}function rf(e,t,n,r){let i=[...t??[],...r].filter(rs).slice(0,10).map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});return{value:rh(e,n),images:i}}function rm(e,t,n){if(e===t)return n?ra(n):rc(t);let r=rc(e),i=n&&!rd(n)?ra(n):r??(n?ra(n):null),o=rc(t);if(rp(e),!i)return o;let s=o?rf(o.value,o.images,i.value,i.images):i;return ru(t,s),ra(s)}let rg=/^([ \t]*)([-*+])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,rx=/^([ \t]*)(\d{1,9})([.)])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,rv=/^([ \t]*)(\d{1,3})(、)([ \t]*)/,rb=/^[ \t]*([-*_])(?:[ \t]*\1){2,}[ \t]*$/,ry=/^[ \t]{0,3}(`{3,}|~{3,})/;function rj(e){return"mcp"===e.name&&e.sourceInfo?.path==="builtin:mcp"}function rk(e){return"/mcp"===e.trim()}let rw="pi-enter-send-mode",rS="enter",rC=null,rE=new Set;function rN(){return null===rC&&(rC=function(){try{let e=window.localStorage.getItem(rw);return"ctrlEnter"===e?"ctrlEnter":"enter"}catch{return rS}}()),rC}function r$(e){return rE.add(e),()=>{rE.delete(e)}}function rI(e){rC=e;try{window.localStorage.setItem(rw,e)}catch{}rE.forEach(e=>e())}function rT(){return(0,i.useSyncExternalStore)(r$,rN,()=>rS)}let rM="pi-chat-content-width",rR="pi-chat-content-font-size",rL={width:820,fontSize:14},rz=null,rW=new Set;function rA(e){let t=Number(e);return Number.isFinite(t)?Math.max(820,Math.min(2e3,Math.round(t))):820}function rP(e){let t=Number(e??14);return Number.isFinite(t)?Math.max(12,Math.min(24,Math.round(t))):14}function rO(e){try{return window.localStorage.getItem(e)}catch{return null}}function rF(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 rB(){return rz||rF(rz={width:rA(rO(rM)),fontSize:rP(rO(rR))}),rz}function rD(e){return rW.add(e),()=>{rW.delete(e)}}function rH(e,t){let n="width"===e?rA(t):rP(t);rF(rz={...rB(),[e]:n});try{window.localStorage.setItem("width"===e?rM:rR,String(n))}catch{}rW.forEach(e=>e())}let r_=e=>rH("width",e),rU=e=>rH("fontSize",e);function rq(){return{...(0,i.useSyncExternalStore)(rD,rB,()=>rL),setWidth:r_,setFontSize:rU}}let rZ=[{value:100,label:"settings.fontWeightThin"},{value:200,label:"settings.fontWeightExtraLight"},{value:300,label:"settings.fontWeightLight"},{value:400,label:"settings.fontWeightRegular"},{value:500,label:"settings.fontWeightMedium"},{value:600,label:"settings.fontWeightSemiBold"}],rK={ui:"pi-ui-font-family",mono:"pi-mono-font-family",uiWeight:"pi-ui-font-weight",monoWeight:"pi-mono-font-weight"},rV={ui:"",mono:"",uiWeight:400,monoWeight:400};function rJ(e){let t="string"==typeof e?Number(e):e;return rZ.find(e=>e.value===t)?.value??400}function rY(e){return"string"==typeof e&&e.length<=500?e:""}let rG=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded"]),rX=["ui","mono"],rQ=Object.keys(rK),r0=null,r1=new Set;function r2(){let e={...rV};for(let t of rX)try{e[t]=rY(window.localStorage.getItem(rK[t]));let n=`${t}Weight`;e[n]=rJ(window.localStorage.getItem(rK[n]))}catch{}return e}function r4(e){for(let t of rX){let n=`--font-${t}`,r=function(e,t){let n=rY(t).split(",").flatMap(e=>{let t=e.trim().replace(/\s+/g," "),n=t.length>=2&&('"'===t[0]||"'"===t[0])&&t.endsWith(t[0]);return(n&&(t=t.slice(1,-1).trim()),t)?[!n&&rG.has(t.toLowerCase())?t.toLowerCase():JSON.stringify(t)]:[]}).join(", ");return n?`${n}, var(--font-${e}-default)`:""}(t,e[t]);r?document.documentElement.style.setProperty(n,r):document.documentElement.style.removeProperty(n);let i=e[`${t}Weight`];400===i?document.documentElement.style.removeProperty(`${n}-weight`):document.documentElement.style.setProperty(`${n}-weight`,String(i))}}function r8(){return r0||r4(r0=r2()),r0}function r5(){r1.forEach(e=>e())}function r3(e){if(null!==e.key&&!Object.values(rK).includes(e.key))return;let t=r2(),n=r8();rQ.every(e=>t[e]===n[e])||(r0=t,r4(t),r5())}function r6(e){return 0===r1.size&&window.addEventListener("storage",r3),r1.add(e),r8(),()=>{r1.delete(e),0===r1.size&&window.removeEventListener("storage",r3)}}function r9(e){let t=r8(),n=rQ.filter(n=>t[n]!==e[n]);if(n.length){for(let t of(r0=e,r4(e),n))try{e[t]===rV[t]?window.localStorage.removeItem(rK[t]):window.localStorage.setItem(rK[t],String(e[t]))}catch{}r5()}}function r7(e,t){r9({...r8(),[e]:rY(t)})}function ie(e,t){r9({...r8(),[`${e}Weight`]:rJ(t)})}function it(e){r9({...r8(),[e]:"",[`${e}Weight`]:400})}function ir(){return{...(0,i.useSyncExternalStore)(r6,r8,()=>rV),setFontPreference:r7,setFontWeight:ie,resetFontPreference:it}}function ii(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 io(e){let{active:t,onSelect:n,star:o,gutter:s=!!o,children:l}=e,a=e$(),[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)(ii,{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)(ii,{filled:!1,size:12})})]})}let is=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function il(e,t){return is.compare(e.name||e.modelId,t.name||t.modelId)||is.compare(e.provider,t.provider)||is.compare(e.modelId,t.modelId)}function ia(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)(),$=e$(),I=(0,i.useRef)(null),T=(0,i.useRef)(null),[M,R]=(0,i.useState)(!1),[L,z]=(0,i.useState)(null),[W,A]=(0,i.useState)(""),P=v||b,O=(0,i.useMemo)(()=>[...p].sort(il),[p]),F=(t=W.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=>{I.current&&!I.current.contains(e.target)&&T.current&&!T.current.contains(e.target)&&(R(!1),A(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{P&&(R(!1),A(""))},[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:$?"flex-start":void 0,gap:6,width:$?"100%":void 0,maxWidth:$?"100%":220,height:32,padding:$?"8px 10px":"8px 12px",overflow:"hidden",border:"none",borderRadius:9,background: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:I,className:`model-selector is-${k}${P?" is-disabled":""}`,style:{position:"relative",width:"field"===k||$?"100%":void 0,minWidth:0,flex:"toolbar"===k&&$?"1 1 auto":void 0},onKeyDown:e=>{"Escape"===e.key&&M&&(e.preventDefault(),e.stopPropagation(),A(""),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&&A(""),!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=$?{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:W,onChange:e=>A(e.target.value),placeholder:N("chat.filterModels"),"aria-label":N("chat.filterModels"),autoFocus:!$,autoComplete:"off",spellCheck:!1,style:{boxSizing:"border-box",width:"100%",minWidth:220*!$,padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})}),(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[m&&!W.trim()&&(0,r.jsx)(io,{active:!h,gutter:!!C,onSelect:()=>{R(!1),A(""),m()},children:(0,r.jsx)(id,{label:g??"Default"})}),0===D.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:W.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)(io,{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),A(""),(!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),A(""),C?.(e.provider,e.modelId)}}:void 0,children:(0,r.jsx)(id,{label:e.name})},`${e.provider}:${e.modelId}`))]},e.provider))]})]}))]})}function id(e){let{label:t}=e;return(0,r.jsx)("span",{title:t,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})}let ic=["configured","chat-only","read-only","default","full"],iu={configured:"configured","chat-only":"none","read-only":"read-only",default:"default",full:"full"},ip=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function ih(e,t,n){return t<=0?0:((e+n)%t+t)%t}function im(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 ig=["auto","off","minimal","low","medium","high","xhigh","max"],ix={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 iv(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let ib=[{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 iy(e){return function(e){let t=e.trim().match(/^\/([^\s]+)(?:\s|$)/);if(t)return ib.find(e=>e.name===t[1])}(e)?.availableWhileStreaming===!0}let ij=["builtin","extension","prompt","skill"],ik={builtin:"chat.builtIn",extension:"chat.extensions",prompt:"chat.prompts",skill:"chat.skills"},iw={builtin:0,extension:1,prompt:2,skill:3};function iS(e,t,n){let r=e.name.toLowerCase(),i=iC(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function iC(e,t){return"builtin"===e.source?t(e.description):e.description??""}function iE(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}async function iN(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 i$(e){return{data:e.data,mimeType:e.mimeType}}function iI(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function iT(e){return(e??[]).filter(rs).slice(0,10).map(iI)}function iM(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function iR(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 iL(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 iz(e){let{error:t}=e,{t:n}=(0,E.s)();return t?(0,r.jsx)(iL,{tone:"error",title:n("chat.modelError"),body:t}):null}function iW(e){let{warnings:t}=e,{t:n}=(0,E.s)();return t&&0!==t.length?(0,r.jsx)(iL,{tone:"warning",title:n(t.length>1?"chat.modelScopeWarnings":"chat.modelScopeWarning"),body:t.join("\n")}):null}let iA=(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:$,isCompacting:I,compactError:T,compactResult:M,toolPreset:R,onToolPresetChange:L,thinkingLevel:z,isAutoThinkingSelection:W=!1,onThinkingLevelChange:A,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:ei,cwd:eo,compact:es=!1}=e,{t:el}=(0,E.s)(),{fontSize:ea}=rq(),{ui:ed,uiWeight:ec}=ir(),eu=e$(),ep=rT(),[eh,ef]=(0,i.useState)(()=>ei?rc(ei)?.value??"":""),[em,eg]=(0,i.useState)(!1),[ex,ev]=(0,i.useState)(!1),[eb,ey]=(0,i.useState)(!1),[ej,ek]=(0,i.useState)(()=>ei?iT(rc(ei)?.images):[]),ew=eh.trimStart(),eS=0===ej.length&&ew.startsWith("!"),eC=eS&&ew.startsWith("!!"),[eE,eN]=(0,i.useState)(!1),[eI,eT]=(0,i.useState)(0),[eM,eR]=(0,i.useState)(null),[eL,ez]=(0,i.useState)(null),[eW,eA]=(0,i.useState)(!1),[eP,eO]=(0,i.useState)(null),[eF,eB]=(0,i.useState)(0),[eD,eH]=(0,i.useState)(!1),[e_,eU]=(0,i.useState)(!1),[eq,eZ]=(0,i.useState)(0),[eK,eV]=(0,i.useState)(!1),eJ=(0,i.useRef)(!1),[eY,eG]=(0,i.useState)(null),[eX,eQ]=(0,i.useState)(!1),[e0,e1]=(0,i.useState)(null),[e2,e4]=(0,i.useState)(null),e8=eo&&e2?.cwd===eo?e2.values:{},e5=(0,i.useRef)(null),e3=(0,i.useRef)(null),e6=(0,i.useRef)(null),e9=(0,i.useRef)(null),e7=(0,i.useRef)(null),te=(0,i.useRef)(null),tt=(0,i.useRef)(!1),tn=(0,i.useRef)(0),tr=(0,i.useRef)(!1),ti=(0,i.useRef)(null),to=(0,i.useRef)([]),ts=(0,i.useRef)(null),tl=(0,i.useRef)([]),ta=(0,i.useRef)([]),td=(0,i.useRef)(null),tc=(0,i.useRef)(null),tu=(0,i.useRef)(ei),tp=(0,i.useRef)(eh),th=(0,i.useRef)(ej),tf=(0,i.useRef)(0);tp.current=eh,th.current=ej,(0,i.useImperativeHandle)(t,()=>({insertIfEmpty(e){let t=e5.current;(t?t.value:eh).trim()||(tp.current=e,ef(e),ez(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=e5.current;if(t=i?i.value:eh,n=th.current.length,r=tf.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=iT("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 rs(r)?[r]:[]}));tp.current=o,th.current=s,ef(o),ez(null),eU(!1),ek(e=>(e.forEach(iM),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=e5.current,n=[e,t?t.value:eh].filter(e=>e.trim()).join("\n\n");tp.current=n,ef(n),ez(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(tu.current!==e)return void rm(e,t);let n={value:tp.current,images:th.current.map(i$)},r=rm(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(tu.current=t,i)return;let o=iT(r.images);tp.current=r.value,th.current=o,ef(r.value),ek(e=>(e.forEach(iM),o)),ez(null),eU(!1)},restoreSubmission(e,t,n){if(!e.trim()&&!t?.length)return;let r=tu.current,i=n??r,o=i===r,s=!o&&i?rc(i):null,l=rf(e,t,o?tp.current:s?.value??"",o?th.current.map(i$):s?.images??[]);if(i&&ru(i,l),!o)return;let a=t?.length?[...iT(t).slice(0,Math.max(0,10-th.current.length)),...th.current].slice(0,10):th.current;tp.current=l.value,th.current=a,ef(t=>{let n=rh(e,t);return tp.current=n,n}),ez(null),eU(!1),t?.length&&ek(e=>{let n=Math.max(0,10-e.length),r=iT(t).slice(0,n),i=r.length>0?[...r,...e]:e;return th.current=i,i}),requestAnimationFrame(()=>{let e=e5.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=e5.current;if(!t)return void ef(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;tp.current=l,ef(l),ez(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){tm(e)}}));let tm=(0,i.useCallback)(async e=>{if(es)return;let t=Math.max(0,10-th.current.length-tf.current),n=e.filter(e=>e.type.startsWith("image/")&&e.size<=0xa00000).slice(0,t);if(n.length){tf.current+=n.length;try{let e=await Promise.all(n.map(async e=>({...await iN(e),previewUrl:URL.createObjectURL(e)})));ek(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(iM);let r=[...t,...n];return th.current=r,r})}finally{tf.current-=n.length}}},[es]),tg=(0,i.useCallback)(e=>{ek(t=>{let n=[...t],[r]=n.splice(e,1);return r&&iM(r),th.current=n,n})},[]),tx=(0,i.useCallback)(()=>{th.current=[],ek(e=>(e.forEach(iM),[]))},[]),tv=(0,i.useCallback)(()=>{tp.current="",ef(""),ez(null),eU(!1),ei&&rp(ei),tu.current&&tu.current!==ei&&rp(tu.current),tx(),e5.current&&(e5.current.style.height="auto")},[tx,ei]);(0,i.useEffect)(()=>{ei&&tu.current===ei&&ru(ei,{value:eh,images:ej.map(i$)})},[ej,ei,eh]),(0,i.useEffect)(()=>{let e=tu.current;if(e===ei)return;e&&ru(e,{value:tp.current,images:th.current.map(i$)});let t=ei?rc(ei):null;tu.current=ei;let n=t?.value??"",r=iT(t?.images);tp.current=n,th.current=r,ef(n),ez(null),eU(!1),ek(e=>(e.forEach(iM),r))},[ei]);let tb=(0,i.useCallback)(()=>{let e=e5.current;e&&(e.style.height="auto",e.value&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[]);(0,i.useLayoutEffect)(tb,[eh,ea,ed,ec,tb]),(0,i.useEffect)(()=>{let e=e5.current;if(!e)return;let t=-1,n=new ResizeObserver(e=>{let[n]=e;n.contentRect.width!==t&&(t=n.contentRect.width,tb())});return n.observe(e),()=>n.disconnect()},[tb]),(0,i.useEffect)(()=>{let e=e5.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(rb.test(e))return null;let t=rg.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=rx.exec(e)??rv.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=ry.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)(()=>()=>{th.current.forEach(iM)},[]);let ty=(0,i.useCallback)(async e=>{if(ej.length||!e.startsWith("/")||!Y)return!1;if(eJ.current)return!0;eJ.current=!0,eV(!0);try{var t,n;let r=await Y(e);if(!r.handled)return!1;return r.error||(t=tp.current,n=th.current.length,0!==n||t.trim()!==e)||tv(),!0}finally{eJ.current=!1,eV(!1)}},[ej.length,tv,Y]),tj=(0,i.useCallback)(async()=>{var e;let t=eh.trim();(t||ej.length)&&(Q?.(),(!m||iy(e=t)||rk(e))&&await ty(t)||m||(tv(),u(t,ej.length?ej:void 0)))},[eh,ej,m,ty,u,tv,Q]),tk=!es&&eh.startsWith("/")&&!/\s/.test(eh.slice(1))?eh.slice(1).toLowerCase():null,tw=null===tk?[]:[...m?ib.filter(e=>e.availableWhileStreaming):ib,...Z??[]].filter(e=>{let t=e.name.toLowerCase(),n=iC(e,el).toLowerCase();return t.includes(tk)||n.includes(tk)}).sort((e,t)=>{let n=iS(e,tk,el)-iS(t,tk,el);return 0!==n?n:iw[e.source]-iw[t.source]||ip.compare(e.name,t.name)}),{commands:tS,groups:tC}=(n=0,{commands:(o=ij.map(e=>{let t=tw.filter(t=>t.source===e),r="skill"===e?[...t.filter(e=>!iE(e,e8)),...t.filter(e=>iE(e,e8))]: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}),tE=1===tw.length?el(tk?"chat.match":"chat.command"):el(tk?"chat.matches":"chat.commands",{count:tw.length}),tN=!!eh.trim()||ej.length>0,t$=ej.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)&&!eD;(0,i.useEffect)(()=>{0===ej.length&&eH(!1)},[ej.length]);let tI=(0,i.useCallback)((e,t)=>{if(!eo)return void ez(null);let n=t??e.length;ez(et(e.slice(0,n)))},[eo]),tT=eL?.query??null,tM=i.useMemo(()=>null!==tT&&eY&&eY.cwd===eo?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:er(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:er(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||en(e.entry.path)-en(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(eY.entries,tT):[],[tT,eY,eo]),tR=!!(tT&&eY?.truncated&&eY.cwd===eo);(0,i.useEffect)(()=>{if(!tR||!eo||!tT)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(eo)}&q=${encodeURIComponent(tT)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>e1({cwd:eo,query:tT,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tR,tT,eo]);let tL=tR&&null!==e0&&e0.cwd===eo&&e0.query===tT,tz=tL?e0.matches:tM,tW=null===eL?null:`${eL.start}:${+!!eL.quoted}:${eL.query}`;(0,i.useEffect)(()=>{if(null===tW){eA(!1),eB(0);return}eA(!0),eB(0)},[tW]);let tA=null!==eL;(0,i.useEffect)(()=>{if(!tA||!eo)return;let e=td.current;e&&e.cwd===eo&&Date.now()-e.fetchedAt<1e4||tc.current===eo||(tc.current=eo,eQ(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(eo)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{eG({cwd:eo,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)=>en(e.path)-en(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),td.current={cwd:eo,fetchedAt:Date.now()}}).catch(()=>{td.current=null}).finally(()=>{tc.current=null,eQ(!1)}))},[tA,eo]);let tP=(0,i.useCallback)(e=>{if(!eL)return;let t=e5.current,n=t?.selectionStart??eh.length,r=eh.slice(0,eL.start),i=eh.slice(n);eL.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,eL.quoted),s=r+o.text+i,l=r.length+o.cursorOffset;ef(s),ez(et(s.slice(0,l))),requestAnimationFrame(()=>{let e=e5.current;e&&(e.focus(),e.setSelectionRange(l,l),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[eL,eh]);(0,i.useEffect)(()=>{eF>=tz.length&&eB(Math.max(0,tz.length-1))},[tz.length,eF]),(0,i.useEffect)(()=>{tl.current.length=tz.length},[tz.length]),(0,i.useEffect)(()=>{eW&&tl.current[eF]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eF,eW]),(0,i.useEffect)(()=>{eq>=_.length&&eZ(Math.max(0,_.length-1))},[_.length,eq]),(0,i.useEffect)(()=>{ta.current.length=_.length},[_.length]),(0,i.useEffect)(()=>{e_&&ta.current[eq]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eq,e_]);let tO=(0,i.useCallback)(e=>{ef(e),eU(!1),eZ(0),ez(null),requestAnimationFrame(()=>{let t=e5.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),tF=(0,i.useCallback)(e=>{let t=`/${e.name} `;ef(t),eN(!1),eT(0),requestAnimationFrame(()=>{let e=e5.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),tB=(0,i.useCallback)(e=>{let t=eh.trim();if(!t&&!ej.length)return;Q?.();let n=ej.length?ej:void 0,r=()=>{if(t.startsWith("/")&&ee){tv(),ee(t,"steer"===e?"steer":"followUp",n);return}tv(),"steer"===e&&h?h(t,n):"followup"===e&&f&&f(t,n)};!ej.length&&Y&&iy(t)?ty(t):!ej.length&&Y&&rk(t)?ty(t).then(e=>{e||r()},()=>r()):r()},[eh,ej,Y,ee,h,f,tv,Q,ty]),tD=(0,i.useCallback)(e=>{let t=tS.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eI-1);if("right"===e)return Math.min(t,eI+1);let n=to.current[eI];if(!n)return"down"===e?Math.min(t,eI+1):Math.max(0,eI-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,o=r.top+r.height/2,s=-1,l=1/0;for(let n=0;n<=t;n+=1){if(n===eI)continue;let t=to.current[n];if(!t)continue;let r=t.getBoundingClientRect(),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,eI+1):Math.max(0,eI-1)},[tS.length,eI]),tH=(0,i.useCallback)(e=>{let t=e.nativeEvent,n="Enter"===e.key&&!e.shiftKey,r=eu||"ctrlEnter"===ep?n&&(e.ctrlKey||e.metaKey):n,i=eu?r:n,o=Date.now()-tn.current<100,s=tt.current||t.isComposing||229===t.keyCode;if(i&&(s||o)){o&&e.preventDefault();return}if(e_&&!s){if("ArrowDown"===e.key){e.preventDefault(),eZ(e=>Math.min(Math.max(0,_.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eZ(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),eU(!1);return}if(("Tab"===e.key||i)&&_[eq]){e.preventDefault(),tO(_[eq]);return}}if(eE&&null!==tk){if("ArrowDown"===e.key){e.preventDefault(),eT(tD("down"));return}if("ArrowUp"===e.key){e.preventDefault(),eT(tD("up"));return}if("ArrowRight"===e.key){e.preventDefault(),eT(tD("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),eT(tD("left"));return}if("Escape"===e.key){e.preventDefault(),eN(!1);return}let t=tS[eI];if("Tab"===e.key&&t){e.preventDefault(),tF(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 rj(t)&&rk(e)}(eh,t,m)?(eN(!1),tj()):tF(t);return}}if(eW&&null!==eL&&!s){if("ArrowDown"===e.key){e.preventDefault(),eB(e=>ih(e,tz.length,1));return}if("ArrowUp"===e.key){e.preventDefault(),eB(e=>ih(e,tz.length,-1));return}if("Escape"===e.key){e.preventDefault(),eA(!1);return}if(("Tab"===e.key||i)&&tz[eF]){e.preventDefault(),tP(tz[eF]);return}}if("ArrowUp"===e.key&&!s&&!m&&_.length>0&&0===eh.trim().length){e.preventDefault(),eN(!1),eA(!1),eZ(_.length-1),eU(!0);return}if("Escape"===e.key&&!s&&m&&p){e.preventDefault(),p();return}r&&(e.preventDefault(),m&&(h||f)?tB(e.altKey&&f||!h?"followup":"steer"):tj())},[eu,ep,m,h,f,p,eE,tk,tS,eI,tF,tB,tj,tD,eW,eL,tz,eF,tP,e_,_,eq,tO,eh]),t_=(0,i.useCallback)(()=>{let e=e5.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),tU=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!es&&t.length){e.preventDefault(),tm(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(),tp.current=a,ef(a),eU(!1),tI(a,l+o.length),requestAnimationFrame(()=>{s.focus(),s.setSelectionRange(l+o.length,l+o.length)})},[es,tm,tI]);(0,i.useEffect)(()=>{if(null===tk){eN(!1),eT(0),tr.current=!1;return}eN(!0),eT(0),!tr.current&&J&&(tr.current=!0,Promise.resolve(J()).catch(()=>{tr.current=!1}))},[tk,J]),(0,i.useEffect)(()=>{if(!eE||!eo)return;let e=!1;return e4({cwd:eo,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(eo)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;e4({cwd:eo,values:n})}).catch(()=>{e||e4({cwd:eo,values:{}})}),()=>{e=!0}},[eE,eo]),(0,i.useEffect)(()=>{eI>=tS.length&&eT(Math.max(0,tS.length-1))},[tS.length,eI]),(0,i.useEffect)(()=>{to.current.length=tS.length},[tS.length]),(0,i.useEffect)(()=>{eE&&to.current[eI]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eI,eE]),(0,i.useLayoutEffect)(()=>{if(!eE||null===tk)return void eR(null);let e=ti.current;if(e)return im(e,e=>{eR(t=>t===e?t:e)})},[eE,tk]),(0,i.useLayoutEffect)(()=>{if(!eW||null===eL)return void eO(null);let e=ts.current;if(e)return im(e,e=>{eO(t=>t===e?t:e)})},[eW,eL]);let tq=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}}),tZ=M?Math.max(0,M.tokensBefore-M.estimatedTokensAfter):0,tK=M?`${M.reason&&"manual"!==M.reason?`${M.reason[0].toUpperCase()}${M.reason.slice(1)} `:el("chat.compacted")} ${iv(M.tokensBefore)} -> ${iv(M.estimatedTokensAfter)} tokens (${el("chat.tokensSaved",{saved:iv(tZ)})})`:null,tV=z&&"auto"!==z?z:null,tJ="auto"!==(s=tV??"auto")&&O?O[s]??s:s,tY=Object.entries(iu).find(e=>{let[,t]=e;return t===(R??"configured")})?.[0]??"configured",tG="chat-only"===tY?el("chat.chatOnly"):tY;return(0,i.useEffect)(()=>{let e=e=>{e3.current&&!e3.current.contains(e.target)&&eg(!1),e6.current&&!e6.current.contains(e.target)&&ev(!1),e9.current&&!e9.current.contains(e.target)&&ey(!1),!e7.current||e7.current.contains(e.target)||e5.current?.contains(e.target)||eU(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{m&&eg(!1)},[m]),(0,i.useEffect)(()=>{eu||ey(!1)},[eu]),(0,r.jsxs)("fieldset",{disabled:eK,"aria-busy":eK,className:es?void 0:"chat-input-shell",style:{flexShrink:0,minWidth:0,margin:0,border:0,background:"transparent",padding:es?0:"0 16px 8px",paddingRight:es?0:eu?16:52,opacity:eK?.5:1,transition:"opacity 0.15s"},children:[!es&&(0,r.jsx)("input",{ref:te,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:e=>{tm(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)(iz,{error:y}),(0,r.jsx)(iW,{warnings:j}),t$&&(l=b?.find(e=>e.provider===g?.provider&&e.id===g?.modelId),(0,r.jsx)(iL,{tone:"warning",title:el("chat.imageNotSupportedTitle"),body:el("chat.imageNotSupportedBody",{model:l?.name||g?.modelId||""}),onClose:()=>eH(!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:el("chat.queued",{count:(H?.steering.length??0)+(H?.followUp.length??0)})}),U&&(0,r.jsxs)("button",{onClick:U,title:el("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"})]}),el("chat.recall")]})]}),H?.steering.map((e,t)=>(0,r.jsx)(iR,{kind:"steer",text:e},`steer-${t}`)),H?.followUp.map((e,t)=>(0,r.jsx)(iR,{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"})]}),el("chat.retrying",{attempt:D.attempt,max:D.maxAttempts}),D.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",D.errorMessage]})]}),tK&&(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"})}),tK]}),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}),ej.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:ej.map((e,t)=>(0,r.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,r.jsx)(t2,{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:()=>tg(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},t))}),(0,r.jsxs)("div",{style:{position:"relative",minWidth:0},children:[e_&&_.length>0&&(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",maxHeight:"min(44vh, 360px)"},children:[(0,r.jsx)("div",{title:el("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===eq;return(0,r.jsxs)("button",{ref:e=>{ta.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tO(e)},onMouseEnter:()=>eZ(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}`)})})]}),eE&&null!==tk&&(0,r.jsxs)("div",{ref:ti,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eM?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${eM}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?el("chat.loadingCommands"):el("chat.slashCommands",{label:tE})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:el("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:10},children:K||0!==tw.length?tC.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:el(ik[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(e=>{let{command:t,index:n}=e,i=n===eI,o=iE(t,e8);return(0,r.jsxs)("button",{ref:e=>{to.current[n]=e},type:"button",onMouseDown:e=>{e.preventDefault(),tF(t)},onMouseEnter:()=>eT(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:el("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:iC(t,el)})]},`${t.source}:${t.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:el("chat.noCommands")})})]}),eW&&null!==eL&&(a=eX&&(!eY||eY.cwd!==eo),d=1===tz.length?el("chat.match"):el("chat.matches",{count:tz.length}),c=eY?.truncated&&!tL?eL.query?el("chat.searchingAll"):el("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:ts,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eP?"min(48vh, 400px)":`min(48vh, 400px, ${eP}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:a?el("chat.loadingFiles"):el("chat.files",{label:d,hint:c})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:el("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:a||0!==tz.length?tz.map((e,t)=>{let n=t===eF,i=e.path.split("/").pop()??e.path,o=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tl.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tP(e)},onMouseEnter:()=>eB(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:tR&&!tL?el("chat.searching"):el("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{style:{minWidth:0,display:"flex",flexDirection:es?"column":"row",gap:8,alignItems:es?"stretch":"center",background:"var(--bg)",border:es?"none":`1px solid ${eS?"var(--tool-bg)":m&&(h||f)?"rgba(234,179,8,0.4)":"color-mix(in srgb, var(--border) 70%, transparent)"}`,borderRadius:14*!es,padding:es?0:eu?"6px 6px 6px 12px":"10px 10px 10px 14px",boxShadow:es?"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:e5,className:"chat-input-textarea","aria-label":es?el("chat.quoteQuestion"):void 0,value:eh,onChange:e=>{tp.current=e.target.value,ef(e.target.value),eU(!1),tI(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;tI(t.value,t.selectionStart)},onKeyDown:tH,onCompositionStart:()=>{tt.current=!0},onCompositionEnd:e=>{tt.current=!1,tn.current=Date.now();let t=e.currentTarget;tI(t.value,t.selectionStart)},onInput:t_,onPaste:tU,placeholder:m&&(h||f)?el("chat.steerPlaceholder"):m?el("chat.agentPlaceholder"):el("chat.messagePlaceholder"),rows:1,style:{flex:es?"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:es?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:()=>tB("steer"),disabled:!tN,title:el("chat.steerHint"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tN?"rgba(234,179,8,0.12)":"none",border:"1px solid rgba(234,179,8,0.35)",borderRadius:8,color:tN?"rgba(180,130,0,1)":"var(--text-dim)",cursor:tN?"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"})]}),el("chat.steer")]}),f&&(0,r.jsxs)("button",{onClick:()=>tB("followup"),disabled:!tN,title:`${el("chat.followUpHint")} (${eu?"Ctrl/Cmd+":""}Alt/Option+Enter)`,"aria-keyshortcuts":eu?"Control+Alt+Enter Meta+Alt+Enter":"Alt+Enter",style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tN?"rgba(129,140,248,0.12)":"none",border:"1px solid rgba(129,140,248,0.35)",borderRadius:8,color:tN?"rgba(99,102,241,1)":"var(--text-dim)",cursor:tN?"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"})]}),el("chat.followUp")]})]}):(0,r.jsxs)("button",{onClick:tj,disabled:!eh.trim()&&!ej.length,title:el("chat.send"),"aria-label":el("chat.send"),style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,...eu?{width:36,height:36,padding:0}:{padding:"7px 14px"},background:eh.trim()||ej.length?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:eh.trim()||ej.length?"var(--accent-contrast)":"var(--text-dim)",cursor:eh.trim()||ej.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:eh.trim()||ej.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"})]}),!eu&&el("chat.send")]})]})]}),eS&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eC?"var(--text-muted)":"var(--accent)",marginTop:4},children:[el("chat.shell")," \xb7 ",eC?el("chat.outputLocal"):el("chat.outputModel")]}),!es&&(0,r.jsxs)("div",{className:"chat-input-controls",style:{marginTop:eu?4:8,display:eu?"grid":"flex",gridTemplateColumns:eu?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:eu?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2},children:[(0,r.jsx)("button",{onClick:()=>te.current?.click(),title:el("chat.attachImage"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:ej.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=ej.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=ej.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"})]})}),(tq.length>0||g||y)&&k&&(0,r.jsx)(ia,{options:tq,value:g,onChange:k,disabled:m,busy:w,isAutoSelection:x,defaultValue:S,onSetDefault:C})]}),!eu&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsxs)("div",{ref:e9,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:eu?0:"auto"},children:[eu&&(0,r.jsx)("button",{type:"button",title:eb?void 0:el("chat.moreControls"),"aria-label":el("chat.moreControls"),"aria-expanded":eb,"aria-hidden":eb||void 0,tabIndex:eb?-1:void 0,onClick:()=>{ey(!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:eb?"default":"pointer",fontSize:12,fontWeight:500,visibility:eb?"hidden":"visible",pointerEvents:eb?"none":"auto",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{eb||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{eb||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:el("chat.moreControls")}),(0,r.jsxs)("div",{style:{display:eu?eb?"flex":"none":"flex",alignItems:"center",gap:eu?1:2,...eu?{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:[A&&(0,r.jsxs)("div",{ref:e6,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>ev(e=>!e),title:m?el("chat.currentReasoning",{level:tJ}):el("chat.changeReasoning",{level:tJ}),"aria-label":el("chat.changeReasoningLabel"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eu?"0 6px":"8px 12px",width:eu?"auto":void 0,height:32,background:ex?"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=ex?"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"})]}),(!eu||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:tJ})]}),ex&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",...eu?{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:ig.filter(e=>!P||"auto"===e||P.includes(e)).map(e=>{let t="auto"===e?W:!W&&tV===e,n=el(ix[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)(io,{active:t,onSelect:()=>{if(ev(!1),"auto"===e){W||A("auto");return}(!t||W)&&A(e)},gutter:!!B,star:B&&"auto"!==e?{isDefault:F===e,saveLabel:el("chat.saveDefaultThinking"),defaultLabel:el("chat.defaultThinking"),onSave:()=>{ev(!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:e3,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>!m&&eg(e=>!e),disabled:m,title:el("chat.changeToolPreset")+`: ${tG}`,"aria-label":el("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eu?"0 6px":"8px 12px",width:eu?"auto":void 0,height:32,background:em?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:m?"not-allowed":"pointer",fontSize:12,opacity:m?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{m||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=em?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(!eu||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:tG})]}),em&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:eu?void 0:0,left:eu?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:ic.map(e=>{let t,n=iu[e],i=(R??"configured")===n;return t="configured"===e?el("chat.configuredTools"):"chat-only"===e?el("chat.chatOnly"):"read-only"===e?el("chat.readOnlyTools",{count:4}):"default"===e?el("chat.builtInTools",{count:4}):el("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{eg(!1),i||L(n)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:t})]},e)})})]}),(!m||I)&&N&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{onClick:I?$:N,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eu?"0 6px":"8px 12px",width:eu?"auto":void 0,height:32,background:I?"rgba(239,68,68,0.08)":"none",border:"none",borderRadius:9,color:I?"#ef4444":"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=I?"rgba(239,68,68,0.16)":"var(--bg-hover)",e.currentTarget.style.color=I?"#ef4444":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=I?"rgba(239,68,68,0.08)":"none",e.currentTarget.style.color=I?"#ef4444":"var(--text-muted)"},title:I?el("chat.stopCompaction"):el("chat.compactContext"),"aria-label":I?el("chat.stopCompaction"):el("chat.compactContext"),children:I?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(!eu||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:el("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"})]}),(!eu||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:el("chat.compact")})]})})}),m&&(0,r.jsxs)("button",{onClick:p,title:el("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"})}),el("chat.stop")]}),void 0!==X&&(0,r.jsx)("button",{onClick:X,title:G?el("chat.disableSound"):el("chat.enableSound"),"aria-label":G?el("chat.disableSound"):el("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"})]})}),eu&&eb&&(0,r.jsx)("button",{type:"button",title:el("chat.collapseControls"),"aria-label":el("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eg(!1),ev(!1),ey(!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 iP=n(88576),iO=n.n(iP);function iF(e){let{level:t,children:n,headingIndex:i,onClick:o}=e;return(0,r.jsx)("button",{type:"button",className:iO().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 iB=[...tQ??[],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]:[]}}],iD=[[tN.A,{throwOnError:!1,strict:!1}]];function iH(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 i_=(0,i.memo)(function(e){let{markdown:t,onHeadingClick:n,onAnswerClick:o}=e,s=(0,i.useMemo)(()=>tF(t),[t]);return t?(0,r.jsx)("div",{className:iO().outline,children:(0,r.jsx)(tE.oz,{remarkPlugins:iB,rehypePlugins:iD,components:{h1:e=>{let{children:t,node:i}=e;return(0,r.jsx)(iF,{level:1,headingIndex:iH(i),onClick:n,children:t})},h2:e=>{let{children:t,node:i}=e;return(0,r.jsx)(iF,{level:2,headingIndex:iH(i),onClick:n,children:t})},h3:e=>{let{children:t,node:i}=e;return(0,r.jsx)(iF,{level:3,headingIndex:iH(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:iO().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 iU(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),$=(0,i.useRef)(null),I=(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:W}=L;S.current=L;let A=(0,i.useCallback)(e=>{I.current={index:e,until:Date.now()+1600},f(e)},[]),P=(0,i.useCallback)((e,t)=>{let n=I.current;if(n&&Date.now()<n.until)return void f(n.index);I.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=tt(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}=tl(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,A(h.index);let i=.3*e.clientHeight;e.scrollTo({top:Math.max(0,n-i),behavior:"smooth"})}},150))},[A,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(A(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})},[A,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;A(e.index),n.scrollTo({top:Math.max(0,s),behavior:"smooth"})},[A,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;A(e.index),r.scrollTo({top:Math.max(0,d),behavior:"smooth"})},[A,l,o]),q=(0,i.useCallback)(()=>{$.current&&(clearTimeout($.current),$.current=null)},[]),Z=(0,i.useCallback)(()=>{q(),v(!0)},[q]),K=(0,i.useCallback)(()=>{q(),$.current=setTimeout(()=>{$.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,W),display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none",zIndex:2},children:(0,r.jsx)("div",{style:{width:8,height:8,borderRadius:2,background:n?"rgba(128,128,128,0.42)":"rgba(128,128,128,0.16)",border:`1.5px solid ${n?"rgba(128,128,128,0.95)":"rgba(128,128,128,0.58)"}`,boxShadow:n?"0 0 0 2px var(--bg-panel)":"none",transition:"transform 0.1s, background 0.1s",transform:t?"scale(1.25)":"scale(1)"}})},e.index)}),x&&u.length>0&&(0,r.jsx)("div",{ref:C,className:iO().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:iO().turn,"data-minimap-preview-index":e.index,"data-located":n?"true":void 0,children:[(0,r.jsxs)("span",{className:iO().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:iO().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:iO().content,children:[(0,r.jsx)("button",{type:"button",className:iO().user,"data-minimap-preview-user":e.index,onClick:()=>{D(e,"smooth")},children:(0,r.jsx)("span",{className:iO().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:iO().assistant,children:[(0,r.jsx)("button",{type:"button",className:iO().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)(i_,{markdown:t.markdown,onAnswerClick:()=>H(e,n),onHeadingClick:t=>U(e,n,t)})]},n))]})]},e.index)})})]})}var iq=n(42790);function iZ(e){let{text:t}=e,n=(0,i.useMemo)(()=>new iq.v().ansi_to_html(t),[t]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:n}})}function iK(e){let t,n,o,{widgets:s,children:l}=e,{t:a}=(0,E.s)(),d=(0,i.useId)(),c=(0,i.useRef)(null),u=(0,i.useRef)(new Map),[p,h]=(0,i.useState)(()=>s.find(e=>{let t=e.lines.length;return t>1&&t<=3})?.key??null),[f,m]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{var e;let t=new Map(s.map(e=>[e.key,[...e.lines]])),n=(e=c.current,e?Array.from(t,t=>{let[n,r]=t,i=e.get(n);return i&&i.length===r.length?r.some((e,t)=>e!==i[t])?n:null:i?n:null}).filter(e=>null!==e):[]);for(let[e,n]of(c.current=t,u.current))t.has(e)||(clearTimeout(n),u.current.delete(e));for(let e of(m(e=>{let r=new Set(Array.from(e).filter(e=>t.has(e)));for(let e of n)r.add(e);return r.size===e.size&&Array.from(r).every(t=>e.has(t))?e:r}),n)){let t=u.current.get(e);t&&clearTimeout(t),u.current.set(e,setTimeout(()=>{u.current.delete(e),m(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},1100))}},[s]),(0,i.useEffect)(()=>()=>{for(let e of u.current.values())clearTimeout(e);u.current.clear()},[]),0===s.length)return null;let g=s.find(e=>e.key===p&&e.lines.length>0);return(0,r.jsxs)(r.Fragment,{children:[g&&(0,r.jsx)("div",{className:"extension-widget-panels",children:(t=s.indexOf(g),n=`${d}-trigger-${t}`,o=`${d}-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:g.key}),(0,r.jsx)("pre",{className:"extension-widget-content",children:(0,r.jsx)(iZ,{text:g.lines.join("\n")})})]},g.key))}),(0,r.jsxs)("div",{className:"extension-status-row",children:[(0,r.jsx)("div",{className:"extension-widget-triggers","aria-label":a("chat.extensionWidgets"),children:s.map((e,t)=>{let n=e.lines.length>0,i=n&&e.key===g?.key,o=f.has(e.key),s=a(1===e.lines.length?"chat.extensionWidgetLine":"chat.extensionWidgetLines",{count:e.lines.length}),l=a("belowEditor"===e.placement?"chat.extensionWidgetBelow":"chat.extensionWidgetAbove"),c=`${d}-trigger-${t}`,u=`${d}-panel-${t}`,p=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"extension-widget-update-pulse","aria-hidden":"true"}),(0,r.jsx)("span",{className:"extension-widget-placement","aria-hidden":"true",children:(0,r.jsx)("svg",{className:"extension-widget-placement-icon",viewBox:"0 0 8 6",width:"8",height:"6","data-direction":"belowEditor"===e.placement?"down":"up",focusable:"false",children:(0,r.jsx)("path",{d:"belowEditor"===e.placement?"M0 0h8L4 6z":"M4 0l4 6H0z"})})}),(0,r.jsx)("span",{className:"extension-widget-key",children:e.key})]});return n?(0,r.jsx)("button",{id:c,type:"button",className:`extension-widget-trigger${i?" is-expanded":""}${o?" is-updating":""}`,"aria-controls":u,"aria-expanded":i,"aria-label":`${l}: ${e.key}, ${s}`,title:`${e.key} - ${l} - ${i?a("i18n.collapse"):a("i18n.expand")}`,onClick:()=>{h(t=>{var n;return t===(n=e.key)?null:n})},children:p},e.key):(0,r.jsx)("div",{className:`extension-widget-trigger${o?" is-updating":""}`,"aria-label":`${l}: ${e.key}, ${s}`,title:`${e.key} - ${l}`,children:p},e.key)})}),l]})]})}let iV="command:";function iJ(e){let{statuses:t,widgets:n=[],onCommand:i,commandsDisabled:o=!1}=e,s=function(e){let t=[];for(let n of[...e].sort((e,t)=>e.key.localeCompare(t.key))){let e=n.text.replace(/\r\n?/g,"\n").split("\n").map(e=>e.replace(/\t/g," ").replace(/ +/g," ").trim()).join("\n").trim(),r=function(e){if(!e.startsWith(iV))return null;let t=e.slice(iV.length).trim();return t.length>1&&t.startsWith("/")?t:null}(n.key);if(r){let n=e5(e).replace(/\s+/g," ").trim();t.push({kind:"command",command:r,label:n||r})}else e5(e).trim()&&t.push({kind:"text",text:e})}return t}(t);if(0===s.length&&0===n.length)return null;let l=s.some(e=>"command"===e.kind),a=s.map(e=>"text"===e.kind?e5(e.text):e.label).join(" "),d=s.length>0?(0,r.jsx)("div",{role:"status",className:"extension-status-line","aria-label":a,title:a,children:(0,r.jsx)("span",{className:"extension-status-text",children:s.map((e,t)=>"text"===e.kind?(0,r.jsx)("span",{className:"extension-status-item",children:(0,r.jsx)(iZ,{text:e.text})},t):(0,r.jsx)("button",{type:"button",className:"extension-status-item extension-status-command",disabled:!i||o,title:`${e.label} \xb7 ${e.command}`,"aria-label":`${e.label} (${e.command})`,onClick:()=>i?.(e.command),children:e.label},t))})}):null;return(0,r.jsx)("div",{className:`extension-status-shelf${n.length>0?" has-widgets":""}${s.length>0?" has-status":""}${l?" has-commands":""}`,children:n.length>0?(0,r.jsx)(iK,{widgets:n,children:d}):d})}function iY(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document;return"visible"!==e.visibilityState||!e.hasFocus()}function iG(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 iX(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 iQ(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function i0(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(!iQ(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=iQ(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=iQ(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 i1 extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}function i2(e){return e instanceof i1&&"prompt_rejected"===e.code&&!1===e.accepted}async function i4(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 i1(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}function i8(){return globalThis.__piSessionViewCache||(globalThis.__piSessionViewCache=new Map),globalThis.__piSessionViewCache}function i5(e){try{return JSON.stringify(e).length}catch{return Number.MAX_SAFE_INTEGER}}function i3(e){let t=i8().get(e);return t?Date.now()-t.savedAt>6e5?(i8().delete(e),null):(i8().delete(e),i8().set(e,t),t):null}function i6(e){if(!e.sessionId||!e.revision)return!1;let t=i8();t.delete(e.sessionId);let n={...e,savedAt:Date.now()};return!(i5(n)>0x2000000)&&(t.set(n.sessionId,n),!function(){let e=i8();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+=i5(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-=i5(r))}}(),i8().has(n.sessionId))}function i9(e){i8().delete(e)}var i7=n(14755);let oe="pi-tool-preset";function ot(){try{return window.localStorage}catch{return null}}function on(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 or(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,on(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),on(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function oi(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 oo(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(oi).filter(Boolean)}):JSON.stringify({text:"",images:[]})}class os 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 ol{constructor(e){this.options=e,this.current=null,this.retry=null,this.retryGeneration=0}close(){this.stopRetrying(),this.current&&this.discard(this.current,new os("closed"))}maintain(e){if(!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof os?"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 os("closed")}if(1===t.source.readyState)return;this.discard(t,new os("closed"))}}open(e){let t,n,r;this.current&&this.discard(this.current,new os("closed"));try{t=this.options.createSource(e)}catch(e){throw new os("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 os("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 os("startup_error",e));return}this.options.onEvent(t)}},t.onerror=()=>{this.fail(a,new os("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 oa(e){return("tool_execution_start"===e.type||"tool_execution_update"===e.type||"tool_execution_end"===e.type)&&"string"==typeof e.parentToolCallId&&""!==e.parentToolCallId}function od(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 oc(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ou(e,t){return e.every(e=>t.has(e.id))?e:e.filter(e=>t.has(e.id))}function op(e,t){return e.some(e=>e.id===t)?e.filter(e=>e.id!==t):e}function oh(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return e+t>=n-r}let of={isStreaming:!1,streamingMessage:null};function om(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 og(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"resume":return{...e,isStreaming:!0};case"snapshot":{let n=i0(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 om(e,n.contentIndex,()=>({type:"text",text:""}));case"text_delta":return om(e,n.contentIndex,e=>e?.type==="text"?{...e,text:e.text+n.delta}:null);case"text_end":return om(e,n.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:n.content}));case"thinking_start":return om(e,n.contentIndex,()=>({type:"thinking",thinking:""}));case"thinking_delta":return om(e,n.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+n.delta}:null);case"thinking_end":return om(e,n.contentIndex,e=>({...e?.type==="thinking"?e:{},type:"thinking",thinking:n.content}));case"toolcall_start":return om(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 om(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 om(e,n.contentIndex,()=>({type:"toolCall",toolCallId:n.toolCall.id,toolName:n.toolCall.name,input:n.toolCall.arguments}));default:return e}case"end":return of;default:return e}}function ox(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function ov(e){return e&&"auto"!==e?e:null}let ob=new Map,oy=[2e3,5e3,1e4];function oj(e){return new Promise(t=>setTimeout(t,e))}function ok(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function ow(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:ok(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:ok(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=ok(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function oS(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 oC(e){return Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)}function oE(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 oN(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 o$(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 oI(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:$,onContextUsageChange:I,onOpenFile:R,onFilesUploaded:L,onOpenSession:z,onAskInNewChat:W,quoteSelectionEnabled:A=!1,initialPrompt:P,onInitialPromptConsumed:O,soundEnabled:F=!0,onSoundToggle:B,playDoneSound:D=()=>{},unlockAudio:H}=e,{t:_}=(0,E.s)(),U=e$(),q=l?.relation?.kind!=="subagent",Z=(0,i.useRef)(D);Z.current=D;let K=(0,i.useRef)(F);K.current=F;let V=(0,i.useRef)(!1),J=(0,i.useCallback)(()=>{q&&K.current&&Z.current(),m?.()},[q,m]),Y=(0,i.useRef)(a?null:c??null),[G,X]=(0,i.useState)(()=>{let e=Y.current;return e&&!e.atBottom?e:null}),[Q,ee]=(0,i.useState)(!1),{loading:et,error:en,messages:er,activeToolResults:es,entryIds:el,historyCursor:ea,hasEarlierMessages:ed,streamState:ec,agentRunning:eu,bashRunning:ep,pendingBash:eh,modelNames:ef,modelList:em,modelError:eg,modelScopeWarnings:ex,modelThinkingLevels:ev,modelThinkingLevelMaps:eb,toolPreset:ey,thinkingLevel:ej,retryInfo:ek,contextUsage:ew,forkingEntryId:eS,isCompacting:eC,compactError:eE,compactResult:eN,displayModel:eI,modelSwitching:eT,sessionStats:eM,slashCommands:eR,slashCommandsLoading:eL,queuedMessages:ez,notices:eW,extensionDialog:eA,waitingExtensionDialogCount:eP,extensionCustomUi:eO,waitingExtensionCustomUiCount:eF,extensionStatuses:eB,extensionWidgets:eD,respondToExtensionUi:eH,sendExtensionCustomInput:e_,setNoticePaused:eU,addNotice:eq,isAutoModelSelection:eZ,isAutoThinkingSelection:eK,defaultModel:eV,savedDefaultThinkingLevel:eJ,agentPhase:eY,isNew:eG,editEntryId:eX,showScrollToBottom:eQ,sessionIdRef:e0,scrollContainerRef:e2,lastUserMsgRef:e4,promptAnchorActive:e8,handleSend:e5,handleAbort:e3,handleFork:e6,handleEditContent:e9,cancelEdit:e7,handleModelChange:te,handleCompact:tn,handleSteer:ta,handleFollowUp:td,handlePromptWithStreamingBehavior:tc,handleAbortCompaction:tp,handleRecallQueue:th,handleBuiltinSlashCommand:tf,handleToolPresetChange:tj,handleThinkingLevelChange:tE,handleSetDefaultModel:tN,handleSetDefaultThinkingLevel:t$,loadSlashCommands:tI,scrollUserMsgToTop:tT,loadContext:tM,activeLeafId:tR,scrollToBottom:tL,scrollToMessage:tz}=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,W]=(0,i.useState)(!1),[A,P]=(0,i.useReducer)(og,of),[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)(i7.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=(0,i.useRef)(0),ew=(0,i.useRef)(0),[eS,eC]=(0,i.useState)(null),[eE,eN]=(0,i.useState)(null),[e$,eI]=(0,i.useState)(null),[eT,eM]=(0,i.useState)(null),[eR,eL]=(0,i.useState)(null),[ez,eW]=(0,i.useState)(!1),[eA,eP]=(0,i.useState)(!1),[eO,eF]=(0,i.useState)(!0),[eB,eD]=(0,i.useState)(null),[eH,e_]=(0,i.useState)(null),[eU,eq]=(0,i.useState)(null),[eZ,eK]=(0,i.useState)(!1),[eV,eJ]=(0,i.useState)(!1),[eY,eG]=(0,i.useState)([]),[eX,eQ]=(0,i.useState)(!1),[e0,e1]=(0,i.useReducer)(ow,{visible:[],pending:[]}),[e2,e4]=(0,i.useState)(null),[e8,e5]=(0,i.useState)([]),[e3,e6]=(0,i.useState)([]),[e9,e7]=(0,i.useState)([]),[te,tt]=(0,i.useState)([]),[tn,tr]=(0,i.useState)({steering:[],followUp:[]}),ti=(0,i.useRef)(null),to=(0,i.useRef)(null),ts=(0,i.useRef)(0),tl=(0,i.useRef)(!1),ta=(0,i.useRef)(t?.id??null),td=(0,i.useRef)(t?.id??null),tc=(0,i.useRef)(!1),tu=(0,i.useRef)(!1),tp=(0,i.useRef)(!1),th=(0,i.useRef)(!1),tf=(0,i.useRef)(-1),tm=(0,i.useRef)(!1),tg=(0,i.useRef)(0),tx=(0,i.useRef)(null),tv=(0,i.useRef)(!!e.deferInitialScroll),tb=(0,i.useRef)(null),ty=(0,i.useRef)(!1),tj=(0,i.useRef)(!0),tk=(0,i.useRef)(0),tw=(0,i.useRef)(null),tS=(0,i.useRef)(void 0),tC=(0,i.useRef)(void 0),tE=(0,i.useRef)(null),tN=(0,i.useRef)(null),t$=(0,i.useRef)([]),tI=(0,i.useRef)(null),tT=(0,i.useRef)(0),tM=(0,i.useRef)(!1),tR=(0,i.useRef)(null),tL=(0,i.useRef)(null),tz=(0,i.useRef)({}),tW=(0,i.useRef)(null),tA=(0,i.useRef)(0),tP=(0,i.useRef)(null),tO=(0,i.useRef)(!1),tF=(0,i.useRef)(new Map),tB=(0,i.useRef)(!0),tD=(0,i.useRef)(new Map),tH=(0,i.useRef)(null),t_=(0,i.useRef)([]),tU=(0,i.useRef)([]),tq=(0,i.useRef)(null),tZ=(0,i.useRef)(null),tK=(0,i.useRef)(!1);td.current=t?.id??null,tH.current=v,t_.current=E,tU.current=T,tq.current=S,tZ.current=R,tK.current=z,ti.current||(ti.current=new ol({createSource:e=>new EventSource(`/api/agent/${encodeURIComponent(e)}/events`),onEvent:e=>tx.current?.(e),shouldMaintain:e=>tB.current&&ta.current===e&&(tu.current||tl.current||td.current===e),readinessTimeoutMs:6e4,reconnectDelayMs:1e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let tV=e.setToolPreset??el,tJ=t?.id;(0,i.useLayoutEffect)(()=>{(tJ||x&&!ta.current)&&tV(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ot();if(!e)return i7.Q8;try{let t=e.getItem(oe);return(0,i7.sn)(t)?t:i7.Q8}catch{return i7.Q8}}())},[tJ,x,tV]);let tY=(0,i.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"smooth",t=tE.current;t&&(t.scrollTo({top:t.scrollHeight,behavior:e}),tk.current=t.scrollTop)},[]),tG=e$??eT??v?.context.model??eR??null,tX=x?en??ei:tG??(v?.context.messages.length===0?ei:null),tQ=ov(v?.context.thinkingLevel&&"off"!==v.context.thinkingLevel?v.context.thinkingLevel:null),t0=x?ea??ec:ef??eg??tQ??(v?.context.messages.length===0?ec:null),t1=t?.id??o??void 0,t2=(0,i.useCallback)(e=>{eM(e?.model?{provider:e.model.provider,modelId:e.model.id}:null),e?.thinkingLevel!==void 0&&ex(ov(e.thinkingLevel))},[]),t4=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=tF.current.get(t);if(!e)break;t=e}return t},[]),t8=(0,i.useCallback)((t,n,r)=>{let i=n?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}}),s=t4(r);if(!tB.current&&!tM.current&&r===o)return;let l=e.chatInputRef?.current;if(l)l.restoreSubmission(t,i,s);else{let e,n;s&&(n=rf(t,i,(e=rc(s)??{value:"",images:[]}).value,e.images),ru(s,n))}},[o,e.chatInputRef,t4]),[t5,t3]=(0,i.useState)(()=>{let e=t?.id;return e&&!rc(e)&&ob.delete(e),e&&ob.get(e)||null}),t6=(0,i.useCallback)(e=>{t?.id&&(e?ob.set(t.id,e):ob.delete(t.id),t3(e))},[t?.id]),t9=(0,i.useCallback)((n,r)=>{t?.id&&(e.chatInputRef?.current?.replaceMessage(n),t6(r))},[e.chatInputRef,t?.id,t6]),t7=(0,i.useCallback)(()=>t6(null),[t6]),ne=(0,i.useMemo)(()=>{if(e2)return{...e2,totalActiveMs:v?.totalActiveMs,...ey?{contextUsage:ey}:{}};let e=v?.stats,n=function(e,t,n){let r=or(n);if(!e)return r;let i=or(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:ta.current??t?.id??"",sessionName:t?.name,...n,totalActiveMs:v?.totalActiveMs,...ey?{contextUsage:ey}:{}}:null},[E,e2,ey,v?.context.messages,v?.filePath,v?.totalActiveMs,v?.stats,t?.id,t?.name]),nt=(0,i.useCallback)((e,t,n,r)=>{tB.current&&ta.current===t&&tA.current===n&&!(r<=ew.current)&&(ew.current=r,e?.contextUsage!==void 0&&ej(e.contextUsage??null))},[]),nn=(0,i.useCallback)(async e=>{let t=tA.current,n=++ek.current;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();nt(i.state,e,t,n)}catch{}},[nt]),nr=(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:tD.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),W(!1),w(null)),i9(e),null;if(!s.ok)throw Error(`HTTP ${s.status}`);let l=await s.json();if(ta.current!==e)return null;let a=i3(e),d=!!(l.snapshotRevision&&a?.revision===l.snapshotRevision&&a.entryIds.length>=(l.context.entryIds??[]).length),c=d?t_.current:l.context.messages;if(b(d?{...l,context:{...l.context,messages:t_.current,entryIds:tU.current,oldestEntryId:tZ.current,hasMore:tK.current}}:l),C(l.leafId),d?i6({sessionId:e,revision:l.snapshotRevision,messages:t_.current,entryIds:tU.current,leafId:l.leafId,oldestEntryId:tZ.current,hasMore:tK.current,summaryTree:l.tree,thinkingLevel:l.context.thinkingLevel,model:l.context.model,stats:l.stats,totalActiveMs:l.totalActiveMs,loadedEntryIds:tU.current}):(N(c),M(l.context.entryIds??[]),L(l.context.oldestEntryId),W(l.context.hasMore)),tc.current=void 0!==l.toolNames,tV(void 0!==l.toolNames?(0,i7.YO)(l.toolNames):i7.Q8),eI(e=>tO.current?e:null),em(null),w(null),"summary"===l.treeFormat&&l.snapshotRevision&&i6({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&&(ti.current?.close(),ti.current?.maintain(e)),!n&&l.context.thinkingLevel&&"off"!==l.context.thinkingLevel&&ex(ov(l.context.thinkingLevel)),i=!0,t&&j(!1),!n)return null;try{let t=tA.current,n=++ek.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(ta.current!==e)return null;let o=i.state;return t2(o),o?(nt(o,e,t,n),void 0!==o.systemPrompt&&eC(o.systemPrompt??null),void 0!==o.extensionStatuses&&e7(o.extensionStatuses??[]),void 0!==o.extensionWidgets&&tt(o.extensionWidgets??[]),void 0!==o.queuedMessages&&tr(ox(o.queuedMessages)),void 0!==o.autoCompactionEnabled&&eF(o.autoCompactionEnabled??!0)):i.running||tr({steering:[],followUp:[]}),i}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||tD.current.set(i,s),s.finally(()=>{tD.current.get(i)===s&&tD.current.delete(i)}),await s},[nt,tV,t2]),ni=(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(ta.current!==e||r?.signal?.aborted||!tB.current)return;return L(l.context.oldestEntryId),W(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)}},[]),no=(0,i.useCallback)(async e=>{try{let t=await i4(e,{type:"get_tools"});if(!t||!tB.current||ta.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return tV(tc.current?r(t):i7.Q8),h?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[h,tV]),ns=(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=ta.current;if(x&&r&&i&&!tM.current&&(tM.current=!0,o)){if(o!==i){tF.current.set(o,i);let t=e.chatInputRef?.current;t?t.rekeyDraft(o,i):rm(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]),nl=(0,i.useCallback)(async()=>{if(ta.current||!x||!r)return ta.current;if(tN.current)return tN.current;let e=(async()=>{let e=tR.current,t=tL.current;e&&eL(e);let n=(0,i7.xG)(es);tc.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 ta.current=s,o.model&&tR.current===e&&(eL(o.model),e||eo(o.model)),o.thinkingLevel&&tL.current===t&&(ex(ov(o.thinkingLevel)),t||eu(ov(o.thinkingLevel))),s})();tN.current=e;try{return await e}finally{tN.current=null}},[x,r,es]),na=(0,i.useCallback)(async()=>{let e=ta.current??await nl();if(!e)return;let[t]=await Promise.all([i4(e,{type:"get_state"}),no(e)]);tB.current&&ta.current===e&&(t2(t),eC(t.systemPrompt??""))},[nl,no,t2]),nd=(0,i.useCallback)(e=>{t$.current=e,eG(e)},[]),nc=(0,i.useCallback)(()=>{tT.current+=1,tI.current=null,nd([])},[nd]),nu=(0,i.useCallback)(()=>{let e=++tT.current,t=(async()=>{let t=ta.current??await nl();if(!t)return tT.current===e&&nd([]),[];eQ(!0);try{let n=await i4(t,{type:"get_commands"}),r=n?.commands??[];return tT.current===e&&nd(r),r}catch(t){return console.error("Failed to load slash commands:",t),tT.current===e&&nd([]),null}finally{tT.current!==e&&tI.current||eQ(!1)}})();tI.current=t;let n=()=>{tI.current===t&&(tI.current=null)};return t.then(n,n),t},[nl,nd]),np=(0,i.useCallback)(async()=>await nu()??[],[nu]),nh=(0,i.useCallback)(async()=>{let e=tI.current,t=t$.current;return!e&&t.length>0?t:await (e??nu()).catch(()=>null)??(t.length>0?t:null)},[nu]),nf=(0,i.useCallback)(()=>{ts.current+=1,tl.current=!1,to.current&&(clearTimeout(to.current),to.current=null)},[]),nm=(0,i.useCallback)(()=>{ti.current?.close()},[]),ng=(0,i.useCallback)(e=>ti.current.ensureConnected(e),[]),nx=(0,i.useCallback)(e=>{ti.current.maintain(e)},[]);(0,i.useEffect)(()=>{let e=t?.id;if(e)return tB.current=!0,nx(e),()=>{ta.current===e&&ti.current?.close()}},[nx,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||ta.current!==e||td.current!==e||(nm(),nx(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)}},[nm,nx,t?.id]);let nv=(0,i.useCallback)(async(e,t)=>{let n=ta.current;if(e5(t=>op(t,e.id)),n)try{await i4(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e)}},[]),nb=(0,i.useCallback)(async(e,t)=>{let n=ta.current;if(n)try{await i4(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),ny=(0,i.useCallback)(e=>{let t=e.message.trim();t&&e1({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"}})},[]),nj=(0,i.useCallback)(t=>{switch(iG(t)&&l?.(t),t.method){case"select":case"confirm":case"input":case"editor":e5(e=>e.some(e=>e.id===t.id)?e:[...e,t]);break;case"notify":ny({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":e7(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":tt(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":e6(e=>{let n;return t.closed?op(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)})}},[ny,l,e.chatInputRef]),nk=(0,i.useCallback)(()=>{let e=tu.current;return tu.current=!1,F(!1),eq(null),eb(null),I(new Map),P({type:"end"}),e},[]),nw=(0,i.useCallback)(e=>tf.current!==e&&(tf.current=e,s?.(),!0),[s]),nS=(0,i.useCallback)(e=>{if(td.current===e)return void nf();nf(),tl.current=!0;let t=ts.current,n=async()=>{if(t===ts.current&&ta.current===e&&tl.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!==ts.current||ta.current!==e||!tl.current)return;let o=i.state;if(t2(o),i.running&&o&&(o.isStreaming||o.isPromptRunning)){tl.current=!1,to.current=null,tp.current=!!o?.isStreaming,th.current=!!o?.isPromptRunning,tu.current=!0,F(!0),eq(o?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(i.running&&o?.isCompacting){eP(!0),to.current=setTimeout(()=>void n(),600);return}tl.current=!1,to.current=null,nm()}catch{if(t!==ts.current||ta.current!==e||!tl.current)return;to.current=setTimeout(()=>void n(),600)}};to.current=setTimeout(()=>void n(),3e4)},[nf,nm,t2]),nC=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ta.current,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tA.current;if(tA.current===t)try{e&&await nr(e)}finally{if(tA.current!==t)return;let n=th.current,r=tp.current;th.current=!1,tp.current=!1,tP.current=null;let i=nk();n?nw(t):r&&i&&s?.(),e&&nS(e)}},[nr,nw,s,nS,nk]),nE=(0,i.useCallback)(async(e,t)=>{await oj(800);let n=Date.now();for(;tu.current&&Date.now()-n<2e4;){if(void 0!==t&&tA.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(t2(i),!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await nC(e,t)}}catch{}await oj(600)}},[nC,t2]),nN=(0,i.useCallback)(async e=>{let t=tg.current+1;for(tg.current=t;tm.current&&tg.current===t&&ta.current===e;){await oj(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(t2(r.state),r.state?.isBashRunning)continue;if(await nr(e),tg.current!==t||ta.current!==e)return;tm.current=!1,D(!1),_(null);return}catch{}}},[nr,t2]),n$=(0,i.useCallback)(async e=>{if(!tu.current||ta.current!==e)return;let t=tA.current,n=++ek.current;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(ta.current!==e||tA.current!==t)return;let o=i.state;if(nt(o,e,t,n),t2(o),eP(o?.isCompacting??!1),eF(o?.autoCompactionEnabled??!0),tr(ox(o?.queuedMessages)),i.running&&o&&(o.isStreaming||o.isPromptRunning||o.isCompacting)){tp.current=!!o.isStreaming,th.current=!!o.isPromptRunning;return}if(!tu.current)return;o&&(void 0!==o.systemPrompt&&eC(o.systemPrompt??null),void 0!==o.extensionStatuses&&e7(o.extensionStatuses??[]),void 0!==o.extensionWidgets&&tt(o.extensionWidgets??[])),await nC(e,t)}catch{}},[nt,nC,t2]);(0,i.useEffect)(()=>{if(!O)return;let e=()=>{let e=ta.current;e&&n$(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,n$]),(0,i.useEffect)(()=>{tu.current=O},[O]),tx.current=(0,i.useCallback)(e=>{switch(e.type){case"connected":if(P({type:"end"}),Array.isArray(e.pendingExtensionUiIds)){let t=new Set(e.pendingExtensionUiIds);e5(e=>ou(e,t)),e6(e=>ou(e,t))}!0===e.isStreaming&&(nf(),tp.current=!0,tu.current=!0,F(!0),eq({kind:"waiting_model"}));break;case"agent_start":nf(),tp.current=!0,tu.current=!0,F(!0),eq({kind:"waiting_model"}),P({type:"start"});break;case"agent_end":if(!tu.current)break;if(eq(null),eb(null),P({type:"end"}),ta.current){let e=ta.current,t=tA.current,n=++ek.current;nr(e),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(r=>{r&&tB.current&&ta.current===e&&tA.current===t&&(t2(r.state),nt(r.state,e,t,n),r.state?.systemPrompt!==void 0&&eC(r.state.systemPrompt??null),r.state?.extensionStatuses!==void 0&&e7(r.state.extensionStatuses??[]),r.state?.extensionWidgets!==void 0&&tt(r.state.extensionWidgets??[]),tr(ox(r.state?.queuedMessages)))}).catch(()=>{})}break;case"agent_settled":{let e=tp.current;if(tp.current=!1,!e||th.current)break;let t=ta.current,n=nk();eP(!1),t&&(nr(t),nS(t)),n&&s?.();break}case"prompt_done":{let e=tA.current,t=th.current;th.current=!1,tP.current=null;let n=nw(e);if(!t&&!n)break;let r=ta.current;r&&nr(r),!tp.current&&(nk(),r&&nS(r))}break;case"prompt_error":ny({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":ny({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":if(!tu.current||od(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&&eq(null)):t&&eq(null)}else{let t=e.assistantMessageEvent;t&&(P({type:"delta",event:t}),"toolcall_start"!==t.type&&"toolcall_delta"!==t.type&&eq(null))}!ty.current&&tj.current&&null===tw.current&&(tw.current=requestAnimationFrame(()=>{tw.current=null,tj.current&&tY("auto")}));break;case"message_end":{if(!tu.current||od(e))break;let t=e.message;if(t&&"user"===t.role){let e=i0(t),n=oo(e),r=tP.current;tP.current=null,N(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&oo(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]})}else if(t&&(N(e=>[...e,i0(t)]),"assistant"===t.role)){let e=ta.current;e&&nn(e)}P({type:"end"}),eq({kind:"waiting_model"});break}case"tool_execution_start":{if(oa(e))break;let t=e.toolCallId,n=e.toolName;eq(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[];return r.some(e=>e.id===t)||r.push({id:t,name:n}),{kind:"running_tools",tools:r}});break}case"tool_execution_update":{if(oa(e))break;let t=e.toolCallId,n=e.toolName,r=e.partialResult,i=r?.content;("bash"===n||"powershell"===n||n===nT)&&Array.isArray(i)&&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===nT?function(e){if(!nR(e))return null;let{calls:t}=nz(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(!oc(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>oc(e)&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n").split(/\r?\n/),r="";for(let e=n.length-1;e>=0&&!(r=n[e].trim());e-=1);if(!r)return null;let i=r.replace(/\s+/g," ");return i.length<=500?i:`...${i.slice(-497)}`}(e.partialResult);eq(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[],i=r.find(e=>e.id===t),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(oa(e))break;let t=e.toolCallId;I(e=>{if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}),eq(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"queue_update":tr({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":eP(!0),eD(null),e_(null);break;case"auto_compaction_end":case"compaction_end":eP(!1),e.errorMessage?(eD(e.errorMessage),e_(null)):!e.aborted&&(e_(oS(e.result,e.reason??"auto")),ta.current&&nr(ta.current));break;case"extension_ui_request":nj(e);break;case"extension_ui_closed":e5(t=>op(t,e.id))}},[ny,nt,nf,nj,nr,nw,s,nn,nS,tY,nk,t2]);let nI=(0,i.useCallback)(async(e,n)=>{let i=e.trim();if(!i&&!n?.length)return;if(tu.current||tm.current)return void t8(e,n,t1);if(t5&&(t6(null),!await tC.current?.(t5))){t6(t5),t8(e,n,t1);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 tS.current?.(r,t):void t8(e,n,t1)}let s=tA.current+1;nf(),th.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]),tP.current=oo(a),tA.current=s,tu.current=!0,F(!0),eq(o?{kind:"running_command"}:{kind:"waiting_model"}),P({type:"start"}),ty.current=!0,eK(!0);let d=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),c=null,u=!1;try{if(x&&r){let t=ta.current??await tN.current,n=t??await nl();if(!n)throw Error("Unable to create a session for the prompt");c=n,en&&(eL(en),t&&await i4(n,{type:"set_model",provider:en.provider,modelId:en.modelId})),await ng(n),u=!0,await i4(n,{type:"prompt",message:e,...d?.length?{images:d}:{}}),ns(1,e)}else if(t)c=t.id,await ng(t.id),u=!0,await i4(t.id,{type:"prompt",message:e,...d?.length?{images:d}:{}});else throw Error("No active session for the prompt");o&&c&&nE(c,s)}catch(t){if(console.error("Failed to send message:",t),!(!u||i2(t))&&c)return void nE(c,s);if(th.current=!1,N(e=>{let t=e.lastIndexOf(a);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),ny({type:"error",message:t instanceof Error?t.message:String(t)}),t8(e,n,t1),tP.current=null,c)return void n$(c);tu.current=!1,nm(),F(!1),eq(null),P({type:"end"})}},[x,r,en,t,nl,ng,ns,nE,ny,nf,nm,t1,n$,t8,t5,t6]);tS.current=(0,i.useCallback)(async(e,n)=>{if(tu.current||tm.current)return;let r=`${n?"!!":"!"}${e}`;tm.current=!0,_({command:e,excludeFromContext:n}),D(!0);try{let i=ta.current??t?.id??await nl();if(!i)throw Error("Unable to create a session for the shell command");await i4(i,{type:"bash",command:e,excludeFromContext:n}),await nr(i),ns(1,r)}catch(e){console.error("Failed to execute shell command:",e),ny({type:"error",message:e instanceof Error?e.message:String(e)}),t8(r,void 0,t1)}finally{tm.current=!1,_(null),D(!1)}},[ny,t1,nl,nr,ns,t8,t]);let nM=(0,i.useCallback)(async()=>{let e=ta.current;if(e){if(tm.current){try{await i4(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await i4(e,{type:"abort"})}catch(e){console.error("Failed to abort:",e)}}},[]),nL=(0,i.useCallback)(async e=>{if(tm.current)return;let t=ta.current;if(t){eN(e);try{let{cancelled:n,newSessionId:r}=await i4(t,{type:"fork",entryId:e})??{};!n&&r&&d?.(r)}catch(e){console.error("Fork failed:",e),ny({type:"error",message:e instanceof Error?e.message:String(e)})}finally{eN(null)}}},[ny,d]),nW=(0,i.useCallback)(async e=>{if(tm.current)return!1;let t=ta.current;if(!t)return!1;try{let n=await i4(t,{type:"navigate_tree",targetId:e});if(n?.cancelled||ta.current!==t)return!1;return await nr(t),ta.current===t}catch(e){return console.error("Failed to navigate:",e),!1}},[nr]);tC.current=nW;let nA=(0,i.useCallback)(async e=>{if(tm.current||tu.current||eA)return;C(e);let t=ta.current;t&&(await ni(t,e),e&&i4(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[eA,ni]),nP=(0,i.useCallback)(async(e,t)=>{if(x){let n={provider:e,modelId:t};tR.current=n,er(n),eL(n),null===tL.current&&eu(ov(tz.current[`${e}/${t}`])??tW.current);let r=ta.current??await tN.current;if(!r)return;try{await i4(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=ta.current;if(n&&!tO.current){tO.current=!0,eI({provider:e,modelId:t}),eW(!0);try{let r=await i4(n,{type:"set_model",provider:e,modelId:t});eM({provider:r.provider,modelId:r.id}),tO.current=!1,await nr(n)}catch(e){console.error("Failed to set model:",e),tO.current=!1,eI(e$),ny({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nr(n,!1,!0)}finally{tO.current=!1,eW(!1)}}},[ny,e$,x,nr,er]),nO=(0,i.useCallback)(async()=>{let e=ta.current;if(e&&!eA){eP(!0),eD(null),e_(null);try{let t=await i4(e,{type:"compact"});e_(oS(t,"manual")),await nr(e,!0)}catch(e){eD(e instanceof Error?e.message:String(e)),e_(null)}finally{eP(!1)}}},[eA,nr]),nF=(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),tz.current=n.thinkingLevelPins??{},tW.current=ov(n.defaultThinkingLevel),eh(ov(n.savedDefaultThinkingLevel)),x&&!ta.current){let e=l&&n.thinkingLevelPins?.[`${l.provider}/${l.id}`];null===tL.current&&eu(ov(e)??tW.current)}},[x,r,t?.cwd]),nB=(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]),nD=(0,i.useCallback)(()=>{nF().catch(()=>{})},[nF]),nH=(0,i.useCallback)(async(e,t)=>{try{await nB({provider:e,modelId:t})}catch(e){ny({type:"error",message:`Failed to save default model: ${e instanceof Error?e.message:String(e)}`});return}ny({type:"success",message:`Default model: ${e}/${t}`}),eo({provider:e,modelId:t}),(tX?.provider!==e||tX?.modelId!==t)&&await nP(e,t),nD()},[ny,tX,nP,nD,nB]),n_=(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=ta.current??await nl(),s=e=>(e.handled&&(e.error?ny({type:"error",message:e.error}):e.action||ny({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!o||eA)return s({handled:!0,error:"No active session to compact"});eP(!0),eD(null),e_(null);let e=await i4(o,{type:"compact",...i?{customInstructions:i}:{}});return e_(oS(e,"manual")),await nr(o,!0)&&ns(),s({handled:!0,message:"Compacted context"})}case"auto-compact":{if(!o)return s({handled:!0,error:"No active session"});let e=await i4(o,{type:"get_state"}),t=!(e?.autoCompactionEnabled??!0);return await i4(o,{type:"set_auto_compaction",enabled:t}),eF(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 i4(o,{type:"reload"}),await Promise.all([nr(o,!1,!0),no(o),np(),nF()]),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 i4(o,{type:"set_session_name",name:i}),await nr(o)&&ns(),s({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!o)return s({handled:!0,error:"No active session"});let e=await i4(o,{type:"get_session_stats"});return e&&e4(e),m?.(),s({handled:!0,action:"openSessionStats"})}case"mcp":{if(i||!g)return{handled:!1};let e=await nh();if(!e||!(e.some(rj)||!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 i4(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(tu.current||tm.current)return s({handled:!0,error:"Cannot clone while the session is running"});let e=await i4(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&&eP(!1)}},[S,ny,nl,eA,nF,nr,np,no,ns,g,d,m,nh]),nU=(0,i.useCallback)(async(e,t,n)=>{let r=ta.current;if(t5)return void t8(e,n,t1);if(!r){t8(e,n,t1),ny({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 i4(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){console.error("Failed to submit streaming prompt:",t),i2(t)&&t8(e,n,t1),ny({type:"error",message:t instanceof Error?t.message:String(t)})}},[ny,t1,t5,t8]),nq=(0,i.useCallback)(async(e,t)=>{await nU(e,"steer",t)},[nU]),nZ=(0,i.useCallback)(async(e,t,n)=>{await nU(e,t,n)},[nU]),nK=(0,i.useCallback)(async(e,t)=>{await nU(e,"followUp",t)},[nU]),nV=(0,i.useCallback)(async()=>{let e=ta.current;if(e)try{await i4(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),nJ=(0,i.useCallback)(async()=>{let t=ta.current;if(t)try{let n=await i4(t,{type:"clear_queue"});tr({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),ny({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,ny]),nY=(0,i.useCallback)(async e=>{if("auto"===e){tL.current=null,ed(null),em(null);return}x?(tL.current=e,ed(e)):em(e);let t=ta.current??await tN.current;if(t)try{await i4(t,{type:"set_thinking_level",level:e}),tB.current&&ta.current===t&&(ex(e),em(null))}catch(e){console.error("Failed to set thinking level:",e),em(null)}},[x]),nG=(0,i.useCallback)(async e=>{try{await nB({thinkingLevel:e})}catch(e){ny({type:"error",message:`Failed to save default reasoning level: ${e instanceof Error?e.message:String(e)}`});return}ny({type:"success",message:`Default reasoning level: ${e}`}),eh(e),t0!==e&&await nY(e),nD()},[ny,t0,nY,nD,nB]),nX=(0,i.useCallback)(async e=>{let t=(0,i7.xG)(e);!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ot();if(t)try{t.setItem(oe,e)}catch{}}(e),tV(e);let n=ta.current??await tN.current;if(!n){tc.current=void 0!==t;return}try{let e=await i4(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});tc.current=void 0!==t;let r=e?.sessionId??n;(r!==n||e?.recreated)&&(nf(),nm(),e5([]),e6([]),ta.current=r,e?.recreated&&td.current===r&&nx(r)),nc(),e7([]),tt([]);let[i]=await Promise.all([i4(r,{type:"get_state"}),no(r)]);tB.current&&ta.current===r&&(eC(i.systemPrompt??""),t2(i))}catch(e){console.error("Failed to set tools:",e)}},[nf,nc,nm,no,nx,tV,t2]),nQ=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=tE.current;n&&(null!==tw.current&&(cancelAnimationFrame(tw.current),tw.current=null),tv.current=!0,ty.current=!1,tj.current=!1,eK(!1),n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),tk.current=n.scrollTop)},[]),n0=(0,i.useCallback)(()=>{let e=tE.current,t=tb.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!==tw.current&&(cancelAnimationFrame(tw.current),tw.current=null),tj.current=!0,tk.current=n,e.scrollTo({top:n,behavior:"auto"})},[]),n1=(0,i.useCallback)(()=>{let e=tE.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=tu.current,o=tj.current,s=function(e,t,n,r,i){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:96;return!!oh(n,r,i)||!(n<t)&&(!!(!e&&n>t&&oh(n,r,i,o))||e)}(o,tk.current,t,n,r,i?96:8);tj.current=s,tk.current=t;let l=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return!(n<=t)&&!oh(e,t,n,r)}(t,n,r);eJ(e=>e===l?e:l),!o&&s&&i?tY("auto"):s||null===tw.current||(cancelAnimationFrame(tw.current),tw.current=null)}},[tY]);(0,i.useEffect)(()=>{if(tB.current=!0,ew.current=ek.current,t){ta.current=t.id;let e=i3(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),W(e.hasMore),w(null),j(!1)),nr(t.id,!e,!0,{force:!0}).then(e=>{e?.running&&(no(t.id),(e.state?.isStreaming||e.state?.isPromptRunning)&&(tp.current=!!e.state.isStreaming,th.current=!!e.state.isPromptRunning,tu.current=!0,F(!0),eq(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),P({type:"resume"}),!e.state.isStreaming&&e.state.isPromptRunning&&nE(t.id)),e.state?.isBashRunning&&(tm.current=!0,D(!0),nN(t.id))),e?.state&&(void 0!==e.state.isCompacting&&eP(e.state.isCompacting),void 0!==e.state.systemPrompt&&eC(e.state.systemPrompt??null),void 0!==e.state.extensionStatuses&&e7(e.state.extensionStatuses??[]),void 0!==e.state.extensionWidgets&&tt(e.state.extensionWidgets??[]),void 0!==e.state.queuedMessages&&tr(ox(e.state.queuedMessages)))})}return()=>{tB.current=!1;let e=x?o:null;e&&queueMicrotask(()=>{tB.current||tM.current||rp(e)});let t=ta.current,n=tH.current;if(t&&n&&n.sessionId===t&&n.snapshotRevision){let e=i3(t),r=tU.current;!e||r.every(t=>e.entryIds.includes(t)||(e.loadedEntryIds??[]).includes(t))?i6({sessionId:t,revision:n.snapshotRevision,messages:t_.current,entryIds:tU.current,leafId:tq.current,oldestEntryId:tZ.current,hasMore:tK.current,summaryTree:n.tree,thinkingLevel:n.context.thinkingLevel,model:n.context.model,stats:n.stats,totalActiveMs:n.totalActiveMs,loadedEntryIds:tU.current}):i9(t)}null!==tw.current&&(cancelAnimationFrame(tw.current),tw.current=null),tg.current+=1,nf(),nm()}},[]),(0,i.useEffect)(()=>{p?.(eS)},[eS,p]),(0,i.useEffect)(()=>(f?.(na),()=>f?.(null)),[na,f]);let n2=O||B||eA;(0,i.useEffect)(()=>{u&&u(v?.tree??[],S,nA,n2)},[v?.tree,S,nA,n2,u]),(0,i.useEffect)(()=>{let e=tE.current;if(e)return tk.current=e.scrollTop,e.addEventListener("scroll",n1,{passive:!0}),()=>{e.removeEventListener("scroll",n1)}},[E.length,y,n1]),(0,i.useEffect)(()=>{O||eK(!1)},[O]),(0,i.useLayoutEffect)(()=>{E.length>0&&(ty.current?(ty.current=!1,tv.current=!0,n0()):tv.current?!tu.current&&tj.current&&tY("auto"):(tv.current=!0,tY("instant")))},[E.length,O,tY,n0]),(0,i.useEffect)(()=>{let e=new AbortController;return(async()=>{for(let t=0;;t++)try{await nF(e.signal);return}catch(n){if(e.signal.aborted||n instanceof DOMException&&"AbortError"===n.name||t>=oy.length||(await oj(oy[t]),e.signal.aborted))return}})(),()=>e.abort()},[nF,c]),(0,i.useEffect)(()=>{if(!eH)return;let e=setTimeout(()=>e_(null),6e3);return()=>clearTimeout(e)},[eH]);let[n4,n8]=(0,i.useState)(null),n5=(0,i.useRef)(5e3),n3=(0,i.useRef)(null),n6=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(0===e0.visible.length){n6.current=null;return}let e=e0.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{e1({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=e0.visible[0];if(!t||(n6.current!==t.id&&(n6.current=t.id,n5.current=5e3),e0.visible.some(e=>e.id===n4)))return;n3.current=Date.now();let n=setTimeout(()=>{e1({type:"mark_oldest_exiting"})},n5.current);return()=>{clearTimeout(n),null!==n3.current&&(n5.current=Math.max(0,n5.current-(Date.now()-n3.current)),n3.current=null)}},[e0.visible,n4]),(0,i.useEffect)(()=>{e4(null)},[E.length,ey?.tokens,ey?.percent,ey?.contextWindow]);let n9=t0??"auto",n7=e8[0]??null,re=Math.max(0,e8.length-1),rt=e3[0]??null,rn=Math.max(0,e3.length-1);return{data:v,loading:y,error:k,activeLeafId:S,messages:E,activeToolResults:$,entryIds:T,historyCursor:R,hasEarlierMessages:z,streamState:A,agentRunning:O,modelNames:U,modelList:Z,modelError:V,modelScopeWarnings:Y,modelThinkingLevels:X,modelThinkingLevelMaps:ee,newSessionModel:en,toolPreset:es,thinkingLevel:n9,retryInfo:ev,contextUsage:ey,systemPrompt:eS,forkingEntryId:eE,isCompacting:eA,compactError:eB,compactResult:eH,currentModel:tG,displayModel:tX,modelSwitching:ez,sessionStats:ne,autoCompactionEnabled:eO,slashCommands:eY,slashCommandsLoading:eX,queuedMessages:tn,notices:e0.visible,extensionDialog:n7,waitingExtensionDialogCount:re,extensionCustomUi:rt,waitingExtensionCustomUiCount:rn,extensionStatuses:e9,extensionWidgets:te,respondToExtensionUi:nv,sendExtensionCustomInput:nb,isAutoModelSelection:x&&null===en,isAutoThinkingSelection:x&&null===ea,defaultModel:ei,savedDefaultThinkingLevel:ep,agentPhase:eU,isNew:x,editEntryId:t5,promptAnchorActive:eZ,showScrollToBottom:eV,sessionIdRef:ta,scrollContainerRef:tE,lastUserMsgRef:tb,pendingScrollToUserRef:ty,initialScrollDoneRef:tv,handleSend:nI,handleAbort:nM,handleFork:nL,handleNavigate:nW,handleModelChange:nP,handleCompact:nO,handleSteer:nq,handleFollowUp:nK,handlePromptWithStreamingBehavior:nZ,handleAbortCompaction:nV,handleRecallQueue:nJ,handleBuiltinSlashCommand:n_,handleEditContent:t9,cancelEdit:t5?t7:void 0,addNotice:ny,setNoticePaused:n8,handleToolPresetChange:nX,handleThinkingLevelChange:nY,handleSetDefaultModel:nH,handleSetDefaultThinkingLevel:nG,loadTools:no,loadSlashCommands:np,setActiveLeafId:C,setData:b,setMessages:N,loadContext:ni,scrollToBottom:tY,scrollUserMsgToTop:n0,scrollToMessage:nQ,dispatch:P,setAgentRunning:F,setForkingEntryId:eN,bashRunning:B,pendingBash:H,handleAgentEventRef:tx}}({session:l,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:f,onAgentEnd:J,onAttentionNeeded:g,onSessionCreated:x,onSessionForked:v,modelsRefreshKey:b,chatInputRef:y,onBranchDataChange:j,onSystemPromptChange:k,onSystemToolsChange:w,onSystemInfoLoaderChange:S,onSessionStatsPanelOpen:N,onOpenSettings:$,deferInitialScroll:!!G}),tW=eu||ep,[tA,tP]=(0,i.useState)(null),[tO,tF]=(0,i.useState)(!1),[tB,tD]=(0,i.useState)(!1),[tH,t_]=(0,i.useState)(null),tU=(0,i.useRef)(null),tq=(0,i.useRef)(null),tZ=(0,i.useCallback)(()=>{tP(null),tF(!1),t_(null)},[]);(0,i.useEffect)(()=>{A||tZ()},[A,tZ]);let tK=(0,i.useCallback)(()=>{if(!A||tO)return;let e=window.getSelection(),t=e?.rangeCount?e.getRangeAt(0):null,n=t0.current;if(!e||e.isCollapsed||!t||!n||!n.contains(t.commonAncestorContainer))return void tP(null);let r=e.toString().trim();if(!r)return void tP(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);tP({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,tO]);(0,i.useEffect)(()=>{tO&&tA&&tq.current?.insertIfEmpty(tC(tA.text,_("chat.quoteIntro"),_("chat.quoteQuestion")))},[tO,tA,_]),(0,i.useLayoutEffect)(()=>{let e=tU.current;if(!e||!tA)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(tA.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(tA.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)}},[tA,tO,tH]),(0,i.useEffect)(()=>{if(!tA)return;let e=e=>{tO||tU.current?.contains(e.target)||tZ()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),tB||tZ())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[tA,tO,tB,tZ]);let tV=(0,i.useCallback)(()=>{tA&&(y?.current?.insertText(tC(tA.text,_("chat.quoteIntro"),_("chat.quoteQuestion"))),window.getSelection()?.removeAllRanges(),tZ())},[y,tA,tZ,_]),tJ=(0,i.useCallback)(async e=>{let t=e0.current??l?.id;if(!tB&&e.trim()&&tA?.sourceEntryId&&t&&W){tD(!0),t_(null),H?.();try{await W(e,t,tA.sourceEntryId),tZ()}catch(t){tq.current?.restoreSubmission(e),t_(t instanceof Error?t.message:String(t))}finally{tD(!1)}}},[W,tA,tB,l?.id,e0,tZ,H]),tY=(0,i.useRef)(!1);(0,i.useEffect)(()=>{et||en||!P||tY.current||(tY.current=!0,O?.(),e5(P))},[P,et,en,e5,O]),(0,i.useEffect)(()=>{let e=!!eA&&!V.current;V.current=!!eA,q&&e&&Z.current()},[q,eA]),(0,i.useEffect)(()=>{s=tW?e3:null},[tW,e3]);let[tG,tX]=(0,i.useState)(50),tQ=(0,i.useRef)(null),t0=(0,i.useRef)(null),t1=(0,i.useRef)(null),t2=(0,i.useRef)(!1),t4=(0,i.useRef)(!1),t8=(0,i.useRef)(G);t8.current=G;let[t5,t3]=(0,i.useState)(null),t6=er[el.indexOf(t5?.entryId??"")],t9=t6?.role==="assistant"?t5?.blockIndex===void 0?t6.content.find(e=>"text"===e.type):t6.content[t5.blockIndex]:void 0,t7=(0,i.useRef)({entryIds:el,historyCursor:ea,hasEarlierMessages:ed});t7.current={entryIds:el,historyCursor:ea,hasEarlierMessages:ed},(0,i.useLayoutEffect)(()=>{let e=l?.id,t=e2.current,n=t0.current;if(e&&u&&t&&n)return()=>{if(t8.current)return;if(oh(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:t7.current.historyCursor})}},[et,u,e2,l?.id]),(0,i.useEffect)(()=>{a&&X(null)},[a]),(0,i.useEffect)(()=>{let e=l?.id;if(!G||!e||et||a||t4.current)return;t4.current=!0;let t=new AbortController;return(async()=>{let n=t7.current;if(n.entryIds.includes(G.anchorEntryId)){tX(e=>Math.max(e,2*n.entryIds.length)),ee(!0);return}t2.current=!0;let r=n.historyCursor,i=n.hasEarlierMessages;try{for(;i&&r&&!t.signal.aborted;){let n=await tM(e,tR,r,{signal:t.signal});if(t.signal.aborted)return;if(!n){tL("instant"),X(null);return}if(tX(e=>e+Math.max(50,2*n.messages.length)),n.entryIds.includes(G.anchorEntryId))return void ee(!0);if(n.oldestEntryId===G.oldestEntryId)break;r=n.oldestEntryId,i=n.hasMore}t.signal.aborted||(tL("instant"),X(null))}finally{t2.current=!1}})(),()=>{t.abort(),X(null)}},[tR,tM,et,G,tL,a,l?.id]),(0,i.useLayoutEffect)(()=>{let e=t0.current;if(!G||!e||a)return;let t=Array.from(e.children).find(e=>e instanceof HTMLElement&&e.dataset.entryId===G.anchorEntryId);if(t instanceof HTMLElement){tz(t,G.anchorOffset),X(null);return}Q&&(tL("instant"),X(null))},[el,G,Q,tL,tz,a,tG]),(0,i.useEffect)(()=>{if(!a||et)return;let e=new AbortController;return(async()=>{let t=t7.current,n=t.entryIds.includes(a.entryId);if(!n&&!tW&&t.hasEarlierMessages&&t.historyCursor&&!t2.current){t2.current=!0;let r=e2.current;r&&(t1.current=r.scrollHeight-r.scrollTop);let i=await tM(a.sessionId,tR,t.historyCursor,{tail:200,signal:e.signal});t2.current=!1,n=!!i?.entryIds.includes(a.entryId)}e.signal.aborted||(n?(t1.current=null,tX(e=>Math.max(e,(t7.current.entryIds.length+200)*2)),t3(a)):d?.(a))})(),()=>e.abort()},[a,et,tR,tW,tM,d,e2]),(0,i.useLayoutEffect)(()=>{if(!t5||t5!==a)return;let e=`[data-entry-id="${CSS.escape(t5.entryId)}"]`,t=e2.current?.querySelector(t6?.role==="user"?e:`${e} [data-search-target]`);t&&(tz(t),t.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500})),t3(null),d?.(t5)},[t5,a,t6,e2,tz,d]),(0,i.useEffect)(()=>{let e=tQ.current,t=e2.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{if(!e[0]?.isIntersecting||t2.current||!ed||!ea)return;let n=l?.id??e0.current;n&&(t2.current=!0,t1.current=t.scrollHeight-t.scrollTop,tM(n,tR,ea).finally(()=>{t2.current=!1}))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[ea,ed,l,tR,tM,e0,e2]),(0,i.useEffect)(()=>{tX(e=>Math.max(e,er.length))},[er.length]),(0,i.useEffect)(()=>{if(null==t1.current)return;let e=e2.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-t1.current),t1.current=null}},[tG,e2]);let ne=eM?[eM.sessionId,eM.sessionFile??"",eM.sessionName??"",eM.userMessages,eM.assistantMessages,eM.toolCalls,eM.toolResults,eM.totalMessages,eM.tokens.input,eM.tokens.output,eM.tokens.cacheRead,eM.tokens.cacheWrite,eM.tokens.total,eM.cost??0,eM.totalActiveMs??0].join("|"):null,nt=(0,i.useRef)(eM);nt.current=eM,(0,i.useEffect)(()=>{C?.(nt.current)},[ne,C]),(0,i.useEffect)(()=>()=>{C?.(null)},[C]);let nn=ew?`${ew.percent??"null"}|${ew.contextWindow}|${ew.tokens??"null"}`:null,nr=(0,i.useRef)(ew);nr.current=ew,(0,i.useEffect)(()=>{I?.(nr.current)},[nn,I]),(0,i.useEffect)(()=>()=>{I?.(null)},[I]);let ni=(0,i.useCallback)(async e=>{let t=l?.cwd??h;if(!t)return void eq({type:"warning",message:_("chat.dropNeedsCwd")});try{var n;let r,{status:i,data:o}=await eo(t,e,"skip");if(200!==i&&207!==i)throw Error(o.error??`HTTP ${i}`);let s=o.uploaded??[],l=o.skipped??[],a=(n=[...s,...l],r=new Set(n),e.filter(e=>r.has(e.name)).map(e=>ei(e.name,!1)).join(""));for(let e of(a&&y?.current?.insertText(a),s.length>0&&(eq({type:"success",message:_("chat.dropUploaded",{count:s.length})}),L?.()),l.length>0&&eq({type:"warning",message:_("chat.dropAlreadyExists",{names:l.join(", ")})}),o.errors??[]))eq({type:"error",message:_("chat.dropFailed",{message:`${e.name}: ${e.error}`})})}catch(e){eq({type:"error",message:_("chat.dropFailed",{message:e instanceof Error?e.message:String(e)})})}},[eq,y,h,L,l?.cwd,_]),{isDragOver:no,handleDragEnter:ns,handleDragOver:nl,handleDragLeave:na,handleDrop:nd}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),o=(0,i.useCallback)(e=>{oC(e)&&(e.preventDefault(),r.current+=1,n(!0))},[]),s=(0,i.useCallback)(e=>{oC(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},[]);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(function(e){let t=[];for(let n of Array.from(e.items)){if("file"!==n.kind)continue;let e=n.webkitGetAsEntry?.();if(e?.isDirectory){t.push({kind:"folder",name:e.name});continue}let r=n.getAsFile();r&&t.push({kind:"file",file:r})}return t.length>0?t:Array.from(e.files).map(e=>({kind:"file",file:e}))}(t.dataTransfer))},[e])}}((0,i.useCallback)(e=>{let{images:t,files:n,folders:r}=function(e){let t=[],n=[],r=[];for(let i of e)"folder"===i.kind?r.push(i.name):i.file.type.startsWith("image/")?t.push(i.file):n.push(i.file);return{images:t,files:n,folders:r}}(e);t.length>0&&y?.current?.addImages(t),r.length>0&&eq({type:"warning",message:_("chat.dropFoldersUnsupported",{names:r.join(", ")})}),n.length>0&&ni(n)},[eq,y,_,ni])),nc=er.filter(e=>tt(e)||"assistant"===e.role),nu=(0,i.useMemo)(()=>{let e=new Map(es);for(let t of er)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[es,er]),np=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=er.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}(er[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[er]),nh=(t=nc.length,(o=(0,i.useRef)([])).current=Array(t).fill(null).map((e,t)=>o.current[t]??null),o),nf=(0,i.useCallback)(()=>{tX(e=>Math.max(e,2*er.length))},[er.length]),nm=eG&&0===er.length&&!ec.isStreaming&&!tW;T(e2,!!l?.id||!nm);let ng=!!ec.streamingMessage?.content.length,nx=l?.cwd??h??void 0,nv=(0,i.useRef)(null),nb=(0,i.useRef)(0),ny=(0,i.useRef)(null),nj=(0,i.useRef)(!1),nk=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=nv.current;if(!eu||!e8){nk.current=null,nb.current=0,nj.current=!1,e&&(e.style.height="");return}let t=e2.current,n=t0.current,r=e4.current;if(!t||!n||!r||!e)return;let i=!1,o=()=>{var o;let s;if(i||e2.current!==t||t0.current!==n||e4.current!==r||nv.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=!nj.current;u&&(nj.current=!0),c!==nb.current&&(nb.current=c,e.style.height=c>0?`${c}px`:"",u&&c>0&&tT())};nk.current=o,o();let s="u"<typeof ResizeObserver?null:new ResizeObserver(()=>{i||null!==ny.current||(ny.current=requestAnimationFrame(()=>{ny.current=null,o()}))});return s?.observe(t),s?.observe(n),s?.observe(r),()=>{i=!0,nk.current===o&&(nk.current=null),s?.disconnect(),null!==ny.current&&(cancelAnimationFrame(ny.current),ny.current=null)}},[eu,e4,er.length,e8,e2,tT]),(0,i.useLayoutEffect)(()=>{nk.current?.()},[ec.streamingMessage]);let nw=eI?ev[`${eI.provider}:${eI.modelId}`]??null:null,nS=eI?eb[`${eI.provider}:${eI.modelId}`]??null:null,nC=(0,r.jsx)(iA,{ref:y,onSend:e5,onAbort:e3,onSteer:eu?ta:void 0,onFollowUp:eu?td:void 0,onPromptWithStreamingBehavior:eu?tc:void 0,isStreaming:tW,model:eI,isAutoModelSelection:eZ,modelNames:ef,modelList:em,modelError:eg,modelScopeWarnings:ex,onModelChange:te,modelSwitching:eT,defaultModel:eV,onSetDefaultModel:tN,onCompact:l||eG?tn:void 0,onAbortCompaction:tp,isCompacting:eC,compactError:eE,compactResult:eN,toolPreset:ey,onToolPresetChange:l||eG?tj:void 0,thinkingLevel:ej,isAutoThinkingSelection:eK,onThinkingLevelChange:l||eG?tE:void 0,availableThinkingLevels:nw,thinkingLevelMap:nS,savedDefaultThinkingLevel:eJ,onSetDefaultThinkingLevel:l||eG?t$:void 0,retryInfo:ek,queuedMessages:ez,inputHistory:np,onRecallQueue:th,slashCommands:eR,slashCommandsLoading:eL,onLoadSlashCommands:tI,onBuiltinCommand:tf,soundEnabled:F,onSoundToggle:B,onAudioUnlock:H,draftKey:l?.id??f??void 0,cwd:l?.cwd??h});return et?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:_("chat.loadingSession")}):en?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:en}):(0,r.jsxs)("div",{className:"chat-content relative flex h-full min-w-0 flex-col overflow-hidden",style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:ns,onDragOver:nl,onDragLeave:na,onDrop:nd,children:[no&&(0,r.jsxs)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center bg-[rgba(37,99,235,0.06)] backdrop-blur-[1px]",children:[(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:[0,.8,1.6].map(e=>(0,r.jsx)("div",{className:"absolute h-[720px] w-[720px] rounded-full border-[1.5px] border-solid border-[rgba(37,99,235,0.5)] animate-[drop-ripple_2.4s_ease-out_infinite_backwards]",style:{transformOrigin:"center",animationDelay:`${e}s`}},e))}),(0,r.jsxs)("svg",{width:"280",height:"280",viewBox:"0 0 140 140",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"drop-shadow-[0_6px_18px_rgba(37,99,235,0.18)]",children:[(0,r.jsx)("rect",{x:"28",y:"44",width:"84",height:"60",rx:"8",fill:"rgba(37,99,235,0.08)",stroke:"rgba(37,99,235,0.50)",strokeWidth:"1.8"}),(0,r.jsx)("path",{d:"M36 100 L54 72 L68 88 L80 74 L104 100Z",fill:"rgba(37,99,235,0.16)",stroke:"rgba(37,99,235,0.40)",strokeWidth:"1.4",strokeLinejoin:"round"}),(0,r.jsx)("circle",{cx:"96",cy:"58",r:"8",fill:"rgba(37,99,235,0.22)",stroke:"rgba(37,99,235,0.55)",strokeWidth:"1.6"}),(0,r.jsxs)("g",{stroke:"rgba(37,99,235,0.45)",strokeWidth:"1.4",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"96",y1:"46",x2:"96",y2:"43"}),(0,r.jsx)("line",{x1:"96",y1:"70",x2:"96",y2:"73"}),(0,r.jsx)("line",{x1:"84",y1:"58",x2:"81",y2:"58"}),(0,r.jsx)("line",{x1:"108",y1:"58",x2:"111",y2:"58"}),(0,r.jsx)("line",{x1:"87.5",y1:"49.5",x2:"85.4",y2:"47.4"}),(0,r.jsx)("line",{x1:"104.5",y1:"66.5",x2:"106.6",y2:"68.6"}),(0,r.jsx)("line",{x1:"104.5",y1:"49.5",x2:"106.6",y2:"47.4"}),(0,r.jsx)("line",{x1:"87.5",y1:"66.5",x2:"85.4",y2:"68.6"})]})]})]}),(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:36*!U,zIndex:40,display:"flex",justifyContent:"flex-end",padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)(oT,{notices:eW,floating:!0,onPauseChange:eU})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[eA&&(0,r.jsx)(oL,{request:eA,waitingCount:eP,onRespond:eH},eA.id),eO&&(0,r.jsx)(oz,{request:eO,waitingCount:eF,onInput:e_},eO.id),!nm&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:e2,className:"scrollbar-subtle min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-gutter:stable]",style:{visibility:G?"hidden":void 0},children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{ref:t0,onPointerUp:tK,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=er.length-1;e>=0;e--)if("user"===er[e].role){i=e;break}let o=-1;for(let e=er.length-1;e>=0;e--)if(tt(er[e])){o=e;break}let s=new Map,a=0;er.forEach((e,t)=>{(tt(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??er[e],o=tt(n)||"assistant"===n.role,a=s.get(e),d=t.keyPrefix??"message",c=el[e]??e,u=!1;if("assistant"===n.role){u=!0;for(let t=e+1;t<er.length;t++){let e=er[t].role;if("user"===e)break;if("assistant"===e){u=!1;break}}u&&ec.isStreaming&&e===er.length-1&&(u=!1)}void 0!==t.showTimestamp&&(u=t.showTimestamp);let p=(0,r.jsx)(nq,{message:n,toolResults:nu,modelNames:ef,cwd:nx,onOpenFile:R,onOpenSession:z,entryId:el[e],searchBlock:el[e]===t5?.entryId?t9:void 0,onFork:ep||eG?void 0:e6,forking:eS===el[e],onEditContent:tW?void 0:e9,onCancelEdit:e7,isEditing:eX===el[e],showTimestamp:u,prevTimestamp:e>0?er[e-1].timestamp:void 0,sessionId:l?.id??e0.current??void 0,writtenFiles:t.writtenFiles,onCompact:t.recoverTruncation?tn:void 0,isCompacting:t.recoverTruncation?eC:void 0,compactError:t.recoverTruncation?eE:void 0},`${d}-view-${c}`);return o&&void 0!==a?(0,r.jsx)("div",{"data-entry-id":el[e],ref:!1===t.attachRef?void 0:t=>{nh.current[a]=t,e===i&&(e4.current=t)},children:p},`${d}-${c}`):p},c=[];for(let e=0;e<er.length;){let t,n=tt(er[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<er.length&&!tt(er[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&&tl(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}(er,i,a);if(-1===u||(tW||ec.isStreaming)&&a===er.length&&i===o){for(let e=l;e<a;e++)c.push(d(e));e=a;continue}n&&c.push(d(i));let p=er[u],h=tl(p),f=h.answerBlocks.length>0||ti(p)||to(p)?oN(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=er[e];if("custom"===n.role){b||=!!(t5&&t5.entryId===el[e]),x.push(d(e,{attachRef:!1,keyPrefix:"process"}));continue}if("assistant"!==n.role)continue;let r=e===u?oN(n,g,{omitUsage:!!f}):n,i=tr(r);0!==i.length&&(t??=s.get(e),v+=i.filter(e=>"toolCall"===e.type).length,b||=!!(t5&&el[e]===t5.entryId&&(!t9||i.includes(t9))),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=>{nh.current[t]=e},children:(0,r.jsx)(o$,{messageCount:x.length,toolCallCount:v,defaultExpanded:!f,reveal:b,t:_,children:x},f?"answered":"unanswered")},`process-group-${el[l]??l}`)),f){let e=[];for(let t=i+1;t<=u;t++){let n=er[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 s of e){var o;if("toolCall"!==s.type||!(tm(o=s.toolName)||tg(o))&&!tx(s.toolName))continue;let e=t?.get(s.toolCallId);if(e&&!e.isError)for(let t of tx(s.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 tv(e).matchAll(/^\*\*\* Delete File: (.+)$/gm)){let e=(t[1]??"").trim();e&&n.add(e)}return n}(e,n),i=function(e){if(!tb(e)||!tb(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(ty(n))return[];if(n&&"object"==typeof n&&!Array.isArray(n)){let e=tS(tw(n.preview));if(e.length>0)return e}return tS(tk(tv(e)))}(s.input,e):[function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(s.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 tu(n)}(t,n);e&&(r.has(e)||(r.add(e),i.push({filePath:e})))}}return i}(e,nu,nx);c.push(d(u,{messageOverride:f,writtenFiles:t,recoverTruncation:a===er.length&&!ec.isStreaming&&!ts(f)}))}for(let e=u+1;e<a;e++)c.push(d(e));e=a}let{startIndex:u}=(t=Math.min(Math.max(tG,0),Math.max(e=c.length,0)),{startIndex:n=Math.max(0,e-t),hasMore:n>0}),p=u>0||ed;return(0,r.jsxs)(r.Fragment,{children:[p&&(0,r.jsx)("div",{ref:tQ,className:"py-3 text-center text-xs text-text-muted",children:_("chat.loadEarlier")}),c.slice(u)]})})(),ec.isStreaming&&ng&&ec.streamingMessage&&(0,r.jsx)(nq,{message:ec.streamingMessage,toolResults:nu,isStreaming:!0,modelNames:ef,cwd:nx,onOpenFile:R,onOpenSession:z}),eu&&!ng&&(eY||eC)&&(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}(eY,_,eC)})}),ep&&!eh&&(0,r.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:_("chat.runningCommand")})}),eh&&(0,r.jsx)(nq,{message:{role:"bashExecution",command:eh.command,output:"",excludeFromContext:eh.excludeFromContext},sessionId:l?.id??e0.current??void 0,onOpenSession:z}),(0,r.jsx)("div",{ref:nv,"aria-hidden":"true"})]})})}),U||G?null:(0,r.jsx)(iU,{messages:er,streamingMessage:ec.streamingMessage,scrollContainer:e2,messageRefs:nh,onRevealHistory:nf})]})]}),A&&tA&&(0,M.createPortal)((0,r.jsx)("div",{ref:tU,role:tO?"dialog":"toolbar","aria-label":_(tO?"chat.newQuoteChat":"chat.askSelection"),style:{position:"fixed",top:tA.top,left:tA.left,zIndex:260,display:"flex",flexWrap:"wrap",gap:3,width:tO?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:tO?12:3,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",boxShadow:"0 2px 10px rgba(0,0,0,0.12)"},children:tO?(0,r.jsxs)("fieldset",{disabled:tB,"aria-busy":tB,style:{width:"100%",minWidth:0,margin:0,padding:0,border:"none",display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,fontSize:12,fontWeight:600},children:_("chat.askInNewChat")}),(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button",title:_("i18n.close"),"aria-label":_("i18n.close"),disabled:tB,onClick:tZ,style:{border:"none"},children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 6 12 12M18 6 6 18"})})})]}),(0,r.jsx)(iA,{ref:tq,compact:!0,onSend:tJ,onAbort:tZ,isStreaming:!1}),tH&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:tH})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:_("chat.askInCurrent"),"aria-label":_("chat.askInCurrent"),onPointerDown:e=>e.preventDefault(),onClick:tV,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:_("chat.askInCurrent")})]}),W&&tA.sourceEntryId&&!ep&&(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:_("chat.askInNewChat"),"aria-label":_("chat.askInNewChat"),onPointerDown:e=>e.preventDefault(),onClick:()=>{tF(!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:_("chat.askInNewChat")})]})]})}),document.body),(0,r.jsxs)("div",{className:"relative shrink-0",children:[!nm&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"100%",left:0,right:36*!U,display:"flex",justifyContent:"center",paddingBottom:10,pointerEvents:"none",zIndex:20},children:(0,r.jsx)("button",{type:"button",className:`chat-scroll-to-bottom${eQ&&!G?" is-visible":""}`,title:_("chat.scrollToLatest"),"aria-label":_("chat.scrollToLatest"),onClick:()=>tL("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"})})})}),nm&&(0,r.jsx)("div",{className:"mb-3 w-full",style:{paddingLeft:16,paddingRight:U?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:U?7:10,minWidth:0,flex:1,lineHeight:1.4,overflow:"hidden"},children:[(0,r.jsx)(e1.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)(oE,{label:e=>_("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.2"]})]}),(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"]})]})]})]})}),nC,(0,r.jsx)(iJ,{statuses:eB,widgets:eD,onCommand:e5,commandsDisabled:tW})]}),nm&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}function oT(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 oM(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 oR(e){let{expanded:t}=e;return(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:1.6,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:t?(0,r.jsx)("path",{d:"M3.5 1v2.5H1M6.5 1v2.5H9M6.5 9v-2.5H9M3.5 9v-2.5H1"}):(0,r.jsx)("path",{d:"M1 3.5V1h2.5M6.5 1H9v2.5M9 6.5V9H6.5M3.5 9H1V6.5"})})}function oL(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=(0,i.useRef)(null),p=(0,i.useRef)(null),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(!1),x=(0,i.useCallback)(()=>g(e=>!e),[]),[v,b]=(0,i.useState)(()=>Date.now()),y=(0,i.useCallback)(e=>e?.focus(),[]),j=function(e){if("select"===e.method&&e.options.length>0)return e.options[0];if("confirm"===e.method){let t=e.message.split("\n").find(e=>e.trim());return t?.trim()}}(t),k=void 0===t.expiresAt?null:Math.max(0,Math.ceil((t.expiresAt-v)/1e3));(0,i.useLayoutEffect)(()=>{if(d)return;let e=u.current,t=p.current;if(!e||!t)return;let n=!1,r=()=>{if(n)return;let r=t.querySelectorAll("pre, .markdown-table-wrap");if(0===r.length)return;let i=function(e,t){let n=0;for(let e of t)e>1&&e>n&&(n=e);return 0===n?null:40*Math.ceil((e+n)/40)}(e.offsetWidth,Array.from(r,e=>e.scrollWidth-e.clientWidth));null!==i&&f(e=>null!==e&&e>=i?e:i)};r();let i=new MutationObserver(r);return i.observe(t,{childList:!0,subtree:!0,characterData:!0}),document.fonts?.ready.then(r),()=>{n=!0,i.disconnect()}},[d]),(0,i.useEffect)(()=>{if(void 0===t.expiresAt)return;let e=setInterval(()=>b(Date.now()),1e3);return()=>clearInterval(e)},[t.expiresAt]);let w=null!==k&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:s("chat.extensionExpiresIn",{seconds:k})}),S=()=>{"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}),j&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:j}),(0,r.jsx)(oM,{count:n}),w,(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:s("chat.extensionExpand")})]}):(0,r.jsxs)("div",{ref:u,role:"dialog","aria-label":t.title,style:{pointerEvents:"auto",width:m?"100%":`min(${h??560}px, 100%)`,maxHeight:m?"100%":"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{flexShrink:1,minHeight:0,display:"flex",alignItems:"flex-start",gap:8,padding:"12px 14px",borderBottom:"1px solid var(--border)",maxHeight:"50vh",overflowY:"auto"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:650,lineHeight:1.45,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:t.title}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:8,marginTop:3,color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{children:s("chat.extensionRequest")}),(0,r.jsx)(oM,{count:n}),w]})]}),(0,r.jsx)("button",{type:"button",onClick:x,title:s(m?"chat.extensionRestoreSize":"chat.extensionMaximize"),"aria-label":s(m?"chat.extensionRestoreSize":"chat.extensionMaximize"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)(oR,{expanded:m})}),(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",{ref:p,style:{padding:14,flex:"1 1 auto",minHeight:0,overflowY:"auto"},children:["confirm"===t.method&&(0,r.jsx)(nb,{children:t.message}),"select"===t.method&&(0,r.jsx)("div",{onKeyDown:e=>{if(!["ArrowDown","ArrowRight","ArrowUp","ArrowLeft","Home","End"].includes(e.key))return;let t=Array.from(e.currentTarget.querySelectorAll("[data-extension-option]")),n=t.indexOf(e.target);if(n<0)return;e.preventDefault();let r="Home"===e.key?0:"End"===e.key?t.length-1:(n+("ArrowDown"===e.key||"ArrowRight"===e.key?1:-1)+t.length)%t.length;t[r].focus({preventScroll:!0}),t[r].scrollIntoView({block:"nearest"})},style:{display:"grid",gap:8},children:t.options.map((e,n)=>(0,r.jsx)("div",{role:"button",tabIndex:0,"data-extension-option":!0,"aria-label":e,ref:0===n?y:void 0,onClick:()=>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)(nb,{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||S()},style:{width:"100%",padding:"9px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",fontSize:13}}),"editor"===t.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:l,onChange:e=>a(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&!e.nativeEvent.isComposing&&S()},style:{width:"100%",minHeight:220,padding:10,borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:13,lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 14px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("button",{autoFocus:"confirm"===t.method||"select"===t.method&&0===t.options.length,onClick:()=>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:S,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:S,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 oz(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(e8,""),i=e5(e).trimEnd();if(t.test(i))continue;let o=e,s=e9(o);("│"===s||"┃"===s)&&" "===e9(o=e6(o,0))&&(o=e6(o,0));let l=function(e){let t=e3(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(o),a=l>=0?e3(o)[l]?.char:void 0;("│"===a||"┃"===a)&&(o=e6(o,l)),n.push(function(e){let t=e;for(;;){let e=e3(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&&""===e5(n[0]).trim();)n.shift();for(;n.length>0&&""===e5(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)(oM,{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:"max-content",minWidth:"min(920px, 100%)",maxWidth:"100%",maxHeight:"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:l,"aria-label":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=te[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":" ":e7[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)(oM,{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)(iZ,{text:u.join("\n")})})]})})}var oW=n(50640);let oA={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"},oP={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"},oO={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",mov:"video/quicktime",ogv:"video/ogg"};function oF(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}var oB=n(73620);let oD=/^(?:\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 o_=["tags","categories","keywords","tag","category"];function oU(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=o_.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 oq={source:"Source",preview:"Preview",diff:"Diff"},oZ={fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:13,lineHeight:1.6},oK={width:48,minWidth:48,padding:"0 10px",textAlign:"right",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:11,fontStyle:"normal",fontVariantNumeric:"tabular-nums",lineHeight:"20.8px",userSelect:"none",flexShrink:0,verticalAlign:"top"};function oV(){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 oJ(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function oY(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=oJ(n.startContainer),i=oJ(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 oG(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,oW.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,oW.Ay)({node:e,stylesheet:n,useInlineStyles:i,key:`source-token-${t}-${r}`}))})]},`source-line-${t}`)})}function oX(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 oQ(e){let{filePath:t,sourceSessionId:n}=e,{t:i}=(0,E.s)();return(0,r.jsx)("a",{href:oX(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 o0(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function o1(e){let t,{patch:n}=e,{t:i}=(0,E.s)(),o=(t=nw(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%",...oZ},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:oK,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 o2(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(oX(t,"watch",o));v.current=n,n.addEventListener("connected",()=>{let n;d(!0),n=++b.current,fetch(oX(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=oX(t,"read",o,c?{v:c}:void 0),k=null!=p?o0(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)(oQ,{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 o4(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 o8(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(oX(t,"watch",o));v.current=n,n.addEventListener("connected",()=>{let n;d(!0),n=++b.current,fetch(oX(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=oX(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:o4(f)}),null!=p&&(0,r.jsx)("span",{children:o0(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)(oQ,{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 o5(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(oX(t,"watch",o));v.current=n,n.addEventListener("connected",()=>{let n;d(!0),n=++b.current,fetch(oX(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=oX(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:o4(f)}),null!=p&&(0,r.jsx)("span",{children:o0(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)(oQ,{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 o3(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=oF(t),y="pdf"===b,j=y&&s&&s>0?`#page=${s}`:"",k=y?`${oX(t,"read",o,u?{v:u}:void 0)}${j}`:oX(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(oX(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(oX(t,"watch",o));x.current=n,n.addEventListener("connected",()=>{let n;c(!0),n=++v.current,fetch(oX(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:o0(h)}),(0,r.jsx)(oQ,{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 o6(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!==(oA[oF(n)]??null)?(0,r.jsx)(o2,{filePath:n,cwd:i,sourceSessionId:o,watchEnabled:f}):null!==(oP[oF(n)]??null)?(0,r.jsx)(o8,{filePath:n,cwd:i,sourceSessionId:o,watchEnabled:f}):null!==(oO[oF(n)]??null)?(0,r.jsx)(o5,{filePath:n,cwd:i,sourceSessionId:o,watchEnabled:f}):null!==("pdf"===(t=oF(n))||"docx"===t?t:null)?(0,r.jsx)(o3,{filePath:n,cwd:i,sourceSessionId:o,initialPage:p,watchEnabled:f}):(0,r.jsx)(o9,{filePath:n,cwd:i,sourceSessionId:o,onOpenFile:s,onMentionLines:l,onAtMention:a,gitRefreshKey:d,initialDisplayMode:c,initialState:u,onStateChange:h,watchEnabled:f})}function o9(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}=nu(),{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,$]=(0,i.useState)(!1),[I,T]=(0,i.useState)(null),M=u?.displayMode??c??"source",R=u?.wrapLines??!1,L=u?.scrollTop??0,z=u?.scrollLeft??0,[W,A]=(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,A(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,A(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(oX(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(oX(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"===W&&ee("source")},[W,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"?tF(g.content):"",[g]),el=(0,i.useMemo)(()=>g?.language==="markdown"?function(e){let t=function(e){let t=oD.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,oB.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":W,em=ed.length>1e3&&!("diff"===ef&&ei)&&!("preview"===ef&&eh),eg=(0,i.useMemo)(()=>(0,r.jsx)(t4.A,{className:P?"file-source-view is-wrapped":"file-source-view",language:"text"===ec?"plaintext":ec,style:f?t8.xJ:t8.vs,showLineNumbers:!0,lineNumberStyle:{...oK},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...oZ,width:P?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",overflowWrap:P?"anywhere":"normal"}},renderer:e=>(0,r.jsx)(oG,{...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:oK,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"===W&&e?oY(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"===W)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[g?.content,W,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"!==W)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?oY(n,window.getSelection()):null;r&&(e.preventDefault(),ev(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[W,ev,l]),(0,i.useEffect)(()=>{if(!K.current||S||I&&!eo||"diff"===M&&!k||"diff"===M&&ei&&"diff"!==W)return;let e=U.current;e&&(e.scrollTop=V.current.scrollTop,e.scrollLeft=V.current.scrollLeft,K.current=!1)},[g?.content,W,I,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(I&&!eo)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:I});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 ${o0(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:oq[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)(oV,{})}),"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)(oQ,{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:[o0(g.nextOffset)," / ",o0(g.size)]}),(0,r.jsx)("button",{type:"button",className:"file-viewer-mode-button",disabled:N,onClick:()=>{$(!0),en(t,g.nextOffset).finally(()=>$(!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)(o1,{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)(oU,{data:el.data}),(0,r.jsx)(tE.oz,{remarkPlugins:tQ,rehypePlugins:t1,urlTransform:s?tA: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)(nh,{code:s.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(ng,{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?tp(t,eb,n??eb):null;return l&&s?(0,r.jsx)("a",{href:t,...o,onClick:e=>{ta(e)&&(e.preventDefault(),s(l,tf(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?tp(t,eb,n??eb):null,a=l?oX(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)",...oZ},children:ex}):eg})]})}function o7(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 se(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 st=["general","models","archives","skills","agents","plugins","mcp"],sn="pi-web:settings-navigation",sr=new Set(["skills","agents","plugins"]);function si(e){return sr.has(e)}function so(){try{return window.localStorage}catch{return null}}function ss(e){let t=e.getItem(sn);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 sl(e,t){return"models"===e?e:t?JSON.stringify([e,t]):"mcp"===e?e:null}function sa(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:so();if(t)try{let n=ss(t);n.section=e,t.setItem(sn,JSON.stringify(n))}catch{}}function sd(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:so();if(!n)return null;let r=sl(e,t);if(!r)return null;try{let e=ss(n).selections?.[r];return"string"==typeof e&&e.length>0?e:null}catch{return null}}function sc(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:so();if(!r||!t)return;let i=sl(e,n);if(i)try{let e=ss(r);e.selections={...e.selections,[i]:t},r.setItem(sn,JSON.stringify(e))}catch{}}function su(e){return e.isComposing||229===e.keyCode}function sp(e,t){let n=e.activeElement;return!!t&&(!n||n===e.body)&&(t.focus({preventScroll:!0}),!0)}let sh=["input","output","cacheRead","cacheWrite"];function sf(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 sm(e){if(!sg(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 sg(e){return sh.some(t=>""!==e[t].trim())}function sx(e){return new Map(Object.entries(e.providers??{}).map(e=>{let[t,n]=e;return[t,(n.models??[]).map(e=>e.id)]}))}function sv(e,t,n){if(n<=0)return;let r=e.get(t)??[];e.set(t,[...r,...Array.from({length:n},()=>null)])}function sb(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 sy(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-split-view",children:t})}function sj(e){let{children:t}=e;return(0,r.jsx)("aside",{className:"config-sidebar",children:t})}function sk(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-sidebar-list",children:t})}function sw(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 sS(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)(sJ,{checked:i??(n>0&&t===n),disabled:s,loading:l,label:o,describedBy:a,onChange:d})]})}function sC(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 sE(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 sN(e){let{className:t,...n}=e;return(0,r.jsx)("span",{...n,className:["config-sidebar-text",t].filter(Boolean).join(" ")})}function s$(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-stack",t].filter(Boolean).join(" ")})}function sI(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 sM(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 sL(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-section-title",children:t})}function sz(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 sW(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-grid",children:t})}function sA(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 sP(e){let{scope:t,children:n}=e;return(0,r.jsx)("span",{className:`config-scope-tag${"project"===t?" is-project":""}`,children:n})}function sO(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 sF(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)(sO,{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 sB(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 sD(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)(s$,{className:"is-fill",children:[(0,r.jsx)(sB,{title:t,catalogs:n,target:o}),(0,r.jsx)(sz,{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 s_(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)(sV,{size:"small",onClick:s,disabled:o,children:i}):void 0,children:n})}function sU(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-empty-state",children:t})}function sq(e){let{children:t,style:n}=e;return(0,r.jsx)("div",{className:"config-detail",style:n,children:t})}function sZ(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 sK(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 sV(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 sJ(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 sY(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 sG(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 sX(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 sQ(e,t){let n=sX(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 s0(e,t){return t.enabled&&(e?.enabledTotal??0)<=1}function s1(e,t){return e?.providers.find(e=>e.id===t)}let s2={"last-model":"models.enabledLastModel","project-scope":"models.enabledProjectScope"};function s4(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)(sV,{size:"small",onClick:t.pruneStale,disabled:null!==o,title:n("models.enabledPruneHint"),children:n("models.enabledPrune")}),i.editable&&s&&(0,r.jsx)(sV,{size:"small",onClick:t.clearScope,disabled:null!==o,title:n("models.enabledClearHint"),children:n("models.enabledClear")})]}):null}function s8(e){let{providerId:t,controller:n,noteId:i}=e,{t:o}=(0,E.s)(),{view:s,loading:l,pending:a,failure:d}=n,c=s1(s,t),u=d?d.messageKey?o(d.messageKey):d.message:null,p=s5(n,t)?i:void 0;if(l&&!s)return null;if(!c)return(0,r.jsx)(sJ,{checked:!1,disabled:!0,label:o("models.enabledProviderToggle",{provider:t}),describedBy:p,onChange:()=>{}});let h=sQ(s,c);return(0,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("span",{className:"enabled-models-switch-error",children:u}),(0,r.jsx)(sJ,{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 s5(e,t){let{view:n,loading:r}=e;if(r&&!n)return null;let i=s1(n,t);if(!i)return"models.enabledCustomEmpty";let{reason:o}=sQ(n,i);return o?s2[o]:null}function s3(e){let{providerId:t,controller:n,id:i}=e,{t:o}=(0,E.s)(),s=s5(n,t);return s?(0,r.jsx)("div",{id:i,className:"config-detail-heading-note",children:o(s)}):null}function s6(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=s1(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=sX(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=>s0(c,e)),$=(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)(sV,{size:"small",disabled:y||!v.canEnable,"aria-describedby":k?void 0:w,onClick:()=>$(!0,v.enableRefs),children:b?l("models.enableShown"):l("models.enableAll")}),(0,r.jsx)(sV,{size:"small",disabled:y||!v.canDisable,"aria-describedby":k?C?S:void 0:w,onClick:()=>$(!1,v.disableRefs),children:b?l("models.disableShown"):l("models.disableAll")}),(0,r.jsx)(sV,{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=s0(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)(sJ,{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 s9(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 s7={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 le(e){let{id:t,size:n}=e,i=s7[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 lt=["openai-codex","deepseek","openrouter","moonshotai","moonshotai-cn","minimax","minimax-cn","vercel-ai-gateway","opencode-go"],ln="pi-web:provider-usage:";function lr(e){let{providerId:t,enabled:n}=e;return lt.includes(t)?(0,r.jsx)(li,{providerId:t,enabled:n}):null}function li(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(`${ln}${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(`${ln}${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(`${ln}${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 ":"$"}${lo(e.remaining??e.limit)}`:void 0!==e.remaining&&void 0!==e.limit?`${lo(e.remaining)} / ${lo(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 lo(e){return void 0===e?"-":Number.isInteger(e)?String(e):e.toFixed(2)}function ls(){let e=sd("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 ll=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function la(e){let{label:t,children:n}=e;return(0,r.jsx)(sz,{label:t,children:n})}let ld={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 lc(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:{...ld,fontFamily:o?"var(--font-mono)":"inherit"}})}function lu(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:{...ld,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 lp(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:ld})}function lh(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:{...ld,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 lf(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 lm(e){let{children:t}=e;return(0,r.jsx)(sL,{children:t})}function lg(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)(()=>{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(),$=C.filter(e=>!N||e.id.toLocaleLowerCase().includes(N)||e.name?.toLocaleLowerCase().includes(N)),I=$.slice(0,300),T=I.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)(sI,{children:[(0,r.jsx)(sT,{children:(0,r.jsx)(lm,{children:p("i18n.provider")})}),(0,r.jsxs)(sM,{children:[(0,r.jsx)(s8,{providerId:t,controller:u,noteId:j}),(0,r.jsx)(sV,{variant:"danger",size:"small",onClick:d,children:p("i18n.delete")})]})]}),(0,r.jsx)(s3,{providerId:t,controller:u,id:j})]}),(0,r.jsxs)(la,{label:p("i18n.providerName"),children:[(0,r.jsx)(lc,{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)(la,{label:"Base URL",children:[(0,r.jsx)(lc,{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)(la,{label:"API Key",children:[(0,r.jsx)(lu,{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)(la,{label:"API",children:(0,r.jsx)(lh,{value:o.api??"",onChange:e=>k("api",e||void 0),options:ll})}),(0,r.jsxs)(la,{label:"Headers",children:[(0,r.jsx)(lk,{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:{...ld,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===I.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:p("models.discoveryNoMatches")}):I.map((e,t)=>{let n=S.has(e.id),i=x.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:i||n,disabled:n,onChange:()=>{var t;return t=e.id,void v(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),n&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:p("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:h.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:$.length>I.length?p("models.discoveryShowing",{shown:I.length,total:$.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 lx=["off","minimal","low","medium","high","xhigh","max"],lv={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function lb(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:lx.map(e=>{let t=i[e],n=e in i?null===t?"null":"string":"omit",s="string"==typeof t?t:"",l=lv[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 ly={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function lj(e){return e.compat?.thinkingFormat==="deepseek"}function lk(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:{...ld,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:{...ld,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 lw(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)(()=>sf(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=sm(sf(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]),$=(()=>{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}`})(),I="error"===u.phase?u.message:$,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;lj(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),W=z.length?z.join(" \xb7 "):c("models.providerDefaults");return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(sI,{children:[(0,r.jsx)(sT,{children:(0,r.jsx)(lm,{children:c("i18n.model")})}),(0,r.jsxs)(sM,{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)(sV,{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)(sV,{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)(la,{label:"ID *",children:(0,r.jsx)(lc,{value:o.id,onChange:e=>w("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(la,{label:"Name",children:(0,r.jsx)(lc,{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")})]}),I&&(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:I,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:I}),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)(lm,{children:c("models.capabilities")}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginTop:8},children:[(0,r.jsx)(lf,{label:c("models.reasoning"),checked:o.reasoning??!1,onChange:e=>w("reasoning",e||void 0)}),(0,r.jsx)(lf,{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)(lm,{children:c("models.modelSpecs")}),(0,r.jsx)("button",{type:"button",onClick:()=>{if(h)return void f(!1);k.current=o.cost;let e=sf(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)(la,{label:c("models.contextWindow"),children:(0,r.jsx)(lp,{value:void 0!==o.contextWindow?String(o.contextWindow):"",onChange:e=>w("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(la,{label:c("models.maxOutputTokens"),children:(0,r.jsx)(lp,{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)(la,{label:n,children:(0,r.jsx)(lp,{value:m[t],onChange:e=>{let n,r,i;return r=sm(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)}),sg(m)&&!sm(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:W})]}),(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{color:"var(--text-dim)",transform: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)(la,{label:c("models.apiOverride"),children:(0,r.jsx)(lh,{value:o.api??"",onChange:e=>w("api",e||void 0),options:ll})}),(0,r.jsxs)(la,{label:c("models.headers"),children:[(0,r.jsx)(lk,{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)(lm,{children:c("models.compatibility")}),(0,r.jsx)(lf,{label:c("models.deepSeekThinkingCompat"),checked:lj(o),onChange:e=>s(function(e,t){if(t)return{...e,compat:{...e.compat??{},...ly}};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)(lf,{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)(lm,{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)(lb,{value:o.thinkingLevelMap,onChange:e=>w("thinkingLevelMap",e)})]})]})]})]})]})}function lS(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)(sI,{children:[(0,r.jsx)(sT,{children:(0,r.jsx)(lm,{children:a("i18n.subscription")})}),(0,r.jsxs)(sM,{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)(sV,{size:"small",onClick:()=>{u.current?.close(),l({phase:"idle"})},children:a("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(sV,{variant:"primary",size:"small",onClick:h,children:a(t.loggedIn?"i18n.relogin":"i18n.login")}),t.loggedIn&&(0,r.jsx)(sV,{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)(s9,{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)(lr,{providerId:t.id,enabled:t.loggedIn}),t.loggedIn&&(0,r.jsx)(s6,{providerId:t.id,controller:o})]})}function lC(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)(sI,{children:[(0,r.jsx)(sT,{children:(0,r.jsx)(lm,{children:"API Key"})}),(0,r.jsxs)(sM,{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)(sV,{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)(lu,{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)(lr,{providerId:t.id,enabled:t.configured}),t.configured&&(0,r.jsx)(s6,{providerId:t.id,controller:o})]})}function lE(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)(le,{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)(le,{id:e.id,size:28})]},e.id))]})})]})})}function lN(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?s2[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)(ls),[k,w]=(0,i.useState)([]),[S,C]=(0,i.useState)([]),[N,$]=(0,i.useState)(!1),I=(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),I.current=new Set(Object.keys(t.providers??{})),M.current=sx(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&&sc("models",JSON.stringify(y))},[y]);let W=(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]),A=(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:I.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=>{sv(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));sv(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);I.current=new Set(Object.keys(e.providers??{})),M.current=sx(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=s1(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)(lS,{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)(lC,{provider:e,onRefresh:z,enabledModels:l},e.id):null}if("provider"===y.type){let e=a.providers?.[y.name];return e?(0,r.jsx)(lg,{name:y.name,editingName:R?.provider===y.name?R.name:y.name,provider:e,onChange:e=>A(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)(lw,{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)(sb,{embedded:n,title:s("common.models"),subtitle:"~/.pi/agent/models.json",closeLabel:s("i18n.close"),onClose:t,children:[(0,r.jsx)(s4,{controller:l}),(0,r.jsxs)(sy,{children:[(0,r.jsxs)(sj,{children:[(0,r.jsxs)(sk,{children:[K.map(e=>{let t=y?.type==="oauth"&&y.providerId===e.id;return(0,r.jsxs)(sE,{active:t,onClick:()=>j({type:"oauth",providerId:e.id}),children:[(0,r.jsx)(le,{id:e.id,size:16}),(0,r.jsx)(sN,{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)(sE,{active:t,onClick:()=>j({type:"apikey",providerId:e.id}),children:[(0,r.jsx)(le,{id:e.id,size:16}),(0,r.jsx)(sN,{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)(sE,{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)(sN,{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)(sE,{active:i,className:"models-sidebar-indented-item",onClick:()=>j({type:"model",providerName:t,index:n}),children:[(0,r.jsx)(sN,{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)(sE,{className:"models-sidebar-indented-item models-sidebar-add-item",onClick:e=>{e.stopPropagation(),B(t)},children:(0,r.jsxs)(sN,{children:["+ ",s("i18n.model")]})})]},t)})]}),(0,r.jsx)(sY,{onClick:()=>$(!0),children:s("i18n.addProvider")})]}),(0,r.jsx)(sq,{children:(0,r.jsx)(s$,{className:"is-fill",children:c?null:J??(0,r.jsx)(sU,{children:s("i18n.selectProviderModel")})})})]}),(0,r.jsxs)(sZ,{status:(g||f)&&(0,r.jsx)("span",{style:{color:"#f87171"},children:g?s("models.configUnreadable",{error:g}):f}),children:[!n&&(0,r.jsx)(sV,{onClick:t,children:s("i18n.cancel")}),(0,r.jsxs)(sV,{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)(lE,{oauthProviders:k,apiKeyProviders:S,onSelectOAuth:e=>j({type:"oauth",providerId:e}),onSelectApiKey:e=>j({type:"apikey",providerId:e}),onAddCustom:W,onClose:()=>$(!1)})]})}let l$=null;async function lI(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(l$)return l$;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 l$=null,!1}})();return l$=t,t.then(e=>{e||l$!==t||(l$=null)}),t}function lT(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function lM(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 lL(e){return e?JSON.stringify([e.requiresTrust,e.trusted,e.decision,e.decisionPath??null,e.inherited]):""}function lz(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function lW(e,t){return t("project"===e?"skills.scope.project":"global"===e?"skills.scope.global":"skills.scope.path")}function lA(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function lP(e,t){return e?e.slice(0,8):t}function lO(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=lz(t),m=!t.disableModelInvocation;return(0,r.jsxs)(s$,{children:[(0,r.jsxs)("div",{className:"skill-detail-heading",children:[(0,r.jsxs)(sI,{children:[(0,r.jsxs)(sT,{children:[(0,r.jsx)(sP,{scope:f,children:lW(f,h)}),(0,r.jsx)("span",{className:"config-detail-path",children:"project"===f?lM(t.filePath,n):lT(t.filePath)})]}),(0,r.jsx)(sM,{children:(0,r.jsx)(sJ,{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)(sz,{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)(sz,{label:h("i18n.version"),children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:lP(l?.currentVersion??t.install.versionHash,h("i18n.unknown"))}),t.install.canCheckForUpdates&&(0,r.jsx)(sV,{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:lP(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)(sV,{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)(sz,{label:h("config.name"),children:(0,r.jsx)("span",{className:"skill-name-value",children:t.name})}),(0,r.jsx)(sz,{label:h("i18n.description"),children:(0,r.jsx)("span",{className:"skill-description",children:t.description})})]})}function lF(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]),$="global"===k?"~/.pi/agent/skills/":`${lT(t)}/.pi/skills/`;return(0,r.jsxs)(s$,{className:"is-full-height",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)(sB,{title:l("i18n.addSkill"),catalogs:[{href:"https://skills.sh",label:"skills.sh"}],target:(0,r.jsx)(sF,{value:k,label:l("config.saveTo"),options:[{value:"global",label:lW("global",l)},{value:"project",label:lW("project",l),disabled:!o}],path:$,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)(sV,{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)(sV,{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 lB(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)(()=>sd("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,$]=(0,i.useState)({}),[I,T]=(0,i.useState)(new Set),[M,R]=(0,i.useState)(!1),[L,z]=(0,i.useState)(null),[W,A]=(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)(()=>{$({}),A(null),F()},[t]);let B=lL(s),D=(0,i.useRef)(B);(0,i.useEffect)(()=>{D.current!==B&&(D.current=B,F())},[B,F]),(0,i.useEffect)(()=>{f&&sc("skills",f,t)},[t,f]);let H=(0,i.useCallback)(async e=>{let n=(e?[e]:a.filter(e=>!!e.install)).map(lA).filter(e=>!!e);if(0!==n.length){A(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}`);$(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){A(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=lA(e);z(n),A(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;$(t=>({...t,[n]:{package:e.install.package,scope:e.install.scope,state:"up-to-date",currentVersion:o,latestVersion:o}}))}catch(e){A(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)(sb,{embedded:o,title:l("common.skills"),subtitle:lT(t),closeLabel:l("i18n.close"),onClose:n,children:[!P&&(0,r.jsx)(s_,{message:l("trust.skillsNotLoaded")}),(0,r.jsxs)(sy,{children:[(0,r.jsxs)(sj,{children:[(0,r.jsx)(sk,{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"===lz(e)&&!!e.install?.skillsShUrl},{label:t.project,matches:e=>"project"===lz(e)&&!e.install?.skillsShUrl},{label:`${t.global} / skills.sh`,matches:e=>"global"===lz(e)&&!!e.install?.skillsShUrl},{label:t.global,matches:e=>"global"===lz(e)&&!e.install?.skillsShUrl},{label:t.path,matches:e=>"path"===lz(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)(sE,{active:i,onClick:()=>{m(e.filePath),C(!1)},children:[(0,r.jsx)(sG,{active:!o}),(0,r.jsx)(sN,{className:`is-grow${o?" is-muted":""}`,children:e.name}),(n=(t=lA(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)(sw,{aside:(0,r.jsx)(sS,{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)(sC,{error:k.error}),[...i.filter(e=>!e.disableModelInvocation),...i.filter(e=>e.disableModelInvocation)].map(n)]},t)})})()}),(0,r.jsx)(sY,{onClick:()=>C(!0),active:S,children:l("i18n.addSkill")})]}),(0,r.jsx)(sq,{children:(0,r.jsx)(s$,{className:"is-fill",children:S?(0,r.jsx)(lF,{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)(lO,{skill:Z,cwd:t,onToggle:U,toggling:g.has(Z.filePath),saveError:v,updateStatus:lA(Z)?N[lA(Z)]:void 0,checkingUpdate:!!lA(Z)&&I.has(lA(Z)),updating:L===lA(Z),updateError:W,onCheckUpdate:()=>void H(Z),onUpdate:()=>void _(Z)},Z.filePath):(0,r.jsx)(sU,{children:l("i18n.selectSkill")})})})]}),(0,r.jsxs)(sZ,{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)(sV,{onClick:n,children:l("i18n.close")}),a.some(e=>!!e.install)&&(0,r.jsx)(sV,{variant:"secondary",onClick:()=>void H(),disabled:M||null!==L,children:M?l("i18n.checking"):l("i18n.checkUpdates")})]})]})}let lD={builtin:0,global:1,workspace:2,project:3},lH=["read","bash","edit","write","grep","find","ls"],l_=["","off","minimal","low","medium","high","xhigh","max"],lU={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},lq={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"},lZ={background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"default"};function lK(e){return{name:e.name,displayName:e.displayName,description:e.description,systemPrompt:e.systemPrompt,tools:[...e.tools],loadSkills:e.loadSkills,...void 0!==e.skills?{skills:[...e.skills]}:{},loadExtensions:e.loadExtensions,...void 0!==e.extensions?{extensions:[...e.extensions]}:{},promptMode:e.promptMode,...e.model?{model:e.model}:{},...e.thinking?{thinking:e.thinking}:{},...e.maxTurns?{maxTurns:e.maxTurns}:{},inheritContext:e.inheritContext,runInBackground:e.runInBackground,enabled:e.enabled}}function lV(e){return`${e.scope}:${e.name}`}function lJ(e){return"global"===e||"project"===e}function lY(e){return lJ(e)||"builtin"===e}function lG(e){let{label:t,children:n}=e;return(0,r.jsx)(sz,{label:t,children:n})}function lX(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 lQ(e){let{cwd:t,sessionId:n=null,onClose:o,onReloaded:s,embedded:l=!1,trust:a}=e,d=e$(),{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)(()=>sd("agents",t)),[j,k]=(0,i.useState)(lU),[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,W]=(0,i.useState)(!1),[A,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=>lV(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=>{I(!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??sd("agents",t),s=i.find(e=>lV(e)===o)??i.find(e=>"project"===e.scope)??i.find(e=>"global"===e.scope)??i[0]??null;y(s?lV(s):null),s&&(k(lK(s)),S(lJ(s.scope)?"edit":"view"),lJ(s.scope)&&N(s.scope))}catch(e){P(e instanceof Error?e.message:String(e))}finally{I(!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&&sc("agents",b,t)},[t,b]);let et=lL(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(lV(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&&lJ(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?lM(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?{...lq,...lZ}:lq,eh=eo?es:!X||!lY(X.scope)||T||z,ef=(e,t)=>{k(n=>({...n,[e]:t}))},em=async e=>{if(eo)return void ef("enabled",e);if(X&&lY(X.scope)){W(!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=>lV(e)===lV(i)?i:e)),k(e=>({...e,enabled:i.enabled}))}catch(e){P(e instanceof Error?e.message:String(e))}finally{W(!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 i4(n,{type:"reload"}),J(!1),s?.()}catch(e){K(e instanceof Error?e.message:String(e))}finally{G(!1)}}};return(0,r.jsxs)(sb,{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)(sV,{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)(sJ,{checked:O,disabled:H||Y,loading:U,label:c("agents.builtInTitle"),onChange:e=>void eg(e)})]})]}),(0,r.jsxs)(sy,{children:[(0,r.jsxs)(sj,{children:[(0,r.jsx)(sk,{children:$?(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)(sw,{children:c(`agents.scope.${e}`)}),t.map(e=>{let t,n,i=(t=e.name.toLowerCase(),n=lD[e.scope],u.some(e=>e.name.toLowerCase()===t&&lD[e.scope]>n));return(0,r.jsxs)(sE,{active:b===lV(e)&&!eo,onClick:()=>{y(lV(e)),k(lK(e)),S(lJ(e.scope)?"edit":"view"),lJ(e.scope)&&N(e.scope),P(null)},children:[(0,r.jsx)(sG,{active:e.enabled}),(0,r.jsx)(sN,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.displayName}),i&&(0,r.jsx)("span",{className:"agents-overridden-label",children:c("agents.overridden")})]},lV(e))})]},e)})}),(0,r.jsx)(sY,{active:eo,onClick:()=>{let e="custom-agent",t=2;for(;u.some(t=>t.name===e);)e=`custom-agent-${t++}`;y(null),k({...lU,name:e,displayName:e}),S("create"),N("global"),P(null)},children:c("agents.new")})]}),(0,r.jsx)(sq,{children:(0,r.jsx)(s$,{className:"is-fill",children:X||eo?(0,r.jsxs)(s$,{children:[(0,r.jsxs)(sI,{children:[(0,r.jsx)(sT,{children:eo?(0,r.jsx)(sF,{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)(sP,{scope:el,children:c(`agents.scope.${el}`)}),(0,r.jsx)("span",{title:ed,className:"config-detail-path",children:ea})]})}),(0,r.jsxs)(sM,{children:[X&&("view"===w||"edit"===w)&&(0,r.jsx)(sV,{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({...lK(X),name:e,displayName:c("agents.copyName",{name:X.displayName})}),S("create"),N(lJ(X.scope)?X.scope:"global"),P(null)},disabled:T||z,children:c("agents.duplicate")}),X&&lJ(X.scope)&&"edit"===w&&(0,r.jsx)(sV,{variant:"danger",size:"small",onClick:()=>void er(),disabled:T||z,children:c("agents.delete")}),(0,r.jsx)(sJ,{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)(lG,{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:lq}):(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)(lG,{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)(lG,{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)(lG,{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)(lG,{label:c("agents.tools"),children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 16px"},children:lH.map(e=>(0,r.jsx)(lX,{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.jsxs)(lG,{label:c("agents.resources"),children:[(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 20px"},children:[(0,r.jsx)(lX,{label:c("agents.loadSkills"),disabled:es,checked:j.loadSkills,onChange:e=>ef("loadSkills",e)}),(0,r.jsx)(lX,{label:c("agents.loadExtensions"),disabled:es,checked:j.loadExtensions,onChange:e=>ef("loadExtensions",e)})]}),j.loadSkills&&void 0!==j.skills&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:j.skills.length>0?c("agents.skillsOnly",{skills:j.skills.join(", ")}):c("agents.skillsNone")}),j.loadExtensions&&void 0!==j.extensions&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:j.extensions.length>0?c("agents.extensionsOnly",{extensions:j.extensions.join(", ")}):c("agents.extensionsNone")})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:d?"1fr":"minmax(0, 1.5fr) minmax(120px, 0.75fr) minmax(100px, 0.5fr)",gap:12},children:[(0,r.jsx)(lG,{label:c("agents.model"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(ia,{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)(lG,{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:l_.map(e=>(0,r.jsx)("option",{value:e,children:e||c("agents.inherit")},e||"default"))})}),(0,r.jsx)(lG,{label:c("agents.maxTurns"),children:(0,r.jsx)("input",{"aria-label":c("agents.maxTurns"),type:"number",min:1,value: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)(lX,{label:c("agents.inheritContext"),disabled:es,checked:j.inheritContext,onChange:e=>ef("inheritContext",e)}),(0,r.jsx)(lX,{label:c("agents.background"),disabled:es,checked:j.runInBackground,onChange:e=>ef("runInBackground",e)})]})]}):(0,r.jsx)(sU,{children:c("agents.empty")})})})]}),(0,r.jsx)(sZ,{status:(Z||A)&&(0,r.jsx)("span",{role:"alert",style:{color:"#ef4444"},children:Z||A}),children:ei&&(0,r.jsxs)(sV,{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 l0=["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"];function l1(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function l2(e){return`${e.scope}\0${e.source}`}function l4(e){return`extension\0${e.path}`}function l8(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function l5(e,t){return t(`plugins.status.${e}`)}function l3(e){return`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`}function l6(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function l9(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 l7(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)(sD,{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)(sF,{value:i,label:u("config.saveTo"),options:[{value:"global",label:l8("global",u)},{value:"project",label:l8("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:l1,onValueChange:a,onSubmit:c,examplesLabel:u("config.examples"),examples:l0,error:l,children:(0,r.jsx)(sV,{variant:"primary",onClick:c,disabled:s||!n.trim(),className:"is-pushed-right",children:u(s?"i18n.installing":"i18n.install")})})}function ae(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=l2(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)(s$,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(sI,{className:"is-top-aligned",children:[(0,r.jsxs)(sT,{children:[(0,r.jsx)(sP,{scope:n.scope,children:l8(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)(sM,{children:[(0,r.jsx)(sV,{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)(sV,{size:"small",onClick:m,disabled:!d||b||v,"aria-describedby":d?void 0:S,children:g(b?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)(sV,{variant:"danger",size:"small",onClick:()=>h("remove",n),disabled:v||b,children:g(s===`remove:${x}`?"i18n.removing":"i18n.remove")}),(0,r.jsx)(sJ,{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)(sW,{children:[w&&(0,r.jsx)(sA,{label:g("i18n.description"),children:w}),(0,r.jsx)(sA,{label:g("i18n.status"),tone:"plain",style:{color:l6(n.status),textTransform:"capitalize"},children:l5(n.status,g)}),(0,r.jsxs)(sA,{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)(sA,{label:g("i18n.package"),mono:!0,children:n.packageName??g("i18n.unknown")}),(0,r.jsx)(sA,{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)(sA,{label:g("i18n.installedPath"),tone:n.installedPath?"muted":"error",mono:!0,children:n.installedPath?lT(n.installedPath):g("i18n.notFound")}),(0,r.jsx)(sA,{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)(sL,{children:g("i18n.resolvedResources")}),(0,r.jsx)(l9,{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 at(e){let{extension:t}=e,{t:n}=(0,E.s)(),i=t.enabled?"loaded":"disabled";return(0,r.jsxs)(s$,{children:[(0,r.jsx)(sI,{children:(0,r.jsxs)(sT,{children:[(0,r.jsx)(sP,{scope:t.scope,children:l8(t.scope,n)}),(0,r.jsx)(sR,{children:t.name})]})}),(0,r.jsxs)(sW,{children:[(0,r.jsx)(sA,{label:n("i18n.status"),tone:"plain",style:{color:t.enabled?"var(--accent)":"var(--text-dim)"},children:l5(i,n)}),(0,r.jsx)(sA,{label:n("i18n.installedPath"),mono:!0,children:lT(t.path)})]})]})}function an(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)(()=>sd("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,W]=(0,i.useState)({}),[A,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=>l2(e)===x)??null,K=q.find(e=>l4(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=>l2(t)===e)||t.standaloneExtensions.some(t=>l4(t)===e))?e:t.packages[0]?l2(t.packages[0]):t.standaloneExtensions[0]?l4(t.standaloneExtensions[0]):null)}catch(e){g(e instanceof Error?e.message:String(e))}finally{f(!1)}},[n]);(0,i.useEffect)(()=>{W({}),D(null),Y()},[n]);let G=lL(d),X=(0,i.useRef)(G);(0,i.useEffect)(()=>{X.current!==G&&(X.current=G,Y())},[G,Y]),(0,i.useEffect)(()=>{x&&sc("plugins",x,n)},[n,x]);let Q=(0,i.useCallback)(async e=>{let t=(e?[e]:U.filter(e=>e.canCheckForUpdates)).map(l2);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}`);W(e=>{let t={...e};for(let e of r.updates??[])t[l2(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),I(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),W({}),M(c("i18n.packagesUpdated")),o&&M(`${c("i18n.packagesUpdated")} ${c("agents.reloadRequired")}`)}catch(e){I(e instanceof Error?e.message:String(e))}finally{_(!1)}},[n,o,c]),et=(0,i.useCallback)(async(e,t)=>{let r=l2(t);N(`${e}:${r}`),I(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]?l2(o.packages[0]):o.standaloneExtensions[0]?l4(o.standaloneExtensions[0]):null),0===o.packages.length&&0===o.standaloneExtensions.length&&y(!0),M(c("i18n.packageRemoved")),W(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&&W(e=>{let t={...e};return delete t[r],t})}}catch(e){I(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(I(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=l1(j).trim();if(!e)return;k(e);let t=`${w}\0${e}`;N(`install:${t}`),I(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?l2(a):t),y(!1),k(""),M(c("i18n.packageInstalled"))}catch(e){I(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,w,j,c]),ei=(0,i.useCallback)(async()=>{if(o){N("reload"),I(null),M(null),L(null);try{await i4(o,{type:"reload"}),l?.(),await Y(),M(c("i18n.sessionReloaded"))}catch(e){I(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||A.size>0||H;return(0,r.jsxs)(sb,{embedded:a,title:c("common.plugins"),subtitle:lT(n),closeLabel:c("i18n.close"),onClose:s,children:[!V&&(0,r.jsx)(s_,{message:c("trust.pluginsNotLoaded")}),(0,r.jsxs)(sy,{children:[(0,r.jsxs)(sj,{children:[(0,r.jsx)(sk,{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)(sw,{children:c("i18n.extensions")}),q.map(e=>{let t=l4(e);return(0,r.jsxs)(sE,{active:!b&&x===t,title:e.path,onClick:()=>{v(t),y(!1),I(null),M(null)},children:[(0,r.jsx)(sG,{active:e.enabled}),(0,r.jsx)(sN,{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)(sw,{aside:(0,r.jsx)(sS,{enabled:t,total:e.packages.length,disabled:ea,loading:C===`bulk:${e.scope}`,label:c(n?"plugins.groupSwitchOn":"plugins.groupSwitchOff",{group:l8(e.scope,c)}),onChange:t=>void en(e.scope,e.packages,t)}),children:l8(e.scope,c)}),R?.scope===e.scope&&(0,r.jsx)(sC,{error:R.error,note:R.note}),e.packages.map(e=>{let t=l2(e),n=!b&&x===t;return(0,r.jsxs)(sE,{active:n,title:e.description??e.source,onClick:()=>{v(t),y(!1),I(null),M(null)},children:[(0,r.jsx)(sG,{active:!e.disabled,color:l6(e.status)}),(0,r.jsx)(sN,{className:`is-grow${e.disabled?" is-muted":""}`,children:e.source}),z[l2(e)]?.state==="update-available"&&(0,r.jsx)("span",{title:c("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"})]},t)})]},e.scope)})]})}),(0,r.jsx)(sY,{active:b,onClick:()=>{y(!0),I(null),M(null)},children:c("i18n.addPlugin")})]}),(0,r.jsx)(sq,{children:(0,r.jsx)(s$,{className:"is-fill",children:b?(0,r.jsx)(l7,{cwd:n,source:j,scope:w,projectResourcesLoaded:V,busy:eo,actionError:$,onSourceChange:k,onScopeChange:S,onInstall:er}):h?null:K?(0,r.jsx)(at,{extension:K}):Z?(0,r.jsx)(ae,{pkg:Z,cwd:n,busyKey:C,actionError:$,actionMessage:T,sessionId:o,updateStatus:z[l2(Z)],checkingUpdate:A.has(l2(Z)),updateError:B,onAction:et,onCheckUpdate:()=>void Q(Z),onReloadSession:ei},l2(Z)):(0,r.jsx)(sU,{children:c("i18n.selectPackage")})})})]}),(0,r.jsxs)(sZ,{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)(sK,{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(l3)}):(0,r.jsx)(sK,{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)(sV,{onClick:s,children:c("i18n.close")}),el&&(0,r.jsx)(sV,{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)(sV,{variant:"secondary",onClick:()=>void Y(),disabled:ea,children:c("i18n.refresh")})]})]})}let ar={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 ai(e,t){return e.replace(/\{(\w+)\}/g,(e,n)=>void 0===t[n]?e:String(t[n]))}function ao(e){let t=e.replace(/[\\/]+$/,""),n=t.split(/[\\/]/);return n[n.length-1]||t}function as(e){var t;let n,{onClose:o,embedded:s=!1}=e,{locale:l}=(0,E.s)(),a=ar[l]??ar.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),$=(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=eF(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=eO(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)(()=>{$()},[$]);let I=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)(sb,{embedded:s,title:a.title,onClose:o,children:m?(0,r.jsx)(sU,{children:a.loadFailed}):0===d.length?(0,r.jsx)(sU,{children:a.empty}):(0,r.jsxs)(sy,{children:[(0,r.jsx)(sj,{children:(0,r.jsx)(sk,{children:d.map(e=>(0,r.jsx)(sE,{active:e.key===u,onClick:()=>{p(e.key),y(!1),k(""),N(null)},children:(0,r.jsx)(sN,{title:e.root,children:ao(e.root)})},e.key))})}),(0,r.jsx)(sq,{children:I?(0,r.jsxs)(s$,{children:[(0,r.jsxs)(sI,{children:[(0,r.jsx)(sT,{children:(0,r.jsx)(sR,{children:ao(I.root)})}),(0,r.jsxs)(sM,{children:[(0,r.jsx)(sV,{variant:"secondary",size:"small",disabled:x,onClick:()=>void T(I.key),children:x?a.busy:a.unarchive}),!b&&(0,r.jsx)(sV,{variant:"danger",size:"small",disabled:x||0===I.sessions.length,onClick:()=>{y(!0),k(""),N(null)},children:a.deleteSessions})]})]}),(0,r.jsx)(sz,{label:a.path,children:(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",wordBreak:"break-all"},children:(t=I.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:ai(a.deleteConfirmLead,{count:I.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)(sV,{variant:"danger",size:"small",disabled:x||"confirm"!==(n=j.trim().toLowerCase())&&"确认"!==n&&"確認"!==n,onClick:()=>void M(I),children:x?a.busy:a.deleteSessions}),(0,r.jsx)(sV,{variant:"ghost",size:"small",disabled:x,onClick:()=>{y(!1),k("")},children:a.cancel})]})]}),(0,r.jsx)(sL,{children:ai(a.sessions,{count:I.sessions.length})}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2,minHeight:0,overflowY:"auto"},children:I.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:ai(a.messages,{count:e.messageCount})})]})]},e.id)})}),w&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:w})]}):(0,r.jsx)(sU,{children:a.empty})})]})})}let al="\\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",aa=RegExp(`[${al}]`,"gu"),ad=RegExp(`[${al}]`,"u");function ac(e){return e.replace(aa,e=>{let t=e.codePointAt(0)??0;return`\\u{${t.toString(16).toUpperCase().padStart(4,"0")}}`})}let au=/[\s"'`$|&;<>()*?#~]/;function ap(e){let t=ad.test(e),n=ac(e);return""===n||t||au.test(n)?`"${n.replace(/"/g,'\\"')}"`:n}function ah(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return[e,...t].map(ap).join(" ")}function af(e){let t=void 0!==e.command?ah(e.command,e.args):void 0,n=void 0!==e.url?ac(e.url):void 0;return"http"===e.transport?n:"stdio"===e.transport?t:n??t}function am(e){return[e.name,e.command,e.cwd,e.url,...e.args??[],...e.envNames,...e.headerNames].some(e=>void 0!==e&&ad.test(e))}function ag(e){return"oauth-client-secret"===e.kind?{key:"mcp.field.oauthClientSecret"}:{key:"env"===e.kind?"mcp.field.env":"mcp.field.header",params:{name:ac(e.name??"")}}}function ax(e){return"http"===e.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables"}function av(e){return e.flatMap(e=>{let{variables:t,...n}=e;return t.map(e=>({variable:e,field:n}))})}function ab(e,t){return"unparsable"===e.reason||"unreadable"===e.reason?ac(e.error):"link-outside"===e.reason?void 0===t?void 0:ac(t):void 0}let ay="codemode";function aj(e){return`${e.scope}\0${e.name}`}function ak(e){return e?.trust?.decision===!0}function aw(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 aS={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"},aC={connected:"mcp.state.session.connected",failed:"mcp.state.session.failed"};function aE(e,t){return(t?.origin==="session"?aC[e]:void 0)??aS[e]}let aN={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"},a$={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 aI(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 aM(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"},aL={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"},az={connecting:"off",connected:"on","needs-auth":"warning",failed:"error",disconnected:"warning",conflict:"error","not-trusted":"warning"},aW={codemode:"mcp.exposure.codemode",deferred:"mcp.exposure.deferred",direct:"mcp.exposure.direct",hidden:"mcp.exposure.hidden"},aA=["codemode","deferred","direct","hidden"],aP={codemode:"mcp.exposureShort.codemode",deferred:"mcp.exposureShort.deferred",direct:"mcp.exposureShort.direct",hidden:"mcp.exposureShort.hidden"};function aO(e){return"auto-enable-codemode-invalid"!==e.reason}function aF(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 aB(e){return{enabled:e.filter(e=>e.enabled).length,total:e.length}}function aD(e,t){let n=e.flatMap(e=>e.servers.map(aj));return t===ay||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 a_(e){return e.projectOverride?.preference??e.preference}let aU={always:"mcp.codemode.projectOverride.always",automatic:"mcp.codemode.projectOverride.automatic"},aq={on:"mcp.codemode.toolMode.onDescription",only:"mcp.codemode.toolMode.onlyDescription"},aZ={on:"mcp.codemode.toolMode.projectOverride.on",only:"mcp.codemode.toolMode.projectOverride.only"},aK={automatic:"mcp.codemode.automatic",always:"mcp.codemode.always",unavailable:"mcp.codemode.unavailable",unknown:"i18n.unknown"};function aV(e){return"unavailable"===e?"error":"unknown"===e?"off":"on"}let aJ=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e);function aY(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}:{},...aJ(n.names)?{names:n.names}:{},...aJ(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 aG(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 aX(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 aQ(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&&aX(i)?{ok:!0,data:i}:{ok:!1,error:aY(i,r.status)}}let a0=new Set(["cwd-invalid","cwd-denied","cwd-not-directory"]);async function a1(e,t,n){let r=await aQ(e,t,n);if(r.ok||!e||!r.error.reason||!a0.has(r.error.reason))return r;let i=await aQ(null,t,n);return i.ok?{...i,projectError:r.error}:i}async function a2(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 aG(n=>a1(e,t,n),()=>({ok:!1,error:{error:`GET /api/mcp did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function a4(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:aY(o,i.status)}}async function a8(e,t,n){let r=await a4({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 a5(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 aG(n=>a8(e,t,n),()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function a3(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 aG(async n=>{let r=await a4({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 a6(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 aG(async n=>{let r=await a4({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 a9(e){return!e.available&&"builtin-disabled"!==e.reason}function a7(e,t){if(a9(t.mcp))return"mcp-off";if("project"===e){if(!t.project?.trust)return"trust-unreadable";if(!ak(t.project))return"project-untrusted"}}let de={"mcp-off":"mcp.readOnly.mcp-off","project-untrusted":"mcp.readOnly.project-untrusted","trust-unreadable":"mcp.readOnly.trust-unreadable"};function dt(e){return!0!==e.notAnObject}function dn(e){return dt(e)&&void 0===e.webPasswordField}async function dr(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&&aX(i)?{ok:!0,data:i}:{ok:!1,error:aY(i,r.status)}}async function di(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 aG(e=>dr(o,n,e),()=>({ok:!1,error:{error:`POST /api/mcp did not answer within ${i} ms`,timedOut:!0}}),i,r)}let ds={"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 dl(e,t){let n=a7(e.scope,t);return n||(void 0===e.invalidError&&e.validated?e.webPasswordField?"web-password":void 0:"invalid")}let da={"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"},dd={connected:"mcp.test.state.connected","needs-auth":"mcp.test.state.needs-auth",failed:"mcp.test.state.failed",timedOut:"mcp.test.state.timedOut"},dc={connected:"mcp.test.summary.connected","needs-auth":"mcp.test.summary.needs-auth",failed:"mcp.test.summary.failed",timedOut:"mcp.test.summary.timedOut"},du={connected:"mcp.signIn.summary.connected","needs-auth":"mcp.signIn.summary.needs-auth",failed:"mcp.signIn.summary.failed",timedOut:"mcp.signIn.summary.timedOut"};function dp(e){return(Math.max(0,e)/1e3).toFixed(1)}async function dh(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:aY(i,r.status)}}async function df(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 aG(e=>dh(o,n,e),()=>({ok:!1,error:{error:`POST /api/mcp/test did not answer within ${i} ms`,timedOut:!0}}),i,r,{abortAtDeadline:!1})}let dm="•••",dg=new Set(["key","apikey","token","secret","password","passwd","passphrase","pwd","pass","credential","credentials","authorization","bearer","jwt","cookie","signature","pat"]),dx=new Set([...dg,"auth","sig","code","pw"]),dv=["token","secret","password","passwd","apikey"],db=new Set(["file","path","dir","url","uri","endpoint","id","name","type","header","env","var","length","ttl","expiry","expires","timeout","mode","format"]),dy=new Set(["-k"]);function dj(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 dk(e,t){let n=dj(e);return!(n.length>1&&db.has(n[n.length-1]))&&n.some(e=>t.has(e)||dv.some(t=>e.length>t.length&&e.endsWith(t)))}function dw(e){return dk(e,dg)}let dS=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,})"),dC=/^eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*$/,dE=/^[A-Za-z0-9_\-+/=.~]+$/;function dN(e){return!(/\s/.test(e)||dR(e))&&(!!(dS.test(e)||dC.test(e))||!(e.length<24||!dE.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 d$=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Za-z_][A-Za-z0-9_]*/,dI=RegExp(d$.source,"g"),dT=/^(?:bearer|basic|token)\s+/i;function dM(e,t,n){let r=e.replace(dT,"");return t.test(r)&&/^[^A-Za-z0-9]*$/.test(r.replace(n,""))}function dR(e){return dM(e.replace(/\$[$!]/g,"_x"),d$,dI)}let dL=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Z_][A-Z0-9_]*(?![A-Za-z0-9_])/,dz=RegExp(dL.source,"g");function dW(e){return dM(e,dL,dz)}function dA(e,t){if(!e||""===t)return;e.push(t);let n=dF(t);n!==t&&e.push(n)}let dP=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#]*)/;function dO(e,t,n){let r=!1,i=e,o="",s=dP.exec(e);if(s){let[l,a,d]=s,c=d.lastIndexOf("@");if(c>=0&&!t(dF(d.slice(0,c)))){o=`${a}${dm}${d.slice(c)}`,r=!0;let e=d.slice(0,c);dA(n,e);let t=e.indexOf(":");t>=0&&dA(n,e.slice(t+1))}else 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=>dN(dF(e))?(r=!0,dA(n,e),dm):e).join("/");return d=d.replace(/([?&#;])([^&#;]*)/g,(e,i,o)=>{let s=o.indexOf("=");if(s<0){let s=dF(o);return!dN(s)||t(s)?e:(r=!0,dA(n,o),`${i}${dm}`)}let l=o.slice(0,s),a=dF(o.slice(s+1));return""===a||t(a)||!function(e){let t=e;try{t=decodeURIComponent(e)}catch{}return dk(t,dx)}(l)&&!dN(a)?e:(r=!0,dA(n,o.slice(s+1)),`${i}${l}=${dm}`)}),{value:`${o}${c}${d}`,masked:r}}function dF(e){try{return decodeURIComponent(e)}catch{return e}}let dB=/^(\s*[A-Za-z][A-Za-z0-9 _.-]*=)([\s\S]*)$/;function dD(e,t,n){let r=/^([A-Za-z0-9_-]+):(\s*)([\s\S]*)$/.exec(e);if(r&&""!==r[3]&&!r[3].startsWith("//")&&dw(r[1])){let[,i,o,s]=r;return t(s)?{value:e,masked:!1}:(dA(n,s.trim()),{value:`${i}:${o}${dm}`,masked:!0})}let i=e.includes(";")?function(e,t,n){let r=e.split(";");if(r.length<2||!r.every(e=>""===e.trim()||dB.test(e)))return;let i=!1;return{value:r.map(e=>{let r=dB.exec(e);if(!r)return e;let[,o,s]=r;if(""===s.trim()||t(s))return e;if(dw(o.slice(0,-1).trim()))return i=!0,dA(n,s.trim()),`${o}${dm}`;let l=dD(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]&&dw(o[1]))return t(o[2])?{value:e,masked:!1}:(dA(n,o[2]),{value:`${o[1]}=${dm}`,masked:!0});if(/\s/.test(e)){var s,l,a;let r,i;return s=e,l=t,a=n,i=dU((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 dO(e,t,n);if(o&&""!==o[2]){let e=dD(o[2],t,n);return{value:`${o[1]}=${e.value}`,masked:e.masked}}return dN(e)&&!t(e)?(dA(n,e),{value:dm,masked:!0}):{value:e,masked:!1}}function dH(e){if(dy.has(e))return!0;if(!/^--?[A-Za-z]/.test(e))return!1;let t=e.replace(/^-+/,"");return dw(t)||"auth"===dj(t).at(-1)}let d_=/^(?:bearer|basic|token)$/i;function dU(e,t,n,r){let i=!1,o=!1;return{values:e.map(e=>{if(""===e)return e;if(o){if(n&&d_.test(e))return e;if(o=!1,!/^-[A-Za-z-]/.test(e))return t(e)?e:(i=!0,dA(r,e),dm)}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,dA(r,n),`${e}=${dm}`;let o=dD(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(d_.test(e)||t&&dw(t[1]))return o=!0,e}let l=dD(e,t,r);return i||=l.masked,l.value}),masked:i}}function dq(e){let{values:t,masked:n}=dU(e,dW,!1);return{args:t,masked:n}}function dZ(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function dK(e){return!e.startsWith("!")&&!dR(e)}function dV(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 dJ={"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(dJ);let dY={dollarBrace:!1,bareDollar:!1,percent:!1,braceEnv:!1},dG={dollarBrace:!0,bareDollar:!1,percent:!0,braceEnv:!0},dX={...dG,bareDollar:!0},dQ={...dY,braceEnv:!0},d0=/^[A-Za-z_][A-Za-z0-9_]*$/,d1=/\$\{([^{}]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)|%([A-Za-z_][A-Za-z0-9_]*)%|\{(env|file):([^{}]*)\}/g;function d2(e,t){if(!t)return;let n=e[e.length-1];n?.kind==="text"?n.text+=t:e.push({kind:"text",text:t})}function d4(e,t,n){let r=[],i=0;d1.lastIndex=0;for(let o=d1.exec(e);o;o=d1.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(d0.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&&d0.test(u)?{kind:"env",name:u,from:s}:{kind:"unsupported",from:s};else if(void 0!==d||void 0!==c){d2(r,e.slice(i,o.index+1)),i=o.index+1,d1.lastIndex=o.index+1;continue}d2(r,e.slice(i,o.index)),"string"==typeof p?d2(r,p):r.push(p),i=o.index+s.length}return d2(r,e.slice(i)),r}function d8(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 d5(e){return e.startsWith("!")}function d3(e){if(d5(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);d0.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 d6=/<[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,d9=/^(?:\.\.\.|…|\*{3,}|x{3,}|TODO|FIXME|changeme|change[-_]me|replace[-_]?me|placeholder|redacted|\[[^\]]+\])$/i,d7=/(?:^|[\\/])(?:path[\\/]to(?:[\\/]|$)|Users[\\/](?:username|yourname|your[-_][A-Za-z_-]+|user[-_]?name|<[^>]+>)(?:[\\/]|$)|home[\\/](?:username|yourname|your[-_][A-Za-z_-]+|<[^>]+>)(?:[\\/]|$))/i,ce=/^(Bearer|Basic|Token|Bot|ApiKey|Api-Key)\s+(.+)$/i;function ct(e){return e.join("\0")}function cn(e){return"args"===e[0]?`args[${e[1]}]`:e.join(".")}function cr(e){return"env"===e[0]||"headers"===e[0]||"oauth"===e[0]&&"clientSecret"===e[1]}function ci(e){return"command"===e[0]||"args"===e[0]||"cwd"===e[0]}let co=new Set(["HOME","USERPROFILE"]);class cs{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 cl(e){return e.map(e=>"text"in e?e.text:e.from).join("")}let ca=/\$\{[^{}]*\}/g,cd=new Set(["variable","home","workspace-basename","unsupported-variable","input"]);class cc{constructor(e){this.draft=e,this.fields=new Map,this.argTexts=e.args.map(cl),this.urlText=cl(e.url??[])}encode(e,t){let n,r=cr(e),i=cn(e),o=cl(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=d8(e,{atStart:a()});n!==e&&(l=!0),s.push(n)},c=e=>s.push(e),u=e=>s.push({field:e});if(!r&&ci(e)&&1===t.length&&"text"in t[0]&&d7.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(d7.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(d9.test(t)){let n=e.indexOf(t);return[[n,n+t.length]]}let n=ce.exec(t);if(n&&d9.test(n[2].trim())){let t=e.lastIndexOf(n[2].trim());return[[t,t+n[2].trim().length]]}let r=[];d6.lastIndex=0;for(let t=d6.exec(e);t;t=d6.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]&&cu(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,"")||cn(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()&&d5(e)){this.draft.note("shell-command-value",{field:i}),c(e);break}let t=[...e.matchAll(ca)].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}}`})):ci(e)&&a()&&co.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}"})):ci(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]&&cu(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=>ct(t.path)===ct(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=cd.has(t)?`${t}.${n}`:cn(e);if(cd.has(t)){if(this.fields.has(s))return s}else for(let t=2;this.fields.has(s);t++)s=`${cn(e)}#${t}`;let l=this.isSecretContext(e,r)||dw(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 dw(e[1]);case"oauth":return"clientSecret"===e[1];case"args":{if(dq([this.argTexts[e[1]]??""]).masked)return!0;let t=this.argTexts[e[1]-1];return void 0!==t&&dq([t,"x"]).args[1]===dm}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,dO(`https://host.invalid/?${n}=x`,dW).masked)}default:return!1}}}function cu(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 cp(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 ch=/^[A-Za-z0-9_-]+$/;function cf(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 cm=new Set(["mcp","server","mcp-server","mcpserver","cli","index","main","app","src","dist","build","bin","lib"]);function cg(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=cv(t);return o&&!cm.has(o.toLowerCase())?o:cv(r)||r||o||t}let cx=[/^mcp[-_]server[-_]/i,/^server[-_]/i,/^mcp[-_]/i,/[-_]mcp[-_]server$/i,/[-_]mcp$/i,/[-_]server$/i];function cv(e){let t=e;for(let e=!0;e;)for(let n of(e=!1,cx)){let r=t.replace(n,"");r!==t&&r&&(t=r,e=!0)}return t}let cb=new Set(["mcp","www","api","app","server","servers","remote","gateway"]);function cy(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=>!cb.has(e.toLowerCase()));return r[r.length-1]??n[n.length-1]??""}let cj=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 ck(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 cw(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(!cm.has(n.toLowerCase())&&"."!==n&&".."!==n)return cv(n.replace(/_/g,"-"))||n}return""}function cS(e,t){cC(e,t)&&cE(e,Math.ceil(t/1e3),t)}function cC(e,t){return!!("number"==typeof t&&Number.isFinite(t))&&t>0||(void 0!==t&&e.note("timeout-dropped",{value:String(t)}),!1)}function cE(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 cN=["codemode","deferred","direct","hidden"],c$={"codemode-deferred":"codemode"},cI=["localhost","127.0.0.1","[::1]"];function cT(e){return"string"==typeof e&&cN.includes(e)?e:"string"==typeof e&&Object.hasOwn(c$,e)?c$[e]:void 0}function cM(e){try{return new URL(e)}catch{return}}function cR(e){let t=cM(e);return void 0!==t&&"http:"===t.protocol&&cI.includes(t.hostname)&&""===t.search&&""===t.hash}function cL(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cz(e){return cL(e)&&Object.values(e).every(e=>"string"==typeof e)}function cW(e,t){if(!ch.test(e))return{problem:"name",name:e};if(!cL(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(!cL(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=cM(t.url);if(!e||!/^https?:$/.test(e.protocol))return{problem:"url",url:t.url};if(void 0!==t.headers&&!cz(t.headers))return{problem:"headers"};let n=function(e){var t;let n;if(void 0===e)return;if(!cL(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)?cM(t):void 0)&&("https:"===n.protocol||"http:"===n.protocol&&cI.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(!cL(r)||"string"!=typeof r.provider||!r.provider)return{problem:"auth"};if("https:"!==e.protocol&&!cI.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||cz(t.env)?void 0!==t.cwd&&"string"!=typeof t.cwd?{problem:"cwd"}:void 0:{problem:"env"}:{problem:"args"}:{problem:"no-command-or-url"}}let cA=/[A-Za-z_]/,cP=/[A-Za-z0-9_]/,cO=/^[A-Za-z_][A-Za-z0-9_]*$/,cF=new Set([..." \n'\"\\$`|&;<>()#*?[]{}!~="]),cB=new Set([..."|&;<>()"]),cD=/[0-9@*#?$!-]/,cH={n:"\n",t:" ",r:"\r",a:"\x07",b:"\b",e:"\x1b",E:"\x1b",f:"\f",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function c_(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 cU(e,t){return/^(?:[A-Za-z]:\\|\\\\[A-Za-z0-9.$_-])/.test(e.slice(t,t+4))}class cq{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 cZ)return{ok:!1,error:e.detail};throw e}return{ok:!0,words:this.words}}fail(e){throw new cZ(e)}startWord(){return this.parts||(this.lineBreak&&this.fail({code:"multiple-commands"}),this.parts=[],this.windowsWord=cU(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)&&c_(e,this.index)>0)this.index+=c_(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:"`"}):cB.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||!cF.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=cU(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&&cA.test(n)){let n=this.index+1;for(;n<t.length&&cP.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&&cD.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}),cO.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 cZ extends Error{constructor(e){super(e.code),this.detail=e}}function cK(e){return new cq(e).run()}function cV(e){return e.parts.every(e=>"text"===e.type)?e.text:void 0}function cJ(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let cY=["httpUrl","trust","includeTools","excludeTools","authProviderType","targetAudience","targetServiceAccount","tcp"];function cG(e){if(cY.some(t=>t in e))return!0;let t=e.oauth;return cJ(t)&&["redirectUri","authorizationUrl","tokenUrl","audiences","tokenParamName"].some(e=>e in t)}function cX(e){if(!cJ(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]||cJ(t)&&"string"==typeof t.path||"string"==typeof n||"string"==typeof r||"string"==typeof i}function cQ(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 c0(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 c1(e,t){let n=t?c0(t):void 0;return{code:"sse-transport",params:{...e?{server:e}:{},...t?{url:t}:{},...n?{suggestedUrl:n}:{}}}}function c2(e){return e?{server:e}:{}}function c4(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?String(e):void 0}function c8(e,t,n){let r;if(!cJ(t))return{note:{code:"no-command-or-url",params:c2(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 dY;case"opencode":return dQ;case"vscode":return dG;default:return cG(t)?dX:dG}}(n,t),a=o("name"),d=e??("string"==typeof a?a:void 0),c=new cs(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"),d4(e,l,t)};c.name=d,c.inputs=n.inputs;let p=o("inputs");Array.isArray(p)&&(c.inputs=new Map([...n.inputs??[],...c6(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:c2(d)}};if(void 0!==h&&"unknown"===(r="string"==typeof h?cQ(h):"unknown"))return{note:{code:"unsupported-transport",params:{...c2(d),type:String(h)}}};let g="string"==typeof f&&""!==f||Array.isArray(f)||cJ(f),x=void 0!==m;if("sse"===r)return{note:c1(d,m)};if("ws"===r)return{note:{code:"websocket-transport",params:{...c2(d),...m?{url:m}:{}}}};if(void 0===r){if(g&&x)return{note:{code:"ambiguous-command-and-url",params:c2(d)}};if(x){if(void 0!==c0(m))return{note:c1(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:c2(d)}};r="stdio"}}if("stdio"!==r&&"http"!==r)return{note:{code:"unsupported-transport",params:{...c2(d),type:String(h)}}};if("stdio"===r&&!g||"http"===r&&!x)return{note:{code:"no-command-or-url",params:c2(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:{...c2(e.name),problem:"args"}};s=n[0],l=[...n.slice(1),...Array.isArray(l)?l:[]]}else if(cJ(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:c2(e.name)};let d=Array.isArray(l)?[...l]:[];if(void 0!==l&&!Array.isArray(l))return{code:"invalid-config",params:{...c2(e.name),problem:"args"}};if(0===d.length&&/\s/.test(s.trim())&&!/^(?:[A-Za-z]:[\\/]|[\\/]|~[\\/]|\.{1,2}[\\/])/.test(s.trim())){let t=cK(s.trim()),n=t.ok?t.words.map(cV):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=c4(n);if(void 0===r)return{code:"invalid-config",params:{...c2(e.name),problem:"args",index:t}};e.args.push(i(r,!1))}if(void 0!==a){if(!cJ(a))return{code:"invalid-config",params:{...c2(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=c4(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&&dw(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=cJ(o)&&Object.keys(o).some(e=>"authorization"===e.toLowerCase());if(1===s.length&&"text"in s[0]?cp(e,n,l):e.url=s,cJ(o))for(let[t,n]of Object.entries(o)){let r=c4(n);if(void 0===r){e.note("dropped-key",{key:`headers.${t}`});continue}if(""===r.trim()){"authorization"===t.toLowerCase()?e.note("empty-authorization-dropped"):dw(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"):cJ(a)?c5(e,a,i):void 0!==a&&e.note("dropped-key",{key:"oauth"}),cJ(d))for(let t of(c5(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(cG(t))cS(c,v);else["autoApprove","alwaysAllow","transportType"].some(e=>e in t)||"streamableHttp"===t.type?cC(c,v)&&cE(c,Math.ceil(v),void 0):!function(e,t){if(!cC(e,t))return;let n=t>=1e3;e.note("timeout-unit-guessed",{value:t,unit:n?"milliseconds":"seconds"}),n?cE(e,Math.ceil(t/1e3),t):cE(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=cJ(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(c3(c,o("includeTools"),o("excludeTools")),Object.keys(t)))i.has(e)||c.note("dropped-key",{key:e});return{draft:c}}function c5(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 c3(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 c6(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e)cJ(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=>cJ(e)?e.value:e).filter(e=>"string"==typeof e)}:{}});return t}function c9(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=cJ(t)&&cJ(t[s[1]])?t[s[1]]:{};i.push(c7(`${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 c7(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 ue(e,t,n){let r=[],i="",o=()=>{i&&("pi"===t?r.push({kind:"pi",text:i}):r.push(...d4(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 ut(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 un=/^https?:\/\//i,ur=/^wss?:\/\//i,ui={"@earendil-works/pi-coding-agent":"pi","@anthropic-ai/claude-code":"claude","@openai/codex":"codex","@google/gemini-cli":"gemini"},uo=new Set(["pi","claude","codex","gemini"]),us=new Set(["install","remove","uninstall","update","list","config"]);function ul(e){return"error"in e?{error:e.error}:{entries:[e],notes:[]}}let ua={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"},ud=new Map([["-l","--local"]]),uc=["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name"],uu=["env","cwd"];function up(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?uh(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 uh(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 uf=/^[A-Za-z_][A-Za-z0-9_]*=/,um=/^[^\s:]+:/;function ug(e,t,n,r){for(let i of t??[]){let t=ut(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],ue(t[1],n,!0)])}}function ux(e,t,n,r){for(let i of t??[]){let t=ut(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,ue(s,n,!0)])}}function uv(e){if(void 0!==e&&!0!==e){if("user"===e.text)return"global";if("project"===e.text)return"project"}}function ub(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=un.test(l.text)?"http":ur.test(l.text)?"ws":"stdio")&&void 0!==c0(l.text))return c1(s.text,l.text);"http"===o&&"gemini"===t&&e.note("transport-assumed-http")}else o="streamable-http"===d?"http":d;return"sse"===o?c1(s.text,l.text):"ws"===o?{code:"websocket-transport",params:{server:s.text,url:l.text}}:"http"===o?(e.transport="http",e.url=ue(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=ue(l.parts,i,!1),e.args=a.map(e=>ue(e.parts,i,!1)),"stdio")}let uy={"-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 uj(e,t){return"env"===e?uf.test(t.text):um.test(t.text)&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(t.text)}function uk(e){e.oauth.clientSecret=[{kind:"prompt",id:"oauth.clientSecret",reason:"client-secret",label:"clientSecret",from:"",secret:!0}],e.note("client-secret-prompt")}let uw={"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"--client-secret":{name:"client-secret",kind:"flag"}};function uS(e){let t,n=cV(e)??e.text;try{t=dV(n)}catch(e){return{error:{code:"invalid-json",params:{detail:e instanceof Error?e.message:String(e)}}}}return cJ(t)?{value:t}:{error:{code:"no-servers-found"}}}let uC={"--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"}},uE={"-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 uN(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(u$(r),u$(i))}return t}function u$(e){try{return decodeURIComponent(e)}catch{return e}}function uI(e){let t=e.trim();for(let e=0;e<4;e++)try{return dV(t)}catch{let e=u$(t);if(e===t)break;t=e.trim()}}function uT(e){return{error:{code:"install-link-invalid",params:{detail:e}}}}function uM(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:uI(n);return cJ(r)?{entries:[c8(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 cJ(e)?{entries:[c8(n,e,{source:t,flavor:"vscode",rawPi:!1,inputs:c6(r)})],notes:[]}:uT("config")}function uL(e){return{error:{code:"by-name-link",params:{name:e}}}}function uz(e){let t=e.indexOf("?");return t<0?"":e.slice(t+1)}function uW(e){let t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=e.replace(/&/g,"&");try{t=new URL(r)}catch{if(/^https?:\/\/\S+$/i.test(r)&&0===n)return{entries:[uP(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 uM(uN(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 uL(u$(t[1]));if(/^mcp\/api\.mcp\.github\.com\//.test(e))return uL(e.replace(/^mcp\//,""));if(/^mcp\/install\?/.test(e))return uR(uI(uz(r)),"vscode-install-link");return uT(i)}case"vsweb+mcp":return uR(uI(uz(r)),"visual-studio-install-link");case"ghapp":if(/^\/\/mcp\/install/.test(r.slice(r.indexOf(":")+1)))return uR(uI(uz(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 uM(uN(e.search));if("vscode.dev"===r||"insiders.vscode.dev"===r){let t=uN(e.search);if(/^\/redirect\/?$/.test(i)&&t.get("url"))return uW(t.get("url"),n+1);if(/^\/redirect\/mcp\/install\/?$/.test(i)){let e=t.get("config");return e?uR(uI(e),"vscode-install-link",t.get("name")||void 0,uI(t.get("inputs")??"[]")):uT("config")}}if("aka.ms"===r&&/^\/vs\/mcp-install\/?$/i.test(i))return uR(uI(e.search.slice(1)),"visual-studio-install-link");if("github.com"===r&&/^\/copilot\/app\/launch\/?$/.test(i)){let t=uN(e.search).get("open");return t?uW(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:[uP(e,t)],notes:[]}}(t,r,n);default:return{error:{code:"unsupported-url-scheme",params:{scheme:i}}}}}let uA=new Set(["localhost","127.0.0.1","[::1]"]);function uP(e,t){let n=cy(t)||void 0;if(void 0!==c0(t))return{note:c1(n,t)};let r=new cs("url",!1);return r.transport="http",cp(r,t,!1),e?.protocol!=="http:"||uA.has(e.hostname)||r.note("insecure-http",{host:e.hostname}),{draft:r}}let uO=/[\u200B-\u200D\u2060\uFEFF]/g,uF=/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]\S*)?$/i,uB={"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 uD(e){return new Set(e.fields.flatMap(e=>e.targets.map(e=>ct(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(uO,"").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=dV(e)}catch(t){try{n=dV(`{${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 c8(n,r,t)});if(Array.isArray(e)){let r=e.filter(cX);return 0===r.length?{error:{code:"no-servers-found"}}:{entries:r.map(e=>c8(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})),notes:n}}if(!cJ(e))return{error:{code:"no-servers-found"}};let i=cJ(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?cg(t.split("/").pop()??t):void 0,r=Array.isArray(e.remotes)?e.remotes.filter(cJ):[],i=r.filter(e=>"string"==typeof e.type&&"http"===cQ(e.type)&&"string"==typeof e.url);if(0===i.length){let e=r.find(e=>"sse"===e.type);return e?[{note:c1(n,"string"==typeof e.url?e.url:void 0)}]:[{note:{code:"registry-packages-unsupported",params:c2(n)}}]}return i.map(e=>{let r=new cs("registry-server-json",!1);for(let i of(r.name=n,t&&n!==t&&(r.originalName=t),r.transport="http",r.url=c9(e.url,e.variables,"url.","registry-variable"),Array.isArray(e.headers)?e.headers.filter(cJ):[])){if("string"!=typeof i.name||""===i.name)continue;let e=i.name;"string"==typeof i.value&&""!==i.value?r.headers.push([e,c9(i.value,i.variables,`headers.${e}.`,"registry-header")]):r.headers.push([e,[c7(`headers.${e}`,e,"",i,"registry-header")]])}return{draft:r}})}(i),notes:n};if(cJ(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(cJ(e.servers)){let t=c6(e.inputs);return{entries:r(e.servers,{source:"vscode-json",flavor:"vscode",rawPi:!1,inputs:t}),notes:n}}if(cJ(e.mcp)){let t=e.mcp;if(cJ(t.servers)){let e=c6(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(cJ(e.context_servers))return{entries:Object.entries(e.context_servers).map(e=>{let t,[n,r]=e;return cJ(r)&&("extension"===r.source||!cX(r))?{note:{code:"zed-extension-server",params:{server:n}}}:c8(n,cJ(r)?(t={...r},delete t.source,t):r,{source:"zed-json",flavor:"zed",rawPi:!1})}),notes:n};if(cX(e))return{entries:[c8(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})],notes:n};let o=Object.values(e);return o.length>0&&o.every(cJ)&&o.some(cX)?{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(uF.test(l)){if(!("error"in(o=uW(`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)?uW(l):(e=cK(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&&ui[i]&&e[t+1]?.text==="mcp"&&(n=t,r=ui[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 ul(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=ud.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=ua[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?uc:uu).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 cs("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=ut(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=ue(l.parts,"pi",!1);let e=u("header");if("error"in e)return e;for(let[t,n]of e)c.headers.push([t,ue(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=ue(n.parts,"pi",!1)),r&&(c.oauth.clientSecret=ue(r.parts,"pi",!0)),i&&(c.oauth.callbackPort=Number(i.text)),o&&(c.oauth.clientName=ue(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,ue(n,"pi",!0)]);let[t,...n]=s;c.command=ue(t.parts,"pi",!1),c.args=n.map(e=>ue(e.parts,"pi",!1));let r=a("cwd");r&&(c.cwd=ue(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=cW("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 ul(function(e){let t=up("claude",e,uy,{asArgAfter:2,variadic:uj});if("error"in t)return{error:t.error};let n=new cs("claude-mcp-add",!1),r=ub(n,"claude",t.values.get("transport"),[...t.positional,...t.afterDashDash],dG);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=uv(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=ux(n,t.lists.get("header"),dG,"claude");if(r)return{error:r};let s=t.values.get("client-id");s&&!0!==s&&(n.oauth.clientId=ue(s.parts,dG,!1)),t.values.has("client-secret")&&uk(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=ug(n,t.lists.get("env"),dG,"claude");if(e)return{error:e}}return{draft:n}}(t));if("claude"===r&&"add-json"===e)return ul(function(e){let t=up("claude",e,uw,{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=uS(r);if("error"in o)return o;let s=c8(n.text,o.value,{source:"claude-mcp-add-json",flavor:"mcp-servers",rawPi:!1});return"note"in s||(s.draft.scopeHint=uv(t.values.get("scope")),t.values.has("client-secret")&&"http"===s.draft.transport&&!s.draft.oauth.clientSecret&&uk(s.draft)),s}(t));if("claude"===r&&"add-from-claude-desktop"===e)return{error:{code:"claude-desktop-import"}};if("codex"===r&&"add"===e)return ul(function(e){let t=up("codex",e,uC,{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 cs("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!==c0(l.text))return{note:c1(i.text,l.text)};a.transport="http",a.url=ue(l.parts,dY,!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=ue(n.parts,dY,!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=ug(a,r,dY,"codex");if(e)return{error:e};a.command=ue(s[0].parts,dY,!1),a.args=s.slice(1).map(e=>ue(e.parts,dY,!1))}return{draft:a}}(t));if("gemini"===r&&"add"===e)return ul(function(e){let t=up("gemini",e,uE,{asArgAfter:2});if("error"in t)return{error:t.error};let n=new cs("gemini-mcp-add",!1),r=ub(n,"gemini",t.values.get("transport"),[...t.positional,...t.afterDashDash],dX);if("string"!=typeof r)return"cli-usage"===r.code?{error:r}:{note:r};if(n.scopeHint=uv(t.values.get("scope")),"http"===r){t.lists.has("env")&&n.note("cli-option-wrong-transport",{cli:"gemini",option:"--env",transport:"http"});let e=ux(n,t.lists.get("header"),dX,"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=ug(n,t.lists.get("env"),dX,"gemini");if(e)return{error:e}}let i=t.values.get("timeout");for(let e of(i&&!0!==i&&cS(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 c3(n,o("include-tools"),o("exclude-tools")),{draft:n}}(t));if("add"===e||"install"===e)return{error:{code:"cli-unsupported",params:{cli:r}}};if(uo.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]&&us.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=uh(e[n],10)}if(!r)return{error:{code:"cli-option-needs-value",params:{cli:"code",option:"--add-mcp"}}};let o=uS(r);if("error"in o)return o;t.push(c8(void 0,o.value,{source:"vscode-add-mcp",flavor:"vscode",rawPi:!1}))}return{entries:t,notes:[]}}(e.slice(1)):ul(function(e){let t=new cs("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,ue(r.value,dY,!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=ue(i.parts,dY,!1),t.args=e.slice(n+1).map(e=>ue(e.parts,dY,!1));let o=e.slice(n+1).map(e=>e.text),s=o.some(e=>/^mcp-remote(?:@|$)/.test(e))?o.find(e=>un.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:uB[t],params:n}:{code:uB[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 cc(e);if("stdio"===e.transport&&e.command&&""!==cl(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||""===cl(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 cy(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&&cy(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=ck(t,new Set(["-p","--package","-c","--call"]));return e?cg(e):""}case"pnpm":case"yarn":case"bun":case"npm":{let e=t.findIndex(e=>"dlx"===e||"exec"===e||"x"===e),n=e>=0?ck(t.slice(e+1),new Set(["-p","--package"])):void 0;return n?cg(n):""}case"uvx":case"pipx":{let e=ck("pipx"===n&&"run"===t[0]?t.slice(1):t,new Set(["--from","--with","--python","-p","--index-url","--spec"]));return e?cg(e):""}case"uv":{let e=t.indexOf("run"),n=e>=0?ck(t.slice(e+1),new Set(["--with","--directory","--python","-p","--from","--project"])):void 0;return n?cw(n):""}case"docker":case"podman":{let e=t.indexOf("run"),n=e>=0?ck(t.slice(e+1),cj):void 0;if(!n)return"";let r=n.split("/").pop().replace(/[:@].*$/,"");return cv(r)||r}case"python":case"python3":case"py":{let e=t.indexOf("-m");if(e>=0&&t[e+1])return cg(t[e+1].replace(/_/g,"-"));let n=ck(t,new Set(["-X","-W"]));return n?cw(n):""}case"node":case"deno":case"tsx":case"ts-node":{let e=ck("deno"===n&&"run"===t[0]?t.slice(1):t,new Set(["-r","--require","--import","--loader"]));return e?cw(e):""}default:return cv(n.replace(/_/g,"-"))||n}}(e.command,t)}(r.config))&&r.notes.push({code:"name-derived",params:{name:i}});let s=(t=i,ch.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=cf(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:cf(s,[...c,...u])}}),r.name=s;let p=cW(s,function(e){let t=uD(e),n=JSON.parse(JSON.stringify(e.config));t.has(ct(["url"]))&&(n.url="https://placeholder.invalid/");let r=n.oauth;return r&&t.has(ct(["oauth","callbackUrl"]))&&delete r.callbackUrl,n}(r));if(p){a.push({code:"invalid-config",params:{server:s,...p}});continue}!function(e){let t=uD(e);for(let n of uY(e.config))t.has(ct(n))||e.notes.push({code:"literal-secret",params:{field:cn(n)}});let n=e.config;if("url"in n){for(let[t,r]of Object.entries(n.headers??{})){let n=d3(r);n.length>0&&e.notes.push({code:"header-env-reference",params:{header:t,names:n.join(", ")}})}let t=d3(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 u_=/^[A-Za-z_][A-Za-z0-9_]*$/;function uU(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 uq(e){let t=uD(e);return uY(e.config).filter(e=>cr(e)&&!t.has(ct(e)))}function uZ(e){return"string"==typeof e&&""===e.trim()?"missing":"name"}let uK=/^(?:bearer|basic|token)\s+/i;function uV(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(uq(e).map(e=>[cn(e),e])),l=[];for(let[e,t]of Object.entries(n)){let n="string"==typeof t?t.trim():"",r=s.get(e);r?u_.test(n)?l.push([r,n]):o.push({code:"field-reference-invalid",params:{field:e,problem:uZ(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():"";u_.test(r)?"select"!==n.kind&&n.targets.every(e=>cr(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:uZ(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(cn(e.path));let o=ct(e.path);if(d.has(o))continue;if(d.add(o),e.parts.some(e=>"string"!=typeof e&&void 0===i.get(e.field))){uU(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):cr(u)?d8(c.text,{atStart:p}):c.text)}uU(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(uK)?.[0]??"":"";uU(r,e,`${i}\${${t}}`)}for(let e of uY(r))a.add(cn(e));return{ok:!0,config:r,secretPaths:[...a]}}let uJ=["command","args","env","cwd","url","headers","oauth"];function uY(e){let t=[];for(let n of function(e){if(!dZ(e))return[];let t=[];for(let n of["env","headers"]){let r=e[n];if(dZ(r))for(let[e,i]of Object.entries(r))"string"==typeof i&&dK(i)&&""!==i&&(dw(e)||/^(?:bearer|basic|token)\s+\S/i.test(i)||dD(i,dR).masked)&&t.push({kind:"env"===n?"env":"header",name:e})}let n=dZ(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&""!==n&&dK(n)&&t.push({kind:"oauth-client-secret"}),"string"==typeof e.url&&dO(e.url,dW).masked&&t.push({kind:"url"}),"string"==typeof e.command&&dD(e.command,dW).masked&&t.push({kind:"command"}),Array.isArray(e.args)&&dq(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:""):[];dq(n).args.forEach((e,r)=>{e!==n[r]&&t.push(["args",r])})}}return t.sort((e,t)=>uJ.indexOf(e[0])-uJ.indexOf(t[0]))}let uG="PI_WEB_PASSWORD";function uX(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function uQ(e){return uX(e)?Object.entries(e).filter(e=>"string"==typeof e[1]):[]}function u0(e){if(!uX(e))return[];if(!("url"in e))return uQ(e.env).map(e=>{let[t,n]=e;return{kind:"env",name:t,value:n}});let t=uQ(e.headers).map(e=>{let[t,n]=e;return{kind:"header",name:t,value:n}}),n=uX(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&t.push({kind:"oauth-client-secret",value:n}),t}let u1={text:"",rawPi:!1,server:0,values:{},references:{},secretReferences:{}};function u2(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 u4(e,t){let n={...e,...t},r=u2(e.text,e.rawPi,e.server);if(void 0!==r&&r===u2(n.text,n.rawPi,e.server))return n;let i={...n,server:0,values:{},references:{},secretReferences:{}};return delete i.name,i}function u8(e){return dJ[e.code]??"warning"}function u5(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?ac(t):t;if("string"==typeof i.field&&e.code.startsWith("field-")){let e=r.find(e=>e.id===i.field);e&&(o.field=ac(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 u3={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"},u6={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"},u9=JSON.stringify({command:"uvx",args:["mcp-server-fetch"]}),u7=JSON.stringify({name:"fetch",command:"uvx",args:["mcp-server-fetch"]}),pe=[{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 '${u7}'`},{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(u9)}`},{source:"vscode-install-link",text:`vscode:mcp/install?${encodeURIComponent(u7)}`},{source:"visual-studio-install-link",text:`vsweb+mcp:/install?${encodeURIComponent(u7)}`},{source:"copilot-app-install-link",text:`ghapp://mcp/install?${encodeURIComponent(u7)}`}];function pt(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?ac(r):r.field===e.id?n:`‹${ac(t.find(e=>{let{id:t}=e;return t===r.field})?.label??r.field)}›`).join("")}))].join(", ")}function pn(e){return"select"!==e.kind&&e.targets.every(e=>cr(e.path)&&void 0===e.encoding)}let pr=/^[A-Za-z_][A-Za-z0-9_]*$/;function pi(){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 pr.test(r)?r:void 0}let po=/^(?:proxy-)?authorization$/i;function ps(e,t){let n=function(e,t){if(e.startsWith("env.")){let t=e.slice(4);return pr.test(t)?t:pi(t)}let n=function(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];return pi(t,...n)??pi(...n)};if(e.startsWith("headers.")){let t=e.slice(8);return n(po.test(t)?"TOKEN":t.replace(/^x-/i,""))}if("oauth.clientSecret"===e)return n("CLIENT_SECRET")}(e,t);return n===uG?void 0:n}function pl(e){return e.startsWith("env.")||e.startsWith("headers.")||"oauth.clientSecret"===e}function pa(e,t){let n=e;for(let e of t)n=n.split(e).join(dm);return{text:n,masked:n!==e}}function pd(e){let{kind:t,name:n}=e;return void 0===n?{kind:t}:{kind:t,name:n}}function pc(e,t){let n=t.files.find(t=>t.scope===e),r=n?.problems.find(aO);return n&&r?{kind:"file-problem",path:n.path,reason:r.reason}:void 0}function pu(e,t){return e.servers.filter(e=>e.scope===t).map(e=>e.name)}function pp(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 ph(e,t,n){switch(e.kind){case"trust-too-broad":return t(pm[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(pf[e.kind])}}let pf={"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"},pm={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 pg(e){return ac(lT(e))}function px(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}let pv=[{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"}],pb=new Set(["name-derived","name-sanitized","name-deduplicated","name-taken"]);function py(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[u8(e)]-o[u8(t)]);return(0,r.jsx)("ul",{className:"mcp-add-notes",children:s.map((e,t)=>(0,r.jsx)("li",{className:`mcp-add-note is-${u8(e)}`,children:u5(e,i,n)},`${t}\0${e.code}`))})}let pj={"server-invalid":"mcp.add.refused.server-invalid","web-password":"mcp.add.blocked.web-password"};function pk(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:pu(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=a9(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&&pn(r)?n[r.id]={reference:e}:void 0!==t.values[r.id]&&(n[r.id]=t.values[r.id])}return n}(a,t),f=uq(a).map(cn),m=Object.fromEntries(f.flatMap(e=>{let n=t.secretReferences[e];return void 0===n?[]:[[e,n]]})),g=uV(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]=pr.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=uV(e,r,Object.fromEntries(Object.entries(n).map(e=>{let[t,n]=e;return[t,pr.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:u0(r).filter(e=>{let{value:t}=e;return d5(t)}).map(pd),variableReferences:u0(r).map(e=>({...pd(e),variables:d3(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=pa(r.url,i);return{...s,transport:"http",target:ac(e.text),envNames:[],headerNames:Object.keys(r.headers??{}),masked:e.masked}}let l=pa(ah(r.command,r.args??[]),i);return{...s,transport:"stdio",target:l.text,...void 0!==r.cwd?{cwd:ac(r.cwd)}:{},envNames:Object.keys(r.env??{}),headerNames:[],masked:l.masked}}(a,h,g),y=g.ok?cW(p,g.config):void 0,j="blocked"===o.kind?o.block:v.length>0?{kind:"secret",fields:v,fixed:!v.every(pl)}:pc("project",n),k=pu(n,d),w=n.files.find(e=>e.scope===d);if(u)i={kind:"mcp-off"};else if(ch.test(p))if(k.includes(p))i={kind:"name-taken",name:p,suggestedName:cf(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 u0(e))if(t.isCommandConfigValue(n)?n.toUpperCase().includes(uG):t.getConfigValueEnvVarNames(n).some(e=>e.toUpperCase()===uG))return r}(g.config,{isCommandConfigValue:d5,getConfigValueEnvVarNames:d3}))i={kind:"web-password"};else if("project"===d&&j)i={kind:"scope",block:j};else{let e=pc(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=>pb.has(e.code)),S=k.filter(e=>!pb.has(e.code)),C=!s&&!l&&void 0===j,N=()=>{C&&c(pp(o,m))},$=e=>d({...o,...e}),I=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:ac(e.name),path:e.path?pg(e.path):"mcp.json"});case"fields":return t("mcp.add.blocked.fields",{fields:e.fields.map(ac).join(", ")});case"field-invalid":return t("mcp.add.blocked.fieldsInvalid",{fields:e.fields.map(ac).join(", ")});case"config-invalid":return u5(e.note,t,n);case"web-password":return t("mcp.add.blocked.web-password");case"scope":return ph(e.block,t,pg)}}(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)(sD,{title:p("mcp.add.title"),catalogs:pv,target:(0,r.jsxs)(sF,{value:m.scope,label:p("config.saveTo"),options:[{value:"global",label:px("global",p)},{value:"project",label:px("project",p),disabled:void 0!==y&&"project"!==m.scope}],path:pg(I),disabledReason:y?ph(y,p,pg):null,onChange:e=>$({scope:e}),children:[M&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(sV,{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:pg(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(u4(o,{text:e})),onSubmit:N,examplesLabel:p("mcp.add.examples"),examples:""===o.text.trim()?pe.map(e=>{let{source:t,text:n}=e;return{label:p(u6[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(u4(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)(py,{notes:x.notes}),x.ok&&x.servers.length>1&&(0,r.jsxs)(sz,{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=>$({server:Number(e.target.value),name:void 0,values:{},references:{},secretReferences:{}}),children:x.servers.map((e,t)=>(0,r.jsx)("option",{value:t,children:ac(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)(sz,{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=>$({name:e.target.value})})}),(0,r.jsx)(py,{notes:w,fields:v.fields}),j?.kind==="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(sV,{size:"small",onClick:()=>$({name:j.suggestedName}),children:p("mcp.add.useName",{name:ac(j.suggestedName)})})})]}),v&&b&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(sL,{children:p("mcp.add.preview")}),(0,r.jsxs)(sW,{children:[(0,r.jsx)(sA,{label:p("mcp.add.readAs"),children:p(u6[b.source])}),(0,r.jsx)(sA,{label:p("mcp.detail.transport"),children:p(`mcp.transport.${b.transport}`)}),(0,r.jsx)(sA,{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)(sA,{label:p("mcp.detail.cwd"),mono:!0,children:b.cwd}),R.length>0&&(0,r.jsx)(sA,{label:"http"===b.transport?p("mcp.detail.headers"):p("mcp.detail.env"),children:(0,r.jsx)(pw,{names:R})}),b.commandFields.length>0&&(0,r.jsx)(sA,{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=ag(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)(sA,{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:av(b.variableReferences).map(e=>{let{variable:t,field:n}=e,i=ag(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p("mcp.server.variableIn",{variable:ac(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)(py,{notes:S,fields:v.fields}),v.fields.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(sL,{children:p("mcp.add.fields")}),v.fields.map(e=>{var t;let n;return(0,r.jsx)(pS,{field:e,fields:v.fields,draft:o,suggestedName:(t=m.name,(n=e.targets[0])?ps(cn(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)(sL,{children:p("mcp.add.secrets")}),m.pasteSecrets.map(e=>{var t,n;let i;return(0,r.jsx)(pC,{label:e,draft:o,suggestedName:ps(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)&&dR(i)?i:void 0):void 0,problem:m.fieldProblems[e],onDraftChange:d},e)})]})]}),(0,r.jsx)(sV,{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(pm[e.breadth.kind],{path:pg(e.breadth.path)});if("secret-global-only"===e.reason&&e.fields)return t(e.fields.every(pl)?"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:ac(e.name),path:e.path?pg(e.path):"mcp.json"});let n=e.reason?pj[e.reason]:void 0;return n?t(n,{error:ac(e.error)}):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):ac(e.error)}(a,p)]}),a.trustKept&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.trustKept",{folder:pg(a.trust?.decisionPath??n??"")})}),a.notes&&a.notes.length>0&&(0,r.jsx)(py,{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)(sV,{size:"small",onClick:()=>$({name:a.suggestedName}),children:p("mcp.add.useName",{name:ac(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(ac).join(", ")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(sV,{variant:"danger",size:"small",disabled:s||l||void 0!==j,onClick:()=>c(pp(o,m,a.names)),children:p("mcp.add.hostEnv.confirm")})})]})]})]})}function pw(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:ac(e)},e))}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.detail.valuesHidden")})]})}function pS(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=pn(n),f=h?s.references[n.id]:void 0,m=void 0!==f,g=ac(n.label),x=s.values[n.id]??n.defaultValue??"",v=u3[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?pt(n,o,"${"+f+"}",!0):void 0:pt(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)(sz,{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:ac(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?ac(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:u5(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:ac(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:ac(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 pC(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=ac(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)(sz,{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:u5(l,d)}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p?void 0!==s?d("mcp.add.secret.storedAs",{value:ac(s)}):d("mcp.add.field.variableHint"):d("mcp.add.secret.asPasted")})]})}let pE=new Set(["done","failed","cancelled","expired"]);function pN(e){var t;return e?.flow!==void 0&&!e.gone&&(t=e.flow.phase,!pE.has(t))}let p$={"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"},pI={"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"},pM={"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,pE.has(r)&&(delete i.pasteError,delete i.cancelError,i.pasting&&(i.pasting=!1),i.cancelling&&(i.cancelling=!1)),i}function pL(e){return"sign-in-unknown"===e.reason}async function pz(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:aY(s,o.status)}}function pW(e,t,n,r,i){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},s=t.method??"GET";return aG(r=>pz(e,t,n,r),()=>({ok:!1,error:{error:`${s} ${e} did not answer within ${i} ms`,timedOut:!0}}),i,r,o)}function pA(e){return`/api/mcp/sign-in/${encodeURIComponent(e)}`}function pP(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?pI[e.reason]:void 0;return r?t(r):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function pO(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=pN(n),y=(0,i.useRef)(b);if((0,i.useEffect)(()=>{let e=y.current;y.current=b,!e&&b?sp(document,v.current):e&&!b&&sp(document,x.current)},[b]),!t.usesOAuth)return(0,r.jsx)(sA,{label:h("mcp.detail.signIn"),children:void 0!==t.authProvider?h("mcp.signIn.provider",{provider:ac(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,$=j?.phase==="finishing";return(0,r.jsx)(sA,{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:ac(j.name)})}),j&&b&&("authorize"===j.phase?(0,r.jsx)(pF,{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&&$&&(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)(pB,{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")," ",pP(n.error,h)]}),b&&n?.cancelError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.cancelFailed")," ",pP(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")," ",pP(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(p$[o])}),!o&&s&&S&&!b&&(0,r.jsx)("span",{id:m,className:"mcp-config-line is-dim",children:h(p$[s])}),(0,r.jsxs)("div",{className:"mcp-sign-in-actions",children:[b&&j?(0,r.jsx)(sV,{ref:v,size:"small",disabled:n?.cancelling===!0||$,"aria-busy":n?.cancelling===!0||void 0,"aria-describedby":$?g:void 0,onClick:()=>p(t,j.flowId),children:h(n?.cancelling?"mcp.signIn.cancelling":"mcp.signIn.cancel")}):(0,r.jsx)(sV,{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)(sV,{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 pF(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&&sp(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)(s9,{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:ac(p)})]}):(0,r.jsxs)(r.Fragment,{children:[l("mcp.signIn.authorize.notALink")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:ac(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")," ",pP(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:ac(o.error)})]})]}),t.redirectUrl&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:l("mcp.signIn.authorize.redirect",{url:ac(t.redirectUrl)})}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:l("mcp.signIn.authorize.wait")})]})}function pB(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 pM[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:ac(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:ac(t.error)})]})]})}function pD(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function pH(e){return ac(lT(e))}function p_(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 pU(e,t){return e.timedOut?t("mcp.loadTimedOut"):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function pq(e,t){return e.timedOut?t("mcp.actionTimedOut"):pU(e,t)}function pZ(){if("u"<typeof document)return null;let e=document.activeElement;return e instanceof HTMLButtonElement||e instanceof HTMLSelectElement?e:null}function pK(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)(()=>sd("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,$]=(0,i.useState)({}),I=(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,W]=(0,i.useState)({}),A=(0,i.useRef)(z);A.current=z;let[P,O]=(0,i.useState)(0),[F,B]=(0,i.useState)(!1),[D,H]=(0,i.useState)(u1),_=(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=++I.current;T.current?.abort();let n=new AbortController;T.current=n,p(!0);let r=await a2(t,void 0,n.signal);if(e===I.current){if(p(!1),!r.ok)return void c({state:"failed",error:r.error});c({state:"loaded",data:r.data,...r.projectError?{projectError:r.projectError}:{}}),f(e=>aD(aF(r.data,!!t),e))}},[t]),G=lL(s);(0,i.useEffect)(()=>(Y(),()=>{I.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 a5(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 a3(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 a6(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=aj(e);if(L.current.has(n))return;let r={};L.current.set(n,r),$(e=>({...e,[n]:{...e[n],running:!0,startedAt:Date.now(),error:void 0,queueTimedOut:void 0,configKey:void 0}}));let i=J.current,o="loaded"===i.state&&i.data.project?t:null,s=await df({scope:e.scope,name:e.name},o);if(L.current.get(n)!==r)return;L.current.delete(n),$(t=>({...t,[n]:function(e,t,n){let r=e?.signedOutAt,i={...e?.startedAt!==void 0?{startedAt:e.startedAt}:{},...void 0!==r?{signedOutAt:r}:{}};if(void 0!==r&&(e?.startedAt??0)<=r)return{running:!1,...i};let 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=>aj(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)=>{I.current+=1,T.current?.abort(),p(!1),c(t=>({state:"loaded",data:e,..."loaded"===t.state&&t.projectError?{projectError:t.projectError}:{}})),f(r=>aD(aF(e,!!t),n??r))},[t]),er=(0,i.useCallback)(async e=>{let n=aj(e),r=A.current[n];if(r?.starting||pN(r))return;W(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 pW("/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&&(W(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=aj(e);W(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 pW(pA(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirectUrl:t})},n,r,i)}(t,n);V.current&&W(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}:pL(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=aj(e);W(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 pW(pA(e),{method:"DELETE"},t,n,r)}(t);V.current&&W(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):pL(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 pN(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=A.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 pW(pA(e),{},t,n,r)}(r,void 0,e.signal);if(e.signal.aborted)return;W(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):pL(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],pN(n)&&!pN(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 di(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=aj(e),r=pZ();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=aj(e),r=pZ();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=aj(e),n=pZ();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=pZ();y(null),k(null),S({...w,undoing:!0,error:void 0});let t=await ea({action:"undo",token:w.token},"undo",e=>e.restored?aj(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=aj(e),n=pZ();y(null),k(null),W(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(W(e=>({...e,[t]:r.ok?{signedOut:{removed:r.data.signedOut?.removed===!0}}:{...e[t],signOutError:r.error}})),r.ok){let e=Date.now();$(n=>{let r=function(e,t){if(e)return{running:e.running,...void 0!==e.startedAt?{startedAt:e.startedAt}:{},signedOutAt:t}}(n[t],e);return r?{...n,[t]:r}:n})}E({control:n})}},[ea]),ef=(0,i.useCallback)(async e=>{let n=pZ(),r=_.current;y(null),k(null),q(null);let i=await ea(e,"add",e=>e.added?aj(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(u1),E({control:null,toSelectedRow:!0}),!s)return;K({...s,key:aj(s),...d&&t?{trustedFolder:t}:{}}),l&&t&&a?.(t,l);let c=i.data.servers.find(e=>aj(e)===aj(s));c&&!dl(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?dn:dt),keptOff:n?t.filter(e=>!e.enabled&&dt(e)&&!dn(e)).length:0},o=pZ();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&&sc("mcp",h,t)},[t,h]),(0,r.jsx)(pV,{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 pV(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=u1,addFailure:C=null,added:N=null,onAddOpen:$=()=>{},onAddDraftChange:I=()=>{},onAddSubmit:T=()=>{},onSelect:M,onRefresh:R,onCodemodeChange:L,onCodemodeModeChange:z=()=>{},onCodemodeInlineBudgetSave:W=()=>{},onServerSwitch:A=()=>{},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[aj(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?aF(G,!!c):[],Q=G?{mcpAvailable:G.mcp.available,projectServersLoad:ak(G.project)}:void 0,ee=X.flatMap(e=>e.servers),et=ee.find(e=>aj(e)===p),en=N?ee.find(e=>aj(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&&sp(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?sp(document,ep.current):void 0!==e&&void 0===eh&&sp(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=aB(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&&ak(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(aO))?"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)sp(document,ed.current??ec.current);else{var e,t,n;e=document,t=y.control,n=ed.current??ec.current,t&&sp(e,t.isConnected&&!t.disabled?t:n)}},[y,ey]);let ek=e=>G?a7(e,G):void 0,ew=!!G&&a9(G.mcp),eS=X.find(e=>"project"===e.scope)?.servers??[],eC=ek("project"),eE=es?.kind==="untrusted"?[p_(es,V),eC&&"mcp-off"!==eC&&eS.length>0?V(de[eC]):null].filter(Boolean).join(" "):"";return(0,r.jsxs)(sb,{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:[p_(er,V),ew&&(0,r.jsxs)(r.Fragment,{children:[" ",V(de["mcp-off"])]}),G&&!G.mcp.available&&G.mcp.detail&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:ac(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:pU(u.projectError,V)})}),es?.kind==="untrusted"&&(0,r.jsx)(s_,{id:Y,message:eE,trustLabel:V("mcp.trust.trustButton"),onTrust:el}),es?.kind==="inherited"&&(0,r.jsx)(sH,{children:p_(es,V)}),b&&(0,r.jsxs)(sH,{action:b.error?.reason==="undo-unavailable"?void 0:(0,r.jsx)(sV,{ref:ep,size:"small",onClick:B,disabled:b.undoing||ey,children:b.undoing?V("mcp.undoing"):V("mcp.undo")}),children:[V("mcp.removed",{name:ac(b.name),path:pH(b.path)}),b.error&&(0,r.jsxs)(r.Fragment,{children:[" ",V("mcp.undoFailed")," ",pq(b.error,V)]})]}),N&&G&&en&&(0,r.jsx)(pJ,{added:N,cwd:c,server:en,testing:j[N.key]?.running===!0,signIn:k[N.key],signingOut:g===`sign-out:${N.key}`,signInBlock:en?dl(en,G):void 0,onSignIn:H})]}),(0,r.jsxs)(sy,{children:[(0,r.jsxs)(sj,{children:[(0,r.jsx)(sk,{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")," ",pU(u.error,V)]}):G&&Q?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-sidebar-group",children:(0,r.jsx)(pY,{codemode:G.codemode,active:!w&&p===ay,rowRef:ed,onSelect:M})}),X.map(e=>{let t=ek(e.scope);return(0,r.jsx)(pG,{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)(sY,{ref:ec,active:w,onClick:$,children:V("mcp.add.action")})]}),(0,r.jsx)(sq,{children:(0,r.jsx)(s$,{className:"is-fill",children:G&&Q&&ev&&eb?w?(0,r.jsx)(pk,{data:G,cwd:c,draft:S,busy:"add"===g,controlsBusy:ey,failure:C,onDraftChange:I,onSubmit:T,onTrustProject:el}):p===ay?(0,r.jsx)(p7,{codemode:G.codemode,autoEnable:ev,save:m,serverBusy:null!==g,onChange:L,onModeChange:z,onInlineBudgetSave:W}):et?(0,r.jsx)(p1,{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===aj(et)?x.failure:null,test:(s=j[aj(et)],s&&void 0!==s.configKey&&s.configKey!==et.configKey?{running:s.running,...s.response?{response:s.response}:{}}:s),testBlock:dl(et,G),signIn:k[aj(et)],signInBlock:dl(et,G),signOutBlock:(d=a7(et.scope,G))||(void 0===et.invalidError&&et.validated?void 0:"invalid"),onSwitch:A,onExposureChange:P,onRemove:F,onTest:D,onSignIn:H,onSignOut:_,onSignInPaste:U,onSignInCancel:q},aj(et)):(0,r.jsx)(sU,{children:"mcp.empty"===eb?V(eb,{globalPath:pH(ex?.path??"~/.pi/agent/mcp.json")}):V(eb)}):null})})]}),(0,r.jsxs)(sZ,{status:em.length>0?(0,r.jsx)(sK,{tone:em.some(e=>{let{problem:t}=e;return aO(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=ab(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)(sK,{summary:eg.total>0?V("mcp.serverCount",{enabled:eg.enabled,total:eg.total}):""}),children:[!f&&(0,r.jsx)(sV,{onClick:K,children:V("i18n.close")}),(0,r.jsx)(sV,{variant:"secondary",onClick:R,disabled:ey,children:V("i18n.refresh")})]})]})}function pJ(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=ac(t.name),p="project"===t.scope&&n?ac(lM(t.path,n)):pH(t.path),h=i.status,f=!o&&h?.origin==="test"&&"needs-auth"===h.state&&i.usesOAuth,m=s?.starting===!0||pN(s);return(0,r.jsxs)(sH,{action:!f||m||l||a?void 0:(0,r.jsx)(sV,{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 pY(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(aK[l]);return(0,r.jsxs)(sE,{ref:n?i:void 0,active:n,"aria-label":s("mcp.codemode.rowLabel",{state:a}),onClick:()=>o(ay),children:[(0,r.jsx)(sG,{...aT(aV(l))}),(0,r.jsx)(sN,{className:"is-grow",children:s("mcp.codemode.title")}),(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${aV(l)}`,children:a})]})}function pG(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}=aB(o.servers),b=(t=o.servers).some(e=>e.enabled&&dt(e))&&t.every(e=>e.enabled||!dn(e)),y=function(e){if(!(e.servers.length>0))return e.file?e.file.problems.some(aO)?"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")} ${pq(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`${ac(t)}: ${pq(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)(sw,{aside:v>0?(0,r.jsx)(sS,{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:pD(o.scope,g)}),onChange:e=>m(o.scope,o.servers,e)}):void 0,children:pD(o.scope,g)}),j&&(0,r.jsx)(sC,{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=aj(e),n=aw(e,s),i=aI(n),o=a$[n],d=ac(e.name);return(0,r.jsxs)(sE,{ref:l===t?a:void 0,active:l===t,"aria-label":g("mcp.rowLabel",{name:d,state:g(aE(n,e.status))}),onClick:()=>f(t),children:[(0,r.jsx)(sG,{...aT(i)}),(0,r.jsx)(sN,{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 pX(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=ag(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function pQ(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:ac(e)},e))})}function p0(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:ac(t.invalidError??"")})]});let o=aN[n];return o?(0,r.jsx)("span",{className:"mcp-config-line",children:i(o)}):null}function p1(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)(),$=(0,i.useId)(),I=(0,i.useId)(),T=aw(t,n),M=aI(T),R=af(t),L=void 0===t.invalidError,z="http"===t.transport||void 0===t.transport&&void 0!==t.url,W=!z&&("stdio"===t.transport||void 0!==t.command),A=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"===a_(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=aj(t),F=ac(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)(s$,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(sI,{children:[(0,r.jsxs)(sT,{children:[(0,r.jsx)(sP,{scope:t.scope,children:pD(t.scope,N)}),(0,r.jsx)(sR,{children:F})]}),(0,r.jsxs)(sM,{children:[(0,r.jsx)(p6,{server:t,test:h,testBlock:f,describedBy:I,onTest:j}),(0,r.jsx)(sV,{variant:"danger",size:"small",disabled:u||void 0!==a,"aria-describedby":a?$:void 0,onClick:()=>y(t),children:c===`remove:${O}`?N("i18n.removing"):N("i18n.remove")}),(0,r.jsx)(sJ,{checked:t.enabled,disabled:u||void 0!==a||D||B,loading:c===`switch:${O}`,describedBy:H?$: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:$,className:"config-detail-heading-note",children:H})]}),p&&(0,r.jsxs)("p",{role:"alert",className:"mcp-config-line is-error",children:[N("mcp.actionFailed")," ",pq(p,N)]}),(0,r.jsxs)(sW,{children:[(0,r.jsx)(sA,{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(aE(T,t.status))}),(0,r.jsx)(p0,{server:t,state:T}),t.webPasswordField&&(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[N("mcp.server.webPassword")," ",(0,r.jsx)(pX,{fields:[t.webPasswordField]})]})]})}),(0,r.jsx)(p9,{server:t,test:h,testBlock:f,testBlockId:I}),void 0!==t.description&&(0,r.jsx)(sA,{label:N("mcp.detail.description"),tone:"plain",children:ac(t.description)}),t.transport&&(0,r.jsx)(sA,{label:N("mcp.detail.transport"),children:N(`mcp.transport.${t.transport}`)}),void 0!==R&&(0,r.jsx)(sA,{label:z?N("mcp.detail.url"):N("mcp.detail.command"),tone:"plain",mono:!0,children:R}),W&&void 0!==t.cwd&&(0,r.jsx)(sA,{label:N("mcp.detail.cwd"),mono:!0,children:ac(t.cwd)}),W&&t.envNames.length>0&&(0,r.jsx)(sA,{label:N("mcp.detail.env"),children:(0,r.jsx)(pQ,{names:t.envNames})}),z&&t.headerNames.length>0&&(0,r.jsx)(sA,{label:N("mcp.detail.headers"),children:(0,r.jsx)(pQ,{names:t.headerNames})}),L&&t.commandFields.length>0&&(0,r.jsx)(sA,{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)(pX,{fields:t.commandFields})]})}),L&&t.variableReferences.length>0&&(0,r.jsx)(sA,{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(ax(t))}),(0,r.jsx)("span",{className:"mcp-config-chips",children:av(t.variableReferences).map(e=>{let{variable:t,field:n}=e,i=ag(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)(pO,{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)(sA,{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?$: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:aA.map(e=>(0,r.jsx)("option",{value:e,children:"codemode"===e?N("mcp.exposure.optionDefault",{label:N(aP[e])}):N(aP[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(aW[t.exposure])}),void 0!==t.toolExposureCount&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:N("mcp.exposure.toolOverrides",{count:t.toolExposureCount})}),A&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p_(A,N)})]})}),(0,r.jsx)(sA,{label:N("mcp.detail.file"),tone:"dim",mono:!0,children:pH(t.sourcePath)})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[am(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 p2(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:ac(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(ac).join("\n")})]})]})}function p4(e){let{status:t}=e;return"session"===t.origin?(0,r.jsx)(p5,{status:t}):(0,r.jsx)(p8,{status:t})}function p8(e){let{status:t}=e,{t:n,locale:i}=(0,E.s)(),o=t.timedOut?{key:dd.timedOut,tone:"error"}:{key:dd[t.state],tone:aI(t.state)},s=aM(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?du:dc)[t.timedOut?"timedOut":t.state],{count:t.toolCount,seconds:dp(t.durationMs),time:s})]}),(0,r.jsx)(p2,{error:t.error,stderr:t.stderr}),l&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.test.serverInfo",{name:ac(l.title??l.name),version:ac(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:dp(t.queuedMs)})})]})}function p5(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:az[t.state]},s=aM(t.updatedAt,i),l=void 0===t.closedAt?void 0:aM(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":aL[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)(p2,{error:t.error,stderr:t.stderr})]})}function p3(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:ac(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(aP[e.exposure])})]}),e.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:ac(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 p6(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&&sp(document,d.current)},[c]),(0,r.jsx)(sV,{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 p9(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)(sA,{label:s("mcp.detail.connection"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[l?(0,r.jsx)(p4,{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?da[e.reason]:void 0;return n?t(n):pU(e,t)}(n.error,s)]}),i&&(0,r.jsx)("span",{id:o,className:"mcp-config-line is-dim",children:s(ds[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)(sA,{label:s("mcp.detail.listedTools"),tone:"plain",children:(0,r.jsx)(p3,{status:l,serverExposure:t.exposure})})]})}function p7(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"===a_(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:aU[t.preference],params:{path:t.settingsPath}}}(t);return(0,r.jsxs)(s$,{children:[(0,r.jsx)(sI,{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)(sW,{children:[(0,r.jsx)(sA,{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)(sO,{value:u,label:d("mcp.codemode.title"),options:[{value:"automatic",label:d(aK.automatic),disabled:p},{value:"always",label:d(aK.always),disabled:p||void 0!==m}],disabledReason:m?p_(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:ac(t.preferenceError??"")})]}),h.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[d("mcp.codemode.saveFailed")," ",(0,r.jsx)(he,{error:h.error})]}),x&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p_(x,d)}),f&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p_(f,d)})]})}),t.mode?(0,r.jsx)(ht,{mode:t.mode,codemode:t,save:i,waiting:p,onChange:l}):void 0!==t.modeError&&(0,r.jsx)(sA,{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:ac(t.modeError)})]})}),t.inlineBudget?(0,r.jsx)(hn,{budget:t.inlineBudget,save:i,waiting:p,onSave:a}):void 0!==t.inlineBudgetError&&(0,r.jsx)(sA,{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:ac(t.inlineBudgetError)})]})}),(0,r.jsx)(sA,{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:ac(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)(sA,{label:d("mcp.codemode.builtin"),tone:"error",children:p_(g,d)})]})]})}function he(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:ac(t.error)})}function ht(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:aZ[r.value],params:{path:r.settingsPath}}),"only"===(r??t).value&&"automatic"===a_(e)&&n.push({key:"mcp.codemode.toolMode.automaticNote"}),n}(n);return(0,r.jsx)(sA,{label:l("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)(sO,{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(aq[t.value])}),d.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p_(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)(he,{error:i.error})]})]})})}function hn(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&&sp(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)(sA,{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)(sV,{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:p_(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)(he,{error:s.error})]})]})})}let hr=[{kind:"ui",label:"settings.uiFontFamily",placeholder:"settings.uiFontPlaceholder",reset:"settings.resetUiFont",weightLabel:"settings.uiFontWeight"},{kind:"mono",label:"settings.monoFontFamily",placeholder:"settings.monoFontPlaceholder",reset:"settings.resetMonoFont",weightLabel:"settings.monoFontWeight"}];function hi(){let{t:e}=(0,E.s)(),t=ir();return(0,r.jsx)("div",{className:"settings-font-rows",children:hr.map(n=>{let{kind:i,label:o,placeholder:s,reset:l,weightLabel:a}=n,d=t[`${i}Weight`],c=rZ.findIndex(e=>e.value===d);return(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option settings-font-row",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header settings-font-header",children:[(0,r.jsx)("label",{htmlFor:`settings-font-${i}`,children:e(o)}),(0,r.jsx)("input",{id:`settings-font-${i}`,className:`settings-font-input${"mono"===i?" is-mono":""}`,type:"text",value:t[i],placeholder:e(s),maxLength:500,"aria-describedby":"settings-typography-description",autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,onChange:e=>t.setFontPreference(i,e.target.value)}),(0,r.jsx)("output",{htmlFor:`settings-font-${i}-weight`,children:d}),(0,r.jsx)(sV,{variant:"ghost",size:"small",className:"settings-chat-reset",title:e(l),"aria-label":e(l),disabled:!t[i]&&400===d,onClick:()=>t.resetFontPreference(i),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:`settings-font-${i}-weight`,type:"range",min:rZ[0].value,max:rZ[rZ.length-1].value,step:100,value:d,"aria-label":e(a),"aria-valuetext":`${d} ${e(rZ[c].label)}`,onChange:e=>t.setFontWeight(i,Number(e.target.value))})]},i)})})}function ho(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 hs(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}=nu(),{width:h,setWidth:f,fontSize:m,setFontSize:g}=rq(),x=rT(),[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,$]=(0,i.useState)(!1),[I,T]=(0,i.useState)(null),[M,R]=(0,i.useState)(!1),[L,z]=(0,i.useState)(!1),[W,A]=(0,i.useState)("");(0,i.useEffect)(()=>{C(n$()),fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>R(e?.enabled===!0)).catch(()=>{})},[]);let P=async()=>{z(!0),A("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.replace("/login")}catch{A(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 i4(t,{type:"reload"}),n())}catch(e){w(e instanceof Error?e.message:String(e))}finally{j(!1)}},F=async()=>{if(!N){$(!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 lI(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{$(!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:t5.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)(se,{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.typography")}),(0,r.jsx)("p",{id:"settings-typography-description",className:"settings-general-description",children:c("settings.fontDescription")}),(0,r.jsxs)("div",{className:"settings-chat-options",children:[(0,r.jsx)(hi,{}),(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)(sV,{variant:"ghost",size:"small",className:"settings-chat-reset",title:c("settings.resetChatContentFontSize"),"aria-label":c("settings.resetChatContentFontSize"),disabled:14===m,onClick:()=>g(14),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:"settings-chat-content-font-size",type:"range",min:12,max:24,step:1,value:m,onChange:e=>g(Number(e.target.value))})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-width",children:c("settings.chatContentWidth")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-width",children:[h,"px"]}),(0,r.jsx)(sV,{variant:"ghost",size:"small",className:"settings-chat-reset",title:c("settings.resetChatContentWidth"),"aria-label":c("settings.resetChatContentWidth"),disabled:820===h,onClick:()=>f(820),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:"settings-chat-content-width",type:"range",min:820,max:2e3,step:10,value:h,onChange:e=>f(Number(e.target.value))})]})]})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.chat")}),(0,r.jsxs)("div",{className:"settings-chat-options",children:[(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:c("settings.thinkingExpandedDefault")}),(0,r.jsx)(sJ,{checked:S,label:c("settings.thinkingExpandedDefault"),onChange:e=>{window.localStorage.setItem(nE,String(e)),window.dispatchEvent(new Event(nN)),C(e)}})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:c("settings.quoteSelection")}),(0,r.jsx)(sJ,{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:()=>rI("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:()=>rI("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)(sJ,{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")})]}),I&&(0,r.jsx)("p",{role:"status",className:"settings-general-error",style:"ok"===I.kind?{color:"var(--accent)"}:void 0,children:I.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)(sV,{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")]}),W&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:W})]})]})}let hl={en:"Archives","zh-CN":"归档","zh-TW":"封存"};function ha(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:hl[f]??hl.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:si(e.id)})),y=si(m);(0,i.useEffect)(()=>sa(o),[o]),(0,i.useEffect)(()=>{var e;let t;return e=document,t=e=>{"Escape"!==e.key||e.defaultPrevented||su(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")),sa("general"))},[t,y]);let k=e=>{v(t=>new Set(t).add(e)),g(e),sa(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)(ho,{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)(hs,{sessionId:n,onSessionReloaded:l,quoteSelectionEnabled:a,onQuoteSelectionChange:d})),w("models",(0,r.jsx)(lN,{embedded:!0,cwd:t,onClose:s})),w("archives",(0,r.jsx)(as,{embedded:!0,onClose:s})),t&&w("skills",(0,r.jsx)(lB,{embedded:!0,cwd:t,trust:c,onClose:s},t)),t&&w("agents",(0,r.jsx)(lQ,{embedded:!0,cwd:t,sessionId:n,trust:c,onClose:s,onReloaded:l},t)),t&&w("plugins",(0,r.jsx)(an,{embedded:!0,cwd:t,sessionId:n,trust:c,onClose:s,onReloaded:l},t)),w("mcp",(0,r.jsx)(pK,{embedded:!0,cwd:t,trust:c,onTrustProject:u,onProjectTrustChanged:p,onClose:s},t??""))]})]})})}let hd="project-trust-mcp-status";function hc(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)(hu,{cwd:t,busy:n,error:o,listing:d,onCancel:s,onConfirm:l})}function hu(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(),su(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:ac(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:ac(s.statusError)})]}),(0,r.jsx)(hh,{listing:s})]})]}),o&&(0,r.jsx)(hp,{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?hd:void 0,children:d(n?"trust.trusting":"trust.trustProject")})]})]})})}function hp(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:ac(t.error)})]})}function hh(e){let{listing:t}=e,{t:n}=(0,E.s)();if("loading"===t.state)return(0,r.jsx)("p",{id:hd,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:ac(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)(hf,{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)(hx,{server:e},e.name))})]}):null}function hf(e){let{file:t}=e,{t:n}=(0,E.s)();return(0,r.jsx)(r.Fragment,{children:t.problems.map(e=>{let i=ab(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 hm(e){let{fields:t}=e,{t:n}=(0,E.s)();return(0,r.jsx)(r.Fragment,{children:t.map(e=>{let t=ag(e);return(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function hg(e){let{server:t}=e,{t:n}=(0,E.s)();return(0,r.jsx)(r.Fragment,{children:av(t.variableReferences).map(e=>{let{variable:t,field:i}=e,o=ag(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 hx(e){let{server:t}=e,{t:n}=(0,E.s)(),i=af(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:ac(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:ac(t.cwd)})}),am(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:ac(t.invalidError)})]}),t.webPasswordField&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[n("mcp.server.webPassword")," ",(0,r.jsx)(hm,{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)(hm,{fields:t.commandFields})]}),o&&t.variableReferences.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[n(ax(t))," ",(0,r.jsx)(hg,{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 hv(e){return"message"===e.type&&"message"in e&&"system"!==e.message.role}function hb(e){let t=e,n=t.branchPreview,r=hv(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&hv(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function hy(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 hj(e){let{node:t,activePathIds:n,depth:i,isLast:o,parentLines:s,onSelect:l}=e,{node:a,skipped:d,branchPreview:c,labelEntry:u}=hb(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&&hv(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:hv(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)(hj,{node:e,activePathIds:n,depth:i+1,isLast:t===a.children.length-1,parentLines:[...s,!o],onSelect:l},e.entry.id))]})}function hk(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?hy(t)?null:f("i18n.noBranches"):f("i18n.noActiveSession"),N=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=hb(e[0]).node;return t.children.length>1?t.children:[]}(t),$=!C&&N.length>0,I=(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:$?"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:[I,!u&&(0,r.jsx)("span",{children:f("i18n.branches")})]}),x&&b&&(0,r.jsx)("div",{style:{position:"fixed",top:b.top,left:b.left,width:b.width,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",zIndex:500},children:$?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(hj,{node:e,activePathIds:j,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:w},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C})})]}):(0,r.jsxs)("div",{style:{borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>g(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"5px 12px",background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",fontSize:11,textAlign:"left"},children:[I,(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:f("i18n.branches")}),T]}),x&&(0,r.jsx)("div",{style:{position:"absolute",top:"100%",left:0,right:0,background:"var(--bg)",borderBottom:"1px solid var(--border)",boxShadow:"0 4px 12px rgba(0,0,0,0.1)",zIndex:100},children:$?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(hj,{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 hw(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 hS(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e)}catch{return String(e)}}function hC(e){let{children:t}=e;return(0,r.jsx)("div",{className:"tool-definitions-empty",children:t})}function hE(e){let{loading:t,tools:n,translate: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 hS(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(hS).join(", "):void 0,defaultValue:void 0===i.default?void 0:hS(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)(hC,{children:o("tools.noTools")}):(0,r.jsx)(hC,{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)(hC,{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 hN(e){return e.name||e.firstMessage||e.id.slice(0,12)}function h$(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 hI(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||hN(t),p=n?hN(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)(h$,{status:c}),(0,r.jsx)("span",{children:a(`agentSwitcher.status.${c}`)})]})})]})}function hT(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)(hI,{session:t,main:!0,selected:t.id===o,running:s.has(t.id),onSelect:()=>l(t)}),h.map(e=>(0,r.jsx)(hI,{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 hM=n(63606),hR=n(8422);async function hL(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 hz(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=()=>{let e=getComputedStyle(s);return{fontFamily:e.getPropertyValue("--font-mono").trim()||"monospace",fontWeight:rJ(e.getPropertyValue("--font-mono-weight"))}},S=new hR.B({cursorBlink:!0,...j(),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=S;let C=new hM.Y;S.loadAddon(C),S.open(s),S.attachCustomKeyEventHandler(e=>{if("keydown"!==e.type)return!0;let t=e.key.toLowerCase();return!((e.ctrlKey||e.metaKey)&&"v"===t||(e.ctrlKey||e.metaKey)&&"c"===t&&S.hasSelection())});let E=(e=e=>{l||(b=!0,S.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 hL(`/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=E;let N=S.onData(e=>{!g||x||b||E.write(e)}),$=()=>{s.offsetWidth&&s.offsetHeight&&C.fit()},I=S.onResize(e=>{let{cols:t,rows:n}=e;!g||x||b||E.resize(t,n)}),T=new ResizeObserver($);T.observe(s);let M=r6(()=>{if(l)return;let e=j();S.options.fontFamily=e.fontFamily,S.options.fontWeight=e.fontWeight,$()}),R=()=>{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)S.reset();else if(void 0!==t&&n.offset<=t)return;S.write(n.data),t=n.offset}else x=!0,g=!1,S.options.disableStdin=!0,a?.close(),k("exit"===n.type?n.exitCode:null),v("exited")},a.onopen=()=>{g=!0,!b&&(S.options.disableStdin=!1,v("ready"),$(),E.resize(S.cols,S.rows),s.offsetWidth&&s.offsetHeight&&S.focus())},a.onerror=()=>{l||x||(g=!1,S.options.disableStdin=!0,v(a?.readyState===EventSource.CLOSED?"error":"connecting"))})};f.current=(async()=>{$(),u||w>0?await hL(`/api/terminal/${encodeURIComponent(d)}`):await hL("/api/terminal",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:d,cwd:c,cols:S.cols,rows:S.rows})}),R()})().catch(e=>{l||(y(e.message),v("error"))});let L=()=>{g=!1,S.options.disableStdin=!0,a?.close(),x||b||v("connecting")},z=e=>{e.persisted&&R()};return window.addEventListener("pagehide",L),window.addEventListener("pageshow",z),window.addEventListener("offline",L),window.addEventListener("online",R),()=>{l=!0,a?.close(),E.stop(),T.disconnect(),M(),N.dispose(),I.dispose(),window.removeEventListener("pagehide",L),window.removeEventListener("pageshow",z),window.removeEventListener("offline",L),window.removeEventListener("online",R),S.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 hL(`/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 hW="pi-web:terminal-tabs";function hA(e){return{id:Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join(""),cwd:e}}function hP(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let hO=[48,120,240,420,720],hF="pi-web:tab-open-session";function hB(){try{return window.sessionStorage}catch{return null}}function hD(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 hH(e,t){t.setItem(hF,JSON.stringify(e))}function h_(e){return`parked-new:${e}`}function hU(){let e,t,n,l,a,d,c,u,p,f,m,g,x,w=(0,o.useRouter)(),S=(0,o.useSearchParams)(),[C,$]=(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")}});nu(),ir();let{locale:T,t:M}=(0,E.s)(),R=e$(),L=(0,i.useSyncExternalStore)(eC,eE,eN);(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:hP(),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>=hO.length){i=!1;return}let n=hO[e++],s=window.setTimeout(()=>{r.delete(s),o(),t()},n);r.add(s)};t()})()},l=()=>{hP()&&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&&lI(T)},[T]);let{soundEnabled:z,onSoundToggle:W,playDoneSound:A,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&&A()},[A,O]),[U,q]=(0,i.useState)(null),Z=(0,i.useRef)(U);Z.current=U;let[K,V]=(0,i.useState)([]),J=(0,i.useCallback)(e=>{V(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})},[]),Y=(0,i.useMemo)(()=>U?[...K.filter(e=>e.id!==U.id),U]:K,[U,K]),X=(0,i.useMemo)(()=>{var e;return(e=U?.id)?h(Y).find(t=>t.root.id===e||t.subagents.some(t=>t.id===e))??null:null},[U?.id,Y]),Q=!!X?.subagents.length,[ee,et]=(0,i.useState)(()=>new Set),en=(0,i.useCallback)(e=>{et(t=>t.size===e.size&&[...e].every(e=>t.has(e))?t:e)},[]),[er,eo]=(0,i.useState)(null),[es,el]=(0,i.useState)("initial"),ea=(0,i.useRef)(null),[ed,ec]=(0,i.useState)(()=>C.requestedCwd?"validating":"idle"),[eu,ep]=(0,i.useState)(null),[eh,ef]=(0,i.useState)(0),[em,eg]=(0,i.useState)(0),ex=(0,i.useRef)(new Map),ev=(0,i.useCallback)((e,t)=>{ex.current.set(e,t)},[]),[eb,ey]=(0,i.useState)(null),ej=(0,i.useCallback)(e=>{ey(t=>t===e?null:t)},[]),[ek,ew]=(0,i.useState)(0),[eS,eI]=(0,i.useState)(null),[eT,eM]=(0,i.useState)(0),[eR,eL]=(0,i.useState)(null),[ez,eW]=(0,i.useState)(!1),[eA,eP]=(0,i.useState)(!1),[eO,eF]=(0,i.useState)(null),[eB,eD]=(0,i.useState)(()=>!C.sidebarCollapsed),eH=(0,i.useRef)(!C.sidebarCollapsed),[e_,eU]=(0,i.useState)(!1),[eq,eZ]=(0,i.useState)(!1),eK=e_&&eq&&!R;(0,i.useEffect)(()=>{(!e_||R)&&eZ(!1)},[e_,R]);let[eV,eJ]=(0,i.useState)(!1),[eY,eX]=(0,i.useState)(!1),eQ=(0,i.useRef)(260),e0=(0,i.useRef)(560),e1=(0,i.useCallback)(()=>N(.42*window.innerWidth,360,640),[]),e2=(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:e_,rightPanelWidth:e0.current}),[e_]),e4=(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:eB,sidebarWidth:eQ.current}),[eB]),e8=I({ariaLabel:M("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:e2,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"pi-sidebar-width",widthRef:eQ}),e5=I({ariaLabel:M("layout.resizeFilePanel"),cssVariable:"--right-panel-width",defaultWidth:560,getDefaultWidth:e1,getMaxWidth:e4,growthDirection:"left",maxWidth:1200,minWidth:300,storageKey:"pi-right-panel-width",widthRef:e0}),e3=e8.reclampWidth,e6=e5.reclampWidth;(0,i.useEffect)(()=>{eD(!R&&eH.current)},[R]),(0,i.useEffect)(()=>{eX(!0)},[]),(0,i.useEffect)(()=>{e_&&(e3(),e6())},[e6,e3,e_]);let e9=(0,i.useRef)(null),[e7,te]=(0,i.useState)(null),tt=(0,i.useRef)(null),tn=(0,i.useRef)(null),[tr,ti]=(0,i.useState)([]),[to,ts]=(0,i.useState)(null),[tl,ta]=(0,i.useState)(!1),td=(0,i.useRef)(null),tc=hy(tr),tu=(0,i.useCallback)((e,t,n,r)=>{ti(e),ts(t),ta(r),td.current=n},[]),tp=(0,i.useCallback)(e=>{td.current?.(e)},[]),[th,tf]=(0,i.useState)(null),[tm,tg]=(0,i.useState)(null),[tx,tv]=(0,i.useState)(!1),tb=(0,i.useRef)(null),ty=(0,i.useRef)(0),tj=(0,i.useRef)(null),tk=(0,i.useCallback)(e=>{tf(e),tv(!1)},[]),tw=(0,i.useCallback)(e=>{tg(e)},[]),tS=(0,i.useCallback)(e=>{ty.current+=1,tb.current=e,tv(!1)},[]),[tC,tE]=(0,i.useState)(null),[tN,t$]=(0,i.useState)({kind:"idle"}),tI=(0,i.useRef)(null),tT=(0,i.useRef)(U?.id??null);tT.current=U?.id??null;let tM=(0,i.useCallback)(e=>{tE(e)},[]),[tR,tL]=(0,i.useState)(null),tz=(0,i.useRef)(null),tW=(0,i.useCallback)((e,t)=>{np(t).then(()=>{tz.current&&clearTimeout(tz.current),tL(e),tz.current=setTimeout(()=>tL(null),1400)})},[]);(0,i.useEffect)(()=>()=>{tz.current&&clearTimeout(tz.current),tI.current&&clearTimeout(tI.current)},[]);let[tA,tP]=(0,i.useState)(null),tO=(0,i.useCallback)(e=>{tP(e)},[]),[tF,tB]=(0,i.useState)(null),[tD,tH]=(0,i.useState)(null);(0,i.useEffect)(()=>{tc||tB(e=>"branches"===e?null:e)},[tc]),(0,i.useEffect)(()=>{Q||tB(e=>"agents"===e?null:e)},[Q]),(0,i.useEffect)(()=>{eK&&tB(null)},[eK]);let t_=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];R&&eD(!1),tB(t=>t===e?null:e),R&&L&&t&&eJ(!0)},[R,L]),tU=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=tF!==e;if(t_(e,t),!n||tx)return;let r=tb.current;if(!r)return;let i=++ty.current;tv(!0),r().catch(e=>{console.error("Failed to load system information:",e)}).finally(()=>{ty.current===i&&tv(!1)})},[tF,tx,t_]),tq=(0,i.useCallback)(()=>{R&&eD(!1),eJ(!1),tB("session")},[R]),tZ=(0,i.useCallback)(e=>{eI(e)},[]),tK=(0,i.useCallback)(()=>{R&&(tB(null),eJ(!1)),eD(e=>{let t=!e;return R||(eH.current=t),t})},[R]),tV=(0,i.useCallback)(()=>{eD(!1),tB(null),eJ(e=>!e)},[]),tJ=(0,i.useCallback)(()=>{R&&(eD(!1),tB(null),eJ(!1)),eU(e=>!e)},[R]),tY=(0,i.useCallback)(()=>{tB(null),eZ(e=>!e)},[]);(0,i.useEffect)(()=>{if(!eV)return;let e=e=>{let t=tn.current;t&&e.composedPath().includes(t)||eJ(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),eJ(!1))};return document.addEventListener("pointerdown",e,!0),document.addEventListener("keydown",t,!0),()=>{document.removeEventListener("pointerdown",e,!0),document.removeEventListener("keydown",t,!0)}},[eV]),(0,i.useEffect)(()=>{eJ(!1)},[R,L,U?.id,es]),(0,i.useEffect)(()=>{if(!tF||!tt.current)return;let e=()=>{let e=tt.current.getBoundingClientRect();"agents"===tF?tH({top:e.bottom,left:e.left,width:Math.min(420,e.width)}):tH({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(tt.current),()=>t.disconnect()},[tF,R]);let[tG,tX]=(0,i.useState)([]),[tQ,t0]=(0,i.useState)(null),[t1,t2]=(0,i.useState)([]),[t4,t8]=(0,i.useState)(!1),t5=[...tG,...t1.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(hW));t2(e.tabs),e.activeId&&(t0(e.activeId),eU(e.open))}catch{}t8(!0)},[]),(0,i.useEffect)(()=>{if(t4)try{window.sessionStorage.setItem(hW,JSON.stringify({tabs:t1.map(e=>{let{id:t,cwd:n}=e;return{id:t,cwd:n}}),activeId:tQ,open:e_}))}catch{}},[t1,tQ,e_,t4]);let t3=(0,i.useCallback)((e,t,n)=>{tX(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))},[]),t6=(0,i.useCallback)((e,t)=>{e9.current?.insertText(ei(e,t)),R&&(eU(!1),eD(!1))},[R]),t9=(0,i.useCallback)(e=>{let t=e.map(e=>ei(e,!1)).join("");t&&e9.current?.insertText(t),R&&(eU(!1),eD(!1))},[R]),t7=(0,i.useCallback)((e,t,n)=>{let r,i,o,s;e9.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&&(eU(!1),eD(!1))},[R]),ne=C.sessionId,[nt,nn]=(0,i.useState)(null),nr=(0,i.useRef)(null),[ni,no]=(0,i.useState)(()=>!ne);(0,i.useLayoutEffect)(()=>{var e;let t=(e=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:hB();if(!e)return null;try{return hD(e.getItem(hF))}catch{return null}}(),C.requestedCwd||C.sessionId||!e?C:"session"===e.kind?{...C,sessionId:e.sessionId}:{...C,requestedCwd:e.cwd});t!==C&&($(t),t.sessionId&&no(!1))},[C]);let ns=(0,i.useRef)(!1),nl=(0,i.useRef)(0),na=(0,i.useCallback)(()=>{nl.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??nr.current??k(U),U.id),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:hB();if(t&&e)try{hH({kind:"session",sessionId:e},t)}catch{}}(U.id);return}er&&function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:hB(),n=e.trim();if(t&&n)try{hH({kind:"new",cwd:n},t)}catch{}}(er)},[er,U]),(0,i.useEffect)(()=>{let e=C.requestedCwd;if(!e)return;let t=new AbortController;return ec("validating"),ep(null),fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e}),signal:t.signal}).then(async t=>{let n=await t.json().catch(()=>({}));if(!t.ok||!n.cwd)throw Error(n.error??`HTTP ${t.status}`);ns.current=!0;let r=`initial:${e}`;el(r),ea.current=`new:${r}:${n.cwd}`,eo(n.cwd),ec("ready"),new URLSearchParams(window.location.search).get("cwd")||w.replace(`?cwd=${encodeURIComponent(n.cwd)}`,{scroll:!1})}).catch(e=>{t.signal.aborted||(ep(e instanceof Error?e.message:String(e)),ec("error"))}),()=>t.abort()},[C,w]);let nd=(0,i.useCallback)((e,t)=>{let n=++nl.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!==nl.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=ea.current;s&&rm(s,h_(t)),ea.current=null,q(o),eg(e=>e+1),new URLSearchParams(window.location.search).get("session")!==o.id&&w.replace(`?session=${encodeURIComponent(o.id)}`,{scroll:!1})};K.length>0?i({sessions:K}):fetch("/api/sessions").then(e=>e.ok?e.json():null).then(i).catch(()=>{})},[w,K]),nc=(0,i.useCallback)((e,t,n)=>{na();let r=er??nt;if(nn(e),!e)return;let i=n??t??e,o=nr.current??(U?k(U):null);if(nr.current=i,ns.current){ns.current=!1;return}if(r===e&&o!==i||o===i&&(null!==U||r===e))return;let s=ea.current;s&&r&&rm(s,h_(r));let l="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,a=`new:${l}:${e}`;rm(h_(e),a),el(l),ea.current=a,q(null),eo(t=>t&&t!==e?null:t),eg(e=>e+1),ti([]),ts(null),ta(!1),tf(null),tg(null),tv(!1),tB(null),o!==i&&(tX([]),(!tQ||tQ.startsWith("file:"))&&(t0(null),eU(!1)),nd(i,e)),w.replace(window.location.pathname,{scroll:!1})},[nt,tQ,na,er,w,U,nd]),nh=(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;ey(n?{sessionId:e.id,entryId:n,blockIndex:r}:null),na();let i=ea.current,o=er??(null===U?nt:null);i&&o&&rm(i,h_(o)),ea.current=null;let s=k(e);if(nr.current!==s&&(tX([]),(!tQ||tQ.startsWith("file:"))&&(t0(null),eU(!1)),tB(null)),nr.current=s,!t&&U){let t=k(U)===k(e);if(U.id===e.id&&t){R&&eD(!1);return}}eo(null),q(e),eg(e=>e+1),ti([]),ts(null),ta(!1),td.current=null,tf(null),tg(null),tv(!1),no(!0),R&&!t&&eD(!1),t&&(ns.current=!0),t&&new URLSearchParams(window.location.search).get("session")===e.id||w.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[nt,tQ,na,w,R,er,U]),nf=(0,i.useCallback)((e,t)=>{na();let n=`new:${e}:${t}`;rm(h_(t),n),ea.current=n,el(e),q(null),eo(t),eg(e=>e+1),ti([]),ts(null),ta(!1),tf(null),tg(null),tv(!1),tB(null),R&&eD(!1),w.replace(`?cwd=${encodeURIComponent(t)}`,{scroll:!1})},[na,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=>nf(`kb-${Date.now()}`,e),activeCwd:nt});let nm=(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(()=>{})},[]),ng=(0,i.useCallback)(async e=>{let t=K.find(t=>t.id===e);if(t&&!t.transient)return void nh(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}`);nh(n.info)}catch(e){console.error("[pi-web] failed to open session:",e instanceof Error?e.message:e)}},[nh,K]),nx=(0,i.useCallback)((e,t)=>{ef(e=>e+1),ea.current===t&&(na(),ea.current=null,eo(null),q(e),nm(e.id),w.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1}))},[na,w,nm]),nv=(0,i.useCallback)(e=>{let{targetSession:t,title:n,body:r,tag:i}=e;if(!("Notification"in window))return;let o=()=>{iX({title:n,body:r,sessionUrl:t?`/?session=${encodeURIComponent(t.id)}`:"/",tag:i,onClick:()=>{window.focus(),t&&nh(t)}})};"granted"===Notification.permission?(o(),lI(T)):"default"===Notification.permission&&Notification.requestPermission().then(e=>{"granted"===e&&(o(),lI(T))})},[nh,T]),nb=(0,i.useCallback)(()=>{ef(e=>e+1),ew(e=>e+1),U&&nm(U.id),U?.relation?.kind!=="subagent"&&iY()&&nv({targetSession:U,title:U?.name??M("i18n.sessionComplete"),body:M("i18n.taskFinished"),tag:U?`pi-session-complete:${U.id}`:"pi-session-complete"})},[nv,nm,U,M]),ny=(0,i.useCallback)(e=>{var t;U?.relation?.kind!=="subagent"&&iY()&&(t=H.current,!(!iG(e)||t.has(e.id))&&(t.add(e.id),1)&&nv({targetSession:U,title:M("i18n.attentionNeeded"),body:"custom"===e.method?M("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[nv,U,M]),nj=(0,i.useCallback)(async()=>{let e=U?.id;if(e&&"naming"!==tN.kind){tI.current&&clearTimeout(tI.current),tB(null),t$({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(ef(e=>e+1),tT.current!==e)return;q(t=>t?.id===e?{...t,name:r}:t),tE(t=>t?.sessionId===e?{...t,sessionName:r}:t),t$({kind:"success"}),tI.current=setTimeout(()=>t$({kind:"idle"}),1800)}catch(t){if(tT.current!==e)return;t$({kind:"error",message:t instanceof Error?t.message:String(t)}),tI.current=setTimeout(()=>t$({kind:"idle"}),5e3)}}},[tN.kind,U?.id]);(0,i.useEffect)(()=>{tI.current&&clearTimeout(tI.current),t$({kind:"idle"})},[U?.id]);let nk=(0,i.useCallback)(()=>{ew(e=>e+1)},[]),nw=(0,i.useCallback)(e=>{na(),ea.current=null,ef(e=>e+1),eg(e=>e+1),eo(null),q(t=>({...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1})),nm(e),w.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1})},[na,w,nm]),nS=(0,i.useCallback)(async(e,t,n)=>{let r=await i4(t,{type:"fork_branch",entryId:n});if(!r?.newSessionId)throw Error(M("chat.quoteForkFailed"));te({sessionId:r.newSessionId,text:e}),nw(r.newSessionId)},[nw,M]),nC=(0,i.useCallback)(()=>{no(!0)},[]),nE=(0,i.useCallback)(e=>{na(),ef(e=>e+1);let t=Z.current;if(t?.id===e){!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:hB();if(t&&e)try{let n=hD(t.getItem(hF));if(n?.kind!=="session"||n.sessionId!==e)return;t.removeItem(hF)}catch{}}(e);let n=t.cwd,r="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;el(r),ea.current=n?`new:${r}:${n}`:null,q(null),eo(n??null),eg(e=>e+1),ti([]),ts(null),ta(!1),tf(null),tg(null),tv(!1),tB(null),w.replace(n?`?cwd=${encodeURIComponent(n)}`:window.location.pathname,{scroll:!1})}},[na,w]),nN=(0,i.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,i=n?.modeHint,o=n?.page,s=`file:${e}`;tX(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})),t0(s),eU(!0),R&&eD(!1)},[R]),n$=(0,i.useCallback)((e,t)=>{nN(e,G(e),{sourceSessionId:U?.id??null,page:t})},[nN,U?.id]),nI=(0,i.useCallback)(e=>{let t=t1.find(t=>t.cwd===e),n=t??hA(e);t||t2(e=>[...e,n]),t0(n.id),eU(!0),R&&eD(!1)},[t1,R]),nT=(0,i.useCallback)(e=>{t1.some(t=>t.id===e)?t2(t=>t.map(t=>t.id!==e||t.closing?t:{...t,closing:"close"})):(tX(t=>{let n=t.filter(t=>t.id!==e);return 0===n.length&&0===t1.length&&eU(!1),n}),t0(t=>{if(t!==e)return t;let n=tG.filter(t=>t.id!==e);return n.at(-1)?.id??t1.at(-1)?.id??null}))},[tG,t1]),nM=(0,i.useCallback)(()=>{U&&window.open(`/api/sessions/${encodeURIComponent(U.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[U]),nR=er??(null===U&&nt?nt:null),nL=null===U&&nR?`new:${es}:${nR}`:null;(0,i.useLayoutEffect)(()=>{ea.current=nL},[nL]);let nz=null!==U||null!==nR,nW=U?.cwd??nR,nA=ni&&!nz;(0,i.useEffect)(()=>{if(eL(null),eW(!1),eF(null),!nW)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(nW)}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);eL(t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[nW]);let nP=(0,i.useCallback)(async()=>{if(nW&&!eA){eP(!0),eF(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:nW})}),t=await e.json();if(!e.ok||t.error)return void eF({error:t.error??`HTTP ${e.status}`,...t.reason?{reason:t.reason}:{}});eL(t),eW(!1),eM(e=>e+1),eg(e=>e+1)}catch(e){eF({error:e instanceof Error?e.message:String(e)})}finally{eP(!1)}}},[eA,nW]),nO=(0,i.useCallback)(()=>{eF(null),eW(!0)},[]),nF=(0,i.useCallback)((e,t)=>{e===nW&&eL(t)},[nW]),nB=tG.find(e=>e.id===tQ)??null,nD=nt?G(nt)||nt:null,nH=nD?`${nD} - Pi Web`:"Pi Web";(0,i.useEffect)(()=>{let e=()=>{document.title!==nH&&(document.title=nH)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[nH]);let n_=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(eG,{selectedSessionId:U?.id??null,onSelectSession:nh,onNewSession:nf,initialSessionId:ne,skipInitialProjectSelection:null!==C.requestedCwd,onInitialRestoreDone:nC,refreshKey:eh,onSessionDeleted:nE,selectedCwd:U?.cwd??er??null,onCwdChange:nc,onOpenFile:nN,onOpenTerminal:nI,explorerRefreshKey:ek,onExplorerRefresh:nk,onAtMention:t6,onAtMentions:t9,onBackgroundTaskDone:_,onRunningSessionIdsChange:en,onSessionsChange:J}),(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=si(t)&&!nW;return(0,r.jsxs)("button",{type:"button",onClick:()=>eI(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)(ho,{section:t,size:14,strokeWidth:2}),(0,r.jsx)("span",{children:n})]},t)}),(0,r.jsxs)("button",{type:"button",onClick:()=>eI(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:so();if(!t)return"general";try{let n=ss(t).section;if(!("string"==typeof n&&st.includes(n)))return"general";return si(n)&&!e?"general":n}catch{return"general"}}(nW)),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)(ho,{section:"general",size:14,strokeWidth:2}),(0,r.jsx)("span",{children:M("common.settings")})]})]})]}),nU=e=>nz&&eR?.requiresTrust&&!eR.trusted?(0,r.jsxs)("button",{type:"button",onClick:nO,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,nq=e=>{let t,n,i,o,s,l;return e||nz?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",height:"100%"},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>{nM(),e&&L&&eJ(!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&&((tC?.userMessages??0)>0||U.messageCount>0)),n=!U||U.transient||!t||"naming"===tN.kind,i="success"===tN.kind,o="error"===tN.kind,s="naming"===tN.kind?M("title.generating"):i?M("title.updated"):o?M("title.failed"):M("title.generate"),l=!U||U.transient?M("title.unsaved"):t?o?tN.message:M("title.generateSession"):M("title.noMessages"),(0,r.jsxs)("button",{type:"button",onClick:()=>{nj(),e&&L&&eJ(!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"!==tN.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"===tN.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})]})),Q&&(0,r.jsxs)("button",{type:"button",onClick:()=>t_("agents",e),title:M("agentSwitcher.title"),"aria-label":M("agentSwitcher.title"),"aria-pressed":"agents"===tF,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"===tF?"var(--bg-selected)":"none",border:"none",borderTop:"agents"===tF?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"agents"===tF?"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:X.subagents.length})]}),tc&&(e?(0,r.jsx)("button",{type:"button",onClick:()=>t_("branches",!0),title:M("i18n.branches"),"aria-label":M("i18n.branches"),"aria-pressed":"branches"===tF,style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:"100%",padding:0,background:"branches"===tF?"var(--bg-selected)":"none",border:"none",borderTop:"branches"===tF?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"branches"===tF?"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:tr.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)(hk,{tree:tr,activeLeafId:to,onLeafChange:tp,locked:tl,inline:!0,containerRef:tt,open:"branches"===tF,onToggle:()=>t_("branches"),hasSession:!0})),(0,r.jsxs)("button",{ref:tj,type:"button",onClick:()=>tU("system",e),disabled:e&&!nz,title:M("system.prompt"),"aria-label":M("system.prompt"),"aria-pressed":"system"===tF,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"system"===tF?"var(--bg-selected)":"none",border:"none",borderTop:"system"===tF?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:e&&!nz?"not-allowed":"pointer",color:"system"===tF?"var(--text)":"var(--text-muted)",opacity:e&&!nz?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||nz)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="system"===tF?"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:th?"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:()=>tU("tools",e),disabled:e&&!nz,title:M("tools.title"),"aria-label":M("tools.title"),"aria-pressed":"tools"===tF,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"tools"===tF?"var(--bg-selected)":"none",border:"none",borderTop:"tools"===tF?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:e&&!nz?"not-allowed":"pointer",color:"tools"===tF?"var(--text)":"var(--text-muted)",opacity:e&&!nz?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||nz)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="tools"===tF?"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:tm?.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},nZ=e=>{if(!e&&(!nz||!tC&&!tA))return null;let t=tC?.tokens,n=tC?.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(tA?.contextWindow){let e=tA.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(tA.contextWindow)}`:`? / ${i(tA.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)}`)),tA?.contextWindow){let e=tA.percent;d.push(`context: ${null!==e?e.toFixed(1)+"%":"unknown"} of ${tA.contextWindow.toLocaleString()} tokens`)}let c=d.join(" | "),u=e&&L&&eV,p=!!(t&&(t.input>0||t.output>0)||o||a);return(0,r.jsx)("button",{type:"button",onClick:()=>t_("session"),disabled:!nz||u,tabIndex:u?-1:void 0,title:c||M("session.title"),"aria-label":M("session.title"),"aria-pressed":"session"===tF,"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"===tF?"var(--bg-selected)":"none",border:"none",borderTop:"session"===tF?"2px solid var(--accent)":"2px solid transparent",fontSize:11,color:"var(--text-muted)",whiteSpace:"nowrap",cursor:nz?"pointer":"default",fontVariantNumeric:"tabular-nums",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{nz&&!u&&(e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="session"===tF?"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&&nz&&(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]})]})})},nK=e=>{let t=e&&L&&eV;return(0,r.jsx)("button",{type:"button",onClick:tJ,disabled:t,tabIndex:t?-1:void 0,"aria-controls":"file-panel","aria-expanded":e_,"aria-hidden":!!t||void 0,title:e_?M("files.hidePanel"):M("files.showPanel"),"aria-label":e_?M("files.hidePanel"):M("files.showPanel"),"data-mobile-toolbar-file":e?"true":void 0,style:{marginLeft:e||tC||tA?0:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,visibility:t?"hidden":"visible",pointerEvents:t?"none":"auto",background:e_?"var(--bg-selected)":"none",border:"none",borderLeft:"1px solid var(--border)",color:e_?"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=e_?"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${eY?"":" sidebar-mobile-pending"}`,onClick:()=>eD(!1),style:{position:"fixed",inset:0,zIndex:199,background:"rgba(0,0,0,0.4)",opacity:+!!eB,pointerEvents:eB?"auto":"none",transition:"opacity 0.25s ease"}}),(0,r.jsx)("div",{ref:e8.panelRef,id:"session-sidebar",inert:eK,className:`sidebar-container${eB?" sidebar-open":" sidebar-closed"}${eY?"":" sidebar-mobile-pending"}${e8.isResizing?" sidebar-resizing":""}`,style:{"--sidebar-width":`${e8.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:n_}),eB&&(0,r.jsx)("div",{...e8.separatorProps,inert:eK,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${e8.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${M("layout.resizeSidebar")}: ${M("layout.resizeHint")}`}),(0,r.jsxs)("div",{inert:eK,style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:[(0,r.jsxs)("div",{ref:tt,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:tK,title:eB?M("sidebar.hide"):M("sidebar.show"),"aria-label":eB?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:eB?(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:tn,"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:tV,title:eV?M("chat.close"):M("chat.moreControls"),"aria-label":eV?M("chat.close"):M("chat.moreControls"),"aria-controls":"mobile-toolbar-actions","aria-expanded":eV,"data-mobile-toolbar-more":"true",style:{position:"relative",zIndex:eV?21:void 0,display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:eV?"var(--bg-selected)":"none",border:"none",borderRight:"1px solid var(--border)",color:eV?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s, background 0.12s"},children:eV?(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&&nq(!0),nZ(!0),nK(!0),L&&eV&&(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:nq(!0)})]}),!R&&(0,r.jsxs)(r.Fragment,{children:[nU(!1),nq(!1),nZ(!1)]}),!R&&nK(!1),R&&tc&&(0,r.jsx)(hk,{tree:tr,activeLeafId:to,onLeafChange:tp,locked:tl,inline:!0,compact:!0,containerRef:tt,open:"branches"===tF,onToggle:()=>t_("branches"),hasSession:nz,hideInlineButton:!0}),tF&&tD&&(0,r.jsxs)("div",{style:{position:"fixed",top:tD.top,left:tD.left,width:tD.width,maxHeight:`calc(100dvh - ${tD.top}px)`,overflowY:"auto",zIndex:500},children:["agents"===tF&&X&&U&&(0,r.jsx)(hT,{rootSession:X.root,subagents:X.subagents,selectedSessionId:U.id,runningSessionIds:ee,onSelectSession:nh}),"system"===tF&&(0,r.jsx)(hw,{loading:tx,prompt:th,translate:M}),"tools"===tF&&(0,r.jsx)(hE,{loading:tx,tools:tm,translate:M}),"session"===tF&&(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:tC?(e=tC.totalActiveMs??0,t=[...tC.sessionName?[{label:M("session.name"),value:tC.sessionName,copyField:null}]:[],{label:M("session.file"),value:tC.sessionFile??M("session.inMemory"),copyField:"file"},{label:M("session.id"),value:tC.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"),tC.userMessages.toLocaleString(T)],[M("session.assistant"),tC.assistantMessages.toLocaleString(T)],[M("session.toolCalls"),tC.toolCalls.toLocaleString(T)],[M("session.toolResults"),tC.toolResults.toLocaleString(T)],[M("session.total"),tC.totalMessages.toLocaleString(T)]],a=[[M("session.input"),tC.tokens.input.toLocaleString(T)],[M("session.output"),tC.tokens.output.toLocaleString(T)],...tC.tokens.cacheRead>0?[[M("session.cacheRead"),tC.tokens.cacheRead.toLocaleString(T)]]:[],...tC.tokens.cacheWrite>0?[[M("session.cacheWrite"),tC.tokens.cacheWrite.toLocaleString(T)]]:[],[M("session.total"),tC.tokens.total.toLocaleString(T)]],d=tA??tC.contextUsage,u=[...tC.cost>0?[[M("session.cost"),`$${tC.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)}`]]:[],...tC.tokens.cacheRead+tC.tokens.cacheWrite>0&&tC.tokens.cacheRead+tC.tokens.cacheWrite+tC.tokens.input>0?[[M("session.cacheHitRate"),`${(tC.tokens.cacheRead/(tC.tokens.cacheRead+tC.tokens.cacheWrite+tC.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=tR===e;return(0,r.jsx)("button",{type:"button",title:n?M("session.copied"):M(f[e]),onClick:()=>tW(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&&nU(!0)]}),(0,r.jsx)("div",{style:{flex:1,overflow:"hidden",position:"relative"},children:nz?(0,r.jsx)(oI,{session:U,searchTarget:eb?.sessionId===U?.id?eb:null,onSearchTargetHandled:ej,initialScrollPosition:U?ex.current.get(U.id)??null:null,onScrollPositionChange:ev,sessionRunning:!!(U&&ee.has(U.id)),newSessionCwd:nR,newSessionDraftKey:nL,onAgentEnd:nb,onAttentionNeeded:ny,onSessionCreated:nx,onSessionForked:nw,modelsRefreshKey:eT,chatInputRef:e9,onBranchDataChange:tu,onSystemPromptChange:tk,onSystemToolsChange:tw,onSystemInfoLoaderChange:tS,onSessionStatsChange:tM,onSessionStatsPanelOpen:tq,onOpenSettings:tZ,onContextUsageChange:tO,onOpenFile:n$,onFilesUploaded:nk,onOpenSession:ng,onAskInNewChat:nS,quoteSelectionEnabled:F,initialPrompt:e7?.sessionId===U?.id?e7?.text:void 0,onInitialPromptConsumed:()=>te(null),soundEnabled:z,onSoundToggle:W,playDoneSound:A,unlockAudio:P},em):"validating"===ed?(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"===ed?(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:eu})]}):nA?nt?(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${e_?" is-open":""}`,onClick:()=>eU(!1)}),e_&&(0,r.jsx)("div",{...e5.separatorProps,inert:eK,"aria-controls":"file-panel",className:`panel-resize-handle right-panel-resize-handle${e5.isResizing?" is-resizing":""}`,"data-resize-handle":"right-panel",title:`${M("layout.resizeFilePanel")}: ${M("layout.resizeHint")}`}),(0,r.jsxs)("div",{ref:e5.panelRef,id:"file-panel",className:`right-panel-container${e_?" right-panel-open":" right-panel-closed"}${eK?" right-panel-full-width":""}${e5.isResizing?" right-panel-resizing":""}`,style:{"--right-panel-width":`${e5.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)(o7,{tabs:t5,activeTabId:tQ??"",onSelectTab:t0,onCloseTab:nT})}),(0,r.jsx)("button",{type:"button",className:"file-panel-expand-button",onClick:tY,"aria-controls":"file-panel","aria-pressed":eK,title:M(eK?"files.restorePanelWidth":"files.expandPanel"),"aria-label":M(eK?"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:eK?"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:()=>eU(!1),"aria-controls":"file-panel","aria-expanded":e_,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:[nB?.filePath?(0,r.jsx)(o6,{filePath:nB.filePath,cwd:nt??void 0,sourceSessionId:nB.sourceSessionId,gitRefreshKey:ek,initialDisplayMode:nB.initialDisplayMode,initialPage:nB.page,initialState:nB.viewerState,watchEnabled:e_,onStateChange:e=>t3(nB.id,nB.viewerRevision??0,e),onMentionLines:e_?t7:void 0,onAtMention:t6,onOpenFile:(e,t)=>nN(e,G(e),{sourceSessionId:nB.sourceSessionId,page:t})},`${nB.id}:${nB.viewerRevision??0}`):t1.some(e=>e.id===tQ)?null:(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12},children:M("files.noneOpen")}),t1.map(e=>(0,r.jsx)("div",{hidden:e.id!==tQ,style:{width:"100%",height:"100%"},children:(0,r.jsx)(hz,{tab:e,active:e_&&e.id===tQ,onRestart:()=>t2(t=>t.map(t=>t.id===e.id?{...t,closing:"restart"}:t)),onClosed:()=>{let t,n;return t="restart"===e.closing?hA(e.cwd):null,n=t1.filter(t=>t.id!==e.id),void(t2(n=>n.flatMap(n=>n.id!==e.id?[n]:t?[t]:[])),t0(r=>r!==e.id?r:t?.id??n.at(-1)?.id??tG.at(-1)?.id??null),!t&&!n.length&&!tG.length&&eU(!1))},onCloseError:()=>t2(t=>t.map(t=>t.id===e.id?{...t,closing:void 0}:t))})},e.id))]})]})]}),eS&&(0,r.jsx)(ha,{cwd:nW,sessionId:U?.id??null,initialSection:eS,quoteSelectionEnabled:F,onQuoteSelectionChange:D,onClose:()=>{eI(null),eM(e=>e+1)},onSessionReloaded:()=>eg(e=>e+1),projectTrust:eR,onOpenTrustDialog:nO,onProjectTrustChanged:nF}),ez&&nW&&(0,r.jsx)(hc,{cwd:nW,busy:eA,error:eO,onCancel:()=>{eA||eW(!1)},onConfirm:()=>void nP(),onStatus:eL})]})}},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"}}},e=>{e.O(0,[7523,7330,3888,5772,3298,1278,8441,3794,7358],()=>e(e.s=42927)),_N_E=e.O()}]);
|