@pricening/pi-web 0.11.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +8 -8
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/required-server-files.js +1 -1
  6. package/.next/required-server-files.json +1 -1
  7. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  8. package/.next/server/app/_global-error.html +1 -1
  9. package/.next/server/app/_global-error.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  13. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  14. package/.next/server/app/_not-found.html +1 -1
  15. package/.next/server/app/_not-found.rsc +2 -2
  16. package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  17. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
  18. package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  19. package/.next/server/app/api/app-update/route.js +1 -1
  20. package/.next/server/app/index.html +1 -1
  21. package/.next/server/app/index.rsc +4 -4
  22. package/.next/server/app/index.segments/__PAGE__.segment.rsc +4 -4
  23. package/.next/server/app/index.segments/_full.segment.rsc +4 -4
  24. package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  25. package/.next/server/app/login/page_client-reference-manifest.js +1 -1
  26. package/.next/server/app/login.html +1 -1
  27. package/.next/server/app/login.rsc +2 -2
  28. package/.next/server/app/login.segments/_full.segment.rsc +2 -2
  29. package/.next/server/app/login.segments/_tree.segment.rsc +1 -1
  30. package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +2 -2
  31. package/.next/server/app/page.js +1 -1
  32. package/.next/server/app/page_client-reference-manifest.js +1 -1
  33. package/.next/server/app-paths-manifest.json +8 -8
  34. package/.next/server/middleware-build-manifest.js +1 -1
  35. package/.next/server/pages/404.html +1 -1
  36. package/.next/server/pages/500.html +1 -1
  37. package/.next/server/server-reference-manifest.json +1 -1
  38. package/.next/static/chunks/app/{layout-1db5383b28405504.js → layout-6008ff3f9d5055e2.js} +1 -1
  39. package/.next/static/chunks/app/{page-de5b3e3565b1a54b.js → page-7a0af1292fa0d000.js} +1 -1
  40. package/.next/trace +87 -87
  41. package/.next/trace-build +1 -1
  42. package/README.md +4 -3
  43. package/README.zh-CN.md +4 -3
  44. package/package.json +1 -1
  45. /package/.next/static/{7r6-_kJbL2lHOV6A7LdXP → pdx-Am6pppy840OjmypqG}/_buildManifest.js +0 -0
  46. /package/.next/static/{7r6-_kJbL2lHOV6A7LdXP → pdx-Am6pppy840OjmypqG}/_ssgManifest.js +0 -0
@@ -8,7 +8,7 @@ ${n}`}var n2=n(32316),n4=n(88374),n8=n(5924),n3=n(94764),n5=n(63835),n6=n(54152)
8
8
  ${t}`,x=c&&!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(866),n.e(8367),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:()=>d(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)(rJ,{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)(rZ,{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 rZ(e){let{svg:t,onClose:n}=e,{t:o}=(0,eh.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 rV={...rE.xJ,'pre[class*="language-"]':{...rE.xJ['pre[class*="language-"]']}};delete rV['pre[class*="language-"]'].background;let rJ=(0,i.memo)(function(e){let{code:t,lang:n,headerAction:o,isStreaming:s}=e,{isDark:l}=rU(),{t:a}=(0,eh.s)(),[c,d]=(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:()=>{rK(t).then(()=>{d(!0),setTimeout(()=>d(!1),1500)})},className:"markdown-code-action",children:a(c?"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)(rN.A,{language:n||"text",style:l?rV:rE.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})]})}),rY=(0,i.createContext)(!1);function rG(e){let{src:t,alt:n,cwd:o,...s}=e,l=(0,i.useContext)(rY);delete s.node;let a="string"==typeof t?t:void 0,c=a?nB(a,o):null,d=c?`/api/files/${eV(c)}?type=read`:a,u=(0,r.jsx)("img",{src:d,alt:n??"",loading:"lazy",...s});return!d||l?u:(0,r.jsx)(rC,{src:d,alt:n??"",className:"markdown-image",children:u})}function rX(e){let{children:t,className:n,isStreaming:o,cwd:s,onOpenFile:l,keepLineBreaks:a}=e,c=(0,i.useMemo)(()=>ra(t),[t]),d=(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)(rq,{code:l.replace(/\n$/,""),isStreaming:o,defaultPreview:!0}):(0,r.jsx)(rJ,{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?nB(t,s):null;return o&&l?(0,r.jsx)(rY.Provider,{value:!0,children:(0,r.jsx)("a",{href:t,...i,onClick:e=>{if(!nW(e))return;let n=e.currentTarget.getAttribute("target");n&&"_self"!==n||(e.preventDefault(),l(o,n_(t)??void 0))},children:n})}):(0,r.jsx)(rY.Provider,{value:!0,children:(0,r.jsx)("a",{href:t,...i,target:"_blank",rel:"noopener noreferrer",children:n})})},img:e=>(0,r.jsx)(rG,{cwd:s,...e}),ol(e){let{node:t,start:n,style:i,...o}=e,s=String(Math.abs((n??1)+Math.max(t?.children.filter(e=>"element"===e.type&&"li"===e.tagName).length??0,1)-1)).length;return(0,r.jsx)("ol",{start:n,style:{...i,"--ol-marker-digits":Math.max(s,2)},...o})},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)(n2.oz,{remarkPlugins:a?rj:rg,rehypePlugins:rw,urlTransform:l?ro:ri,components:d,children:c})})}function rQ(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 r0=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,r1=/(?:\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 r2(e){let t,n=[],r=null,i=0,o=0,s=0,l=0,a=[],c=[],d=()=>({lineNo:null,text:"",type:"empty"}),u=()=>{if(!r){a=[],c=[];return}let e=Math.max(a.length,c.length);for(let t=0;t<e;t++){let e=a[t]?{lineNo:a[t].lineNo,text:a[t].text,type:"removed"}:d(),n=c[t]?{lineNo:c[t].lineNo,text:c[t].text,type:"added"}:d();r.rows.push({type:"line",left:e,right:n})}a=[],c=[]};for(let d of e.split(/\r?\n/)){if(!(s>0||l>0)){if(d.startsWith("--- ")){u(),t=r4(d.slice(4));continue}if(d.startsWith("+++ ")){u(),r={oldPath:t,newPath:r4(d.slice(4)),rows:[]},n.push(r);continue}}let e=d.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:d});continue}if(!r)continue;if(d.startsWith("\\ ")){u(),r.rows.push({type:"hunk",text:d});continue}let p=d[0],h=d.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?(c.push({lineNo:o++,text:h}),l>0&&l--):""!==d&&(u(),r.rows.push({type:"hunk",text:d}))}u();let p=n.filter(e=>e.rows.some(e=>"line"===e.type));return p.length>0?p:null}function r4(e){return e.split(" ")[0].trim()}let r8=new Set,r3="pi-thinking-expanded",r5="pi-thinking-expanded-changed";function r6(){return"true"===window.localStorage.getItem(r3)}function r9(e){let{files:t,onOpenFile:n}=e,{t:i}=(0,eh.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=eJ(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:[eq(o,12),(0,r.jsx)("span",{children:o})]},t)})})}let r7="codemode",ie=new Set(["running","ok","error","cancelled"]);function it(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ir(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function ii(e){if(!it(e)||!Array.isArray(e.calls))return{calls:[],omitted:0};let t=e.calls.flatMap(e=>{let t=function(e){if(!it(e)||"string"!=typeof e.name)return null;let t="string"==typeof e.status&&ie.has(e.status)?e.status:"ok",n=ir(e.durationMs),r=ir(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=ir(e.omittedCalls);return{calls:t,omitted:void 0!==n&&n>0?Math.floor(n):0}}let io=/^Script (completed|failed)\nWall time ([\d.]+) seconds\nOutput:\n$/;function is(e){return`$${e>=.01?e.toFixed(2):e.toPrecision(2)}`}let il={running:{icon:"…",color:"#d97706"},ok:{icon:"✓",color:"#16a34a"},error:{icon:"✗",color:"#f87171"},cancelled:{icon:"⊘",color:"var(--text-dim)"}};function ia(e){var t;let{call:n}=e,{t:i}=(0,eh.s)(),o=il[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:is(n.cost)})]}),n.error&&(0,r.jsx)("div",{style:{color:"#f87171",paddingLeft:18,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n.error})]})}function ic(e){let t,{calls:n,omitted:o,isError:s}=e,{t:l}=(0,eh.s)(),[a,c]=(0,i.useState)(!1);if(0===n.length&&0===o)return null;let d=a?0:Math.max(0,n.length-20),u=d>0?n.slice(d):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})}),d>0&&(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),style:{alignSelf:"flex-start",padding:0,border:"none",background:"none",color:"var(--accent)",cursor:"pointer",font:"inherit"},children:l("codemode.showEarlierCalls",{count:d})}),(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)(ia,{call:e},e.id||`${d+t}`))}),null!==p&&(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:l("codemode.modelCost",{cost:is(p)})})]})}let id=new Map,iu=/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}\uac00-\ud7af]/u;function ip(e){let t=0,n=0;for(let r of e)iu.test(r)?t++:n++;return t+n/4}let ih=new Map;function im(e){let{children:t,className:n,...o}=e,{t:s}=(0,eh.s)(),[l,a]=(0,i.useState)(!1);if(t.length<=1e5)return(0,r.jsx)(rX,{className:n,...o,children:t});if(!l){var c;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:(c=t.length)>=1e6?`${(c/1e6).toFixed(1)} MB`:c>=1e3?`${Math.round(c/1e3)} KB`:`${c} 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 ig(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 ix=(0,i.memo)(function(e){let{message:t,isStreaming:n,toolResults:i,modelNames:o,cwd:s,onOpenFile:l,onOpenSession:a,entryId:c,searchBlock:d,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)(iv,{message:t,cwd:s,onOpenFile:l,entryId:c,onFork:u,forking:p,onEditContent:h,onCancelEdit:f,isEditing:m}):"assistant"===t.role?(0,r.jsx)(ib,{message:t,isStreaming:n,toolResults:i,modelNames:o,cwd:s,onOpenFile:l,onOpenSession:a,showTimestamp:g,prevTimestamp:x,sessionId:v,entryId:c,searchBlock:d,writtenFiles:b,onCompact:y,isCompacting:j,compactError:k}):"toolResult"===t.role?null:"custom"===t.role?"compaction"===t.customType?(0,r.jsx)(iz,{message:t}):(0,r.jsx)(iF,{message:t,cwd:s,onOpenFile:l}):"bashExecution"===t.role?(0,r.jsx)(iU,{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 iv(e){let{message:t,cwd:n,onOpenFile:o,entryId:s,onFork:l,forking:a,onEditContent:c,onCancelEdit:d,isEditing:u}=e,{t:p}=(0,eh.s)(),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(!1),[x,v]=(0,i.useState)(!1),b=("string"==typeof t.content?t.content:t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")).replace(/\r\n?/g,"\n"),y="string"==typeof t.content?[]:t.content.filter(e=>"image"===e.type),j=tc(b),k=j?.search(/\s/)??-1,w=j?-1===k?j:j.slice(0,k):"",S=j&&-1!==k?j.slice(k+1):"",C=ig(t.timestamp),N=!!s&&!!l,E=j??b,$=j?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,j):t,I=y.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!b},children:y.map((e,t)=>{let n=e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:"";return(0,r.jsx)(rC,{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)})}),T=!!s&&!!c,M=!!u&&!!d;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:j?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0},children:[I,(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexWrap:"wrap"},children:[(0,r.jsxs)("button",{onClick:()=>v(e=>!e),title:p(x?"i18n.collapse":"i18n.expand"),"aria-expanded":x,style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,padding:0,background:"none",border:"none",cursor:"pointer",color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",textAlign:"left"},children:[(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:w}),(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.75,transform:x?"rotate(180deg)":"none",transition:"transform 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),S&&(0,r.jsx)("span",{style:{color:"var(--text)",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.6,whiteSpace:"pre-wrap",wordBreak:"break-word",minWidth:0,flex:1},children:S})]}),x&&(0,r.jsx)(rX,{className:"markdown-user-message",keepLineBreaks:!0,cwd:n,onOpenFile:o,children:b})]}):(0,r.jsxs)(r.Fragment,{children:[I,b&&(0,r.jsx)(im,{className:"markdown-user-message",keepLineBreaks:!0,cwd:n,onOpenFile:o,children:b})]})})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:3},children:[(0,r.jsx)("div",{style:{display:"flex",gap:3,opacity:+!!h,pointerEvents:h?"auto":"none",transition:"opacity 0.12s"},children:(0,r.jsxs)("button",{onClick:()=>{rK(E).then(()=>{g(!0),setTimeout(()=>g(!1),1500)})},title:p("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:m?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{m||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{m||(e.currentTarget.style.color="var(--text-dim)")},children:[m?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),p(m?"i18n.copied":"i18n.copy")]})}),(N||T||M)&&(0,r.jsxs)("div",{style:{display:"flex",gap:3,opacity:h||a||M?1:0,pointerEvents:h||a||M?"auto":"none",transition:"opacity 0.12s"},children:[T&&!M&&(0,r.jsxs)("button",{onClick:()=>c($,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")]}),M&&(0,r.jsxs)("button",{type:"button",onClick:d,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")]}),N&&(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")]})]}),C&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:C})]})]})}function ib(e){var t,n,o;let s,l,a,c,d,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}=e,{t:$}=(0,eh.s)(),I=b?ig(p.timestamp):null,T=(0,i.useMemo)(()=>(p.content??[]).map((e,t)=>({block:e,originalIndex:t})).filter(e=>{let{block:t}=e;return!nM(t,{isStreaming:h})}),[p.content,h]),M=(0,i.useMemo)(()=>T.map(e=>{let{block:t}=e;return t}),[T]),R=nL(p,{isStreaming:h}),L=nA(p,{isStreaming:h}),A=L&&!nz(p),[z,P]=(0,i.useState)(!1),[W,O]=(0,i.useState)(!1),F=(0,i.useRef)(null),D="number"!=typeof p.timestamp?null:`${p.provider??""}/${p.model??""}@${p.timestamp}`,B=(0,i.useRef)(D);B.current=D;let[H,_]=(0,i.useState)(null),U=(0,i.useRef)(T);U.current=T;let K=(0,i.useRef)(new Map),q=(0,i.useMemo)(()=>{if(!h)return K.current=new Map,0;let e=new Map,t=0;for(let{block:n,originalIndex:r}of T){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 ip(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+ip(t.slice(o))}(K.current.get(r),i);e.set(r,{text:i,tokens:o}),t+=o}return K.current=e,t},[T,h]),Z=(0,i.useRef)(q);Z.current=q;let V=(0,i.useRef)(new Map),[J,Y]=(0,i.useState)(new Map),G="assistant"===p.role?iw(p.durationMs):void 0,X=(0,i.useMemo)(()=>{let e=G??(p.timestamp&&y?p.timestamp-y:void 0);if(void 0===e)return;let t=Math.round(e/1e3);return t>0?t:void 0},[G,p.timestamp,y]),Q=(0,i.useMemo)(()=>{let e=new Map;if(!f)return e;for(let[t,n]of f){let r=iw(n.durationMs)??(n.timestamp&&p.timestamp?n.timestamp-p.timestamp:void 0);void 0!==r&&r>=iS&&e.set(t,r)}return e},[f,p.timestamp]),ee=M.filter(e=>"text"===e.type).map(e=>e.text).join("\n");if((0,i.useEffect)(()=>{if(!h){let e=new Date().getTime();Y(t=>{let n=new Map(t);for(let[t,r]of V.current)n.has(t)||n.set(t,Math.round((e-r)/1e3));return n}),F.current=null,_(null);return}let e=setInterval(()=>{var e;let t,n=U.current,r=Date.now();n.forEach(e=>{let{originalIndex:t}=e;V.current.has(t)||V.current.set(t,r)}),Y(e=>{let t=!1,i=new Map(e);for(let e=0;e<n.length-1;e++){let o=n[e].originalIndex,s=n[e+1].originalIndex;if(!i.has(o)&&V.current.has(o)){let e=V.current.get(o),n=V.current.get(s)??r;i.set(o,Math.round((n-e)/1e3)),t=!0}}return t?i:e});let i=Z.current;if(0===i)return;F.current??=function(e,t,n){let r=null===e?void 0:id.get(e);if(r)return r;let i={at:n,tokens:t};return null!==e&&(id.set(e,i),id.size>32&&id.delete(id.keys().next().value)),i}(B.current,i,r);let o=(e=F.current,(t=(r-e.at)/1e3)>.5?(i-e.tokens)/t:null);null!==o&&_(o)},300);return()=>clearInterval(e)},[h]),0===M.length&&!h&&!R&&!L)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(),c=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}]:[]}),c.find(e=>e.id===a)?.name??c.find(e=>a.endsWith(`/${e.id}`))?.name??Object.entries(m??{}).find(e=>{let[t]=e;return t.toLowerCase()===a})?.[1]??`${t}/${n}`)}),h&&(d=Math.round(q),(0,r.jsx)(r.Fragment,{children:d>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4,color:"var(--text)"},title:$("i18n.estimatedTokens"),children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:2,fontSize:11,fontWeight:400},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1.5",x2:"5",y2:"8.5"}),(0,r.jsx)("polyline",{points:"2 6 5 8.5 8 6"})]}),d]}),null!==H&&(u=H>=50?"#53b3cb":H>=30?"#9bc53d":H>=15?"#f9c22e":"#e01a4f",(0,r.jsxs)("span",{style:{marginLeft:6,padding:"1px 6px",borderRadius:4,background:u,color:"#fff",fontSize:11,fontWeight:400},children:[H.toFixed(1)," t/s"]}))]})}))]}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:T.map(e=>{let{block:t,originalIndex:n}=e;return(0,r.jsx)(iy,{block:t,searchTarget:t===w,toolResults:f,isStreaming:h,streamingDuration:J.get(n)??("thinking"===t.type?X:void 0),toolCallDurations:Q,cwd:g,onOpenFile:x,onOpenSession:v,sessionId:j,entryId:k,blockIndex:n},`${k??"stream"}-${n}`)})}),R&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:8*(M.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: ",R]}),L&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:M.length>0||R?8:0,padding:"7px 10px",border:"1px solid rgba(234,179,8,0.3)",borderRadius:6,background:"rgba(234,179,8,0.07)",color:"#ca8a04",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:[$(A?"chat.truncatedWithoutAnswer":"chat.truncatedByOutputLimit"),A&&C&&(0,r.jsx)("button",{type:"button",onClick:C,disabled:N,style:{display:"block",marginTop:8,padding:"3px 8px",border:"1px solid currentColor",borderRadius:5,background:"transparent",color:"inherit",cursor:N?"default":"pointer",font:"inherit"},children:$(N?"chat.compacting":"chat.compactContext")}),A&&E&&(0,r.jsx)("div",{style:{marginTop:8,color:"#ef4444",whiteSpace:"pre-wrap"},children:E})]}),S&&S.length>0&&(0,r.jsx)(r9,{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 "))}),ee&&!h&&(0,r.jsxs)("button",{onClick:()=>{rK(ee).then(()=>{O(!0),setTimeout(()=>O(!1),1500)})},title:$("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:W?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:+!!z,pointerEvents:z?"auto":"none",transition:"opacity 0.12s, color 0.12s"},onMouseEnter:e=>{W||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{W||(e.currentTarget.style.color="var(--text-dim)")},children:[W?(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"})]}),$(W?"i18n.copied":"i18n.copy")]}),I&&!h&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginLeft:"auto"},children:I})]})]})}function iy(e){let{block:t,searchTarget:n,toolResults:i,isStreaming:o,streamingDuration:s,toolCallDurations:l,cwd:a,onOpenFile:c,onOpenSession:d,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)(ij,{block:t,isStreaming:o,cwd:a,onOpenFile:c})});if("thinking"===t.type)return(0,r.jsx)(ik,{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)(iC,{block:t,result:e,duration:n,onOpenSession:d})}return null}function ij(e){let{block:t,isStreaming:n,cwd:i,onOpenFile:o}=e;return(0,r.jsx)(im,{isStreaming:n,cwd:i,onOpenFile:o,children:t.text})}function ik(e){var t;let{block:n,duration:o,sessionId:s,entryId:l,blockIndex:a}=e,{t:c}=(0,eh.s)(),[d,u]=(0,i.useState)(r6),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(!1),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(c);v.current=c;let b=(t=n.thinking,t.trimStart().match(/^[^\r\n]{0,240}/u)?.[0].trimEnd()??"");return(0,i.useEffect)(()=>{let e=()=>u(r6());return window.addEventListener(r5,e),()=>window.removeEventListener(r5,e)},[]),(0,i.useEffect)(()=>{if(!d||!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=ih.get(r);if(i)return ih.delete(r),ih.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 ih.delete(r),e});if(ih.set(r,o),ih.size>100){let e=ih.keys().next().value;e&&ih.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}},[d,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":d,"aria-label":`${c("i18n.thinking")}${b?`: ${b}`:""}`,title:c("i18n.thinking"),onClick:()=>u(e=>!e),style:{display:"inline-flex",alignItems:"center",gap:6,width:d?14:"100%",flexShrink:+!d,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)(rQ,{active:d}),!d&&(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b?(0,r.jsx)(n2.oz,{allowedElements:[],unwrapDisallowed:!0,skipHtml:!0,children:b}):"..."})]}),d&&(0,r.jsx)("div",{style:{flex:1,minWidth:0,color:g?"#f87171":"var(--text-muted)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:f?c("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 iw(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0}let iS=100;function iC(e){var t,n,o,s;let l,{block:a,result:c,duration:d,onOpenSession:u}=e,{t:p}=(0,eh.s)(),[h,f]=(0,i.useState)(()=>{var e;return void 0!==(e=a.toolCallId)&&r8.has(e)}),m=function(e){if(void 0!==e.rawInput||!nU(e.toolName))return null;let{content:t}=e.input;return"string"!=typeof t||""===t?null:Object.keys(e.input).every(e=>i_.has(e))?t:null}(a)??(o=a).rawInput??JSON.stringify(o.input,null,2),g=void 0!==a.rawInput,x=nK(a.toolName),v=c&&!c.isError?function(e){let t=e.details;if(!iR(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}(c):null,b=function(e,t){if(!nq(e.toolName))return null;let n=nG(nZ(e.input,e.rawInput));if(n)return n;let r=t&&!t.isError?t.details:void 0;if(iR(r)){let e=nX(r.preview);if(e)return e}return null}(a,c),y=nq(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}(nZ((s=a).input,s.rawInput))).length?null:l.join(", ").slice(0,120):null,j=a.toolName!==r7||g?null:it(t=a.input)&&"string"==typeof t.code?t.code:null,k=null===j?null:{code:j,...ii(c?.details)},w=null!==k&&void 0!==c&&0===c.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,c?.details),C=c?k?function(e){let[t,...n]=e;return t?.type==="text"&&"string"==typeof t.text&&io.test(t.text)?n:[...e]}(c.content):c.content:[],N=c?C.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,E=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,$=iB(C),I=null!==E&&("(no output)"===E.trim()||""===E.trim()),T=(c?.isError??!1)||nq(a.toolName)&&nJ(c?.details),M=(n=c?.details)&&"object"==typeof n&&"pi-web-subagent"===n.kind&&"string"==typeof n.sessionId?c.details:null,R=k?k.calls.length+k.omitted:0;return(0,r.jsxs)("div",{style:{borderRadius:7,overflow:"hidden",fontSize:12,border:T?"1px solid rgba(248,113,113,0.45)":"1px solid rgba(34,197,94,0.25)",background:T?"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?r8.add(e):r8.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:T?"#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))}),R>0&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:1===R?p("codemode.callCountOne"):p("codemode.callCount",{count:R})}),void 0!==d&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:function(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t),r=Math.floor(n/60),i=n%60;return r<60?`${r}m ${i}s`:`${Math.floor(r/60)}h ${r%60}m ${i}s`}(d)}),(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"})})]}),M&&u&&(0,r.jsx)("button",{type:"button",onClick:()=>u(M.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:T?"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)(ic,{calls:k.calls,omitted:k.omitted,isError:T}),$.length>0&&(0,r.jsx)(iL,{images:$,isError:T}),h&&b&&(0,r.jsx)("div",{style:{borderTop:"1px solid rgba(34,197,94,0.15)",background:"var(--bg)"},children:(0,r.jsx)(i$,{files:b})}),h&&c&&b&&T&&(0,r.jsx)(iA,{text:E??"",isEmpty:I,isError:T}),h&&c&&!b&&!w&&(v?(0,r.jsx)(iN,{diff:v}):(!I||0===$.length)&&(0,r.jsx)(iA,{text:E??"",isEmpty:I,isError:T}))]})}function iN(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)(iE,{text:t.text})})}function iE(e){let{text:t}=e,n=(0,i.useMemo)(()=>r2(t),[t]);return n?(0,r.jsx)(i$,{files:n}):(0,r.jsx)(iM,{text:t})}function i$(e){let{files:t}=e,{t:n}=(0,eh.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)(iI,{title:e.oldPath||n("i18n.before"),side:"left"}),(0,r.jsx)(iI,{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)(iT,{cell:e.left,side:"left"}),(0,r.jsx)(iT,{cell:e.right,side:"right"})]},t))})]},t))})}function iI(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 iT(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 iM(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 iR(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function iL(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=iH(e);return n?(0,r.jsx)(rC,{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 iA(e){let{text:t,isEmpty:n,isError:i}=e,{t:o}=(0,eh.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 iz(e){let{message:t}=e,{t:n}=(0,eh.s)(),[o,s]=(0,i.useState)(!1),l=iD(t.content),a=ig(t.timestamp),c=t.details?.tokensBefore;return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:"compaction"}),a&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:a})]}),(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":o,title:n(o?"i18n.collapse":"i18n.expand"),onClick:()=>s(e=>!e),style:{display:"flex",alignItems:"flex-start",gap:8,width:"100%",padding:0,border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",font:"inherit",textAlign:"left"},children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:4,color:"var(--text-muted)",transform:o?"rotate(90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"4 2.5 7.5 6 4 9.5"})}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:"calc(15px + var(--chat-font-size-offset, 0px))",fontWeight:700,lineHeight:1.35},children:n("i18n.conversationCompacted")}),"number"==typeof c&&Number.isFinite(c)&&(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:n("i18n.compactedFromTokens",{tokens:c.toLocaleString()})})]})]}),o&&(0,r.jsx)(iP,{summary:l})]})]})})}function iP(e){let{summary:t}=e,{t:n}=(0,eh.s)(),o=(0,i.useMemo)(()=>{let e,n,r,i,o;return e=[],n=[],r=t.match(r1),i=r?.[1]??"",o=r?.index===void 0?t:t.slice(0,r.index),i.replace(r0,(t,r,i)=>{let o=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...o):n.push(...o),""}),{body:o.trim(),readFiles:e,modifiedFiles:n}},[t]);return(0,r.jsxs)("div",{style:{marginTop:10},children:[(0,r.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:n("i18n.compactionDescription")}),o.body?(0,r.jsx)(rX,{className:"markdown-compaction-message",children:o.body}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:n("i18n.noSummary")}),(0,r.jsx)(iW,{readFiles:o.readFiles,modifiedFiles:o.modifiedFiles})]})}function iW(e){let{readFiles:t,modifiedFiles:n}=e,{t:i}=(0,eh.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)(iO,{title:i("i18n.modifiedFiles"),files:n}),t.length>0&&(0,r.jsx)(iO,{title:i("i18n.readFiles"),files:t})]})}function iO(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 iF(e){let{message:t,cwd:n,onOpenFile:o}=e,{t:s}=(0,eh.s)(),[l,a]=(0,i.useState)(!1),[c,d]=(0,i.useState)(!1),u=iD(t.content),p=iB(t.content),h=void 0!==t.details,f=h?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(t.details):"",m=t.customType||"extension",g=ig(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)",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:m}),g&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:g})]}),(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[p.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!u},children:p.map((e,t)=>{let n=iH(e);return n?(0,r.jsx)(rC,{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})}),u?(0,r.jsx)(rX,{className:"markdown-custom-message",cwd:n,onOpenFile:o,children:u}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:s("i18n.noMessage")})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[u||f?(0,r.jsx)("button",{onClick:()=>{rK(u||f).then(()=>{d(!0),setTimeout(()=>d(!1),1500)})},style:{padding:"3px 7px",border:"none",background:"none",color:c?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:s(c?"i18n.copied":"i18n.copy")}):null,h&&(0,r.jsx)("button",{onClick:()=>a(e=>!e),style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:s(l?"i18n.hideDetails":"i18n.showDetails")})]}),h&&l&&(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:f})]})})}function iD(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function iB(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)}function iH(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 i_=new Set(["path","file_path","content"]);function iU(e){let{message:t,sessionId:n}=e,[o,s]=(0,i.useState)(null),[l,a]=(0,i.useState)(!1),[c,d]=(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),d(null);try{let e=await fetch(h),t=await e.json();t.success?s(t.data?.output??""):d(t.error??"failed")}catch(e){d(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)(iC,{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"}),c&&(0,r.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:["(",c,")"]})]})]})}function iK(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 iq=new Map;function iZ(e){return{value:e.value,images:e.images.map(e=>({...e}))}}function iV(e){return!e.value&&0===e.images.length}function iJ(e){let t=iq.get(e);return t?iZ(t):null}function iY(e,t){iV(t)?iq.delete(e):iq.set(e,iZ(t))}function iG(e){iq.delete(e)}function iX(e,t){return e.trim()?t.trim()?`${e}
9
9
 
10
10
  ${t}`:e:t}function iQ(e,t,n,r){let i=[...t??[],...r].filter(iK).slice(0,10).map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});return{value:iX(e,n),images:i}}function i0(e,t,n){if(e===t)return n?iZ(n):iJ(t);let r=iJ(e),i=n&&!iV(n)?iZ(n):r??(n?iZ(n):null),o=iJ(t);if(iG(e),!i)return o;let s=o?iQ(o.value,o.images,i.value,i.images):i;return iY(t,s),iZ(s)}let i1=/^([ \t]*)([-*+])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,i2=/^([ \t]*)(\d{1,9})([.)])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,i4=/^([ \t]*)(\d{1,3})(、)([ \t]*)/,i8=/^[ \t]*([-*_])(?:[ \t]*\1){2,}[ \t]*$/,i3=/^[ \t]{0,3}(`{3,}|~{3,})/;function i5(e){return"mcp"===e.name&&e.sourceInfo?.path==="builtin:mcp"}function i6(e){return"/mcp"===e.trim()}let i9="pi-enter-send-mode",i7="enter",oe=null,ot=new Set;function on(){return null===oe&&(oe=function(){try{let e=window.localStorage.getItem(i9);return"ctrlEnter"===e?"ctrlEnter":"enter"}catch{return i7}}()),oe}function or(e){return ot.add(e),()=>{ot.delete(e)}}function oi(e){oe=e;try{window.localStorage.setItem(i9,e)}catch{}ot.forEach(e=>e())}function oo(){return(0,i.useSyncExternalStore)(or,on,()=>i7)}let os="pi-chat-content-width",ol="pi-chat-content-font-size",oa={width:820,fontSize:14},oc=null,od=new Set;function ou(e){let t=Number(e);return Number.isFinite(t)?Math.max(820,Math.min(2e3,Math.round(t))):820}function op(e){let t=Number(e??14);return Number.isFinite(t)?Math.max(12,Math.min(24,Math.round(t))):14}function oh(e){try{return window.localStorage.getItem(e)}catch{return null}}function of(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 om(){return oc||of(oc={width:ou(oh(os)),fontSize:op(oh(ol))}),oc}function og(e){return od.add(e),()=>{od.delete(e)}}function ox(e,t){let n="width"===e?ou(t):op(t);of(oc={...om(),[e]:n});try{window.localStorage.setItem("width"===e?os:ol,String(n))}catch{}od.forEach(e=>e())}let ov=e=>ox("width",e),ob=e=>ox("fontSize",e);function oy(){return{...(0,i.useSyncExternalStore)(og,om,()=>oa),setWidth:ov,setFontSize:ob}}let oj=[{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"}],ok={ui:"pi-ui-font-family",mono:"pi-mono-font-family",uiWeight:"pi-ui-font-weight",monoWeight:"pi-mono-font-weight"},ow={ui:"",mono:"",uiWeight:400,monoWeight:400};function oS(e){let t="string"==typeof e?Number(e):e;return oj.find(e=>e.value===t)?.value??400}function oC(e){return"string"==typeof e&&e.length<=500?e:""}let oN=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded"]),oE=["ui","mono"],o$=Object.keys(ok),oI=null,oT=new Set;function oM(){let e={...ow};for(let t of oE)try{e[t]=oC(window.localStorage.getItem(ok[t]));let n=`${t}Weight`;e[n]=oS(window.localStorage.getItem(ok[n]))}catch{}return e}function oR(e){for(let t of oE){let n=`--font-${t}`,r=function(e,t){let n=oC(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&&oN.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 oL(){return oI||oR(oI=oM()),oI}function oA(){oT.forEach(e=>e())}function oz(e){if(null!==e.key&&!Object.values(ok).includes(e.key))return;let t=oM(),n=oL();o$.every(e=>t[e]===n[e])||(oI=t,oR(t),oA())}function oP(e){return 0===oT.size&&window.addEventListener("storage",oz),oT.add(e),oL(),()=>{oT.delete(e),0===oT.size&&window.removeEventListener("storage",oz)}}function oW(e){let t=oL(),n=o$.filter(n=>t[n]!==e[n]);if(n.length){for(let t of(oI=e,oR(e),n))try{e[t]===ow[t]?window.localStorage.removeItem(ok[t]):window.localStorage.setItem(ok[t],String(e[t]))}catch{}oA()}}function oO(e,t){oW({...oL(),[e]:oC(t)})}function oF(e,t){oW({...oL(),[`${e}Weight`]:oS(t)})}function oD(e){oW({...oL(),[e]:"",[`${e}Weight`]:400})}function oB(){return{...(0,i.useSyncExternalStore)(oP,oL,()=>ow),setFontPreference:oO,setFontWeight:oF,resetFontPreference:oD}}function oH(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 o_(e){let{active:t,onSelect:n,star:o,gutter:s=!!o,children:l}=e,a=ew(),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=!!(o&&!o.isDefault),f=h&&(c||u||a);return(0,r.jsxs)("div",{onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),onFocus:()=>p(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||p(!1)},style:{position:"relative",background:t?"var(--bg-selected)":c?"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)(oH,{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)(oH,{filled:!1,size:12})})]})}function oU(e){let t,n,o,s,l,a,c,d,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,eh.s)(),E=ew(),$=(0,i.useRef)(null),I=(0,i.useRef)(null),[T,M]=(0,i.useState)(!1),[R,L]=(0,i.useState)(null),[A,z]=(0,i.useState)(""),P=v||b,W=(t=A.trim().toLocaleLowerCase())?p.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(t)):p,O=p.length>8,F=[];for(let e of W){let t=F.find(t=>t.provider===e.provider);t?t.options.push(e):F.push({provider:e.provider,options:[e]})}let D=x??(h?p.find(e=>e.modelId===h.modelId&&e.provider===h.provider)?.name??h.modelId:g??(p.length>0?"Select model":"No models"));(0,i.useEffect)(()=>{let e=e=>{$.current&&!$.current.contains(e.target)&&I.current&&!I.current.contains(e.target)&&(M(!1),z(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{P&&(M(!1),z(""))},[P]);let B="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:E?"flex-start":void 0,gap:6,width:E?"100%":void 0,maxWidth:E?"100%":220,height:32,padding:E?"8px 10px":"8px 12px",overflow:"hidden",border:"none",borderRadius:9,background:T?"var(--bg-hover)":"none",color:"var(--text-muted)",cursor:P?"not-allowed":"pointer",fontSize:12,opacity:P?.5:1,transition:"background 0.12s, color 0.12s"};return(0,r.jsxs)("div",{ref:$,className:`model-selector is-${k}${P?" is-disabled":""}`,style:{position:"relative",width:"field"===k||E?"100%":void 0,minWidth:0,flex:"toolbar"===k&&E?"1 1 auto":void 0},onKeyDown:e=>{"Escape"===e.key&&T&&(e.preventDefault(),e.stopPropagation(),z(""),M(!1))},children:[(0,r.jsxs)("button",{type:"button","aria-label":j,"aria-haspopup":"listbox","aria-expanded":T,"aria-busy":b||void 0,disabled:P,title:b?"Switching model":P?D:p.length>0||m?"Change model":"No available models",style:B,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();L({top:t.top,right:t.right,bottom:t.bottom,left:t.left,width:t.width}),M(e=>(e&&z(""),!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=T?"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:D}),"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"})})]}),T&&R&&(n=window.visualViewport?.height??window.innerHeight,o=window.visualViewport?.width??window.innerWidth,s=R.top-8,l=n-R.bottom-8,c=Math.max(120,Math.min((a="up"===w||s>l)?s:l,.6*n)),d=a?{bottom:n-R.top+6}:{top:R.bottom+6},u=E?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:R.left,width:"max-content",minWidth:R.width,maxWidth:Math.max(R.width,o-R.left-8)},(0,r.jsxs)("div",{ref:I,role:"listbox","aria-label":j,style:{position:"fixed",...d,...u,zIndex:500,display:"flex",flexDirection:"column",maxHeight:c,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:[O&&(0,r.jsx)("div",{style:{flexShrink:0,padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:A,onChange:e=>z(e.target.value),placeholder:N("chat.filterModels"),"aria-label":N("chat.filterModels"),autoFocus:!E,autoComplete:"off",spellCheck:!1,style:{boxSizing:"border-box",width:"100%",minWidth:220*!E,padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})}),(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[m&&!A.trim()&&(0,r.jsx)(o_,{active:!h,gutter:!!C,onSelect:()=>{M(!1),z(""),m()},children:(0,r.jsx)(oK,{label:g??"Default"})}),0===F.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:A.trim()?N("chat.noMatchingModels"):"No available models"}):F.map((e,t)=>(0,r.jsxs)("div",{children:[F.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)(o_,{active:e.modelId===h?.modelId&&e.provider===h?.provider,onSelect:()=>{let t;return t=e.modelId===h?.modelId&&e.provider===h?.provider,void(M(!1),z(""),(!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:()=>{M(!1),z(""),C?.(e.provider,e.modelId)}}:void 0,children:(0,r.jsx)(oK,{label:e.name})},`${e.provider}:${e.modelId}`))]},e.provider))]})]}))]})}function oK(e){let{label:t}=e;return(0,r.jsx)("span",{title:t,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})}let oq=["configured","chat-only","read-only","default","full"],oZ={configured:"configured","chat-only":"none","read-only":"read-only",default:"default",full:"full"},oV=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function oJ(e,t,n){return t<=0?0:((e+n)%t+t)%t}function oY(e,t,n,r){e.setRangeText(r,t,n,"end"),e.dispatchEvent(new Event("input",{bubbles:!0}))}function oG(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:r.length,o=e.selectionStart,s=e.selectionEnd;if(e.focus(),o===s&&t<=o&&n>=s){let i=e.value.length-(n-t)+r.length;for(let n=o-t;n>0&&e.selectionStart>t&&document.execCommand("delete");n--);if(document.execCommand("insertText",!1,r))for(let t=n-s;t>0&&e.value.length>i&&document.execCommand("forwardDelete");t--);else oY(e,t,e.selectionStart+(n-s),r)}else e.setSelectionRange(t,n),document.execCommand("insertText",!1,r)||oY(e,t,n,r);i!==r.length&&e.setSelectionRange(t+i,t+i)}function oX(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 oQ=["auto","off","minimal","low","medium","high","xhigh","max"],o0={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 o1(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let o2=[{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 o4(e){return function(e){let t=e.trim().match(/^\/([^\s]+)(?:\s|$)/);if(t)return o2.find(e=>e.name===t[1])}(e)?.availableWhileStreaming===!0}let o8=["builtin","extension","prompt","skill"],o3={builtin:"chat.builtIn",extension:"chat.extensions",prompt:"chat.prompts",skill:"chat.skills"},o5={builtin:0,extension:1,prompt:2,skill:3};function o6(e,t,n){let r=e.name.toLowerCase(),i=o9(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function o9(e,t){return"builtin"===e.source?t(e.description):e.description??""}function o7(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}async function se(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 st(e){return{data:e.data,mimeType:e.mimeType}}function sn(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function sr(e){return(e??[]).filter(iK).slice(0,10).map(sn)}function si(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function so(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 ss(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 sl(e){let{error:t}=e,{t:n}=(0,eh.s)();return t?(0,r.jsx)(ss,{tone:"error",title:n("chat.modelError"),body:t}):null}function sa(e){let{warnings:t}=e,{t:n}=(0,eh.s)();return t&&0!==t.length?(0,r.jsx)(ss,{tone:"warning",title:n(t.length>1?"chat.modelScopeWarnings":"chat.modelScopeWarning"),body:t.join("\n")}):null}let sc=(0,i.forwardRef)(function(e,t){let n,o,s,l,a,c,d,{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:E,isCompacting:$,compactError:I,onDismissCompactError:T,compactResult:M,toolPreset:R,onToolPresetChange:L,thinkingLevel:A,isAutoThinkingSelection:z=!1,onThinkingLevelChange:P,availableThinkingLevels:W,thinkingLevelMap:O,savedDefaultThinkingLevel:F,onSetDefaultThinkingLevel:D,retryInfo:B,queuedMessages:H,inputHistory:_=[],onRecallQueue:U,slashCommands:K,slashCommandsLoading:q,onLoadSlashCommands:Z,onBuiltinCommand:V,soundEnabled:J,onSoundToggle:Y,onAudioUnlock:G,onPromptWithStreamingBehavior:X,draftKey:Q,cwd:ee,onAttachFiles:et,compact:en=!1}=e,{t:er}=(0,eh.s)(),{fontSize:ei}=oy(),{ui:eo,uiWeight:es}=oB(),el=ew(),ea=oo(),[ec,ed]=(0,i.useState)(()=>Q?iJ(Q)?.value??"":""),[eu,ep]=(0,i.useState)(!1),[ef,em]=(0,i.useState)(!1),[eg,ex]=(0,i.useState)(!1),[ev,eb]=(0,i.useState)(()=>Q?sr(iJ(Q)?.images):[]),ey=ec.trimStart(),ej=0===ev.length&&ey.startsWith("!"),ek=ej&&ey.startsWith("!!"),[eS,eC]=(0,i.useState)(!1),[eN,eE]=(0,i.useState)(0),[e$,eI]=(0,i.useState)(null),[eT,eM]=(0,i.useState)(null),[eR,eL]=(0,i.useState)(!1),[eA,ez]=(0,i.useState)(null),[eP,eW]=(0,i.useState)(0),[eO,eF]=(0,i.useState)(!1),[eB,eH]=(0,i.useState)(!1),[eU,eK]=(0,i.useState)(0),[eZ,eV]=(0,i.useState)(!1),eJ=(0,i.useRef)(!1),[eY,eG]=(0,i.useState)(null),[eX,e2]=(0,i.useState)(!1),[e4,e8]=(0,i.useState)(null),[e3,e5]=(0,i.useState)(null),e6=ee&&e3?.cwd===ee?e3.values:{},e9=(0,i.useRef)(null),e7=(0,i.useRef)(null),te=(0,i.useRef)(null),tt=(0,i.useRef)(null),tn=(0,i.useRef)(null),tr=(0,i.useRef)(null),ti=(0,i.useRef)(!1),to=(0,i.useRef)(0),ts=(0,i.useRef)(!1),tl=(0,i.useRef)(null),ta=(0,i.useRef)([]),tc=(0,i.useRef)(null),td=(0,i.useRef)([]),tu=(0,i.useRef)([]),tp=(0,i.useRef)(null),th=(0,i.useRef)(null),tf=(0,i.useRef)(Q),tm=(0,i.useRef)(ec),tg=(0,i.useRef)(ev),tx=(0,i.useRef)(0);tm.current=ec,tg.current=ev,(0,i.useImperativeHandle)(t,()=>({insertIfEmpty(e){let t=e9.current;(t?t.value:ec).trim()||(tm.current=e,ed(e),eM(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=e9.current;if(t=i?i.value:ec,n=tg.current.length,r=tx.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=sr("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 iK(r)?[r]:[]}));tm.current=o,tg.current=s,ed(o),eM(null),eH(!1),eb(e=>(e.forEach(si),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=e9.current,n=[e,t?t.value:ec].filter(e=>e.trim()).join("\n\n");tm.current=n,ed(n),eM(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(tf.current!==e)return void i0(e,t);let n={value:tm.current,images:tg.current.map(st)},r=i0(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(tf.current=t,i)return;let o=sr(r.images);tm.current=r.value,tg.current=o,ed(r.value),eb(e=>(e.forEach(si),o)),eM(null),eH(!1)},restoreSubmission(e,t,n){if(!e.trim()&&!t?.length)return;let r=tf.current,i=n??r,o=i===r,s=!o&&i?iJ(i):null,l=iQ(e,t,o?tm.current:s?.value??"",o?tg.current.map(st):s?.images??[]);if(i&&iY(i,l),!o)return;let a=t?.length?[...sr(t).slice(0,Math.max(0,10-tg.current.length)),...tg.current].slice(0,10):tg.current;tm.current=l.value,tg.current=a,ed(t=>{let n=iX(e,t);return tm.current=n,n}),eM(null),eH(!1),t?.length&&eb(e=>{let n=Math.max(0,10-e.length),r=sr(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tg.current=i,i}),requestAnimationFrame(()=>{let e=e9.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=e9.current;if(!t)return void ed(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n);oG(t,n,r,(i.length>0&&!i.endsWith(" ")?" ":"")+e),eM(null)},addImages(e){tv(e)}}));let tv=(0,i.useCallback)(async e=>{if(en)return;let t=Math.max(0,10-tg.current.length-tx.current),n=e.filter(e=>e.type.startsWith("image/")&&e.size<=0xa00000).slice(0,t);if(n.length){tx.current+=n.length;try{let e=await Promise.all(n.map(async e=>({...await se(e),previewUrl:URL.createObjectURL(e)})));eb(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(si);let r=[...t,...n];return tg.current=r,r})}finally{tx.current-=n.length}}},[en]),tb=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",et?et(t):tv(t)},[et,tv]),ty=(0,i.useCallback)(e=>{eb(t=>{let n=[...t],[r]=n.splice(e,1);return r&&si(r),tg.current=n,n})},[]),tj=(0,i.useCallback)(()=>{tg.current=[],eb(e=>(e.forEach(si),[]))},[]),tk=(0,i.useCallback)(()=>{tm.current="",ed(""),eM(null),eH(!1),Q&&iG(Q),tf.current&&tf.current!==Q&&iG(tf.current),tj(),e9.current&&(e9.current.style.height="auto")},[tj,Q]);(0,i.useEffect)(()=>{Q&&tf.current===Q&&iY(Q,{value:ec,images:ev.map(st)})},[ev,Q,ec]),(0,i.useEffect)(()=>{let e=tf.current;if(e===Q)return;e&&iY(e,{value:tm.current,images:tg.current.map(st)});let t=Q?iJ(Q):null;tf.current=Q;let n=t?.value??"",r=sr(t?.images);tm.current=n,tg.current=r,ed(n),eM(null),eH(!1),eb(e=>(e.forEach(si),r))},[Q]);let tw=(0,i.useCallback)(()=>{let e=e9.current;e&&(e.style.height="auto",e.value&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[]);(0,i.useLayoutEffect)(tw,[ec,ei,eo,es,tw]),(0,i.useEffect)(()=>{let e=e9.current;if(!e)return;let t=-1,n=new ResizeObserver(e=>{let[n]=e;n.contentRect.width!==t&&(t=n.contentRect.width,tw())});return n.observe(e),()=>n.disconnect()},[tw]),(0,i.useEffect)(()=>{let e=e9.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(i8.test(e))return null;let t=i1.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=i2.exec(e)??i4.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=i3.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:`
11
- ${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)(()=>()=>{tg.current.forEach(si)},[]);let tS=(0,i.useCallback)(async e=>{if(ev.length||!e.startsWith("/")||!V)return!1;if(eJ.current)return!0;eJ.current=!0,eV(!0);try{var t,n;let r=await V(e);if(!r.handled)return!1;return r.error||(t=tm.current,n=tg.current.length,0!==n||t.trim()!==e)||tk(),!0}finally{eJ.current=!1,eV(!1)}},[ev.length,tk,V]),tC=(0,i.useCallback)(async()=>{var e;let t=ec.trim();(t||ev.length)&&(G?.(),(!m||o4(e=t)||i6(e))&&await tS(t)||m||(tk(),u(t,ev.length?ev:void 0)))},[ec,ev,m,tS,u,tk,G]),tN=!en&&ec.startsWith("/")&&!/\s/.test(ec.slice(1))?ec.slice(1).toLowerCase():null,tE=null===tN?[]:[...m?o2.filter(e=>e.availableWhileStreaming):o2,...K??[]].filter(e=>{let t=e.name.toLowerCase(),n=o9(e,er).toLowerCase();return t.includes(tN)||n.includes(tN)}).sort((e,t)=>{let n=o6(e,tN,er)-o6(t,tN,er);return 0!==n?n:o5[e.source]-o5[t.source]||oV.compare(e.name,t.name)}),{commands:t$,groups:tI}=(n=0,{commands:(o=o8.map(e=>{let t=tE.filter(t=>t.source===e),r="skill"===e?[...t.filter(e=>!o7(e,e6)),...t.filter(e=>o7(e,e6))]: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}),tT=1===tE.length?er(tN?"chat.match":"chat.command"):er(tN?"chat.matches":"chat.commands",{count:tE.length}),tM=!!ec.trim()||ev.length>0,tR=ev.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)&&!eO;(0,i.useEffect)(()=>{0===ev.length&&eF(!1)},[ev.length]);let tL=(0,i.useCallback)((e,t)=>{if(!ee)return void eM(null);let n=t??e.length;eM(eQ(e.slice(0,n)))},[ee]),tA=eT?.query??null,tz=i.useMemo(()=>null!==tA&&eY&&eY.cwd===ee?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:e1(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:e1(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||e0(e.entry.path)-e0(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(eY.entries,tA):[],[tA,eY,ee]),tP=!!(tA&&eY?.truncated&&eY.cwd===ee);(0,i.useEffect)(()=>{if(!tP||!ee||!tA)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}&q=${encodeURIComponent(tA)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>e8({cwd:ee,query:tA,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tP,tA,ee]);let tW=tP&&null!==e4&&e4.cwd===ee&&e4.query===tA,tO=tW?e4.matches:tz,tF=null===eT?null:`${eT.start}:${+!!eT.quoted}:${eT.query}`;(0,i.useEffect)(()=>{if(null===tF){eL(!1),eW(0);return}eL(!0),eW(0)},[tF]);let tD=null!==eT;(0,i.useEffect)(()=>{if(!tD||!ee)return;let e=tp.current;e&&e.cwd===ee&&Date.now()-e.fetchedAt<1e4||th.current===ee||(th.current=ee,e2(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{eG({cwd:ee,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)=>e0(e.path)-e0(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tp.current={cwd:ee,fetchedAt:Date.now()}}).catch(()=>{tp.current=null}).finally(()=>{th.current=null,e2(!1)}))},[tD,ee]);let tB=(0,i.useCallback)(e=>{if(!eT)return;let t=e9.current;if(!t)return;let n=t.selectionStart??t.value.length,r=n+(eT.quoted&&'"'===t.value[n]?1:0),i=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let o=i?`@"${r}" `:`@${r} `;return{text:o,cursorOffset:o.length}}(e.path,e.isDir,eT.quoted),o=eT.start+i.cursorOffset;oG(t,eT.start,r,i.text,i.cursorOffset),eM(eQ(t.value.slice(0,o)))},[eT]);(0,i.useEffect)(()=>{eP>=tO.length&&eW(Math.max(0,tO.length-1))},[tO.length,eP]),(0,i.useEffect)(()=>{td.current.length=tO.length},[tO.length]),(0,i.useEffect)(()=>{eR&&td.current[eP]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eP,eR]),(0,i.useEffect)(()=>{eU>=_.length&&eK(Math.max(0,_.length-1))},[_.length,eU]),(0,i.useEffect)(()=>{tu.current.length=_.length},[_.length]),(0,i.useEffect)(()=>{eB&&tu.current[eU]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eU,eB]);let tH=(0,i.useCallback)(e=>{ed(e),eH(!1),eK(0),eM(null),requestAnimationFrame(()=>{let t=e9.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),t_=(0,i.useCallback)(e=>{let t=`/${e.name} `;ed(t),eC(!1),eE(0),requestAnimationFrame(()=>{let e=e9.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),tU=(0,i.useCallback)(e=>{let t=ec.trim();if(!t&&!ev.length)return;G?.();let n=ev.length?ev:void 0,r=()=>{if(t.startsWith("/")&&X){tk(),X(t,"steer"===e?"steer":"followUp",n);return}tk(),"steer"===e&&h?h(t,n):"followup"===e&&f&&f(t,n)};!ev.length&&V&&o4(t)?tS(t):!ev.length&&V&&i6(t)?tS(t).then(e=>{e||r()},()=>r()):r()},[ec,ev,V,X,h,f,tk,G,tS]),tK=(0,i.useCallback)(e=>{let t=t$.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eN-1);if("right"===e)return Math.min(t,eN+1);let n=ta.current[eN];if(!n)return"down"===e?Math.min(t,eN+1):Math.max(0,eN-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===eN)continue;let t=ta.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 c=1e3*Math.abs(a)+Math.abs(r.left+r.width/2-i);c<l&&(s=n,l=c)}return s>=0?s:"down"===e?Math.min(t,eN+1):Math.max(0,eN-1)},[t$.length,eN]),tq=(0,i.useCallback)(e=>{let t=e.nativeEvent,n="Enter"===e.key&&!e.shiftKey,r=el||"ctrlEnter"===ea?n&&(e.ctrlKey||e.metaKey):n,i=el?r:n,o=Date.now()-to.current<100,s=ti.current||t.isComposing||229===t.keyCode;if(i&&(s||o)){o&&e.preventDefault();return}if(eB&&!s){if("ArrowDown"===e.key){e.preventDefault(),eK(e=>Math.min(Math.max(0,_.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eK(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),eH(!1);return}if(("Tab"===e.key||i)&&_[eU]){e.preventDefault(),tH(_[eU]);return}}if(eS&&null!==tN){if("ArrowDown"===e.key){e.preventDefault(),eE(tK("down"));return}if("ArrowUp"===e.key){e.preventDefault(),eE(tK("up"));return}if("ArrowRight"===e.key){e.preventDefault(),eE(tK("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),eE(tK("left"));return}if("Escape"===e.key){e.preventDefault(),eC(!1);return}let t=t$[eN];if("Tab"===e.key&&t){e.preventDefault(),t_(t);return}if(i&&t){e.preventDefault(),r&&function(e,t,n){if("builtin"===t.source)return"builtin"===t.source&&e.trim()===`/${t.name}`&&(!n||!0===t.availableWhileStreaming);return i5(t)&&i6(e)}(ec,t,m)?(eC(!1),tC()):t_(t);return}}if(eR&&null!==eT&&!s){if("ArrowDown"===e.key){e.preventDefault(),eW(e=>oJ(e,tO.length,1));return}if("ArrowUp"===e.key){e.preventDefault(),eW(e=>oJ(e,tO.length,-1));return}if("Escape"===e.key){e.preventDefault(),eL(!1);return}if(("Tab"===e.key||i)&&tO[eP]){e.preventDefault(),tB(tO[eP]);return}}if("ArrowUp"===e.key&&!s&&!m&&_.length>0&&0===ec.trim().length){e.preventDefault(),eC(!1),eL(!1),eK(_.length-1),eH(!0);return}if("Escape"===e.key&&!s&&m&&p){e.preventDefault(),p();return}r&&(e.preventDefault(),m&&(h||f)?tU(e.altKey&&f||!h?"followup":"steer"):tC())},[el,ea,m,h,f,p,eS,tN,t$,eN,t_,tU,tC,tK,eR,eT,tO,eP,tB,eB,_,eU,tH,ec]),tZ=(0,i.useCallback)(()=>{let e=e9.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),tV=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!en&&t.length){e.preventDefault(),tv(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"),c=s.replace(/([\\()])/g,"\\$1");n+=`${e.slice(r,t)}[${a}](${c})`,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(),tm.current=a,ed(a),eH(!1),tL(a,l+o.length),requestAnimationFrame(()=>{s.focus(),s.setSelectionRange(l+o.length,l+o.length)})},[en,tv,tL]);(0,i.useEffect)(()=>{if(null===tN){eC(!1),eE(0),ts.current=!1;return}eC(!0),eE(0),!ts.current&&Z&&(ts.current=!0,Promise.resolve(Z()).catch(()=>{ts.current=!1}))},[tN,Z]),(0,i.useEffect)(()=>{if(!eS||!ee)return;let e=!1;return e5({cwd:ee,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(ee)}`).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;e5({cwd:ee,values:n})}).catch(()=>{e||e5({cwd:ee,values:{}})}),()=>{e=!0}},[eS,ee]),(0,i.useEffect)(()=>{eN>=t$.length&&eE(Math.max(0,t$.length-1))},[t$.length,eN]),(0,i.useEffect)(()=>{ta.current.length=t$.length},[t$.length]),(0,i.useEffect)(()=>{eS&&ta.current[eN]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eN,eS]),(0,i.useLayoutEffect)(()=>{if(!eS||null===tN)return void eI(null);let e=tl.current;if(e)return oX(e,e=>{eI(t=>t===e?t:e)})},[eS,tN]),(0,i.useLayoutEffect)(()=>{if(!eR||null===eT)return void ez(null);let e=tc.current;if(e)return oX(e,e=>{ez(t=>t===e?t:e)})},[eR,eT]);let tJ=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}}),tY=M?Math.max(0,M.tokensBefore-M.estimatedTokensAfter):0,tG=M?`${M.reason&&"manual"!==M.reason?`${M.reason[0].toUpperCase()}${M.reason.slice(1)} `:er("chat.compacted")} ${o1(M.tokensBefore)} -> ${o1(M.estimatedTokensAfter)} tokens (${er("chat.tokensSaved",{saved:o1(tY)})})`:null,tX=A&&"auto"!==A?A:null,tQ="auto"!==(s=tX??"auto")&&O?O[s]??s:s,t0=Object.entries(oZ).find(e=>{let[,t]=e;return t===(R??"configured")})?.[0]??"configured",t1="chat-only"===t0?er("chat.chatOnly"):t0;return(0,i.useEffect)(()=>{let e=e=>{e7.current&&!e7.current.contains(e.target)&&ep(!1),te.current&&!te.current.contains(e.target)&&em(!1),tt.current&&!tt.current.contains(e.target)&&ex(!1),!tn.current||tn.current.contains(e.target)||e9.current?.contains(e.target)||eH(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{m&&ep(!1)},[m]),(0,i.useEffect)(()=>{el||ex(!1)},[el]),(0,r.jsxs)("fieldset",{disabled:eZ,"aria-busy":eZ,className:en?void 0:"chat-input-shell",style:{flexShrink:0,minWidth:0,margin:0,border:0,background:"transparent",padding:en?0:"0 16px 8px",paddingRight:en?0:el?16:52,opacity:eZ?.5:1,transition:"opacity 0.15s"},children:[!en&&(0,r.jsx)("input",{ref:tr,type:"file",accept:et?void 0:"image/*",multiple:!0,style:{display:"none"},onChange:tb}),(0,r.jsxs)("div",{style:{maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(0,r.jsx)(sl,{error:y}),(0,r.jsx)(sa,{warnings:j}),tR&&(l=b?.find(e=>e.provider===g?.provider&&e.id===g?.modelId),(0,r.jsx)(ss,{tone:"warning",title:er("chat.imageNotSupportedTitle"),body:er("chat.imageNotSupportedBody",{model:l?.name||g?.modelId||""}),onClose:()=>eF(!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:er("chat.queued",{count:(H?.steering.length??0)+(H?.followUp.length??0)})}),U&&(0,r.jsxs)("button",{onClick:U,title:er("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"})]}),er("chat.recall")]})]}),H?.steering.map((e,t)=>(0,r.jsx)(so,{kind:"steer",text:e},`steer-${t}`)),H?.followUp.map((e,t)=>(0,r.jsx)(so,{kind:"follow-up",text:e},`followup-${t}`))]}),B&&(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"})]}),er("chat.retrying",{attempt:B.attempt,max:B.maxAttempts}),B.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",B.errorMessage]})]}),tG&&(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"})}),tG]}),I&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,marginBottom:8,padding:T?"3px 3px 3px 10px":"7px 10px",background:"rgba(239,68,68,0.07)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:6,color:"#ef4444",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,padding:T?"4px 0":0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:I}),T&&(0,r.jsx)(eD,{onClick:T,title:er("chat.dismissCompactError")})]}),ev.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:ev.map((e,t)=>(0,r.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,r.jsx)(rC,{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:()=>ty(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:[eB&&_.length>0&&(0,r.jsxs)("div",{ref:tn,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:er("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===eU;return(0,r.jsxs)("button",{ref:e=>{tu.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tH(e)},onMouseEnter:()=>eK(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),eS&&null!==tN&&(0,r.jsxs)("div",{ref:tl,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===e$?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${e$}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:q?er("chat.loadingCommands"):er("chat.slashCommands",{label:tT})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:er("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:10},children:q||0!==tE.length?tI.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:er(o3[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===eN,o=o7(t,e6);return(0,r.jsxs)("button",{ref:e=>{ta.current[n]=e},type:"button",onMouseDown:e=>{e.preventDefault(),t_(t)},onMouseEnter:()=>eE(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:er("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:o9(t,er)})]},`${t.source}:${t.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:er("chat.noCommands")})})]}),eR&&null!==eT&&(a=eX&&(!eY||eY.cwd!==ee),c=1===tO.length?er("chat.match"):er("chat.matches",{count:tO.length}),d=eY?.truncated&&!tW?eT.query?er("chat.searchingAll"):er("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:tc,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eA?"min(48vh, 400px)":`min(48vh, 400px, ${eA}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:a?er("chat.loadingFiles"):er("chat.files",{label:c,hint:d})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:er("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:a||0!==tO.length?tO.map((e,t)=>{let n=t===eP,i=e.path.split("/").pop()??e.path,o=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{td.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tB(e)},onMouseEnter:()=>eW(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)(e_,{size:14}):eq(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:tP&&!tW?er("chat.searching"):er("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{style:{minWidth:0,display:"flex",flexDirection:en?"column":"row",gap:8,alignItems:en?"stretch":"center",background:"var(--bg)",border:en?"none":`1px solid ${ej?"var(--tool-bg)":m&&(h||f)?"rgba(234,179,8,0.4)":"color-mix(in srgb, var(--border) 70%, transparent)"}`,borderRadius:14*!en,padding:en?0:el?"6px 6px 6px 12px":"10px 10px 10px 14px",boxShadow:en?"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:e9,className:"chat-input-textarea","aria-label":en?er("chat.quoteQuestion"):void 0,value:ec,onChange:e=>{tm.current=e.target.value,ed(e.target.value),eH(!1),tL(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;tL(t.value,t.selectionStart)},onKeyDown:tq,onCompositionStart:()=>{ti.current=!0},onCompositionEnd:e=>{ti.current=!1,to.current=Date.now();let t=e.currentTarget;tL(t.value,t.selectionStart)},onInput:tZ,onPaste:tV,placeholder:m&&(h||f)?er("chat.steerPlaceholder"):m?er("chat.agentPlaceholder"):er("chat.messagePlaceholder"),rows:1,style:{flex:en?"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:en?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:()=>tU("steer"),disabled:!tM,title:er("chat.steerHint"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tM?"rgba(234,179,8,0.12)":"none",border:"1px solid rgba(234,179,8,0.35)",borderRadius:8,color:tM?"rgba(180,130,0,1)":"var(--text-dim)",cursor:tM?"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"})]}),er("chat.steer")]}),f&&(0,r.jsxs)("button",{onClick:()=>tU("followup"),disabled:!tM,title:`${er("chat.followUpHint")} (${el?"Ctrl/Cmd+":""}Alt/Option+Enter)`,"aria-keyshortcuts":el?"Control+Alt+Enter Meta+Alt+Enter":"Alt+Enter",style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tM?"rgba(129,140,248,0.12)":"none",border:"1px solid rgba(129,140,248,0.35)",borderRadius:8,color:tM?"rgba(99,102,241,1)":"var(--text-dim)",cursor:tM?"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"})]}),er("chat.followUp")]})]}):(0,r.jsxs)("button",{onClick:tC,disabled:!ec.trim()&&!ev.length,title:er("chat.send"),"aria-label":er("chat.send"),style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,...el?{width:36,height:36,padding:0}:{padding:"7px 14px"},background:ec.trim()||ev.length?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:ec.trim()||ev.length?"var(--accent-contrast)":"var(--text-dim)",cursor:ec.trim()||ev.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:ec.trim()||ev.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"})]}),!el&&er("chat.send")]})]})]}),ej&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:ek?"var(--text-muted)":"var(--accent)",marginTop:4},children:[er("chat.shell")," \xb7 ",ek?er("chat.outputLocal"):er("chat.outputModel")]}),!en&&(0,r.jsxs)("div",{className:"chat-input-controls",style:{marginTop:el?4:8,display:el?"grid":"flex",gridTemplateColumns:el?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:el?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2},children:[(0,r.jsx)("button",{onClick:()=>tr.current?.click(),title:er("chat.attachFiles"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:ev.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=ev.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=ev.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"})]})}),(tJ.length>0||g||y)&&k&&(0,r.jsx)(oU,{options:tJ,value:g,onChange:k,disabled:m,busy:w,isAutoSelection:x,defaultValue:S,onSetDefault:C})]}),!el&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsxs)("div",{ref:tt,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:el?0:"auto"},children:[el&&(0,r.jsx)("button",{type:"button",title:eg?void 0:er("chat.moreControls"),"aria-label":er("chat.moreControls"),"aria-expanded":eg,"aria-hidden":eg||void 0,tabIndex:eg?-1:void 0,onClick:()=>{ex(!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:eg?"default":"pointer",fontSize:12,fontWeight:500,visibility:eg?"hidden":"visible",pointerEvents:eg?"none":"auto",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{eg||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{eg||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:er("chat.moreControls")}),(0,r.jsxs)("div",{style:{display:el?eg?"flex":"none":"flex",alignItems:"center",gap:el?1:2,...el?{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:[P&&(0,r.jsxs)("div",{ref:te,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>em(e=>!e),title:m?er("chat.currentReasoning",{level:tQ}):er("chat.changeReasoning",{level:tQ}),"aria-label":er("chat.changeReasoningLabel"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:el?"0 6px":"8px 12px",width:el?"auto":void 0,height:32,background:ef?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=ef?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),(!el||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:tQ})]}),ef&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",...el?{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:oQ.filter(e=>!W||"auto"===e||W.includes(e)).map(e=>{let t="auto"===e?z:!z&&tX===e,n=er(o0[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)(o_,{active:t,onSelect:()=>{if(em(!1),"auto"===e){z||P("auto");return}(!t||z)&&P(e)},gutter:!!D,star:D&&"auto"!==e?{isDefault:F===e,saveLabel:er("chat.saveDefaultThinking"),defaultLabel:er("chat.defaultThinking"),onSave:()=>{em(!1),D(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:e7,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>!m&&ep(e=>!e),disabled:m,title:er("chat.changeToolPreset")+`: ${t1}`,"aria-label":er("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:el?"0 6px":"8px 12px",width:el?"auto":void 0,height:32,background:eu?"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=eu?"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"})}),(!el||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t1})]}),eu&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:el?void 0:0,left:el?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:oq.map(e=>{let t,n=oZ[e],i=(R??"configured")===n;return t="configured"===e?er("chat.configuredTools"):"chat-only"===e?er("chat.chatOnly"):"read-only"===e?er("chat.readOnlyTools",{count:4}):"default"===e?er("chat.builtInTools",{count:4}):er("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{ep(!1),i||L(n)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:t})]},e)})})]}),(!m||$)&&N&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{onClick:$?E:N,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:el?"0 6px":"8px 12px",width:el?"auto":void 0,height:32,background:$?"rgba(239,68,68,0.08)":"none",border:"none",borderRadius:9,color:$?"#ef4444":"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=$?"rgba(239,68,68,0.16)":"var(--bg-hover)",e.currentTarget.style.color=$?"#ef4444":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=$?"rgba(239,68,68,0.08)":"none",e.currentTarget.style.color=$?"#ef4444":"var(--text-muted)"},title:$?er("chat.stopCompaction"):er("chat.compactContext"),"aria-label":$?er("chat.stopCompaction"):er("chat.compactContext"),children:$?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(!el||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:er("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"})]}),(!el||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:er("chat.compact")})]})})}),m&&(0,r.jsxs)("button",{onClick:p,title:er("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"})}),er("chat.stop")]}),void 0!==Y&&(0,r.jsx)("button",{onClick:Y,title:J?er("chat.disableSound"):er("chat.enableSound"),"aria-label":J?er("chat.disableSound"):er("chat.enableSound"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:J?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",opacity:J?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=J?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.opacity=J?"1":"0.55"},children:J?(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"})]})}),el&&eg&&(0,r.jsx)("button",{type:"button",title:er("chat.collapseControls"),"aria-label":er("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{ep(!1),em(!1),ex(!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 sd=n(88576),su=n.n(sd);function sp(e){let{level:t,children:n,headingIndex:i,onClick:o}=e;return(0,r.jsx)("button",{type:"button",className:su().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 sh=[...rk??[],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]:[]}}],sf=[[n4.A,{throwOnError:!1,strict:!1}]];function sm(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 sg=(0,i.memo)(function(e){let{markdown:t,onHeadingClick:n,onAnswerClick:o}=e,s=(0,i.useMemo)(()=>ra(t),[t]);return t?(0,r.jsx)("div",{className:su().outline,children:(0,r.jsx)(n2.oz,{remarkPlugins:sh,rehypePlugins:sf,components:{h1:e=>{let{children:t,node:i}=e;return(0,r.jsx)(sp,{level:1,headingIndex:sm(i),onClick:n,children:t})},h2:e=>{let{children:t,node:i}=e;return(0,r.jsx)(sp,{level:2,headingIndex:sm(i),onClick:n,children:t})},h3:e=>{let{children:t,node:i}=e;return(0,r.jsx)(sp,{level:3,headingIndex:sm(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:su().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 sx(e){let{messages:t,streamingMessage:n,scrollContainer:o,messageRefs:s,onRevealHistory:l}=e,{t:a}=(0,eh.s)(),[c,d]=(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),E=(0,i.useRef)(null),$=(0,i.useRef)(null),I=(0,i.useRef)(null),T=(0,i.useMemo)(()=>n?[...t,n]:t,[t,n]),M=(0,i.useRef)(T);M.current=T;let R=(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:L,gap:A}=R;S.current=R;let z=(0,i.useCallback)(e=>{$.current={index:e,until:Date.now()+1600},f(e)},[]),P=(0,i.useCallback)((e,t)=>{let n=$.current;if(n&&Date.now()<n.until)return void f(n.index);$.current=null;let r=t.filter(e=>null!==e.targetTurn.scrollTop);if(0===r.length)return void f(null);let i=e.scrollTop+.3*e.clientHeight;f(r.reduce((e,t)=>Math.abs((t.targetTurn.scrollTop??0)-i)<Math.abs((e.targetTurn.scrollTop??0)-i)?t:e,r[0]).index)},[]),W=(0,i.useCallback)(()=>{let e=o.current;if(!e)return;let t=e.scrollHeight-e.clientHeight,n=w.current;d(t>20),P(e,n)},[o,P]),O=(0,i.useRef)(null),F=(0,i.useCallback)(()=>{O.current||(O.current=setTimeout(()=>{O.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 M.current){let o=nT(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 c=function(e){if("assistant"!==e.role)return"";let{answerBlocks:t}=nP(e);return t.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n").trim()}(t);c&&a.assistantPreviews.push({markdown:c,element:s})}let c=i.map((e,t)=>({topRatio:0,targetTurn:e,index:t}));g(t.clientHeight),w.current=c,p(c),d(e.scrollHeight-e.clientHeight>20),P(e,c);let u=I.current,h=u?c[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;I.current=null,z(h.index);let i=.3*e.clientHeight;e.scrollTo({top:Math.max(0,n-i),behavior:"smooth"})}},150))},[z,s,o,P]);(0,i.useEffect)(()=>{let e=o.current;if(e)return e.addEventListener("scroll",W,{passive:!0}),()=>e.removeEventListener("scroll",W)},[o,W]),(0,i.useEffect)(()=>{let e=o.current;if(!e)return;let t=()=>{F(),W()},n=new ResizeObserver(t);return n.observe(e),e.firstElementChild&&n.observe(e.firstElementChild),t(),()=>{n.disconnect(),O.current&&(clearTimeout(O.current),O.current=null)}},[F,o,W]),(0,i.useEffect)(()=>{let e=setTimeout(()=>{F(),W()},50);return()=>clearTimeout(e)},[t.length,F,W]);let D=(0,i.useCallback)((e,t)=>{let n=o.current;if(!n)return;if(z(e.index),null===e.targetTurn.scrollTop){I.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})},[z,l,o]),B=(0,i.useCallback)((e,t)=>{let n=o.current;if(!n)return;let r=e.targetTurn.assistantPreviews[t]?.element;if(!r){I.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;z(e.index),n.scrollTo({top:Math.max(0,s),behavior:"smooth"})},[z,l,o]),H=(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)),c=t[a];if(!r&&Math.abs(o-c.topRatio*i)>Math.max(10,n/2))return null;return c},[]),_=(0,i.useCallback)((e,t,n)=>{let r=o.current;if(!r)return;let i=e.targetTurn.assistantPreviews[t]?.element;if(!i){I.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(),c=s.getBoundingClientRect().top-a.top+r.scrollTop-.3*r.clientHeight;z(e.index),r.scrollTo({top:Math.max(0,c),behavior:"smooth"})},[z,l,o]),U=(0,i.useCallback)(()=>{E.current&&(clearTimeout(E.current),E.current=null)},[]),K=(0,i.useCallback)(()=>{U(),v(!0)},[U]),q=(0,i.useCallback)(()=>{U(),E.current=setTimeout(()=>{E.current=null,v(!1),y(null)},250)},[U]);(0,i.useEffect)(()=>()=>U(),[U]);let Z=(0,i.useCallback)(e=>{if(!c)return;j.current=!0,K();let t=e.currentTarget.getBoundingClientRect();y(Math.max(0,Math.min(1,(e.clientY-t.top)/t.height)));let n=(e,n)=>{let r=H(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)},[H,D,K,c]),V=null===b?null:H(b),J=V?.index??null;if((0,i.useEffect)(()=>{if(!x||null===J)return;let e=C.current,t=N.current.get(J);if(!e||!t)return;let n=t.offsetTop-(e.clientHeight-t.offsetHeight)/2;e.scrollTop=Math.max(0,n)},[u,x,J]),!c)return null;let Y=Math.max(1,(L.length>0?L[L.length-1].topRatio*m:12)-12);return(0,r.jsxs)("div",{ref:k,onMouseDown:Z,onMouseEnter:K,onMouseLeave:q,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:Y,width:1,background:"var(--border)",transform:"translateX(-50%)",zIndex:0}}),L.map(e=>{let t=x&&V?.index===e.index,n=h===e.index;return(0,r.jsx)("div",{"data-minimap-node-index":e.index,"data-minimap-node-active":n?"":void 0,style:{position:"absolute",top:`${100*e.topRatio}%`,transform:"translateY(-50%)",left:0,right:0,height:Math.max(1,A),display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none",zIndex:2},children:(0,r.jsx)("div",{style:{width:8,height:8,borderRadius:2,background:n?"rgba(128,128,128,0.42)":"rgba(128,128,128,0.16)",border:`1.5px solid ${n?"rgba(128,128,128,0.95)":"rgba(128,128,128,0.58)"}`,boxShadow:n?"0 0 0 2px var(--bg-panel)":"none",transition:"transform 0.1s, background 0.1s",transform:t?"scale(1.25)":"scale(1)"}})},e.index)}),x&&u.length>0&&(0,r.jsx)("div",{ref:C,className:su().preview,"data-minimap-preview-box":"",onMouseEnter:K,onMouseDown:e=>e.stopPropagation(),onMouseMove:e=>e.stopPropagation(),children:u.map(e=>{var t;let n=J===e.index;return(0,r.jsxs)("div",{ref:t=>{t?N.current.set(e.index,t):N.current.delete(e.index)},className:su().turn,"data-minimap-preview-index":e.index,"data-located":n?"true":void 0,children:[(0,r.jsxs)("span",{className:su().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:su().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:su().content,children:[(0,r.jsx)("button",{type:"button",className:su().user,"data-minimap-preview-user":e.index,onClick:()=>{D(e,"smooth")},children:(0,r.jsx)("span",{className:su().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:su().assistant,children:[(0,r.jsx)("button",{type:"button",className:su().assistantJump,"data-minimap-preview-assistant":`${e.index}-${n}`,onClick:()=>B(e,n),"aria-label":a("chatMinimap.locateAssistant"),title:a("chatMinimap.locateAssistant"),children:"A"}),(0,r.jsx)(sg,{markdown:t.markdown,onAnswerClick:()=>B(e,n),onHeadingClick:t=>_(e,n,t)})]},n))]})]},e.index)})})]})}var sv=n(42790);function sb(e){let{text:t}=e,n=(0,i.useMemo)(()=>new sv.v().ansi_to_html(t),[t]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:n}})}function sy(e){let t,n,o,{widgets:s,children:l}=e,{t:a}=(0,eh.s)(),c=(0,i.useId)(),d=(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=d.current,e?Array.from(t,t=>{let[n,r]=t,i=e.get(n);return i&&i.length===r.length?r.some((e,t)=>e!==i[t])?n:null:i?n:null}).filter(e=>null!==e):[]);for(let[e,n]of(d.current=t,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=`${c}-trigger-${t}`,o=`${c}-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)(sb,{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"),d=`${c}-trigger-${t}`,u=`${c}-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:d,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 sj="command:";function sk(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(sj))return null;let t=e.slice(sj.length).trim();return t.length>1&&t.startsWith("/")?t:null}(n.key);if(r){let n=nk(e).replace(/\s+/g," ").trim();t.push({kind:"command",command:r,label:n||r})}else nk(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?nk(e.text):e.label).join(" "),c=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)(sb,{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)(sy,{widgets:n,children:c}):c})}function sw(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document;return"visible"!==e.visibilityState||!e.hasFocus()}function sS(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 sC(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 sN(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sE(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(!sN(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=sN(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=sN(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 s$ extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}function sI(e){return e instanceof s$&&"prompt_rejected"===e.code&&!1===e.accepted}async function sT(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 s$(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}function sM(){return globalThis.__piSessionViewCache||(globalThis.__piSessionViewCache=new Map),globalThis.__piSessionViewCache}function sR(e){try{return JSON.stringify(e).length}catch{return Number.MAX_SAFE_INTEGER}}function sL(e){let t=sM().get(e);return t?Date.now()-t.savedAt>6e5?(sM().delete(e),null):(sM().delete(e),sM().set(e,t),t):null}function sA(e){if(!e.sessionId||!e.revision)return!1;let t=sM();t.delete(e.sessionId);let n={...e,savedAt:Date.now()};return!(sR(n)>0x2000000)&&(t.set(n.sessionId,n),!function(){let e=sM();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+=sR(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-=sR(r))}}(),sM().has(n.sessionId))}function sz(e){sM().delete(e)}var sP=n(14755);let sW="pi-tool-preset";function sO(){try{return window.localStorage}catch{return null}}function sF(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 sD(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,sF(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),sF(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function sB(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 sH(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(sB).filter(Boolean)}):JSON.stringify({text:"",images:[]})}class s_ 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 sU{constructor(e){this.options=e,this.current=null,this.retry=null,this.retryGeneration=0}close(){this.stopRetrying(),this.current&&this.discard(this.current,new s_("closed"))}maintain(e){if(!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof s_?"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 s_("closed")}if(1===t.source.readyState)return;this.discard(t,new s_("closed"))}}open(e){let t,n,r;this.current&&this.discard(this.current,new s_("closed"));try{t=this.options.createSource(e)}catch(e){throw new s_("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 s_("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 s_("startup_error",e));return}this.options.onEvent(t)}},t.onerror=()=>{this.fail(a,new s_("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 sK(e){return("tool_execution_start"===e.type||"tool_execution_update"===e.type||"tool_execution_end"===e.type)&&"string"==typeof e.parentToolCallId&&""!==e.parentToolCallId}function sq(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 sZ(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sV(e,t){return e.every(e=>t.has(e.id))?e:e.filter(e=>t.has(e.id))}function sJ(e,t){return e.some(e=>e.id===t)?e.filter(e=>e.id!==t):e}function sY(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return e+t>=n-r}let sG={isStreaming:!1,streamingMessage:null};function sX(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 sQ(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"resume":return{...e,isStreaming:!0};case"snapshot":{let n=sE(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 sX(e,n.contentIndex,()=>({type:"text",text:""}));case"text_delta":return sX(e,n.contentIndex,e=>e?.type==="text"?{...e,text:e.text+n.delta}:null);case"text_end":return sX(e,n.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:n.content}));case"thinking_start":return sX(e,n.contentIndex,()=>({type:"thinking",thinking:""}));case"thinking_delta":return sX(e,n.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+n.delta}:null);case"thinking_end":return sX(e,n.contentIndex,e=>({...e?.type==="thinking"?e:{},type:"thinking",thinking:n.content}));case"toolcall_start":return sX(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 sX(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 sX(e,n.contentIndex,()=>({type:"toolCall",toolCallId:n.toolCall.id,toolName:n.toolCall.name,input:n.toolCall.arguments}));default:return e}case"end":return sG;default:return e}}function s0(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function s1(e){return e&&"auto"!==e?e:null}let s2=new Map,s4=[2e3,5e3,1e4];function s8(e){return new Promise(t=>setTimeout(t,e))}function s3(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function s5(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:s3(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:s3(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=s3(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function s6(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 s9(e){return Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)}let s7=null,le=null;function lt(e){let{label:t}=e,[n,o]=(0,i.useState)(()=>le);if((0,i.useEffect)(()=>{if(le)return;let e=!1;return(s7??=fetch("/api/app-update").then(async e=>{if(!e.ok)return null;let t=await e.json();return t.updateAvailable&&t.latestVersion&&t.releaseUrl?t:null}).then(e=>(le=e,e)).catch(()=>(s7=null,null))).then(t=>{!e&&t&&o(t)}),()=>{e=!0}},[]),!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 ln(e){let{messageCount:t,toolCallCount:n,defaultExpanded:o=!1,reveal:s=!1,children:l,t:a}=e,[c,d]=(0,i.useState)(o);(0,i.useLayoutEffect)(()=>{s&&d(!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":c||s,onClick:()=>d(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(c?"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:c?"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 ")})]}),(c||s)&&(0,r.jsx)("div",{style:{marginTop:8},children:l})]})}function lr(e){var t;let o,{session:l,searchTarget:a,onSearchTargetHandled:c,initialScrollPosition:d,onScrollPositionChange:u,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:f,newSessionContextBar:m,initialNewSessionChoices:g,onNewSessionChoicesChange:x,onAgentEnd:v,onAttentionNeeded:b,onSessionCreated:y,onSessionForked:j,modelsRefreshKey:k,chatInputRef:w,onBranchDataChange:S,onSystemPromptChange:C,onSystemToolsChange:N,onSystemInfoLoaderChange:E,onSessionStatsChange:$,onSessionStatsPanelOpen:I,onOpenSettings:T,onContextUsageChange:M,onOpenFile:R,onFilesUploaded:L,onOpenSession:A,onAskInNewChat:z,quoteSelectionEnabled:P=!1,initialPrompt:W,onInitialPromptConsumed:O,soundEnabled:F=!0,onSoundToggle:D,playDoneSound:B=()=>{},unlockAudio:H}=e,{t:_}=(0,eh.s)(),U=ew(),K=l?.relation?.kind!=="subagent",q=(0,i.useRef)(B);q.current=B;let Z=(0,i.useRef)(F);Z.current=F;let V=(0,i.useRef)(!1),J=(0,i.useCallback)(e=>{K&&Z.current&&!e.aborted&&q.current(),v?.(e)},[K,v]),Y=(0,i.useRef)(a?null:d??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:ei,entryIds:eo,historyCursor:es,hasEarlierMessages:el,streamState:ea,agentRunning:ec,bashRunning:ed,pendingBash:eu,modelNames:ep,modelList:ef,modelError:em,modelScopeWarnings:eg,modelThinkingLevels:ex,modelThinkingLevelMaps:ev,toolPreset:eb,thinkingLevel:ey,retryInfo:ej,contextUsage:ek,forkingEntryId:eC,isCompacting:eN,compactError:eE,compactResult:e$,displayModel:eT,modelSwitching:eM,sessionStats:eR,slashCommands:eL,slashCommandsLoading:eA,queuedMessages:ez,notices:eP,extensionDialog:eW,waitingExtensionDialogCount:eO,extensionCustomUi:eF,waitingExtensionCustomUiCount:eD,extensionStatuses:eB,extensionWidgets:eH,respondToExtensionUi:e_,sendExtensionCustomInput:eU,setNoticePaused:eK,addNotice:eq,isAutoModelSelection:eZ,isAutoThinkingSelection:eV,defaultModel:eJ,savedDefaultThinkingLevel:eY,agentPhase:eG,isNew:eX,editEntryId:eQ,showScrollToBottom:e0,sessionIdRef:e1,scrollContainerRef:e8,lastUserMsgRef:e3,promptAnchorActive:e5,handleSend:e6,handleAbort:e9,handleFork:e7,handleEditContent:te,cancelEdit:tt,handleModelChange:tn,handleCompact:tr,handleSteer:ti,handleFollowUp:to,handlePromptWithStreamingBehavior:ts,handleAbortCompaction:tl,dismissCompactError:ta,handleRecallQueue:tc,handleBuiltinSlashCommand:td,handleToolPresetChange:tu,handleThinkingLevelChange:tp,handleSetDefaultModel:th,handleSetDefaultThinkingLevel:tf,loadSlashCommands:tm,scrollUserMsgToTop:tg,loadContext:tx,activeLeafId:tv,scrollToBottom:tb,scrollToMessage:ty}=function(e){let{session:t,newSessionCwd:r,newSessionDraftKey:o,onAgentEnd:s,onAttentionNeeded:l,onSessionCreated:a,onSessionForked:c,modelsRefreshKey:d,onBranchDataChange:u,onSystemPromptChange:p,onSystemToolsChange:h,onSystemInfoLoaderChange:f,onSessionStatsPanelOpen:m,onOpenSettings:g}=e,x=null===t&&null!==r,v=x?e.initialNewSessionChoices??null:null,[b,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(!x),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),[E,$]=(0,i.useState)([]),[I,T]=(0,i.useState)(new Map),[M,R]=(0,i.useState)([]),[L,A]=(0,i.useState)(null),[z,P]=(0,i.useState)(!1),[W,O]=(0,i.useReducer)(sQ,sG),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)(!1),[_,U]=(0,i.useState)(null),[K,q]=(0,i.useState)({}),[Z,V]=(0,i.useState)([]),[J,Y]=(0,i.useState)(null),[G,X]=(0,i.useState)([]),[Q,ee]=(0,i.useState)({}),[et,en]=(0,i.useState)({}),[er,ei]=(0,i.useState)(()=>v?.model??null),[eo,es]=(0,i.useState)(null),[el,ea]=(0,i.useState)(sP.Q8),[ec,ed]=(0,i.useState)(()=>v?.thinkingLevel??null),[eu,ep]=(0,i.useState)(null),[eh,ef]=(0,i.useState)(null),[em,eg]=(0,i.useState)(null),[ex,ev]=(0,i.useState)(null),[eb,ey]=(0,i.useState)(null),[ej,ek]=(0,i.useState)(null),ew=(0,i.useRef)(0),eS=(0,i.useRef)(0),[eC,eN]=(0,i.useState)(null),[eE,e$]=(0,i.useState)(null),[eI,eT]=(0,i.useState)(null),[eM,eR]=(0,i.useState)(null),[eL,eA]=(0,i.useState)(null),[ez,eP]=(0,i.useState)(!1),[eW,eO]=(0,i.useState)(!1),[eF,eD]=(0,i.useState)(!0),[eB,eH]=(0,i.useState)(null),[e_,eU]=(0,i.useState)(null),[eK,eq]=(0,i.useState)(null),[eZ,eV]=(0,i.useState)(!1),[eJ,eY]=(0,i.useState)(!1),[eG,eX]=(0,i.useState)([]),[eQ,e0]=(0,i.useState)(!1),[e1,e2]=(0,i.useReducer)(s5,{visible:[],pending:[]}),[e4,e8]=(0,i.useState)(null),[e3,e5]=(0,i.useState)([]),[e6,e9]=(0,i.useState)([]),[e7,te]=(0,i.useState)([]),[tt,tn]=(0,i.useState)([]),[tr,ti]=(0,i.useState)({steering:[],followUp:[]}),to=(0,i.useRef)(null),ts=(0,i.useRef)(null),tl=(0,i.useRef)(0),ta=(0,i.useRef)(!1),tc=(0,i.useRef)(t?.id??null),td=(0,i.useRef)(t?.id??null),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)(!1),tx=(0,i.useRef)(0),tv=(0,i.useRef)(null),tb=(0,i.useRef)(!!e.deferInitialScroll),ty=(0,i.useRef)(null),tj=(0,i.useRef)(!1),tk=(0,i.useRef)(!0),tw=(0,i.useRef)(0),tS=(0,i.useRef)(null),tC=(0,i.useRef)(void 0),tN=(0,i.useRef)(void 0),tE=(0,i.useRef)(null),t$=(0,i.useRef)(null),tI=(0,i.useRef)([]),tT=(0,i.useRef)(null),tM=(0,i.useRef)(0),tR=(0,i.useRef)(!1),tL=(0,i.useRef)(v?.model??null),tA=(0,i.useRef)(v?.thinkingLevel??null),tz=(0,i.useRef)({}),tP=(0,i.useRef)(null),tW=(0,i.useRef)(0),tO=(0,i.useRef)(null),tF=(0,i.useRef)(!1),tD=(0,i.useRef)(new Map),tB=(0,i.useRef)(!0),tH=(0,i.useRef)(new Map),t_=(0,i.useRef)(null),tU=(0,i.useRef)([]),tK=(0,i.useRef)([]),tq=(0,i.useRef)(null),tZ=(0,i.useRef)(null),tV=(0,i.useRef)(!1);td.current=t?.id??null,t_.current=b,tU.current=E,tK.current=M,tq.current=C,tZ.current=L,tV.current=z,to.current||(to.current=new sU({createSource:e=>new EventSource(`/api/agent/${encodeURIComponent(e)}/events`),onEvent:e=>tv.current?.(e),shouldMaintain:e=>tB.current&&tc.current===e&&(tp.current||ta.current||td.current===e),readinessTimeoutMs:6e4,reconnectDelayMs:1e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let tJ=e.setToolPreset??ea,tY=t?.id;(0,i.useLayoutEffect)(()=>{(tY||x&&!tc.current)&&tJ(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:sO();if(!e)return sP.Q8;try{let t=e.getItem(sW);return(0,sP.sn)(t)?t:sP.Q8}catch{return sP.Q8}}())},[tY,x,tJ]);let tG=e.onNewSessionChoicesChange;(0,i.useEffect)(()=>{x&&tG?.({model:er,thinkingLevel:ec})},[x,er,ec,tG]);let tX=(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}),tw.current=t.scrollTop)},[]),tQ=eI??eM??b?.context.model??eL??null,t0=x?er??eo:tQ??(b?.context.messages.length===0?eo:null),t1=s1(b?.context.thinkingLevel&&"off"!==b.context.thinkingLevel?b.context.thinkingLevel:null),t2=x?ec??eu:em??ex??t1??(b?.context.messages.length===0?eu:null),t4=t?.id??o??void 0,t8=(0,i.useCallback)(e=>{eR(e?.model?{provider:e.model.provider,modelId:e.model.id}:null),e?.thinkingLevel!==void 0&&ev(s1(e.thinkingLevel))},[]),t3=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=tD.current.get(t);if(!e)break;t=e}return t},[]),t5=(0,i.useCallback)((t,n,r)=>{let i=n?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}}),s=t3(r);if(!tB.current&&!tR.current&&r===o)return;let l=e.chatInputRef?.current;if(l)l.restoreSubmission(t,i,s);else{let e,n;s&&(n=iQ(t,i,(e=iJ(s)??{value:"",images:[]}).value,e.images),iY(s,n))}},[o,e.chatInputRef,t3]),[t6,t9]=(0,i.useState)(()=>{let e=t?.id;return e&&!iJ(e)&&s2.delete(e),e&&s2.get(e)||null}),t7=(0,i.useCallback)(e=>{t?.id&&(e?s2.set(t.id,e):s2.delete(t.id),t9(e))},[t?.id]),ne=(0,i.useCallback)((n,r)=>{t?.id&&(e.chatInputRef?.current?.replaceMessage(n),t7(r))},[e.chatInputRef,t?.id,t7]),nt=(0,i.useCallback)(()=>t7(null),[t7]),nn=(0,i.useMemo)(()=>{if(e4)return{...e4,totalActiveMs:b?.totalActiveMs,...ej?{contextUsage:ej}:{}};let e=b?.stats,n=function(e,t,n){let r=sD(n);if(!e)return r;let i=sD(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,b?.context.messages??[],E);return 0!==n.tokens.total||0!==E.length||e?{sessionFile:b?.filePath||void 0,sessionId:tc.current??t?.id??"",sessionName:t?.name,...n,totalActiveMs:b?.totalActiveMs,...ej?{contextUsage:ej}:{}}:null},[E,e4,ej,b?.context.messages,b?.filePath,b?.totalActiveMs,b?.stats,t?.id,t?.name]),nr=(0,i.useCallback)((e,t,n,r)=>{tB.current&&tc.current===t&&tW.current===n&&!(r<=eS.current)&&(eS.current=r,e?.contextUsage!==void 0&&ek(e.contextUsage??null))},[]),ni=(0,i.useCallback)(async e=>{let t=tW.current,n=++ew.current;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();nr(i.state,e,t,n)}catch{}},[nr]),no=(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:tH.current.get(i);if(o)return await o;let s=(async()=>{let i=!1;try{t&&k(!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&&(y(null),N(null),$([]),R([]),A(null),P(!1),S(null)),sz(e),null;if(!s.ok)throw Error(`HTTP ${s.status}`);let l=await s.json();if(tc.current!==e)return null;let a=sL(e),c=!!(l.snapshotRevision&&a?.revision===l.snapshotRevision&&a.entryIds.length>=(l.context.entryIds??[]).length),d=c?tU.current:l.context.messages;if(y(c?{...l,context:{...l.context,messages:tU.current,entryIds:tK.current,oldestEntryId:tZ.current,hasMore:tV.current}}:l),N(l.leafId),c?sA({sessionId:e,revision:l.snapshotRevision,messages:tU.current,entryIds:tK.current,leafId:l.leafId,oldestEntryId:tZ.current,hasMore:tV.current,summaryTree:l.tree,thinkingLevel:l.context.thinkingLevel,model:l.context.model,stats:l.stats,totalActiveMs:l.totalActiveMs,loadedEntryIds:tK.current}):($(d),R(l.context.entryIds??[]),A(l.context.oldestEntryId),P(l.context.hasMore)),tu.current=void 0!==l.toolNames,tJ(void 0!==l.toolNames?(0,sP.YO)(l.toolNames):sP.Q8),eT(e=>tF.current?e:null),eg(null),S(null),"summary"===l.treeFormat&&l.snapshotRevision&&sA({sessionId:e,revision:l.snapshotRevision,messages:d,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&&(to.current?.close(),to.current?.maintain(e)),!n&&l.context.thinkingLevel&&"off"!==l.context.thinkingLevel&&ev(s1(l.context.thinkingLevel)),i=!0,t&&k(!1),!n)return null;try{let t=tW.current,n=++ew.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(tc.current!==e)return null;let o=i.state;return t8(o),o?(nr(o,e,t,n),void 0!==o.systemPrompt&&eN(o.systemPrompt??null),void 0!==o.extensionStatuses&&te(o.extensionStatuses??[]),void 0!==o.extensionWidgets&&tn(o.extensionWidgets??[]),void 0!==o.queuedMessages&&ti(s0(o.queuedMessages)),void 0!==o.autoCompactionEnabled&&eD(o.autoCompactionEnabled??!0)):i.running||ti({steering:[],followUp:[]}),i}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return S(String(e)),"error"}finally{t&&!i&&k(!1)}})();return r?.force||tH.current.set(i,s),s.finally(()=>{tH.current.get(i)===s&&tH.current.delete(i)}),await s},[nr,tJ,t8]),ns=(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(tc.current!==e||r?.signal?.aborted||!tB.current)return;return A(l.context.oldestEntryId),P(l.context.hasMore),y(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?($(e=>[...l.context.messages,...e]),R(e=>[...l.context.entryIds,...e])):($(l.context.messages),R(l.context.entryIds??[])),l.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),nl=(0,i.useCallback)(async e=>{try{let t=await sT(e,{type:"get_tools"});if(!t||!tB.current||tc.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return tJ(tu.current?r(t):sP.Q8),h?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[h,tJ]),na=(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=tc.current;if(x&&r&&i&&!tR.current&&(tR.current=!0,o)){if(o!==i){tD.current.set(o,i);let t=e.chatInputRef?.current;t?t.rekeyDraft(o,i):i0(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]),nc=(0,i.useCallback)(async()=>{if(tc.current||!x||!r)return tc.current;if(t$.current)return t$.current;let e=(async()=>{let e=tL.current,t=tA.current;e&&eA(e);let n=(0,sP.xG)(el);tu.current=void 0!==n;let i=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r,type:"ensure_session",...void 0!==n?{toolNames:n}:{},...e?{provider:e.provider,modelId:e.modelId}:{},...t?{thinkingLevel:t}:{}})});if(!i.ok){let e=await i.json().catch(()=>null);throw Error("string"==typeof e?.error?e.error:`HTTP ${i.status}`)}let o=await i.json(),s=o.sessionId;return tc.current=s,o.model&&tL.current===e&&(eA(o.model),e||es(o.model)),o.thinkingLevel&&tA.current===t&&(ev(s1(o.thinkingLevel)),t||ep(s1(o.thinkingLevel))),s})();t$.current=e;try{return await e}finally{t$.current=null}},[x,r,el]),nd=(0,i.useCallback)(async()=>{let e=tc.current??await nc();if(!e)return;let[t]=await Promise.all([sT(e,{type:"get_state"}),nl(e)]);tB.current&&tc.current===e&&(t8(t),eN(t.systemPrompt??""))},[nc,nl,t8]),nu=(0,i.useCallback)(e=>{tI.current=e,eX(e)},[]),np=(0,i.useCallback)(()=>{tM.current+=1,tT.current=null,nu([])},[nu]),nh=(0,i.useCallback)(()=>{let e=++tM.current,t=(async()=>{let t=tc.current??await nc();if(!t)return tM.current===e&&nu([]),[];e0(!0);try{let n=await sT(t,{type:"get_commands"}),r=n?.commands??[];return tM.current===e&&nu(r),r}catch(t){return console.error("Failed to load slash commands:",t),tM.current===e&&nu([]),null}finally{tM.current!==e&&tT.current||e0(!1)}})();tT.current=t;let n=()=>{tT.current===t&&(tT.current=null)};return t.then(n,n),t},[nc,nu]),nf=(0,i.useCallback)(async()=>await nh()??[],[nh]),nm=(0,i.useCallback)(async()=>{let e=tT.current,t=tI.current;return!e&&t.length>0?t:await (e??nh()).catch(()=>null)??(t.length>0?t:null)},[nh]),ng=(0,i.useCallback)(()=>{tl.current+=1,ta.current=!1,ts.current&&(clearTimeout(ts.current),ts.current=null)},[]),nx=(0,i.useCallback)(()=>{to.current?.close()},[]),nv=(0,i.useCallback)(e=>to.current.ensureConnected(e),[]),nb=(0,i.useCallback)(e=>{to.current.maintain(e)},[]);(0,i.useEffect)(()=>{let e=t?.id;if(e)return tB.current=!0,nb(e),()=>{tc.current===e&&to.current?.close()}},[nb,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||tc.current!==e||td.current!==e||(nx(),nb(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)}},[nx,nb,t?.id]);let ny=(0,i.useCallback)(async(e,t)=>{let n=tc.current;if(e5(t=>sJ(t,e.id)),n)try{await sT(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e)}},[]),nj=(0,i.useCallback)(async(e,t)=>{let n=tc.current;if(n)try{await sT(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),nk=(0,i.useCallback)(e=>{let t=e.message.trim();t&&e2({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"}})},[]),nw=(0,i.useCallback)(t=>{switch(sS(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":nk({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":te(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":tn(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":e9(e=>{let n;return t.closed?sJ(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)})}},[nk,l,e.chatInputRef]),nS=(0,i.useCallback)(()=>{let e=tp.current;return tp.current=!1,D(!1),eq(null),ey(null),T(new Map),O({type:"end"}),e},[]),nC=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return tm.current!==e&&(tm.current=e,s?.({aborted:t}),!0)},[s]),nN=(0,i.useCallback)(e=>{if(td.current===e)return void ng();ng(),ta.current=!0;let t=tl.current,n=async()=>{if(t===tl.current&&tc.current===e&&ta.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!==tl.current||tc.current!==e||!ta.current)return;let o=i.state;if(t8(o),i.running&&o&&(o.isStreaming||o.isPromptRunning)){ta.current=!1,ts.current=null,th.current=!!o?.isStreaming,tf.current=!!o?.isPromptRunning,tp.current=!0,D(!0),eq(o?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(i.running&&o?.isCompacting){eO(!0),ts.current=setTimeout(()=>void n(),600);return}ta.current=!1,ts.current=null,nx()}catch{if(t!==tl.current||tc.current!==e||!ta.current)return;ts.current=setTimeout(()=>void n(),600)}};ts.current=setTimeout(()=>void n(),3e4)},[ng,nx,t8]),nE=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tc.current,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tW.current;if(tW.current===t)try{e&&await no(e)}finally{if(tW.current!==t)return;let n=tf.current,r=th.current;tf.current=!1,th.current=!1,tO.current=null;let i=nS();n?nC(t):r&&i&&s?.({aborted:!1}),e&&nN(e)}},[no,nC,s,nN,nS]),n$=(0,i.useCallback)(async(e,t)=>{await s8(800);let n=Date.now();for(;tp.current&&Date.now()-n<2e4;){if(void 0!==t&&tW.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(t8(i),!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await nE(e,t)}}catch{}await s8(600)}},[nE,t8]),nI=(0,i.useCallback)(async e=>{let t=tx.current+1;for(tx.current=t;tg.current&&tx.current===t&&tc.current===e;){await s8(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(t8(r.state),r.state?.isBashRunning)continue;if(await no(e),tx.current!==t||tc.current!==e)return;tg.current=!1,H(!1),U(null);return}catch{}}},[no,t8]),nT=(0,i.useCallback)(async e=>{if(!tp.current||tc.current!==e)return;let t=tW.current,n=++ew.current;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(tc.current!==e||tW.current!==t)return;let o=i.state;if(nr(o,e,t,n),t8(o),eO(o?.isCompacting??!1),eD(o?.autoCompactionEnabled??!0),ti(s0(o?.queuedMessages)),i.running&&o&&(o.isStreaming||o.isPromptRunning||o.isCompacting)){th.current=!!o.isStreaming,tf.current=!!o.isPromptRunning;return}if(!tp.current)return;o&&(void 0!==o.systemPrompt&&eN(o.systemPrompt??null),void 0!==o.extensionStatuses&&te(o.extensionStatuses??[]),void 0!==o.extensionWidgets&&tn(o.extensionWidgets??[])),await nE(e,t)}catch{}},[nr,nE,t8]);(0,i.useEffect)(()=>{if(!F)return;let e=()=>{let e=tc.current;e&&nT(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)}},[F,nT]),(0,i.useEffect)(()=>{tp.current=F},[F]),tv.current=(0,i.useCallback)(e=>{switch(e.type){case"connected":if(O({type:"end"}),Array.isArray(e.pendingExtensionUiIds)){let t=new Set(e.pendingExtensionUiIds);e5(e=>sV(e,t)),e9(e=>sV(e,t))}!0===e.isStreaming&&(ng(),th.current=!0,tp.current=!0,D(!0),eq({kind:"waiting_model"})),tc.current&&ni(tc.current);break;case"agent_start":ng(),th.current=!0,tp.current=!0,D(!0),eq({kind:"waiting_model"}),ey(null),O({type:"start"});break;case"agent_end":if(!tp.current)break;if(eq(null),ey(null),O({type:"end"}),tc.current){let e=tc.current,t=tW.current,n=++ew.current;no(e),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(r=>{r&&tB.current&&tc.current===e&&tW.current===t&&(t8(r.state),nr(r.state,e,t,n),r.state?.systemPrompt!==void 0&&eN(r.state.systemPrompt??null),r.state?.extensionStatuses!==void 0&&te(r.state.extensionStatuses??[]),r.state?.extensionWidgets!==void 0&&tn(r.state.extensionWidgets??[]),ti(s0(r.state?.queuedMessages)))}).catch(()=>{})}break;case"agent_settled":{let t=th.current;if(th.current=!1,!t||tf.current)break;let n=tc.current,r=nS();eO(!1),n&&(no(n),nN(n)),r&&s?.({aborted:!0===e.aborted});break}case"prompt_done":{let t=tW.current,n=tf.current;tf.current=!1,tO.current=null;let r=nC(t,!0===e.aborted);if(!n&&!r)break;let i=tc.current;i&&no(i),!th.current&&(nS(),i&&nN(i))}break;case"prompt_error":nk({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":nk({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":if(!tp.current||sq(e))break;if("message_start"===e.type){let t=e.message;if(t?.role==="user")break;t?.role==="assistant"?(O({type:"snapshot",message:t}),t.content.length>0&&eq(null)):t&&eq(null)}else{let t=e.assistantMessageEvent;t&&(O({type:"delta",event:t}),"toolcall_start"!==t.type&&"toolcall_delta"!==t.type&&eq(null))}!tj.current&&tk.current&&null===tS.current&&(tS.current=requestAnimationFrame(()=>{tS.current=null,tk.current&&tX("auto")}));break;case"message_end":{if(!tp.current||sq(e))break;let t=e.message;if(t&&"user"===t.role){let e=sE(t),n=sH(e),r=tO.current;tO.current=null,$(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&sH(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]})}else if(t&&($(e=>[...e,sE(t)]),"assistant"===t.role)){let e=tc.current;e&&ni(e)}O({type:"end"}),eq({kind:"waiting_model"});break}case"tool_execution_start":{if(sK(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(sK(e))break;let t=e.toolCallId,n=e.toolName,r=e.partialResult,i=r?.content;("bash"===n||"powershell"===n||n===r7)&&Array.isArray(i)&&T(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===r7?function(e){if(!it(e))return null;let{calls:t}=ii(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(!sZ(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>sZ(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(sK(e))break;let t=e.toolCallId;T(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":ti({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":ey({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":ey(null);break;case"auto_compaction_start":case"compaction_start":eO(!0),eH(null),eU(null);break;case"auto_compaction_end":case"compaction_end":eO(!1),e.errorMessage?(eH(e.errorMessage),eU(null)):!e.aborted&&(eU(s6(e.result,e.reason??"auto")),tc.current&&no(tc.current));break;case"extension_ui_request":nw(e);break;case"extension_ui_closed":e5(t=>sJ(t,e.id))}},[nk,nr,ng,nw,no,nC,s,ni,nN,tX,nS,t8]);let nM=(0,i.useCallback)(async(e,n)=>{let i=e.trim();if(!i&&!n?.length)return;if(tp.current||tg.current)return void t5(e,n,t4);if(t6&&(t7(null),!await tN.current?.(t6))){t7(t6),t5(e,n,t4);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 tC.current?.(r,t):void t5(e,n,t4)}let s=tW.current+1;ng(),tf.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()};$(e=>[...e,a]),tO.current=sH(a),tW.current=s,tp.current=!0,D(!0),eq(o?{kind:"running_command"}:{kind:"waiting_model"}),O({type:"start"}),tj.current=!0,eV(!0);let c=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),d=null,u=!1;try{if(x&&r){let t=tc.current??await t$.current,n=t??await nc();if(!n)throw Error("Unable to create a session for the prompt");d=n,er&&(eA(er),t&&await sT(n,{type:"set_model",provider:er.provider,modelId:er.modelId})),await nv(n),u=!0,await sT(n,{type:"prompt",message:e,...c?.length?{images:c}:{}}),na(1,e)}else if(t)d=t.id,await nv(t.id),u=!0,await sT(t.id,{type:"prompt",message:e,...c?.length?{images:c}:{}});else throw Error("No active session for the prompt");o&&d&&n$(d,s)}catch(t){if(console.error("Failed to send message:",t),!(!u||sI(t))&&d)return void n$(d,s);if(tf.current=!1,$(e=>{let t=e.lastIndexOf(a);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),nk({type:"error",message:t instanceof Error?t.message:String(t)}),t5(e,n,t4),tO.current=null,d)return void nT(d);tp.current=!1,nx(),D(!1),eq(null),O({type:"end"})}},[x,r,er,t,nc,nv,na,n$,nk,ng,nx,t4,nT,t5,t6,t7]);tC.current=(0,i.useCallback)(async(e,n)=>{if(tp.current||tg.current)return;let r=`${n?"!!":"!"}${e}`;tg.current=!0,U({command:e,excludeFromContext:n}),H(!0);try{let i=tc.current??t?.id??await nc();if(!i)throw Error("Unable to create a session for the shell command");await sT(i,{type:"bash",command:e,excludeFromContext:n}),await no(i),na(1,r)}catch(e){console.error("Failed to execute shell command:",e),nk({type:"error",message:e instanceof Error?e.message:String(e)}),t5(r,void 0,t4)}finally{tg.current=!1,U(null),H(!1)}},[nk,t4,nc,no,na,t5,t]);let nR=(0,i.useCallback)(async()=>{let e=tc.current;if(e){if(tg.current){try{await sT(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await sT(e,{type:"abort"})}catch(e){console.error("Failed to abort:",e)}}},[]),nL=(0,i.useCallback)(async e=>{if(tg.current)return;let t=tc.current;if(t){e$(e);try{let{cancelled:n,newSessionId:r}=await sT(t,{type:"fork",entryId:e})??{};!n&&r&&c?.(r)}catch(e){console.error("Fork failed:",e),nk({type:"error",message:e instanceof Error?e.message:String(e)})}finally{e$(null)}}},[nk,c]),nA=(0,i.useCallback)(async e=>{if(tg.current)return!1;let t=tc.current;if(!t)return!1;try{let n=await sT(t,{type:"navigate_tree",targetId:e});if(n?.cancelled||tc.current!==t)return!1;return await no(t),tc.current===t}catch(e){return console.error("Failed to navigate:",e),!1}},[no]);tN.current=nA;let nz=(0,i.useCallback)(async e=>{if(tg.current||tp.current||eW)return;N(e);let t=tc.current;t&&(await ns(t,e),e&&sT(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[eW,ns]),nP=(0,i.useCallback)(async(e,t)=>{if(x){let n={provider:e,modelId:t};tL.current=n,ei(n),eA(n),null===tA.current&&ep(s1(tz.current[`${e}/${t}`])??tP.current);let r=tc.current??await t$.current;if(!r)return;try{await sT(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tc.current;if(n&&!tF.current){tF.current=!0,eT({provider:e,modelId:t}),eP(!0);try{let r=await sT(n,{type:"set_model",provider:e,modelId:t});eR({provider:r.provider,modelId:r.id}),tF.current=!1,await no(n)}catch(e){console.error("Failed to set model:",e),tF.current=!1,eT(eI),nk({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await no(n,!1,!0)}finally{tF.current=!1,eP(!1)}}},[nk,eI,x,no,ei]),nW=(0,i.useCallback)(async()=>{let e=tc.current;if(e&&!eW){eO(!0),eH(null),eU(null);try{let t=await sT(e,{type:"compact"});eU(s6(t,"manual")),await no(e,!0)}catch(e){eH(e instanceof Error?e.message:String(e)),eU(null)}finally{eO(!1)}}},[eW,no]),nO=(0,i.useCallback)(()=>eH(null),[]),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||Y(t instanceof Error?t.message:String(t)),t}q(n.models),Y(n.modelError??null),X(n.modelScopeWarnings??[]),ee(n.thinkingLevels??{}),en(n.thinkingLevelMaps??{});let s=n.modelList??[];V(s);let l=n.defaultModel?s.find(e=>e.id===n.defaultModel?.modelId&&e.provider===n.defaultModel?.provider):void 0;if(es(l?{provider:l.provider,modelId:l.id}:null),tz.current=n.thinkingLevelPins??{},tP.current=s1(n.defaultThinkingLevel),ef(s1(n.savedDefaultThinkingLevel)),x&&!tc.current){let e=tL.current,t=e&&(0===s.length||s.some(t=>t.provider===e.provider&&t.id===e.modelId));e&&!t&&(tL.current=null,ei(null));let r=t?e:l&&{provider:l.provider,modelId:l.id},i=r&&n.thinkingLevelPins?.[`${r.provider}/${r.modelId}`];null===tA.current&&ep(s1(i)??tP.current)}},[x,r,t?.cwd]),nD=(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]),nB=(0,i.useCallback)(()=>{nF().catch(()=>{})},[nF]),nH=(0,i.useCallback)(async(e,t)=>{try{await nD({provider:e,modelId:t})}catch(e){nk({type:"error",message:`Failed to save default model: ${e instanceof Error?e.message:String(e)}`});return}nk({type:"success",message:`Default model: ${e}/${t}`}),es({provider:e,modelId:t}),(t0?.provider!==e||t0?.modelId!==t)&&await nP(e,t),nB()},[nk,t0,nP,nB,nD]),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=tc.current??await nc(),s=e=>(e.handled&&(e.error?nk({type:"error",message:e.error}):e.action||nk({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!o||eW)return s({handled:!0,error:"No active session to compact"});eO(!0),eH(null),eU(null);let e=await sT(o,{type:"compact",...i?{customInstructions:i}:{}});return eU(s6(e,"manual")),await no(o,!0)&&na(),s({handled:!0,message:"Compacted context"})}case"auto-compact":{if(!o)return s({handled:!0,error:"No active session"});let e=await sT(o,{type:"get_state"}),t=!(e?.autoCompactionEnabled??!0);return await sT(o,{type:"set_auto_compaction",enabled:t}),eD(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 sT(o,{type:"reload"}),await Promise.all([no(o,!1,!0),nl(o),nf(),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 sT(o,{type:"set_session_name",name:i}),await no(o)&&na(),s({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!o)return s({handled:!0,error:"No active session"});let e=await sT(o,{type:"get_session_stats"});return e&&e8(e),m?.(),s({handled:!0,action:"openSessionStats"})}case"mcp":{if(i||!g)return{handled:!1};let e=await nm();if(!e||!(e.some(i5)||!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 sT(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(tp.current||tg.current)return s({handled:!0,error:"Cannot clone while the session is running"});let e=await sT(o,{type:"clone",leafId:C});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 c?.(e.newSessionId),t}default:return{handled:!1}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&eO(!1)}},[C,nk,nc,eW,nF,no,nf,nl,na,g,c,m,nm]),nU=(0,i.useCallback)(async(e,t,n)=>{let r=tc.current;if(t6)return void t5(e,n,t4);if(!r){t5(e,n,t4),nk({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 sT(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){console.error("Failed to submit streaming prompt:",t),sI(t)&&t5(e,n,t4),nk({type:"error",message:t instanceof Error?t.message:String(t)})}},[nk,t4,t6,t5]),nK=(0,i.useCallback)(async(e,t)=>{await nU(e,"steer",t)},[nU]),nq=(0,i.useCallback)(async(e,t,n)=>{await nU(e,t,n)},[nU]),nZ=(0,i.useCallback)(async(e,t)=>{await nU(e,"followUp",t)},[nU]),nV=(0,i.useCallback)(async()=>{let e=tc.current;if(e)try{await sT(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),nJ=(0,i.useCallback)(async()=>{let t=tc.current;if(t)try{let n=await sT(t,{type:"clear_queue"});ti({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),nk({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,nk]),nY=(0,i.useCallback)(async e=>{if("auto"===e){tA.current=null,ed(null),eg(null);return}x?(tA.current=e,ed(e)):eg(e);let t=tc.current??await t$.current;if(t)try{await sT(t,{type:"set_thinking_level",level:e}),tB.current&&tc.current===t&&(ev(e),eg(null))}catch(e){console.error("Failed to set thinking level:",e),eg(null)}},[x]),nG=(0,i.useCallback)(async e=>{try{await nD({thinkingLevel:e})}catch(e){nk({type:"error",message:`Failed to save default reasoning level: ${e instanceof Error?e.message:String(e)}`});return}nk({type:"success",message:`Default reasoning level: ${e}`}),ef(e),t2!==e&&await nY(e),nB()},[nk,t2,nY,nB,nD]),nX=(0,i.useCallback)(async e=>{let t=(0,sP.xG)(e);!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sO();if(t)try{t.setItem(sW,e)}catch{}}(e),tJ(e);let n=tc.current??await t$.current;if(!n){tu.current=void 0!==t;return}try{let e=await sT(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});tu.current=void 0!==t;let r=e?.sessionId??n;(r!==n||e?.recreated)&&(ng(),nx(),e5([]),e9([]),tc.current=r,e?.recreated&&td.current===r&&nb(r)),np(),te([]),tn([]);let[i]=await Promise.all([sT(r,{type:"get_state"}),nl(r)]);tB.current&&tc.current===r&&(eN(i.systemPrompt??""),t8(i))}catch(e){console.error("Failed to set tools:",e)}},[ng,np,nx,nl,nb,tJ,t8]),nQ=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=tE.current;n&&(null!==tS.current&&(cancelAnimationFrame(tS.current),tS.current=null),tb.current=!0,tj.current=!1,tk.current=!1,eV(!1),n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),tw.current=n.scrollTop)},[]),n0=(0,i.useCallback)(()=>{let e=tE.current,t=ty.current;if(!e||!t)return;let n=Math.min(Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop-16),Math.max(0,e.scrollHeight-e.clientHeight));null!==tS.current&&(cancelAnimationFrame(tS.current),tS.current=null),tk.current=!0,tw.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=tp.current,o=tk.current,s=function(e,t,n,r,i){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:96;return!!sY(n,r,i)||!(n<t)&&(!!(!e&&n>t&&sY(n,r,i,o))||e)}(o,tw.current,t,n,r,i?96:8);tk.current=s,tw.current=t;let l=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return!(n<=t)&&!sY(e,t,n,r)}(t,n,r);eY(e=>e===l?e:l),!o&&s&&i?tX("auto"):s||null===tS.current||(cancelAnimationFrame(tS.current),tS.current=null)}},[tX]);(0,i.useEffect)(()=>{if(tB.current=!0,eS.current=ew.current,t){tc.current=t.id;let e=sL(t.id);e&&(y({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}),N(e.leafId),$(e.messages),R(e.entryIds),A(e.oldestEntryId),P(e.hasMore),S(null),k(!1)),no(t.id,!e,!0,{force:!0}).then(e=>{e?.running&&(nl(t.id),(e.state?.isStreaming||e.state?.isPromptRunning)&&(th.current=!!e.state.isStreaming,tf.current=!!e.state.isPromptRunning,tp.current=!0,D(!0),eq(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),O({type:"resume"}),!e.state.isStreaming&&e.state.isPromptRunning&&n$(t.id)),e.state?.isBashRunning&&(tg.current=!0,H(!0),nI(t.id))),e?.state&&(void 0!==e.state.isCompacting&&eO(e.state.isCompacting),void 0!==e.state.systemPrompt&&eN(e.state.systemPrompt??null),void 0!==e.state.extensionStatuses&&te(e.state.extensionStatuses??[]),void 0!==e.state.extensionWidgets&&tn(e.state.extensionWidgets??[]),void 0!==e.state.queuedMessages&&ti(s0(e.state.queuedMessages)))})}return()=>{tB.current=!1;let e=x?o:null;e&&queueMicrotask(()=>{tB.current||tR.current||iG(e)});let t=tc.current,n=t_.current;if(t&&n&&n.sessionId===t&&n.snapshotRevision){let e=sL(t),r=tK.current;!e||r.every(t=>e.entryIds.includes(t)||(e.loadedEntryIds??[]).includes(t))?sA({sessionId:t,revision:n.snapshotRevision,messages:tU.current,entryIds:tK.current,leafId:tq.current,oldestEntryId:tZ.current,hasMore:tV.current,summaryTree:n.tree,thinkingLevel:n.context.thinkingLevel,model:n.context.model,stats:n.stats,totalActiveMs:n.totalActiveMs,loadedEntryIds:tK.current}):sz(t)}null!==tS.current&&(cancelAnimationFrame(tS.current),tS.current=null),tx.current+=1,ng(),nx()}},[]),(0,i.useEffect)(()=>{p?.(eC)},[eC,p]),(0,i.useEffect)(()=>(f?.(nd),()=>f?.(null)),[nd,f]);let n2=F||B||eW;(0,i.useEffect)(()=>{u&&u(b?.tree??[],C,nz,n2)},[b?.tree,C,nz,n2,u]),(0,i.useEffect)(()=>{let e=tE.current;if(e)return tw.current=e.scrollTop,e.addEventListener("scroll",n1,{passive:!0}),()=>{e.removeEventListener("scroll",n1)}},[E.length,j,n1]),(0,i.useEffect)(()=>{F||eV(!1)},[F]),(0,i.useLayoutEffect)(()=>{E.length>0&&(tj.current?(tj.current=!1,tb.current=!0,n0()):tb.current?!tp.current&&tk.current&&tX("auto"):(tb.current=!0,tX("instant")))},[E.length,F,tX,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>=s4.length||(await s8(s4[t]),e.signal.aborted))return}})(),()=>e.abort()},[nF,d]),(0,i.useEffect)(()=>{if(!e_)return;let e=setTimeout(()=>eU(null),6e3);return()=>clearTimeout(e)},[e_]);let[n4,n8]=(0,i.useState)(null),n3=(0,i.useRef)(5e3),n5=(0,i.useRef)(null),n6=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(0===e1.visible.length){n6.current=null;return}let e=e1.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{e2({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=e1.visible[0];if(!t||(n6.current!==t.id&&(n6.current=t.id,n3.current=5e3),e1.visible.some(e=>e.id===n4)))return;n5.current=Date.now();let n=setTimeout(()=>{e2({type:"mark_oldest_exiting"})},n3.current);return()=>{clearTimeout(n),null!==n5.current&&(n3.current=Math.max(0,n3.current-(Date.now()-n5.current)),n5.current=null)}},[e1.visible,n4]),(0,i.useEffect)(()=>{e8(null)},[E.length,ej?.tokens,ej?.percent,ej?.contextWindow]);let n9=t2??"auto",n7=e3[0]??null,re=Math.max(0,e3.length-1),rt=e6[0]??null,rn=Math.max(0,e6.length-1);return{data:b,loading:j,error:w,activeLeafId:C,messages:E,activeToolResults:I,entryIds:M,historyCursor:L,hasEarlierMessages:z,streamState:W,agentRunning:F,modelNames:K,modelList:Z,modelError:J,modelScopeWarnings:G,modelThinkingLevels:Q,modelThinkingLevelMaps:et,newSessionModel:er,toolPreset:el,thinkingLevel:n9,retryInfo:eb,contextUsage:ej,systemPrompt:eC,forkingEntryId:eE,isCompacting:eW,compactError:eB,compactResult:e_,currentModel:tQ,displayModel:t0,modelSwitching:ez,sessionStats:nn,autoCompactionEnabled:eF,slashCommands:eG,slashCommandsLoading:eQ,queuedMessages:tr,notices:e1.visible,extensionDialog:n7,waitingExtensionDialogCount:re,extensionCustomUi:rt,waitingExtensionCustomUiCount:rn,extensionStatuses:e7,extensionWidgets:tt,respondToExtensionUi:ny,sendExtensionCustomInput:nj,isAutoModelSelection:x&&null===er,isAutoThinkingSelection:x&&null===ec,defaultModel:eo,savedDefaultThinkingLevel:eh,agentPhase:eK,isNew:x,editEntryId:t6,promptAnchorActive:eZ,showScrollToBottom:eJ,sessionIdRef:tc,scrollContainerRef:tE,lastUserMsgRef:ty,pendingScrollToUserRef:tj,initialScrollDoneRef:tb,handleSend:nM,handleAbort:nR,handleFork:nL,handleNavigate:nA,handleModelChange:nP,handleCompact:nW,handleSteer:nK,handleFollowUp:nZ,handlePromptWithStreamingBehavior:nq,handleAbortCompaction:nV,dismissCompactError:nO,handleRecallQueue:nJ,handleBuiltinSlashCommand:n_,handleEditContent:ne,cancelEdit:t6?nt:void 0,addNotice:nk,setNoticePaused:n8,handleToolPresetChange:nX,handleThinkingLevelChange:nY,handleSetDefaultModel:nH,handleSetDefaultThinkingLevel:nG,loadTools:nl,loadSlashCommands:nf,setActiveLeafId:N,setData:y,setMessages:$,loadContext:ns,scrollToBottom:tX,scrollUserMsgToTop:n0,scrollToMessage:nQ,dispatch:O,setAgentRunning:D,setForkingEntryId:e$,bashRunning:B,pendingBash:_,handleAgentEventRef:tv}}({session:l,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:f,initialNewSessionChoices:g,onNewSessionChoicesChange:x,onAgentEnd:J,onAttentionNeeded:b,onSessionCreated:y,onSessionForked:j,modelsRefreshKey:k,chatInputRef:w,onBranchDataChange:S,onSystemPromptChange:C,onSystemToolsChange:N,onSystemInfoLoaderChange:E,onSessionStatsPanelOpen:I,onOpenSettings:T,deferInitialScroll:!!G}),tj=ec||ed,[tk,tw]=(0,i.useState)(null),[tS,tC]=(0,i.useState)(!1),[tN,tE]=(0,i.useState)(!1),[t$,tI]=(0,i.useState)(null),tT=(0,i.useRef)(null),tM=(0,i.useRef)(null),tR=(0,i.useCallback)(()=>{tw(null),tC(!1),tI(null)},[]);(0,i.useEffect)(()=>{P||tR()},[P,tR]);let tL=(0,i.useCallback)(()=>{if(!P||tS)return;let e=window.getSelection(),t=e?.rangeCount?e.getRangeAt(0):null,n=tB.current;if(!e||e.isCollapsed||!t||!n||!n.contains(t.commonAncestorContainer))return void tw(null);let r=e.toString().trim();if(!r)return void tw(null);let i=t.getBoundingClientRect(),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);tw({text:r,top:Math.min(window.innerHeight-44,i.bottom+8),left:Math.max(64,Math.min(window.innerWidth-64,i.left+i.width/2)),sourceEntryId:o})},[P,tS]);(0,i.useEffect)(()=>{tS&&tk&&tM.current?.insertIfEmpty(n1(tk.text,_("chat.quoteIntro"),_("chat.quoteQuestion")))},[tS,tk,_]),(0,i.useLayoutEffect)(()=>{let e=tT.current;if(!e||!tk)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(tk.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(tk.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)}},[tk,tS,t$]),(0,i.useEffect)(()=>{if(!tk)return;let e=e=>{tS||tT.current?.contains(e.target)||tR()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),tN||tR())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[tk,tS,tN,tR]);let tA=(0,i.useCallback)(()=>{tk&&(w?.current?.insertText(n1(tk.text,_("chat.quoteIntro"),_("chat.quoteQuestion"))),window.getSelection()?.removeAllRanges(),tR())},[w,tk,tR,_]),tz=(0,i.useCallback)(async e=>{let t=e1.current??l?.id;if(!tN&&e.trim()&&tk?.sourceEntryId&&t&&z){tE(!0),tI(null),H?.();try{await z(e,t,tk.sourceEntryId),tR()}catch(t){tM.current?.restoreSubmission(e),tI(t instanceof Error?t.message:String(t))}finally{tE(!1)}}},[z,tk,tN,l?.id,e1,tR,H]),tP=(0,i.useRef)(!1);(0,i.useEffect)(()=>{et||en||!W||tP.current||(tP.current=!0,O?.(),e6(W))},[W,et,en,e6,O]),(0,i.useEffect)(()=>{let e=!!eW&&!V.current;V.current=!!eW,K&&e&&q.current()},[K,eW]),(0,i.useEffect)(()=>{s=tj?e9:null},[tj,e9]);let[tW,tO]=(0,i.useState)(50),[tF,tD]=(0,i.useState)(null),tB=(0,i.useRef)(null),tH=(0,i.useRef)(null),t_=(0,i.useRef)(!1),tU=(0,i.useRef)(!1),tK=(0,i.useRef)(G);tK.current=G;let[tq,tZ]=(0,i.useState)(null),tV=er[eo.indexOf(tq?.entryId??"")],tJ=tV?.role==="assistant"?tq?.blockIndex===void 0?tV.content.find(e=>"text"===e.type):tV.content[tq.blockIndex]:void 0,tY=(0,i.useRef)({entryIds:eo,historyCursor:es,hasEarlierMessages:el});tY.current={entryIds:eo,historyCursor:es,hasEarlierMessages:el};let tG=(0,i.useRef)(null),tX=(0,i.useCallback)(async(e,t,n)=>{tG.current=t;let r=await tx(e,tv,t,n);return r||tG.current!==t||(tG.current=null),r},[tv,tx]);(0,i.useEffect)(()=>{es!==tG.current&&(tG.current=null)},[es]),(0,i.useLayoutEffect)(()=>{let e=l?.id,t=e8.current,n=tB.current;if(e&&u&&t&&n)return()=>{if(tK.current)return;if(sY(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:tY.current.historyCursor})}},[et,u,e8,l?.id]),(0,i.useEffect)(()=>{a&&X(null)},[a]),(0,i.useEffect)(()=>{let e=l?.id;if(!G||!e||et||a||tU.current)return;tU.current=!0;let t=new AbortController;return(async()=>{let n=tY.current;if(n.entryIds.includes(G.anchorEntryId)){tO(e=>Math.max(e,2*n.entryIds.length)),ee(!0);return}t_.current=!0;let r=n.historyCursor,i=n.hasEarlierMessages;try{for(;i&&r&&!t.signal.aborted;){let n=await tX(e,r,{signal:t.signal});if(t.signal.aborted)return;if(!n){tb("instant"),X(null);return}if(tO(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||(tb("instant"),X(null))}finally{t_.current=!1}})(),()=>{t.abort(),X(null)}},[tv,tX,et,G,tb,a,l?.id]),(0,i.useLayoutEffect)(()=>{let e=tB.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){ty(t,G.anchorOffset),X(null);return}Q&&(tb("instant"),X(null))},[eo,G,Q,tb,ty,a,tW]),(0,i.useEffect)(()=>{if(!a||et)return;let e=new AbortController;return(async()=>{let t=tY.current,n=t.entryIds.includes(a.entryId);if(!n&&!tj&&t.hasEarlierMessages&&t.historyCursor&&!t_.current){t_.current=!0;let r=e8.current;r&&(tH.current=r.scrollHeight-r.scrollTop);let i=await tX(a.sessionId,t.historyCursor,{tail:200,signal:e.signal});t_.current=!1,n=!!i?.entryIds.includes(a.entryId)}e.signal.aborted||(n?(tH.current=null,tO(e=>Math.max(e,(tY.current.entryIds.length+200)*2)),tZ(a)):c?.(a))})(),()=>e.abort()},[a,et,tj,tX,c,e8]),(0,i.useLayoutEffect)(()=>{if(!tq||tq!==a)return;let e=`[data-entry-id="${CSS.escape(tq.entryId)}"]`,t=e8.current?.querySelector(tV?.role==="user"?e:`${e} [data-search-target]`);t&&(ty(t),t.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500})),tZ(null),c?.(tq)},[tq,a,tV,e8,ty,c]),(0,i.useEffect)(()=>{let e=e8.current;if(!tF||!e)return;let t=new IntersectionObserver(t=>{if(!t[0]?.isIntersecting||t_.current)return;if(!el){tH.current=e.scrollHeight-e.scrollTop,tO(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50;return e+t})(e));return}if(!es||es===tG.current)return;let n=l?.id??e1.current;n&&(t_.current=!0,tH.current=e.scrollHeight-e.scrollTop,tX(n,es).finally(()=>{t_.current=!1}))},{root:e,threshold:0});return t.observe(tF),()=>t.disconnect()},[tF,tW,es,el,l,tX,e1,e8]),(0,i.useEffect)(()=>{tO(e=>Math.max(e,er.length))},[er.length]),(0,i.useEffect)(()=>{if(null==tH.current)return;let e=e8.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-tH.current),tH.current=null}},[tW,e8]);let tQ=eR?[eR.sessionId,eR.sessionFile??"",eR.sessionName??"",eR.userMessages,eR.assistantMessages,eR.toolCalls,eR.toolResults,eR.totalMessages,eR.tokens.input,eR.tokens.output,eR.tokens.cacheRead,eR.tokens.cacheWrite,eR.tokens.total,eR.cost??0,eR.totalActiveMs??0].join("|"):null,t0=(0,i.useRef)(eR);t0.current=eR,(0,i.useEffect)(()=>{$?.(t0.current)},[tQ,$]),(0,i.useEffect)(()=>()=>{$?.(null)},[$]);let t1=ek?`${ek.percent??"null"}|${ek.contextWindow}|${ek.tokens??"null"}`:null,t2=(0,i.useRef)(ek);t2.current=ek,(0,i.useEffect)(()=>{M?.(t2.current)},[t1,M]),(0,i.useEffect)(()=>()=>{M?.(null)},[M]);let t4=(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 e4(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=>e2(e.name,!1)).join(""));for(let e of(a&&w?.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,w,h,L,l?.cwd,_]),t8=(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&&w?.current?.addImages(t),r.length>0&&eq({type:"warning",message:_("chat.dropFoldersUnsupported",{names:r.join(", ")})}),n.length>0&&t4(n)},[eq,w,_,t4]),t3=(0,i.useCallback)(e=>{t8(e.map(e=>({kind:"file",file:e})))},[t8]),{isDragOver:t5,handleDragEnter:t6,handleDragOver:t9,handleDragLeave:t7,handleDrop:ne}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),o=(0,i.useCallback)(e=>{s9(e)&&(e.preventDefault(),r.current+=1,n(!0))},[]),s=(0,i.useCallback)(e=>{s9(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])}}(t8),nt=er.filter(e=>nT(e)||"assistant"===e.role),nn=(0,i.useMemo)(()=>{let e=new Map(ei);for(let t of er)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[ei,er]),nr=(0,i.useMemo)(()=>new WeakMap,[]),ni=(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]),no=(t=nt.length,(o=(0,i.useRef)([])).current=Array(t).fill(null).map((e,t)=>o.current[t]??null),o),ns=(0,i.useCallback)(()=>{tO(e=>Math.max(e,2*er.length))},[er.length]),nl=eX&&0===er.length&&!ea.isStreaming&&!tj;eS(e8,!!l?.id||!nl);let na=!!ea.streamingMessage?.content.length,nc=l?.cwd??h??void 0,nd=(0,i.useRef)(null),nu=(0,i.useRef)(0),np=(0,i.useRef)(null),nh=(0,i.useRef)(!1),nf=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=nd.current;if(!ec||!e5){nf.current=null,nu.current=0,nh.current=!1,e&&(e.style.height="");return}let t=e8.current,n=tB.current,r=e3.current;if(!t||!n||!r||!e)return;let i=!1,o=()=>{var o;let s;if(i||e8.current!==t||tB.current!==n||e3.current!==r||nd.current!==e)return;let l=t.getBoundingClientRect().top,a=Math.max(0,r.getBoundingClientRect().top-l+t.scrollTop-16),c=e.getBoundingClientRect().top-l+t.scrollTop,d=(o=t.clientHeight,0===(s=Math.max(0,a))?0:Math.max(0,Math.ceil(s+o-Math.max(0,c)))),u=!nh.current;u&&(nh.current=!0),d!==nu.current&&(nu.current=d,e.style.height=d>0?`${d}px`:"",u&&d>0&&tg())};nf.current=o,o();let s="u"<typeof ResizeObserver?null:new ResizeObserver(()=>{i||null!==np.current||(np.current=requestAnimationFrame(()=>{np.current=null,o()}))});return s?.observe(t),s?.observe(n),s?.observe(r),()=>{i=!0,nf.current===o&&(nf.current=null),s?.disconnect(),null!==np.current&&(cancelAnimationFrame(np.current),np.current=null)}},[ec,e3,er.length,e5,e8,tg]),(0,i.useLayoutEffect)(()=>{nf.current?.()},[ea.streamingMessage]);let nm=eT?ex[`${eT.provider}:${eT.modelId}`]??null:null,ng=eT?ev[`${eT.provider}:${eT.modelId}`]??null:null,nx=(0,r.jsx)(sc,{ref:w,onSend:e6,onAbort:e9,onSteer:ec?ti:void 0,onFollowUp:ec?to:void 0,onPromptWithStreamingBehavior:ec?ts:void 0,isStreaming:tj,model:eT,isAutoModelSelection:eZ,modelNames:ep,modelList:ef,modelError:em,modelScopeWarnings:eg,onModelChange:tn,modelSwitching:eM,defaultModel:eJ,onSetDefaultModel:th,onCompact:l||eX?tr:void 0,onAbortCompaction:tl,isCompacting:eN,compactError:eE,onDismissCompactError:ta,compactResult:e$,toolPreset:eb,onToolPresetChange:l||eX?tu:void 0,thinkingLevel:ey,isAutoThinkingSelection:eV,onThinkingLevelChange:l||eX?tp:void 0,availableThinkingLevels:nm,thinkingLevelMap:ng,savedDefaultThinkingLevel:eY,onSetDefaultThinkingLevel:l||eX?tf:void 0,retryInfo:ej,queuedMessages:ez,inputHistory:ni,onRecallQueue:tc,slashCommands:eL,slashCommandsLoading:eA,onLoadSlashCommands:tm,onBuiltinCommand:td,soundEnabled:F,onSoundToggle:D,onAudioUnlock:H,draftKey:l?.id??f??void 0,cwd:l?.cwd??h,onAttachFiles:t3});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:t6,onDragOver:t9,onDragLeave:t7,onDrop:ne,children:[t5&&(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)(li,{notices:eP,floating:!0,onPauseChange:eK})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[eW&&(0,r.jsx)(ll,{request:eW,waitingCount:eO,onRespond:e_},eW.id),eF&&(0,r.jsx)(la,{request:eF,waitingCount:eD,onInput:eU},eF.id),!nl&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:e8,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:tB,onPointerUp:tL,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(nT(er[e])){o=e;break}let s=new Map,a=0;er.forEach((e,t)=>{(nT(e)||"assistant"===e.role)&&s.set(t,a++)});let c=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.messageOverride??er[e];if(nI(n))return null;let o=nT(n)||"assistant"===n.role,a=s.get(e),c=t.keyPrefix??"message",d=eo[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&&ea.isStreaming&&e===er.length-1&&(u=!1)}void 0!==t.showTimestamp&&(u=t.showTimestamp);let p=(0,r.jsx)(ix,{message:n,toolResults:nn,modelNames:ep,cwd:nc,onOpenFile:R,onOpenSession:A,entryId:eo[e],searchBlock:eo[e]===tq?.entryId?tJ:void 0,onFork:ed||eX?void 0:e7,forking:eC===eo[e],onEditContent:tj?void 0:te,onCancelEdit:tt,isEditing:eQ===eo[e],showTimestamp:u,prevTimestamp:e>0?er[e-1].timestamp:void 0,sessionId:l?.id??e1.current??void 0,writtenFiles:t.writtenFiles,onCompact:t.recoverTruncation?tr:void 0,isCompacting:t.recoverTruncation?eN:void 0,compactError:t.recoverTruncation?eE:void 0},`${c}-view-${d}`);return o&&void 0!==a?(0,r.jsx)("div",{"data-entry-id":eo[e],ref:!1===t.attachRef?void 0:t=>{no.current[a]=t,e===i&&(e3.current=t)},children:p},`${c}-${d}`):p},d=[];for(let e=0;e<er.length;){let t,n=nT(er[e]);if(!n&&0!==e){d.push(c(e)),e+=1;continue}let i=n?e:-1,l=n?e:0,a=e+1;for(;a<er.length&&!nT(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&&nP(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||(tj||ea.isStreaming)&&a===er.length&&i===o){for(let e=l;e<a;e++)d.push(c(e));e=a;continue}n&&d.push(c(i));let p=function(e,t){let n=e.get(t);if(n)return n;let{answerBlocks:r}=nP(t),i=r.length>0||nL(t)||nA(t)?n0(t,r):null,o=t.content.indexOf(r[0]),s={answer:i,process:n0(t,t.content.slice(0,o<0?void 0:o),{omitUsage:!!i})};return e.set(t,s),s}(nr,er[u]),h=p.answer,f=[],m=0,g=!1;for(let e=i+1;e<=u;e++){let n=er[e];if("custom"===n.role){if(nI(n))continue;g||=!!(tq&&tq.entryId===eo[e]),f.push(c(e,{attachRef:!1,keyPrefix:"process"}));continue}if("assistant"!==n.role)continue;let r=e===u?p.process:n,i=nR(r);0!==i.length&&(t??=s.get(e),m+=i.filter(e=>"toolCall"===e.type).length,g||=!!(tq&&eo[e]===tq.entryId&&(!tJ||i.includes(tJ))),f.push(c(e,{attachRef:!1,keyPrefix:"process",messageOverride:r,showTimestamp:!1})))}if(f.length>0){let e=(h?.content??[]).some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0);d.push((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{no.current[t]=e},children:(0,r.jsx)(ln,{messageCount:f.length,toolCallCount:m,defaultExpanded:!e,reveal:g,t:_,children:f},e?"answered":"unanswered")},`process-group-${eo[l]??l}`))}if(h){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){let n=e.writtenFiles;return n&&n.length===t.length&&n.every((e,n)=>e.filePath===t[n].filePath)?n:(e.writtenFiles=t,t)}(p,function(e,t,n){let r=new Set,i=[];for(let s of e){var o;if("toolCall"!==s.type||!(nU(o=s.toolName)||nK(o))&&!nq(s.toolName))continue;let e=t?.get(s.toolCallId);if(e&&!e.isError)for(let t of nq(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 nZ(e).matchAll(/^\*\*\* Delete File: (.+)$/gm)){let e=(t[1]??"").trim();e&&n.add(e)}return n}(e,n),i=function(e){if(!nV(e)||!nV(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(nJ(n))return[];if(n&&"object"==typeof n&&!Array.isArray(n)){let e=nQ(nX(n.preview));if(e.length>0)return e}return nQ(nG(nZ(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 nD(n)}(t,n);e&&(r.has(e)||(r.add(e),i.push({filePath:e})))}}return i}(e,nn,nc));d.push(c(u,{messageOverride:h,writtenFiles:t,recoverTruncation:a===er.length&&!ea.isStreaming&&!nz(h)}))}for(let e=u+1;e<a;e++)d.push(c(e));e=a}let{startIndex:u}=(t=Math.min(Math.max(tW,0),Math.max(e=d.length,0)),{startIndex:n=Math.max(0,e-t),hasMore:n>0}),p=u>0||el;return(0,r.jsxs)(r.Fragment,{children:[p&&(0,r.jsx)("div",{ref:tD,className:"py-3 text-center text-xs text-text-muted",children:_("chat.loadEarlier")}),d.slice(u)]})})(),ea.isStreaming&&na&&ea.streamingMessage&&(0,r.jsx)(ix,{message:ea.streamingMessage,toolResults:nn,isStreaming:!0,modelNames:ep,cwd:nc,onOpenFile:R,onOpenSession:A}),ec&&!na&&(eG||eN)&&(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}(eG,_,eN)})}),ed&&!eu&&(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")})}),eu&&(0,r.jsx)(ix,{message:{role:"bashExecution",command:eu.command,output:"",excludeFromContext:eu.excludeFromContext},sessionId:l?.id??e1.current??void 0,onOpenSession:A}),(0,r.jsx)("div",{ref:nd,"aria-hidden":"true"})]})})}),U||G?null:(0,r.jsx)(sx,{messages:er,streamingMessage:ea.streamingMessage,scrollContainer:e8,messageRefs:no,onRevealHistory:ns})]})]}),P&&tk&&(0,eI.createPortal)((0,r.jsx)("div",{ref:tT,role:tS?"dialog":"toolbar","aria-label":_(tS?"chat.newQuoteChat":"chat.askSelection"),style:{position:"fixed",top:tk.top,left:tk.left,zIndex:260,display:"flex",flexWrap:"wrap",gap:3,width:tS?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:tS?12:3,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",boxShadow:"0 2px 10px rgba(0,0,0,0.12)"},children:tS?(0,r.jsxs)("fieldset",{disabled:tN,"aria-busy":tN,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:tN,onClick:tR,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)(sc,{ref:tM,compact:!0,onSend:tz,onAbort:tR,isStreaming:!1}),t$&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:t$})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:_("chat.askInCurrent"),"aria-label":_("chat.askInCurrent"),onPointerDown:e=>e.preventDefault(),onClick:tA,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")})]}),z&&tk.sourceEntryId&&!ed&&(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:_("chat.askInNewChat"),"aria-label":_("chat.askInNewChat"),onPointerDown:e=>e.preventDefault(),onClick:()=>{tC(!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:[!nl&&(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${e0&&!G?" is-visible":""}`,title:_("chat.scrollToLatest"),"aria-label":_("chat.scrollToLatest"),onClick:()=>tb("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"})})})}),nl&&(0,r.jsx)("div",{className:"new-session-hero",style:{paddingLeft:16,paddingRight:U?16:52},children:(0,r.jsxs)("div",{className:"new-session-hero-row",style:{maxWidth:"var(--chat-content-max-width, 820px)"},children:[(0,r.jsxs)("div",{className:"new-session-versions",children:[(0,r.jsxs)("span",{children:["web ",(0,r.jsxs)("span",{className:"new-session-version",children:["v","0.11.0"]})]}),(0,r.jsxs)("span",{children:["pi ",(0,r.jsxs)("span",{className:"new-session-version",children:["v","1.1.0"]})]})]}),(0,r.jsxs)("div",{className:"new-session-brand",style:{gap:U?7:10},children:[(0,r.jsx)(nv.default,{src:"/icons/apple-touch-icon.png",width:32,height:32,alt:"",priority:!0,style:{flexShrink:0}}),(0,r.jsx)("span",{className:"new-session-brand-name",children:"Pi Web"}),(0,r.jsx)(lt,{label:e=>_("appUpdate.releaseNotes",{version:e})})]}),m]})}),nx,(0,r.jsx)(sk,{statuses:eB,widgets:eH,onCommand:e6,commandsDisabled:tj})]}),nl&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}function li(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)=>{var s;let l,a,c,d="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:d,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:(s=e.message,l=[],a=(e,t)=>{if(!t)return;let n=l[l.length-1];n?.kind===e?n.text+=t:l.push({kind:e,text:t})},c=!1,s.split("\n").forEach((e,t)=>{let n=nN.test(e);t>0&&a(n&&c?"art":"text","\n"),a(n?"art":"text",e),c=n}),l).map((e,t)=>"art"===e.kind?(0,r.jsx)("span",{style:{display:"inline-block",verticalAlign:"top",maxWidth:"100%",overflowX:"auto",whiteSpace:"pre",fontFamily:"Menlo, Consolas, 'DejaVu Sans Mono', monospace",lineHeight:1,color:"var(--text)"},children:e.text},t):e.text)})]},e.id)})})}function lo(e){let{count:t}=e,{t:n}=(0,eh.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 ls(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 ll(e){let{request:t,waitingCount:n,onRespond:o}=e,{t:s}=(0,eh.s)(),[l,a]=(0,i.useState)("editor"===t.method?t.prefill??"":""),[c,d]=(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(c)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()}},[c]),(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:c?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:c?(0,r.jsxs)("button",{type:"button",onClick:()=>d(!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)(lo,{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)(lo,{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)(ls,{expanded:m})}),(0,r.jsx)("button",{type:"button",onClick:()=>d(!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)(rX,{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)(rX,{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 la(e){let{request:t,waitingCount:n,onInput:o}=e,{t:s}=(0,eh.s)(),l=(0,i.useRef)(null),a=(0,i.useRef)(!1),[c,d]=(0,i.useState)(!1),u=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(nj,""),i=nk(e).trimEnd();if(t.test(i))continue;let o=e,s=nC(o);("│"===s||"┃"===s)&&" "===nC(o=nS(o,0))&&(o=nS(o,0));let l=function(e){let t=nw(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(o),a=l>=0?nw(o)[l]?.char:void 0;("│"===a||"┃"===a)&&(o=nS(o,l)),n.push(function(e){let t=e;for(;;){let e=nw(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&&""===nk(n[0]).trim();)n.shift();for(;n.length>0&&""===nk(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)(()=>{c||l.current?.focus()},[c]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:c?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:c?(0,r.jsxs)("button",{type:"button",onClick:()=>d(!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)(lo,{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=n$[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":" ":nE[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)(lo,{count:n}),(0,r.jsx)("button",{type:"button",onClick:()=>d(!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)(sb,{text:u.join("\n")})})]})})}let lc=null,ld="";function lu(e){let{context:t,mobile:n,initialFocus:o,onInitialFocusDone:s,onPick:l,onUseDefaultDirectory:a,onOpenFolder:c,onRefreshWorktrees:d,onCreateWorktree:u}=e,{t:p}=(0,eh.s)(),[h,f]=(0,i.useState)(()=>ld),m=(0,i.useRef)(null),g=(0,i.useRef)(o),x=(0,i.useRef)(s);return x.current=s,(0,i.useEffect)(()=>{if(ld)return;let e=!1;return(lc??=fetch("/api/home").then(e=>e.json()).then(e=>ld=e.home??"").catch(()=>(lc=null,""))).then(t=>{!e&&t&&f(t)}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=g.current;if(!e)return;g.current=null,x.current();let t=m.current;ep(document,("worktree"===e?t?.button("worktree"):null)??t?.button("project")??null)},[]),(0,r.jsx)("div",{className:"new-session-context",children:(0,r.jsx)(nr,{handleRef:m,layout:"inline",context:t,mobile:n,label:p("workspace.newSessionContext"),homeDir:h,newWorktreeTitle:p("sidebar.newWorktreeForSession"),onPick:l,onUseDefaultDirectory:a,onOpenFolder:c,onRefreshWorktrees:d,onCreateWorktree:u})})}var lp=n(50640);let lh={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"},lf={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"},lm={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",mov:"video/quicktime",ogv:"video/ogg"};function lg(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}var lx=n(73620);let lv=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function lb(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 ly=["tags","categories","keywords","tag","category"];function lj(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=ly.find(e=>Array.isArray(n[e])),l=s?n[s].map(lb).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=lb(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 lk={source:"Source",preview:"Preview",diff:"Diff"},lw={fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:13,lineHeight:1.6},lS={...rE.xJ,'pre[class*="language-"]':{...rE.xJ['pre[class*="language-"]']}};delete lS['pre[class*="language-"]'].background;let lC={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 lN(){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 lE(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function l$(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=lE(n.startContainer),i=lE(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 lI(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"),c=a?s[0]:null,d=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:[c&&(0,lp.Ay)({node:c,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:d.map((e,r)=>(0,lp.Ay)({node:e,stylesheet:n,useInlineStyles:i,key:`source-token-${t}-${r}`}))})]},`source-line-${t}`)})}function lT(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=eV(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 lM(e){let{filePath:t,sourceSessionId:n}=e,{t:i}=(0,eh.s)();return(0,r.jsx)("a",{href:lT(t,"download",n),download:eJ(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 lR(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function lL(e){let t,{patch:n}=e,{t:i}=(0,eh.s)(),o=(t=r2(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=[],c=0;for(;c<o.length;)if(l.has(c)){let e=[];for(;c<o.length&&l.has(c);)e.push(o[c]),c++;a.push({hidden:!1,lines:e})}else{let e=0;for(;c<o.length&&!l.has(c);)e++,c++;a.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...lw},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:lC,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 lA(e){let{filePath:t,cwd:n,sourceSessionId:o,watchEnabled:s=!0}=e,{t:l}=(0,eh.s)(),[a,c]=(0,i.useState)(!1),[d,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=eJ(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),m(null),x(null),c(!1)},[t,o]),(0,i.useEffect)(()=>{if(c(!1),v.current&&(v.current.close(),v.current=null),!s)return;let e=!0,n=new EventSource(lT(t,"watch",o));v.current=n,n.addEventListener("connected",()=>{let n;c(!0),n=++b.current,fetch(lT(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=()=>{c(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,o,s]);let j=lT(t,"read",o,d?{v:d}:void 0),k=null!=p?lR(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:eG(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)(lM,{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 lz(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 lP(e){let{filePath:t,cwd:n,sourceSessionId:o,watchEnabled:s=!0}=e,{t:l}=(0,eh.s)(),[a,c]=(0,i.useState)(!1),[d,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=eJ(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),m(null),x(null),c(!1)},[t,o]),(0,i.useEffect)(()=>{if(c(!1),v.current&&(v.current.close(),v.current=null),!s)return;let e=!0,n=new EventSource(lT(t,"watch",o));v.current=n,n.addEventListener("connected",()=>{let n;c(!0),n=++b.current,fetch(lT(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=()=>{c(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,o,s]);let j=lT(t,"read",o,d?{v:d}: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:eG(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"audio"}),null!=f&&(0,r.jsx)("span",{children:lz(f)}),null!=p&&(0,r.jsx)("span",{children:lR(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)(lM,{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 lW(e){let{filePath:t,cwd:n,sourceSessionId:o,watchEnabled:s=!0}=e,{t:l}=(0,eh.s)(),[a,c]=(0,i.useState)(!1),[d,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=eJ(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),m(null),x(null),c(!1)},[t,o]),(0,i.useEffect)(()=>{if(c(!1),v.current&&(v.current.close(),v.current=null),!s)return;let e=!0,n=new EventSource(lT(t,"watch",o));v.current=n,n.addEventListener("connected",()=>{let n;c(!0),n=++b.current,fetch(lT(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=()=>{c(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,o,s]);let j=lT(t,"read",o,d?{v:d}: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:eG(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"video"}),null!=f&&(0,r.jsx)("span",{children:lz(f)}),null!=p&&(0,r.jsx)("span",{children:lR(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)(lM,{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 lO(e){let{filePath:t,cwd:n,sourceSessionId:o,initialPage:s,watchEnabled:l=!0}=e,{t:a}=(0,eh.s)(),[c,d]=(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=lg(t),y="pdf"===b,j=y&&s&&s>0?`#page=${s}`:"",k=y?`${lT(t,"read",o,u?{v:u}:void 0)}${j}`:lT(t,"preview",o,u?{v:u}:void 0);return(0,i.useEffect)(()=>{p(0),f(null),g(null),d(!1);let e=!0,n=++v.current;return fetch(lT(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(d(!1),x.current&&(x.current.close(),x.current=null),!l)return;let e=!0,n=new EventSource(lT(t,"watch",o));x.current=n,n.addEventListener("connected",()=>{let n;d(!0),n=++v.current,fetch(lT(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=()=>{d(!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:eG(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===b?"docx preview":"pdf"}),null!=h&&(0,r.jsx)("span",{children:lR(h)}),(0,r.jsx)(lM,{filePath:t,sourceSessionId:o}),(0,r.jsxs)("span",{title:a(c?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:c?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:c?"#4ade80":"var(--border)",display:"inline-block",boxShadow:c?"0 0 4px #4ade80":"none"}}),c?"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:eJ(t)}),style:{width:"100%",height:"100%",border:"none",background:y?"var(--bg)":"#eef1f5"}},k)})]})}function lF(e){let t,{filePath:n,cwd:i,sourceSessionId:o,onOpenFile:s,onMentionLines:l,onAtMention:a,gitRefreshKey:c,initialDisplayMode:d,initialState:u,initialPage:p,onStateChange:h,watchEnabled:f=!0}=e;return null!==(lh[lg(n)]??null)?(0,r.jsx)(lA,{filePath:n,cwd:i,sourceSessionId:o,watchEnabled:f}):null!==(lf[lg(n)]??null)?(0,r.jsx)(lP,{filePath:n,cwd:i,sourceSessionId:o,watchEnabled:f}):null!==(lm[lg(n)]??null)?(0,r.jsx)(lW,{filePath:n,cwd:i,sourceSessionId:o,watchEnabled:f}):null!==("pdf"===(t=lg(n))||"docx"===t?t:null)?(0,r.jsx)(lO,{filePath:n,cwd:i,sourceSessionId:o,initialPage:p,watchEnabled:f}):(0,r.jsx)(lD,{filePath:n,cwd:i,sourceSessionId:o,onOpenFile:s,onMentionLines:l,onAtMention:a,gitRefreshKey:c,initialDisplayMode:d,initialState:u,onStateChange:h,watchEnabled:f})}function lD(e){let{filePath:t,cwd:n,sourceSessionId:o,onOpenFile:s,onMentionLines:l,onAtMention:a,gitRefreshKey:c,initialDisplayMode:d,initialState:u,onStateChange:p,watchEnabled:h=!0}=e,{isDark:f}=rU(),{t:m}=(0,eh.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,E]=(0,i.useState)(!1),[$,I]=(0,i.useState)(null),T=u?.displayMode??d??"source",M=u?.wrapLines??!1,R=u?.scrollTop??0,L=u?.scrollLeft??0,[A,z]=(0,i.useState)(T),[P,W]=(0,i.useState)(M),[O,F]=(0,i.useState)(!1),D=(0,i.useRef)(null),B=(0,i.useRef)(0),H=(0,i.useRef)(0),_=(0,i.useRef)(null),U=(0,i.useRef)(!1),K=(0,i.useRef)(void 0===u&&void 0===d),q=(0,i.useRef)(!0),Z=(0,i.useRef)({displayMode:T,wrapLines:M,scrollTop:R,scrollLeft:L}),V=(0,i.useRef)(p),[J,Y]=(0,i.useState)(null);V.current=p;let G=(0,i.useCallback)(e=>{Z.current.displayMode=e,z(e)},[]),X=(0,i.useCallback)(()=>{W(e=>{let t=!e;return Z.current.wrapLines=t,t})},[]);(0,i.useEffect)(()=>(Z.current={displayMode:T,wrapLines:M,scrollTop:R,scrollLeft:L},q.current=!0,U.current=!1,z(T),W(M),()=>{V.current?.({...Z.current})}),[t,o,T,M,R,L]);let Q=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=++B.current;return fetch(lT(e,"read",o,{offset:t||void 0})).then(e=>e.json()).then(e=>n!==B.current?null:e.error?(I(e.error),null):(I(null),x(n=>t&&n?{...e,content:n.content+e.content}:e),e)).catch(e=>(n!==B.current||I(String(e)),null))},[o]),ee=(0,i.useCallback)(async e=>{let t=++H.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!==H.current)return;b(i.ok&&o.supported&&"string"==typeof o.patch?o:null)}catch{t===H.current&&b(null)}finally{t===H.current&&(j(!1),w(!0))}},[n]);(0,i.useEffect)(()=>{let e=!0;return C(!0),I(null),x(null),b(null),w(!1),F(!1),Q(t).finally(()=>{e&&C(!1)}),()=>{e=!1}},[t,Q,o]),(0,i.useEffect)(()=>{if(F(!1),D.current&&(D.current.close(),D.current=null),!h)return;let e=()=>{Q(t),ee(t)},n=new EventSource(lT(t,"watch",o));D.current=n,n.addEventListener("connected",()=>{F(!0),e()}),n.addEventListener("change",e);let r=()=>{F(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{n.close(),D.current===n&&(D.current=null)}},[t,Q,ee,o,h]),(0,i.useEffect)(()=>{ee(t)},[ee,t,c]),(0,i.useEffect)(()=>{K.current&&!g?.truncated&&(g?.language==="markdown"||g?.language==="html")&&(K.current=!1,G("preview"))},[g?.language,g?.truncated,G]);let et=v?.supported===!0&&"string"==typeof v.patch,en=et&&"deleted"===v.status;(0,i.useEffect)(()=>{k&&!et&&"diff"===A&&G("source")},[A,k,et,G]),(0,i.useEffect)(()=>{"diff"===T&&et&&!U.current&&(U.current=!0,G("diff"))},[T,et,G]);let er=(0,i.useMemo)(()=>g?.language==="markdown"?ra(g.content):"",[g]),ei=(0,i.useMemo)(()=>g?.language==="markdown"?function(e){let t=function(e){let t=lv.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,lx.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]),eo=g?.content??"",es=(0,i.useMemo)(()=>eo.split("\n"),[eo]),el=g?.language??"text",ea="html"===el,ec="markdown"===el,ed=!g?.truncated&&(ea||ec),eu=en?"diff":A,ep=es.length>1e3&&!("diff"===eu&&et)&&!("preview"===eu&&ed),ef=(0,i.useMemo)(()=>(0,r.jsx)(rN.A,{className:P?"file-source-view is-wrapped":"file-source-view",language:"text"===el?"plaintext":el,style:f?lS:rE.vs,showLineNumbers:!0,lineNumberStyle:{...lC},customStyle:{margin:0,padding:0,border:0,backgroundColor:"var(--bg)",...lw,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)(lI,{...e,wrapLines:P}),wrapLongLines:P,children:eo}),[f,el,eo,P]),em=(0,i.useMemo)(()=>ep?es.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:lC,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,[es,ep,P]);(0,i.useEffect)(()=>{let e=()=>{let e=_.current;Y(t=>{let n=l&&"source"===A&&e?l$(e,window.getSelection()):null;return null===t&&null===n||t&&n&&t.startLine===n.startLine&&t.endLine===n.endLine?t:n})};if(e(),l&&"source"===A)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[g?.content,A,l]);let eg=(0,i.useCallback)(e=>{l&&e&&l(eG(t,n),e.startLine,e.endLine)},[n,t,l]);if((0,i.useEffect)(()=>{if(!l||"source"!==A)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let n=_.current,r=n?l$(n,window.getSelection()):null;r&&(e.preventDefault(),eg(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[A,eg,l]),(0,i.useEffect)(()=>{if(!q.current||S||$&&!en||"diff"===T&&!k||"diff"===T&&et&&"diff"!==A)return;let e=_.current;e&&(e.scrollTop=Z.current.scrollTop,e.scrollLeft=Z.current.scrollLeft,q.current=!1)},[g?.content,A,$,k,et,en,S,T]),S||"diff"===T&&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($&&!en)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:$});if(!g&&!en)return null;let ex=eY(t),ev=en?["diff"]:["source",...ed?["preview"]:[],...et?["diff"]:[]],eb=en?m("files.deleted"):`${el} \xb7 ${es.length} lines \xb7 ${lR(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:eG(t,n)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:eb,children:eb}),!en&&(0,r.jsx)("span",{title:O?m("i18n.liveSync"):m("i18n.notWatching"),"aria-label":O?m("i18n.liveSync"):m("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:O?"#4ade80":"var(--border)",boxShadow:O?"0 0 4px #4ade80":"none"}}),(0,r.jsxs)("div",{className:"file-viewer-controls",children:[ev.length>1&&(0,r.jsx)("div",{className:"file-viewer-mode-switch","aria-label":m("i18n.fileViewMode"),children:ev.map(e=>{let t=eu===e;return(0,r.jsx)("button",{type:"button",onClick:()=>G(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:lk[e]},e)})}),(0,r.jsxs)("div",{className:"file-viewer-actions",children:[(a||l)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{J&&l?eg(J):a?.(eG(t,n),!1)},title:J&&l?`${m("i18n.mentionSelectedLines")} (L${J.startLine}${J.startLine!==J.endLine?`-L${J.endLine}`:""})`:m("files.insertPath"),"aria-label":m("files.mention"),disabled:!a&&!l,className:"file-viewer-icon-button",children:(0,r.jsx)(lN,{})}),"source"===eu&&(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("button",{type:"button",onClick:X,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"})]})})})]}),!en&&(0,r.jsx)(lM,{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:[lR(g.nextOffset)," / ",lR(g.size)]}),(0,r.jsx)("button",{type:"button",className:"file-viewer-mode-button",disabled:N,onClick:()=>{E(!0),Q(t,g.nextOffset).finally(()=>E(!1))},children:N?m("i18n.loading"):m("i18n.loadMore")})]}),(0,r.jsx)("div",{ref:_,className:"file-viewer-content",onScroll:e=>{Z.current.scrollTop=e.currentTarget.scrollTop,Z.current.scrollLeft=e.currentTarget.scrollLeft},style:{flex:1,overflow:"auto",background:"var(--bg)",paddingBottom:g?.truncated?48:void 0},children:"diff"===eu&&et?(0,r.jsx)(lL,{patch:v.patch}):ea&&"preview"===eu?(0,r.jsx)("iframe",{srcDoc:eo,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:m("i18n.htmlPreview")}):ec&&"preview"===eu?(0,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[ei?.data&&(0,r.jsx)(lj,{data:ei.data}),(0,r.jsx)(n2.oz,{remarkPlugins:rk,rehypePlugins:rS,urlTransform:s?ro:ri,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)(rq,{code:s.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(rJ,{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?nB(t,ex,n??ex):null;if(!l||!s)return t&&/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(t)?(0,r.jsx)("a",{href:t,...o,target:"_blank",rel:"noopener noreferrer",children:i}):(0,r.jsx)("a",{href:t,...o,children:i});return(0,r.jsx)("a",{href:t,...o,onClick:e=>{nW(e)&&(e.preventDefault(),s(l,n_(t)??void 0))},children:i})},img(e){let{src:t,alt:i,...s}=e;delete s.node;let l="string"==typeof t?nB(t,ex,n??ex):null,a=l?lT(l,"read",o):t;return(0,r.jsx)("img",{src:a,alt:i??"",loading:"lazy",...s})}},children:er})]}):ep?(0,r.jsx)("div",{className:"file-source-view is-lightweight",style:{width:P?"100%":"max-content",minWidth:"100%",minHeight:"100%",background:"var(--bg)",...lw},children:em}):ef})]})}function lB(e){let{tabs:t,activeTabId:n,onSelectTab:o,onCloseTab:s}=e,{t:l}=(0,eh.s)(),[a,c]=(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"})]}):eq(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:()=>c(e.id),onMouseLeave:()=>c(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 lH(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 l_=["general","models","archives","skills","agents","plugins","mcp"],lU="pi-web:settings-navigation",lK=new Set(["skills","agents","plugins"]);function lq(e){return lK.has(e)}function lZ(){try{return window.localStorage}catch{return null}}function lV(e){let t=e.getItem(lU);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 lJ(e,t){return"models"===e?e:t?JSON.stringify([e,t]):"mcp"===e?e:null}function lY(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:lZ();if(t)try{let n=lV(t);n.section=e,t.setItem(lU,JSON.stringify(n))}catch{}}function lG(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:lZ();if(!n)return null;let r=lJ(e,t);if(!r)return null;try{let e=lV(n).selections?.[r];return"string"==typeof e&&e.length>0?e:null}catch{return null}}function lX(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:lZ();if(!r||!t)return;let i=lJ(e,n);if(i)try{let e=lV(r);e.selections={...e.selections,[i]:t},r.setItem(lU,JSON.stringify(e))}catch{}}let lQ=["input","output","cacheRead","cacheWrite"];function l0(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 l1(e){if(!l2(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 l2(e){return lQ.some(t=>""!==e[t].trim())}function l4(e){return new Map(Object.entries(e.providers??{}).map(e=>{let[t,n]=e;return[t,(n.models??[]).map(e=>e.id)]}))}function l8(e,t,n){if(n<=0)return;let r=e.get(t)??[];e.set(t,[...r,...Array.from({length:n},()=>null)])}function l3(e){let{embedded:t,title:n,subtitle:i,closeLabel:o="Close",onClose:s,children:l,width:a=900,height:c="78vh"}=e,d=t?void 0:{"--config-panel-width":`${a}px`,"--config-panel-height":c};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:d,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 l5(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-split-view",children:t})}function l6(e){let{children:t}=e;return(0,r.jsx)("aside",{className:"config-sidebar",children:t})}function l9(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-sidebar-list",children:t})}function l7(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 ae(e){let{enabled:t,total:n,checked:i,label:o,disabled:s=!1,loading:l=!1,describedBy:a,onChange:c}=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)(aC,{checked:i??(n>0&&t===n),disabled:s,loading:l,label:o,describedBy:a,onChange:c})]})}function at(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 an(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 ar(e){let{className:t,...n}=e;return(0,r.jsx)("span",{...n,className:["config-sidebar-text",t].filter(Boolean).join(" ")})}function ai(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-stack",t].filter(Boolean).join(" ")})}function ao(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header",t].filter(Boolean).join(" ")})}function as(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header-info",t].filter(Boolean).join(" ")})}function al(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-actions",t].filter(Boolean).join(" ")})}function aa(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-title",children:t})}function ac(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-section-title",children:t})}function ad(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 au(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-grid",children:t})}function ap(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 ah(e){let{scope:t,children:n}=e;return(0,r.jsx)("span",{className:`config-scope-tag${"project"===t?" is-project":""}`,children:n})}function af(e){let{value:t,options:n,label:o,disabledReason:s,size:l="default",onChange:a,children:c}=e,d=(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?d:void 0,disabled:e.disabled,className:"config-scope-switch-option",onClick:()=>{e.disabled||a(e.value)},children:e.label},e.value))}),c]}),u&&(0,r.jsx)("span",{id:d,className:"config-scope-switch-reason",children:u})]})}function am(e){let{value:t,options:n,label:o,path:s,disabledReason:l,onChange:a,children:c}=e;return(0,r.jsxs)("div",{className:"config-save-target",children:[(0,r.jsx)(af,{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})}),c]})}function ag(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)(aa,{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 ax(e){let{title:t,catalogs:n,target:o,inputLabel:s,inputId:l,placeholder:a,value:c,canSubmit:d,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)(ai,{className:"is-fill",children:[(0,r.jsx)(ag,{title:t,catalogs:n,target:o}),(0,r.jsx)(ad,{label:s,children:x?(0,r.jsx)("textarea",{id:l,ref:y,value:c,"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(),d&&h())}}):(0,r.jsx)("input",{id:l,ref:b,value:c,"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&&d&&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 av(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 ab(e){let{id:t,message:n,trustLabel:i,trusting:o=!1,onTrust:s}=e;return(0,r.jsx)(av,{id:t,action:s&&i?(0,r.jsx)(aS,{size:"small",onClick:s,disabled:o,children:i}):void 0,children:n})}function ay(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-empty-state",children:t})}function aj(e){let{children:t,style:n}=e;return(0,r.jsx)("div",{className:"config-detail",style:n,children:t})}function ak(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 aw(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 aS(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 aC(e){let{checked:t,disabled:n=!1,loading:i=!1,size:o="default",label:s,describedBy:l,onChange:a}=e,c=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:c,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 aN(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 aE(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 a$(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 aI(e,t){let n=a$(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 aT(e,t){return t.enabled&&(e?.enabledTotal??0)<=1}function aM(e,t){return e?.providers.find(e=>e.id===t)}let aR={"last-model":"models.enabledLastModel","project-scope":"models.enabledProjectScope"};function aL(e){let{controller:t}=e,{t:n}=(0,eh.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)(aS,{size:"small",onClick:t.pruneStale,disabled:null!==o,title:n("models.enabledPruneHint"),children:n("models.enabledPrune")}),i.editable&&s&&(0,r.jsx)(aS,{size:"small",onClick:t.clearScope,disabled:null!==o,title:n("models.enabledClearHint"),children:n("models.enabledClear")})]}):null}function aA(e){let{providerId:t,controller:n,noteId:i}=e,{t:o}=(0,eh.s)(),{view:s,loading:l,pending:a,failure:c}=n,d=aM(s,t),u=c?c.messageKey?o(c.messageKey):c.message:null,p=az(n,t)?i:void 0;if(l&&!s)return null;if(!d)return(0,r.jsx)(aC,{checked:!1,disabled:!0,label:o("models.enabledProviderToggle",{provider:t}),describedBy:p,onChange:()=>{}});let h=aI(s,d);return(0,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("span",{className:"enabled-models-switch-error",children:u}),(0,r.jsx)(aC,{checked:h.checked,loading:a===`provider:${d.id}`,disabled:null!==a||h.blocked,label:o("models.enabledProviderToggle",{provider:d.name}),describedBy:p,onChange:e=>n.setProvider(d.id,e)})]})}function az(e,t){let{view:n,loading:r}=e;if(r&&!n)return null;let i=aM(n,t);if(!i)return"models.enabledCustomEmpty";let{reason:o}=aI(n,i);return o?aR[o]:null}function aP(e){let{providerId:t,controller:n,id:i}=e,{t:o}=(0,eh.s)(),s=az(n,t);return s?(0,r.jsx)("div",{id:i,className:"config-detail-heading-note",children:o(s)}):null}function aW(e){var t;let n,{providerId:o,controller:s}=e,{t:l}=(0,eh.s)(),[a,c]=(0,i.useState)(""),{view:d,loading:u,pending:p,failure:h}=s,f=aM(d,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)(()=>c(""),[o]),u&&!d)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=a$(d,x),b=x.length!==f.models.length,y=null!==p,j=`provider:${f.id}`,k=d?.editable===!0,w=`${g}-scope`,S=`${g}-last`,C=k&&!v.canDisable&&v.disableRefs.length>0,N=C||k&&x.some(e=>aT(d,e)),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)(aS,{size:"small",disabled:y||!v.canEnable,"aria-describedby":k?void 0:w,onClick:()=>E(!0,v.enableRefs),children:b?l("models.enableShown"):l("models.enableAll")}),(0,r.jsx)(aS,{size:"small",disabled:y||!v.canDisable,"aria-describedby":k?C?S:void 0:w,onClick:()=>E(!1,v.disableRefs),children:b?l("models.disableShown"):l("models.disableAll")}),(0,r.jsx)(aS,{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=>c(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=aT(d,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)(aC,{checked:e.enabled,loading:p===e.ref,disabled:y||!d?.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 aO(e){let{message:t,hint:n,value:i,placeholder:o,submitLabel:s,inputLabel:l,disabled:a=!1,plainEnterSubmits:c=!0,inputRef:d,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:d,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&&(c||t.metaKey||t.ctrlKey)&&h&&p()}}),(0,r.jsx)("button",{type:"button",className:"oauth-paste-submit",onClick:p,disabled:!h,children:s})]})]})}let aF={anthropic:{symbol:"anthropic",color:!1},openai:{symbol:"openai",color:!1},"openai-codex":{symbol:"openai",color:!1},google:{symbol:"google",color:!0},"google-vertex":{symbol:"google",color:!0},"ant-ling":{symbol:"antgroup",color:!0},deepseek:{symbol:"deepseek",color:!0},groq:{symbol:"groq",color:!1},mistral:{symbol:"mistral",color:!0},moonshotai:{symbol:"moonshot",color:!1},"moonshotai-cn":{symbol:"moonshot",color:!1},moonshot:{symbol:"moonshot",color:!1},minimax:{symbol:"minimax",color:!0},"minimax-cn":{symbol:"minimax",color:!0},fireworks:{symbol:"fireworks",color:!0},huggingface:{symbol:"huggingface",color:!0},cerebras:{symbol:"cerebras",color:!0},openrouter:{symbol:"openrouter",color:!1},xai:{symbol:"xai",color:!1},"cloudflare-ai-gateway":{symbol:"cloudflare",color:!0},"cloudflare-workers-ai":{symbol:"cloudflare",color:!0},"vercel-ai-gateway":{symbol:"vercel",color:!1},"github-copilot":{symbol:"githubcopilot",color:!1},"amazon-bedrock":{symbol:"aws",color:!0},azure:{symbol:"azure",color:!0},"azure-openai-responses":{symbol:"azure",color:!0},"kimi-coding":{symbol:"kimi",color:!0},nvidia:{symbol:"nvidia",color:!0},opencode:{symbol:"opencode",color:!1},"opencode-go":{symbol:"opencode",color:!1},qwen:{symbol:"qwen",color:!0},xiaomi:{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-ams":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-cn":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-sgp":{symbol:"xiaomimimo",color:!1},zai:{symbol:"zai",color:!1},"zai-coding-cn":{symbol:"zai",color:!1},zhipu:{symbol:"zhipu",color:!0},cohere:{symbol:"cohere",color:!0},perplexity:{symbol:"perplexity",color:!0},together:{symbol:"together",color:!0},grok:{symbol:"grok",color:!1}};function aD(e){let{id:t,size:n}=e,i=aF[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 aB=["openai-codex","deepseek","openrouter","moonshotai","moonshotai-cn","minimax","minimax-cn","vercel-ai-gateway","opencode-go","kimi-coding"],aH="pi-web:provider-usage:";function a_(e){let{providerId:t,enabled:n}=e;return aB.includes(t)?(0,r.jsx)(aU,{providerId:t,enabled:n}):null}function aU(e){let{providerId:t,enabled:n}=e,[o,s]=(0,i.useState)(null),[l,a]=(0,i.useState)(!1),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),h=(0,i.useRef)(null),{locale:f,t:m}=(0,eh.s)();(0,i.useEffect)(()=>{h.current&&clearTimeout(h.current),p(!1),s(null);try{let e=localStorage.getItem(`${aH}${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(`${aH}${t}`)}catch{}}return d(null),()=>{h.current&&clearTimeout(h.current)}},[t]);let g=(0,i.useCallback)(async()=>{a(!0),d(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(`${aH}${t}`,JSON.stringify(n))}catch{}p(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>p(!1),2e3)}else d(n.message??m("providerUsage.queryFailed"))}catch(e){d(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,tl.ob)(x.capturedAt,f)})})]}),!x&&!c&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)"},children:m("providerUsage.notQueried")}),c&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171"},children:c}),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 ":"$"}${aK(e.remaining??e.limit)}`:void 0!==e.remaining&&void 0!==e.limit?`${aK(e.remaining)} / ${aK(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 aK(e){return void 0===e?"-":Number.isInteger(e)?String(e):e.toFixed(2)}function aq(){let e=lG("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 aZ=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function aV(e){let{label:t,children:n}=e;return(0,r.jsx)(ad,{label:t,children:n})}let aJ={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 aY(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:{...aJ,fontFamily:o?"var(--font-mono)":"inherit"}})}function aG(e){let{value:t,onChange:n,placeholder:o,mono:s,onKeyDown:l,autoComplete:a="off",spellCheck:c=!1,style:d}=e,[u,p]=(0,i.useState)(!1),{t:h}=(0,eh.s)();return(0,i.useEffect)(()=>{t||p(!1)},[t]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...d},children:[(0,r.jsx)("input",{type:u?"text":"password",value:t,onChange:e=>n(e.target.value),onKeyDown:l,placeholder:o,style:{...aJ,paddingRight:34,fontFamily:s?"var(--font-mono)":"inherit"},autoComplete:a,spellCheck:c}),(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 aX(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:aJ})}function aQ(e){let{value:t,onChange:n,options:i,required:o}=e,{t:s}=(0,eh.s)();return(0,r.jsxs)("select",{value:t,onChange:e=>n(e.target.value),style:{...aJ,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 a0(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 a1(e){let{children:t}=e;return(0,r.jsx)(ac,{children:t})}function a2(e){let{name:t,editingName:n,provider:o,onChange:s,onEditingNameChange:l,onRename:a,onDelete:c,onAddModels:d,enabledModels:u}=e,{t:p}=(0,eh.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(),E=C.filter(e=>!N||e.id.toLocaleLowerCase().includes(N)||e.name?.toLocaleLowerCase().includes(N)),$=E.slice(0,300),I=$.filter(e=>!S.has(e.id)).map(e=>e.id),T=x.filter(e=>!S.has(e)).length,M=I.length>0&&I.every(e=>x.includes(e)),R=!M&&I.some(e=>x.includes(e));return(0,i.useEffect)(()=>{y.current&&(y.current.indeterminate=R)},[R]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(ao,{children:[(0,r.jsx)(as,{children:(0,r.jsx)(a1,{children:p("i18n.provider")})}),(0,r.jsxs)(al,{children:[(0,r.jsx)(aA,{providerId:t,controller:u,noteId:j}),(0,r.jsx)(aS,{variant:"danger",size:"small",onClick:c,children:p("i18n.delete")})]})]}),(0,r.jsx)(aP,{providerId:t,controller:u,id:j})]}),(0,r.jsxs)(aV,{label:p("i18n.providerName"),children:[(0,r.jsx)(aY,{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)(aV,{label:"Base URL",children:[(0,r.jsx)(aY,{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)(aV,{label:"API Key",children:[(0,r.jsx)(aG,{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)(aV,{label:"API",children:(0,r.jsx)(aQ,{value:o.api??"",onChange:e=>k("api",e||void 0),options:aZ})}),(0,r.jsxs)(aV,{label:"Headers",children:[(0,r.jsx)(a9,{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:{...aJ,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:I.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:y,type:"checkbox",checked:M,disabled:0===I.length,onChange:()=>{let e=new Set(I);v(t=>M?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...I])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),p("models.discoverySelectShown")]}),0===$.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:p("models.discoveryNoMatches")}):$.map((e,t)=>{let n=S.has(e.id),i=x.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:i||n,disabled:n,onChange:()=>{var t;return t=e.id,void v(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),n&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:p("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:h.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:E.length>$.length?p("models.discoveryShowing",{shown:$.length,total:E.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&&(d(t),v([]))},disabled:0===T,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:T?"var(--accent)":"var(--bg-panel)",color:T?"var(--accent-contrast)":"var(--text-dim)",cursor:T?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:T?p("models.discoveryAddSelectedCount",{count:T}):p("models.discoveryAddSelected")})]})]})]})]})}let a4=["off","minimal","low","medium","high","xhigh","max"],a8={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function a3(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:a4.map(e=>{let t=i[e],n=e in i?null===t?"null":"string":"omit",s="string"==typeof t?t:"",l=a8[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)"},c={background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600};return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:l,flexShrink:0,opacity:"null"===n?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===n?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===n?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>o(e,"omit"),style:{...a,..."omit"===n?c:{}},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?c:{},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 a5={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function a6(e){return e.compat?.thinkingFormat==="deepseek"}function a9(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))},c=(e,t)=>{a(o.map(n=>n.id===e?{...n,...t}:n))},d={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=>c(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...aJ,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>c(e.id,{value:t.target.value}),placeholder:"value",style:{...aJ,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:d,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 a7(e){let{providerName:t,provider:n,model:o,onChange:s,onDelete:l}=e,[a,c]=(0,i.useState)({phase:"idle"}),{t:d}=(0,eh.s)(),[u,p]=(0,i.useState)({phase:"idle"}),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(()=>l0(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 d("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?[d("i18n.connected"),...e,a.responseText||null].filter(Boolean).join(" \xb7 "):[d("i18n.failed"),...e,a.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>{c({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){c({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 c({phase:"error",message:r.error??`HTTP ${e.status}`,latencyMs:r.latencyMs,status:r.status});c({phase:"success",latencyMs:r.latencyMs,status:r.status,responseText:r.responseText})}catch(e){c({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 c=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=l1(l0(i));o>0&&s&&(n.cost={...i,...s},r+=o)}return{model:n,appliedCount:r}}(o,a.recommendation.preset);c.appliedCount>0&&(j.current=o,s(c.model)),f(!1),p({phase:"success",recommendation:a.recommendation,appliedCount:c.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]),E=(()=>{if("success"!==u.phase)return null;let{recommendation:e,appliedCount:n}=u,r=n>0?d("models.catalogFilled",{count:n}):d("models.catalogNoEmptyFields");if("unreliable"===e.price.status){let t="no-exact-match"===e.price.reason?d("models.catalogNoExactMatch"):d("models.catalogPriceUnreliable");return`${r} \xb7 ${t}`}let i="provider"===e.price.method?d("models.catalogPriceProvider",{provider:e.price.providerName??e.price.providerId??t}):"base-url"===e.price.method?d("models.catalogPriceBaseUrl",{provider:e.price.providerName??e.price.providerId??t}):d("models.catalogPriceConsensus",{support:e.price.support,total:e.price.total});return`${r} \xb7 ${i}`})(),$="error"===u.phase?u.message:E,I="error"===u.phase?"#ef4444":"success"===u.phase&&"unreliable"===u.recommendation.price.status?"#d97706":"var(--text-dim)",T=[{key:"input",label:d("models.costInput")},{key:"output",label:d("models.costOutput")},{key:"cacheRead",label:d("models.costCacheRead")},{key:"cacheWrite",label:d("models.costCacheWrite")}],M=new Set(Object.keys(o.compat??{})),R=0;a6(o)&&(R+=1,M.delete("thinkingFormat"),M.delete("requiresReasoningContentOnAssistantMessages")),Object.prototype.hasOwnProperty.call(o.compat??{},"supportsDeveloperRole")&&(R+=1,M.delete("supportsDeveloperRole")),R+=M.size;let L=[o.api?`API: ${o.api}`:null,Object.keys(o.headers??{}).length?d("models.headersSummary",{count:Object.keys(o.headers??{}).length}):null,R?d("models.compatSummary",{count:R}):null,Object.keys(o.thinkingLevelMap??{}).length?d("models.thinkingSummary",{count:Object.keys(o.thinkingLevelMap??{}).length}):null].filter(e=>!!e),A=L.length?L.join(" \xb7 "):d("models.providerDefaults");return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(ao,{children:[(0,r.jsx)(as,{children:(0,r.jsx)(a1,{children:d("i18n.model")})}),(0,r.jsxs)(al,{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)(aS,{size:"small",variant:"success"===a.phase?"primary":"secondary",onClick:"success"===a.phase?()=>c({phase:"idle"}):C,disabled:!o.id.trim()||"testing"===a.phase,title:d("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?d("i18n.checking"):"success"===a.phase?d("common.ok"):d("i18n.test")]}),(0,r.jsx)(aS,{variant:"danger",size:"small",onClick:l,children:d("i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(aV,{label:"ID *",children:(0,r.jsx)(aY,{value:o.id,onChange:e=>w("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(aV,{label:"Name",children:(0,r.jsx)(aY,{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?d("models.catalogFilling"):d("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:d("models.catalogSource")})]}),$&&(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:8,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:I,fontSize:10},children:[(0,r.jsx)("span",{title:$,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:$}),j.current&&(0,r.jsx)("button",{onClick:()=>{let e=j.current;e&&(j.current=null,s(e),p({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:d("models.catalogUndo")})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(a1,{children:d("models.capabilities")}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginTop:8},children:[(0,r.jsx)(a0,{label:d("models.reasoning"),checked:o.reasoning??!1,onChange:e=>w("reasoning",e||void 0)}),(0,r.jsx)(a0,{label:d("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)(a1,{children:d("models.modelSpecs")}),(0,r.jsx)("button",{type:"button",onClick:()=>{if(h)return void f(!1);k.current=o.cost;let e=l0(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?d("models.finishEditingCosts"):d("models.editCosts")})]}),(0,r.jsxs)("div",{style:{marginTop:10,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:10},children:[(0,r.jsx)(aV,{label:d("models.contextWindow"),children:(0,r.jsx)(aX,{value:void 0!==o.contextWindow?String(o.contextWindow):"",onChange:e=>w("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(aV,{label:d("models.maxOutputTokens"),children:(0,r.jsx)(aX,{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:d("models.costPerMillion")}),h?(0,r.jsxs)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(110px, 1fr))",gap:8},children:[T.map(e=>{let{key:t,label:n}=e;return(0,r.jsx)(aV,{label:n,children:(0,r.jsx)(aX,{value:m[t],onChange:e=>{let n,r,i;return r=l1(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)}),l2(m)&&!l1(m)&&(0,r.jsx)("div",{"aria-live":"polite",style:{gridColumn:"1 / -1",color:"#d97706",fontSize:10},children:d("models.costAllRequired")})]}):(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(105px, 1fr))",gap:"8px 16px"},children:T.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])?d("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:d("models.advancedSettings")}),(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-dim)",fontSize:10,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:A})]}),(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{color:"var(--text-dim)",transform:v?"rotate(180deg)":"none",transition:"transform 0.15s ease"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),v&&(0,r.jsxs)("div",{id:"model-advanced-settings",style:{display:"flex",flexDirection:"column",gap:14,padding:"4px 0 16px"},children:[(0,r.jsx)(aV,{label:d("models.apiOverride"),children:(0,r.jsx)(aQ,{value:o.api??"",onChange:e=>w("api",e||void 0),options:aZ})}),(0,r.jsxs)(aV,{label:d("models.headers"),children:[(0,r.jsx)(a9,{headers:o.headers,onChange:e=>w("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:d("models.headersHelp")})]}),o.reasoning&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsx)(a1,{children:d("models.compatibility")}),(0,r.jsx)(a0,{label:d("models.deepSeekThinkingCompat"),checked:a6(o),onChange:e=>s(function(e,t){if(t)return{...e,compat:{...e.compat??{},...a5}};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)(a0,{label:d("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)(a1,{children:d("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:d("models.clearAll")})]}),(0,r.jsx)(a3,{value:o.thinkingLevelMap,onChange:e=>w("thinkingLevelMap",e)})]})]})]})]})]})}function ce(e){let{provider:t,onRefresh:n,enabledModels:o}=e,[s,l]=(0,i.useState)({phase:"idle"}),{t:a}=(0,eh.s)(),[c,d]=(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"}),d(""),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"}),d("");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}d("")}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)(ao,{children:[(0,r.jsx)(as,{children:(0,r.jsx)(a1,{children:a("i18n.subscription")})}),(0,r.jsxs)(al,{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)(aS,{size:"small",onClick:()=>{u.current?.close(),l({phase:"idle"})},children:a("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(aS,{variant:"primary",size:"small",onClick:h,children:a(t.loggedIn?"i18n.relogin":"i18n.login")}),t.loggedIn&&(0,r.jsx)(aS,{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)(aO,{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:c,placeholder:"auth"===s.phase?"http://localhost:1455/auth/callback?code=…":s.placeholder??"Enter value…",submitLabel:a("i18n.submit"),inputRef:p,onValueChange:d,onSubmit:()=>void m(s.token,c)}),"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)(a_,{providerId:t.id,enabled:t.loggedIn}),t.loggedIn&&(0,r.jsx)(aW,{providerId:t.id,controller:o})]})}function ct(e){let{provider:t,onRefresh:n,enabledModels:o}=e,[s,l]=(0,i.useState)(""),[a,c]=(0,i.useState)(!1),[d,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(!1),{t:g}=(0,eh.s)();(0,i.useEffect)(()=>{l(""),h(null),m(!1)},[t.id]);let x=(0,i.useCallback)(async()=>{if(s.trim()){c(!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{c(!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)(ao,{children:[(0,r.jsx)(as,{children:(0,r.jsx)(a1,{children:"API Key"})}),(0,r.jsxs)(al,{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)(aS,{variant:"danger",size:"small",onClick:v,disabled:d,children:g(d?"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)(aG,{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)(a_,{providerId:t.id,enabled:t.configured}),t.configured&&(0,r.jsx)(aW,{providerId:t.id,controller:o})]})}function cn(e){let{oauthProviders:t,apiKeyProviders:n,onSelectOAuth:o,onSelectApiKey:s,onAddCustom:l,onClose:a}=e,[c,d]=(0,i.useState)(""),{t:u}=(0,eh.s)(),p=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>p.current?.focus(),30)},[]);let h=c.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:c,onChange:e=>d(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)(aD,{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)(aD,{id:e.id,size:28})]},e.id))]})})]})})}function cr(e){let{onClose:t,embedded:n=!1,cwd:o=null}=e,{t:s}=(0,eh.s)(),l=function(e){let[t,n]=(0,i.useState)(null),[r,o]=(0,i.useState)(!0),[s,l]=(0,i.useState)(null),[a,c]=(0,i.useState)(null),d=(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),c(null)}).catch(e=>{t.signal.aborted||c({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(d.current){u.current={key:t,body:r};return}d.current=t,l(t),c(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?aR[i.reason]:void 0;c(e?{messageKey:e}:{message:i.error??`HTTP ${t.status}`});return}n(i)}catch(e){c({message:e instanceof Error?e.message:String(e)})}finally{d.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,c]=(0,i.useState)({providers:{}}),[d,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)(aq),[k,w]=(0,i.useState)([]),[S,C]=(0,i.useState)([]),[N,E]=(0,i.useState)(!1),$=(0,i.useRef)(new Set),I=(0,i.useRef)(new Map),T=(0,i.useRef)(new Map),[M,R]=(0,i.useState)(null),L=(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:{}};c(t),$.current=new Set(Object.keys(t.providers??{})),T.current=l4(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)),L()},[L]),(0,i.useEffect)(()=>{y&&lX("models",JSON.stringify(y))},[y]);let A=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;a.providers?.[e];)e=`new-provider-${t++}`;c(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),j({type:"provider",name:e})},[a.providers]),z=(0,i.useCallback)((e,t)=>{c(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 c=l.get(n);c&&(l.delete(n),l.set(r,c));let d=Object.entries(i),u=d.findIndex(e=>{let[t]=e;return t===n});return d[u]=[r,d[u][1]],{...e,providers:Object.fromEntries(d)}}(e,{savedProviders:$.current,renames:I.current,slots:T.current},t,n);return r?(c(r),R(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},[]),W=(0,i.useCallback)((e,t)=>{P(a,e,t)?m(null):m(s("models.providerNameTaken",{name:t}))},[P,a,s]),O=(0,i.useCallback)(e=>{T.current.delete(e),R(t=>t?.provider===e?null:t),c(t=>{let n={...t.providers??{}};return delete n[e],{...t,providers:n}}),c(e=>{let t=Object.keys(e.providers??{});return j(t.length>0?{type:"provider",name:t[0]}:null),e})},[]),F=(0,i.useCallback)(e=>{l8(T.current,e,1),c(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),c(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)=>{c(n=>{let r=new Set((n.providers?.[e]?.models??[]).map(e=>e.id));l8(T.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({...e}));return{...n,providers:{...n.providers??{},[e]:{...i,models:o}}}})},[]),B=(0,i.useCallback)((e,t,n)=>{c(r=>{let i=r.providers?.[e]??{},o=[...i.models??[]];return o[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:o}}}})},[]),H=(0,i.useCallback)((e,t)=>{T.current.get(e)?.splice(t,1),c(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})},[]),_=(0,i.useCallback)(async()=>{if(g)return;h(!0),m(null),b(!1);let e=a,t=M?.name.trim();if(M&&t&&a.providers?.[M.provider]){let n=P(a,M.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=[...I.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,T.current,I.current);$.current=new Set(Object.keys(e.providers??{})),T.current=l4(e),I.current.clear(),l.resync(t,n)}}catch(e){m(String(e))}finally{h(!1)}},[P,a,l,g,M,s]),U=Object.entries(a.providers??{}),K=e=>{let t=function(e,t){if(!e||e.allEnabled)return null;let n=aM(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},q=k.filter(e=>e.loggedIn),Z=S.filter(e=>e.configured),V=(()=>{if(!y)return null;if("oauth"===y.type){let e=k.find(e=>e.id===y.providerId);return e?(0,r.jsx)(ce,{provider:e,onRefresh:L,enabledModels:l},e.id):null}if("apikey"===y.type){let e=S.find(e=>e.id===y.providerId);return e?(0,r.jsx)(ct,{provider:e,onRefresh:L,enabledModels:l},e.id):null}if("provider"===y.type){let e=a.providers?.[y.name];return e?(0,r.jsx)(a2,{name:y.name,editingName:M?.provider===y.name?M.name:y.name,provider:e,onChange:e=>z(y.name,e),onEditingNameChange:e=>R(e===y.name?null:{provider:y.name,name:e}),onRename:e=>W(y.name,e),onDelete:()=>O(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)(a7,{providerName:y.providerName,provider:e,model:t,onChange:e=>B(y.providerName,y.index,e),onDelete:()=>H(y.providerName,y.index)},`${y.providerName}-${y.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(l3,{embedded:n,title:s("common.models"),subtitle:"~/.pi/agent/models.json",closeLabel:s("i18n.close"),onClose:t,children:[(0,r.jsx)(aL,{controller:l}),(0,r.jsxs)(l5,{children:[(0,r.jsxs)(l6,{children:[(0,r.jsxs)(l9,{children:[q.map(e=>{let t=y?.type==="oauth"&&y.providerId===e.id;return(0,r.jsxs)(an,{active:t,onClick:()=>j({type:"oauth",providerId:e.id}),children:[(0,r.jsx)(aD,{id:e.id,size:16}),(0,r.jsx)(ar,{className:"is-grow",children:e.name}),K(e.id)]},e.id)}),Z.map(e=>{let t=y?.type==="apikey"&&y.providerId===e.id;return(0,r.jsxs)(an,{active:t,onClick:()=>j({type:"apikey",providerId:e.id}),children:[(0,r.jsx)(aD,{id:e.id,size:16}),(0,r.jsx)(ar,{className:"is-grow",children:e.displayName}),K(e.id)]},e.id)}),(q.length>0||Z.length>0)&&U.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),d?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:s("i18n.loading")}):U.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)(an,{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)(ar,{className:"is-grow",children:t}),K(t)]}),o.map((e,n)=>{let i=y?.type==="model"&&y.providerName===t&&y.index===n;return(0,r.jsxs)(an,{active:i,className:"models-sidebar-indented-item",onClick:()=>j({type:"model",providerName:t,index:n}),children:[(0,r.jsx)(ar,{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)(an,{className:"models-sidebar-indented-item models-sidebar-add-item",onClick:e=>{e.stopPropagation(),F(t)},children:(0,r.jsxs)(ar,{children:["+ ",s("i18n.model")]})})]},t)})]}),(0,r.jsx)(aN,{onClick:()=>E(!0),children:s("i18n.addProvider")})]}),(0,r.jsx)(aj,{children:(0,r.jsx)(ai,{className:"is-fill",children:d?null:V??(0,r.jsx)(ay,{children:s("i18n.selectProviderModel")})})})]}),(0,r.jsxs)(ak,{status:(g||f)&&(0,r.jsx)("span",{style:{color:"#f87171"},children:g?s("models.configUnreadable",{error:g}):f}),children:[!n&&(0,r.jsx)(aS,{onClick:t,children:s("i18n.cancel")}),(0,r.jsxs)(aS,{variant:"primary",onClick:_,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)(cn,{oauthProviders:k,apiKeyProviders:S,onSelectOAuth:e=>j({type:"oauth",providerId:e}),onSelectApiKey:e=>j({type:"apikey",providerId:e}),onAddCustom:A,onClose:()=>E(!1)})]})}let ci=null;async function co(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(ci)return ci;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 ci=null,!1}})();return ci=t,t.then(e=>{e||ci!==t||(ci=null)}),t}function cs(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function cl(e,t){let n=t.replace(/[/\\]+$/,"");return n&&(e===n||e.startsWith(`${n}/`)||e.startsWith(`${n}\\`))?`./${e.slice(n.length).replace(/^[/\\]/,"")}`:cs(e)}function ca(e,t,n,r){return e.filter(e=>n(e)!==t&&(t||!r?.(e)))}function cc(e){return e?JSON.stringify([e.requiresTrust,e.trusted,e.decision,e.decisionPath??null,e.inherited]):""}function cd(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function cu(e,t){return t("project"===e?"skills.scope.project":"global"===e?"skills.scope.global":"skills.scope.path")}function cp(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function ch(e,t){return e?e.slice(0,8):t}function cf(e){let{skill:t,cwd:n,onToggle:i,toggling:o,saveError:s,updateStatus:l,checkingUpdate:a,updating:c,updateError:d,onCheckUpdate:u,onUpdate:p}=e,{t:h}=(0,eh.s)(),f=cd(t),m=!t.disableModelInvocation;return(0,r.jsxs)(ai,{children:[(0,r.jsxs)("div",{className:"skill-detail-heading",children:[(0,r.jsxs)(ao,{children:[(0,r.jsxs)(as,{children:[(0,r.jsx)(ah,{scope:f,children:cu(f,h)}),(0,r.jsx)("span",{className:"config-detail-path",children:"project"===f?cl(t.filePath,n):cs(t.filePath)})]}),(0,r.jsx)(al,{children:(0,r.jsx)(aC,{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)(ad,{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)(ad,{label:h("i18n.version"),children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:ch(l?.currentVersion??t.install.versionHash,h("i18n.unknown"))}),t.install.canCheckForUpdates&&(0,r.jsx)(aS,{size:"small",onClick:u,disabled:a||c,children:h("i18n.check")}),l?.state==="update-available"&&(0,r.jsx)("span",{className:"skill-version-value is-update",children:ch(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)(aS,{variant:"primary",size:"small",onClick:p,disabled:c||a,children:h(c?"i18n.updating":"i18n.update")})]}),d&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:d})]}),(0,r.jsx)(ad,{label:h("config.name"),children:(0,r.jsx)("span",{className:"skill-name-value",children:t.name})}),(0,r.jsx)(ad,{label:h("i18n.description"),children:(0,r.jsx)("span",{className:"skill-description",children:t.description})})]})}function cm(e){let{cwd:t,installedPackages:n,projectResourcesLoaded:o,onInstalled:s}=e,{t:l}=(0,eh.s)(),[a,c]=(0,i.useState)(""),[d,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]),E="global"===k?"~/.pi/agent/skills/":`${cs(t)}/.pi/skills/`;return(0,r.jsxs)(ai,{className:"is-full-height",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)(ag,{title:l("i18n.addSkill"),catalogs:[{href:"https://skills.sh",label:"skills.sh"}],target:(0,r.jsx)(am,{value:k,label:l("config.saveTo"),options:[{value:"global",label:cu("global",l)},{value:"project",label:cu("project",l),disabled:!o}],path:E,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=>c(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)(aS,{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})]}),d.length>0&&(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:d.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)(aS,{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 cg(e){let{cwd:t,onClose:n,embedded:o=!1,trust:s}=e,{t:l}=(0,eh.s)(),[a,c]=(0,i.useState)([]),[d,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(()=>lG("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,E]=(0,i.useState)({}),[$,I]=(0,i.useState)(new Set),[T,M]=(0,i.useState)(!1),[R,L]=(0,i.useState)(null),[A,z]=(0,i.useState)(null),[P,W]=(0,i.useState)(!0),O=(0,i.useCallback)(async()=>{u(!0),h(null);try{let e=await fetch(`/api/skills?cwd=${encodeURIComponent(t)}`),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);let r=n.skills??[];return c(r),W(n.projectResourcesLoaded??!0),m(e=>{if(e&&r.some(t=>t.filePath===e))return e;let t=r.find(e=>!e.disableModelInvocation)??r[0];return t?.filePath??null}),r}catch(e){return h(String(e)),[]}finally{u(!1)}},[t]);(0,i.useEffect)(()=>{E({}),z(null),O()},[t]);let F=cc(s),D=(0,i.useRef)(F);(0,i.useEffect)(()=>{D.current!==F&&(D.current=F,O())},[F,O]),(0,i.useEffect)(()=>{f&&lX("skills",f,t)},[t,f]);let B=(0,i.useCallback)(async e=>{let n=(e?[e]:a.filter(e=>!!e.install)).map(cp).filter(e=>!!e);if(0!==n.length){z(null),I(e=>new Set([...e,...n])),e||M(!0);try{let n=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,package:e?.install?.package,scope:e?.install?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);E(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){z(e instanceof Error?e.message:String(e))}finally{I(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),e||M(!1)}}},[t,a]),H=(0,i.useCallback)(async e=>{if(!e.install)return;let n=cp(e);L(n),z(null);try{let r=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,package:e.install.package,scope:e.install.scope})}),i=await r.json();if(!r.ok||i.error||!i.success)throw Error(i.error??`HTTP ${r.status}`);await O();let o=i.skill?.install?.versionHash;E(t=>({...t,[n]:{package:e.install.package,scope:e.install.scope,state:"up-to-date",currentVersion:o,latestVersion:o}}))}catch(e){z(e instanceof Error?e.message:String(e))}finally{L(null)}},[t,O]),_=(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}`);c(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n))}catch(e){b(String(e))}finally{x(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),U=(0,i.useCallback)(async(e,t,n)=>{let r=ca(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;c(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]),K=a.find(e=>e.filePath===f)??null,q=d||g.size>0||null!==R;return(0,r.jsxs)(l3,{embedded:o,title:l("common.skills"),subtitle:cs(t),closeLabel:l("i18n.close"),onClose:n,children:[!P&&(0,r.jsx)(ab,{message:l("trust.skillsNotLoaded")}),(0,r.jsxs)(l5,{children:[(0,r.jsxs)(l6,{children:[(0,r.jsx)(l9,{children:d?(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"===cd(e)&&!!e.install?.skillsShUrl},{label:t.project,matches:e=>"project"===cd(e)&&!e.install?.skillsShUrl},{label:`${t.global} / skills.sh`,matches:e=>"global"===cd(e)&&!!e.install?.skillsShUrl},{label:t.global,matches:e=>"global"===cd(e)&&!e.install?.skillsShUrl},{label:t.path,matches:e=>"path"===cd(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)(an,{active:i,onClick:()=>{m(e.filePath),C(!1)},children:[(0,r.jsx)(aE,{active:!o}),(0,r.jsx)(ar,{className:`is-grow${o?" is-muted":""}`,children:e.name}),(n=(t=cp(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)(l7,{aside:(0,r.jsx)(ae,{enabled:o,total:i.length,disabled:q,loading:y===t,label:l(s?"skills.groupSwitchOn":"skills.groupSwitchOff",{group:t}),onChange:e=>void U(t,i,e)}),children:t}),k?.group===t&&(0,r.jsx)(at,{error:k.error}),[...i.filter(e=>!e.disableModelInvocation),...i.filter(e=>e.disableModelInvocation)].map(n)]},t)})})()}),(0,r.jsx)(aN,{onClick:()=>C(!0),active:S,children:l("i18n.addSkill")})]}),(0,r.jsx)(aj,{children:(0,r.jsx)(ai,{className:"is-fill",children:S?(0,r.jsx)(cm,{cwd:t,projectResourcesLoaded:P,installedPackages:{global:new Set(a.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(a.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{O()}}):d?null:K?(0,r.jsx)(cf,{skill:K,cwd:t,onToggle:_,toggling:g.has(K.filePath),saveError:v,updateStatus:cp(K)?N[cp(K)]:void 0,checkingUpdate:!!cp(K)&&$.has(cp(K)),updating:R===cp(K),updateError:A,onCheckUpdate:()=>void B(K),onUpdate:()=>void H(K)},K.filePath):(0,r.jsx)(ay,{children:l("i18n.selectSkill")})})})]}),(0,r.jsxs)(ak,{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)(aS,{onClick:n,children:l("i18n.close")}),a.some(e=>!!e.install)&&(0,r.jsx)(aS,{variant:"secondary",onClick:()=>void B(),disabled:T||null!==R,children:T?l("i18n.checking"):l("i18n.checkUpdates")})]})]})}let cx={builtin:0,global:1,workspace:2,project:3},cv=["read","bash","edit","write","grep","find","ls"],cb=["","off","minimal","low","medium","high","xhigh","max"],cy={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},cj={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"},ck={background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"default"};function cw(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 cS(e){return`${e.scope}:${e.name}`}function cC(e){return"global"===e||"project"===e}function cN(e){return cC(e)||"builtin"===e}function cE(e){let{label:t,children:n}=e;return(0,r.jsx)(ad,{label:t,children:n})}function c$(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 cI(e){let{cwd:t,sessionId:n=null,onClose:o,onReloaded:s,embedded:l=!1,trust:a}=e,c=ew(),{t:d}=(0,eh.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)(()=>lG("agents",t)),[j,k]=(0,i.useState)(cy),[w,S]=(0,i.useState)("view"),[C,N]=(0,i.useState)("global"),[E,$]=(0,i.useState)(!0),[I,T]=(0,i.useState)(!1),[M,R]=(0,i.useState)(!1),[L,A]=(0,i.useState)(!1),[z,P]=(0,i.useState)(null),[W,O]=(0,i.useState)(!1),[F,D]=(0,i.useState)(10),[B,H]=(0,i.useState)(!0),[_,U]=(0,i.useState)(!1),[K,q]=(0,i.useState)(null),[Z,V]=(0,i.useState)(!1),[J,Y]=(0,i.useState)(!1),G=(0,i.useMemo)(()=>u.find(e=>cS(e)===b)??null,[u,b]),X=(0,i.useMemo)(()=>h.map(e=>({provider:e.provider,modelId:e.id,name:e.name})),[h]),Q=(0,i.useCallback)(async e=>{$(!0),P(null);try{let n=await fetch(`/api/subagents/profiles?cwd=${encodeURIComponent(t)}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);let i=r.profiles??[];p(i);let o=e??lG("agents",t),s=i.find(e=>cS(e)===o)??i.find(e=>"project"===e.scope)??i.find(e=>"global"===e.scope)??i[0]??null;y(s?cS(s):null),s&&(k(cw(s)),S(cC(s.scope)?"edit":"view"),cC(s.scope)&&N(s.scope))}catch(e){P(e instanceof Error?e.message:String(e))}finally{$(!1)}},[t]);(0,i.useEffect)(()=>{Q()},[Q]),(0,i.useEffect)(()=>{let e=new AbortController;return H(!0),q(null),(async()=>{try{let t=await fetch("/api/subagents/settings",{cache:"no-store",signal:e.signal}),n=await t.json();if(!t.ok||n.error||"boolean"!=typeof n.enabled)throw Error(n.error??`HTTP ${t.status}`);O(n.enabled),"number"==typeof n.maxConcurrent&&D(n.maxConcurrent)}catch(t){if(e.signal.aborted)return;q(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||H(!1)}})(),()=>e.abort()},[]),(0,i.useEffect)(()=>{b&&lX("agents",b,t)},[t,b]);let ee=cc(a);(0,i.useEffect)(()=>{let e=new AbortController;return g(!0),v(null),(async()=>{try{let n=await fetch(`/api/models?cwd=${encodeURIComponent(t)}`,{signal:e.signal}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);f(r.modelList??[]),v(r.modelError??null)}catch(t){if(e.signal.aborted)return;v(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||g(!1)}})(),()=>e.abort()},[t,ee]);let et=async()=>{T(!0),P(null),R(!1);try{let e=await fetch("/api/subagents/profiles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:C,profile:j})}),n=await e.json();if(!e.ok||n.error||!n.profile)throw Error(n.error??`HTTP ${e.status}`);await Q(cS(n.profile)),R(!0),setTimeout(()=>R(!1),2e3)}catch(e){P(e instanceof Error?e.message:String(e))}finally{T(!1)}},en=async()=>{if(G&&cC(G.scope)&&window.confirm(d("agents.deleteConfirm",{name:G.displayName}))){T(!0),P(null);try{let e=await fetch("/api/subagents/profiles",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:G.scope,name:G.name})}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);await Q()}catch(e){P(e instanceof Error?e.message:String(e))}finally{T(!1)}}},er="view"!==w,ei="create"===w,eo=!er||I||L,es=ei?C:G?.scope,el=ei?"global"===C?`~/.pi/agent/agents/${j.name||"..."}.md`:`./.pi/agents/${j.name||"..."}.md`:G?(G.filePath?"project"===G.scope||"workspace"===G.scope?cl(G.filePath,t):cs(G.filePath):null)??d("agents.builtinPath"):"",ea=ei?el:G?.filePath??el,ec=!j.model||h.some(e=>`${e.provider}/${e.id}`===j.model),ed=(()=>{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)}})(),eu=eo?{...cj,...ck}:cj,ep=ei?eo:!G||!cN(G.scope)||I||L,ef=(e,t)=>{k(n=>({...n,[e]:t}))},em=async e=>{if(ei)return void ef("enabled",e);if(G&&cN(G.scope)){A(!0),P(null);try{let n=await fetch("/api/subagents/profiles",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:G.scope,name:G.name,enabled:e})}),r=await n.json();if(!n.ok||r.error||!r.profile)throw Error(r.error??`HTTP ${n.status}`);let i=r.profile;p(e=>e.map(e=>cS(e)===cS(i)?i:e)),k(e=>({...e,enabled:i.enabled}))}catch(e){P(e instanceof Error?e.message:String(e))}finally{A(!1)}}},eg=async e=>{U(!0),q(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),r=await t.json();if(!t.ok||r.error||"boolean"!=typeof r.enabled)throw Error(r.error??`HTTP ${t.status}`);O(r.enabled),V(!!n)}catch(e){q(e instanceof Error?e.message:String(e))}finally{U(!1)}},ex=async e=>{D(e),q(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxConcurrent:e})}),n=await t.json();if(!t.ok||n.error||"number"!=typeof n.maxConcurrent)throw Error(n.error??`HTTP ${t.status}`);D(n.maxConcurrent)}catch(e){q(e instanceof Error?e.message:String(e))}},ev=async()=>{if(n){Y(!0),q(null);try{await sT(n,{type:"reload"}),V(!1),s?.()}catch(e){q(e instanceof Error?e.message:String(e))}finally{Y(!1)}}};return(0,r.jsxs)(l3,{embedded:l,title:d("common.agents"),subtitle:cs(t),closeLabel:d("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:d("agents.builtInTitle")}),(0,r.jsx)("span",{children:d("agents.builtInDescription")}),Z&&(0,r.jsx)("span",{role:"status",className:"agents-feature-reload-notice",children:d("agents.reloadRequired")})]}),(0,r.jsxs)("div",{className:"agents-feature-actions",children:[Z&&n&&(0,r.jsx)(aS,{size:"small",onClick:()=>void ev(),disabled:J||_,children:J?d("agents.reloading"):d("agents.reloadSession")}),(0,r.jsxs)("label",{className:"agents-concurrency-control",title:d("agents.maxConcurrentDescription"),children:[(0,r.jsx)("span",{children:d("agents.maxConcurrent")}),(0,r.jsx)("input",{"aria-label":d("agents.maxConcurrent"),type:"number",min:1,max:32,value:F,disabled:B||_,onChange:e=>D(Number(e.target.value)),onBlur:()=>void ex(F)})]}),(0,r.jsx)(aC,{checked:W,disabled:B||J,loading:_,label:d("agents.builtInTitle"),onChange:e=>void eg(e)})]})]}),(0,r.jsxs)(l5,{children:[(0,r.jsxs)(l6,{children:[(0,r.jsx)(l9,{children:E?(0,r.jsx)("div",{style:{padding:10,color:"var(--text-dim)",fontSize:12},children:d("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)(l7,{children:d(`agents.scope.${e}`)}),t.map(e=>{let t,n,i=(t=e.name.toLowerCase(),n=cx[e.scope],u.some(e=>e.name.toLowerCase()===t&&cx[e.scope]>n));return(0,r.jsxs)(an,{active:b===cS(e)&&!ei,onClick:()=>{y(cS(e)),k(cw(e)),S(cC(e.scope)?"edit":"view"),cC(e.scope)&&N(e.scope),P(null)},children:[(0,r.jsx)(aE,{active:e.enabled}),(0,r.jsx)(ar,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.displayName}),i&&(0,r.jsx)("span",{className:"agents-overridden-label",children:d("agents.overridden")})]},cS(e))})]},e)})}),(0,r.jsx)(aN,{active:ei,onClick:()=>{let e="custom-agent",t=2;for(;u.some(t=>t.name===e);)e=`custom-agent-${t++}`;y(null),k({...cy,name:e,displayName:e}),S("create"),N("global"),P(null)},children:d("agents.new")})]}),(0,r.jsx)(aj,{children:(0,r.jsx)(ai,{className:"is-fill",children:G||ei?(0,r.jsxs)(ai,{children:[(0,r.jsxs)(ao,{children:[(0,r.jsx)(as,{children:ei?(0,r.jsx)(am,{value:C,label:d("config.saveTo"),options:["global","project"].map(e=>({value:e,label:d(`agents.scope.${e}`),disabled:I})),path:el,onChange:N}):(0,r.jsxs)(r.Fragment,{children:[es&&(0,r.jsx)(ah,{scope:es,children:d(`agents.scope.${es}`)}),(0,r.jsx)("span",{title:ea,className:"config-detail-path",children:el})]})}),(0,r.jsxs)(al,{children:[G&&("view"===w||"edit"===w)&&(0,r.jsx)(aS,{size:"small",onClick:()=>{if(!G)return;let e=function(e,t){let n=new Set(t.map(e=>e.name.toLowerCase())),r=`${e}-copy`,i=r,o=2;for(;n.has(i.toLowerCase());)i=`${r}-${o++}`;return i}(G.name,u);y(null),k({...cw(G),name:e,displayName:d("agents.copyName",{name:G.displayName})}),S("create"),N(cC(G.scope)?G.scope:"global"),P(null)},disabled:I||L,children:d("agents.duplicate")}),G&&cC(G.scope)&&"edit"===w&&(0,r.jsx)(aS,{variant:"danger",size:"small",onClick:()=>void en(),disabled:I||L,children:d("agents.delete")}),(0,r.jsx)(aC,{checked:j.enabled,disabled:ep,label:j.enabled?d("agents.disable"):d("agents.enable"),onChange:e=>void em(e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:c?"1fr":"minmax(0, 1fr) minmax(0, 1fr)",gap:12},children:[(0,r.jsx)(cE,{label:d("agents.name"),children:ei?(0,r.jsx)("input",{"aria-label":d("agents.name"),value:j.name,disabled:eo,onChange:e=>ef("name",e.target.value),style:cj}):(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)(cE,{label:d("agents.displayName"),children:(0,r.jsx)("input",{"aria-label":d("agents.displayName"),value:j.displayName,disabled:eo,onChange:e=>ef("displayName",e.target.value),style:eu})})]}),(0,r.jsx)(cE,{label:d("agents.description"),children:(0,r.jsx)("input",{"aria-label":d("agents.description"),value:j.description,disabled:eo,onChange:e=>ef("description",e.target.value),style:eu})}),(0,r.jsx)(cE,{label:d("agents.prompt"),children:(0,r.jsx)("textarea",{className:"agents-system-prompt","aria-label":d("agents.prompt"),value:j.systemPrompt,disabled:eo,onChange:e=>ef("systemPrompt",e.target.value),style:{...eu,height:195,minHeight:195,maxHeight:"60vh",padding:9,overflow:"auto",resize:eo?"none":"vertical",lineHeight:1.5}})}),(0,r.jsx)(cE,{label:d("agents.tools"),children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 16px"},children:cv.map(e=>(0,r.jsx)(c$,{label:e,disabled:eo,checked:j.tools.includes(e),onChange:t=>ef("tools",t?[...j.tools,e]:j.tools.filter(t=>t!==e))},e))})}),(0,r.jsxs)(cE,{label:d("agents.resources"),children:[(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 20px"},children:[(0,r.jsx)(c$,{label:d("agents.loadSkills"),disabled:eo,checked:j.loadSkills,onChange:e=>ef("loadSkills",e)}),(0,r.jsx)(c$,{label:d("agents.loadExtensions"),disabled:eo,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?d("agents.skillsOnly",{skills:j.skills.join(", ")}):d("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?d("agents.extensionsOnly",{extensions:j.extensions.join(", ")}):d("agents.extensionsNone")})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:c?"1fr":"minmax(0, 1.5fr) minmax(120px, 0.75fr) minmax(100px, 0.5fr)",gap:12},children:[(0,r.jsx)(cE,{label:d("agents.model"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(oU,{options:X,value:ed,onChange:(e,t)=>ef("model",`${e}/${t}`),onClear:()=>ef("model",void 0),emptyLabel:m?d("agents.modelsLoading"):d("agents.inherit"),selectedLabel:j.model&&!ec?d("agents.modelUnavailable",{model:j.model}):void 0,disabled:eo||m||0===h.length&&!j.model,ariaLabel:d("agents.model"),variant:"field",placement:"auto"}),x&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:10},children:x})]})}),(0,r.jsx)(cE,{label:d("agents.thinking"),children:(0,r.jsx)("select",{"aria-label":d("agents.thinking"),value:j.thinking??"",disabled:eo,onChange:e=>ef("thinking",e.target.value||void 0),style:eu,children:cb.map(e=>(0,r.jsx)("option",{value:e,children:e||d("agents.inherit")},e||"default"))})}),(0,r.jsx)(cE,{label:d("agents.maxTurns"),children:(0,r.jsx)("input",{"aria-label":d("agents.maxTurns"),type:"number",min:1,value:j.maxTurns??"",disabled:eo,onChange:e=>ef("maxTurns",e.target.value?Number(e.target.value):void 0),style:eu})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"10px 20px"},children:[(0,r.jsx)(c$,{label:d("agents.inheritContext"),disabled:eo,checked:j.inheritContext,onChange:e=>ef("inheritContext",e)}),(0,r.jsx)(c$,{label:d("agents.background"),disabled:eo,checked:j.runInBackground,onChange:e=>ef("runInBackground",e)})]})]}):(0,r.jsx)(ay,{children:d("agents.empty")})})})]}),(0,r.jsx)(ak,{status:(K||z)&&(0,r.jsx)("span",{role:"alert",style:{color:"#ef4444"},children:K||z}),children:er&&(0,r.jsxs)(aS,{variant:"primary",onClick:()=>void et(),disabled:I||M||L||!j.name.trim(),className:M?"is-success":void 0,children:[M&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:M?d("i18n.saved"):I?d("agents.saving"):d("agents.save")})]})})]})}let cT=["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"];function cM(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function cR(e){return`${e.scope}\0${e.source}`}function cL(e){return`extension\0${e.path}`}function cA(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function cz(e,t){return t(`plugins.status.${e}`)}function cP(e){return`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`}function cW(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function cO(e){let{pkg:t}=e,{t:n}=(0,eh.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 cF(e){let{cwd:t,source:n,scope:i,projectResourcesLoaded:o,busy:s,actionError:l,onSourceChange:a,onScopeChange:c,onInstall:d}=e,{t:u}=(0,eh.s)();return(0,r.jsx)(ax,{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)(am,{value:i,label:u("config.saveTo"),options:[{value:"global",label:cA("global",u)},{value:"project",label:cA("project",u),disabled:!o}],path:"project"===i?`${cs(t)}/.pi/{npm,git}`:"~/.pi/agent/{npm,git}",disabledReason:u("trust.projectScopeUnavailable"),onChange:c}),inputLabel:u("config.source"),inputId:"plugin-source",placeholder:"npm:@scope/package",value:n,canSubmit:!s&&!!n.trim(),normalizeValue:cM,onValueChange:a,onSubmit:d,examplesLabel:u("config.examples"),examples:cT,error:l,children:(0,r.jsx)(aS,{variant:"primary",onClick:d,disabled:s||!n.trim(),className:"is-pushed-right",children:u(s?"i18n.installing":"i18n.install")})})}function cD(e){let t,{pkg:n,cwd:o,busyKey:s,actionError:l,actionMessage:a,sessionId:c,updateStatus:d,checkingUpdate:u,updateError:p,onAction:h,onCheckUpdate:f,onReloadSession:m}=e,{t:g}=(0,eh.s)(),x=cR(n),v=(s?.endsWith(x)||s?.startsWith("bulk:"))??!1,b="reload"===s,y=!n.disabled,j=n.canCheckForUpdates,k=d?.state==="update-available",w=n.description?.trim(),S=(0,i.useId)();return(0,r.jsxs)(ai,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(ao,{className:"is-top-aligned",children:[(0,r.jsxs)(as,{children:[(0,r.jsx)(ah,{scope:n.scope,children:cA(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)(al,{children:[(0,r.jsx)(aS,{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)(aS,{size:"small",onClick:m,disabled:!c||b||v,"aria-describedby":c?void 0:S,children:g(b?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)(aS,{variant:"danger",size:"small",onClick:()=>h("remove",n),disabled:v||b,children:g(s===`remove:${x}`?"i18n.removing":"i18n.remove")}),(0,r.jsx)(aC,{checked:y,loading:v||b,onChange:()=>h(n.disabled?"enable":"disable",n),label:g(n.disabled?"i18n.enablePackage":"i18n.disablePackage")})]})]}),!c&&(0,r.jsx)("div",{id:S,className:"config-detail-heading-note",children:g("i18n.openSessionToReload")})]}),(0,r.jsxs)(au,{children:[w&&(0,r.jsx)(ap,{label:g("i18n.description"),children:w}),(0,r.jsx)(ap,{label:g("i18n.status"),tone:"plain",style:{color:cW(n.status),textTransform:"capitalize"},children:cz(n.status,g)}),(0,r.jsxs)(ap,{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:d.displayName,children:g("i18n.updateAvailable")}),j&&(u||d&&!k)&&(0,r.jsx)("span",{className:`skill-update-status ${u?"is-checking":d?.state==="up-to-date"?"is-success":d?.state==="error"?"is-error":"is-muted"}`,children:u?g("i18n.checking"):d?.state==="up-to-date"?g("i18n.upToDate"):d?.state==="unsupported"?g("i18n.automaticChecksUnavailable"):d?.message||g("i18n.checkFailed")})]}),p&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:p})]}),(0,r.jsx)(ap,{label:g("i18n.package"),mono:!0,children:n.packageName??g("i18n.unknown")}),(0,r.jsx)(ap,{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)(ap,{label:g("i18n.installedPath"),tone:n.installedPath?"muted":"error",mono:!0,children:n.installedPath?cs(n.installedPath):g("i18n.notFound")}),(0,r.jsx)(ap,{label:g("i18n.cwd"),tone:"dim",mono:!0,children:cs(o)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)(ac,{children:g("i18n.resolvedResources")}),(0,r.jsx)(cO,{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 cB(e){let{extension:t}=e,{t:n}=(0,eh.s)(),i=t.enabled?"loaded":"disabled";return(0,r.jsxs)(ai,{children:[(0,r.jsx)(ao,{children:(0,r.jsxs)(as,{children:[(0,r.jsx)(ah,{scope:t.scope,children:cA(t.scope,n)}),(0,r.jsx)(aa,{children:t.name})]})}),(0,r.jsxs)(au,{children:[(0,r.jsx)(ap,{label:n("i18n.status"),tone:"plain",style:{color:t.enabled?"var(--accent)":"var(--text-dim)"},children:cz(i,n)}),(0,r.jsx)(ap,{label:n("i18n.installedPath"),mono:!0,children:cs(t.path)})]})]})}function cH(e){var t;let{cwd:n,sessionId:o,onClose:s,onReloaded:l,embedded:a=!1,trust:c}=e,{t:d}=(0,eh.s)(),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!0),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(()=>lG("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),[E,$]=(0,i.useState)(null),[I,T]=(0,i.useState)(null),[M,R]=(0,i.useState)(null),[L,A]=(0,i.useState)({}),[z,P]=(0,i.useState)(new Set),[W,O]=(0,i.useState)(!1),[F,D]=(0,i.useState)(null),[B,H]=(0,i.useState)(!1),_=(0,i.useMemo)(()=>u?.packages??[],[u?.packages]),U=(0,i.useMemo)(()=>u?.standaloneExtensions??[],[u?.standaloneExtensions]),K=_.find(e=>cR(e)===x)??null,q=U.find(e=>cL(e)===x)??null,Z=u?.projectResourcesLoaded??!0,V=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:_.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[_]),J=(0,i.useCallback)(async()=>{f(!0),g(null),R(null);try{let e=await fetch(`/api/plugins?cwd=${encodeURIComponent(n)}`),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);p(t),y(e=>0===t.packages.length&&0===t.standaloneExtensions.length||e),v(e=>e&&(t.packages.some(t=>cR(t)===e)||t.standaloneExtensions.some(t=>cL(t)===e))?e:t.packages[0]?cR(t.packages[0]):t.standaloneExtensions[0]?cL(t.standaloneExtensions[0]):null)}catch(e){g(e instanceof Error?e.message:String(e))}finally{f(!1)}},[n]);(0,i.useEffect)(()=>{A({}),D(null),J()},[n]);let Y=cc(c),G=(0,i.useRef)(Y);(0,i.useEffect)(()=>{G.current!==Y&&(G.current=Y,J())},[Y,J]),(0,i.useEffect)(()=>{x&&lX("plugins",x,n)},[n,x]);let X=(0,i.useCallback)(async e=>{let t=(e?[e]:_.filter(e=>e.canCheckForUpdates)).map(cR);if(0!==t.length){D(null),P(e=>new Set([...e,...t])),e||O(!0);try{let t=await fetch("/api/plugins/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n,source:e?.source,scope:e?.scope})}),r=await t.json();if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);A(e=>{let t={...e};for(let e of r.updates??[])t[cR(e)]=e;return t})}catch(e){D(e instanceof Error?e.message:String(e))}finally{P(e=>{let n=new Set(e);for(let e of t)n.delete(e);return n}),e||O(!1)}}},[n,_]),Q=(0,i.useCallback)(async()=>{H(!0),$(null),T(null),D(null);try{let e=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"update",cwd:n})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);p(t),A({}),T(d("i18n.packagesUpdated")),o&&T(`${d("i18n.packagesUpdated")} ${d("agents.reloadRequired")}`)}catch(e){$(e instanceof Error?e.message:String(e))}finally{H(!1)}},[n,o,d]),ee=(0,i.useCallback)(async(e,t)=>{let r=cR(t);N(`${e}:${r}`),$(null),T(null),R(null);try{let i=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,source:t.source,scope:t.scope,cwd:n})}),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]?cR(o.packages[0]):o.standaloneExtensions[0]?cL(o.standaloneExtensions[0]):null),0===o.packages.length&&0===o.standaloneExtensions.length&&y(!0),T(d("i18n.packageRemoved")),A(e=>{let t={...e};return delete t[r],t});else{let t={install:d("i18n.packageInstalled"),update:d("i18n.packageUpdated"),disable:d("i18n.packageDisabled"),enable:d("i18n.packageEnabled")};T(t[e]),"update"===e&&A(e=>{let t={...e};return delete t[r],t})}}catch(e){$(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,d]),et=(0,i.useCallback)(async(e,t,r)=>{let i=ca(t,r,e=>!e.disabled,e=>e.filtered),s=r?0:t.filter(e=>!e.disabled&&e.filtered).length,l=s>0?d("plugins.bulkKeptFiltered",{count:s}):void 0;if($(null),T(null),R(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:c,...u}=s;p(u);let h=c.filter(e=>e.error);if(h.length<c.length){let e=r?d("plugins.bulkEnabled"):d("plugins.bulkDisabled");T(o?`${e} ${d("agents.reloadRequired")}`:e)}h.length>0&&R({scope:e,note:l,error:[d("plugins.bulkFailed",{count:h.length,total:c.length}),...h.map(e=>`${e.source}: ${e.error}`)].join("\n")})}catch(t){R({scope:e,note:l,error:t instanceof Error?t.message:String(t)})}finally{N(null)}},[n,o,d]),en=(0,i.useCallback)(async()=>{let e=cM(j).trim();if(!e)return;k(e);let t=`${w}\0${e}`;N(`install:${t}`),$(null),T(null),R(null);try{var r;let i,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?cR(a):t),y(!1),k(""),T(d("i18n.packageInstalled"))}catch(e){$(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,w,j,d]),er=(0,i.useCallback)(async()=>{if(o){N("reload"),$(null),T(null),R(null);try{await sT(o,{type:"reload"}),l?.(),await J(),T(d("i18n.sessionReloaded"))}catch(e){$(e instanceof Error?e.message:String(e))}finally{N(null)}}},[J,l,o,d]),ei=C?.startsWith("install:")??!1,eo=Object.values(L).filter(e=>"update-available"===e.state).length,es=_.some(e=>e.canCheckForUpdates),el=h||null!==C||z.size>0||B;return(0,r.jsxs)(l3,{embedded:a,title:d("common.plugins"),subtitle:cs(n),closeLabel:d("i18n.close"),onClose:s,children:[!Z&&(0,r.jsx)(ab,{message:d("trust.pluginsNotLoaded")}),(0,r.jsxs)(l5,{children:[(0,r.jsxs)(l6,{children:[(0,r.jsx)(l9,{children:h?(0,r.jsx)("div",{className:"config-sidebar-message",children:d("i18n.loading")}):m?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:m}):0===_.length&&0===U.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:d("i18n.noPlugins")}):(0,r.jsxs)(r.Fragment,{children:[U.length>0&&(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(l7,{children:d("i18n.extensions")}),U.map(e=>{let t=cL(e);return(0,r.jsxs)(an,{active:!b&&x===t,title:e.path,onClick:()=>{v(t),y(!1),$(null),T(null)},children:[(0,r.jsx)(aE,{active:e.enabled}),(0,r.jsx)(ar,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.name})]},t)})]}),V.map(e=>{let t=e.packages.filter(e=>!e.disabled).length,n=t===e.packages.length;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(l7,{aside:(0,r.jsx)(ae,{enabled:t,total:e.packages.length,disabled:el,loading:C===`bulk:${e.scope}`,label:d(n?"plugins.groupSwitchOn":"plugins.groupSwitchOff",{group:cA(e.scope,d)}),onChange:t=>void et(e.scope,e.packages,t)}),children:cA(e.scope,d)}),M?.scope===e.scope&&(0,r.jsx)(at,{error:M.error,note:M.note}),e.packages.map(e=>{let t=cR(e),n=!b&&x===t;return(0,r.jsxs)(an,{active:n,title:e.description??e.source,onClick:()=>{v(t),y(!1),$(null),T(null)},children:[(0,r.jsx)(aE,{active:!e.disabled,color:cW(e.status)}),(0,r.jsx)(ar,{className:`is-grow${e.disabled?" is-muted":""}`,children:e.source}),L[cR(e)]?.state==="update-available"&&(0,r.jsx)("span",{title:d("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"})]},t)})]},e.scope)})]})}),(0,r.jsx)(aN,{active:b,onClick:()=>{y(!0),$(null),T(null)},children:d("i18n.addPlugin")})]}),(0,r.jsx)(aj,{children:(0,r.jsx)(ai,{className:"is-fill",children:b?(0,r.jsx)(cF,{cwd:n,source:j,scope:w,projectResourcesLoaded:Z,busy:ei,actionError:E,onSourceChange:k,onScopeChange:S,onInstall:en}):h?null:q?(0,r.jsx)(cB,{extension:q}):K?(0,r.jsx)(cD,{pkg:K,cwd:n,busyKey:C,actionError:E,actionMessage:I,sessionId:o,updateStatus:L[cR(K)],checkingUpdate:z.has(cR(K)),updateError:F,onAction:ee,onCheckUpdate:()=>void X(K),onReloadSession:er},cR(K)):(0,r.jsx)(ay,{children:d("i18n.selectPackage")})})})]}),(0,r.jsxs)(ak,{status:eo>0?(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--accent)"},children:[eo," ",1===eo?d("i18n.update"):d("i18n.updates")]}):u?.diagnostics.length?(0,r.jsx)(aw,{tone:u.diagnostics.some(e=>"error"===e.type)?"error":"warning",summary:1===u.diagnostics.length?d("plugins.diagnostic"):d("plugins.diagnostics",{count:u.diagnostics.length}),details:u.diagnostics.map(cP)}):(0,r.jsx)(aw,{summary:u?[d("i18n.resourceCount",{count:(t=u.totals).extensions,label:d("i18n.extensionShort")}),d("i18n.resourceCount",{count:t.skills,label:d("i18n.skillShort")}),d("i18n.resourceCount",{count:t.prompts,label:d("i18n.promptShort")}),d("i18n.resourceCount",{count:t.themes,label:d("i18n.themeShort")})].join(" \xb7 "):""}),children:[!a&&(0,r.jsx)(aS,{onClick:s,children:d("i18n.close")}),es&&(0,r.jsx)(aS,{variant:eo>0?"primary":"secondary",onClick:()=>void(eo>0?Q():X()),disabled:el,title:eo>0?d("i18n.updateAllPluginsHint"):void 0,children:B?d("i18n.updating"):W?d("i18n.checking"):eo>0?`${d("i18n.updateAllPlugins")} (${eo})`:d("i18n.checkUpdates")}),(0,r.jsx)(aS,{variant:"secondary",onClick:()=>void J(),disabled:el,children:d("i18n.refresh")})]})]})}let c_={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 cU(e,t){return e.replace(/\{(\w+)\}/g,(e,n)=>void 0===t[n]?e:String(t[n]))}function cK(e){let t=e.replace(/[\\/]+$/,""),n=t.split(/[\\/]/);return n[n.length-1]||t}function cq(e){var t;let n,{onClose:o,embedded:s=!1}=e,{locale:l}=(0,eh.s)(),a=c_[l]??c_.en,[c,d]=(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,S]=(0,i.useState)(null),C=(0,i.useCallback)(async()=>{g(!1);try{let[e,t]=await Promise.all([fetch("/api/archives",{cache:"no-store"}),fetch("/api/home",{cache:"no-store"})]);if(!e.ok)throw Error("load failed");let n=await e.json(),r=await t.json().catch(()=>({}));"string"==typeof r.home&&f(r.home);let i=Array.isArray(n.projects)?n.projects:[];d(i),p(e=>e&&i.some(t=>t.key===e)?e:i[0]?.key??null)}catch{g(!0)}},[]);(0,i.useEffect)(()=>{C()},[C]);let N=c.find(e=>e.key===u)??null,E=async e=>{if(0!==e.length){v(!0),S(null);try{for(let t of R(e)){let e={action:"set",ids:t,archived:!1},n=await fetch("/api/sessions/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store"});if(!n.ok)throw Error(`unarchive failed: ${n.status}`)}y(!1),k(""),await C()}catch{S(a.loadFailed)}finally{v(!1)}}},$=async e=>{v(!0),S(null);try{let t=await fetch("/api/archives/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectKey:e.key,confirm:j.trim()})}),n=await t.json().catch(()=>({}));if(409===t.status&&n.runningSessionIds?.length)return void S(a.runningBlocked);if(!t.ok)throw Error(n.error??"delete failed");y(!1),k(""),d(t=>t.filter(t=>t.key!==e.key)),p(t=>t===e.key?null:t)}catch{S(a.deleteFailed)}finally{v(!1)}};return(0,r.jsx)(l3,{embedded:s,title:a.title,onClose:o,children:m?(0,r.jsx)(ay,{children:a.loadFailed}):0===c.length?(0,r.jsx)(ay,{children:a.empty}):(0,r.jsxs)(l5,{children:[(0,r.jsx)(l6,{children:(0,r.jsx)(l9,{children:c.map(e=>(0,r.jsx)(an,{active:e.key===u,onClick:()=>{p(e.key),y(!1),k(""),S(null)},children:(0,r.jsx)(ar,{title:e.root,children:cK(e.root)})},e.key))})}),(0,r.jsx)(aj,{children:N?(0,r.jsxs)(ai,{children:[(0,r.jsxs)(ao,{children:[(0,r.jsx)(as,{children:(0,r.jsx)(aa,{children:cK(N.root)})}),(0,r.jsxs)(al,{children:[(0,r.jsx)(aS,{variant:"secondary",size:"small",disabled:x||0===N.families.length,onClick:()=>void E(N.families.map(e=>e.id)),children:x?a.busy:a.unarchive}),!b&&(0,r.jsx)(aS,{variant:"danger",size:"small",disabled:x||0===N.families.length,onClick:()=>{y(!0),k(""),S(null)},children:a.deleteSessions})]})]}),(0,r.jsx)(ad,{label:a.path,children:(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",wordBreak:"break-all"},children:(t=N.root,h&&t.startsWith(h)?"~"+t.slice(h.length):t)})}),b&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:cU(a.deleteConfirmLead,{count:N.families.length})}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:a.deleteConfirmHint}),(0,r.jsx)("input",{value: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)(aS,{variant:"danger",size:"small",disabled:x||"confirm"!==(n=j.trim().toLowerCase())&&"确认"!==n&&"確認"!==n,onClick:()=>void $(N),children:x?a.busy:a.deleteSessions}),(0,r.jsx)(aS,{variant:"ghost",size:"small",disabled:x,onClick:()=>{y(!1),k("")},children:a.cancel})]})]}),(0,r.jsx)(ac,{children:cU(a.sessions,{count:N.families.length})}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2,minHeight:0,overflowY:"auto"},children:N.families.map(e=>{let t=function(e,t){let n=e.name?.trim();if(n)return n;let r=e.firstMessage?.replace(/\s+/g," ").trim();return r&&"(no messages)"!==r?r:t}(e,a.untitled);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3,padding:"8px 10px",borderRadius:6,background:"var(--bg-hover)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,fontSize:12,fontWeight:500,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:t,children:t}),(0,r.jsx)(aS,{variant:"ghost",size:"small",disabled:x,onClick:()=>void E([e.id]),children:x?a.busy:a.unarchive})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,fontSize:11,color:"var(--text-muted)"},children:[(0,r.jsx)("span",{children:(0,tl.fw)(new Date(e.archivedAt),l)}),(0,r.jsx)("span",{children:cU(a.messages,{count:e.messageCount})})]})]},e.id)})}),w&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:w})]}):(0,r.jsx)(ay,{children:a.empty})})]})})}let cZ="\\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",cV=RegExp(`[${cZ}]`,"gu"),cJ=RegExp(`[${cZ}]`,"u");function cY(e){return e.replace(cV,e=>{let t=e.codePointAt(0)??0;return`\\u{${t.toString(16).toUpperCase().padStart(4,"0")}}`})}let cG=/[\s"'`$|&;<>()*?#~]/;function cX(e){let t=cJ.test(e),n=cY(e);return""===n||t||cG.test(n)?`"${n.replace(/"/g,'\\"')}"`:n}function cQ(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return[e,...t].map(cX).join(" ")}function c0(e){let t=void 0!==e.command?cQ(e.command,e.args):void 0,n=void 0!==e.url?cY(e.url):void 0;return"http"===e.transport?n:"stdio"===e.transport?t:n??t}function c1(e){return[e.name,e.command,e.cwd,e.url,...e.args??[],...e.envNames,...e.headerNames].some(e=>void 0!==e&&cJ.test(e))}function c2(e){return"oauth-client-secret"===e.kind?{key:"mcp.field.oauthClientSecret"}:{key:"env"===e.kind?"mcp.field.env":"mcp.field.header",params:{name:cY(e.name??"")}}}function c4(e){return"http"===e.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables"}function c8(e){return e.length>0?{key:"mcp.server.overridesGlobal",params:{keys:e.join(", ")}}:{key:"mcp.server.overridesGlobalNothing"}}function c3(e){return e.flatMap(e=>{let{variables:t,...n}=e;return t.map(e=>({variable:e,field:n}))})}function c5(e,t){return"unparsable"===e.reason||"unreadable"===e.reason?cY(e.error):"link-outside"===e.reason?void 0===t?void 0:cY(t):void 0}let c6="codemode";function c9(e){return`${e.scope}\0${e.name}`}function c7(e){return e?.trust?.decision===!0}function de(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":"global"===e.scope&&e.overriddenByProject&&t.projectServersLoad?"overridden":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 dt={invalid:"mcp.state.invalid","web-password":"mcp.state.web-password",disabled:"mcp.state.disabled","not-trusted":"mcp.state.not-trusted",replaced:"mcp.state.replaced",overridden:"mcp.state.overridden","mcp-off":"mcp.state.mcp-off",connected:"mcp.state.connected","needs-auth":"mcp.state.needs-auth",failed:"mcp.state.failed",connecting:"mcp.state.connecting",disconnected:"mcp.state.disconnected",conflict:"mcp.state.conflict",on:"mcp.state.on"},dn={connected:"mcp.state.session.connected",failed:"mcp.state.session.failed"};function dr(e,t){return(t?.origin==="session"?dn[e]:void 0)??dt[e]}let di={disabled:"mcp.server.disabled","not-trusted":"mcp.stateDetail.not-trusted",replaced:"mcp.server.shadowedByProject",overridden:"mcp.server.overriddenByProject","mcp-off":"mcp.stateDetail.mcp-off",disconnected:"mcp.stateDetail.disconnected",conflict:"mcp.stateDetail.conflict"},ds={invalid:"mcp.stateShort.invalid","web-password":"mcp.stateShort.web-password",disabled:"mcp.stateShort.disabled","not-trusted":"mcp.stateShort.not-trusted",replaced:"mcp.stateShort.replaced",overridden:"mcp.stateShort.overridden","needs-auth":"mcp.stateShort.needs-auth",failed:"mcp.stateShort.failed",connecting:"mcp.stateShort.connecting",disconnected:"mcp.stateShort.disconnected",conflict:"mcp.stateShort.conflict"};function dl(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 da(e){return"on"===e?{active:!0}:"off"===e?{active:!1}:{color:"error"===e?"#ef4444":"#f59e0b"}}function dc(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 dd={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"},du={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"},dp={connecting:"off",connected:"on","needs-auth":"warning",failed:"error",disconnected:"warning",conflict:"error","not-trusted":"warning"},dh={codemode:"mcp.exposure.codemode",deferred:"mcp.exposure.deferred",direct:"mcp.exposure.direct",hidden:"mcp.exposure.hidden"},df=["codemode","deferred","direct","hidden"],dm={codemode:"mcp.exposureShort.codemode",deferred:"mcp.exposureShort.deferred",direct:"mcp.exposureShort.direct",hidden:"mcp.exposureShort.hidden"};function dg(e){return"auto-enable-codemode-invalid"!==e.reason}function dx(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 dv(e){return{enabled:e.filter(e=>e.enabled).length,total:e.length}}function db(e,t){let n=e.flatMap(e=>e.servers.map(c9));return t===c6||null!==t&&n.includes(t)?t:n[0]??null}function dy(e){let t=e?.trust;return void 0!==t&&t.requiresTrust&&!t.trusted}function dj(e){return e.projectOverride?.preference??e.preference}let dk={always:"mcp.codemode.projectOverride.always",automatic:"mcp.codemode.projectOverride.automatic"},dw={on:"mcp.codemode.toolMode.onDescription",only:"mcp.codemode.toolMode.onlyDescription"},dS={on:"mcp.codemode.toolMode.projectOverride.on",only:"mcp.codemode.toolMode.projectOverride.only"},dC={automatic:"mcp.codemode.automatic",always:"mcp.codemode.always",unavailable:"mcp.codemode.unavailable",unknown:"i18n.unknown"};function dN(e){return"unavailable"===e?"error":"unknown"===e?"off":"on"}let dE=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e);function d$(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}:{},...dE(n.names)?{names:n.names}:{},...dE(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 dI(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 dT(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 dM(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&&dT(i)?{ok:!0,data:i}:{ok:!1,error:d$(i,r.status)}}let dR=new Set(["cwd-invalid","cwd-denied","cwd-not-directory"]);async function dL(e,t,n){let r=await dM(e,t,n);if(r.ok||!e||!r.error.reason||!dR.has(r.error.reason))return r;let i=await dM(null,t,n);return i.ok?{...i,projectError:r.error}:i}async function dA(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 dI(n=>dL(e,t,n),()=>({ok:!1,error:{error:`GET /api/mcp did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function dz(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:d$(o,i.status)}}async function dP(e,t,n){let r=await dz({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 dW(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 dI(n=>dP(e,t,n),()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function dO(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 dI(async n=>{let r=await dz({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 dF(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 dI(async n=>{let r=await dz({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 dD(e){return!e.available&&"builtin-disabled"!==e.reason}function dB(e,t){if(dD(t.mcp))return"mcp-off";if("project"===e){if(!t.project?.trust)return"trust-unreadable";if(!c7(t.project))return"project-untrusted"}}let dH={"mcp-off":"mcp.readOnly.mcp-off","project-untrusted":"mcp.readOnly.project-untrusted","trust-unreadable":"mcp.readOnly.trust-unreadable"};function d_(e){return!0!==e.notAnObject}function dU(e){return d_(e)&&void 0===e.webPasswordField}async function dK(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&&dT(i)?{ok:!0,data:i}:{ok:!1,error:d$(i,r.status)}}async function dq(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 dI(e=>dK(o,n,e),()=>({ok:!1,error:{error:`POST /api/mcp did not answer within ${i} ms`,timedOut:!0}}),i,r)}let dZ={"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 dV(e,t){let n=dB(e.scope,t);return n||(void 0===e.invalidError&&e.validated?e.webPasswordField?"web-password":void 0:"invalid")}let dJ={"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"},dY={connected:"mcp.test.state.connected","needs-auth":"mcp.test.state.needs-auth",failed:"mcp.test.state.failed",timedOut:"mcp.test.state.timedOut"},dG={connected:"mcp.test.summary.connected","needs-auth":"mcp.test.summary.needs-auth",failed:"mcp.test.summary.failed",timedOut:"mcp.test.summary.timedOut"},dX={connected:"mcp.signIn.summary.connected","needs-auth":"mcp.signIn.summary.needs-auth",failed:"mcp.signIn.summary.failed",timedOut:"mcp.signIn.summary.timedOut"};function dQ(e){return(Math.max(0,e)/1e3).toFixed(1)}async function d0(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:d$(i,r.status)}}async function d1(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 dI(e=>d0(o,n,e),()=>({ok:!1,error:{error:`POST /api/mcp/test did not answer within ${i} ms`,timedOut:!0}}),i,r,{abortAtDeadline:!1})}let d2="•••",d4=new Set(["key","apikey","token","secret","password","passwd","passphrase","pwd","pass","credential","credentials","authorization","bearer","jwt","cookie","signature","pat"]),d8=new Set([...d4,"auth","sig","code","pw"]),d3=["token","secret","password","passwd","apikey"],d5=new Set(["file","path","dir","url","uri","endpoint","id","name","type","header","env","var","length","ttl","expiry","expires","timeout","mode","format"]),d6=new Set(["-k"]);function d9(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 d7(e,t){let n=d9(e);return!(n.length>1&&d5.has(n[n.length-1]))&&n.some(e=>t.has(e)||d3.some(t=>e.length>t.length&&e.endsWith(t)))}function ue(e){return d7(e,d4)}let ut=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,})"),un=/^eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*$/,ur=/^[A-Za-z0-9_\-+/=.~]+$/;function ui(e){return!(/\s/.test(e)||uc(e))&&(!!(ut.test(e)||un.test(e))||!(e.length<24||!ur.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 uo=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Za-z_][A-Za-z0-9_]*/,us=RegExp(uo.source,"g"),ul=/^(?:bearer|basic|token)\s+/i;function ua(e,t,n){let r=e.replace(ul,"");return t.test(r)&&/^[^A-Za-z0-9]*$/.test(r.replace(n,""))}function uc(e){return ua(e.replace(/\$[$!]/g,"_x"),uo,us)}let ud=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Z_][A-Z0-9_]*(?![A-Za-z0-9_])/,uu=RegExp(ud.source,"g");function up(e){return ua(e,ud,uu)}function uh(e,t){if(!e||""===t)return;e.push(t);let n=ug(t);n!==t&&e.push(n)}let uf=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#]*)/;function um(e,t,n){let r=!1,i=e,o="",s=uf.exec(e);if(s){let[l,a,c]=s,d=c.lastIndexOf("@");if(d>=0&&!t(ug(c.slice(0,d)))){o=`${a}${d2}${c.slice(d)}`,r=!0;let e=c.slice(0,d);uh(n,e);let t=e.indexOf(":");t>=0&&uh(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),c=l<0?"":i.slice(l),d=a.split("/").map(e=>ui(ug(e))?(r=!0,uh(n,e),d2):e).join("/");return c=c.replace(/([?&#;])([^&#;]*)/g,(e,i,o)=>{let s=o.indexOf("=");if(s<0){let s=ug(o);return!ui(s)||t(s)?e:(r=!0,uh(n,o),`${i}${d2}`)}let l=o.slice(0,s),a=ug(o.slice(s+1));return""===a||t(a)||!function(e){let t=e;try{t=decodeURIComponent(e)}catch{}return d7(t,d8)}(l)&&!ui(a)?e:(r=!0,uh(n,o.slice(s+1)),`${i}${l}=${d2}`)}),{value:`${o}${d}${c}`,masked:r}}function ug(e){try{return decodeURIComponent(e)}catch{return e}}let ux=/^(\s*[A-Za-z][A-Za-z0-9 _.-]*=)([\s\S]*)$/;function uv(e,t,n){let r=/^([A-Za-z0-9_-]+):(\s*)([\s\S]*)$/.exec(e);if(r&&""!==r[3]&&!r[3].startsWith("//")&&ue(r[1])){let[,i,o,s]=r;return t(s)?{value:e,masked:!1}:(uh(n,s.trim()),{value:`${i}:${o}${d2}`,masked:!0})}let i=e.includes(";")?function(e,t,n){let r=e.split(";");if(r.length<2||!r.every(e=>""===e.trim()||ux.test(e)))return;let i=!1;return{value:r.map(e=>{let r=ux.exec(e);if(!r)return e;let[,o,s]=r;if(""===s.trim()||t(s))return e;if(ue(o.slice(0,-1).trim()))return i=!0,uh(n,s.trim()),`${o}${d2}`;let l=uv(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]&&ue(o[1]))return t(o[2])?{value:e,masked:!1}:(uh(n,o[2]),{value:`${o[1]}=${d2}`,masked:!0});if(/\s/.test(e)){var s,l,a;let r,i;return s=e,l=t,a=n,i=uj((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 um(e,t,n);if(o&&""!==o[2]){let e=uv(o[2],t,n);return{value:`${o[1]}=${e.value}`,masked:e.masked}}return ui(e)&&!t(e)?(uh(n,e),{value:d2,masked:!0}):{value:e,masked:!1}}function ub(e){if(d6.has(e))return!0;if(!/^--?[A-Za-z]/.test(e))return!1;let t=e.replace(/^-+/,"");return ue(t)||"auth"===d9(t).at(-1)}let uy=/^(?:bearer|basic|token)$/i;function uj(e,t,n,r){let i=!1,o=!1;return{values:e.map(e=>{if(""===e)return e;if(o){if(n&&uy.test(e))return e;if(o=!1,!/^-[A-Za-z-]/.test(e))return t(e)?e:(i=!0,uh(r,e),d2)}let s=/^(--?[A-Za-z][A-Za-z0-9_.-]*)=([\s\S]*)$/.exec(e);if(s){let[,e,n]=s;if(""!==n&&ub(e)&&!t(n))return i=!0,uh(r,n),`${e}=${d2}`;let o=uv(n,t,r);return i||=o.masked,`${e}=${o.value}`}if(/^--?[A-Za-z][A-Za-z0-9_.-]*$/.test(e))return o=ub(e),e;if(n){let t=/^([A-Za-z0-9_-]+):$/.exec(e);if(uy.test(e)||t&&ue(t[1]))return o=!0,e}let l=uv(e,t,r);return i||=l.masked,l.value}),masked:i}}function uk(e){let{values:t,masked:n}=uj(e,up,!1);return{args:t,masked:n}}function uw(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function uS(e){return!e.startsWith("!")&&!uc(e)}function uC(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 uN={"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(uN);let uE={dollarBrace:!1,bareDollar:!1,percent:!1,braceEnv:!1},u$={dollarBrace:!0,bareDollar:!1,percent:!0,braceEnv:!0},uI={...u$,bareDollar:!0},uT={...uE,braceEnv:!0},uM=/^[A-Za-z_][A-Za-z0-9_]*$/,uR=/\$\{([^{}]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)|%([A-Za-z_][A-Za-z0-9_]*)%|\{(env|file):([^{}]*)\}/g;function uL(e,t){if(!t)return;let n=e[e.length-1];n?.kind==="text"?n.text+=t:e.push({kind:"text",text:t})}function uA(e,t,n){let r=[],i=0;uR.lastIndex=0;for(let o=uR.exec(e);o;o=uR.exec(e)){let[s,l,a,c,d,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(uM.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!==c&&t.percent&&n)p={kind:"env",name:c,from:s};else if(void 0!==d&&t.braceEnv)p="env"===d&&uM.test(u)?{kind:"env",name:u,from:s}:{kind:"unsupported",from:s};else if(void 0!==c||void 0!==d){uL(r,e.slice(i,o.index+1)),i=o.index+1,uR.lastIndex=o.index+1;continue}uL(r,e.slice(i,o.index)),"string"==typeof p?uL(r,p):r.push(p),i=o.index+s.length}return uL(r,e.slice(i)),r}function uz(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 uP(e){return e.startsWith("!")}function uW(e){if(uP(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);uM.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 uO=/<[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,uF=/^(?:\.\.\.|…|\*{3,}|x{3,}|TODO|FIXME|changeme|change[-_]me|replace[-_]?me|placeholder|redacted|\[[^\]]+\])$/i,uD=/(?:^|[\\/])(?:path[\\/]to(?:[\\/]|$)|Users[\\/](?:username|yourname|your[-_][A-Za-z_-]+|user[-_]?name|<[^>]+>)(?:[\\/]|$)|home[\\/](?:username|yourname|your[-_][A-Za-z_-]+|<[^>]+>)(?:[\\/]|$))/i,uB=/^(Bearer|Basic|Token|Bot|ApiKey|Api-Key)\s+(.+)$/i;function uH(e){return e.join("\0")}function u_(e){return"args"===e[0]?`args[${e[1]}]`:e.join(".")}function uU(e){return"env"===e[0]||"headers"===e[0]||"oauth"===e[0]&&"clientSecret"===e[1]}function uK(e){return"command"===e[0]||"args"===e[0]||"cwd"===e[0]}let uq=new Set(["HOME","USERPROFILE"]);class uZ{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 uV(e){return e.map(e=>"text"in e?e.text:e.from).join("")}let uJ=/\$\{[^{}]*\}/g,uY=new Set(["variable","home","workspace-basename","unsupported-variable","input"]);class uG{constructor(e){this.draft=e,this.fields=new Map,this.argTexts=e.args.map(uV),this.urlText=uV(e.url??[])}encode(e,t){let n,r=uU(e),i=u_(e),o=uV(t),s=[],l=!1,a=()=>s.every(e=>""===e),c=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=uz(e,{atStart:a()});n!==e&&(l=!0),s.push(n)},d=e=>s.push(e),u=e=>s.push({field:e});if(!r&&uK(e)&&1===t.length&&"text"in t[0]&&uD.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(uD.test(n))return t&&d(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[c,d]of function(e){let t=e.trim();if(uF.test(t)){let n=e.indexOf(t);return[[n,n+t.length]]}let n=uB.exec(t);if(n&&uF.test(n[2].trim())){let t=e.lastIndexOf(n[2].trim());return[[t,t+n[2].trim().length]]}let r=[];uO.lastIndex=0;for(let t=uO.exec(e);t;t=uO.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 c<n&&d>t}))continue;c>s&&r(t.slice(s,c)),"url"===e[0]&&uX(o,p+c)&&(n="uri-component");let h=t.slice(c,d);u(this.field(e,"placeholder",(l=e,a=h,"env"===l[0]||"headers"===l[0]?l[1]:a.replace(/^[<{\s]+|[>}\s]+$/g,"")||u_(l)),h)),s=d}s<t.length&&r(t.slice(s))};switch(s.kind){case"text":m(s.text,c,[]);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()&&uP(e)){this.draft.note("shell-command-value",{field:i}),d(e);break}let t=[...e.matchAll(uJ)].map(e=>[e.index,e.index+e[0].length]);m(e,d,t);break}case"env":r?(d(`\${${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}}`})):uK(e)&&a()&&uq.has(s.name)&&f?(d("~"),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?(d("${HOME}"),this.draft.note("home-variable-translated",{field:i,from:s.from,to:"${HOME}"})):uK(e)&&a()&&f?(d("~"),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")):(d("."),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]&&uX(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=>uH(t.path)===uH(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=uY.has(t)?`${t}.${n}`:u_(e);if(uY.has(t)){if(this.fields.has(s))return s}else for(let t=2;this.fields.has(s);t++)s=`${u_(e)}#${t}`;let l=this.isSecretContext(e,r)||ue(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 ue(e[1]);case"oauth":return"clientSecret"===e[1];case"args":{if(uk([this.argTexts[e[1]]??""]).masked)return!0;let t=this.argTexts[e[1]-1];return void 0!==t&&uk([t,"x"]).args[1]===d2}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,um(`https://host.invalid/?${n}=x`,up).masked)}default:return!1}}}function uX(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 uQ(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 u0=/^[A-Za-z0-9_-]+$/;function u1(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 u2=new Set(["mcp","server","mcp-server","mcpserver","cli","index","main","app","src","dist","build","bin","lib"]);function u4(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=u3(t);return o&&!u2.has(o.toLowerCase())?o:u3(r)||r||o||t}let u8=[/^mcp[-_]server[-_]/i,/^server[-_]/i,/^mcp[-_]/i,/[-_]mcp[-_]server$/i,/[-_]mcp$/i,/[-_]server$/i];function u3(e){let t=e;for(let e=!0;e;)for(let n of(e=!1,u8)){let r=t.replace(n,"");r!==t&&r&&(t=r,e=!0)}return t}let u5=new Set(["mcp","www","api","app","server","servers","remote","gateway"]);function u6(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=>!u5.has(e.toLowerCase()));return r[r.length-1]??n[n.length-1]??""}let u9=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 u7(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 pe(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(!u2.has(n.toLowerCase())&&"."!==n&&".."!==n)return u3(n.replace(/_/g,"-"))||n}return""}function pt(e,t){pn(e,t)&&pr(e,Math.ceil(t/1e3),t)}function pn(e,t){return!!("number"==typeof t&&Number.isFinite(t))&&t>0||(void 0!==t&&e.note("timeout-dropped",{value:String(t)}),!1)}function pr(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 pi=["codemode","deferred","direct","hidden"],po={"codemode-deferred":"codemode"},ps=["localhost","127.0.0.1","[::1]"];function pl(e){return"string"==typeof e&&pi.includes(e)?e:"string"==typeof e&&Object.hasOwn(po,e)?po[e]:void 0}function pa(e){try{return new URL(e)}catch{return}}function pc(e){let t=pa(e);return void 0!==t&&"http:"===t.protocol&&ps.includes(t.hostname)&&""===t.search&&""===t.hash}function pd(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function pu(e){return pd(e)&&Object.values(e).every(e=>"string"==typeof e)}function pp(e,t){if(!u0.test(e))return{problem:"name",name:e};if(!pd(t))return{problem:"not-an-object"};let{type:n,exposure:r,enabled:i,timeout:o,toolExposure:s,description:l}=t;if(void 0!==r&&!pl(r))return{problem:"exposure",value:String(r)};if(void 0!==s){if(!pd(s))return{problem:"tool-exposure"};for(let[e,t]of Object.entries(s))if(!pl(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=pa(t.url);if(!e||!/^https?:$/.test(e.protocol))return{problem:"url",url:t.url};if(void 0!==t.headers&&!pu(t.headers))return{problem:"headers"};let n=function(e){var t;let n;if(void 0===e)return;if(!pd(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||!pc(e.callbackUrl))return{problem:"callback-url",value:String(e.callbackUrl)};let t=new URL(e.callbackUrl).port;if(t&&void 0!==r&&Number(t)!==r)return{problem:"callback-port-mismatch",value:t}}if(void 0!==e.scope&&"string"!=typeof e.scope)return{problem:"oauth-scope"};if(void 0!==e.clientName&&("string"!=typeof e.clientName||!e.clientName.trim()))return{problem:"oauth-client-name"};if(void 0!==e.clientRegistration&&"dcr"!==e.clientRegistration){if("cimd"!==e.clientRegistration)return{problem:"oauth-client-registration",value:String(e.clientRegistration)};if(void 0!==e.clientId||void 0!==e.clientName)return{problem:"oauth-client-registration-client"};let t="string"==typeof e.callbackUrl?pa(e.callbackUrl):void 0;if(t&&("[::1]"===t.hostname||"/callback"!==t.pathname))return{problem:"oauth-client-registration-callback"}}if(void 0!==e.authServerMetadataUrl&&!(void 0!==(n="string"==typeof(t=e.authServerMetadataUrl)?pa(t):void 0)&&("https:"===n.protocol||"http:"===n.protocol&&ps.includes(n.hostname))))return{problem:"auth-server-metadata-url",value:String(e.authServerMetadataUrl)}}(t.oauth);if(n)return n;let r=t.auth;if(void 0!==r){if(!pd(r)||"string"!=typeof r.provider||!r.provider)return{problem:"auth"};if("https:"!==e.protocol&&!ps.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||pu(t.env)?void 0!==t.cwd&&"string"!=typeof t.cwd?{problem:"cwd"}:void 0:{problem:"env"}:{problem:"args"}:{problem:"no-command-or-url"}}let ph=/[A-Za-z_]/,pf=/[A-Za-z0-9_]/,pm=/^[A-Za-z_][A-Za-z0-9_]*$/,pg=new Set([..." \n'\"\\$`|&;<>()#*?[]{}!~="]),px=new Set([..."|&;<>()"]),pv=/[0-9@*#?$!-]/,pb={n:"\n",t:" ",r:"\r",a:"\x07",b:"\b",e:"\x1b",E:"\x1b",f:"\f",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function py(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 pj(e,t){return/^(?:[A-Za-z]:\\|\\\\[A-Za-z0-9.$_-])/.test(e.slice(t,t+4))}class pk{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 pw)return{ok:!1,error:e.detail};throw e}return{ok:!0,words:this.words}}fail(e){throw new pw(e)}startWord(){return this.parts||(this.lineBreak&&this.fail({code:"multiple-commands"}),this.parts=[],this.windowsWord=pj(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)&&py(e,this.index)>0)this.index+=py(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:"`"}):px.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||!pg.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=pj(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 pb?(t+=pb[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&&ph.test(n)){let n=this.index+1;for(;n<t.length&&pf.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&&pv.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}),pm.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 pw extends Error{constructor(e){super(e.code),this.detail=e}}function pS(e){return new pk(e).run()}function pC(e){return e.parts.every(e=>"text"===e.type)?e.text:void 0}function pN(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let pE=["httpUrl","trust","includeTools","excludeTools","authProviderType","targetAudience","targetServiceAccount","tcp"];function p$(e){if(pE.some(t=>t in e))return!0;let t=e.oauth;return pN(t)&&["redirectUri","authorizationUrl","tokenUrl","audiences","tokenParamName"].some(e=>e in t)}function pI(e){if(!pN(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]||pN(t)&&"string"==typeof t.path||"string"==typeof n||"string"==typeof r||"string"==typeof i}function pT(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 pM(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 pR(e,t){let n=t?pM(t):void 0;return{code:"sse-transport",params:{...e?{server:e}:{},...t?{url:t}:{},...n?{suggestedUrl:n}:{}}}}function pL(e){return e?{server:e}:{}}function pA(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?String(e):void 0}function pz(e,t,n){let r;if(!pN(t))return{note:{code:"no-command-or-url",params:pL(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 uE;case"opencode":return uT;case"vscode":return u$;default:return p$(t)?uI:u$}}(n,t),a=o("name"),c=e??("string"==typeof a?a:void 0),d=new uZ(n.source,s),u=(e,t)=>{if(s)return e?[{kind:"pi",text:e}]:[];return t&&"mcp-servers"===n.flavor&&/^!|\$\$|\$!/.test(e)&&d.note("looks-like-pi-config"),uA(e,l,t)};d.name=c,d.inputs=n.inputs;let p=o("inputs");Array.isArray(p)&&(d.inputs=new Map([...n.inputs??[],...pO(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:pL(c)}};if(void 0!==h&&"unknown"===(r="string"==typeof h?pT(h):"unknown"))return{note:{code:"unsupported-transport",params:{...pL(c),type:String(h)}}};let g="string"==typeof f&&""!==f||Array.isArray(f)||pN(f),x=void 0!==m;if("sse"===r)return{note:pR(c,m)};if("ws"===r)return{note:{code:"websocket-transport",params:{...pL(c),...m?{url:m}:{}}}};if(void 0===r){if(g&&x)return{note:{code:"ambiguous-command-and-url",params:pL(c)}};if(x){if(void 0!==pM(m))return{note:pR(c,m)};r="http","mcp-servers"===n.flavor&&"string"==typeof t.url&&"string"!=typeof t.httpUrl&&d.note("transport-guessed")}else{if(!g)return{note:{code:"no-command-or-url",params:pL(c)}};r="stdio"}}if("stdio"!==r&&"http"!==r)return{note:{code:"unsupported-transport",params:{...pL(c),type:String(h)}}};if("stdio"===r&&!g||"http"===r&&!x)return{note:{code:"no-command-or-url",params:pL(c)}};if(d.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:{...pL(e.name),problem:"args"}};s=n[0],l=[...n.slice(1),...Array.isArray(l)?l:[]]}else if(pN(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:pL(e.name)};let c=Array.isArray(l)?[...l]:[];if(void 0!==l&&!Array.isArray(l))return{code:"invalid-config",params:{...pL(e.name),problem:"args"}};if(0===c.length&&/\s/.test(s.trim())&&!/^(?:[A-Za-z]:[\\/]|[\\/]|~[\\/]|\.{1,2}[\\/])/.test(s.trim())){let t=pS(s.trim()),n=t.ok?t.words.map(pC):void 0;n&&n.length>1&&n.every(e=>void 0!==e)&&(e.note("command-split",{command:s}),s=n[0],c.push(...n.slice(1)))}for(let[t,n]of(e.command=i(s,!1),c.entries())){let r=pA(n);if(void 0===r)return{code:"invalid-config",params:{...pL(e.name),problem:"args",index:t}};e.args.push(i(r,!1))}if(void 0!==a){if(!pN(a))return{code:"invalid-config",params:{...pL(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=pA(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&&ue(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 d=r("cwd");for(let n of("string"==typeof d&&""!==d?e.cwd=i(d,!1):void 0!==d&&""!==d&&e.note("dropped-key",{key:"cwd"}),["headers","oauth","auth","url","httpUrl","serverUrl"]))n in t&&(r(n),e.note("dropped-key",{key:n}))}(d,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=pN(o)&&Object.keys(o).some(e=>"authorization"===e.toLowerCase());if(1===s.length&&"text"in s[0]?uQ(e,n,l):e.url=s,pN(o))for(let[t,n]of Object.entries(o)){let r=pA(n);if(void 0===r){e.note("dropped-key",{key:`headers.${t}`});continue}if(""===r.trim()){"authorization"===t.toLowerCase()?e.note("empty-authorization-dropped"):ue(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"),c=r("auth");if(!1===a?e.note("oauth-disable-unsupported"):pN(a)?pP(e,a,i):void 0!==a&&e.note("dropped-key",{key:"oauth"}),pN(c))for(let t of(pP(e,{...void 0!==c.CLIENT_ID?{clientId:c.CLIENT_ID}:{},...void 0!==c.CLIENT_SECRET?{clientSecret:c.CLIENT_SECRET}:{},...void 0!==c.scopes?{scopes:c.scopes}:{}},i,"auth."),Object.keys(c)))["CLIENT_ID","CLIENT_SECRET","scopes"].includes(t)||e.note("oauth-option-dropped",{key:`auth.${t}`});else void 0!==c&&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}))}(d,t,m,o,u);let v=o("timeout");if(void 0!==v)if(s)"number"==typeof v&&v>0?d.timeout=v:d.note("timeout-dropped",{value:String(v)});else if("opencode"===n.flavor)d.note("timeout-dropped",{value:String(v)});else if(p$(t))pt(d,v);else["autoApprove","alwaysAllow","transportType"].some(e=>e in t)||"streamableHttp"===t.type?pn(d,v)&&pr(d,Math.ceil(v),void 0):!function(e,t){if(!pn(e,t))return;let n=t>=1e3;e.note("timeout-unit-guessed",{value:t,unit:n?"milliseconds":"seconds"}),n?pr(e,Math.ceil(t/1e3),t):pr(e,Math.ceil(t),void 0)}(d,v);let b=o("enabled"),y=o("disabled");!1===b||!0===y?(d.enabled=!1,d.note("imported-disabled")):(void 0!==b&&"boolean"!=typeof b||void 0!==y&&"boolean"!=typeof y)&&d.note("dropped-key",{key:void 0!==b?"enabled":"disabled"});let j=o("exposure");if(void 0!==j){let e=pl(j);e?d.exposure=e:d.note("invalid-exposure-dropped",{value:String(j)})}let k=o("toolExposure");if(void 0!==k){let e=pN(k)?Object.entries(k).map(e=>{let[t,n]=e;return[t,pl(n)]}):void 0;e?.every(e=>{let[,t]=e;return void 0!==t})?d.toolExposure=Object.fromEntries(e):d.note("invalid-exposure-dropped",{value:"toolExposure"})}if(s||void 0===j&&void 0===k||d.note("looks-like-pi-config"),s){let e=o("description");"string"==typeof e?d.description=e:void 0!==e&&d.note("dropped-key",{key:"description"})}for(let e of(pW(d,o("includeTools"),o("excludeTools")),Object.keys(t)))i.has(e)||d.note("dropped-key",{key:e});return{draft:d}}function pP(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"clientRegistration":"dcr"===o||"cimd"===o?e.oauth.clientRegistration=o: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&&pc(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 pW(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 pO(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e)pN(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=>pN(e)?e.value:e).filter(e=>"string"==typeof e)}:{}});return t}function pF(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=pN(t)&&pN(t[s[1]])?t[s[1]]:{};i.push(pD(`${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 pD(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 pB(e,t,n){let r=[],i="",o=()=>{i&&("pi"===t?r.push({kind:"pi",text:i}):r.push(...uA(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 pH(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 p_=/^https?:\/\//i,pU=/^wss?:\/\//i,pK={"@earendil-works/pi-coding-agent":"pi","@anthropic-ai/claude-code":"claude","@openai/codex":"codex","@google/gemini-cli":"gemini"},pq=new Set(["pi","claude","codex","gemini"]),pZ=new Set(["install","remove","uninstall","update","list","config"]);function pV(e){return"error"in e?{error:e.error}:{entries:[e],notes:[]}}let pJ={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"},pY=new Map([["-l","--local"]]),pG=["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name"],pX=["env","cwd"];function pQ(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,c=a>0?l.slice(0,a):l,d=n[c];if(!d){if(i.positional.length>=r.asArgAfter){i.positional.push(s),i.seen.set(`as-arg:${c}`,c);continue}return{error:{code:"cli-unknown-option",params:{cli:e,option:c}}}}if(i.seen.set(d.name,c),"flag"===d.kind){i.values.set(d.name,!0);continue}let u=a>0?p0(s,a+1):void 0;if("value"===d.kind||"list"===d.kind){let n=u??t[++o];if(void 0===n)return{error:{code:"cli-option-needs-value",params:{cli:e,option:c}}};"value"===d.kind?i.values.set(d.name,n):i.lists.set(d.name,[...i.lists.get(d.name)??[],n]);continue}let p=u?[u]:[];if(!u)for(;o+1<t.length&&r.variadic(d.name,t[o+1]);)p.push(t[++o]);if(0===p.length)return{error:{code:"cli-option-needs-value",params:{cli:e,option:c}}};i.lists.set(d.name,[...i.lists.get(d.name)??[],...p])}return i}function p0(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 p1=/^[A-Za-z_][A-Za-z0-9_]*=/,p2=/^[^\s:]+:/;function p4(e,t,n,r){for(let i of t??[]){let t=pH(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],pB(t[1],n,!0)])}}function p8(e,t,n,r){for(let i of t??[]){let t=pH(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,pB(s,n,!0)])}}function p3(e){if(void 0!==e&&!0!==e){if("user"===e.text)return"global";if("project"===e.text)return"project"}}function p5(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 c=void 0===n||!0===n?void 0:n.text.toLowerCase();if(void 0===c){if("http"==(o=p_.test(l.text)?"http":pU.test(l.text)?"ws":"stdio")&&void 0!==pM(l.text))return pR(s.text,l.text);"http"===o&&"gemini"===t&&e.note("transport-assumed-http")}else o="streamable-http"===c?"http":c;return"sse"===o?pR(s.text,l.text):"ws"===o?{code:"websocket-transport",params:{server:s.text,url:l.text}}:"http"===o?(e.transport="http",e.url=pB(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=pB(l.parts,i,!1),e.args=a.map(e=>pB(e.parts,i,!1)),"stdio")}let p6={"-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 p9(e,t){return"env"===e?p1.test(t.text):p2.test(t.text)&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(t.text)}function p7(e){e.oauth.clientSecret=[{kind:"prompt",id:"oauth.clientSecret",reason:"client-secret",label:"clientSecret",from:"",secret:!0}],e.note("client-secret-prompt")}let he={"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"--client-secret":{name:"client-secret",kind:"flag"}};function ht(e){let t,n=pC(e)??e.text;try{t=uC(n)}catch(e){return{error:{code:"invalid-json",params:{detail:e instanceof Error?e.message:String(e)}}}}return pN(t)?{value:t}:{error:{code:"no-servers-found"}}}let hn={"--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"}},hr={"-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 hi(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(ho(r),ho(i))}return t}function ho(e){try{return decodeURIComponent(e)}catch{return e}}function hs(e){let t=e.trim();for(let e=0;e<4;e++)try{return uC(t)}catch{let e=ho(t);if(e===t)break;t=e.trim()}}function hl(e){return{error:{code:"install-link-invalid",params:{detail:e}}}}function ha(e){let t=e.get("config");if(!t)return hl("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:hs(n);return pN(r)?{entries:[pz(e.get("name")||void 0,r,{source:"cursor-install-link",flavor:"mcp-servers",rawPi:!1})],notes:[]}:hl("config")}function hc(e,t,n,r){return pN(e)?{entries:[pz(n,e,{source:t,flavor:"vscode",rawPi:!1,inputs:pO(r)})],notes:[]}:hl("config")}function hd(e){return{error:{code:"by-name-link",params:{name:e}}}}function hu(e){let t=e.indexOf("?");return t<0?"":e.slice(t+1)}function hp(e){let t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=e.replace(/&amp;/g,"&");try{t=new URL(r)}catch{if(/^https?:\/\/\S+$/i.test(r)&&0===n)return{entries:[hf(void 0,r)],notes:[]};return{error:{code:"unrecognized-input"}}}if(n>3)return hl("nesting");let i=t.protocol.replace(/:$/,"").toLowerCase();switch(i){case"cursor":if(/\/mcp\/install\/?$/.test(t.pathname))return ha(hi(t.search));return hl("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 hd(ho(t[1]));if(/^mcp\/api\.mcp\.github\.com\//.test(e))return hd(e.replace(/^mcp\//,""));if(/^mcp\/install\?/.test(e))return hc(hs(hu(r)),"vscode-install-link");return hl(i)}case"vsweb+mcp":return hc(hs(hu(r)),"visual-studio-install-link");case"ghapp":if(/^\/\/mcp\/install/.test(r.slice(r.indexOf(":")+1)))return hc(hs(hu(r)),"copilot-app-install-link");return hl(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 ha(hi(e.search));if("vscode.dev"===r||"insiders.vscode.dev"===r){let t=hi(e.search);if(/^\/redirect\/?$/.test(i)&&t.get("url"))return hp(t.get("url"),n+1);if(/^\/redirect\/mcp\/install\/?$/.test(i)){let e=t.get("config");return e?hc(hs(e),"vscode-install-link",t.get("name")||void 0,hs(t.get("inputs")??"[]")):hl("config")}}if("aka.ms"===r&&/^\/vs\/mcp-install\/?$/i.test(i))return hc(hs(e.search.slice(1)),"visual-studio-install-link");if("github.com"===r&&/^\/copilot\/app\/launch\/?$/.test(i)){let t=hi(e.search).get("open");return t?hp(t,n+1):hl("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:[hf(e,t)],notes:[]}}(t,r,n);default:return{error:{code:"unsupported-url-scheme",params:{scheme:i}}}}}let hh=new Set(["localhost","127.0.0.1","[::1]"]);function hf(e,t){let n=u6(t)||void 0;if(void 0!==pM(t))return{note:pR(n,t)};let r=new uZ("url",!1);return r.transport="http",uQ(r,t,!1),e?.protocol!=="http:"||hh.has(e.hostname)||r.note("insecure-http",{host:e.hostname}),{draft:r}}let hm=/[\u200B-\u200D\u2060\uFEFF]/g,hg=/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]\S*)?$/i,hx={"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 hv(e){return new Set(e.fields.flatMap(e=>e.targets.map(e=>uH(e.path))))}function hb(e){var t;let n,r,i,o,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},l=(n=e.replace(hm,"").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=uC(e)}catch(t){try{n=uC(`{${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 pz(n,r,t)});if(Array.isArray(e)){let r=e.filter(pI);return 0===r.length?{error:{code:"no-servers-found"}}:{entries:r.map(e=>pz(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})),notes:n}}if(!pN(e))return{error:{code:"no-servers-found"}};let i=pN(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?u4(t.split("/").pop()??t):void 0,r=Array.isArray(e.remotes)?e.remotes.filter(pN):[],i=r.filter(e=>"string"==typeof e.type&&"http"===pT(e.type)&&"string"==typeof e.url);if(0===i.length){let e=r.find(e=>"sse"===e.type);return e?[{note:pR(n,"string"==typeof e.url?e.url:void 0)}]:[{note:{code:"registry-packages-unsupported",params:pL(n)}}]}return i.map(e=>{let r=new uZ("registry-server-json",!1);for(let i of(r.name=n,t&&n!==t&&(r.originalName=t),r.transport="http",r.url=pF(e.url,e.variables,"url.","registry-variable"),Array.isArray(e.headers)?e.headers.filter(pN):[])){if("string"!=typeof i.name||""===i.name)continue;let e=i.name;"string"==typeof i.value&&""!==i.value?r.headers.push([e,pF(i.value,i.variables,`headers.${e}.`,"registry-header")]):r.headers.push([e,[pD(`headers.${e}`,e,"",i,"registry-header")]])}return{draft:r}})}(i),notes:n};if(pN(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(pN(e.servers)){let t=pO(e.inputs);return{entries:r(e.servers,{source:"vscode-json",flavor:"vscode",rawPi:!1,inputs:t}),notes:n}}if(pN(e.mcp)){let t=e.mcp;if(pN(t.servers)){let e=pO(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(pN(e.context_servers))return{entries:Object.entries(e.context_servers).map(e=>{let t,[n,r]=e;return pN(r)&&("extension"===r.source||!pI(r))?{note:{code:"zed-extension-server",params:{server:n}}}:pz(n,pN(r)?(t={...r},delete t.source,t):r,{source:"zed-json",flavor:"zed",rawPi:!1})}),notes:n};if(pI(e))return{entries:[pz(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})],notes:n};let o=Object.values(e);return o.length>0&&o.every(pN)&&o.some(pI)?{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(hg.test(l)){if(!("error"in(o=hp(`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)?hp(l):(e=pS(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&&pK[i]&&e[t+1]?.text==="mcp"&&(n=t,r=pK[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 pV(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=pY.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=pJ[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},c=(void 0===l?pG:pX).find(e=>r.has(e)||i.has(e));if(c)return{error:{code:"cli-option-wrong-transport",params:{cli:"pi",option:`--${c}`,transport:void 0===l?"stdio":"http"}}};let d=new uZ("pi-mcp-add",!0);d.name=o.text,d.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=pH(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){d.transport="http",d.url=pB(l.parts,"pi",!1);let e=u("header");if("error"in e)return e;for(let[t,n]of e)d.headers.push([t,pB(n,"pi",!0)]);let t=a("bearer-token-env-var");if(void 0!==t){let e=["Authorization",[{kind:"pi",text:`Bearer \${${t.text}}`}]],n=d.headers.findIndex(e=>{let[t]=e;return"Authorization"===t});n>=0?d.headers[n]=e:d.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&&(d.oauth.clientId=pB(n.parts,"pi",!1)),r&&(d.oauth.clientSecret=pB(r.parts,"pi",!0)),i&&(d.oauth.callbackPort=Number(i.text)),o&&(d.oauth.clientName=pB(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{d.transport="stdio";let e=u("env");if("error"in e)return e;for(let[t,n]of e)d.env.push([t,pB(n,"pi",!0)]);let[t,...n]=s;d.command=pB(t.parts,"pi",!1),d.args=n.map(e=>pB(e.parts,"pi",!1));let r=a("cwd");r&&(d.cwd=pB(r.parts,"pi",!1)),p.command=t.text}let h=a("exposure");void 0!==h&&(p.exposure=h.text,d.exposure=pl(h.text)??h.text);let f=a("description");void 0!==f&&(p.description=f.text,d.description=f.text);let m=pp("server",p);return m?{note:{code:"invalid-config",params:{server:o.text,...m}}}:{draft:d}}(t,i.slice(1)));if("claude"===r&&"add"===e)return pV(function(e){let t=pQ("claude",e,p6,{asArgAfter:2,variadic:p9});if("error"in t)return{error:t.error};let n=new uZ("claude-mcp-add",!1),r=p5(n,"claude",t.values.get("transport"),[...t.positional,...t.afterDashDash],u$);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=p3(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=p8(n,t.lists.get("header"),u$,"claude");if(r)return{error:r};let s=t.values.get("client-id");s&&!0!==s&&(n.oauth.clientId=pB(s.parts,u$,!1)),t.values.has("client-secret")&&p7(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=p4(n,t.lists.get("env"),u$,"claude");if(e)return{error:e}}return{draft:n}}(t));if("claude"===r&&"add-json"===e)return pV(function(e){let t=pQ("claude",e,he,{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=ht(r);if("error"in o)return o;let s=pz(n.text,o.value,{source:"claude-mcp-add-json",flavor:"mcp-servers",rawPi:!1});return"note"in s||(s.draft.scopeHint=p3(t.values.get("scope")),t.values.has("client-secret")&&"http"===s.draft.transport&&!s.draft.oauth.clientSecret&&p7(s.draft)),s}(t));if("claude"===r&&"add-from-claude-desktop"===e)return{error:{code:"claude-desktop-import"}};if("codex"===r&&"add"===e)return pV(function(e){let t=pQ("codex",e,hn,{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 uZ("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!==pM(l.text))return{note:pR(i.text,l.text)};a.transport="http",a.url=pB(l.parts,uE,!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=pB(n.parts,uE,!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=p4(a,r,uE,"codex");if(e)return{error:e};a.command=pB(s[0].parts,uE,!1),a.args=s.slice(1).map(e=>pB(e.parts,uE,!1))}return{draft:a}}(t));if("gemini"===r&&"add"===e)return pV(function(e){let t=pQ("gemini",e,hr,{asArgAfter:2});if("error"in t)return{error:t.error};let n=new uZ("gemini-mcp-add",!1),r=p5(n,"gemini",t.values.get("transport"),[...t.positional,...t.afterDashDash],uI);if("string"!=typeof r)return"cli-usage"===r.code?{error:r}:{note:r};if(n.scopeHint=p3(t.values.get("scope")),"http"===r){t.lists.has("env")&&n.note("cli-option-wrong-transport",{cli:"gemini",option:"--env",transport:"http"});let e=p8(n,t.lists.get("header"),uI,"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=p4(n,t.lists.get("env"),uI,"gemini");if(e)return{error:e}}let i=t.values.get("timeout");for(let e of(i&&!0!==i&&pt(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 pW(n,o("include-tools"),o("exclude-tools")),{draft:n}}(t));if("add"===e||"install"===e)return{error:{code:"cli-unsupported",params:{cli:r}}};if(pq.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]&&pZ.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=p0(e[n],10)}if(!r)return{error:{code:"cli-option-needs-value",params:{cli:"code",option:"--add-mcp"}}};let o=ht(r);if("error"in o)return o;t.push(pz(void 0,o.value,{source:"vscode-add-mcp",flavor:"vscode",rawPi:!1}))}return{entries:t,notes:[]}}(e.slice(1)):pV(function(e){let t=new uZ("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,pB(r.value,uE,!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=pB(i.parts,uE,!1),t.args=e.slice(n+1).map(e=>pB(e.parts,uE,!1));let o=e.slice(n+1).map(e=>e.text),s=o.some(e=>/^mcp-remote(?:@|$)/.test(e))?o.find(e=>p_.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:hx[t],params:n}:{code:hx[t]}}(e.error)}}if("error"in o)return{ok:!1,notes:[o.error]};let a=[...o.notes],c=[],d=[...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 uG(e);if("stdio"===e.transport&&e.command&&""!==uV(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||""===uV(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:c,clientRegistration:d,callbackUrl:u,scope:p,authServerMetadataUrl:h}=e.oauth;s&&(o.clientId=n.encode(["oauth","clientId"],s)),l&&(o.clientSecret=n.encode(["oauth","clientSecret"],l)),void 0!==a&&(o.callbackPort=a),c&&(o.clientName=n.encode(["oauth","clientName"],c)),d&&(o.clientRegistration=d),u&&(o.callbackUrl=n.encode(["oauth","callbackUrl"],u)),p&&(o.scope=n.encode(["oauth","scope"],p)),h&&(o.authServerMetadataUrl=n.encode(["oauth","authServerMetadataUrl"],h)),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 u6(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&&u6(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=u7(t,new Set(["-p","--package","-c","--call"]));return e?u4(e):""}case"pnpm":case"yarn":case"bun":case"npm":{let e=t.findIndex(e=>"dlx"===e||"exec"===e||"x"===e),n=e>=0?u7(t.slice(e+1),new Set(["-p","--package"])):void 0;return n?u4(n):""}case"uvx":case"pipx":{let e=u7("pipx"===n&&"run"===t[0]?t.slice(1):t,new Set(["--from","--with","--python","-p","--index-url","--spec"]));return e?u4(e):""}case"uv":{let e=t.indexOf("run"),n=e>=0?u7(t.slice(e+1),new Set(["--with","--directory","--python","-p","--from","--project"])):void 0;return n?pe(n):""}case"docker":case"podman":{let e=t.indexOf("run"),n=e>=0?u7(t.slice(e+1),u9):void 0;if(!n)return"";let r=n.split("/").pop().replace(/[:@].*$/,"");return u3(r)||r}case"python":case"python3":case"py":{let e=t.indexOf("-m");if(e>=0&&t[e+1])return u4(t[e+1].replace(/_/g,"-"));let n=u7(t,new Set(["-X","-W"]));return n?pe(n):""}case"node":case"deno":case"tsx":case"ts-node":{let e=u7("deno"===n&&"run"===t[0]?t.slice(1):t,new Set(["-r","--require","--import","--loader"]));return e?pe(e):""}default:return u3(n.replace(/_/g,"-"))||n}}(e.command,t)}(r.config))&&r.notes.push({code:"name-derived",params:{name:i}});let s=(t=i,u0.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=u1(s,o?[...d,...u]:u);l!==s&&(r.notes.push({code:"name-deduplicated",params:{original:s,name:l}}),s=l),!o&&d.includes(s)&&r.notes.push({code:"name-taken",params:{name:s,suggestedName:u1(s,[...d,...u])}}),r.name=s;let p=pp(s,function(e){let t=hv(e),n=JSON.parse(JSON.stringify(e.config));t.has(uH(["url"]))&&(n.url="https://placeholder.invalid/");let r=n.oauth;return r&&t.has(uH(["oauth","callbackUrl"]))&&delete r.callbackUrl,n}(r));if(p){a.push({code:"invalid-config",params:{server:s,...p}});continue}!function(e){let t=hv(e);for(let n of hE(e.config))t.has(uH(n))||e.notes.push({code:"literal-secret",params:{field:u_(n)}});let n=e.config;if("url"in n){for(let[t,r]of Object.entries(n.headers??{})){let n=uW(r);n.length>0&&e.notes.push({code:"header-env-reference",params:{header:t,names:n.join(", ")}})}let t=uW(n.oauth?.clientSecret??"");t.length>0&&e.notes.push({code:"client-secret-env-reference",params:{names:t.join(", ")}})}}(r),u.add(s),c.push(r)}return 0===c.length?{ok:!1,notes:a.length>0?a:[{code:"no-servers-found"}]}:{ok:!0,servers:c,notes:a}}let hy=/^[A-Za-z_][A-Za-z0-9_]*$/;function hj(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 hk(e){let t=hv(e);return hE(e.config).filter(e=>uU(e)&&!t.has(uH(e)))}function hw(e){return"string"==typeof e&&""===e.trim()?"missing":"name"}let hS=/^(?:bearer|basic|token)\s+/i;function hC(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(hk(e).map(e=>[u_(e),e])),l=[];for(let[e,t]of Object.entries(n)){let n="string"==typeof t?t.trim():"",r=s.get(e);r?hy.test(n)?l.push([r,n]):o.push({code:"field-reference-invalid",params:{field:e,problem:hw(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():"";hy.test(r)?"select"!==n.kind&&n.targets.every(e=>uU(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:hw(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,c=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(u_(e.path));let o=uH(e.path);if(c.has(o))continue;if(c.add(o),e.parts.some(e=>"string"!=typeof e&&void 0===i.get(e.field))){hj(r,e.path,void 0);continue}let s="";for(let t of e.parts){var d,u,p,h;s+="string"==typeof t?t:(d=i.get(t.field),u=e.path,p=""===s,h=e.encoding,"reference"in d?`\${${d.reference}}`:"uri-component"===h?encodeURIComponent(d.text):uU(u)?uz(d.text,{atStart:p}):d.text)}hj(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(hS)?.[0]??"":"";hj(r,e,`${i}\${${t}}`)}for(let e of hE(r))a.add(u_(e));return{ok:!0,config:r,secretPaths:[...a]}}let hN=["command","args","env","cwd","url","headers","oauth"];function hE(e){let t=[];for(let n of function(e){if(!uw(e))return[];let t=[];for(let n of["env","headers"]){let r=e[n];if(uw(r))for(let[e,i]of Object.entries(r))"string"==typeof i&&uS(i)&&""!==i&&(ue(e)||/^(?:bearer|basic|token)\s+\S/i.test(i)||uv(i,uc).masked)&&t.push({kind:"env"===n?"env":"header",name:e})}let n=uw(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&""!==n&&uS(n)&&t.push({kind:"oauth-client-secret"}),"string"==typeof e.url&&um(e.url,up).masked&&t.push({kind:"url"}),"string"==typeof e.command&&uv(e.command,up).masked&&t.push({kind:"command"}),Array.isArray(e.args)&&uk(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:""):[];uk(n).args.forEach((e,r)=>{e!==n[r]&&t.push(["args",r])})}}return t.sort((e,t)=>hN.indexOf(e[0])-hN.indexOf(t[0]))}let h$="PI_WEB_PASSWORD";function hI(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function hT(e){return hI(e)?Object.entries(e).filter(e=>"string"==typeof e[1]):[]}function hM(e){if(!hI(e))return[];if(!("url"in e))return hT(e.env).map(e=>{let[t,n]=e;return{kind:"env",name:t,value:n}});let t=hT(e.headers).map(e=>{let[t,n]=e;return{kind:"header",name:t,value:n}}),n=hI(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&t.push({kind:"oauth-client-secret",value:n}),t}let hR={text:"",rawPi:!1,server:0,values:{},references:{},secretReferences:{}};function hL(e,t,n){let r=hb(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 hA(e,t){let n={...e,...t},r=hL(e.text,e.rawPi,e.server);if(void 0!==r&&r===hL(n.text,n.rawPi,e.server))return n;let i={...n,server:0,values:{},references:{},secretReferences:{}};return delete i.name,i}function hz(e){return uN[e.code]??"warning"}function hP(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?cY(t):t;if("string"==typeof i.field&&e.code.startsWith("field-")){let e=r.find(e=>e.id===i.field);e&&(o.field=cY(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 hW={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"},hO={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"},hF=JSON.stringify({command:"uvx",args:["mcp-server-fetch"]}),hD=JSON.stringify({name:"fetch",command:"uvx",args:["mcp-server-fetch"]}),hB=[{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 '${hD}'`},{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(hF)}`},{source:"vscode-install-link",text:`vscode:mcp/install?${encodeURIComponent(hD)}`},{source:"visual-studio-install-link",text:`vsweb+mcp:/install?${encodeURIComponent(hD)}`},{source:"copilot-app-install-link",text:`ghapp://mcp/install?${encodeURIComponent(hD)}`}];function hH(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?cY(r):r.field===e.id?n:`‹${cY(t.find(e=>{let{id:t}=e;return t===r.field})?.label??r.field)}›`).join("")}))].join(", ")}function h_(e){return"select"!==e.kind&&e.targets.every(e=>uU(e.path)&&void 0===e.encoding)}let hU=/^[A-Za-z_][A-Za-z0-9_]*$/;function hK(){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 hU.test(r)?r:void 0}let hq=/^(?:proxy-)?authorization$/i;function hZ(e,t){let n=function(e,t){if(e.startsWith("env.")){let t=e.slice(4);return hU.test(t)?t:hK(t)}let n=function(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];return hK(t,...n)??hK(...n)};if(e.startsWith("headers.")){let t=e.slice(8);return n(hq.test(t)?"TOKEN":t.replace(/^x-/i,""))}if("oauth.clientSecret"===e)return n("CLIENT_SECRET")}(e,t);return n===h$?void 0:n}function hV(e){return e.startsWith("env.")||e.startsWith("headers.")||"oauth.clientSecret"===e}function hJ(e,t){let n=e;for(let e of t)n=n.split(e).join(d2);return{text:n,masked:n!==e}}function hY(e){let{kind:t,name:n}=e;return void 0===n?{kind:t}:{kind:t,name:n}}function hG(e,t){let n=t.files.find(t=>t.scope===e),r=n?.problems.find(dg);return n&&r?{kind:"file-problem",path:n.path,reason:r.reason}:void 0}function hX(e,t){return e.servers.filter(e=>e.scope===t).map(e=>e.name)}function hQ(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 h0(e,t,n){switch(e.kind){case"trust-too-broad":return t(h2[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(h1[e.kind])}}let h1={"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"},h2={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 h4(e){return cY(cs(e))}function h8(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}let h3=[{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"}],h5=new Set(["name-derived","name-sanitized","name-deduplicated","name-taken"]);function h6(e){let{notes:t,fields:n=[]}=e,{t:i}=(0,eh.s)();if(0===t.length)return null;let o={error:0,warning:1,info:2},s=[...t].sort((e,t)=>o[hz(e)]-o[hz(t)]);return(0,r.jsx)("ul",{className:"mcp-add-notes",children:s.map((e,t)=>(0,r.jsx)("li",{className:`mcp-add-note is-${hz(e)}`,children:hP(e,i,n)},`${t}\0${e.code}`))})}let h9={"server-invalid":"mcp.add.refused.server-invalid","web-password":"mcp.add.blocked.web-password"};function h7(e){let{data:t,cwd:n,draft:o,busy:s,controlsBusy:l,failure:a,onDraftChange:c,onSubmit:d,onTrustProject:u}=e,{t:p}=(0,eh.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:dy(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=>hb(t.text,{rawPi:t.rawPi,takenNames:hX(n,e)}),l=s(t.scope??"global"),a=l.ok?l.servers[Math.min(t.server,l.servers.length-1)]:void 0,c=t.scope??(a?.scopeHint==="project"&&"write"===o.kind?"project":"global");c!==(t.scope??"global")&&(a=(l=s(c)).ok?l.servers[Math.min(t.server,l.servers.length-1)]:void 0);let d={parsed:l,name:t.name??"",scope:c,projectMode:o,..."blocked"===o.kind?{projectBlock:o.block}:{},values:{},pasteSecrets:[],secretReferences:{},fieldProblems:{},secretPaths:[],trustFolder:!1},u=dD(n.mcp);if(!a)return{...d,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&&h_(r)?n[r.id]={reference:e}:void 0!==t.values[r.id]&&(n[r.id]=t.values[r.id])}return n}(a,t),f=hk(a).map(u_),m=Object.fromEntries(f.flatMap(e=>{let n=t.secretReferences[e];return void 0===n?[]:[[e,n]]})),g=hC(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]=hU.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=hC(e,r,Object.fromEntries(Object.entries(n).map(e=>{let[t,n]=e;return[t,hU.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:hM(r).filter(e=>{let{value:t}=e;return uP(t)}).map(hY),variableReferences:hM(r).map(e=>({...hY(e),variables:uW(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=hJ(r.url,i);return{...s,transport:"http",target:cY(e.text),envNames:[],headerNames:Object.keys(r.headers??{}),masked:e.masked}}let l=hJ(cQ(r.command,r.args??[]),i);return{...s,transport:"stdio",target:l.text,...void 0!==r.cwd?{cwd:cY(r.cwd)}:{},envNames:Object.keys(r.env??{}),headerNames:[],masked:l.masked}}(a,h,g),y=g.ok?pp(p,g.config):void 0,j="blocked"===o.kind?o.block:v.length>0?{kind:"secret",fields:v,fixed:!v.every(hV)}:hG("project",n),k=hX(n,c),w=n.files.find(e=>e.scope===c);if(u)i={kind:"mcp-off"};else if(u0.test(p))if(k.includes(p))i={kind:"name-taken",name:p,suggestedName:u1(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 hM(e))if(t.isCommandConfigValue(n)?n.toUpperCase().includes(h$):t.getConfigValueEnvVarNames(n).some(e=>e.toUpperCase()===h$))return r}(g.config,{isCommandConfigValue:uP,getConfigValueEnvVarNames:uW}))i={kind:"web-password"};else if("project"===c&&j)i={kind:"scope",block:j};else{let e=hG(c,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"===c&&j?e({...t,scope:"global"},n,r):{parsed:l,server:a,name:p,scope:c,projectMode:o,...j?{projectBlock:j}:{},values:h,pasteSecrets:f,secretReferences:m,fill:g,fieldProblems:x,secretPaths:v,preview:b,...i?{submitBlock:i}:{},trustFolder:"project"===c&&"trust-and-write"===o.kind}})(o,t,n),[o,t,n]),g=(0,i.useMemo)(()=>(function(e){let t=hb(e,{rawPi:!0});if(!t.ok)return!1;let n=hb(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=>h5.has(e.code)),S=k.filter(e=>!h5.has(e.code)),C=!s&&!l&&void 0===j,N=()=>{C&&d(hQ(o,m))},E=e=>c({...o,...e}),$=t.files.find(e=>e.scope===m.scope)?.path??("project"===m.scope&&n?`${n.replace(/[\\/]+$/,"")}/.pi/mcp.json`:"mcp.json"),I=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:cY(e.name),path:e.path?h4(e.path):"mcp.json"});case"fields":return t("mcp.add.blocked.fields",{fields:e.fields.map(cY).join(", ")});case"field-invalid":return t("mcp.add.blocked.fieldsInvalid",{fields:e.fields.map(cY).join(", ")});case"config-invalid":return hP(e.note,t,n);case"web-password":return t("mcp.add.blocked.web-password");case"scope":return h0(e.block,t,h4)}}(j,p,v?.fields):void 0,T=y?.kind==="project-untrusted"&&y.trustable&&u,M=b?"http"===b.transport?b.headerNames:b.envNames:[];return(0,r.jsxs)(ax,{title:p("mcp.add.title"),catalogs:h3,target:(0,r.jsxs)(am,{value:m.scope,label:p("config.saveTo"),options:[{value:"global",label:h8("global",p)},{value:"project",label:h8("project",p),disabled:void 0!==y&&"project"!==m.scope}],path:h4($),disabledReason:y?h0(y,p,h4):null,onChange:e=>E({scope:e}),children:[T&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aS,{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:h4(m.projectMode.folder)})})]}),inputLabel:p("mcp.add.inputLabel"),inputId:"mcp-add-source",placeholder:p("mcp.add.placeholder"),value:o.text,canSubmit:C,onValueChange:e=>c(hA(o,{text:e})),onSubmit:N,examplesLabel:p("mcp.add.examples"),examples:""===o.text.trim()?hB.map(e=>{let{source:t,text:n}=e;return{label:p(hO[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=>c(hA(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)(h6,{notes:x.notes}),x.ok&&x.servers.length>1&&(0,r.jsxs)(ad,{label:p("mcp.add.serverLabel"),children:[(0,r.jsx)("select",{className:"mcp-add-input","aria-label":p("mcp.add.serverLabel"),value:String(x.servers.indexOf(v??x.servers[0])),onChange:e=>E({server:Number(e.target.value),name:void 0,values:{},references:{},secretReferences:{}}),children:x.servers.map((e,t)=>(0,r.jsx)("option",{value:t,children:cY(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)(ad,{label:p("config.name"),children:(0,r.jsx)("input",{id:f,className:"mcp-add-input","aria-label":p("config.name"),value:m.name,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>E({name:e.target.value})})}),(0,r.jsx)(h6,{notes:w,fields:v.fields}),j?.kind==="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aS,{size:"small",onClick:()=>E({name:j.suggestedName}),children:p("mcp.add.useName",{name:cY(j.suggestedName)})})})]}),v&&b&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ac,{children:p("mcp.add.preview")}),(0,r.jsxs)(au,{children:[(0,r.jsx)(ap,{label:p("mcp.add.readAs"),children:p(hO[b.source])}),(0,r.jsx)(ap,{label:p("mcp.detail.transport"),children:p(`mcp.transport.${b.transport}`)}),(0,r.jsx)(ap,{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)(ap,{label:p("mcp.detail.cwd"),mono:!0,children:b.cwd}),M.length>0&&(0,r.jsx)(ap,{label:"http"===b.transport?p("mcp.detail.headers"):p("mcp.detail.env"),children:(0,r.jsx)(fe,{names:M})}),b.commandFields.length>0&&(0,r.jsx)(ap,{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=c2(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)(ap,{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:c3(b.variableReferences).map(e=>{let{variable:t,field:n}=e,i=c2(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p("mcp.server.variableIn",{variable:cY(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)(h6,{notes:S,fields:v.fields}),v.fields.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ac,{children:p("mcp.add.fields")}),v.fields.map(e=>{var t;let n;return(0,r.jsx)(ft,{field:e,fields:v.fields,draft:o,suggestedName:(t=m.name,(n=e.targets[0])?hZ(u_(n.path),t):void 0),problem:m.fieldProblems[e.id],onDraftChange:c},e.id)})]}),m.pasteSecrets.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ac,{children:p("mcp.add.secrets")}),m.pasteSecrets.map(e=>{var t,n;let i;return(0,r.jsx)(fn,{label:e,draft:o,suggestedName:hZ(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)&&uc(i)?i:void 0):void 0,problem:m.fieldProblems[e],onDraftChange:c},e)})]})]}),(0,r.jsx)(aS,{variant:"primary",className:"is-pushed-right",disabled:!C,"aria-busy":s||void 0,"aria-describedby":I?h:void 0,onClick:N,children:s?p("mcp.add.adding"):m.trustFolder?p("mcp.add.buttonTrust"):p("mcp.add.button")}),I&&(0,r.jsx)("p",{id:h,className:`mcp-config-line ${j?.kind==="scope"?"is-warning":"is-dim"}`,children:I}),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(h2[e.breadth.kind],{path:h4(e.breadth.path)});if("secret-global-only"===e.reason&&e.fields)return t(e.fields.every(hV)?"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:cY(e.name),path:e.path?h4(e.path):"mcp.json"});let n=e.reason?h9[e.reason]:void 0;return n?t(n,{error:cY(e.error)}):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):cY(e.error)}(a,p)]}),a.trustKept&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.trustKept",{folder:h4(a.trust?.decisionPath??n??"")})}),a.notes&&a.notes.length>0&&(0,r.jsx)(h6,{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)(aS,{size:"small",onClick:()=>E({name:a.suggestedName}),children:p("mcp.add.useName",{name:cY(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(cY).join(", ")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aS,{variant:"danger",size:"small",disabled:s||l||void 0!==j,onClick:()=>d(hQ(o,m,a.names)),children:p("mcp.add.hostEnv.confirm")})})]})]})]})}function fe(e){let{names:t}=e,{t:n}=(0,eh.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:cY(e)},e))}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.detail.valuesHidden")})]})}function ft(e){let t,{field:n,fields:o,draft:s,suggestedName:l,problem:a,onDraftChange:c}=e,{t:d}=(0,eh.s)(),u=(0,i.useId)(),p=a?{"aria-invalid":!0,"aria-describedby":u}:{},h=h_(n),f=h?s.references[n.id]:void 0,m=void 0!==f,g=cY(n.label),x=s.values[n.id]??n.defaultValue??"",v=hW[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?hH(n,o,"${"+f+"}",!0):void 0:hH(n,o,`‹${d("mcp.add.field.slot")}›`),j=e=>c({...s,values:{...s.values,[n.id]:e}}),k=e=>{let t={...s.references};void 0===e?delete t[n.id]:t[n.id]=e,c({...s,references:t})};return(0,r.jsxs)("div",{className:"mcp-add-field",children:[(0,r.jsx)(ad,{label:g,children:m?(0,r.jsx)("input",{className:"mcp-add-input","aria-label":d("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:d("mcp.add.field.choose")}),(n.options??[]).map(e=>(0,r.jsx)("option",{value:e,children:cY(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?cY(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:hP(a,d,[n])}),(0,r.jsxs)("span",{className:"mcp-config-lines",children:[n.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:cY(n.description)}),v&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:d(v)}),m?(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:y?d("mcp.add.field.storedAsVariable",{value:y}):d("mcp.add.field.variableHint")}):(0,r.jsxs)(r.Fragment,{children:[y&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:d("mcp.add.field.storedAs",{value:y})}),n.optional&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:b?d("mcp.add.field.optionalHeader",{name:cY(b)}):d("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:d("mcp.add.field.useVariable")})]})]})}function fn(e){let{label:t,draft:n,suggestedName:o,stored:s,problem:l,onDraftChange:a}=e,{t:c}=(0,eh.s)(),d=(0,i.useId)(),u=n.secretReferences[t],p=void 0!==u,h=cY(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})," ",c("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:c("mcp.add.field.useVariable")})]}),p&&(0,r.jsx)(ad,{label:c("mcp.add.field.variableName",{field:h}),children:(0,r.jsx)("input",{className:"mcp-add-input","aria-label":c("mcp.add.field.variableName",{field:h}),value:u,placeholder:o??"API_TOKEN",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...l?{"aria-invalid":!0,"aria-describedby":d}:{},onChange:e=>f(e.target.value)})}),l&&(0,r.jsx)("span",{id:d,className:"mcp-config-line is-error",children:hP(l,c)}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p?void 0!==s?c("mcp.add.secret.storedAs",{value:cY(s)}):c("mcp.add.field.variableHint"):c("mcp.add.secret.asPasted")})]})}let fr=new Set(["done","failed","cancelled","expired"]);function fi(e){var t;return e?.flow!==void 0&&!e.gone&&(t=e.flow.phase,!fr.has(t))}let fo={"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"},fs={"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"},fl={connecting:"mcp.signIn.phase.connecting",starting:"mcp.signIn.phase.starting",finishing:"mcp.signIn.phase.finishing"},fa={"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 fc(e,t,n){var r;let i={...e,flow:t,deadlineAt:n+t.expiresInMs,gone:!1};return r=t.phase,fr.has(r)&&(delete i.pasteError,delete i.cancelError,i.pasting&&(i.pasting=!1),i.cancelling&&(i.cancelling=!1)),i}function fd(e){return"sign-in-unknown"===e.reason}async function fu(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:d$(s,o.status)}}function fp(e,t,n,r,i){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},s=t.method??"GET";return dI(r=>fu(e,t,n,r),()=>({ok:!1,error:{error:`${s} ${e} did not answer within ${i} ms`,timedOut:!0}}),i,r,o)}function fh(e){return`/api/mcp/sign-in/${encodeURIComponent(e)}`}function ff(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?fs[e.reason]:void 0;return r?t(r):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function fm(e){let{server:t,run:n,block:o,signOutBlock:s,controlsBusy:l,signingOut:a,onSignIn:c,onSignOut:d,onPaste:u,onCancel:p}=e,{t:h}=(0,eh.s)(),f=(0,i.useId)(),m=(0,i.useId)(),g=(0,i.useId)(),x=(0,i.useRef)(null),v=(0,i.useRef)(null),b=fi(n),y=(0,i.useRef)(b);if((0,i.useEffect)(()=>{let e=y.current;y.current=b,!e&&b?ep(document,v.current):e&&!b&&ep(document,x.current)},[b]),!t.usesOAuth)return(0,r.jsx)(ap,{label:h("mcp.detail.signIn"),children:void 0!==t.authProvider?h("mcp.signIn.provider",{provider:cY(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,E=j?.phase==="finishing";return(0,r.jsx)(ap,{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:cY(j.name)})}),j&&b&&("authorize"===j.phase?(0,r.jsx)(fg,{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(fl[j.phase]??"mcp.signIn.phase.connecting")})),j&&b&&E&&(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)(fx,{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")," ",ff(n.error,h)]}),b&&n?.cancelError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.cancelFailed")," ",ff(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")," ",ff(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(fo[o])}),!o&&s&&S&&!b&&(0,r.jsx)("span",{id:m,className:"mcp-config-line is-dim",children:h(fo[s])}),(0,r.jsxs)("div",{className:"mcp-sign-in-actions",children:[b&&j?(0,r.jsx)(aS,{ref:v,size:"small",disabled:n?.cancelling===!0||E,"aria-busy":n?.cancelling===!0||void 0,"aria-describedby":E?g:void 0,onClick:()=>p(t,j.flowId),children:h(n?.cancelling?"mcp.signIn.cancelling":"mcp.signIn.cancel")}):(0,r.jsx)(aS,{ref:x,size:"small",variant:"primary",disabled:C,"aria-busy":k||void 0,"aria-describedby":o?f:void 0,onClick:()=>c(t),children:h(k?"mcp.signIn.starting":"mcp.signIn.button")}),S&&!b&&(0,r.jsx)(aS,{size:"small",disabled:N,"aria-busy":a||void 0,"aria-describedby":s?o?f:m:void 0,onClick:()=>d(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 fg(e){let{flow:t,pasting:n,pasteError:o,onPaste:s}=e,{t:l}=(0,eh.s)(),[a,c]=(0,i.useState)(""),d=(0,i.useRef)(null),u=(0,i.useRef)(n);(0,i.useEffect)(()=>{let e=u.current;u.current=n,e&&!n&&ep(document,d.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)(aO,{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:cY(p)})]}):(0,r.jsxs)(r.Fragment,{children:[l("mcp.signIn.authorize.notALink")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:cY(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:d,onValueChange:c,onSubmit:()=>s(a)}),o&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[l("mcp.signIn.paste.refused")," ",ff(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:cY(o.error)})]})]}),t.redirectUrl&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:l("mcp.signIn.authorize.redirect",{url:cY(t.redirectUrl)})}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:l("mcp.signIn.authorize.wait")})]})}function fx(e){let{flow:t,shared:n}=e,{t:i}=(0,eh.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 fa[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:cY(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:cY(t.error)})]})]})}function fv(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function fb(e){return cY(cs(e))}function fy(e,t){let{key:n,params:r}=e;return r?t(n,void 0===r.path?r:{...r,path:fb(r.path)}):t(n)}function fj(e,t){return e.timedOut?t("mcp.loadTimedOut"):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function fk(e,t){return e.timedOut?t("mcp.actionTimedOut"):fj(e,t)}function fw(){if("u"<typeof document)return null;let e=document.activeElement;return e instanceof HTMLButtonElement||e instanceof HTMLSelectElement?e:null}function fS(e){let{cwd:t,onClose:n,embedded:o=!1,trust:s,onTrustProject:l,onProjectTrustChanged:a}=e,[c,d]=(0,i.useState)({state:"loading"}),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(()=>lG("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,N]=(0,i.useState)(null),[E,$]=(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),[A,z]=(0,i.useState)({}),P=(0,i.useRef)(A);P.current=A;let[W,O]=(0,i.useState)(0),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)(hR),_=(0,i.useRef)(B);_.current=B;let[U,K]=(0,i.useState)(null),[q,Z]=(0,i.useState)(null),V=(0,i.useRef)(!0),J=(0,i.useRef)(c);J.current=c;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 dA(t,void 0,n.signal);if(e===I.current){if(p(!1),!r.ok)return void d({state:"failed",error:r.error});d({state:"loaded",data:r.data,...r.projectError?{projectError:r.projectError}:{}}),f(e=>db(dx(r.data,!!t),e))}},[t]),G=cc(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 dW(e,void 0,t.signal);M.current===t&&(M.current=null,g({saving:!1,error:n.ok?null:n.error,target:"preference"}),n.ok&&d(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 dO(e,void 0,t.signal);M.current===t&&(M.current=null,g({saving:!1,error:n.ok?null:n.error,target:"mode"}),n.ok&&d(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 dF(e,void 0,t.signal);M.current===t&&(M.current=null,g({saving:!1,error:n.ok?null:n.error,target:"inlineBudget"}),n.ok&&d(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=c9(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 d1({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=>c9(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),d(t=>({state:"loaded",data:e,..."loaded"===t.state&&t.projectError?{projectError:t.projectError}:{}})),f(r=>db(dx(e,!!t),n??r))},[t]),er=(0,i.useCallback)(async e=>{let n=c9(e),r=P.current[n];if(r?.starting||fi(r))return;z(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 fp("/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&&(z(e=>({...e,[n]:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();return e.ok?fc({},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=c9(e);z(e=>e[r]?.flow?.flowId===t?{...e,[r]:{...e[r],pasting:!0,pasteError:void 0}}:e);let i=await function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(e,t)=>fetch(e,t),r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:15e3;return fp(fh(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirectUrl:t})},n,r,i)}(t,n);V.current&&z(e=>{let n=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Date.now();if(!e?.flow||e.flow.flowId!==t)return e;let i={...e,pasting:!1,version:(e.version??0)+1};return n.ok?{...fc(i,n.data,r),pasteError:void 0}:fd(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=c9(e);z(e=>e[n]?.flow?.flowId===t?{...e,[n]:{...e[n],cancelling:!0}}:e);let r=await function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return fp(fh(e),{method:"DELETE"},t,n,r)}(t);V.current&&z(e=>{let i=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Date.now();if(!e?.flow||e.flow.flowId!==t)return e;let i={...e,cancelling:!1,cancelError:void 0,version:(e.version??0)+1};return n.ok?fc(i,n.data,r):fd(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(A).flatMap(e=>{let[t,n]=e;return fi(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=P.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 fp(fh(e),{},t,n,r)}(r,void 0,e.signal);if(e.signal.aborted)return;z(e=>{let t=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Date.now(),i=arguments.length>4?arguments[4]:void 0;return e?.flow&&e.flow.flowId===t&&(void 0===i||(e.version??0)===i)?n.ok?fc(e,n.data,r):fd(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,W]);let el=(0,i.useRef)(A);(0,i.useEffect)(()=>{let e=el.current;el.current=A,Object.keys(A).some(t=>{var n,r;return n=e[t],r=A[t],fi(n)&&!fi(r)})&&Y()},[A,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 dq(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]),ec=(0,i.useCallback)(async(e,t)=>{let n=c9(e),r=fw();y(null),k(null);let i=await ea({action:t?"enable":"disable",scope:e.scope,name:e.name},`switch:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[ea]),ed=(0,i.useCallback)(async(e,t)=>{let n=c9(e),r=fw();y(null),k(null);let i=await ea({action:"set-in-project",name:e.name,enabled:t},`in-project:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[ea]),eu=(0,i.useCallback)(async(e,t)=>{let n=c9(e),r=fw();y(null),k(null);let i=await ea({action:"set-exposure",scope:e.scope,name:e.name,exposure:t},`exposure:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[ea]),ep=(0,i.useCallback)(async e=>{let t=c9(e),n=fw();y(null),k(null);let r=await ea({action:"remove",scope:e.scope,name:e.name},`remove:${t}`);if(!r)return;if(!r.ok){y({key:t,failure:r.error}),N({control:n});return}let i=r.data.undo;i&&S({...i,undoing:!1})},[ea]),eh=(0,i.useCallback)(async()=>{if(!w)return;let e=fw();y(null),k(null),S({...w,undoing:!0,error:void 0});let t=await ea({action:"undo",token:w.token},"undo",e=>e.restored?c9(e.restored):void 0);t&&(S(e=>e?.token!==w.token?e:t.ok?null:{...e,undoing:!1,error:t.error}),t.ok||N({control:e}))},[ea,w]),ef=(0,i.useCallback)(async e=>{let t=c9(e),n=fw();y(null),k(null),z(e=>({...e,[t]:{...e[t],signOutError:void 0,signedOut:void 0}}));let r=await ea({action:"sign-out",scope:e.scope,name:e.name},`sign-out:${t}`);if(r){if(z(e=>({...e,[t]:r.ok?{signedOut:{removed:r.data.signedOut?.removed===!0}}:{...e[t],signOutError:r.error}})),r.ok){let e=Date.now();$(n=>{let r=function(e,t){if(e)return{running:e.running,...void 0!==e.startedAt?{startedAt:e.startedAt}:{},signedOutAt:t}}(n[t],e);return r?{...n,[t]:r}:n})}N({control:n})}},[ea]),em=(0,i.useCallback)(async e=>{let n=fw(),r=_.current;y(null),k(null),K(null);let i=await ea(e,"add",e=>e.added?c9(e.added):void 0);if(!i)return;let o=_.current!==r;if(!i.ok){o||K(i.error),i.error.trust&&t&&a?.(t,i.error.trust),N({control:n});return}let{added:s,trust:l,trustedFolder:c}=i.data;if(D(!1),o||H(hR),N({control:null,toSelectedRow:!0}),!s)return;Z({...s,key:c9(s),...c&&t?{trustedFolder:t}:{}}),l&&t&&a?.(t,l);let d=i.data.servers.find(e=>c9(e)===c9(s));d&&!dV(d,i.data)&&et(d)},[t,a,ea,et]),eg=w?.token,ex=w?.expiresInMs;(0,i.useEffect)(()=>{if(void 0===eg||void 0===ex)return;let e=setTimeout(()=>S(e=>e?.token===eg?null:e),ex);return()=>clearTimeout(e)},[eg,ex]);let ev=(0,i.useCallback)(async(e,t,n)=>{let{targets:r,keptOff:i}={targets:ca(t,n,e=>e.enabled).filter(n?dU:d_),keptOff:n?t.filter(e=>!e.enabled&&d_(e)&&!dU(e)).length:0},o=fw();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(N({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&&lX("mcp",h,t)},[t,h]),(0,r.jsx)(fC,{cwd:t,load:c,selected:h,refreshing:u,embedded:o,codemodeSave:m,busy:x,actionError:b,groupStatus:j,undo:w,focusBack:C,tests:E,signIns:A,adding:F,addDraft:B,addFailure:U,added:q,onAddOpen:()=>{D(!0),Z(null),y(null)},onAddDraftChange:e=>{_.current=e,H(e),K(null)},onAddSubmit:e=>void em(e),onTest:e=>void et(e),onSignIn:e=>void er(e),onSignOut:e=>void ef(e),onSignInPaste:(e,t,n)=>void ei(e,t,n),onSignInCancel:(e,t)=>void eo(e,t),onSelect:e=>{f(e),y(null),D(!1),Z(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 ec(e,t),onServerSwitchInProject:(e,t)=>void ed(e,t),onExposureChange:(e,t)=>void eu(e,t),onGroupSwitch:(e,t,n)=>void ev(e,t,n),onRemove:e=>void ep(e),onUndo:()=>void eh(),onTrustProject:l,onClose:n})}function fC(e){var t,n,o,s;let l,a,c,{cwd:d,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=hR,addFailure:C=null,added:N=null,onAddOpen:E=()=>{},onAddDraftChange:$=()=>{},onAddSubmit:I=()=>{},onSelect:T,onRefresh:M,onCodemodeChange:R,onCodemodeModeChange:L=()=>{},onCodemodeInlineBudgetSave:A=()=>{},onServerSwitch:z=()=>{},onServerSwitchInProject:P=()=>{},onExposureChange:W=()=>{},onGroupSwitch:O=()=>{},onRemove:F=()=>{},onUndo:D=()=>{},onTest:B=()=>{},onSignIn:H=()=>{},onSignOut:_=()=>{},onSignInPaste:U=()=>{},onSignInCancel:K=()=>{},onTrustProject:q,onClose:Z}=e,{t:V}=(0,eh.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[c9(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?dx(G,!!d):[],Q=G?{mcpAvailable:G.mcp.available,projectServersLoad:c7(G.project)}:void 0,ee=X.flatMap(e=>e.servers),et=ee.find(e=>c9(e)===p),en=N?ee.find(e=>c9(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=q&&dy(G?.project)?q:void 0,ea=es?.kind==="untrusted"&&void 0!==el,ec=(0,i.useRef)(null),ed=(0,i.useRef)(null),eu=(0,i.useRef)(ea);(0,i.useEffect)(()=>{let e=eu.current;eu.current=ea,e&&!ea&&ep(document,ec.current??ed.current)},[ea]);let ef=(0,i.useRef)(null),em=b?.token,eg=(0,i.useRef)(em);(0,i.useEffect)(()=>{let e=eg.current;eg.current=em,void 0!==em&&em!==e?ep(document,ef.current):void 0!==e&&void 0===em&&ep(document,ec.current??ed.current)},[em]);let ex=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}))):[],ev=dv(ee),eb=G?.files.find(e=>"global"===e.scope),ey=G?function(e){let t=e.files.find(e=>"project"===e.scope);if(t?.autoEnableCodemode!==void 0&&c7(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,ej=G?(n=ee.length,o=G.files,n>0?"mcp.selectItem":o.some(e=>e.problems.some(dg))?"mcp.emptyFileProblem":"mcp.empty"):void 0,ek=null!==g||h||m.saving,ew=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(y&&!ek&&ew.current!==y)if(ew.current=y,y.toSelectedRow)ep(document,ec.current??ed.current);else{var e,t,n;e=document,t=y.control,n=ec.current??ed.current,t&&ep(e,t.isConnected&&!t.disabled?t:n)}},[y,ek]);let eS=e=>G?dB(e,G):void 0,eC=!!G&&dD(G.mcp),eN=X.find(e=>"project"===e.scope)?.servers??[],eE=eS("project"),e$=es?.kind==="untrusted"?[fy(es,V),eE&&"mcp-off"!==eE&&eN.length>0?V(dH[eE]):null].filter(Boolean).join(" "):"";return(0,r.jsxs)(l3,{embedded:f,title:V("settings.mcp"),subtitle:d?cs(d):void 0,closeLabel:V("i18n.close"),onClose:Z,children:[(0,r.jsxs)("div",{className:"mcp-config-notices",children:[er&&(0,r.jsxs)(av,{id:J,children:[fy(er,V),eC&&(0,r.jsxs)(r.Fragment,{children:[" ",V(dH["mcp-off"])]}),G&&!G.mcp.available&&G.mcp.detail&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:cY(G.mcp.detail)})]})]}),ei&&(0,r.jsx)(av,{children:V("mcp.hostInactive",{path:fb(ei.cwd),owner:fb(ei.owner)})}),"loaded"===u.state&&u.projectError&&(0,r.jsx)(av,{children:V("mcp.projectNotListed",{reason:fj(u.projectError,V)})}),es?.kind==="untrusted"&&(0,r.jsx)(ab,{id:Y,message:e$,trustLabel:V("mcp.trust.trustButton"),onTrust:el}),es?.kind==="inherited"&&(0,r.jsx)(av,{children:fy(es,V)}),b&&(0,r.jsxs)(av,{action:b.error?.reason==="undo-unavailable"?void 0:(0,r.jsx)(aS,{ref:ef,size:"small",onClick:D,disabled:b.undoing||ek,children:b.undoing?V("mcp.undoing"):V("mcp.undo")}),children:[V("mcp.removed",{name:cY(b.name),path:fb(b.path)}),b.error&&(0,r.jsxs)(r.Fragment,{children:[" ",V("mcp.undoFailed")," ",fk(b.error,V)]})]}),N&&G&&en&&(0,r.jsx)(fN,{added:N,cwd:d,server:en,testing:j[N.key]?.running===!0,signIn:k[N.key],signingOut:g===`sign-out:${N.key}`,signInBlock:en?dV(en,G):void 0,onSignIn:H})]}),(0,r.jsxs)(l5,{children:[(0,r.jsxs)(l6,{children:[(0,r.jsx)(l9,{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")," ",fj(u.error,V)]}):G&&Q?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-sidebar-group",children:(0,r.jsx)(fE,{codemode:G.codemode,active:!w&&p===c6,rowRef:ec,onSelect:T})}),X.map(e=>{let t=eS(e.scope);return(0,r.jsx)(f$,{group:e,context:Q,selected:w?null:p,selectedRowRef:ec,block:t,blockNoticeId:"mcp-off"===t?er?J:void 0:t&&es?.kind==="untrusted"?Y:void 0,busy:g,controlsBusy:ek,status:v?.scope===e.scope?v:null,onSelect:T,onGroupSwitch:O},e.scope)})]}):null}),G&&(0,r.jsx)(aN,{ref:ed,active:w,onClick:E,children:V("mcp.add.action")})]}),(0,r.jsx)(aj,{children:(0,r.jsx)(ai,{className:"is-fill",children:G&&Q&&ey&&ej?w?(0,r.jsx)(h7,{data:G,cwd:d,draft:S,busy:"add"===g,controlsBusy:ek,failure:C,onDraftChange:$,onSubmit:I,onTrustProject:el}):p===c6?(0,r.jsx)(fD,{codemode:G.codemode,autoEnable:ey,save:m,serverBusy:null!==g,onChange:R,onModeChange:L,onInlineBudgetSave:A}):et?(0,r.jsx)(fR,{server:et,context:Q,codemode:G.codemode,toolSearchDisabled:G.toolSearchDisabled,autoEnable:ey,block:eS(et.scope),inProject:function(e,t){if("global"!==e.scope||void 0!==e.invalidError||e.notAnObject||!c7(t.project))return;let n=t.files.find(e=>"project"===e.scope);if(!n||n.problems.some(e=>"auto-enable-codemode-invalid"!==e.reason))return;let r=t.servers.find(t=>"project"===t.scope&&t.name===e.name);return r?r.override?{kind:"override",key:c9(r),keys:r.override.keys,applies:!0===e.overriddenByProject}:void 0:{kind:"switch"}}(et,G),inProjectBlock:eS("project"),savedWhileOff:!G.mcp.available&&!eC,busy:g,controlsBusy:ek,actionError:x?.key===c9(et)?x.failure:null,test:(s=j[c9(et)],s&&void 0!==s.configKey&&s.configKey!==et.configKey?{running:s.running,...s.response?{response:s.response}:{}}:s),testBlock:dV(et,G),signIn:k[c9(et)],signInBlock:dV(et,G),signOutBlock:(c=dB(et.scope,G))||(void 0===et.invalidError&&et.validated?void 0:"invalid"),onSwitch:z,onSwitchInProject:P,onShowServer:e=>{T(e),requestAnimationFrame(()=>ep(document,ec.current??ed.current))},onExposureChange:W,onRemove:F,onTest:B,onSignIn:H,onSignOut:_,onSignInPaste:U,onSignInCancel:K},c9(et)):(0,r.jsx)(ay,{children:"mcp.empty"===ej?V(ej,{globalPath:fb(eb?.path??"~/.pi/agent/mcp.json")}):V(ej)}):null})})]}),(0,r.jsxs)(ak,{status:ex.length>0?(0,r.jsx)(aw,{tone:ex.some(e=>{let{problem:t}=e;return dg(t)})?"error":"warning",summary:1===ex.length?V("mcp.footer.fileProblem"):V("mcp.footer.fileProblems",{count:ex.length}),details:ex.map(e=>{let{file:t,problem:n}=e,i=c5(n,t.realPath);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:fb(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)(aw,{summary:ev.total>0?V("mcp.serverCount",{enabled:ev.enabled,total:ev.total}):""}),children:[!f&&(0,r.jsx)(aS,{onClick:Z,children:V("i18n.close")}),(0,r.jsx)(aS,{variant:"secondary",onClick:M,disabled:ek,children:V("i18n.refresh")})]})]})}function fN(e){let{added:t,cwd:n,server:i,testing:o,signIn:s,signingOut:l,signInBlock:a,onSignIn:c}=e,{t:d}=(0,eh.s)(),u=cY(t.name),p="project"===t.scope&&n?cY(cl(t.path,n)):fb(t.path),h=i.status,f=!o&&h?.origin==="test"&&"needs-auth"===h.state&&i.usesOAuth,m=s?.starting===!0||fi(s);return(0,r.jsxs)(av,{action:!f||m||l||a?void 0:(0,r.jsx)(aS,{size:"small",variant:"primary",onClick:()=>c(i),children:d("mcp.signIn.button")}),children:[void 0===t.trustedFolder?d("mcp.add.added",{name:u,path:p}):t.trustedFolder===n?d("mcp.add.addedTrustedHere",{name:u,path:p}):d("mcp.add.addedTrusted",{name:u,path:p,folder:fb(t.trustedFolder)}),o&&(0,r.jsxs)(r.Fragment,{children:[" ",d("mcp.add.testing")]}),f&&(0,r.jsxs)(r.Fragment,{children:[" ",d("mcp.add.needsSignIn")]})]})}function fE(e){let{codemode:t,active:n,rowRef:i,onSelect:o}=e,{t:s}=(0,eh.s)(),l=t.builtinDisabled||"unavailable"===t.sandbox.state?"unavailable":t.preference??"unknown",a=s(dC[l]);return(0,r.jsxs)(an,{ref:n?i:void 0,active:n,"aria-label":s("mcp.codemode.rowLabel",{state:a}),onClick:()=>o(c6),children:[(0,r.jsx)(aE,{...da(dN(l))}),(0,r.jsx)(ar,{className:"is-grow",children:s("mcp.codemode.title")}),(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${dN(l)}`,children:a})]})}function f$(e){var t;let n,i,{group:o,context:s,selected:l,selectedRowRef:a,block:c,blockNoticeId:d,busy:u,controlsBusy:p,status:h,onSelect:f,onGroupSwitch:m}=e,{t:g}=(0,eh.s)(),{enabled:x,total:v}=dv(o.servers),b=(t=o.servers).some(e=>e.enabled&&d_(e))&&t.every(e=>e.enabled||!dU(e)),y=function(e){if(!(e.servers.length>0))return e.file?e.file.problems.some(dg)?"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")} ${fk(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`${cY(t)}: ${fk(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)(l7,{aside:v>0?(0,r.jsx)(ae,{enabled:x,total:v,checked:b,disabled:p||void 0!==c,loading:u===`group:${o.scope}`,describedBy:c?d:void 0,label:g(b?"mcp.groupSwitchOn":"mcp.groupSwitchOff",{group:fv(o.scope,g)}),onChange:e=>m(o.scope,o.servers,e)}):void 0,children:fv(o.scope,g)}),j&&(0,r.jsx)(at,{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=c9(e),n=de(e,s),i=dl(n),o=ds[n],c=cY(e.name);return(0,r.jsxs)(an,{ref:l===t?a:void 0,active:l===t,"aria-label":g("mcp.rowLabel",{name:c,state:g(dr(n,e.status))}),onClick:()=>f(t),children:[(0,r.jsx)(aE,{...da(i)}),(0,r.jsx)(ar,{className:`is-grow${"on"===i?"":" is-muted"}`,children:c}),o&&(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${i}`,children:g(o)})]},t)})]})}function fI(e){let{fields:t}=e,{t:n}=(0,eh.s)();return(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>{let t=c2(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function fT(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:cY(e)},e))})}function fM(e){let{server:t,state:n}=e,{t:i}=(0,eh.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:cY(t.invalidError??"")})]});let o=di[n];return o?(0,r.jsx)("span",{className:"mcp-config-line",children:i(o)}):null}function fR(e){let{server:t,context:n,codemode:o,toolSearchDisabled:s,autoEnable:l,block:a,inProject:c,inProjectBlock:d,savedWhileOff:u,busy:p,controlsBusy:h,actionError:f,test:m,testBlock:g,signIn:x,signInBlock:v,signOutBlock:b,onSwitch:y,onSwitchInProject:j,onShowServer:k,onExposureChange:w,onRemove:S,onTest:C,onSignIn:N,onSignOut:E,onSignInPaste:$,onSignInCancel:I}=e,{t:T}=(0,eh.s)(),M=(0,i.useId)(),R=(0,i.useId)(),L=de(t,n),A=dl(L),z=c0(t),P=void 0===t.invalidError,W="http"===t.transport||void 0===t.transport&&void 0!==t.url,O=!W&&("stdio"===t.transport||void 0!==t.command),F=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"===dj(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,D=(0,i.useId)(),B=(0,i.useId)(),H=c9(t),_=cY(t.name),U=!t.enabled&&void 0!==t.webPasswordField,K=!0===t.notAnObject,q=a?T(`mcp.reason.${a}`):K?T("mcp.reason.entry-not-object"):U?T("mcp.reason.web-password"):u?T("mcp.write.savedWhileOff"):void 0;return(0,r.jsxs)(ai,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(ao,{children:[(0,r.jsxs)(as,{children:[(0,r.jsx)(ah,{scope:t.scope,children:fv(t.scope,T)}),(0,r.jsx)(aa,{children:_})]}),(0,r.jsxs)(al,{children:[(0,r.jsx)(fO,{server:t,test:m,testBlock:g,describedBy:R,onTest:C}),(0,r.jsx)(aS,{variant:"danger",size:"small",disabled:h||void 0!==a,"aria-describedby":a?M:void 0,onClick:()=>S(t),children:p===`remove:${H}`?T("i18n.removing"):T("i18n.remove")}),(0,r.jsx)(aC,{checked:t.enabled,disabled:h||void 0!==a||K||U,loading:p===`switch:${H}`,describedBy:q?M:void 0,label:T(t.enabled?"mcp.server.switchOff":"mcp.server.switchOn",{name:_}),onChange:e=>y(t,e)})]})]}),q&&(0,r.jsx)("div",{id:M,className:"config-detail-heading-note",children:q})]}),f&&(0,r.jsxs)("p",{role:"alert",className:"mcp-config-line is-error",children:[T("mcp.actionFailed")," ",fk(f,T)]}),(0,r.jsxs)(au,{children:[(0,r.jsx)(ap,{label:T("i18n.status"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:`mcp-config-state is-${A}`,children:T(dr(L,t.status))}),(0,r.jsx)(fM,{server:t,state:L}),t.webPasswordField&&(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[T("mcp.server.webPassword")," ",(0,r.jsx)(fI,{fields:[t.webPasswordField]})]})]})}),(0,r.jsx)(fF,{server:t,test:m,testBlock:g,testBlockId:R}),void 0!==t.description&&(0,r.jsx)(ap,{label:T("mcp.detail.description"),tone:"plain",children:cY(t.description)}),t.transport&&(0,r.jsx)(ap,{label:T("mcp.detail.transport"),children:T(`mcp.transport.${t.transport}`)}),void 0!==z&&(0,r.jsx)(ap,{label:W?T("mcp.detail.url"):T("mcp.detail.command"),tone:"plain",mono:!0,children:z}),O&&void 0!==t.cwd&&(0,r.jsx)(ap,{label:T("mcp.detail.cwd"),mono:!0,children:cY(t.cwd)}),O&&t.envNames.length>0&&(0,r.jsx)(ap,{label:T("mcp.detail.env"),children:(0,r.jsx)(fT,{names:t.envNames})}),W&&t.headerNames.length>0&&(0,r.jsx)(ap,{label:T("mcp.detail.headers"),children:(0,r.jsx)(fT,{names:t.headerNames})}),P&&t.commandFields.length>0&&(0,r.jsx)(ap,{label:T("mcp.detail.shellCommands"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:T("mcp.server.commandFields")}),(0,r.jsx)(fI,{fields:t.commandFields})]})}),P&&t.variableReferences.length>0&&(0,r.jsx)(ap,{label:T("mcp.detail.variables"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:T(c4(t))}),(0,r.jsx)("span",{className:"mcp-config-chips",children:c3(t.variableReferences).map(e=>{let{variable:t,field:n}=e,i=c2(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:T("mcp.server.variableIn",{variable:t,field:T(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})}),W&&P&&(0,r.jsx)(fm,{server:t,run:x,block:v,signOutBlock:b,controlsBusy:h,signingOut:p===`sign-out:${H}`,onSignIn:N,onSignOut:E,onPaste:$,onCancel:I}),t.exposure&&(0,r.jsx)(ap,{label:T("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":T("mcp.exposure.label",{name:_}),"aria-describedby":[D,a?M:null].filter(Boolean).join(" "),value:t.exposure,disabled:h||void 0!==a,onChange:e=>{let n=e.target.value;n!==t.exposure&&w(t,n)},children:df.map(e=>(0,r.jsx)("option",{value:e,children:"codemode"===e?T("mcp.exposure.optionDefault",{label:T(dm[e])}):T(dm[e])},e))}),p===`exposure:${H}`&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:T("i18n.saving")})]}),(0,r.jsx)("span",{id:D,className:"mcp-config-line",children:T(dh[t.exposure])}),void 0!==t.toolExposureCount&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:T("mcp.exposure.toolOverrides",{count:t.toolExposureCount})}),F&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:fy(F,T)})]})}),c&&(0,r.jsx)(ap,{label:T("mcp.detail.inProject"),tone:"plain",children:(0,r.jsx)("span",{className:"mcp-config-lines",children:"override"===c.kind?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"mcp-config-line",children:c.applies?T("mcp.inProject.overridden",{keys:c.keys.join(", ")}):T("mcp.inProject.refused")}),(0,r.jsx)("span",{children:(0,r.jsx)(aS,{size:"small",onClick:()=>k(c.key),children:T("mcp.inProject.show")})})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:(0,r.jsx)(aS,{size:"small",disabled:h||void 0!==d||U,"aria-describedby":[B,d||U?M:null].filter(Boolean).join(" "),onClick:()=>j(t,!t.enabled),children:p===`in-project:${H}`?T("i18n.saving"):T(t.enabled?"mcp.inProject.turnOff":"mcp.inProject.turnOn")})}),(0,r.jsx)("span",{id:B,className:"mcp-config-line is-dim",children:T("mcp.inProject.saved")})]})})}),(0,r.jsx)(ap,{label:T("mcp.detail.file"),tone:"dim",mono:!0,children:fb(t.sourcePath)})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[c1(t)&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:T("mcp.server.hiddenCharacters")}),!t.validated&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:T("mcp.server.unchecked")}),t.replacesGlobal&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:T("mcp.server.replacesGlobal")}),t.override&&(0,r.jsx)("p",{className:"mcp-config-line",children:fy(c8(t.override.keys),T)}),t.shadowedByProject&&"replaced"!==L&&(0,r.jsx)("p",{className:"mcp-config-line",children:T("mcp.server.shadowedByProject")}),t.overriddenByProject&&"overridden"!==L&&(0,r.jsx)("p",{className:"mcp-config-line",children:T("mcp.server.overriddenByProject")}),t.masked&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:T("mcp.server.masked")})]})]})}function fL(e){let{error:t,stderr:n}=e,{t:i}=(0,eh.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:cY(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(cY).join("\n")})]})]})}function fA(e){let{status:t}=e;return"session"===t.origin?(0,r.jsx)(fP,{status:t}):(0,r.jsx)(fz,{status:t})}function fz(e){let{status:t}=e,{t:n,locale:i}=(0,eh.s)(),o=t.timedOut?{key:dY.timedOut,tone:"error"}:{key:dY[t.state],tone:dl(t.state)},s=dc(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?dX:dG)[t.timedOut?"timedOut":t.state],{count:t.toolCount,seconds:dQ(t.durationMs),time:s})]}),(0,r.jsx)(fL,{error:t.error,stderr:t.stderr}),l&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.test.serverInfo",{name:cY(l.title??l.name),version:cY(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:fb(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:dQ(t.queuedMs)})})]})}function fP(e){let{status:t}=e,{t:n,locale:i}=(0,eh.s)(),o=void 0!==t.closedAt?{key:"mcp.session.state.closed",tone:"off"}:{key:dd[t.state],tone:dp[t.state]},s=dc(t.updatedAt,i),l=void 0===t.closedAt?void 0:dc(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":du[t.state],{path:fb(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:fb(t.conflict)})]}),(0,r.jsx)(fL,{error:t.error,stderr:t.stderr})]})}function fW(e){let{status:t,serverExposure:n}=e,{t:i}=(0,eh.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:cY(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(dm[e.exposure])})]}),e.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:cY(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 fO(e){let{server:t,test:n,testBlock:o,describedBy:s,onTest:l}=e,{t:a}=(0,eh.s)(),c=(0,i.useRef)(null),d=n?.running===!0,u=(0,i.useRef)(d);return(0,i.useEffect)(()=>{let e=u.current;u.current=d,e&&!d&&ep(document,c.current)},[d]),(0,r.jsx)(aS,{ref:c,size:"small",disabled:d||void 0!==o,"aria-busy":d||void 0,"aria-describedby":o?s:void 0,onClick:()=>l(t),children:a(d?"mcp.test.testing":"mcp.test.button")})}function fF(e){let{server:t,test:n,testBlock:i,testBlockId:o}=e,{t:s}=(0,eh.s)(),l=t.status;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ap,{label:s("mcp.detail.connection"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[l?(0,r.jsx)(fA,{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?dJ[e.reason]:void 0;return n?t(n):fj(e,t)}(n.error,s)]}),i&&(0,r.jsx)("span",{id:o,className:"mcp-config-line is-dim",children:s(dZ[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)(ap,{label:s("mcp.detail.listedTools"),tone:"plain",children:(0,r.jsx)(fW,{status:l,serverExposure:t.exposure})})]})}function fD(e){let{codemode:t,autoEnable:n,save:i,serverBusy:o,onChange:s,onModeChange:l,onInlineBudgetSave:a}=e,{t:c}=(0,eh.s)(),d=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"===dj(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:dk[t.preference],params:{path:t.settingsPath}}}(t);return(0,r.jsxs)(ai,{children:[(0,r.jsx)(ao,{children:(0,r.jsx)(as,{children:(0,r.jsx)(aa,{children:c("mcp.codemode.title")})})}),(0,r.jsx)("p",{className:"mcp-config-line",children:c("mcp.codemode.intro")}),(0,r.jsxs)(au,{children:[(0,r.jsx)(ap,{label:c("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)(af,{value:u,label:c("mcp.codemode.title"),options:[{value:"automatic",label:c(dC.automatic),disabled:p},{value:"always",label:c(dC.always),disabled:p||void 0!==m}],disabledReason:m?fy(m,c):null,onChange:e=>{e!==u&&s(e)},children:h.saving&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:c("i18n.saving")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:c("always"===u?"mcp.codemode.alwaysDescription":"mcp.codemode.automaticDescription")})]}):(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[c("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:cY(t.preferenceError??"")})]}),h.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[c("mcp.codemode.saveFailed")," ",(0,r.jsx)(fB,{error:h.error})]}),x&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:fy(x,c)}),f&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:fy(f,c)})]})}),t.mode?(0,r.jsx)(fH,{mode:t.mode,codemode:t,save:i,waiting:p,onChange:l}):void 0!==t.modeError&&(0,r.jsx)(ap,{label:c("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[c("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:cY(t.modeError)})]})}),t.inlineBudget?(0,r.jsx)(f_,{budget:t.inlineBudget,save:i,waiting:p,onSave:a}):void 0!==t.inlineBudgetError&&(0,r.jsx)(ap,{label:c("mcp.codemode.inlineBudget"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[c("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:cY(t.inlineBudgetError)})]})}),(0,r.jsx)(ap,{label:c("mcp.codemode.sandbox"),tone:"plain",children:"unavailable"===d.state?(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[c("mcp.codemode.sandbox.unavailable")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:cY(d.error)})]}):(0,r.jsx)("span",{className:"mcp-config-line",children:c("available"===d.state?"mcp.codemode.sandbox.available":"mcp.codemode.sandbox.not-checked")})}),g&&(0,r.jsx)(ap,{label:c("mcp.codemode.builtin"),tone:"error",children:fy(g,c)})]})]})}function fB(e){let{error:t}=e,{t:n}=(0,eh.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:cY(t.error)})}function fH(e){let{mode:t,codemode:n,save:i,waiting:o,onChange:s}=e,{t:l}=(0,eh.s)(),a="mode"===i.target,c=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:dS[r.value],params:{path:r.settingsPath}}),"only"===(r??t).value&&"automatic"===dj(e)&&n.push({key:"mcp.codemode.toolMode.automaticNote"}),n}(n);return(0,r.jsx)(ap,{label:l("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)(af,{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(dw[t.value])}),c.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:fy(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)(fB,{error:i.error})]})]})})}function f_(e){let t,n,{budget:o,save:s,waiting:l,onSave:a}=e,{t:c}=(0,eh.s)(),d=(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&&ep(document,d.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)(ap,{label:c("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:d,className:"mcp-add-input mcp-codemode-budget-input",inputMode:"numeric","aria-label":c("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:c("mcp.codemode.inlineBudget.unit")}),(0,r.jsx)(aS,{type:"submit",size:"small",disabled:!g||l,children:c("mcp.codemode.inlineBudget.save")}),v&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:c("i18n.saving")})]}),!m.ok&&(0,r.jsx)("span",{className:"mcp-config-line is-error",children:c("mcp.codemode.inlineBudget.invalidDraft",{max:String(o.max)})}),(0,r.jsx)("span",{id:u,className:"mcp-config-line",children:c("mcp.codemode.inlineBudget.description",{default:String(o.default)})}),y.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:fy(e,c)},e.key)),x&&s.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[c("mcp.codemode.inlineBudget.saveFailed")," ",(0,r.jsx)(fB,{error:s.error})]})]})})}let fU=[{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 fK(){let{t:e}=(0,eh.s)(),t=oB();return(0,r.jsx)("div",{className:"settings-font-rows",children:fU.map(n=>{let{kind:i,label:o,placeholder:s,reset:l,weightLabel:a}=n,c=t[`${i}Weight`],d=oj.findIndex(e=>e.value===c);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:c}),(0,r.jsx)(aS,{variant:"ghost",size:"small",className:"settings-chat-reset",title:e(l),"aria-label":e(l),disabled:!t[i]&&400===c,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:oj[0].value,max:oj[oj.length-1].value,step:100,value:c,"aria-label":e(a),"aria-valuetext":`${c} ${e(oj[d].label)}`,onChange:e=>t.setFontWeight(i,Number(e.target.value))})]},i)})})}function fq(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 fZ(e){let{sessionId:t,onSessionReloaded:n,quoteSelectionEnabled:o,onQuoteSelectionChange:s}=e,{locale:l,setLocale:a,supportedLocales:c,t:d}=(0,eh.s)(),{preference:u,setThemePreference:p}=rU(),{width:h,setWidth:f,fontSize:m,setFontSize:g}=oy(),x=oo(),[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,E]=(0,i.useState)(!1),[$,I]=(0,i.useState)(null),[T,M]=(0,i.useState)(!1),[R,L]=(0,i.useState)(!1),[A,z]=(0,i.useState)("");(0,i.useEffect)(()=>{C(r6()),fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>M(e?.enabled===!0)).catch(()=>{})},[]);let P=async()=>{L(!0),z("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.replace("/login")}catch{z(d("auth.logoutFailed"))}finally{L(!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 W=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 sT(t,{type:"reload"}),n())}catch(e){w(e instanceof Error?e.message:String(e))}finally{j(!1)}},O=async()=>{if(!N){E(!0),I(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 co(l))throw Error("unsupported or not permitted");I({kind:"ok",message:d("settings.pushRegistered")})}catch(e){I({kind:"error",message:`${d("settings.pushRegisterFailed")} ${e instanceof Error?e.message:String(e)}`})}finally{E(!1)}}};return(0,r.jsxs)("div",{className:"settings-general",children:[(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.appearance")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":d("settings.appearance"),className:"settings-theme-options",children:r$.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)(lH,{preference:e.id}),(0,r.jsx)("span",{className:"settings-theme-option-label",children:d(e.label)})]},e.id)})})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.typography")}),(0,r.jsx)("p",{id:"settings-typography-description",className:"settings-general-description",children:d("settings.fontDescription")}),(0,r.jsxs)("div",{className:"settings-chat-options",children:[(0,r.jsx)(fK,{}),(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:d("settings.chatContentFontSize")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-font-size",children:[m,"px"]}),(0,r.jsx)(aS,{variant:"ghost",size:"small",className:"settings-chat-reset",title:d("settings.resetChatContentFontSize"),"aria-label":d("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:d("settings.chatContentWidth")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-width",children:[h,"px"]}),(0,r.jsx)(aS,{variant:"ghost",size:"small",className:"settings-chat-reset",title:d("settings.resetChatContentWidth"),"aria-label":d("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:d("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:d("settings.thinkingExpandedDefault")}),(0,r.jsx)(aC,{checked:S,label:d("settings.thinkingExpandedDefault"),onChange:e=>{window.localStorage.setItem(r3,String(e)),window.dispatchEvent(new Event(r5)),C(e)}})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:d("settings.quoteSelection")}),(0,r.jsx)(aC,{checked:o,label:d("settings.quoteSelection"),onChange:s})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",role:"radiogroup","aria-label":d("settings.enterSendMode"),children:[(0,r.jsx)("span",{children:d("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:()=>oi("enter"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:d("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:()=>oi("ctrlEnter"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:d("settings.enterSendModeCtrlEnter")})]})]})]})]})]}),v?.isWindows&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.shellTool")}),(0,r.jsx)("p",{className:"settings-general-description",children:d("settings.shellToolDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:d("settings.usePowerShell")}),(0,r.jsx)(aC,{checked:v.powerShellEnabled,loading:y,label:d("settings.usePowerShell"),onChange:e=>void W(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:d("settings.pushPermission")}),(0,r.jsx)("p",{className:"settings-general-description",children:d("settings.pushPermissionDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:d("settings.pushPermission")}),(0,r.jsx)("button",{type:"button",className:"config-button config-button-small config-button-secondary",disabled:N,onClick:()=>void O(),children:N?d("settings.pushRegisterLoading"):d("settings.pushRegister")})]}),$&&(0,r.jsx)("p",{role:"status",className:"settings-general-error",style:"ok"===$.kind?{color:"var(--accent)"}:void 0,children:$.message})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("common.language")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":d("common.language"),className:"settings-language-options",children:c.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)})})]}),T&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsxs)(aS,{variant:"secondary",disabled:R,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"})}),R?d("auth.loggingOut"):d("auth.logOut")]}),A&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:A})]})]})}let fV={en:"Archives","zh-CN":"归档","zh-TW":"封存"};function fJ(e){let{cwd:t,sessionId:n,initialSection:o,onClose:s,onSessionReloaded:l,quoteSelectionEnabled:a,onQuoteSelectionChange:c,projectTrust:d,onOpenTrustDialog:u,onProjectTrustChanged:p}=e,{t:h,locale:f}=(0,eh.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:fV[f]??fV.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:lq(e.id)})),y=lq(m);(0,i.useEffect)(()=>lY(o),[o]),(0,i.useEffect)(()=>{var e;let t;return e=document,t=e=>{"Escape"!==e.key||e.defaultPrevented||eu(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")),lY("general"))},[t,y]);let k=e=>{v(t=>new Set(t).add(e)),g(e),lY(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)(fq,{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)(fZ,{sessionId:n,onSessionReloaded:l,quoteSelectionEnabled:a,onQuoteSelectionChange:c})),w("models",(0,r.jsx)(cr,{embedded:!0,cwd:t,onClose:s})),w("archives",(0,r.jsx)(cq,{embedded:!0,onClose:s})),t&&w("skills",(0,r.jsx)(cg,{embedded:!0,cwd:t,trust:d,onClose:s},t)),t&&w("agents",(0,r.jsx)(cI,{embedded:!0,cwd:t,sessionId:n,trust:d,onClose:s,onReloaded:l},t)),t&&w("plugins",(0,r.jsx)(cH,{embedded:!0,cwd:t,sessionId:n,trust:d,onClose:s,onReloaded:l},t)),w("mcp",(0,r.jsx)(fS,{embedded:!0,cwd:t,trust:d,onTrustProject:u,onProjectTrustChanged:p,onClose:s},t??""))]})]})})}let fY="project-trust-mcp-status";function fG(e){let{cwd:t,busy:n,error:o,onCancel:s,onConfirm:l,onStatus:a}=e,[c,d]=(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;d({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);d(r),"loaded"===r.state&&r.status&&u.current?.(r.status)}).catch(t=>{e&&d(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)(fX,{cwd:t,busy:n,error:o,listing:c,onCancel:s,onConfirm:l})}function fX(e){let{cwd:t,busy:n,error:o,listing:s,onCancel:l,onConfirm:a}=e,{t:c}=(0,eh.s)(),d="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(),eu(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:c("trust.dialogTitle")}),(0,r.jsx)("div",{id:"project-trust-description",className:"project-trust-text",children:c("trust.dialogBody")}),(0,r.jsx)("code",{className:"project-trust-path",children:cY(t)}),u&&(0,r.jsx)("p",{id:"project-trust-notice",role:"status",className:"project-trust-notice",children:c(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:c("mcp.reason.trust-unreadable")}),(0,r.jsx)("code",{className:"project-trust-mcp-detail",children:cY(s.statusError)})]}),(0,r.jsx)(f0,{listing:s})]})]}),o&&(0,r.jsx)(fQ,{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:c(u?"trust.close":"trust.cancel")}),!u&&(0,r.jsx)("button",{type:"button",className:"project-trust-button is-primary",onClick:a,disabled:n||d,"aria-busy":n||void 0,"aria-describedby":d?fY:void 0,children:c(n?"trust.trusting":"trust.trustProject")})]})]})})}function fQ(e){let{error:t}=e,{t:n}=(0,eh.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:cY(t.error)})]})}function f0(e){let{listing:t}=e,{t:n}=(0,eh.s)();if("loading"===t.state)return(0,r.jsx)("p",{id:fY,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:cY(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)(f1,{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)(f8,{server:e},e.name))})]}):null}function f1(e){let{file:t}=e,{t:n}=(0,eh.s)();return(0,r.jsx)(r.Fragment,{children:t.problems.map(e=>{let i=c5(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 f2(e){let{fields:t}=e,{t:n}=(0,eh.s)();return(0,r.jsx)(r.Fragment,{children:t.map(e=>{let t=c2(e);return(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function f4(e){let{server:t}=e,{t:n}=(0,eh.s)();return(0,r.jsx)(r.Fragment,{children:c3(t.variableReferences).map(e=>{let{variable:t,field:i}=e,o=c2(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 f8(e){let t,{server:n}=e,{t:i}=(0,eh.s)(),o=c0(n),s=void 0===n.invalidError;return(0,r.jsxs)("li",{className:"project-trust-mcp-server",children:[(0,r.jsxs)("div",{className:"project-trust-mcp-server-head",children:[(0,r.jsx)("span",{className:"project-trust-mcp-server-name",children:cY(n.name)}),n.transport&&(0,r.jsx)("span",{className:"project-trust-mcp-tag",children:i(`mcp.transport.${n.transport}`)})]}),void 0!==o&&(0,r.jsx)("code",{className:"project-trust-mcp-target",children:o}),void 0!==n.cwd&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:i("trust.mcp.cwd",{path:cY(n.cwd)})}),c1(n)&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:i("mcp.server.hiddenCharacters")}),void 0!==n.invalidError&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.invalid")," ",(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:cY(n.invalidError)})]}),n.webPasswordField&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.webPassword")," ",(0,r.jsx)(f2,{fields:[n.webPasswordField]})]}),!n.enabled&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:i("mcp.server.disabled")}),s&&n.commandFields.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.commandFields")," ",(0,r.jsx)(f2,{fields:n.commandFields})]}),s&&n.variableReferences.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i(c4(n))," ",(0,r.jsx)(f4,{server:n})]}),n.replacesGlobal&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:i("mcp.server.replacesGlobal")}),n.override&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:i((t=c8(n.override.keys)).key,t.params)}),n.masked&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-dim",children:i("mcp.server.masked")})]})}function f3(e){return"message"===e.type&&"message"in e&&"system"!==e.message.role}function f5(e){let t=e,n=t.branchPreview,r=f3(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&f3(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function f6(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 f9(e){let{node:t,activePathIds:n,depth:i,isLast:o,parentLines:s,onSelect:l}=e,{node:a,skipped:c,branchPreview:d,labelEntry:u}=f5(t),p=n.has(a.entry.id),h=n.has(t.entry.id)||n.has(a.entry.id),f=d?.text??function(e){if("message"===e.type&&f3(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=d?d.role??null:f3(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"}),c>0&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",c]}),(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)(f9,{node:e,activePathIds:n,depth:i+1,isLast:t===a.children.length-1,parentLines:[...s,!o],onSelect:l},e.entry.id))]})}function f7(e){let{tree:t,activeLeafId:n,onLeafChange:o,inline:s,containerRef:l,open:a,onToggle:c,hasSession:d,compact:u,hideInlineButton:p,locked:h=!1}=e,{t:f}=(0,eh.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=d?f6(t)?null:f("i18n.noBranches"):f("i18n.noActiveSession"),N=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=f5(e[0]).node;return t.children.length>1?t.children:[]}(t),E=!C&&N.length>0,$=(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:E?"var(--accent)":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),I=(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{marginLeft:2,transform:x?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})});return s?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"stretch"},children:[(0,r.jsxs)("button",{ref:v,onClick:()=>c?c():g(e=>!e),style:{display:p?"none":"flex",alignItems:"center",gap:6,height:"100%",padding:"0 12px",background:x?"var(--bg-selected)":"none",border:"none",borderTop:x?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:"pointer",color:x?"var(--text)":"var(--text-muted)",fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color=x?"var(--text)":"var(--text-muted)"},title:f("i18n.branches"),"aria-label":f("i18n.branches"),"aria-pressed":x,children:[$,!u&&(0,r.jsx)("span",{children:f("i18n.branches")})]}),x&&b&&(0,r.jsx)("div",{style:{position:"fixed",top:b.top,left:b.left,width:b.width,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",zIndex:500},children:E?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(f9,{node:e,activePathIds:j,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:w},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C})})]}):(0,r.jsxs)("div",{style:{borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>g(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"5px 12px",background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",fontSize:11,textAlign:"left"},children:[$,(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:f("i18n.branches")}),I]}),x&&(0,r.jsx)("div",{style:{position:"absolute",top:"100%",left:0,right:0,background:"var(--bg)",borderBottom:"1px solid var(--border)",boxShadow:"0 4px 12px rgba(0,0,0,0.1)",zIndex:100},children:E?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(f9,{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 me(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:`
11
+ ${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)(()=>()=>{tg.current.forEach(si)},[]);let tS=(0,i.useCallback)(async e=>{if(ev.length||!e.startsWith("/")||!V)return!1;if(eJ.current)return!0;eJ.current=!0,eV(!0);try{var t,n;let r=await V(e);if(!r.handled)return!1;return r.error||(t=tm.current,n=tg.current.length,0!==n||t.trim()!==e)||tk(),!0}finally{eJ.current=!1,eV(!1)}},[ev.length,tk,V]),tC=(0,i.useCallback)(async()=>{var e;let t=ec.trim();(t||ev.length)&&(G?.(),(!m||o4(e=t)||i6(e))&&await tS(t)||m||(tk(),u(t,ev.length?ev:void 0)))},[ec,ev,m,tS,u,tk,G]),tN=!en&&ec.startsWith("/")&&!/\s/.test(ec.slice(1))?ec.slice(1).toLowerCase():null,tE=null===tN?[]:[...m?o2.filter(e=>e.availableWhileStreaming):o2,...K??[]].filter(e=>{let t=e.name.toLowerCase(),n=o9(e,er).toLowerCase();return t.includes(tN)||n.includes(tN)}).sort((e,t)=>{let n=o6(e,tN,er)-o6(t,tN,er);return 0!==n?n:o5[e.source]-o5[t.source]||oV.compare(e.name,t.name)}),{commands:t$,groups:tI}=(n=0,{commands:(o=o8.map(e=>{let t=tE.filter(t=>t.source===e),r="skill"===e?[...t.filter(e=>!o7(e,e6)),...t.filter(e=>o7(e,e6))]: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}),tT=1===tE.length?er(tN?"chat.match":"chat.command"):er(tN?"chat.matches":"chat.commands",{count:tE.length}),tM=!!ec.trim()||ev.length>0,tR=ev.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)&&!eO;(0,i.useEffect)(()=>{0===ev.length&&eF(!1)},[ev.length]);let tL=(0,i.useCallback)((e,t)=>{if(!ee)return void eM(null);let n=t??e.length;eM(eQ(e.slice(0,n)))},[ee]),tA=eT?.query??null,tz=i.useMemo(()=>null!==tA&&eY&&eY.cwd===ee?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:e1(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:e1(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||e0(e.entry.path)-e0(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(eY.entries,tA):[],[tA,eY,ee]),tP=!!(tA&&eY?.truncated&&eY.cwd===ee);(0,i.useEffect)(()=>{if(!tP||!ee||!tA)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}&q=${encodeURIComponent(tA)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>e8({cwd:ee,query:tA,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tP,tA,ee]);let tW=tP&&null!==e4&&e4.cwd===ee&&e4.query===tA,tO=tW?e4.matches:tz,tF=null===eT?null:`${eT.start}:${+!!eT.quoted}:${eT.query}`;(0,i.useEffect)(()=>{if(null===tF){eL(!1),eW(0);return}eL(!0),eW(0)},[tF]);let tD=null!==eT;(0,i.useEffect)(()=>{if(!tD||!ee)return;let e=tp.current;e&&e.cwd===ee&&Date.now()-e.fetchedAt<1e4||th.current===ee||(th.current=ee,e2(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{eG({cwd:ee,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)=>e0(e.path)-e0(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tp.current={cwd:ee,fetchedAt:Date.now()}}).catch(()=>{tp.current=null}).finally(()=>{th.current=null,e2(!1)}))},[tD,ee]);let tB=(0,i.useCallback)(e=>{if(!eT)return;let t=e9.current;if(!t)return;let n=t.selectionStart??t.value.length,r=n+(eT.quoted&&'"'===t.value[n]?1:0),i=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let o=i?`@"${r}" `:`@${r} `;return{text:o,cursorOffset:o.length}}(e.path,e.isDir,eT.quoted),o=eT.start+i.cursorOffset;oG(t,eT.start,r,i.text,i.cursorOffset),eM(eQ(t.value.slice(0,o)))},[eT]);(0,i.useEffect)(()=>{eP>=tO.length&&eW(Math.max(0,tO.length-1))},[tO.length,eP]),(0,i.useEffect)(()=>{td.current.length=tO.length},[tO.length]),(0,i.useEffect)(()=>{eR&&td.current[eP]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eP,eR]),(0,i.useEffect)(()=>{eU>=_.length&&eK(Math.max(0,_.length-1))},[_.length,eU]),(0,i.useEffect)(()=>{tu.current.length=_.length},[_.length]),(0,i.useEffect)(()=>{eB&&tu.current[eU]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eU,eB]);let tH=(0,i.useCallback)(e=>{ed(e),eH(!1),eK(0),eM(null),requestAnimationFrame(()=>{let t=e9.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),t_=(0,i.useCallback)(e=>{let t=`/${e.name} `;ed(t),eC(!1),eE(0),requestAnimationFrame(()=>{let e=e9.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),tU=(0,i.useCallback)(e=>{let t=ec.trim();if(!t&&!ev.length)return;G?.();let n=ev.length?ev:void 0,r=()=>{if(t.startsWith("/")&&X){tk(),X(t,"steer"===e?"steer":"followUp",n);return}tk(),"steer"===e&&h?h(t,n):"followup"===e&&f&&f(t,n)};!ev.length&&V&&o4(t)?tS(t):!ev.length&&V&&i6(t)?tS(t).then(e=>{e||r()},()=>r()):r()},[ec,ev,V,X,h,f,tk,G,tS]),tK=(0,i.useCallback)(e=>{let t=t$.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eN-1);if("right"===e)return Math.min(t,eN+1);let n=ta.current[eN];if(!n)return"down"===e?Math.min(t,eN+1):Math.max(0,eN-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===eN)continue;let t=ta.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 c=1e3*Math.abs(a)+Math.abs(r.left+r.width/2-i);c<l&&(s=n,l=c)}return s>=0?s:"down"===e?Math.min(t,eN+1):Math.max(0,eN-1)},[t$.length,eN]),tq=(0,i.useCallback)(e=>{let t=e.nativeEvent,n="Enter"===e.key&&!e.shiftKey,r=el||"ctrlEnter"===ea?n&&(e.ctrlKey||e.metaKey):n,i=el?r:n,o=Date.now()-to.current<100,s=ti.current||t.isComposing||229===t.keyCode;if(i&&(s||o)){o&&e.preventDefault();return}if(eB&&!s){if("ArrowDown"===e.key){e.preventDefault(),eK(e=>Math.min(Math.max(0,_.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eK(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),eH(!1);return}if(("Tab"===e.key||i)&&_[eU]){e.preventDefault(),tH(_[eU]);return}}if(eS&&null!==tN){if("ArrowDown"===e.key){e.preventDefault(),eE(tK("down"));return}if("ArrowUp"===e.key){e.preventDefault(),eE(tK("up"));return}if("ArrowRight"===e.key){e.preventDefault(),eE(tK("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),eE(tK("left"));return}if("Escape"===e.key){e.preventDefault(),eC(!1);return}let t=t$[eN];if("Tab"===e.key&&t){e.preventDefault(),t_(t);return}if(i&&t){e.preventDefault(),r&&function(e,t,n){if("builtin"===t.source)return"builtin"===t.source&&e.trim()===`/${t.name}`&&(!n||!0===t.availableWhileStreaming);return i5(t)&&i6(e)}(ec,t,m)?(eC(!1),tC()):t_(t);return}}if(eR&&null!==eT&&!s){if("ArrowDown"===e.key){e.preventDefault(),eW(e=>oJ(e,tO.length,1));return}if("ArrowUp"===e.key){e.preventDefault(),eW(e=>oJ(e,tO.length,-1));return}if("Escape"===e.key){e.preventDefault(),eL(!1);return}if(("Tab"===e.key||i)&&tO[eP]){e.preventDefault(),tB(tO[eP]);return}}if("ArrowUp"===e.key&&!s&&!m&&_.length>0&&0===ec.trim().length){e.preventDefault(),eC(!1),eL(!1),eK(_.length-1),eH(!0);return}if("Escape"===e.key&&!s&&m&&p){e.preventDefault(),p();return}r&&(e.preventDefault(),m&&(h||f)?tU(e.altKey&&f||!h?"followup":"steer"):tC())},[el,ea,m,h,f,p,eS,tN,t$,eN,t_,tU,tC,tK,eR,eT,tO,eP,tB,eB,_,eU,tH,ec]),tZ=(0,i.useCallback)(()=>{let e=e9.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),tV=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!en&&t.length){e.preventDefault(),tv(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"),c=s.replace(/([\\()])/g,"\\$1");n+=`${e.slice(r,t)}[${a}](${c})`,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(),tm.current=a,ed(a),eH(!1),tL(a,l+o.length),requestAnimationFrame(()=>{s.focus(),s.setSelectionRange(l+o.length,l+o.length)})},[en,tv,tL]);(0,i.useEffect)(()=>{if(null===tN){eC(!1),eE(0),ts.current=!1;return}eC(!0),eE(0),!ts.current&&Z&&(ts.current=!0,Promise.resolve(Z()).catch(()=>{ts.current=!1}))},[tN,Z]),(0,i.useEffect)(()=>{if(!eS||!ee)return;let e=!1;return e5({cwd:ee,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(ee)}`).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;e5({cwd:ee,values:n})}).catch(()=>{e||e5({cwd:ee,values:{}})}),()=>{e=!0}},[eS,ee]),(0,i.useEffect)(()=>{eN>=t$.length&&eE(Math.max(0,t$.length-1))},[t$.length,eN]),(0,i.useEffect)(()=>{ta.current.length=t$.length},[t$.length]),(0,i.useEffect)(()=>{eS&&ta.current[eN]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eN,eS]),(0,i.useLayoutEffect)(()=>{if(!eS||null===tN)return void eI(null);let e=tl.current;if(e)return oX(e,e=>{eI(t=>t===e?t:e)})},[eS,tN]),(0,i.useLayoutEffect)(()=>{if(!eR||null===eT)return void ez(null);let e=tc.current;if(e)return oX(e,e=>{ez(t=>t===e?t:e)})},[eR,eT]);let tJ=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}}),tY=M?Math.max(0,M.tokensBefore-M.estimatedTokensAfter):0,tG=M?`${M.reason&&"manual"!==M.reason?`${M.reason[0].toUpperCase()}${M.reason.slice(1)} `:er("chat.compacted")} ${o1(M.tokensBefore)} -> ${o1(M.estimatedTokensAfter)} tokens (${er("chat.tokensSaved",{saved:o1(tY)})})`:null,tX=A&&"auto"!==A?A:null,tQ="auto"!==(s=tX??"auto")&&O?O[s]??s:s,t0=Object.entries(oZ).find(e=>{let[,t]=e;return t===(R??"configured")})?.[0]??"configured",t1="chat-only"===t0?er("chat.chatOnly"):t0;return(0,i.useEffect)(()=>{let e=e=>{e7.current&&!e7.current.contains(e.target)&&ep(!1),te.current&&!te.current.contains(e.target)&&em(!1),tt.current&&!tt.current.contains(e.target)&&ex(!1),!tn.current||tn.current.contains(e.target)||e9.current?.contains(e.target)||eH(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{m&&ep(!1)},[m]),(0,i.useEffect)(()=>{el||ex(!1)},[el]),(0,r.jsxs)("fieldset",{disabled:eZ,"aria-busy":eZ,className:en?void 0:"chat-input-shell",style:{flexShrink:0,minWidth:0,margin:0,border:0,background:"transparent",padding:en?0:"0 16px 8px",paddingRight:en?0:el?16:52,opacity:eZ?.5:1,transition:"opacity 0.15s"},children:[!en&&(0,r.jsx)("input",{ref:tr,type:"file",accept:et?void 0:"image/*",multiple:!0,style:{display:"none"},onChange:tb}),(0,r.jsxs)("div",{style:{maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(0,r.jsx)(sl,{error:y}),(0,r.jsx)(sa,{warnings:j}),tR&&(l=b?.find(e=>e.provider===g?.provider&&e.id===g?.modelId),(0,r.jsx)(ss,{tone:"warning",title:er("chat.imageNotSupportedTitle"),body:er("chat.imageNotSupportedBody",{model:l?.name||g?.modelId||""}),onClose:()=>eF(!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:er("chat.queued",{count:(H?.steering.length??0)+(H?.followUp.length??0)})}),U&&(0,r.jsxs)("button",{onClick:U,title:er("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"})]}),er("chat.recall")]})]}),H?.steering.map((e,t)=>(0,r.jsx)(so,{kind:"steer",text:e},`steer-${t}`)),H?.followUp.map((e,t)=>(0,r.jsx)(so,{kind:"follow-up",text:e},`followup-${t}`))]}),B&&(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"})]}),er("chat.retrying",{attempt:B.attempt,max:B.maxAttempts}),B.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",B.errorMessage]})]}),tG&&(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"})}),tG]}),I&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,marginBottom:8,padding:T?"3px 3px 3px 10px":"7px 10px",background:"rgba(239,68,68,0.07)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:6,color:"#ef4444",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,padding:T?"4px 0":0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:I}),T&&(0,r.jsx)(eD,{onClick:T,title:er("chat.dismissCompactError")})]}),ev.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:ev.map((e,t)=>(0,r.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,r.jsx)(rC,{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:()=>ty(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:[eB&&_.length>0&&(0,r.jsxs)("div",{ref:tn,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:er("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===eU;return(0,r.jsxs)("button",{ref:e=>{tu.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tH(e)},onMouseEnter:()=>eK(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),eS&&null!==tN&&(0,r.jsxs)("div",{ref:tl,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===e$?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${e$}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:q?er("chat.loadingCommands"):er("chat.slashCommands",{label:tT})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:er("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:10},children:q||0!==tE.length?tI.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:er(o3[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===eN,o=o7(t,e6);return(0,r.jsxs)("button",{ref:e=>{ta.current[n]=e},type:"button",onMouseDown:e=>{e.preventDefault(),t_(t)},onMouseEnter:()=>eE(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:er("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:o9(t,er)})]},`${t.source}:${t.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:er("chat.noCommands")})})]}),eR&&null!==eT&&(a=eX&&(!eY||eY.cwd!==ee),c=1===tO.length?er("chat.match"):er("chat.matches",{count:tO.length}),d=eY?.truncated&&!tW?eT.query?er("chat.searchingAll"):er("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:tc,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eA?"min(48vh, 400px)":`min(48vh, 400px, ${eA}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:a?er("chat.loadingFiles"):er("chat.files",{label:c,hint:d})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:er("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:a||0!==tO.length?tO.map((e,t)=>{let n=t===eP,i=e.path.split("/").pop()??e.path,o=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{td.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tB(e)},onMouseEnter:()=>eW(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)(e_,{size:14}):eq(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:tP&&!tW?er("chat.searching"):er("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{style:{minWidth:0,display:"flex",flexDirection:en?"column":"row",gap:8,alignItems:en?"stretch":"center",background:"var(--bg)",border:en?"none":`1px solid ${ej?"var(--tool-bg)":m&&(h||f)?"rgba(234,179,8,0.4)":"color-mix(in srgb, var(--border) 70%, transparent)"}`,borderRadius:14*!en,padding:en?0:el?"6px 6px 6px 12px":"10px 10px 10px 14px",boxShadow:en?"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:e9,className:"chat-input-textarea","aria-label":en?er("chat.quoteQuestion"):void 0,value:ec,onChange:e=>{tm.current=e.target.value,ed(e.target.value),eH(!1),tL(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;tL(t.value,t.selectionStart)},onKeyDown:tq,onCompositionStart:()=>{ti.current=!0},onCompositionEnd:e=>{ti.current=!1,to.current=Date.now();let t=e.currentTarget;tL(t.value,t.selectionStart)},onInput:tZ,onPaste:tV,placeholder:m&&(h||f)?er("chat.steerPlaceholder"):m?er("chat.agentPlaceholder"):er("chat.messagePlaceholder"),rows:1,style:{flex:en?"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:en?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:()=>tU("steer"),disabled:!tM,title:er("chat.steerHint"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tM?"rgba(234,179,8,0.12)":"none",border:"1px solid rgba(234,179,8,0.35)",borderRadius:8,color:tM?"rgba(180,130,0,1)":"var(--text-dim)",cursor:tM?"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"})]}),er("chat.steer")]}),f&&(0,r.jsxs)("button",{onClick:()=>tU("followup"),disabled:!tM,title:`${er("chat.followUpHint")} (${el?"Ctrl/Cmd+":""}Alt/Option+Enter)`,"aria-keyshortcuts":el?"Control+Alt+Enter Meta+Alt+Enter":"Alt+Enter",style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tM?"rgba(129,140,248,0.12)":"none",border:"1px solid rgba(129,140,248,0.35)",borderRadius:8,color:tM?"rgba(99,102,241,1)":"var(--text-dim)",cursor:tM?"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"})]}),er("chat.followUp")]})]}):(0,r.jsxs)("button",{onClick:tC,disabled:!ec.trim()&&!ev.length,title:er("chat.send"),"aria-label":er("chat.send"),style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,...el?{width:36,height:36,padding:0}:{padding:"7px 14px"},background:ec.trim()||ev.length?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:ec.trim()||ev.length?"var(--accent-contrast)":"var(--text-dim)",cursor:ec.trim()||ev.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:ec.trim()||ev.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"})]}),!el&&er("chat.send")]})]})]}),ej&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:ek?"var(--text-muted)":"var(--accent)",marginTop:4},children:[er("chat.shell")," \xb7 ",ek?er("chat.outputLocal"):er("chat.outputModel")]}),!en&&(0,r.jsxs)("div",{className:"chat-input-controls",style:{marginTop:el?4:8,display:el?"grid":"flex",gridTemplateColumns:el?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:el?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2},children:[(0,r.jsx)("button",{onClick:()=>tr.current?.click(),title:er("chat.attachFiles"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:ev.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=ev.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=ev.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"})]})}),(tJ.length>0||g||y)&&k&&(0,r.jsx)(oU,{options:tJ,value:g,onChange:k,disabled:m,busy:w,isAutoSelection:x,defaultValue:S,onSetDefault:C})]}),!el&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsxs)("div",{ref:tt,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:el?0:"auto"},children:[el&&(0,r.jsx)("button",{type:"button",title:eg?void 0:er("chat.moreControls"),"aria-label":er("chat.moreControls"),"aria-expanded":eg,"aria-hidden":eg||void 0,tabIndex:eg?-1:void 0,onClick:()=>{ex(!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:eg?"default":"pointer",fontSize:12,fontWeight:500,visibility:eg?"hidden":"visible",pointerEvents:eg?"none":"auto",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{eg||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{eg||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:er("chat.moreControls")}),(0,r.jsxs)("div",{style:{display:el?eg?"flex":"none":"flex",alignItems:"center",gap:el?1:2,...el?{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:[P&&(0,r.jsxs)("div",{ref:te,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>em(e=>!e),title:m?er("chat.currentReasoning",{level:tQ}):er("chat.changeReasoning",{level:tQ}),"aria-label":er("chat.changeReasoningLabel"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:el?"0 6px":"8px 12px",width:el?"auto":void 0,height:32,background:ef?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=ef?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),(!el||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:tQ})]}),ef&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",...el?{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:oQ.filter(e=>!W||"auto"===e||W.includes(e)).map(e=>{let t="auto"===e?z:!z&&tX===e,n=er(o0[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)(o_,{active:t,onSelect:()=>{if(em(!1),"auto"===e){z||P("auto");return}(!t||z)&&P(e)},gutter:!!D,star:D&&"auto"!==e?{isDefault:F===e,saveLabel:er("chat.saveDefaultThinking"),defaultLabel:er("chat.defaultThinking"),onSave:()=>{em(!1),D(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:e7,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>!m&&ep(e=>!e),disabled:m,title:er("chat.changeToolPreset")+`: ${t1}`,"aria-label":er("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:el?"0 6px":"8px 12px",width:el?"auto":void 0,height:32,background:eu?"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=eu?"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"})}),(!el||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t1})]}),eu&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:el?void 0:0,left:el?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:oq.map(e=>{let t,n=oZ[e],i=(R??"configured")===n;return t="configured"===e?er("chat.configuredTools"):"chat-only"===e?er("chat.chatOnly"):"read-only"===e?er("chat.readOnlyTools",{count:4}):"default"===e?er("chat.builtInTools",{count:4}):er("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{ep(!1),i||L(n)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:t})]},e)})})]}),(!m||$)&&N&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{onClick:$?E:N,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:el?"0 6px":"8px 12px",width:el?"auto":void 0,height:32,background:$?"rgba(239,68,68,0.08)":"none",border:"none",borderRadius:9,color:$?"#ef4444":"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=$?"rgba(239,68,68,0.16)":"var(--bg-hover)",e.currentTarget.style.color=$?"#ef4444":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=$?"rgba(239,68,68,0.08)":"none",e.currentTarget.style.color=$?"#ef4444":"var(--text-muted)"},title:$?er("chat.stopCompaction"):er("chat.compactContext"),"aria-label":$?er("chat.stopCompaction"):er("chat.compactContext"),children:$?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(!el||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:er("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"})]}),(!el||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:er("chat.compact")})]})})}),m&&(0,r.jsxs)("button",{onClick:p,title:er("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"})}),er("chat.stop")]}),void 0!==Y&&(0,r.jsx)("button",{onClick:Y,title:J?er("chat.disableSound"):er("chat.enableSound"),"aria-label":J?er("chat.disableSound"):er("chat.enableSound"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:J?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",opacity:J?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=J?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.opacity=J?"1":"0.55"},children:J?(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"})]})}),el&&eg&&(0,r.jsx)("button",{type:"button",title:er("chat.collapseControls"),"aria-label":er("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{ep(!1),em(!1),ex(!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 sd=n(88576),su=n.n(sd);function sp(e){let{level:t,children:n,headingIndex:i,onClick:o}=e;return(0,r.jsx)("button",{type:"button",className:su().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 sh=[...rk??[],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]:[]}}],sf=[[n4.A,{throwOnError:!1,strict:!1}]];function sm(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 sg=(0,i.memo)(function(e){let{markdown:t,onHeadingClick:n,onAnswerClick:o}=e,s=(0,i.useMemo)(()=>ra(t),[t]);return t?(0,r.jsx)("div",{className:su().outline,children:(0,r.jsx)(n2.oz,{remarkPlugins:sh,rehypePlugins:sf,components:{h1:e=>{let{children:t,node:i}=e;return(0,r.jsx)(sp,{level:1,headingIndex:sm(i),onClick:n,children:t})},h2:e=>{let{children:t,node:i}=e;return(0,r.jsx)(sp,{level:2,headingIndex:sm(i),onClick:n,children:t})},h3:e=>{let{children:t,node:i}=e;return(0,r.jsx)(sp,{level:3,headingIndex:sm(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:su().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 sx(e){let{messages:t,streamingMessage:n,scrollContainer:o,messageRefs:s,onRevealHistory:l}=e,{t:a}=(0,eh.s)(),[c,d]=(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),E=(0,i.useRef)(null),$=(0,i.useRef)(null),I=(0,i.useRef)(null),T=(0,i.useMemo)(()=>n?[...t,n]:t,[t,n]),M=(0,i.useRef)(T);M.current=T;let R=(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:L,gap:A}=R;S.current=R;let z=(0,i.useCallback)(e=>{$.current={index:e,until:Date.now()+1600},f(e)},[]),P=(0,i.useCallback)((e,t)=>{let n=$.current;if(n&&Date.now()<n.until)return void f(n.index);$.current=null;let r=t.filter(e=>null!==e.targetTurn.scrollTop);if(0===r.length)return void f(null);let i=e.scrollTop+.3*e.clientHeight;f(r.reduce((e,t)=>Math.abs((t.targetTurn.scrollTop??0)-i)<Math.abs((e.targetTurn.scrollTop??0)-i)?t:e,r[0]).index)},[]),W=(0,i.useCallback)(()=>{let e=o.current;if(!e)return;let t=e.scrollHeight-e.clientHeight,n=w.current;d(t>20),P(e,n)},[o,P]),O=(0,i.useRef)(null),F=(0,i.useCallback)(()=>{O.current||(O.current=setTimeout(()=>{O.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 M.current){let o=nT(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 c=function(e){if("assistant"!==e.role)return"";let{answerBlocks:t}=nP(e);return t.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n").trim()}(t);c&&a.assistantPreviews.push({markdown:c,element:s})}let c=i.map((e,t)=>({topRatio:0,targetTurn:e,index:t}));g(t.clientHeight),w.current=c,p(c),d(e.scrollHeight-e.clientHeight>20),P(e,c);let u=I.current,h=u?c[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;I.current=null,z(h.index);let i=.3*e.clientHeight;e.scrollTo({top:Math.max(0,n-i),behavior:"smooth"})}},150))},[z,s,o,P]);(0,i.useEffect)(()=>{let e=o.current;if(e)return e.addEventListener("scroll",W,{passive:!0}),()=>e.removeEventListener("scroll",W)},[o,W]),(0,i.useEffect)(()=>{let e=o.current;if(!e)return;let t=()=>{F(),W()},n=new ResizeObserver(t);return n.observe(e),e.firstElementChild&&n.observe(e.firstElementChild),t(),()=>{n.disconnect(),O.current&&(clearTimeout(O.current),O.current=null)}},[F,o,W]),(0,i.useEffect)(()=>{let e=setTimeout(()=>{F(),W()},50);return()=>clearTimeout(e)},[t.length,F,W]);let D=(0,i.useCallback)((e,t)=>{let n=o.current;if(!n)return;if(z(e.index),null===e.targetTurn.scrollTop){I.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})},[z,l,o]),B=(0,i.useCallback)((e,t)=>{let n=o.current;if(!n)return;let r=e.targetTurn.assistantPreviews[t]?.element;if(!r){I.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;z(e.index),n.scrollTo({top:Math.max(0,s),behavior:"smooth"})},[z,l,o]),H=(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)),c=t[a];if(!r&&Math.abs(o-c.topRatio*i)>Math.max(10,n/2))return null;return c},[]),_=(0,i.useCallback)((e,t,n)=>{let r=o.current;if(!r)return;let i=e.targetTurn.assistantPreviews[t]?.element;if(!i){I.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(),c=s.getBoundingClientRect().top-a.top+r.scrollTop-.3*r.clientHeight;z(e.index),r.scrollTo({top:Math.max(0,c),behavior:"smooth"})},[z,l,o]),U=(0,i.useCallback)(()=>{E.current&&(clearTimeout(E.current),E.current=null)},[]),K=(0,i.useCallback)(()=>{U(),v(!0)},[U]),q=(0,i.useCallback)(()=>{U(),E.current=setTimeout(()=>{E.current=null,v(!1),y(null)},250)},[U]);(0,i.useEffect)(()=>()=>U(),[U]);let Z=(0,i.useCallback)(e=>{if(!c)return;j.current=!0,K();let t=e.currentTarget.getBoundingClientRect();y(Math.max(0,Math.min(1,(e.clientY-t.top)/t.height)));let n=(e,n)=>{let r=H(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)},[H,D,K,c]),V=null===b?null:H(b),J=V?.index??null;if((0,i.useEffect)(()=>{if(!x||null===J)return;let e=C.current,t=N.current.get(J);if(!e||!t)return;let n=t.offsetTop-(e.clientHeight-t.offsetHeight)/2;e.scrollTop=Math.max(0,n)},[u,x,J]),!c)return null;let Y=Math.max(1,(L.length>0?L[L.length-1].topRatio*m:12)-12);return(0,r.jsxs)("div",{ref:k,onMouseDown:Z,onMouseEnter:K,onMouseLeave:q,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:Y,width:1,background:"var(--border)",transform:"translateX(-50%)",zIndex:0}}),L.map(e=>{let t=x&&V?.index===e.index,n=h===e.index;return(0,r.jsx)("div",{"data-minimap-node-index":e.index,"data-minimap-node-active":n?"":void 0,style:{position:"absolute",top:`${100*e.topRatio}%`,transform:"translateY(-50%)",left:0,right:0,height:Math.max(1,A),display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none",zIndex:2},children:(0,r.jsx)("div",{style:{width:8,height:8,borderRadius:2,background:n?"rgba(128,128,128,0.42)":"rgba(128,128,128,0.16)",border:`1.5px solid ${n?"rgba(128,128,128,0.95)":"rgba(128,128,128,0.58)"}`,boxShadow:n?"0 0 0 2px var(--bg-panel)":"none",transition:"transform 0.1s, background 0.1s",transform:t?"scale(1.25)":"scale(1)"}})},e.index)}),x&&u.length>0&&(0,r.jsx)("div",{ref:C,className:su().preview,"data-minimap-preview-box":"",onMouseEnter:K,onMouseDown:e=>e.stopPropagation(),onMouseMove:e=>e.stopPropagation(),children:u.map(e=>{var t;let n=J===e.index;return(0,r.jsxs)("div",{ref:t=>{t?N.current.set(e.index,t):N.current.delete(e.index)},className:su().turn,"data-minimap-preview-index":e.index,"data-located":n?"true":void 0,children:[(0,r.jsxs)("span",{className:su().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:su().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:su().content,children:[(0,r.jsx)("button",{type:"button",className:su().user,"data-minimap-preview-user":e.index,onClick:()=>{D(e,"smooth")},children:(0,r.jsx)("span",{className:su().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:su().assistant,children:[(0,r.jsx)("button",{type:"button",className:su().assistantJump,"data-minimap-preview-assistant":`${e.index}-${n}`,onClick:()=>B(e,n),"aria-label":a("chatMinimap.locateAssistant"),title:a("chatMinimap.locateAssistant"),children:"A"}),(0,r.jsx)(sg,{markdown:t.markdown,onAnswerClick:()=>B(e,n),onHeadingClick:t=>_(e,n,t)})]},n))]})]},e.index)})})]})}var sv=n(42790);function sb(e){let{text:t}=e,n=(0,i.useMemo)(()=>new sv.v().ansi_to_html(t),[t]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:n}})}function sy(e){let t,n,o,{widgets:s,children:l}=e,{t:a}=(0,eh.s)(),c=(0,i.useId)(),d=(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=d.current,e?Array.from(t,t=>{let[n,r]=t,i=e.get(n);return i&&i.length===r.length?r.some((e,t)=>e!==i[t])?n:null:i?n:null}).filter(e=>null!==e):[]);for(let[e,n]of(d.current=t,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=`${c}-trigger-${t}`,o=`${c}-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)(sb,{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"),d=`${c}-trigger-${t}`,u=`${c}-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:d,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 sj="command:";function sk(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(sj))return null;let t=e.slice(sj.length).trim();return t.length>1&&t.startsWith("/")?t:null}(n.key);if(r){let n=nk(e).replace(/\s+/g," ").trim();t.push({kind:"command",command:r,label:n||r})}else nk(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?nk(e.text):e.label).join(" "),c=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)(sb,{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)(sy,{widgets:n,children:c}):c})}function sw(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document;return"visible"!==e.visibilityState||!e.hasFocus()}function sS(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 sC(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 sN(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sE(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(!sN(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=sN(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=sN(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 s$ extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}function sI(e){return e instanceof s$&&"prompt_rejected"===e.code&&!1===e.accepted}async function sT(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 s$(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}function sM(){return globalThis.__piSessionViewCache||(globalThis.__piSessionViewCache=new Map),globalThis.__piSessionViewCache}function sR(e){try{return JSON.stringify(e).length}catch{return Number.MAX_SAFE_INTEGER}}function sL(e){let t=sM().get(e);return t?Date.now()-t.savedAt>6e5?(sM().delete(e),null):(sM().delete(e),sM().set(e,t),t):null}function sA(e){if(!e.sessionId||!e.revision)return!1;let t=sM();t.delete(e.sessionId);let n={...e,savedAt:Date.now()};return!(sR(n)>0x2000000)&&(t.set(n.sessionId,n),!function(){let e=sM();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+=sR(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-=sR(r))}}(),sM().has(n.sessionId))}function sz(e){sM().delete(e)}var sP=n(14755);let sW="pi-tool-preset";function sO(){try{return window.localStorage}catch{return null}}function sF(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 sD(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,sF(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),sF(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function sB(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 sH(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(sB).filter(Boolean)}):JSON.stringify({text:"",images:[]})}class s_ 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 sU{constructor(e){this.options=e,this.current=null,this.retry=null,this.retryGeneration=0}close(){this.stopRetrying(),this.current&&this.discard(this.current,new s_("closed"))}maintain(e){if(!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof s_?"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 s_("closed")}if(1===t.source.readyState)return;this.discard(t,new s_("closed"))}}open(e){let t,n,r;this.current&&this.discard(this.current,new s_("closed"));try{t=this.options.createSource(e)}catch(e){throw new s_("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 s_("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 s_("startup_error",e));return}this.options.onEvent(t)}},t.onerror=()=>{this.fail(a,new s_("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 sK(e){return("tool_execution_start"===e.type||"tool_execution_update"===e.type||"tool_execution_end"===e.type)&&"string"==typeof e.parentToolCallId&&""!==e.parentToolCallId}function sq(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 sZ(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sV(e,t){return e.every(e=>t.has(e.id))?e:e.filter(e=>t.has(e.id))}function sJ(e,t){return e.some(e=>e.id===t)?e.filter(e=>e.id!==t):e}function sY(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return e+t>=n-r}let sG={isStreaming:!1,streamingMessage:null};function sX(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 sQ(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"resume":return{...e,isStreaming:!0};case"snapshot":{let n=sE(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 sX(e,n.contentIndex,()=>({type:"text",text:""}));case"text_delta":return sX(e,n.contentIndex,e=>e?.type==="text"?{...e,text:e.text+n.delta}:null);case"text_end":return sX(e,n.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:n.content}));case"thinking_start":return sX(e,n.contentIndex,()=>({type:"thinking",thinking:""}));case"thinking_delta":return sX(e,n.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+n.delta}:null);case"thinking_end":return sX(e,n.contentIndex,e=>({...e?.type==="thinking"?e:{},type:"thinking",thinking:n.content}));case"toolcall_start":return sX(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 sX(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 sX(e,n.contentIndex,()=>({type:"toolCall",toolCallId:n.toolCall.id,toolName:n.toolCall.name,input:n.toolCall.arguments}));default:return e}case"end":return sG;default:return e}}function s0(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function s1(e){return e&&"auto"!==e?e:null}let s2=new Map,s4=[2e3,5e3,1e4];function s8(e){return new Promise(t=>setTimeout(t,e))}function s3(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function s5(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:s3(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:s3(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=s3(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function s6(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 s9(e){return Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)}let s7=null,le=null;function lt(e){let{label:t}=e,[n,o]=(0,i.useState)(()=>le);if((0,i.useEffect)(()=>{if(le)return;let e=!1;return(s7??=fetch("/api/app-update").then(async e=>{if(!e.ok)return null;let t=await e.json();return t.updateAvailable&&t.latestVersion&&t.releaseUrl?t:null}).then(e=>(le=e,e)).catch(()=>(s7=null,null))).then(t=>{!e&&t&&o(t)}),()=>{e=!0}},[]),!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 ln(e){let{messageCount:t,toolCallCount:n,defaultExpanded:o=!1,reveal:s=!1,children:l,t:a}=e,[c,d]=(0,i.useState)(o);(0,i.useLayoutEffect)(()=>{s&&d(!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":c||s,onClick:()=>d(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(c?"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:c?"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 ")})]}),(c||s)&&(0,r.jsx)("div",{style:{marginTop:8},children:l})]})}function lr(e){var t;let o,{session:l,searchTarget:a,onSearchTargetHandled:c,initialScrollPosition:d,onScrollPositionChange:u,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:f,newSessionContextBar:m,initialNewSessionChoices:g,onNewSessionChoicesChange:x,onAgentEnd:v,onAttentionNeeded:b,onSessionCreated:y,onSessionForked:j,modelsRefreshKey:k,chatInputRef:w,onBranchDataChange:S,onSystemPromptChange:C,onSystemToolsChange:N,onSystemInfoLoaderChange:E,onSessionStatsChange:$,onSessionStatsPanelOpen:I,onOpenSettings:T,onContextUsageChange:M,onOpenFile:R,onFilesUploaded:L,onOpenSession:A,onAskInNewChat:z,quoteSelectionEnabled:P=!1,initialPrompt:W,onInitialPromptConsumed:O,soundEnabled:F=!0,onSoundToggle:D,playDoneSound:B=()=>{},unlockAudio:H}=e,{t:_}=(0,eh.s)(),U=ew(),K=l?.relation?.kind!=="subagent",q=(0,i.useRef)(B);q.current=B;let Z=(0,i.useRef)(F);Z.current=F;let V=(0,i.useRef)(!1),J=(0,i.useCallback)(e=>{K&&Z.current&&!e.aborted&&q.current(),v?.(e)},[K,v]),Y=(0,i.useRef)(a?null:d??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:ei,entryIds:eo,historyCursor:es,hasEarlierMessages:el,streamState:ea,agentRunning:ec,bashRunning:ed,pendingBash:eu,modelNames:ep,modelList:ef,modelError:em,modelScopeWarnings:eg,modelThinkingLevels:ex,modelThinkingLevelMaps:ev,toolPreset:eb,thinkingLevel:ey,retryInfo:ej,contextUsage:ek,forkingEntryId:eC,isCompacting:eN,compactError:eE,compactResult:e$,displayModel:eT,modelSwitching:eM,sessionStats:eR,slashCommands:eL,slashCommandsLoading:eA,queuedMessages:ez,notices:eP,extensionDialog:eW,waitingExtensionDialogCount:eO,extensionCustomUi:eF,waitingExtensionCustomUiCount:eD,extensionStatuses:eB,extensionWidgets:eH,respondToExtensionUi:e_,sendExtensionCustomInput:eU,setNoticePaused:eK,addNotice:eq,isAutoModelSelection:eZ,isAutoThinkingSelection:eV,defaultModel:eJ,savedDefaultThinkingLevel:eY,agentPhase:eG,isNew:eX,editEntryId:eQ,showScrollToBottom:e0,sessionIdRef:e1,scrollContainerRef:e8,lastUserMsgRef:e3,promptAnchorActive:e5,handleSend:e6,handleAbort:e9,handleFork:e7,handleEditContent:te,cancelEdit:tt,handleModelChange:tn,handleCompact:tr,handleSteer:ti,handleFollowUp:to,handlePromptWithStreamingBehavior:ts,handleAbortCompaction:tl,dismissCompactError:ta,handleRecallQueue:tc,handleBuiltinSlashCommand:td,handleToolPresetChange:tu,handleThinkingLevelChange:tp,handleSetDefaultModel:th,handleSetDefaultThinkingLevel:tf,loadSlashCommands:tm,scrollUserMsgToTop:tg,loadContext:tx,activeLeafId:tv,scrollToBottom:tb,scrollToMessage:ty}=function(e){let{session:t,newSessionCwd:r,newSessionDraftKey:o,onAgentEnd:s,onAttentionNeeded:l,onSessionCreated:a,onSessionForked:c,modelsRefreshKey:d,onBranchDataChange:u,onSystemPromptChange:p,onSystemToolsChange:h,onSystemInfoLoaderChange:f,onSessionStatsPanelOpen:m,onOpenSettings:g}=e,x=null===t&&null!==r,v=x?e.initialNewSessionChoices??null:null,[b,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(!x),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),[E,$]=(0,i.useState)([]),[I,T]=(0,i.useState)(new Map),[M,R]=(0,i.useState)([]),[L,A]=(0,i.useState)(null),[z,P]=(0,i.useState)(!1),[W,O]=(0,i.useReducer)(sQ,sG),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)(!1),[_,U]=(0,i.useState)(null),[K,q]=(0,i.useState)({}),[Z,V]=(0,i.useState)([]),[J,Y]=(0,i.useState)(null),[G,X]=(0,i.useState)([]),[Q,ee]=(0,i.useState)({}),[et,en]=(0,i.useState)({}),[er,ei]=(0,i.useState)(()=>v?.model??null),[eo,es]=(0,i.useState)(null),[el,ea]=(0,i.useState)(sP.Q8),[ec,ed]=(0,i.useState)(()=>v?.thinkingLevel??null),[eu,ep]=(0,i.useState)(null),[eh,ef]=(0,i.useState)(null),[em,eg]=(0,i.useState)(null),[ex,ev]=(0,i.useState)(null),[eb,ey]=(0,i.useState)(null),[ej,ek]=(0,i.useState)(null),ew=(0,i.useRef)(0),eS=(0,i.useRef)(0),[eC,eN]=(0,i.useState)(null),[eE,e$]=(0,i.useState)(null),[eI,eT]=(0,i.useState)(null),[eM,eR]=(0,i.useState)(null),[eL,eA]=(0,i.useState)(null),[ez,eP]=(0,i.useState)(!1),[eW,eO]=(0,i.useState)(!1),[eF,eD]=(0,i.useState)(!0),[eB,eH]=(0,i.useState)(null),[e_,eU]=(0,i.useState)(null),[eK,eq]=(0,i.useState)(null),[eZ,eV]=(0,i.useState)(!1),[eJ,eY]=(0,i.useState)(!1),[eG,eX]=(0,i.useState)([]),[eQ,e0]=(0,i.useState)(!1),[e1,e2]=(0,i.useReducer)(s5,{visible:[],pending:[]}),[e4,e8]=(0,i.useState)(null),[e3,e5]=(0,i.useState)([]),[e6,e9]=(0,i.useState)([]),[e7,te]=(0,i.useState)([]),[tt,tn]=(0,i.useState)([]),[tr,ti]=(0,i.useState)({steering:[],followUp:[]}),to=(0,i.useRef)(null),ts=(0,i.useRef)(null),tl=(0,i.useRef)(0),ta=(0,i.useRef)(!1),tc=(0,i.useRef)(t?.id??null),td=(0,i.useRef)(t?.id??null),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)(!1),tx=(0,i.useRef)(0),tv=(0,i.useRef)(null),tb=(0,i.useRef)(!!e.deferInitialScroll),ty=(0,i.useRef)(null),tj=(0,i.useRef)(!1),tk=(0,i.useRef)(!0),tw=(0,i.useRef)(0),tS=(0,i.useRef)(null),tC=(0,i.useRef)(void 0),tN=(0,i.useRef)(void 0),tE=(0,i.useRef)(null),t$=(0,i.useRef)(null),tI=(0,i.useRef)([]),tT=(0,i.useRef)(null),tM=(0,i.useRef)(0),tR=(0,i.useRef)(!1),tL=(0,i.useRef)(v?.model??null),tA=(0,i.useRef)(v?.thinkingLevel??null),tz=(0,i.useRef)({}),tP=(0,i.useRef)(null),tW=(0,i.useRef)(0),tO=(0,i.useRef)(null),tF=(0,i.useRef)(!1),tD=(0,i.useRef)(new Map),tB=(0,i.useRef)(!0),tH=(0,i.useRef)(new Map),t_=(0,i.useRef)(null),tU=(0,i.useRef)([]),tK=(0,i.useRef)([]),tq=(0,i.useRef)(null),tZ=(0,i.useRef)(null),tV=(0,i.useRef)(!1);td.current=t?.id??null,t_.current=b,tU.current=E,tK.current=M,tq.current=C,tZ.current=L,tV.current=z,to.current||(to.current=new sU({createSource:e=>new EventSource(`/api/agent/${encodeURIComponent(e)}/events`),onEvent:e=>tv.current?.(e),shouldMaintain:e=>tB.current&&tc.current===e&&(tp.current||ta.current||td.current===e),readinessTimeoutMs:6e4,reconnectDelayMs:1e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let tJ=e.setToolPreset??ea,tY=t?.id;(0,i.useLayoutEffect)(()=>{(tY||x&&!tc.current)&&tJ(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:sO();if(!e)return sP.Q8;try{let t=e.getItem(sW);return(0,sP.sn)(t)?t:sP.Q8}catch{return sP.Q8}}())},[tY,x,tJ]);let tG=e.onNewSessionChoicesChange;(0,i.useEffect)(()=>{x&&tG?.({model:er,thinkingLevel:ec})},[x,er,ec,tG]);let tX=(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}),tw.current=t.scrollTop)},[]),tQ=eI??eM??b?.context.model??eL??null,t0=x?er??eo:tQ??(b?.context.messages.length===0?eo:null),t1=s1(b?.context.thinkingLevel&&"off"!==b.context.thinkingLevel?b.context.thinkingLevel:null),t2=x?ec??eu:em??ex??t1??(b?.context.messages.length===0?eu:null),t4=t?.id??o??void 0,t8=(0,i.useCallback)(e=>{eR(e?.model?{provider:e.model.provider,modelId:e.model.id}:null),e?.thinkingLevel!==void 0&&ev(s1(e.thinkingLevel))},[]),t3=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=tD.current.get(t);if(!e)break;t=e}return t},[]),t5=(0,i.useCallback)((t,n,r)=>{let i=n?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}}),s=t3(r);if(!tB.current&&!tR.current&&r===o)return;let l=e.chatInputRef?.current;if(l)l.restoreSubmission(t,i,s);else{let e,n;s&&(n=iQ(t,i,(e=iJ(s)??{value:"",images:[]}).value,e.images),iY(s,n))}},[o,e.chatInputRef,t3]),[t6,t9]=(0,i.useState)(()=>{let e=t?.id;return e&&!iJ(e)&&s2.delete(e),e&&s2.get(e)||null}),t7=(0,i.useCallback)(e=>{t?.id&&(e?s2.set(t.id,e):s2.delete(t.id),t9(e))},[t?.id]),ne=(0,i.useCallback)((n,r)=>{t?.id&&(e.chatInputRef?.current?.replaceMessage(n),t7(r))},[e.chatInputRef,t?.id,t7]),nt=(0,i.useCallback)(()=>t7(null),[t7]),nn=(0,i.useMemo)(()=>{if(e4)return{...e4,totalActiveMs:b?.totalActiveMs,...ej?{contextUsage:ej}:{}};let e=b?.stats,n=function(e,t,n){let r=sD(n);if(!e)return r;let i=sD(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,b?.context.messages??[],E);return 0!==n.tokens.total||0!==E.length||e?{sessionFile:b?.filePath||void 0,sessionId:tc.current??t?.id??"",sessionName:t?.name,...n,totalActiveMs:b?.totalActiveMs,...ej?{contextUsage:ej}:{}}:null},[E,e4,ej,b?.context.messages,b?.filePath,b?.totalActiveMs,b?.stats,t?.id,t?.name]),nr=(0,i.useCallback)((e,t,n,r)=>{tB.current&&tc.current===t&&tW.current===n&&!(r<=eS.current)&&(eS.current=r,e?.contextUsage!==void 0&&ek(e.contextUsage??null))},[]),ni=(0,i.useCallback)(async e=>{let t=tW.current,n=++ew.current;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();nr(i.state,e,t,n)}catch{}},[nr]),no=(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:tH.current.get(i);if(o)return await o;let s=(async()=>{let i=!1;try{t&&k(!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&&(y(null),N(null),$([]),R([]),A(null),P(!1),S(null)),sz(e),null;if(!s.ok)throw Error(`HTTP ${s.status}`);let l=await s.json();if(tc.current!==e)return null;let a=sL(e),c=!!(l.snapshotRevision&&a?.revision===l.snapshotRevision&&a.entryIds.length>=(l.context.entryIds??[]).length),d=c?tU.current:l.context.messages;if(y(c?{...l,context:{...l.context,messages:tU.current,entryIds:tK.current,oldestEntryId:tZ.current,hasMore:tV.current}}:l),N(l.leafId),c?sA({sessionId:e,revision:l.snapshotRevision,messages:tU.current,entryIds:tK.current,leafId:l.leafId,oldestEntryId:tZ.current,hasMore:tV.current,summaryTree:l.tree,thinkingLevel:l.context.thinkingLevel,model:l.context.model,stats:l.stats,totalActiveMs:l.totalActiveMs,loadedEntryIds:tK.current}):($(d),R(l.context.entryIds??[]),A(l.context.oldestEntryId),P(l.context.hasMore)),tu.current=void 0!==l.toolNames,tJ(void 0!==l.toolNames?(0,sP.YO)(l.toolNames):sP.Q8),eT(e=>tF.current?e:null),eg(null),S(null),"summary"===l.treeFormat&&l.snapshotRevision&&sA({sessionId:e,revision:l.snapshotRevision,messages:d,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&&(to.current?.close(),to.current?.maintain(e)),!n&&l.context.thinkingLevel&&"off"!==l.context.thinkingLevel&&ev(s1(l.context.thinkingLevel)),i=!0,t&&k(!1),!n)return null;try{let t=tW.current,n=++ew.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(tc.current!==e)return null;let o=i.state;return t8(o),o?(nr(o,e,t,n),void 0!==o.systemPrompt&&eN(o.systemPrompt??null),void 0!==o.extensionStatuses&&te(o.extensionStatuses??[]),void 0!==o.extensionWidgets&&tn(o.extensionWidgets??[]),void 0!==o.queuedMessages&&ti(s0(o.queuedMessages)),void 0!==o.autoCompactionEnabled&&eD(o.autoCompactionEnabled??!0)):i.running||ti({steering:[],followUp:[]}),i}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return S(String(e)),"error"}finally{t&&!i&&k(!1)}})();return r?.force||tH.current.set(i,s),s.finally(()=>{tH.current.get(i)===s&&tH.current.delete(i)}),await s},[nr,tJ,t8]),ns=(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(tc.current!==e||r?.signal?.aborted||!tB.current)return;return A(l.context.oldestEntryId),P(l.context.hasMore),y(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?($(e=>[...l.context.messages,...e]),R(e=>[...l.context.entryIds,...e])):($(l.context.messages),R(l.context.entryIds??[])),l.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),nl=(0,i.useCallback)(async e=>{try{let t=await sT(e,{type:"get_tools"});if(!t||!tB.current||tc.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return tJ(tu.current?r(t):sP.Q8),h?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[h,tJ]),na=(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=tc.current;if(x&&r&&i&&!tR.current&&(tR.current=!0,o)){if(o!==i){tD.current.set(o,i);let t=e.chatInputRef?.current;t?t.rekeyDraft(o,i):i0(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]),nc=(0,i.useCallback)(async()=>{if(tc.current||!x||!r)return tc.current;if(t$.current)return t$.current;let e=(async()=>{let e=tL.current,t=tA.current;e&&eA(e);let n=(0,sP.xG)(el);tu.current=void 0!==n;let i=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r,type:"ensure_session",...void 0!==n?{toolNames:n}:{},...e?{provider:e.provider,modelId:e.modelId}:{},...t?{thinkingLevel:t}:{}})});if(!i.ok){let e=await i.json().catch(()=>null);throw Error("string"==typeof e?.error?e.error:`HTTP ${i.status}`)}let o=await i.json(),s=o.sessionId;return tc.current=s,o.model&&tL.current===e&&(eA(o.model),e||es(o.model)),o.thinkingLevel&&tA.current===t&&(ev(s1(o.thinkingLevel)),t||ep(s1(o.thinkingLevel))),s})();t$.current=e;try{return await e}finally{t$.current=null}},[x,r,el]),nd=(0,i.useCallback)(async()=>{let e=tc.current??await nc();if(!e)return;let[t]=await Promise.all([sT(e,{type:"get_state"}),nl(e)]);tB.current&&tc.current===e&&(t8(t),eN(t.systemPrompt??""))},[nc,nl,t8]),nu=(0,i.useCallback)(e=>{tI.current=e,eX(e)},[]),np=(0,i.useCallback)(()=>{tM.current+=1,tT.current=null,nu([])},[nu]),nh=(0,i.useCallback)(()=>{let e=++tM.current,t=(async()=>{let t=tc.current??await nc();if(!t)return tM.current===e&&nu([]),[];e0(!0);try{let n=await sT(t,{type:"get_commands"}),r=n?.commands??[];return tM.current===e&&nu(r),r}catch(t){return console.error("Failed to load slash commands:",t),tM.current===e&&nu([]),null}finally{tM.current!==e&&tT.current||e0(!1)}})();tT.current=t;let n=()=>{tT.current===t&&(tT.current=null)};return t.then(n,n),t},[nc,nu]),nf=(0,i.useCallback)(async()=>await nh()??[],[nh]),nm=(0,i.useCallback)(async()=>{let e=tT.current,t=tI.current;return!e&&t.length>0?t:await (e??nh()).catch(()=>null)??(t.length>0?t:null)},[nh]),ng=(0,i.useCallback)(()=>{tl.current+=1,ta.current=!1,ts.current&&(clearTimeout(ts.current),ts.current=null)},[]),nx=(0,i.useCallback)(()=>{to.current?.close()},[]),nv=(0,i.useCallback)(e=>to.current.ensureConnected(e),[]),nb=(0,i.useCallback)(e=>{to.current.maintain(e)},[]);(0,i.useEffect)(()=>{let e=t?.id;if(e)return tB.current=!0,nb(e),()=>{tc.current===e&&to.current?.close()}},[nb,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||tc.current!==e||td.current!==e||(nx(),nb(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)}},[nx,nb,t?.id]);let ny=(0,i.useCallback)(async(e,t)=>{let n=tc.current;if(e5(t=>sJ(t,e.id)),n)try{await sT(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e)}},[]),nj=(0,i.useCallback)(async(e,t)=>{let n=tc.current;if(n)try{await sT(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),nk=(0,i.useCallback)(e=>{let t=e.message.trim();t&&e2({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"}})},[]),nw=(0,i.useCallback)(t=>{switch(sS(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":nk({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":te(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":tn(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":e9(e=>{let n;return t.closed?sJ(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)})}},[nk,l,e.chatInputRef]),nS=(0,i.useCallback)(()=>{let e=tp.current;return tp.current=!1,D(!1),eq(null),ey(null),T(new Map),O({type:"end"}),e},[]),nC=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return tm.current!==e&&(tm.current=e,s?.({aborted:t}),!0)},[s]),nN=(0,i.useCallback)(e=>{if(td.current===e)return void ng();ng(),ta.current=!0;let t=tl.current,n=async()=>{if(t===tl.current&&tc.current===e&&ta.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!==tl.current||tc.current!==e||!ta.current)return;let o=i.state;if(t8(o),i.running&&o&&(o.isStreaming||o.isPromptRunning)){ta.current=!1,ts.current=null,th.current=!!o?.isStreaming,tf.current=!!o?.isPromptRunning,tp.current=!0,D(!0),eq(o?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(i.running&&o?.isCompacting){eO(!0),ts.current=setTimeout(()=>void n(),600);return}ta.current=!1,ts.current=null,nx()}catch{if(t!==tl.current||tc.current!==e||!ta.current)return;ts.current=setTimeout(()=>void n(),600)}};ts.current=setTimeout(()=>void n(),3e4)},[ng,nx,t8]),nE=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tc.current,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tW.current;if(tW.current===t)try{e&&await no(e)}finally{if(tW.current!==t)return;let n=tf.current,r=th.current;tf.current=!1,th.current=!1,tO.current=null;let i=nS();n?nC(t):r&&i&&s?.({aborted:!1}),e&&nN(e)}},[no,nC,s,nN,nS]),n$=(0,i.useCallback)(async(e,t)=>{await s8(800);let n=Date.now();for(;tp.current&&Date.now()-n<2e4;){if(void 0!==t&&tW.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(t8(i),!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await nE(e,t)}}catch{}await s8(600)}},[nE,t8]),nI=(0,i.useCallback)(async e=>{let t=tx.current+1;for(tx.current=t;tg.current&&tx.current===t&&tc.current===e;){await s8(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(t8(r.state),r.state?.isBashRunning)continue;if(await no(e),tx.current!==t||tc.current!==e)return;tg.current=!1,H(!1),U(null);return}catch{}}},[no,t8]),nT=(0,i.useCallback)(async e=>{if(!tp.current||tc.current!==e)return;let t=tW.current,n=++ew.current;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(tc.current!==e||tW.current!==t)return;let o=i.state;if(nr(o,e,t,n),t8(o),eO(o?.isCompacting??!1),eD(o?.autoCompactionEnabled??!0),ti(s0(o?.queuedMessages)),i.running&&o&&(o.isStreaming||o.isPromptRunning||o.isCompacting)){th.current=!!o.isStreaming,tf.current=!!o.isPromptRunning;return}if(!tp.current)return;o&&(void 0!==o.systemPrompt&&eN(o.systemPrompt??null),void 0!==o.extensionStatuses&&te(o.extensionStatuses??[]),void 0!==o.extensionWidgets&&tn(o.extensionWidgets??[])),await nE(e,t)}catch{}},[nr,nE,t8]);(0,i.useEffect)(()=>{if(!F)return;let e=()=>{let e=tc.current;e&&nT(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)}},[F,nT]),(0,i.useEffect)(()=>{tp.current=F},[F]),tv.current=(0,i.useCallback)(e=>{switch(e.type){case"connected":if(O({type:"end"}),Array.isArray(e.pendingExtensionUiIds)){let t=new Set(e.pendingExtensionUiIds);e5(e=>sV(e,t)),e9(e=>sV(e,t))}!0===e.isStreaming&&(ng(),th.current=!0,tp.current=!0,D(!0),eq({kind:"waiting_model"})),tc.current&&ni(tc.current);break;case"agent_start":ng(),th.current=!0,tp.current=!0,D(!0),eq({kind:"waiting_model"}),ey(null),O({type:"start"});break;case"agent_end":if(!tp.current)break;if(eq(null),ey(null),O({type:"end"}),tc.current){let e=tc.current,t=tW.current,n=++ew.current;no(e),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(r=>{r&&tB.current&&tc.current===e&&tW.current===t&&(t8(r.state),nr(r.state,e,t,n),r.state?.systemPrompt!==void 0&&eN(r.state.systemPrompt??null),r.state?.extensionStatuses!==void 0&&te(r.state.extensionStatuses??[]),r.state?.extensionWidgets!==void 0&&tn(r.state.extensionWidgets??[]),ti(s0(r.state?.queuedMessages)))}).catch(()=>{})}break;case"agent_settled":{let t=th.current;if(th.current=!1,!t||tf.current)break;let n=tc.current,r=nS();eO(!1),n&&(no(n),nN(n)),r&&s?.({aborted:!0===e.aborted});break}case"prompt_done":{let t=tW.current,n=tf.current;tf.current=!1,tO.current=null;let r=nC(t,!0===e.aborted);if(!n&&!r)break;let i=tc.current;i&&no(i),!th.current&&(nS(),i&&nN(i))}break;case"prompt_error":nk({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":nk({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":if(!tp.current||sq(e))break;if("message_start"===e.type){let t=e.message;if(t?.role==="user")break;t?.role==="assistant"?(O({type:"snapshot",message:t}),t.content.length>0&&eq(null)):t&&eq(null)}else{let t=e.assistantMessageEvent;t&&(O({type:"delta",event:t}),"toolcall_start"!==t.type&&"toolcall_delta"!==t.type&&eq(null))}!tj.current&&tk.current&&null===tS.current&&(tS.current=requestAnimationFrame(()=>{tS.current=null,tk.current&&tX("auto")}));break;case"message_end":{if(!tp.current||sq(e))break;let t=e.message;if(t&&"user"===t.role){let e=sE(t),n=sH(e),r=tO.current;tO.current=null,$(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&sH(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]})}else if(t&&($(e=>[...e,sE(t)]),"assistant"===t.role)){let e=tc.current;e&&ni(e)}O({type:"end"}),eq({kind:"waiting_model"});break}case"tool_execution_start":{if(sK(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(sK(e))break;let t=e.toolCallId,n=e.toolName,r=e.partialResult,i=r?.content;("bash"===n||"powershell"===n||n===r7)&&Array.isArray(i)&&T(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===r7?function(e){if(!it(e))return null;let{calls:t}=ii(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(!sZ(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>sZ(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(sK(e))break;let t=e.toolCallId;T(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":ti({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":ey({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":ey(null);break;case"auto_compaction_start":case"compaction_start":eO(!0),eH(null),eU(null);break;case"auto_compaction_end":case"compaction_end":eO(!1),e.errorMessage?(eH(e.errorMessage),eU(null)):!e.aborted&&(eU(s6(e.result,e.reason??"auto")),tc.current&&no(tc.current));break;case"extension_ui_request":nw(e);break;case"extension_ui_closed":e5(t=>sJ(t,e.id))}},[nk,nr,ng,nw,no,nC,s,ni,nN,tX,nS,t8]);let nM=(0,i.useCallback)(async(e,n)=>{let i=e.trim();if(!i&&!n?.length)return;if(tp.current||tg.current)return void t5(e,n,t4);if(t6&&(t7(null),!await tN.current?.(t6))){t7(t6),t5(e,n,t4);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 tC.current?.(r,t):void t5(e,n,t4)}let s=tW.current+1;ng(),tf.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()};$(e=>[...e,a]),tO.current=sH(a),tW.current=s,tp.current=!0,D(!0),eq(o?{kind:"running_command"}:{kind:"waiting_model"}),O({type:"start"}),tj.current=!0,eV(!0);let c=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),d=null,u=!1;try{if(x&&r){let t=tc.current??await t$.current,n=t??await nc();if(!n)throw Error("Unable to create a session for the prompt");d=n,er&&(eA(er),t&&await sT(n,{type:"set_model",provider:er.provider,modelId:er.modelId})),await nv(n),u=!0,await sT(n,{type:"prompt",message:e,...c?.length?{images:c}:{}}),na(1,e)}else if(t)d=t.id,await nv(t.id),u=!0,await sT(t.id,{type:"prompt",message:e,...c?.length?{images:c}:{}});else throw Error("No active session for the prompt");o&&d&&n$(d,s)}catch(t){if(console.error("Failed to send message:",t),!(!u||sI(t))&&d)return void n$(d,s);if(tf.current=!1,$(e=>{let t=e.lastIndexOf(a);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),nk({type:"error",message:t instanceof Error?t.message:String(t)}),t5(e,n,t4),tO.current=null,d)return void nT(d);tp.current=!1,nx(),D(!1),eq(null),O({type:"end"})}},[x,r,er,t,nc,nv,na,n$,nk,ng,nx,t4,nT,t5,t6,t7]);tC.current=(0,i.useCallback)(async(e,n)=>{if(tp.current||tg.current)return;let r=`${n?"!!":"!"}${e}`;tg.current=!0,U({command:e,excludeFromContext:n}),H(!0);try{let i=tc.current??t?.id??await nc();if(!i)throw Error("Unable to create a session for the shell command");await sT(i,{type:"bash",command:e,excludeFromContext:n}),await no(i),na(1,r)}catch(e){console.error("Failed to execute shell command:",e),nk({type:"error",message:e instanceof Error?e.message:String(e)}),t5(r,void 0,t4)}finally{tg.current=!1,U(null),H(!1)}},[nk,t4,nc,no,na,t5,t]);let nR=(0,i.useCallback)(async()=>{let e=tc.current;if(e){if(tg.current){try{await sT(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await sT(e,{type:"abort"})}catch(e){console.error("Failed to abort:",e)}}},[]),nL=(0,i.useCallback)(async e=>{if(tg.current)return;let t=tc.current;if(t){e$(e);try{let{cancelled:n,newSessionId:r}=await sT(t,{type:"fork",entryId:e})??{};!n&&r&&c?.(r)}catch(e){console.error("Fork failed:",e),nk({type:"error",message:e instanceof Error?e.message:String(e)})}finally{e$(null)}}},[nk,c]),nA=(0,i.useCallback)(async e=>{if(tg.current)return!1;let t=tc.current;if(!t)return!1;try{let n=await sT(t,{type:"navigate_tree",targetId:e});if(n?.cancelled||tc.current!==t)return!1;return await no(t),tc.current===t}catch(e){return console.error("Failed to navigate:",e),!1}},[no]);tN.current=nA;let nz=(0,i.useCallback)(async e=>{if(tg.current||tp.current||eW)return;N(e);let t=tc.current;t&&(await ns(t,e),e&&sT(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[eW,ns]),nP=(0,i.useCallback)(async(e,t)=>{if(x){let n={provider:e,modelId:t};tL.current=n,ei(n),eA(n),null===tA.current&&ep(s1(tz.current[`${e}/${t}`])??tP.current);let r=tc.current??await t$.current;if(!r)return;try{await sT(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tc.current;if(n&&!tF.current){tF.current=!0,eT({provider:e,modelId:t}),eP(!0);try{let r=await sT(n,{type:"set_model",provider:e,modelId:t});eR({provider:r.provider,modelId:r.id}),tF.current=!1,await no(n)}catch(e){console.error("Failed to set model:",e),tF.current=!1,eT(eI),nk({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await no(n,!1,!0)}finally{tF.current=!1,eP(!1)}}},[nk,eI,x,no,ei]),nW=(0,i.useCallback)(async()=>{let e=tc.current;if(e&&!eW){eO(!0),eH(null),eU(null);try{let t=await sT(e,{type:"compact"});eU(s6(t,"manual")),await no(e,!0)}catch(e){eH(e instanceof Error?e.message:String(e)),eU(null)}finally{eO(!1)}}},[eW,no]),nO=(0,i.useCallback)(()=>eH(null),[]),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||Y(t instanceof Error?t.message:String(t)),t}q(n.models),Y(n.modelError??null),X(n.modelScopeWarnings??[]),ee(n.thinkingLevels??{}),en(n.thinkingLevelMaps??{});let s=n.modelList??[];V(s);let l=n.defaultModel?s.find(e=>e.id===n.defaultModel?.modelId&&e.provider===n.defaultModel?.provider):void 0;if(es(l?{provider:l.provider,modelId:l.id}:null),tz.current=n.thinkingLevelPins??{},tP.current=s1(n.defaultThinkingLevel),ef(s1(n.savedDefaultThinkingLevel)),x&&!tc.current){let e=tL.current,t=e&&(0===s.length||s.some(t=>t.provider===e.provider&&t.id===e.modelId));e&&!t&&(tL.current=null,ei(null));let r=t?e:l&&{provider:l.provider,modelId:l.id},i=r&&n.thinkingLevelPins?.[`${r.provider}/${r.modelId}`];null===tA.current&&ep(s1(i)??tP.current)}},[x,r,t?.cwd]),nD=(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]),nB=(0,i.useCallback)(()=>{nF().catch(()=>{})},[nF]),nH=(0,i.useCallback)(async(e,t)=>{try{await nD({provider:e,modelId:t})}catch(e){nk({type:"error",message:`Failed to save default model: ${e instanceof Error?e.message:String(e)}`});return}nk({type:"success",message:`Default model: ${e}/${t}`}),es({provider:e,modelId:t}),(t0?.provider!==e||t0?.modelId!==t)&&await nP(e,t),nB()},[nk,t0,nP,nB,nD]),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=tc.current??await nc(),s=e=>(e.handled&&(e.error?nk({type:"error",message:e.error}):e.action||nk({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!o||eW)return s({handled:!0,error:"No active session to compact"});eO(!0),eH(null),eU(null);let e=await sT(o,{type:"compact",...i?{customInstructions:i}:{}});return eU(s6(e,"manual")),await no(o,!0)&&na(),s({handled:!0,message:"Compacted context"})}case"auto-compact":{if(!o)return s({handled:!0,error:"No active session"});let e=await sT(o,{type:"get_state"}),t=!(e?.autoCompactionEnabled??!0);return await sT(o,{type:"set_auto_compaction",enabled:t}),eD(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 sT(o,{type:"reload"}),await Promise.all([no(o,!1,!0),nl(o),nf(),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 sT(o,{type:"set_session_name",name:i}),await no(o)&&na(),s({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!o)return s({handled:!0,error:"No active session"});let e=await sT(o,{type:"get_session_stats"});return e&&e8(e),m?.(),s({handled:!0,action:"openSessionStats"})}case"mcp":{if(i||!g)return{handled:!1};let e=await nm();if(!e||!(e.some(i5)||!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 sT(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(tp.current||tg.current)return s({handled:!0,error:"Cannot clone while the session is running"});let e=await sT(o,{type:"clone",leafId:C});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 c?.(e.newSessionId),t}default:return{handled:!1}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&eO(!1)}},[C,nk,nc,eW,nF,no,nf,nl,na,g,c,m,nm]),nU=(0,i.useCallback)(async(e,t,n)=>{let r=tc.current;if(t6)return void t5(e,n,t4);if(!r){t5(e,n,t4),nk({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 sT(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){console.error("Failed to submit streaming prompt:",t),sI(t)&&t5(e,n,t4),nk({type:"error",message:t instanceof Error?t.message:String(t)})}},[nk,t4,t6,t5]),nK=(0,i.useCallback)(async(e,t)=>{await nU(e,"steer",t)},[nU]),nq=(0,i.useCallback)(async(e,t,n)=>{await nU(e,t,n)},[nU]),nZ=(0,i.useCallback)(async(e,t)=>{await nU(e,"followUp",t)},[nU]),nV=(0,i.useCallback)(async()=>{let e=tc.current;if(e)try{await sT(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),nJ=(0,i.useCallback)(async()=>{let t=tc.current;if(t)try{let n=await sT(t,{type:"clear_queue"});ti({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),nk({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,nk]),nY=(0,i.useCallback)(async e=>{if("auto"===e){tA.current=null,ed(null),eg(null);return}x?(tA.current=e,ed(e)):eg(e);let t=tc.current??await t$.current;if(t)try{await sT(t,{type:"set_thinking_level",level:e}),tB.current&&tc.current===t&&(ev(e),eg(null))}catch(e){console.error("Failed to set thinking level:",e),eg(null)}},[x]),nG=(0,i.useCallback)(async e=>{try{await nD({thinkingLevel:e})}catch(e){nk({type:"error",message:`Failed to save default reasoning level: ${e instanceof Error?e.message:String(e)}`});return}nk({type:"success",message:`Default reasoning level: ${e}`}),ef(e),t2!==e&&await nY(e),nB()},[nk,t2,nY,nB,nD]),nX=(0,i.useCallback)(async e=>{let t=(0,sP.xG)(e);!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sO();if(t)try{t.setItem(sW,e)}catch{}}(e),tJ(e);let n=tc.current??await t$.current;if(!n){tu.current=void 0!==t;return}try{let e=await sT(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});tu.current=void 0!==t;let r=e?.sessionId??n;(r!==n||e?.recreated)&&(ng(),nx(),e5([]),e9([]),tc.current=r,e?.recreated&&td.current===r&&nb(r)),np(),te([]),tn([]);let[i]=await Promise.all([sT(r,{type:"get_state"}),nl(r)]);tB.current&&tc.current===r&&(eN(i.systemPrompt??""),t8(i))}catch(e){console.error("Failed to set tools:",e)}},[ng,np,nx,nl,nb,tJ,t8]),nQ=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=tE.current;n&&(null!==tS.current&&(cancelAnimationFrame(tS.current),tS.current=null),tb.current=!0,tj.current=!1,tk.current=!1,eV(!1),n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),tw.current=n.scrollTop)},[]),n0=(0,i.useCallback)(()=>{let e=tE.current,t=ty.current;if(!e||!t)return;let n=Math.min(Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop-16),Math.max(0,e.scrollHeight-e.clientHeight));null!==tS.current&&(cancelAnimationFrame(tS.current),tS.current=null),tk.current=!0,tw.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=tp.current,o=tk.current,s=function(e,t,n,r,i){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:96;return!!sY(n,r,i)||!(n<t)&&(!!(!e&&n>t&&sY(n,r,i,o))||e)}(o,tw.current,t,n,r,i?96:8);tk.current=s,tw.current=t;let l=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return!(n<=t)&&!sY(e,t,n,r)}(t,n,r);eY(e=>e===l?e:l),!o&&s&&i?tX("auto"):s||null===tS.current||(cancelAnimationFrame(tS.current),tS.current=null)}},[tX]);(0,i.useEffect)(()=>{if(tB.current=!0,eS.current=ew.current,t){tc.current=t.id;let e=sL(t.id);e&&(y({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}),N(e.leafId),$(e.messages),R(e.entryIds),A(e.oldestEntryId),P(e.hasMore),S(null),k(!1)),no(t.id,!e,!0,{force:!0}).then(e=>{e?.running&&(nl(t.id),(e.state?.isStreaming||e.state?.isPromptRunning)&&(th.current=!!e.state.isStreaming,tf.current=!!e.state.isPromptRunning,tp.current=!0,D(!0),eq(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),O({type:"resume"}),!e.state.isStreaming&&e.state.isPromptRunning&&n$(t.id)),e.state?.isBashRunning&&(tg.current=!0,H(!0),nI(t.id))),e?.state&&(void 0!==e.state.isCompacting&&eO(e.state.isCompacting),void 0!==e.state.systemPrompt&&eN(e.state.systemPrompt??null),void 0!==e.state.extensionStatuses&&te(e.state.extensionStatuses??[]),void 0!==e.state.extensionWidgets&&tn(e.state.extensionWidgets??[]),void 0!==e.state.queuedMessages&&ti(s0(e.state.queuedMessages)))})}return()=>{tB.current=!1;let e=x?o:null;e&&queueMicrotask(()=>{tB.current||tR.current||iG(e)});let t=tc.current,n=t_.current;if(t&&n&&n.sessionId===t&&n.snapshotRevision){let e=sL(t),r=tK.current;!e||r.every(t=>e.entryIds.includes(t)||(e.loadedEntryIds??[]).includes(t))?sA({sessionId:t,revision:n.snapshotRevision,messages:tU.current,entryIds:tK.current,leafId:tq.current,oldestEntryId:tZ.current,hasMore:tV.current,summaryTree:n.tree,thinkingLevel:n.context.thinkingLevel,model:n.context.model,stats:n.stats,totalActiveMs:n.totalActiveMs,loadedEntryIds:tK.current}):sz(t)}null!==tS.current&&(cancelAnimationFrame(tS.current),tS.current=null),tx.current+=1,ng(),nx()}},[]),(0,i.useEffect)(()=>{p?.(eC)},[eC,p]),(0,i.useEffect)(()=>(f?.(nd),()=>f?.(null)),[nd,f]);let n2=F||B||eW;(0,i.useEffect)(()=>{u&&u(b?.tree??[],C,nz,n2)},[b?.tree,C,nz,n2,u]),(0,i.useEffect)(()=>{let e=tE.current;if(e)return tw.current=e.scrollTop,e.addEventListener("scroll",n1,{passive:!0}),()=>{e.removeEventListener("scroll",n1)}},[E.length,j,n1]),(0,i.useEffect)(()=>{F||eV(!1)},[F]),(0,i.useLayoutEffect)(()=>{E.length>0&&(tj.current?(tj.current=!1,tb.current=!0,n0()):tb.current?!tp.current&&tk.current&&tX("auto"):(tb.current=!0,tX("instant")))},[E.length,F,tX,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>=s4.length||(await s8(s4[t]),e.signal.aborted))return}})(),()=>e.abort()},[nF,d]),(0,i.useEffect)(()=>{if(!e_)return;let e=setTimeout(()=>eU(null),6e3);return()=>clearTimeout(e)},[e_]);let[n4,n8]=(0,i.useState)(null),n3=(0,i.useRef)(5e3),n5=(0,i.useRef)(null),n6=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(0===e1.visible.length){n6.current=null;return}let e=e1.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{e2({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=e1.visible[0];if(!t||(n6.current!==t.id&&(n6.current=t.id,n3.current=5e3),e1.visible.some(e=>e.id===n4)))return;n5.current=Date.now();let n=setTimeout(()=>{e2({type:"mark_oldest_exiting"})},n3.current);return()=>{clearTimeout(n),null!==n5.current&&(n3.current=Math.max(0,n3.current-(Date.now()-n5.current)),n5.current=null)}},[e1.visible,n4]),(0,i.useEffect)(()=>{e8(null)},[E.length,ej?.tokens,ej?.percent,ej?.contextWindow]);let n9=t2??"auto",n7=e3[0]??null,re=Math.max(0,e3.length-1),rt=e6[0]??null,rn=Math.max(0,e6.length-1);return{data:b,loading:j,error:w,activeLeafId:C,messages:E,activeToolResults:I,entryIds:M,historyCursor:L,hasEarlierMessages:z,streamState:W,agentRunning:F,modelNames:K,modelList:Z,modelError:J,modelScopeWarnings:G,modelThinkingLevels:Q,modelThinkingLevelMaps:et,newSessionModel:er,toolPreset:el,thinkingLevel:n9,retryInfo:eb,contextUsage:ej,systemPrompt:eC,forkingEntryId:eE,isCompacting:eW,compactError:eB,compactResult:e_,currentModel:tQ,displayModel:t0,modelSwitching:ez,sessionStats:nn,autoCompactionEnabled:eF,slashCommands:eG,slashCommandsLoading:eQ,queuedMessages:tr,notices:e1.visible,extensionDialog:n7,waitingExtensionDialogCount:re,extensionCustomUi:rt,waitingExtensionCustomUiCount:rn,extensionStatuses:e7,extensionWidgets:tt,respondToExtensionUi:ny,sendExtensionCustomInput:nj,isAutoModelSelection:x&&null===er,isAutoThinkingSelection:x&&null===ec,defaultModel:eo,savedDefaultThinkingLevel:eh,agentPhase:eK,isNew:x,editEntryId:t6,promptAnchorActive:eZ,showScrollToBottom:eJ,sessionIdRef:tc,scrollContainerRef:tE,lastUserMsgRef:ty,pendingScrollToUserRef:tj,initialScrollDoneRef:tb,handleSend:nM,handleAbort:nR,handleFork:nL,handleNavigate:nA,handleModelChange:nP,handleCompact:nW,handleSteer:nK,handleFollowUp:nZ,handlePromptWithStreamingBehavior:nq,handleAbortCompaction:nV,dismissCompactError:nO,handleRecallQueue:nJ,handleBuiltinSlashCommand:n_,handleEditContent:ne,cancelEdit:t6?nt:void 0,addNotice:nk,setNoticePaused:n8,handleToolPresetChange:nX,handleThinkingLevelChange:nY,handleSetDefaultModel:nH,handleSetDefaultThinkingLevel:nG,loadTools:nl,loadSlashCommands:nf,setActiveLeafId:N,setData:y,setMessages:$,loadContext:ns,scrollToBottom:tX,scrollUserMsgToTop:n0,scrollToMessage:nQ,dispatch:O,setAgentRunning:D,setForkingEntryId:e$,bashRunning:B,pendingBash:_,handleAgentEventRef:tv}}({session:l,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:f,initialNewSessionChoices:g,onNewSessionChoicesChange:x,onAgentEnd:J,onAttentionNeeded:b,onSessionCreated:y,onSessionForked:j,modelsRefreshKey:k,chatInputRef:w,onBranchDataChange:S,onSystemPromptChange:C,onSystemToolsChange:N,onSystemInfoLoaderChange:E,onSessionStatsPanelOpen:I,onOpenSettings:T,deferInitialScroll:!!G}),tj=ec||ed,[tk,tw]=(0,i.useState)(null),[tS,tC]=(0,i.useState)(!1),[tN,tE]=(0,i.useState)(!1),[t$,tI]=(0,i.useState)(null),tT=(0,i.useRef)(null),tM=(0,i.useRef)(null),tR=(0,i.useCallback)(()=>{tw(null),tC(!1),tI(null)},[]);(0,i.useEffect)(()=>{P||tR()},[P,tR]);let tL=(0,i.useCallback)(()=>{if(!P||tS)return;let e=window.getSelection(),t=e?.rangeCount?e.getRangeAt(0):null,n=tB.current;if(!e||e.isCollapsed||!t||!n||!n.contains(t.commonAncestorContainer))return void tw(null);let r=e.toString().trim();if(!r)return void tw(null);let i=t.getBoundingClientRect(),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);tw({text:r,top:Math.min(window.innerHeight-44,i.bottom+8),left:Math.max(64,Math.min(window.innerWidth-64,i.left+i.width/2)),sourceEntryId:o})},[P,tS]);(0,i.useEffect)(()=>{tS&&tk&&tM.current?.insertIfEmpty(n1(tk.text,_("chat.quoteIntro"),_("chat.quoteQuestion")))},[tS,tk,_]),(0,i.useLayoutEffect)(()=>{let e=tT.current;if(!e||!tk)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(tk.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(tk.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)}},[tk,tS,t$]),(0,i.useEffect)(()=>{if(!tk)return;let e=e=>{tS||tT.current?.contains(e.target)||tR()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),tN||tR())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[tk,tS,tN,tR]);let tA=(0,i.useCallback)(()=>{tk&&(w?.current?.insertText(n1(tk.text,_("chat.quoteIntro"),_("chat.quoteQuestion"))),window.getSelection()?.removeAllRanges(),tR())},[w,tk,tR,_]),tz=(0,i.useCallback)(async e=>{let t=e1.current??l?.id;if(!tN&&e.trim()&&tk?.sourceEntryId&&t&&z){tE(!0),tI(null),H?.();try{await z(e,t,tk.sourceEntryId),tR()}catch(t){tM.current?.restoreSubmission(e),tI(t instanceof Error?t.message:String(t))}finally{tE(!1)}}},[z,tk,tN,l?.id,e1,tR,H]),tP=(0,i.useRef)(!1);(0,i.useEffect)(()=>{et||en||!W||tP.current||(tP.current=!0,O?.(),e6(W))},[W,et,en,e6,O]),(0,i.useEffect)(()=>{let e=!!eW&&!V.current;V.current=!!eW,K&&e&&q.current()},[K,eW]),(0,i.useEffect)(()=>{s=tj?e9:null},[tj,e9]);let[tW,tO]=(0,i.useState)(50),[tF,tD]=(0,i.useState)(null),tB=(0,i.useRef)(null),tH=(0,i.useRef)(null),t_=(0,i.useRef)(!1),tU=(0,i.useRef)(!1),tK=(0,i.useRef)(G);tK.current=G;let[tq,tZ]=(0,i.useState)(null),tV=er[eo.indexOf(tq?.entryId??"")],tJ=tV?.role==="assistant"?tq?.blockIndex===void 0?tV.content.find(e=>"text"===e.type):tV.content[tq.blockIndex]:void 0,tY=(0,i.useRef)({entryIds:eo,historyCursor:es,hasEarlierMessages:el});tY.current={entryIds:eo,historyCursor:es,hasEarlierMessages:el};let tG=(0,i.useRef)(null),tX=(0,i.useCallback)(async(e,t,n)=>{tG.current=t;let r=await tx(e,tv,t,n);return r||tG.current!==t||(tG.current=null),r},[tv,tx]);(0,i.useEffect)(()=>{es!==tG.current&&(tG.current=null)},[es]),(0,i.useLayoutEffect)(()=>{let e=l?.id,t=e8.current,n=tB.current;if(e&&u&&t&&n)return()=>{if(tK.current)return;if(sY(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:tY.current.historyCursor})}},[et,u,e8,l?.id]),(0,i.useEffect)(()=>{a&&X(null)},[a]),(0,i.useEffect)(()=>{let e=l?.id;if(!G||!e||et||a||tU.current)return;tU.current=!0;let t=new AbortController;return(async()=>{let n=tY.current;if(n.entryIds.includes(G.anchorEntryId)){tO(e=>Math.max(e,2*n.entryIds.length)),ee(!0);return}t_.current=!0;let r=n.historyCursor,i=n.hasEarlierMessages;try{for(;i&&r&&!t.signal.aborted;){let n=await tX(e,r,{signal:t.signal});if(t.signal.aborted)return;if(!n){tb("instant"),X(null);return}if(tO(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||(tb("instant"),X(null))}finally{t_.current=!1}})(),()=>{t.abort(),X(null)}},[tv,tX,et,G,tb,a,l?.id]),(0,i.useLayoutEffect)(()=>{let e=tB.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){ty(t,G.anchorOffset),X(null);return}Q&&(tb("instant"),X(null))},[eo,G,Q,tb,ty,a,tW]),(0,i.useEffect)(()=>{if(!a||et)return;let e=new AbortController;return(async()=>{let t=tY.current,n=t.entryIds.includes(a.entryId);if(!n&&!tj&&t.hasEarlierMessages&&t.historyCursor&&!t_.current){t_.current=!0;let r=e8.current;r&&(tH.current=r.scrollHeight-r.scrollTop);let i=await tX(a.sessionId,t.historyCursor,{tail:200,signal:e.signal});t_.current=!1,n=!!i?.entryIds.includes(a.entryId)}e.signal.aborted||(n?(tH.current=null,tO(e=>Math.max(e,(tY.current.entryIds.length+200)*2)),tZ(a)):c?.(a))})(),()=>e.abort()},[a,et,tj,tX,c,e8]),(0,i.useLayoutEffect)(()=>{if(!tq||tq!==a)return;let e=`[data-entry-id="${CSS.escape(tq.entryId)}"]`,t=e8.current?.querySelector(tV?.role==="user"?e:`${e} [data-search-target]`);t&&(ty(t),t.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500})),tZ(null),c?.(tq)},[tq,a,tV,e8,ty,c]),(0,i.useEffect)(()=>{let e=e8.current;if(!tF||!e)return;let t=new IntersectionObserver(t=>{if(!t[0]?.isIntersecting||t_.current)return;if(!el){tH.current=e.scrollHeight-e.scrollTop,tO(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50;return e+t})(e));return}if(!es||es===tG.current)return;let n=l?.id??e1.current;n&&(t_.current=!0,tH.current=e.scrollHeight-e.scrollTop,tX(n,es).finally(()=>{t_.current=!1}))},{root:e,threshold:0});return t.observe(tF),()=>t.disconnect()},[tF,tW,es,el,l,tX,e1,e8]),(0,i.useEffect)(()=>{tO(e=>Math.max(e,er.length))},[er.length]),(0,i.useEffect)(()=>{if(null==tH.current)return;let e=e8.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-tH.current),tH.current=null}},[tW,e8]);let tQ=eR?[eR.sessionId,eR.sessionFile??"",eR.sessionName??"",eR.userMessages,eR.assistantMessages,eR.toolCalls,eR.toolResults,eR.totalMessages,eR.tokens.input,eR.tokens.output,eR.tokens.cacheRead,eR.tokens.cacheWrite,eR.tokens.total,eR.cost??0,eR.totalActiveMs??0].join("|"):null,t0=(0,i.useRef)(eR);t0.current=eR,(0,i.useEffect)(()=>{$?.(t0.current)},[tQ,$]),(0,i.useEffect)(()=>()=>{$?.(null)},[$]);let t1=ek?`${ek.percent??"null"}|${ek.contextWindow}|${ek.tokens??"null"}`:null,t2=(0,i.useRef)(ek);t2.current=ek,(0,i.useEffect)(()=>{M?.(t2.current)},[t1,M]),(0,i.useEffect)(()=>()=>{M?.(null)},[M]);let t4=(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 e4(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=>e2(e.name,!1)).join(""));for(let e of(a&&w?.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,w,h,L,l?.cwd,_]),t8=(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&&w?.current?.addImages(t),r.length>0&&eq({type:"warning",message:_("chat.dropFoldersUnsupported",{names:r.join(", ")})}),n.length>0&&t4(n)},[eq,w,_,t4]),t3=(0,i.useCallback)(e=>{t8(e.map(e=>({kind:"file",file:e})))},[t8]),{isDragOver:t5,handleDragEnter:t6,handleDragOver:t9,handleDragLeave:t7,handleDrop:ne}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),o=(0,i.useCallback)(e=>{s9(e)&&(e.preventDefault(),r.current+=1,n(!0))},[]),s=(0,i.useCallback)(e=>{s9(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])}}(t8),nt=er.filter(e=>nT(e)||"assistant"===e.role),nn=(0,i.useMemo)(()=>{let e=new Map(ei);for(let t of er)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[ei,er]),nr=(0,i.useMemo)(()=>new WeakMap,[]),ni=(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]),no=(t=nt.length,(o=(0,i.useRef)([])).current=Array(t).fill(null).map((e,t)=>o.current[t]??null),o),ns=(0,i.useCallback)(()=>{tO(e=>Math.max(e,2*er.length))},[er.length]),nl=eX&&0===er.length&&!ea.isStreaming&&!tj;eS(e8,!!l?.id||!nl);let na=!!ea.streamingMessage?.content.length,nc=l?.cwd??h??void 0,nd=(0,i.useRef)(null),nu=(0,i.useRef)(0),np=(0,i.useRef)(null),nh=(0,i.useRef)(!1),nf=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=nd.current;if(!ec||!e5){nf.current=null,nu.current=0,nh.current=!1,e&&(e.style.height="");return}let t=e8.current,n=tB.current,r=e3.current;if(!t||!n||!r||!e)return;let i=!1,o=()=>{var o;let s;if(i||e8.current!==t||tB.current!==n||e3.current!==r||nd.current!==e)return;let l=t.getBoundingClientRect().top,a=Math.max(0,r.getBoundingClientRect().top-l+t.scrollTop-16),c=e.getBoundingClientRect().top-l+t.scrollTop,d=(o=t.clientHeight,0===(s=Math.max(0,a))?0:Math.max(0,Math.ceil(s+o-Math.max(0,c)))),u=!nh.current;u&&(nh.current=!0),d!==nu.current&&(nu.current=d,e.style.height=d>0?`${d}px`:"",u&&d>0&&tg())};nf.current=o,o();let s="u"<typeof ResizeObserver?null:new ResizeObserver(()=>{i||null!==np.current||(np.current=requestAnimationFrame(()=>{np.current=null,o()}))});return s?.observe(t),s?.observe(n),s?.observe(r),()=>{i=!0,nf.current===o&&(nf.current=null),s?.disconnect(),null!==np.current&&(cancelAnimationFrame(np.current),np.current=null)}},[ec,e3,er.length,e5,e8,tg]),(0,i.useLayoutEffect)(()=>{nf.current?.()},[ea.streamingMessage]);let nm=eT?ex[`${eT.provider}:${eT.modelId}`]??null:null,ng=eT?ev[`${eT.provider}:${eT.modelId}`]??null:null,nx=(0,r.jsx)(sc,{ref:w,onSend:e6,onAbort:e9,onSteer:ec?ti:void 0,onFollowUp:ec?to:void 0,onPromptWithStreamingBehavior:ec?ts:void 0,isStreaming:tj,model:eT,isAutoModelSelection:eZ,modelNames:ep,modelList:ef,modelError:em,modelScopeWarnings:eg,onModelChange:tn,modelSwitching:eM,defaultModel:eJ,onSetDefaultModel:th,onCompact:l||eX?tr:void 0,onAbortCompaction:tl,isCompacting:eN,compactError:eE,onDismissCompactError:ta,compactResult:e$,toolPreset:eb,onToolPresetChange:l||eX?tu:void 0,thinkingLevel:ey,isAutoThinkingSelection:eV,onThinkingLevelChange:l||eX?tp:void 0,availableThinkingLevels:nm,thinkingLevelMap:ng,savedDefaultThinkingLevel:eY,onSetDefaultThinkingLevel:l||eX?tf:void 0,retryInfo:ej,queuedMessages:ez,inputHistory:ni,onRecallQueue:tc,slashCommands:eL,slashCommandsLoading:eA,onLoadSlashCommands:tm,onBuiltinCommand:td,soundEnabled:F,onSoundToggle:D,onAudioUnlock:H,draftKey:l?.id??f??void 0,cwd:l?.cwd??h,onAttachFiles:t3});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:t6,onDragOver:t9,onDragLeave:t7,onDrop:ne,children:[t5&&(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)(li,{notices:eP,floating:!0,onPauseChange:eK})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[eW&&(0,r.jsx)(ll,{request:eW,waitingCount:eO,onRespond:e_},eW.id),eF&&(0,r.jsx)(la,{request:eF,waitingCount:eD,onInput:eU},eF.id),!nl&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:e8,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:tB,onPointerUp:tL,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(nT(er[e])){o=e;break}let s=new Map,a=0;er.forEach((e,t)=>{(nT(e)||"assistant"===e.role)&&s.set(t,a++)});let c=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.messageOverride??er[e];if(nI(n))return null;let o=nT(n)||"assistant"===n.role,a=s.get(e),c=t.keyPrefix??"message",d=eo[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&&ea.isStreaming&&e===er.length-1&&(u=!1)}void 0!==t.showTimestamp&&(u=t.showTimestamp);let p=(0,r.jsx)(ix,{message:n,toolResults:nn,modelNames:ep,cwd:nc,onOpenFile:R,onOpenSession:A,entryId:eo[e],searchBlock:eo[e]===tq?.entryId?tJ:void 0,onFork:ed||eX?void 0:e7,forking:eC===eo[e],onEditContent:tj?void 0:te,onCancelEdit:tt,isEditing:eQ===eo[e],showTimestamp:u,prevTimestamp:e>0?er[e-1].timestamp:void 0,sessionId:l?.id??e1.current??void 0,writtenFiles:t.writtenFiles,onCompact:t.recoverTruncation?tr:void 0,isCompacting:t.recoverTruncation?eN:void 0,compactError:t.recoverTruncation?eE:void 0},`${c}-view-${d}`);return o&&void 0!==a?(0,r.jsx)("div",{"data-entry-id":eo[e],ref:!1===t.attachRef?void 0:t=>{no.current[a]=t,e===i&&(e3.current=t)},children:p},`${c}-${d}`):p},d=[];for(let e=0;e<er.length;){let t,n=nT(er[e]);if(!n&&0!==e){d.push(c(e)),e+=1;continue}let i=n?e:-1,l=n?e:0,a=e+1;for(;a<er.length&&!nT(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&&nP(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||(tj||ea.isStreaming)&&a===er.length&&i===o){for(let e=l;e<a;e++)d.push(c(e));e=a;continue}n&&d.push(c(i));let p=function(e,t){let n=e.get(t);if(n)return n;let{answerBlocks:r}=nP(t),i=r.length>0||nL(t)||nA(t)?n0(t,r):null,o=t.content.indexOf(r[0]),s={answer:i,process:n0(t,t.content.slice(0,o<0?void 0:o),{omitUsage:!!i})};return e.set(t,s),s}(nr,er[u]),h=p.answer,f=[],m=0,g=!1;for(let e=i+1;e<=u;e++){let n=er[e];if("custom"===n.role){if(nI(n))continue;g||=!!(tq&&tq.entryId===eo[e]),f.push(c(e,{attachRef:!1,keyPrefix:"process"}));continue}if("assistant"!==n.role)continue;let r=e===u?p.process:n,i=nR(r);0!==i.length&&(t??=s.get(e),m+=i.filter(e=>"toolCall"===e.type).length,g||=!!(tq&&eo[e]===tq.entryId&&(!tJ||i.includes(tJ))),f.push(c(e,{attachRef:!1,keyPrefix:"process",messageOverride:r,showTimestamp:!1})))}if(f.length>0){let e=(h?.content??[]).some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0);d.push((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{no.current[t]=e},children:(0,r.jsx)(ln,{messageCount:f.length,toolCallCount:m,defaultExpanded:!e,reveal:g,t:_,children:f},e?"answered":"unanswered")},`process-group-${eo[l]??l}`))}if(h){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){let n=e.writtenFiles;return n&&n.length===t.length&&n.every((e,n)=>e.filePath===t[n].filePath)?n:(e.writtenFiles=t,t)}(p,function(e,t,n){let r=new Set,i=[];for(let s of e){var o;if("toolCall"!==s.type||!(nU(o=s.toolName)||nK(o))&&!nq(s.toolName))continue;let e=t?.get(s.toolCallId);if(e&&!e.isError)for(let t of nq(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 nZ(e).matchAll(/^\*\*\* Delete File: (.+)$/gm)){let e=(t[1]??"").trim();e&&n.add(e)}return n}(e,n),i=function(e){if(!nV(e)||!nV(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(nJ(n))return[];if(n&&"object"==typeof n&&!Array.isArray(n)){let e=nQ(nX(n.preview));if(e.length>0)return e}return nQ(nG(nZ(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 nD(n)}(t,n);e&&(r.has(e)||(r.add(e),i.push({filePath:e})))}}return i}(e,nn,nc));d.push(c(u,{messageOverride:h,writtenFiles:t,recoverTruncation:a===er.length&&!ea.isStreaming&&!nz(h)}))}for(let e=u+1;e<a;e++)d.push(c(e));e=a}let{startIndex:u}=(t=Math.min(Math.max(tW,0),Math.max(e=d.length,0)),{startIndex:n=Math.max(0,e-t),hasMore:n>0}),p=u>0||el;return(0,r.jsxs)(r.Fragment,{children:[p&&(0,r.jsx)("div",{ref:tD,className:"py-3 text-center text-xs text-text-muted",children:_("chat.loadEarlier")}),d.slice(u)]})})(),ea.isStreaming&&na&&ea.streamingMessage&&(0,r.jsx)(ix,{message:ea.streamingMessage,toolResults:nn,isStreaming:!0,modelNames:ep,cwd:nc,onOpenFile:R,onOpenSession:A}),ec&&!na&&(eG||eN)&&(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}(eG,_,eN)})}),ed&&!eu&&(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")})}),eu&&(0,r.jsx)(ix,{message:{role:"bashExecution",command:eu.command,output:"",excludeFromContext:eu.excludeFromContext},sessionId:l?.id??e1.current??void 0,onOpenSession:A}),(0,r.jsx)("div",{ref:nd,"aria-hidden":"true"})]})})}),U||G?null:(0,r.jsx)(sx,{messages:er,streamingMessage:ea.streamingMessage,scrollContainer:e8,messageRefs:no,onRevealHistory:ns})]})]}),P&&tk&&(0,eI.createPortal)((0,r.jsx)("div",{ref:tT,role:tS?"dialog":"toolbar","aria-label":_(tS?"chat.newQuoteChat":"chat.askSelection"),style:{position:"fixed",top:tk.top,left:tk.left,zIndex:260,display:"flex",flexWrap:"wrap",gap:3,width:tS?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:tS?12:3,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",boxShadow:"0 2px 10px rgba(0,0,0,0.12)"},children:tS?(0,r.jsxs)("fieldset",{disabled:tN,"aria-busy":tN,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:tN,onClick:tR,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)(sc,{ref:tM,compact:!0,onSend:tz,onAbort:tR,isStreaming:!1}),t$&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:t$})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:_("chat.askInCurrent"),"aria-label":_("chat.askInCurrent"),onPointerDown:e=>e.preventDefault(),onClick:tA,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")})]}),z&&tk.sourceEntryId&&!ed&&(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:_("chat.askInNewChat"),"aria-label":_("chat.askInNewChat"),onPointerDown:e=>e.preventDefault(),onClick:()=>{tC(!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:[!nl&&(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${e0&&!G?" is-visible":""}`,title:_("chat.scrollToLatest"),"aria-label":_("chat.scrollToLatest"),onClick:()=>tb("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"})})})}),nl&&(0,r.jsx)("div",{className:"new-session-hero",style:{paddingLeft:16,paddingRight:U?16:52},children:(0,r.jsxs)("div",{className:"new-session-hero-row",style:{maxWidth:"var(--chat-content-max-width, 820px)"},children:[(0,r.jsxs)("div",{className:"new-session-versions",children:[(0,r.jsxs)("span",{children:["web ",(0,r.jsxs)("span",{className:"new-session-version",children:["v","0.11.1"]})]}),(0,r.jsxs)("span",{children:["pi ",(0,r.jsxs)("span",{className:"new-session-version",children:["v","1.1.0"]})]})]}),(0,r.jsxs)("div",{className:"new-session-brand",style:{gap:U?7:10},children:[(0,r.jsx)(nv.default,{src:"/icons/apple-touch-icon.png",width:32,height:32,alt:"",priority:!0,style:{flexShrink:0}}),(0,r.jsx)("span",{className:"new-session-brand-name",children:"Pi Web"}),(0,r.jsx)(lt,{label:e=>_("appUpdate.releaseNotes",{version:e})})]}),m]})}),nx,(0,r.jsx)(sk,{statuses:eB,widgets:eH,onCommand:e6,commandsDisabled:tj})]}),nl&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}function li(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)=>{var s;let l,a,c,d="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:d,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:(s=e.message,l=[],a=(e,t)=>{if(!t)return;let n=l[l.length-1];n?.kind===e?n.text+=t:l.push({kind:e,text:t})},c=!1,s.split("\n").forEach((e,t)=>{let n=nN.test(e);t>0&&a(n&&c?"art":"text","\n"),a(n?"art":"text",e),c=n}),l).map((e,t)=>"art"===e.kind?(0,r.jsx)("span",{style:{display:"inline-block",verticalAlign:"top",maxWidth:"100%",overflowX:"auto",whiteSpace:"pre",fontFamily:"Menlo, Consolas, 'DejaVu Sans Mono', monospace",lineHeight:1,color:"var(--text)"},children:e.text},t):e.text)})]},e.id)})})}function lo(e){let{count:t}=e,{t:n}=(0,eh.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 ls(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 ll(e){let{request:t,waitingCount:n,onRespond:o}=e,{t:s}=(0,eh.s)(),[l,a]=(0,i.useState)("editor"===t.method?t.prefill??"":""),[c,d]=(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(c)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()}},[c]),(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:c?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:c?(0,r.jsxs)("button",{type:"button",onClick:()=>d(!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)(lo,{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)(lo,{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)(ls,{expanded:m})}),(0,r.jsx)("button",{type:"button",onClick:()=>d(!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)(rX,{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)(rX,{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 la(e){let{request:t,waitingCount:n,onInput:o}=e,{t:s}=(0,eh.s)(),l=(0,i.useRef)(null),a=(0,i.useRef)(!1),[c,d]=(0,i.useState)(!1),u=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(nj,""),i=nk(e).trimEnd();if(t.test(i))continue;let o=e,s=nC(o);("│"===s||"┃"===s)&&" "===nC(o=nS(o,0))&&(o=nS(o,0));let l=function(e){let t=nw(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(o),a=l>=0?nw(o)[l]?.char:void 0;("│"===a||"┃"===a)&&(o=nS(o,l)),n.push(function(e){let t=e;for(;;){let e=nw(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&&""===nk(n[0]).trim();)n.shift();for(;n.length>0&&""===nk(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)(()=>{c||l.current?.focus()},[c]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:c?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:c?(0,r.jsxs)("button",{type:"button",onClick:()=>d(!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)(lo,{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=n$[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":" ":nE[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)(lo,{count:n}),(0,r.jsx)("button",{type:"button",onClick:()=>d(!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)(sb,{text:u.join("\n")})})]})})}let lc=null,ld="";function lu(e){let{context:t,mobile:n,initialFocus:o,onInitialFocusDone:s,onPick:l,onUseDefaultDirectory:a,onOpenFolder:c,onRefreshWorktrees:d,onCreateWorktree:u}=e,{t:p}=(0,eh.s)(),[h,f]=(0,i.useState)(()=>ld),m=(0,i.useRef)(null),g=(0,i.useRef)(o),x=(0,i.useRef)(s);return x.current=s,(0,i.useEffect)(()=>{if(ld)return;let e=!1;return(lc??=fetch("/api/home").then(e=>e.json()).then(e=>ld=e.home??"").catch(()=>(lc=null,""))).then(t=>{!e&&t&&f(t)}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=g.current;if(!e)return;g.current=null,x.current();let t=m.current;ep(document,("worktree"===e?t?.button("worktree"):null)??t?.button("project")??null)},[]),(0,r.jsx)("div",{className:"new-session-context",children:(0,r.jsx)(nr,{handleRef:m,layout:"inline",context:t,mobile:n,label:p("workspace.newSessionContext"),homeDir:h,newWorktreeTitle:p("sidebar.newWorktreeForSession"),onPick:l,onUseDefaultDirectory:a,onOpenFolder:c,onRefreshWorktrees:d,onCreateWorktree:u})})}var lp=n(50640);let lh={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"},lf={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"},lm={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",mov:"video/quicktime",ogv:"video/ogg"};function lg(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}var lx=n(73620);let lv=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function lb(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 ly=["tags","categories","keywords","tag","category"];function lj(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=ly.find(e=>Array.isArray(n[e])),l=s?n[s].map(lb).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=lb(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 lk={source:"Source",preview:"Preview",diff:"Diff"},lw={fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:13,lineHeight:1.6},lS={...rE.xJ,'pre[class*="language-"]':{...rE.xJ['pre[class*="language-"]']}};delete lS['pre[class*="language-"]'].background;let lC={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 lN(){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 lE(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function l$(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=lE(n.startContainer),i=lE(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 lI(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"),c=a?s[0]:null,d=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:[c&&(0,lp.Ay)({node:c,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:d.map((e,r)=>(0,lp.Ay)({node:e,stylesheet:n,useInlineStyles:i,key:`source-token-${t}-${r}`}))})]},`source-line-${t}`)})}function lT(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=eV(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 lM(e){let{filePath:t,sourceSessionId:n}=e,{t:i}=(0,eh.s)();return(0,r.jsx)("a",{href:lT(t,"download",n),download:eJ(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 lR(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function lL(e){let t,{patch:n}=e,{t:i}=(0,eh.s)(),o=(t=r2(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=[],c=0;for(;c<o.length;)if(l.has(c)){let e=[];for(;c<o.length&&l.has(c);)e.push(o[c]),c++;a.push({hidden:!1,lines:e})}else{let e=0;for(;c<o.length&&!l.has(c);)e++,c++;a.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...lw},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:lC,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 lA(e){let{filePath:t,cwd:n,sourceSessionId:o,watchEnabled:s=!0}=e,{t:l}=(0,eh.s)(),[a,c]=(0,i.useState)(!1),[d,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=eJ(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),m(null),x(null),c(!1)},[t,o]),(0,i.useEffect)(()=>{if(c(!1),v.current&&(v.current.close(),v.current=null),!s)return;let e=!0,n=new EventSource(lT(t,"watch",o));v.current=n,n.addEventListener("connected",()=>{let n;c(!0),n=++b.current,fetch(lT(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=()=>{c(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,o,s]);let j=lT(t,"read",o,d?{v:d}:void 0),k=null!=p?lR(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:eG(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)(lM,{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 lz(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 lP(e){let{filePath:t,cwd:n,sourceSessionId:o,watchEnabled:s=!0}=e,{t:l}=(0,eh.s)(),[a,c]=(0,i.useState)(!1),[d,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=eJ(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),m(null),x(null),c(!1)},[t,o]),(0,i.useEffect)(()=>{if(c(!1),v.current&&(v.current.close(),v.current=null),!s)return;let e=!0,n=new EventSource(lT(t,"watch",o));v.current=n,n.addEventListener("connected",()=>{let n;c(!0),n=++b.current,fetch(lT(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=()=>{c(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,o,s]);let j=lT(t,"read",o,d?{v:d}: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:eG(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"audio"}),null!=f&&(0,r.jsx)("span",{children:lz(f)}),null!=p&&(0,r.jsx)("span",{children:lR(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)(lM,{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 lW(e){let{filePath:t,cwd:n,sourceSessionId:o,watchEnabled:s=!0}=e,{t:l}=(0,eh.s)(),[a,c]=(0,i.useState)(!1),[d,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=eJ(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),m(null),x(null),c(!1)},[t,o]),(0,i.useEffect)(()=>{if(c(!1),v.current&&(v.current.close(),v.current=null),!s)return;let e=!0,n=new EventSource(lT(t,"watch",o));v.current=n,n.addEventListener("connected",()=>{let n;c(!0),n=++b.current,fetch(lT(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=()=>{c(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,o,s]);let j=lT(t,"read",o,d?{v:d}: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:eG(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"video"}),null!=f&&(0,r.jsx)("span",{children:lz(f)}),null!=p&&(0,r.jsx)("span",{children:lR(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)(lM,{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 lO(e){let{filePath:t,cwd:n,sourceSessionId:o,initialPage:s,watchEnabled:l=!0}=e,{t:a}=(0,eh.s)(),[c,d]=(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=lg(t),y="pdf"===b,j=y&&s&&s>0?`#page=${s}`:"",k=y?`${lT(t,"read",o,u?{v:u}:void 0)}${j}`:lT(t,"preview",o,u?{v:u}:void 0);return(0,i.useEffect)(()=>{p(0),f(null),g(null),d(!1);let e=!0,n=++v.current;return fetch(lT(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(d(!1),x.current&&(x.current.close(),x.current=null),!l)return;let e=!0,n=new EventSource(lT(t,"watch",o));x.current=n,n.addEventListener("connected",()=>{let n;d(!0),n=++v.current,fetch(lT(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=()=>{d(!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:eG(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===b?"docx preview":"pdf"}),null!=h&&(0,r.jsx)("span",{children:lR(h)}),(0,r.jsx)(lM,{filePath:t,sourceSessionId:o}),(0,r.jsxs)("span",{title:a(c?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:c?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:c?"#4ade80":"var(--border)",display:"inline-block",boxShadow:c?"0 0 4px #4ade80":"none"}}),c?"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:eJ(t)}),style:{width:"100%",height:"100%",border:"none",background:y?"var(--bg)":"#eef1f5"}},k)})]})}function lF(e){let t,{filePath:n,cwd:i,sourceSessionId:o,onOpenFile:s,onMentionLines:l,onAtMention:a,gitRefreshKey:c,initialDisplayMode:d,initialState:u,initialPage:p,onStateChange:h,watchEnabled:f=!0}=e;return null!==(lh[lg(n)]??null)?(0,r.jsx)(lA,{filePath:n,cwd:i,sourceSessionId:o,watchEnabled:f}):null!==(lf[lg(n)]??null)?(0,r.jsx)(lP,{filePath:n,cwd:i,sourceSessionId:o,watchEnabled:f}):null!==(lm[lg(n)]??null)?(0,r.jsx)(lW,{filePath:n,cwd:i,sourceSessionId:o,watchEnabled:f}):null!==("pdf"===(t=lg(n))||"docx"===t?t:null)?(0,r.jsx)(lO,{filePath:n,cwd:i,sourceSessionId:o,initialPage:p,watchEnabled:f}):(0,r.jsx)(lD,{filePath:n,cwd:i,sourceSessionId:o,onOpenFile:s,onMentionLines:l,onAtMention:a,gitRefreshKey:c,initialDisplayMode:d,initialState:u,onStateChange:h,watchEnabled:f})}function lD(e){let{filePath:t,cwd:n,sourceSessionId:o,onOpenFile:s,onMentionLines:l,onAtMention:a,gitRefreshKey:c,initialDisplayMode:d,initialState:u,onStateChange:p,watchEnabled:h=!0}=e,{isDark:f}=rU(),{t:m}=(0,eh.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,E]=(0,i.useState)(!1),[$,I]=(0,i.useState)(null),T=u?.displayMode??d??"source",M=u?.wrapLines??!1,R=u?.scrollTop??0,L=u?.scrollLeft??0,[A,z]=(0,i.useState)(T),[P,W]=(0,i.useState)(M),[O,F]=(0,i.useState)(!1),D=(0,i.useRef)(null),B=(0,i.useRef)(0),H=(0,i.useRef)(0),_=(0,i.useRef)(null),U=(0,i.useRef)(!1),K=(0,i.useRef)(void 0===u&&void 0===d),q=(0,i.useRef)(!0),Z=(0,i.useRef)({displayMode:T,wrapLines:M,scrollTop:R,scrollLeft:L}),V=(0,i.useRef)(p),[J,Y]=(0,i.useState)(null);V.current=p;let G=(0,i.useCallback)(e=>{Z.current.displayMode=e,z(e)},[]),X=(0,i.useCallback)(()=>{W(e=>{let t=!e;return Z.current.wrapLines=t,t})},[]);(0,i.useEffect)(()=>(Z.current={displayMode:T,wrapLines:M,scrollTop:R,scrollLeft:L},q.current=!0,U.current=!1,z(T),W(M),()=>{V.current?.({...Z.current})}),[t,o,T,M,R,L]);let Q=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=++B.current;return fetch(lT(e,"read",o,{offset:t||void 0})).then(e=>e.json()).then(e=>n!==B.current?null:e.error?(I(e.error),null):(I(null),x(n=>t&&n?{...e,content:n.content+e.content}:e),e)).catch(e=>(n!==B.current||I(String(e)),null))},[o]),ee=(0,i.useCallback)(async e=>{let t=++H.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!==H.current)return;b(i.ok&&o.supported&&"string"==typeof o.patch?o:null)}catch{t===H.current&&b(null)}finally{t===H.current&&(j(!1),w(!0))}},[n]);(0,i.useEffect)(()=>{let e=!0;return C(!0),I(null),x(null),b(null),w(!1),F(!1),Q(t).finally(()=>{e&&C(!1)}),()=>{e=!1}},[t,Q,o]),(0,i.useEffect)(()=>{if(F(!1),D.current&&(D.current.close(),D.current=null),!h)return;let e=()=>{Q(t),ee(t)},n=new EventSource(lT(t,"watch",o));D.current=n,n.addEventListener("connected",()=>{F(!0),e()}),n.addEventListener("change",e);let r=()=>{F(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{n.close(),D.current===n&&(D.current=null)}},[t,Q,ee,o,h]),(0,i.useEffect)(()=>{ee(t)},[ee,t,c]),(0,i.useEffect)(()=>{K.current&&!g?.truncated&&(g?.language==="markdown"||g?.language==="html")&&(K.current=!1,G("preview"))},[g?.language,g?.truncated,G]);let et=v?.supported===!0&&"string"==typeof v.patch,en=et&&"deleted"===v.status;(0,i.useEffect)(()=>{k&&!et&&"diff"===A&&G("source")},[A,k,et,G]),(0,i.useEffect)(()=>{"diff"===T&&et&&!U.current&&(U.current=!0,G("diff"))},[T,et,G]);let er=(0,i.useMemo)(()=>g?.language==="markdown"?ra(g.content):"",[g]),ei=(0,i.useMemo)(()=>g?.language==="markdown"?function(e){let t=function(e){let t=lv.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,lx.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]),eo=g?.content??"",es=(0,i.useMemo)(()=>eo.split("\n"),[eo]),el=g?.language??"text",ea="html"===el,ec="markdown"===el,ed=!g?.truncated&&(ea||ec),eu=en?"diff":A,ep=es.length>1e3&&!("diff"===eu&&et)&&!("preview"===eu&&ed),ef=(0,i.useMemo)(()=>(0,r.jsx)(rN.A,{className:P?"file-source-view is-wrapped":"file-source-view",language:"text"===el?"plaintext":el,style:f?lS:rE.vs,showLineNumbers:!0,lineNumberStyle:{...lC},customStyle:{margin:0,padding:0,border:0,backgroundColor:"var(--bg)",...lw,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)(lI,{...e,wrapLines:P}),wrapLongLines:P,children:eo}),[f,el,eo,P]),em=(0,i.useMemo)(()=>ep?es.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:lC,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,[es,ep,P]);(0,i.useEffect)(()=>{let e=()=>{let e=_.current;Y(t=>{let n=l&&"source"===A&&e?l$(e,window.getSelection()):null;return null===t&&null===n||t&&n&&t.startLine===n.startLine&&t.endLine===n.endLine?t:n})};if(e(),l&&"source"===A)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[g?.content,A,l]);let eg=(0,i.useCallback)(e=>{l&&e&&l(eG(t,n),e.startLine,e.endLine)},[n,t,l]);if((0,i.useEffect)(()=>{if(!l||"source"!==A)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let n=_.current,r=n?l$(n,window.getSelection()):null;r&&(e.preventDefault(),eg(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[A,eg,l]),(0,i.useEffect)(()=>{if(!q.current||S||$&&!en||"diff"===T&&!k||"diff"===T&&et&&"diff"!==A)return;let e=_.current;e&&(e.scrollTop=Z.current.scrollTop,e.scrollLeft=Z.current.scrollLeft,q.current=!1)},[g?.content,A,$,k,et,en,S,T]),S||"diff"===T&&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($&&!en)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:$});if(!g&&!en)return null;let ex=eY(t),ev=en?["diff"]:["source",...ed?["preview"]:[],...et?["diff"]:[]],eb=en?m("files.deleted"):`${el} \xb7 ${es.length} lines \xb7 ${lR(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:eG(t,n)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:eb,children:eb}),!en&&(0,r.jsx)("span",{title:O?m("i18n.liveSync"):m("i18n.notWatching"),"aria-label":O?m("i18n.liveSync"):m("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:O?"#4ade80":"var(--border)",boxShadow:O?"0 0 4px #4ade80":"none"}}),(0,r.jsxs)("div",{className:"file-viewer-controls",children:[ev.length>1&&(0,r.jsx)("div",{className:"file-viewer-mode-switch","aria-label":m("i18n.fileViewMode"),children:ev.map(e=>{let t=eu===e;return(0,r.jsx)("button",{type:"button",onClick:()=>G(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:lk[e]},e)})}),(0,r.jsxs)("div",{className:"file-viewer-actions",children:[(a||l)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{J&&l?eg(J):a?.(eG(t,n),!1)},title:J&&l?`${m("i18n.mentionSelectedLines")} (L${J.startLine}${J.startLine!==J.endLine?`-L${J.endLine}`:""})`:m("files.insertPath"),"aria-label":m("files.mention"),disabled:!a&&!l,className:"file-viewer-icon-button",children:(0,r.jsx)(lN,{})}),"source"===eu&&(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("button",{type:"button",onClick:X,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"})]})})})]}),!en&&(0,r.jsx)(lM,{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:[lR(g.nextOffset)," / ",lR(g.size)]}),(0,r.jsx)("button",{type:"button",className:"file-viewer-mode-button",disabled:N,onClick:()=>{E(!0),Q(t,g.nextOffset).finally(()=>E(!1))},children:N?m("i18n.loading"):m("i18n.loadMore")})]}),(0,r.jsx)("div",{ref:_,className:"file-viewer-content",onScroll:e=>{Z.current.scrollTop=e.currentTarget.scrollTop,Z.current.scrollLeft=e.currentTarget.scrollLeft},style:{flex:1,overflow:"auto",background:"var(--bg)",paddingBottom:g?.truncated?48:void 0},children:"diff"===eu&&et?(0,r.jsx)(lL,{patch:v.patch}):ea&&"preview"===eu?(0,r.jsx)("iframe",{srcDoc:eo,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:m("i18n.htmlPreview")}):ec&&"preview"===eu?(0,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[ei?.data&&(0,r.jsx)(lj,{data:ei.data}),(0,r.jsx)(n2.oz,{remarkPlugins:rk,rehypePlugins:rS,urlTransform:s?ro:ri,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)(rq,{code:s.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(rJ,{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?nB(t,ex,n??ex):null;if(!l||!s)return t&&/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(t)?(0,r.jsx)("a",{href:t,...o,target:"_blank",rel:"noopener noreferrer",children:i}):(0,r.jsx)("a",{href:t,...o,children:i});return(0,r.jsx)("a",{href:t,...o,onClick:e=>{nW(e)&&(e.preventDefault(),s(l,n_(t)??void 0))},children:i})},img(e){let{src:t,alt:i,...s}=e;delete s.node;let l="string"==typeof t?nB(t,ex,n??ex):null,a=l?lT(l,"read",o):t;return(0,r.jsx)("img",{src:a,alt:i??"",loading:"lazy",...s})}},children:er})]}):ep?(0,r.jsx)("div",{className:"file-source-view is-lightweight",style:{width:P?"100%":"max-content",minWidth:"100%",minHeight:"100%",background:"var(--bg)",...lw},children:em}):ef})]})}function lB(e){let{tabs:t,activeTabId:n,onSelectTab:o,onCloseTab:s}=e,{t:l}=(0,eh.s)(),[a,c]=(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"})]}):eq(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:()=>c(e.id),onMouseLeave:()=>c(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 lH(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 l_=["general","models","archives","skills","agents","plugins","mcp"],lU="pi-web:settings-navigation",lK=new Set(["skills","agents","plugins"]);function lq(e){return lK.has(e)}function lZ(){try{return window.localStorage}catch{return null}}function lV(e){let t=e.getItem(lU);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 lJ(e,t){return"models"===e?e:t?JSON.stringify([e,t]):"mcp"===e?e:null}function lY(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:lZ();if(t)try{let n=lV(t);n.section=e,t.setItem(lU,JSON.stringify(n))}catch{}}function lG(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:lZ();if(!n)return null;let r=lJ(e,t);if(!r)return null;try{let e=lV(n).selections?.[r];return"string"==typeof e&&e.length>0?e:null}catch{return null}}function lX(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:lZ();if(!r||!t)return;let i=lJ(e,n);if(i)try{let e=lV(r);e.selections={...e.selections,[i]:t},r.setItem(lU,JSON.stringify(e))}catch{}}let lQ=["input","output","cacheRead","cacheWrite"];function l0(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 l1(e){if(!l2(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 l2(e){return lQ.some(t=>""!==e[t].trim())}function l4(e){return new Map(Object.entries(e.providers??{}).map(e=>{let[t,n]=e;return[t,(n.models??[]).map(e=>e.id)]}))}function l8(e,t,n){if(n<=0)return;let r=e.get(t)??[];e.set(t,[...r,...Array.from({length:n},()=>null)])}function l3(e){let{embedded:t,title:n,subtitle:i,closeLabel:o="Close",onClose:s,children:l,width:a=900,height:c="78vh"}=e,d=t?void 0:{"--config-panel-width":`${a}px`,"--config-panel-height":c};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:d,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 l5(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-split-view",children:t})}function l6(e){let{children:t}=e;return(0,r.jsx)("aside",{className:"config-sidebar",children:t})}function l9(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-sidebar-list",children:t})}function l7(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 ae(e){let{enabled:t,total:n,checked:i,label:o,disabled:s=!1,loading:l=!1,describedBy:a,onChange:c}=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)(aC,{checked:i??(n>0&&t===n),disabled:s,loading:l,label:o,describedBy:a,onChange:c})]})}function at(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 an(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 ar(e){let{className:t,...n}=e;return(0,r.jsx)("span",{...n,className:["config-sidebar-text",t].filter(Boolean).join(" ")})}function ai(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-stack",t].filter(Boolean).join(" ")})}function ao(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header",t].filter(Boolean).join(" ")})}function as(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header-info",t].filter(Boolean).join(" ")})}function al(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-actions",t].filter(Boolean).join(" ")})}function aa(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-title",children:t})}function ac(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-section-title",children:t})}function ad(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 au(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-grid",children:t})}function ap(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 ah(e){let{scope:t,children:n}=e;return(0,r.jsx)("span",{className:`config-scope-tag${"project"===t?" is-project":""}`,children:n})}function af(e){let{value:t,options:n,label:o,disabledReason:s,size:l="default",onChange:a,children:c}=e,d=(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?d:void 0,disabled:e.disabled,className:"config-scope-switch-option",onClick:()=>{e.disabled||a(e.value)},children:e.label},e.value))}),c]}),u&&(0,r.jsx)("span",{id:d,className:"config-scope-switch-reason",children:u})]})}function am(e){let{value:t,options:n,label:o,path:s,disabledReason:l,onChange:a,children:c}=e;return(0,r.jsxs)("div",{className:"config-save-target",children:[(0,r.jsx)(af,{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})}),c]})}function ag(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)(aa,{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 ax(e){let{title:t,catalogs:n,target:o,inputLabel:s,inputId:l,placeholder:a,value:c,canSubmit:d,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)(ai,{className:"is-fill",children:[(0,r.jsx)(ag,{title:t,catalogs:n,target:o}),(0,r.jsx)(ad,{label:s,children:x?(0,r.jsx)("textarea",{id:l,ref:y,value:c,"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(),d&&h())}}):(0,r.jsx)("input",{id:l,ref:b,value:c,"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&&d&&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 av(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 ab(e){let{id:t,message:n,trustLabel:i,trusting:o=!1,onTrust:s}=e;return(0,r.jsx)(av,{id:t,action:s&&i?(0,r.jsx)(aS,{size:"small",onClick:s,disabled:o,children:i}):void 0,children:n})}function ay(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-empty-state",children:t})}function aj(e){let{children:t,style:n}=e;return(0,r.jsx)("div",{className:"config-detail",style:n,children:t})}function ak(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 aw(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 aS(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 aC(e){let{checked:t,disabled:n=!1,loading:i=!1,size:o="default",label:s,describedBy:l,onChange:a}=e,c=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:c,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 aN(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 aE(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 a$(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 aI(e,t){let n=a$(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 aT(e,t){return t.enabled&&(e?.enabledTotal??0)<=1}function aM(e,t){return e?.providers.find(e=>e.id===t)}let aR={"last-model":"models.enabledLastModel","project-scope":"models.enabledProjectScope"};function aL(e){let{controller:t}=e,{t:n}=(0,eh.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)(aS,{size:"small",onClick:t.pruneStale,disabled:null!==o,title:n("models.enabledPruneHint"),children:n("models.enabledPrune")}),i.editable&&s&&(0,r.jsx)(aS,{size:"small",onClick:t.clearScope,disabled:null!==o,title:n("models.enabledClearHint"),children:n("models.enabledClear")})]}):null}function aA(e){let{providerId:t,controller:n,noteId:i}=e,{t:o}=(0,eh.s)(),{view:s,loading:l,pending:a,failure:c}=n,d=aM(s,t),u=c?c.messageKey?o(c.messageKey):c.message:null,p=az(n,t)?i:void 0;if(l&&!s)return null;if(!d)return(0,r.jsx)(aC,{checked:!1,disabled:!0,label:o("models.enabledProviderToggle",{provider:t}),describedBy:p,onChange:()=>{}});let h=aI(s,d);return(0,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("span",{className:"enabled-models-switch-error",children:u}),(0,r.jsx)(aC,{checked:h.checked,loading:a===`provider:${d.id}`,disabled:null!==a||h.blocked,label:o("models.enabledProviderToggle",{provider:d.name}),describedBy:p,onChange:e=>n.setProvider(d.id,e)})]})}function az(e,t){let{view:n,loading:r}=e;if(r&&!n)return null;let i=aM(n,t);if(!i)return"models.enabledCustomEmpty";let{reason:o}=aI(n,i);return o?aR[o]:null}function aP(e){let{providerId:t,controller:n,id:i}=e,{t:o}=(0,eh.s)(),s=az(n,t);return s?(0,r.jsx)("div",{id:i,className:"config-detail-heading-note",children:o(s)}):null}function aW(e){var t;let n,{providerId:o,controller:s}=e,{t:l}=(0,eh.s)(),[a,c]=(0,i.useState)(""),{view:d,loading:u,pending:p,failure:h}=s,f=aM(d,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)(()=>c(""),[o]),u&&!d)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=a$(d,x),b=x.length!==f.models.length,y=null!==p,j=`provider:${f.id}`,k=d?.editable===!0,w=`${g}-scope`,S=`${g}-last`,C=k&&!v.canDisable&&v.disableRefs.length>0,N=C||k&&x.some(e=>aT(d,e)),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)(aS,{size:"small",disabled:y||!v.canEnable,"aria-describedby":k?void 0:w,onClick:()=>E(!0,v.enableRefs),children:b?l("models.enableShown"):l("models.enableAll")}),(0,r.jsx)(aS,{size:"small",disabled:y||!v.canDisable,"aria-describedby":k?C?S:void 0:w,onClick:()=>E(!1,v.disableRefs),children:b?l("models.disableShown"):l("models.disableAll")}),(0,r.jsx)(aS,{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=>c(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=aT(d,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)(aC,{checked:e.enabled,loading:p===e.ref,disabled:y||!d?.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 aO(e){let{message:t,hint:n,value:i,placeholder:o,submitLabel:s,inputLabel:l,disabled:a=!1,plainEnterSubmits:c=!0,inputRef:d,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:d,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&&(c||t.metaKey||t.ctrlKey)&&h&&p()}}),(0,r.jsx)("button",{type:"button",className:"oauth-paste-submit",onClick:p,disabled:!h,children:s})]})]})}let aF={anthropic:{symbol:"anthropic",color:!1},openai:{symbol:"openai",color:!1},"openai-codex":{symbol:"openai",color:!1},google:{symbol:"google",color:!0},"google-vertex":{symbol:"google",color:!0},"ant-ling":{symbol:"antgroup",color:!0},deepseek:{symbol:"deepseek",color:!0},groq:{symbol:"groq",color:!1},mistral:{symbol:"mistral",color:!0},moonshotai:{symbol:"moonshot",color:!1},"moonshotai-cn":{symbol:"moonshot",color:!1},moonshot:{symbol:"moonshot",color:!1},minimax:{symbol:"minimax",color:!0},"minimax-cn":{symbol:"minimax",color:!0},fireworks:{symbol:"fireworks",color:!0},huggingface:{symbol:"huggingface",color:!0},cerebras:{symbol:"cerebras",color:!0},openrouter:{symbol:"openrouter",color:!1},xai:{symbol:"xai",color:!1},"cloudflare-ai-gateway":{symbol:"cloudflare",color:!0},"cloudflare-workers-ai":{symbol:"cloudflare",color:!0},"vercel-ai-gateway":{symbol:"vercel",color:!1},"github-copilot":{symbol:"githubcopilot",color:!1},"amazon-bedrock":{symbol:"aws",color:!0},azure:{symbol:"azure",color:!0},"azure-openai-responses":{symbol:"azure",color:!0},"kimi-coding":{symbol:"kimi",color:!0},nvidia:{symbol:"nvidia",color:!0},opencode:{symbol:"opencode",color:!1},"opencode-go":{symbol:"opencode",color:!1},qwen:{symbol:"qwen",color:!0},xiaomi:{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-ams":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-cn":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-sgp":{symbol:"xiaomimimo",color:!1},zai:{symbol:"zai",color:!1},"zai-coding-cn":{symbol:"zai",color:!1},zhipu:{symbol:"zhipu",color:!0},cohere:{symbol:"cohere",color:!0},perplexity:{symbol:"perplexity",color:!0},together:{symbol:"together",color:!0},grok:{symbol:"grok",color:!1}};function aD(e){let{id:t,size:n}=e,i=aF[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 aB=["openai-codex","deepseek","openrouter","moonshotai","moonshotai-cn","minimax","minimax-cn","vercel-ai-gateway","opencode-go","kimi-coding"],aH="pi-web:provider-usage:";function a_(e){let{providerId:t,enabled:n}=e;return aB.includes(t)?(0,r.jsx)(aU,{providerId:t,enabled:n}):null}function aU(e){let{providerId:t,enabled:n}=e,[o,s]=(0,i.useState)(null),[l,a]=(0,i.useState)(!1),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),h=(0,i.useRef)(null),{locale:f,t:m}=(0,eh.s)();(0,i.useEffect)(()=>{h.current&&clearTimeout(h.current),p(!1),s(null);try{let e=localStorage.getItem(`${aH}${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(`${aH}${t}`)}catch{}}return d(null),()=>{h.current&&clearTimeout(h.current)}},[t]);let g=(0,i.useCallback)(async()=>{a(!0),d(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(`${aH}${t}`,JSON.stringify(n))}catch{}p(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>p(!1),2e3)}else d(n.message??m("providerUsage.queryFailed"))}catch(e){d(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,tl.ob)(x.capturedAt,f)})})]}),!x&&!c&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)"},children:m("providerUsage.notQueried")}),c&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171"},children:c}),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 ":"$"}${aK(e.remaining??e.limit)}`:void 0!==e.remaining&&void 0!==e.limit?`${aK(e.remaining)} / ${aK(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 aK(e){return void 0===e?"-":Number.isInteger(e)?String(e):e.toFixed(2)}function aq(){let e=lG("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 aZ=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function aV(e){let{label:t,children:n}=e;return(0,r.jsx)(ad,{label:t,children:n})}let aJ={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 aY(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:{...aJ,fontFamily:o?"var(--font-mono)":"inherit"}})}function aG(e){let{value:t,onChange:n,placeholder:o,mono:s,onKeyDown:l,autoComplete:a="off",spellCheck:c=!1,style:d}=e,[u,p]=(0,i.useState)(!1),{t:h}=(0,eh.s)();return(0,i.useEffect)(()=>{t||p(!1)},[t]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...d},children:[(0,r.jsx)("input",{type:u?"text":"password",value:t,onChange:e=>n(e.target.value),onKeyDown:l,placeholder:o,style:{...aJ,paddingRight:34,fontFamily:s?"var(--font-mono)":"inherit"},autoComplete:a,spellCheck:c}),(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 aX(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:aJ})}function aQ(e){let{value:t,onChange:n,options:i,required:o}=e,{t:s}=(0,eh.s)();return(0,r.jsxs)("select",{value:t,onChange:e=>n(e.target.value),style:{...aJ,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 a0(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 a1(e){let{children:t}=e;return(0,r.jsx)(ac,{children:t})}function a2(e){let{name:t,editingName:n,provider:o,onChange:s,onEditingNameChange:l,onRename:a,onDelete:c,onAddModels:d,enabledModels:u}=e,{t:p}=(0,eh.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(),E=C.filter(e=>!N||e.id.toLocaleLowerCase().includes(N)||e.name?.toLocaleLowerCase().includes(N)),$=E.slice(0,300),I=$.filter(e=>!S.has(e.id)).map(e=>e.id),T=x.filter(e=>!S.has(e)).length,M=I.length>0&&I.every(e=>x.includes(e)),R=!M&&I.some(e=>x.includes(e));return(0,i.useEffect)(()=>{y.current&&(y.current.indeterminate=R)},[R]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(ao,{children:[(0,r.jsx)(as,{children:(0,r.jsx)(a1,{children:p("i18n.provider")})}),(0,r.jsxs)(al,{children:[(0,r.jsx)(aA,{providerId:t,controller:u,noteId:j}),(0,r.jsx)(aS,{variant:"danger",size:"small",onClick:c,children:p("i18n.delete")})]})]}),(0,r.jsx)(aP,{providerId:t,controller:u,id:j})]}),(0,r.jsxs)(aV,{label:p("i18n.providerName"),children:[(0,r.jsx)(aY,{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)(aV,{label:"Base URL",children:[(0,r.jsx)(aY,{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)(aV,{label:"API Key",children:[(0,r.jsx)(aG,{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)(aV,{label:"API",children:(0,r.jsx)(aQ,{value:o.api??"",onChange:e=>k("api",e||void 0),options:aZ})}),(0,r.jsxs)(aV,{label:"Headers",children:[(0,r.jsx)(a9,{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:{...aJ,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:I.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:y,type:"checkbox",checked:M,disabled:0===I.length,onChange:()=>{let e=new Set(I);v(t=>M?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...I])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),p("models.discoverySelectShown")]}),0===$.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:p("models.discoveryNoMatches")}):$.map((e,t)=>{let n=S.has(e.id),i=x.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:i||n,disabled:n,onChange:()=>{var t;return t=e.id,void v(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),n&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:p("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:h.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:E.length>$.length?p("models.discoveryShowing",{shown:$.length,total:E.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&&(d(t),v([]))},disabled:0===T,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:T?"var(--accent)":"var(--bg-panel)",color:T?"var(--accent-contrast)":"var(--text-dim)",cursor:T?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:T?p("models.discoveryAddSelectedCount",{count:T}):p("models.discoveryAddSelected")})]})]})]})]})}let a4=["off","minimal","low","medium","high","xhigh","max"],a8={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function a3(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:a4.map(e=>{let t=i[e],n=e in i?null===t?"null":"string":"omit",s="string"==typeof t?t:"",l=a8[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)"},c={background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600};return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:l,flexShrink:0,opacity:"null"===n?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===n?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===n?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>o(e,"omit"),style:{...a,..."omit"===n?c:{}},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?c:{},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 a5={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function a6(e){return e.compat?.thinkingFormat==="deepseek"}function a9(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))},c=(e,t)=>{a(o.map(n=>n.id===e?{...n,...t}:n))},d={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=>c(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...aJ,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>c(e.id,{value:t.target.value}),placeholder:"value",style:{...aJ,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:d,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 a7(e){let{providerName:t,provider:n,model:o,onChange:s,onDelete:l}=e,[a,c]=(0,i.useState)({phase:"idle"}),{t:d}=(0,eh.s)(),[u,p]=(0,i.useState)({phase:"idle"}),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(()=>l0(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 d("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?[d("i18n.connected"),...e,a.responseText||null].filter(Boolean).join(" \xb7 "):[d("i18n.failed"),...e,a.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>{c({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){c({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 c({phase:"error",message:r.error??`HTTP ${e.status}`,latencyMs:r.latencyMs,status:r.status});c({phase:"success",latencyMs:r.latencyMs,status:r.status,responseText:r.responseText})}catch(e){c({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 c=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=l1(l0(i));o>0&&s&&(n.cost={...i,...s},r+=o)}return{model:n,appliedCount:r}}(o,a.recommendation.preset);c.appliedCount>0&&(j.current=o,s(c.model)),f(!1),p({phase:"success",recommendation:a.recommendation,appliedCount:c.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]),E=(()=>{if("success"!==u.phase)return null;let{recommendation:e,appliedCount:n}=u,r=n>0?d("models.catalogFilled",{count:n}):d("models.catalogNoEmptyFields");if("unreliable"===e.price.status){let t="no-exact-match"===e.price.reason?d("models.catalogNoExactMatch"):d("models.catalogPriceUnreliable");return`${r} \xb7 ${t}`}let i="provider"===e.price.method?d("models.catalogPriceProvider",{provider:e.price.providerName??e.price.providerId??t}):"base-url"===e.price.method?d("models.catalogPriceBaseUrl",{provider:e.price.providerName??e.price.providerId??t}):d("models.catalogPriceConsensus",{support:e.price.support,total:e.price.total});return`${r} \xb7 ${i}`})(),$="error"===u.phase?u.message:E,I="error"===u.phase?"#ef4444":"success"===u.phase&&"unreliable"===u.recommendation.price.status?"#d97706":"var(--text-dim)",T=[{key:"input",label:d("models.costInput")},{key:"output",label:d("models.costOutput")},{key:"cacheRead",label:d("models.costCacheRead")},{key:"cacheWrite",label:d("models.costCacheWrite")}],M=new Set(Object.keys(o.compat??{})),R=0;a6(o)&&(R+=1,M.delete("thinkingFormat"),M.delete("requiresReasoningContentOnAssistantMessages")),Object.prototype.hasOwnProperty.call(o.compat??{},"supportsDeveloperRole")&&(R+=1,M.delete("supportsDeveloperRole")),R+=M.size;let L=[o.api?`API: ${o.api}`:null,Object.keys(o.headers??{}).length?d("models.headersSummary",{count:Object.keys(o.headers??{}).length}):null,R?d("models.compatSummary",{count:R}):null,Object.keys(o.thinkingLevelMap??{}).length?d("models.thinkingSummary",{count:Object.keys(o.thinkingLevelMap??{}).length}):null].filter(e=>!!e),A=L.length?L.join(" \xb7 "):d("models.providerDefaults");return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(ao,{children:[(0,r.jsx)(as,{children:(0,r.jsx)(a1,{children:d("i18n.model")})}),(0,r.jsxs)(al,{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)(aS,{size:"small",variant:"success"===a.phase?"primary":"secondary",onClick:"success"===a.phase?()=>c({phase:"idle"}):C,disabled:!o.id.trim()||"testing"===a.phase,title:d("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?d("i18n.checking"):"success"===a.phase?d("common.ok"):d("i18n.test")]}),(0,r.jsx)(aS,{variant:"danger",size:"small",onClick:l,children:d("i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(aV,{label:"ID *",children:(0,r.jsx)(aY,{value:o.id,onChange:e=>w("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(aV,{label:"Name",children:(0,r.jsx)(aY,{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?d("models.catalogFilling"):d("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:d("models.catalogSource")})]}),$&&(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:8,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:I,fontSize:10},children:[(0,r.jsx)("span",{title:$,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:$}),j.current&&(0,r.jsx)("button",{onClick:()=>{let e=j.current;e&&(j.current=null,s(e),p({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:d("models.catalogUndo")})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(a1,{children:d("models.capabilities")}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginTop:8},children:[(0,r.jsx)(a0,{label:d("models.reasoning"),checked:o.reasoning??!1,onChange:e=>w("reasoning",e||void 0)}),(0,r.jsx)(a0,{label:d("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)(a1,{children:d("models.modelSpecs")}),(0,r.jsx)("button",{type:"button",onClick:()=>{if(h)return void f(!1);k.current=o.cost;let e=l0(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?d("models.finishEditingCosts"):d("models.editCosts")})]}),(0,r.jsxs)("div",{style:{marginTop:10,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:10},children:[(0,r.jsx)(aV,{label:d("models.contextWindow"),children:(0,r.jsx)(aX,{value:void 0!==o.contextWindow?String(o.contextWindow):"",onChange:e=>w("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(aV,{label:d("models.maxOutputTokens"),children:(0,r.jsx)(aX,{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:d("models.costPerMillion")}),h?(0,r.jsxs)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(110px, 1fr))",gap:8},children:[T.map(e=>{let{key:t,label:n}=e;return(0,r.jsx)(aV,{label:n,children:(0,r.jsx)(aX,{value:m[t],onChange:e=>{let n,r,i;return r=l1(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)}),l2(m)&&!l1(m)&&(0,r.jsx)("div",{"aria-live":"polite",style:{gridColumn:"1 / -1",color:"#d97706",fontSize:10},children:d("models.costAllRequired")})]}):(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(105px, 1fr))",gap:"8px 16px"},children:T.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])?d("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:d("models.advancedSettings")}),(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-dim)",fontSize:10,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:A})]}),(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{color:"var(--text-dim)",transform:v?"rotate(180deg)":"none",transition:"transform 0.15s ease"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),v&&(0,r.jsxs)("div",{id:"model-advanced-settings",style:{display:"flex",flexDirection:"column",gap:14,padding:"4px 0 16px"},children:[(0,r.jsx)(aV,{label:d("models.apiOverride"),children:(0,r.jsx)(aQ,{value:o.api??"",onChange:e=>w("api",e||void 0),options:aZ})}),(0,r.jsxs)(aV,{label:d("models.headers"),children:[(0,r.jsx)(a9,{headers:o.headers,onChange:e=>w("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:d("models.headersHelp")})]}),o.reasoning&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsx)(a1,{children:d("models.compatibility")}),(0,r.jsx)(a0,{label:d("models.deepSeekThinkingCompat"),checked:a6(o),onChange:e=>s(function(e,t){if(t)return{...e,compat:{...e.compat??{},...a5}};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)(a0,{label:d("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)(a1,{children:d("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:d("models.clearAll")})]}),(0,r.jsx)(a3,{value:o.thinkingLevelMap,onChange:e=>w("thinkingLevelMap",e)})]})]})]})]})]})}function ce(e){let{provider:t,onRefresh:n,enabledModels:o}=e,[s,l]=(0,i.useState)({phase:"idle"}),{t:a}=(0,eh.s)(),[c,d]=(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"}),d(""),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"}),d("");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}d("")}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)(ao,{children:[(0,r.jsx)(as,{children:(0,r.jsx)(a1,{children:a("i18n.subscription")})}),(0,r.jsxs)(al,{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)(aS,{size:"small",onClick:()=>{u.current?.close(),l({phase:"idle"})},children:a("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(aS,{variant:"primary",size:"small",onClick:h,children:a(t.loggedIn?"i18n.relogin":"i18n.login")}),t.loggedIn&&(0,r.jsx)(aS,{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)(aO,{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:c,placeholder:"auth"===s.phase?"http://localhost:1455/auth/callback?code=…":s.placeholder??"Enter value…",submitLabel:a("i18n.submit"),inputRef:p,onValueChange:d,onSubmit:()=>void m(s.token,c)}),"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)(a_,{providerId:t.id,enabled:t.loggedIn}),t.loggedIn&&(0,r.jsx)(aW,{providerId:t.id,controller:o})]})}function ct(e){let{provider:t,onRefresh:n,enabledModels:o}=e,[s,l]=(0,i.useState)(""),[a,c]=(0,i.useState)(!1),[d,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(!1),{t:g}=(0,eh.s)();(0,i.useEffect)(()=>{l(""),h(null),m(!1)},[t.id]);let x=(0,i.useCallback)(async()=>{if(s.trim()){c(!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{c(!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)(ao,{children:[(0,r.jsx)(as,{children:(0,r.jsx)(a1,{children:"API Key"})}),(0,r.jsxs)(al,{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)(aS,{variant:"danger",size:"small",onClick:v,disabled:d,children:g(d?"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)(aG,{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)(a_,{providerId:t.id,enabled:t.configured}),t.configured&&(0,r.jsx)(aW,{providerId:t.id,controller:o})]})}function cn(e){let{oauthProviders:t,apiKeyProviders:n,onSelectOAuth:o,onSelectApiKey:s,onAddCustom:l,onClose:a}=e,[c,d]=(0,i.useState)(""),{t:u}=(0,eh.s)(),p=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>p.current?.focus(),30)},[]);let h=c.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:c,onChange:e=>d(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)(aD,{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)(aD,{id:e.id,size:28})]},e.id))]})})]})})}function cr(e){let{onClose:t,embedded:n=!1,cwd:o=null}=e,{t:s}=(0,eh.s)(),l=function(e){let[t,n]=(0,i.useState)(null),[r,o]=(0,i.useState)(!0),[s,l]=(0,i.useState)(null),[a,c]=(0,i.useState)(null),d=(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),c(null)}).catch(e=>{t.signal.aborted||c({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(d.current){u.current={key:t,body:r};return}d.current=t,l(t),c(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?aR[i.reason]:void 0;c(e?{messageKey:e}:{message:i.error??`HTTP ${t.status}`});return}n(i)}catch(e){c({message:e instanceof Error?e.message:String(e)})}finally{d.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,c]=(0,i.useState)({providers:{}}),[d,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)(aq),[k,w]=(0,i.useState)([]),[S,C]=(0,i.useState)([]),[N,E]=(0,i.useState)(!1),$=(0,i.useRef)(new Set),I=(0,i.useRef)(new Map),T=(0,i.useRef)(new Map),[M,R]=(0,i.useState)(null),L=(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:{}};c(t),$.current=new Set(Object.keys(t.providers??{})),T.current=l4(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)),L()},[L]),(0,i.useEffect)(()=>{y&&lX("models",JSON.stringify(y))},[y]);let A=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;a.providers?.[e];)e=`new-provider-${t++}`;c(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),j({type:"provider",name:e})},[a.providers]),z=(0,i.useCallback)((e,t)=>{c(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 c=l.get(n);c&&(l.delete(n),l.set(r,c));let d=Object.entries(i),u=d.findIndex(e=>{let[t]=e;return t===n});return d[u]=[r,d[u][1]],{...e,providers:Object.fromEntries(d)}}(e,{savedProviders:$.current,renames:I.current,slots:T.current},t,n);return r?(c(r),R(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},[]),W=(0,i.useCallback)((e,t)=>{P(a,e,t)?m(null):m(s("models.providerNameTaken",{name:t}))},[P,a,s]),O=(0,i.useCallback)(e=>{T.current.delete(e),R(t=>t?.provider===e?null:t),c(t=>{let n={...t.providers??{}};return delete n[e],{...t,providers:n}}),c(e=>{let t=Object.keys(e.providers??{});return j(t.length>0?{type:"provider",name:t[0]}:null),e})},[]),F=(0,i.useCallback)(e=>{l8(T.current,e,1),c(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),c(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)=>{c(n=>{let r=new Set((n.providers?.[e]?.models??[]).map(e=>e.id));l8(T.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({...e}));return{...n,providers:{...n.providers??{},[e]:{...i,models:o}}}})},[]),B=(0,i.useCallback)((e,t,n)=>{c(r=>{let i=r.providers?.[e]??{},o=[...i.models??[]];return o[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:o}}}})},[]),H=(0,i.useCallback)((e,t)=>{T.current.get(e)?.splice(t,1),c(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})},[]),_=(0,i.useCallback)(async()=>{if(g)return;h(!0),m(null),b(!1);let e=a,t=M?.name.trim();if(M&&t&&a.providers?.[M.provider]){let n=P(a,M.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=[...I.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,T.current,I.current);$.current=new Set(Object.keys(e.providers??{})),T.current=l4(e),I.current.clear(),l.resync(t,n)}}catch(e){m(String(e))}finally{h(!1)}},[P,a,l,g,M,s]),U=Object.entries(a.providers??{}),K=e=>{let t=function(e,t){if(!e||e.allEnabled)return null;let n=aM(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},q=k.filter(e=>e.loggedIn),Z=S.filter(e=>e.configured),V=(()=>{if(!y)return null;if("oauth"===y.type){let e=k.find(e=>e.id===y.providerId);return e?(0,r.jsx)(ce,{provider:e,onRefresh:L,enabledModels:l},e.id):null}if("apikey"===y.type){let e=S.find(e=>e.id===y.providerId);return e?(0,r.jsx)(ct,{provider:e,onRefresh:L,enabledModels:l},e.id):null}if("provider"===y.type){let e=a.providers?.[y.name];return e?(0,r.jsx)(a2,{name:y.name,editingName:M?.provider===y.name?M.name:y.name,provider:e,onChange:e=>z(y.name,e),onEditingNameChange:e=>R(e===y.name?null:{provider:y.name,name:e}),onRename:e=>W(y.name,e),onDelete:()=>O(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)(a7,{providerName:y.providerName,provider:e,model:t,onChange:e=>B(y.providerName,y.index,e),onDelete:()=>H(y.providerName,y.index)},`${y.providerName}-${y.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(l3,{embedded:n,title:s("common.models"),subtitle:"~/.pi/agent/models.json",closeLabel:s("i18n.close"),onClose:t,children:[(0,r.jsx)(aL,{controller:l}),(0,r.jsxs)(l5,{children:[(0,r.jsxs)(l6,{children:[(0,r.jsxs)(l9,{children:[q.map(e=>{let t=y?.type==="oauth"&&y.providerId===e.id;return(0,r.jsxs)(an,{active:t,onClick:()=>j({type:"oauth",providerId:e.id}),children:[(0,r.jsx)(aD,{id:e.id,size:16}),(0,r.jsx)(ar,{className:"is-grow",children:e.name}),K(e.id)]},e.id)}),Z.map(e=>{let t=y?.type==="apikey"&&y.providerId===e.id;return(0,r.jsxs)(an,{active:t,onClick:()=>j({type:"apikey",providerId:e.id}),children:[(0,r.jsx)(aD,{id:e.id,size:16}),(0,r.jsx)(ar,{className:"is-grow",children:e.displayName}),K(e.id)]},e.id)}),(q.length>0||Z.length>0)&&U.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),d?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:s("i18n.loading")}):U.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)(an,{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)(ar,{className:"is-grow",children:t}),K(t)]}),o.map((e,n)=>{let i=y?.type==="model"&&y.providerName===t&&y.index===n;return(0,r.jsxs)(an,{active:i,className:"models-sidebar-indented-item",onClick:()=>j({type:"model",providerName:t,index:n}),children:[(0,r.jsx)(ar,{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)(an,{className:"models-sidebar-indented-item models-sidebar-add-item",onClick:e=>{e.stopPropagation(),F(t)},children:(0,r.jsxs)(ar,{children:["+ ",s("i18n.model")]})})]},t)})]}),(0,r.jsx)(aN,{onClick:()=>E(!0),children:s("i18n.addProvider")})]}),(0,r.jsx)(aj,{children:(0,r.jsx)(ai,{className:"is-fill",children:d?null:V??(0,r.jsx)(ay,{children:s("i18n.selectProviderModel")})})})]}),(0,r.jsxs)(ak,{status:(g||f)&&(0,r.jsx)("span",{style:{color:"#f87171"},children:g?s("models.configUnreadable",{error:g}):f}),children:[!n&&(0,r.jsx)(aS,{onClick:t,children:s("i18n.cancel")}),(0,r.jsxs)(aS,{variant:"primary",onClick:_,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)(cn,{oauthProviders:k,apiKeyProviders:S,onSelectOAuth:e=>j({type:"oauth",providerId:e}),onSelectApiKey:e=>j({type:"apikey",providerId:e}),onAddCustom:A,onClose:()=>E(!1)})]})}let ci=null;async function co(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(ci)return ci;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 ci=null,!1}})();return ci=t,t.then(e=>{e||ci!==t||(ci=null)}),t}function cs(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function cl(e,t){let n=t.replace(/[/\\]+$/,"");return n&&(e===n||e.startsWith(`${n}/`)||e.startsWith(`${n}\\`))?`./${e.slice(n.length).replace(/^[/\\]/,"")}`:cs(e)}function ca(e,t,n,r){return e.filter(e=>n(e)!==t&&(t||!r?.(e)))}function cc(e){return e?JSON.stringify([e.requiresTrust,e.trusted,e.decision,e.decisionPath??null,e.inherited]):""}function cd(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function cu(e,t){return t("project"===e?"skills.scope.project":"global"===e?"skills.scope.global":"skills.scope.path")}function cp(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function ch(e,t){return e?e.slice(0,8):t}function cf(e){let{skill:t,cwd:n,onToggle:i,toggling:o,saveError:s,updateStatus:l,checkingUpdate:a,updating:c,updateError:d,onCheckUpdate:u,onUpdate:p}=e,{t:h}=(0,eh.s)(),f=cd(t),m=!t.disableModelInvocation;return(0,r.jsxs)(ai,{children:[(0,r.jsxs)("div",{className:"skill-detail-heading",children:[(0,r.jsxs)(ao,{children:[(0,r.jsxs)(as,{children:[(0,r.jsx)(ah,{scope:f,children:cu(f,h)}),(0,r.jsx)("span",{className:"config-detail-path",children:"project"===f?cl(t.filePath,n):cs(t.filePath)})]}),(0,r.jsx)(al,{children:(0,r.jsx)(aC,{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)(ad,{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)(ad,{label:h("i18n.version"),children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:ch(l?.currentVersion??t.install.versionHash,h("i18n.unknown"))}),t.install.canCheckForUpdates&&(0,r.jsx)(aS,{size:"small",onClick:u,disabled:a||c,children:h("i18n.check")}),l?.state==="update-available"&&(0,r.jsx)("span",{className:"skill-version-value is-update",children:ch(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)(aS,{variant:"primary",size:"small",onClick:p,disabled:c||a,children:h(c?"i18n.updating":"i18n.update")})]}),d&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:d})]}),(0,r.jsx)(ad,{label:h("config.name"),children:(0,r.jsx)("span",{className:"skill-name-value",children:t.name})}),(0,r.jsx)(ad,{label:h("i18n.description"),children:(0,r.jsx)("span",{className:"skill-description",children:t.description})})]})}function cm(e){let{cwd:t,installedPackages:n,projectResourcesLoaded:o,onInstalled:s}=e,{t:l}=(0,eh.s)(),[a,c]=(0,i.useState)(""),[d,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]),E="global"===k?"~/.pi/agent/skills/":`${cs(t)}/.pi/skills/`;return(0,r.jsxs)(ai,{className:"is-full-height",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)(ag,{title:l("i18n.addSkill"),catalogs:[{href:"https://skills.sh",label:"skills.sh"}],target:(0,r.jsx)(am,{value:k,label:l("config.saveTo"),options:[{value:"global",label:cu("global",l)},{value:"project",label:cu("project",l),disabled:!o}],path:E,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=>c(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)(aS,{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})]}),d.length>0&&(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:d.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)(aS,{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 cg(e){let{cwd:t,onClose:n,embedded:o=!1,trust:s}=e,{t:l}=(0,eh.s)(),[a,c]=(0,i.useState)([]),[d,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(()=>lG("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,E]=(0,i.useState)({}),[$,I]=(0,i.useState)(new Set),[T,M]=(0,i.useState)(!1),[R,L]=(0,i.useState)(null),[A,z]=(0,i.useState)(null),[P,W]=(0,i.useState)(!0),O=(0,i.useCallback)(async()=>{u(!0),h(null);try{let e=await fetch(`/api/skills?cwd=${encodeURIComponent(t)}`),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);let r=n.skills??[];return c(r),W(n.projectResourcesLoaded??!0),m(e=>{if(e&&r.some(t=>t.filePath===e))return e;let t=r.find(e=>!e.disableModelInvocation)??r[0];return t?.filePath??null}),r}catch(e){return h(String(e)),[]}finally{u(!1)}},[t]);(0,i.useEffect)(()=>{E({}),z(null),O()},[t]);let F=cc(s),D=(0,i.useRef)(F);(0,i.useEffect)(()=>{D.current!==F&&(D.current=F,O())},[F,O]),(0,i.useEffect)(()=>{f&&lX("skills",f,t)},[t,f]);let B=(0,i.useCallback)(async e=>{let n=(e?[e]:a.filter(e=>!!e.install)).map(cp).filter(e=>!!e);if(0!==n.length){z(null),I(e=>new Set([...e,...n])),e||M(!0);try{let n=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,package:e?.install?.package,scope:e?.install?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);E(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){z(e instanceof Error?e.message:String(e))}finally{I(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),e||M(!1)}}},[t,a]),H=(0,i.useCallback)(async e=>{if(!e.install)return;let n=cp(e);L(n),z(null);try{let r=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,package:e.install.package,scope:e.install.scope})}),i=await r.json();if(!r.ok||i.error||!i.success)throw Error(i.error??`HTTP ${r.status}`);await O();let o=i.skill?.install?.versionHash;E(t=>({...t,[n]:{package:e.install.package,scope:e.install.scope,state:"up-to-date",currentVersion:o,latestVersion:o}}))}catch(e){z(e instanceof Error?e.message:String(e))}finally{L(null)}},[t,O]),_=(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}`);c(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n))}catch(e){b(String(e))}finally{x(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),U=(0,i.useCallback)(async(e,t,n)=>{let r=ca(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;c(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]),K=a.find(e=>e.filePath===f)??null,q=d||g.size>0||null!==R;return(0,r.jsxs)(l3,{embedded:o,title:l("common.skills"),subtitle:cs(t),closeLabel:l("i18n.close"),onClose:n,children:[!P&&(0,r.jsx)(ab,{message:l("trust.skillsNotLoaded")}),(0,r.jsxs)(l5,{children:[(0,r.jsxs)(l6,{children:[(0,r.jsx)(l9,{children:d?(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"===cd(e)&&!!e.install?.skillsShUrl},{label:t.project,matches:e=>"project"===cd(e)&&!e.install?.skillsShUrl},{label:`${t.global} / skills.sh`,matches:e=>"global"===cd(e)&&!!e.install?.skillsShUrl},{label:t.global,matches:e=>"global"===cd(e)&&!e.install?.skillsShUrl},{label:t.path,matches:e=>"path"===cd(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)(an,{active:i,onClick:()=>{m(e.filePath),C(!1)},children:[(0,r.jsx)(aE,{active:!o}),(0,r.jsx)(ar,{className:`is-grow${o?" is-muted":""}`,children:e.name}),(n=(t=cp(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)(l7,{aside:(0,r.jsx)(ae,{enabled:o,total:i.length,disabled:q,loading:y===t,label:l(s?"skills.groupSwitchOn":"skills.groupSwitchOff",{group:t}),onChange:e=>void U(t,i,e)}),children:t}),k?.group===t&&(0,r.jsx)(at,{error:k.error}),[...i.filter(e=>!e.disableModelInvocation),...i.filter(e=>e.disableModelInvocation)].map(n)]},t)})})()}),(0,r.jsx)(aN,{onClick:()=>C(!0),active:S,children:l("i18n.addSkill")})]}),(0,r.jsx)(aj,{children:(0,r.jsx)(ai,{className:"is-fill",children:S?(0,r.jsx)(cm,{cwd:t,projectResourcesLoaded:P,installedPackages:{global:new Set(a.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(a.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{O()}}):d?null:K?(0,r.jsx)(cf,{skill:K,cwd:t,onToggle:_,toggling:g.has(K.filePath),saveError:v,updateStatus:cp(K)?N[cp(K)]:void 0,checkingUpdate:!!cp(K)&&$.has(cp(K)),updating:R===cp(K),updateError:A,onCheckUpdate:()=>void B(K),onUpdate:()=>void H(K)},K.filePath):(0,r.jsx)(ay,{children:l("i18n.selectSkill")})})})]}),(0,r.jsxs)(ak,{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)(aS,{onClick:n,children:l("i18n.close")}),a.some(e=>!!e.install)&&(0,r.jsx)(aS,{variant:"secondary",onClick:()=>void B(),disabled:T||null!==R,children:T?l("i18n.checking"):l("i18n.checkUpdates")})]})]})}let cx={builtin:0,global:1,workspace:2,project:3},cv=["read","bash","edit","write","grep","find","ls"],cb=["","off","minimal","low","medium","high","xhigh","max"],cy={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},cj={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"},ck={background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"default"};function cw(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 cS(e){return`${e.scope}:${e.name}`}function cC(e){return"global"===e||"project"===e}function cN(e){return cC(e)||"builtin"===e}function cE(e){let{label:t,children:n}=e;return(0,r.jsx)(ad,{label:t,children:n})}function c$(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 cI(e){let{cwd:t,sessionId:n=null,onClose:o,onReloaded:s,embedded:l=!1,trust:a}=e,c=ew(),{t:d}=(0,eh.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)(()=>lG("agents",t)),[j,k]=(0,i.useState)(cy),[w,S]=(0,i.useState)("view"),[C,N]=(0,i.useState)("global"),[E,$]=(0,i.useState)(!0),[I,T]=(0,i.useState)(!1),[M,R]=(0,i.useState)(!1),[L,A]=(0,i.useState)(!1),[z,P]=(0,i.useState)(null),[W,O]=(0,i.useState)(!1),[F,D]=(0,i.useState)(10),[B,H]=(0,i.useState)(!0),[_,U]=(0,i.useState)(!1),[K,q]=(0,i.useState)(null),[Z,V]=(0,i.useState)(!1),[J,Y]=(0,i.useState)(!1),G=(0,i.useMemo)(()=>u.find(e=>cS(e)===b)??null,[u,b]),X=(0,i.useMemo)(()=>h.map(e=>({provider:e.provider,modelId:e.id,name:e.name})),[h]),Q=(0,i.useCallback)(async e=>{$(!0),P(null);try{let n=await fetch(`/api/subagents/profiles?cwd=${encodeURIComponent(t)}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);let i=r.profiles??[];p(i);let o=e??lG("agents",t),s=i.find(e=>cS(e)===o)??i.find(e=>"project"===e.scope)??i.find(e=>"global"===e.scope)??i[0]??null;y(s?cS(s):null),s&&(k(cw(s)),S(cC(s.scope)?"edit":"view"),cC(s.scope)&&N(s.scope))}catch(e){P(e instanceof Error?e.message:String(e))}finally{$(!1)}},[t]);(0,i.useEffect)(()=>{Q()},[Q]),(0,i.useEffect)(()=>{let e=new AbortController;return H(!0),q(null),(async()=>{try{let t=await fetch("/api/subagents/settings",{cache:"no-store",signal:e.signal}),n=await t.json();if(!t.ok||n.error||"boolean"!=typeof n.enabled)throw Error(n.error??`HTTP ${t.status}`);O(n.enabled),"number"==typeof n.maxConcurrent&&D(n.maxConcurrent)}catch(t){if(e.signal.aborted)return;q(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||H(!1)}})(),()=>e.abort()},[]),(0,i.useEffect)(()=>{b&&lX("agents",b,t)},[t,b]);let ee=cc(a);(0,i.useEffect)(()=>{let e=new AbortController;return g(!0),v(null),(async()=>{try{let n=await fetch(`/api/models?cwd=${encodeURIComponent(t)}`,{signal:e.signal}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);f(r.modelList??[]),v(r.modelError??null)}catch(t){if(e.signal.aborted)return;v(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||g(!1)}})(),()=>e.abort()},[t,ee]);let et=async()=>{T(!0),P(null),R(!1);try{let e=await fetch("/api/subagents/profiles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:C,profile:j})}),n=await e.json();if(!e.ok||n.error||!n.profile)throw Error(n.error??`HTTP ${e.status}`);await Q(cS(n.profile)),R(!0),setTimeout(()=>R(!1),2e3)}catch(e){P(e instanceof Error?e.message:String(e))}finally{T(!1)}},en=async()=>{if(G&&cC(G.scope)&&window.confirm(d("agents.deleteConfirm",{name:G.displayName}))){T(!0),P(null);try{let e=await fetch("/api/subagents/profiles",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:G.scope,name:G.name})}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);await Q()}catch(e){P(e instanceof Error?e.message:String(e))}finally{T(!1)}}},er="view"!==w,ei="create"===w,eo=!er||I||L,es=ei?C:G?.scope,el=ei?"global"===C?`~/.pi/agent/agents/${j.name||"..."}.md`:`./.pi/agents/${j.name||"..."}.md`:G?(G.filePath?"project"===G.scope||"workspace"===G.scope?cl(G.filePath,t):cs(G.filePath):null)??d("agents.builtinPath"):"",ea=ei?el:G?.filePath??el,ec=!j.model||h.some(e=>`${e.provider}/${e.id}`===j.model),ed=(()=>{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)}})(),eu=eo?{...cj,...ck}:cj,ep=ei?eo:!G||!cN(G.scope)||I||L,ef=(e,t)=>{k(n=>({...n,[e]:t}))},em=async e=>{if(ei)return void ef("enabled",e);if(G&&cN(G.scope)){A(!0),P(null);try{let n=await fetch("/api/subagents/profiles",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:G.scope,name:G.name,enabled:e})}),r=await n.json();if(!n.ok||r.error||!r.profile)throw Error(r.error??`HTTP ${n.status}`);let i=r.profile;p(e=>e.map(e=>cS(e)===cS(i)?i:e)),k(e=>({...e,enabled:i.enabled}))}catch(e){P(e instanceof Error?e.message:String(e))}finally{A(!1)}}},eg=async e=>{U(!0),q(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),r=await t.json();if(!t.ok||r.error||"boolean"!=typeof r.enabled)throw Error(r.error??`HTTP ${t.status}`);O(r.enabled),V(!!n)}catch(e){q(e instanceof Error?e.message:String(e))}finally{U(!1)}},ex=async e=>{D(e),q(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxConcurrent:e})}),n=await t.json();if(!t.ok||n.error||"number"!=typeof n.maxConcurrent)throw Error(n.error??`HTTP ${t.status}`);D(n.maxConcurrent)}catch(e){q(e instanceof Error?e.message:String(e))}},ev=async()=>{if(n){Y(!0),q(null);try{await sT(n,{type:"reload"}),V(!1),s?.()}catch(e){q(e instanceof Error?e.message:String(e))}finally{Y(!1)}}};return(0,r.jsxs)(l3,{embedded:l,title:d("common.agents"),subtitle:cs(t),closeLabel:d("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:d("agents.builtInTitle")}),(0,r.jsx)("span",{children:d("agents.builtInDescription")}),Z&&(0,r.jsx)("span",{role:"status",className:"agents-feature-reload-notice",children:d("agents.reloadRequired")})]}),(0,r.jsxs)("div",{className:"agents-feature-actions",children:[Z&&n&&(0,r.jsx)(aS,{size:"small",onClick:()=>void ev(),disabled:J||_,children:J?d("agents.reloading"):d("agents.reloadSession")}),(0,r.jsxs)("label",{className:"agents-concurrency-control",title:d("agents.maxConcurrentDescription"),children:[(0,r.jsx)("span",{children:d("agents.maxConcurrent")}),(0,r.jsx)("input",{"aria-label":d("agents.maxConcurrent"),type:"number",min:1,max:32,value:F,disabled:B||_,onChange:e=>D(Number(e.target.value)),onBlur:()=>void ex(F)})]}),(0,r.jsx)(aC,{checked:W,disabled:B||J,loading:_,label:d("agents.builtInTitle"),onChange:e=>void eg(e)})]})]}),(0,r.jsxs)(l5,{children:[(0,r.jsxs)(l6,{children:[(0,r.jsx)(l9,{children:E?(0,r.jsx)("div",{style:{padding:10,color:"var(--text-dim)",fontSize:12},children:d("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)(l7,{children:d(`agents.scope.${e}`)}),t.map(e=>{let t,n,i=(t=e.name.toLowerCase(),n=cx[e.scope],u.some(e=>e.name.toLowerCase()===t&&cx[e.scope]>n));return(0,r.jsxs)(an,{active:b===cS(e)&&!ei,onClick:()=>{y(cS(e)),k(cw(e)),S(cC(e.scope)?"edit":"view"),cC(e.scope)&&N(e.scope),P(null)},children:[(0,r.jsx)(aE,{active:e.enabled}),(0,r.jsx)(ar,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.displayName}),i&&(0,r.jsx)("span",{className:"agents-overridden-label",children:d("agents.overridden")})]},cS(e))})]},e)})}),(0,r.jsx)(aN,{active:ei,onClick:()=>{let e="custom-agent",t=2;for(;u.some(t=>t.name===e);)e=`custom-agent-${t++}`;y(null),k({...cy,name:e,displayName:e}),S("create"),N("global"),P(null)},children:d("agents.new")})]}),(0,r.jsx)(aj,{children:(0,r.jsx)(ai,{className:"is-fill",children:G||ei?(0,r.jsxs)(ai,{children:[(0,r.jsxs)(ao,{children:[(0,r.jsx)(as,{children:ei?(0,r.jsx)(am,{value:C,label:d("config.saveTo"),options:["global","project"].map(e=>({value:e,label:d(`agents.scope.${e}`),disabled:I})),path:el,onChange:N}):(0,r.jsxs)(r.Fragment,{children:[es&&(0,r.jsx)(ah,{scope:es,children:d(`agents.scope.${es}`)}),(0,r.jsx)("span",{title:ea,className:"config-detail-path",children:el})]})}),(0,r.jsxs)(al,{children:[G&&("view"===w||"edit"===w)&&(0,r.jsx)(aS,{size:"small",onClick:()=>{if(!G)return;let e=function(e,t){let n=new Set(t.map(e=>e.name.toLowerCase())),r=`${e}-copy`,i=r,o=2;for(;n.has(i.toLowerCase());)i=`${r}-${o++}`;return i}(G.name,u);y(null),k({...cw(G),name:e,displayName:d("agents.copyName",{name:G.displayName})}),S("create"),N(cC(G.scope)?G.scope:"global"),P(null)},disabled:I||L,children:d("agents.duplicate")}),G&&cC(G.scope)&&"edit"===w&&(0,r.jsx)(aS,{variant:"danger",size:"small",onClick:()=>void en(),disabled:I||L,children:d("agents.delete")}),(0,r.jsx)(aC,{checked:j.enabled,disabled:ep,label:j.enabled?d("agents.disable"):d("agents.enable"),onChange:e=>void em(e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:c?"1fr":"minmax(0, 1fr) minmax(0, 1fr)",gap:12},children:[(0,r.jsx)(cE,{label:d("agents.name"),children:ei?(0,r.jsx)("input",{"aria-label":d("agents.name"),value:j.name,disabled:eo,onChange:e=>ef("name",e.target.value),style:cj}):(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)(cE,{label:d("agents.displayName"),children:(0,r.jsx)("input",{"aria-label":d("agents.displayName"),value:j.displayName,disabled:eo,onChange:e=>ef("displayName",e.target.value),style:eu})})]}),(0,r.jsx)(cE,{label:d("agents.description"),children:(0,r.jsx)("input",{"aria-label":d("agents.description"),value:j.description,disabled:eo,onChange:e=>ef("description",e.target.value),style:eu})}),(0,r.jsx)(cE,{label:d("agents.prompt"),children:(0,r.jsx)("textarea",{className:"agents-system-prompt","aria-label":d("agents.prompt"),value:j.systemPrompt,disabled:eo,onChange:e=>ef("systemPrompt",e.target.value),style:{...eu,height:195,minHeight:195,maxHeight:"60vh",padding:9,overflow:"auto",resize:eo?"none":"vertical",lineHeight:1.5}})}),(0,r.jsx)(cE,{label:d("agents.tools"),children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 16px"},children:cv.map(e=>(0,r.jsx)(c$,{label:e,disabled:eo,checked:j.tools.includes(e),onChange:t=>ef("tools",t?[...j.tools,e]:j.tools.filter(t=>t!==e))},e))})}),(0,r.jsxs)(cE,{label:d("agents.resources"),children:[(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 20px"},children:[(0,r.jsx)(c$,{label:d("agents.loadSkills"),disabled:eo,checked:j.loadSkills,onChange:e=>ef("loadSkills",e)}),(0,r.jsx)(c$,{label:d("agents.loadExtensions"),disabled:eo,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?d("agents.skillsOnly",{skills:j.skills.join(", ")}):d("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?d("agents.extensionsOnly",{extensions:j.extensions.join(", ")}):d("agents.extensionsNone")})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:c?"1fr":"minmax(0, 1.5fr) minmax(120px, 0.75fr) minmax(100px, 0.5fr)",gap:12},children:[(0,r.jsx)(cE,{label:d("agents.model"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(oU,{options:X,value:ed,onChange:(e,t)=>ef("model",`${e}/${t}`),onClear:()=>ef("model",void 0),emptyLabel:m?d("agents.modelsLoading"):d("agents.inherit"),selectedLabel:j.model&&!ec?d("agents.modelUnavailable",{model:j.model}):void 0,disabled:eo||m||0===h.length&&!j.model,ariaLabel:d("agents.model"),variant:"field",placement:"auto"}),x&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:10},children:x})]})}),(0,r.jsx)(cE,{label:d("agents.thinking"),children:(0,r.jsx)("select",{"aria-label":d("agents.thinking"),value:j.thinking??"",disabled:eo,onChange:e=>ef("thinking",e.target.value||void 0),style:eu,children:cb.map(e=>(0,r.jsx)("option",{value:e,children:e||d("agents.inherit")},e||"default"))})}),(0,r.jsx)(cE,{label:d("agents.maxTurns"),children:(0,r.jsx)("input",{"aria-label":d("agents.maxTurns"),type:"number",min:1,value:j.maxTurns??"",disabled:eo,onChange:e=>ef("maxTurns",e.target.value?Number(e.target.value):void 0),style:eu})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"10px 20px"},children:[(0,r.jsx)(c$,{label:d("agents.inheritContext"),disabled:eo,checked:j.inheritContext,onChange:e=>ef("inheritContext",e)}),(0,r.jsx)(c$,{label:d("agents.background"),disabled:eo,checked:j.runInBackground,onChange:e=>ef("runInBackground",e)})]})]}):(0,r.jsx)(ay,{children:d("agents.empty")})})})]}),(0,r.jsx)(ak,{status:(K||z)&&(0,r.jsx)("span",{role:"alert",style:{color:"#ef4444"},children:K||z}),children:er&&(0,r.jsxs)(aS,{variant:"primary",onClick:()=>void et(),disabled:I||M||L||!j.name.trim(),className:M?"is-success":void 0,children:[M&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:M?d("i18n.saved"):I?d("agents.saving"):d("agents.save")})]})})]})}let cT=["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"];function cM(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function cR(e){return`${e.scope}\0${e.source}`}function cL(e){return`extension\0${e.path}`}function cA(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function cz(e,t){return t(`plugins.status.${e}`)}function cP(e){return`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`}function cW(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function cO(e){let{pkg:t}=e,{t:n}=(0,eh.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 cF(e){let{cwd:t,source:n,scope:i,projectResourcesLoaded:o,busy:s,actionError:l,onSourceChange:a,onScopeChange:c,onInstall:d}=e,{t:u}=(0,eh.s)();return(0,r.jsx)(ax,{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)(am,{value:i,label:u("config.saveTo"),options:[{value:"global",label:cA("global",u)},{value:"project",label:cA("project",u),disabled:!o}],path:"project"===i?`${cs(t)}/.pi/{npm,git}`:"~/.pi/agent/{npm,git}",disabledReason:u("trust.projectScopeUnavailable"),onChange:c}),inputLabel:u("config.source"),inputId:"plugin-source",placeholder:"npm:@scope/package",value:n,canSubmit:!s&&!!n.trim(),normalizeValue:cM,onValueChange:a,onSubmit:d,examplesLabel:u("config.examples"),examples:cT,error:l,children:(0,r.jsx)(aS,{variant:"primary",onClick:d,disabled:s||!n.trim(),className:"is-pushed-right",children:u(s?"i18n.installing":"i18n.install")})})}function cD(e){let t,{pkg:n,cwd:o,busyKey:s,actionError:l,actionMessage:a,sessionId:c,updateStatus:d,checkingUpdate:u,updateError:p,onAction:h,onCheckUpdate:f,onReloadSession:m}=e,{t:g}=(0,eh.s)(),x=cR(n),v=(s?.endsWith(x)||s?.startsWith("bulk:"))??!1,b="reload"===s,y=!n.disabled,j=n.canCheckForUpdates,k=d?.state==="update-available",w=n.description?.trim(),S=(0,i.useId)();return(0,r.jsxs)(ai,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(ao,{className:"is-top-aligned",children:[(0,r.jsxs)(as,{children:[(0,r.jsx)(ah,{scope:n.scope,children:cA(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)(al,{children:[(0,r.jsx)(aS,{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)(aS,{size:"small",onClick:m,disabled:!c||b||v,"aria-describedby":c?void 0:S,children:g(b?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)(aS,{variant:"danger",size:"small",onClick:()=>h("remove",n),disabled:v||b,children:g(s===`remove:${x}`?"i18n.removing":"i18n.remove")}),(0,r.jsx)(aC,{checked:y,loading:v||b,onChange:()=>h(n.disabled?"enable":"disable",n),label:g(n.disabled?"i18n.enablePackage":"i18n.disablePackage")})]})]}),!c&&(0,r.jsx)("div",{id:S,className:"config-detail-heading-note",children:g("i18n.openSessionToReload")})]}),(0,r.jsxs)(au,{children:[w&&(0,r.jsx)(ap,{label:g("i18n.description"),children:w}),(0,r.jsx)(ap,{label:g("i18n.status"),tone:"plain",style:{color:cW(n.status),textTransform:"capitalize"},children:cz(n.status,g)}),(0,r.jsxs)(ap,{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:d.displayName,children:g("i18n.updateAvailable")}),j&&(u||d&&!k)&&(0,r.jsx)("span",{className:`skill-update-status ${u?"is-checking":d?.state==="up-to-date"?"is-success":d?.state==="error"?"is-error":"is-muted"}`,children:u?g("i18n.checking"):d?.state==="up-to-date"?g("i18n.upToDate"):d?.state==="unsupported"?g("i18n.automaticChecksUnavailable"):d?.message||g("i18n.checkFailed")})]}),p&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:p})]}),(0,r.jsx)(ap,{label:g("i18n.package"),mono:!0,children:n.packageName??g("i18n.unknown")}),(0,r.jsx)(ap,{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)(ap,{label:g("i18n.installedPath"),tone:n.installedPath?"muted":"error",mono:!0,children:n.installedPath?cs(n.installedPath):g("i18n.notFound")}),(0,r.jsx)(ap,{label:g("i18n.cwd"),tone:"dim",mono:!0,children:cs(o)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)(ac,{children:g("i18n.resolvedResources")}),(0,r.jsx)(cO,{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 cB(e){let{extension:t}=e,{t:n}=(0,eh.s)(),i=t.enabled?"loaded":"disabled";return(0,r.jsxs)(ai,{children:[(0,r.jsx)(ao,{children:(0,r.jsxs)(as,{children:[(0,r.jsx)(ah,{scope:t.scope,children:cA(t.scope,n)}),(0,r.jsx)(aa,{children:t.name})]})}),(0,r.jsxs)(au,{children:[(0,r.jsx)(ap,{label:n("i18n.status"),tone:"plain",style:{color:t.enabled?"var(--accent)":"var(--text-dim)"},children:cz(i,n)}),(0,r.jsx)(ap,{label:n("i18n.installedPath"),mono:!0,children:cs(t.path)})]})]})}function cH(e){var t;let{cwd:n,sessionId:o,onClose:s,onReloaded:l,embedded:a=!1,trust:c}=e,{t:d}=(0,eh.s)(),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!0),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(()=>lG("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),[E,$]=(0,i.useState)(null),[I,T]=(0,i.useState)(null),[M,R]=(0,i.useState)(null),[L,A]=(0,i.useState)({}),[z,P]=(0,i.useState)(new Set),[W,O]=(0,i.useState)(!1),[F,D]=(0,i.useState)(null),[B,H]=(0,i.useState)(!1),_=(0,i.useMemo)(()=>u?.packages??[],[u?.packages]),U=(0,i.useMemo)(()=>u?.standaloneExtensions??[],[u?.standaloneExtensions]),K=_.find(e=>cR(e)===x)??null,q=U.find(e=>cL(e)===x)??null,Z=u?.projectResourcesLoaded??!0,V=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:_.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[_]),J=(0,i.useCallback)(async()=>{f(!0),g(null),R(null);try{let e=await fetch(`/api/plugins?cwd=${encodeURIComponent(n)}`),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);p(t),y(e=>0===t.packages.length&&0===t.standaloneExtensions.length||e),v(e=>e&&(t.packages.some(t=>cR(t)===e)||t.standaloneExtensions.some(t=>cL(t)===e))?e:t.packages[0]?cR(t.packages[0]):t.standaloneExtensions[0]?cL(t.standaloneExtensions[0]):null)}catch(e){g(e instanceof Error?e.message:String(e))}finally{f(!1)}},[n]);(0,i.useEffect)(()=>{A({}),D(null),J()},[n]);let Y=cc(c),G=(0,i.useRef)(Y);(0,i.useEffect)(()=>{G.current!==Y&&(G.current=Y,J())},[Y,J]),(0,i.useEffect)(()=>{x&&lX("plugins",x,n)},[n,x]);let X=(0,i.useCallback)(async e=>{let t=(e?[e]:_.filter(e=>e.canCheckForUpdates)).map(cR);if(0!==t.length){D(null),P(e=>new Set([...e,...t])),e||O(!0);try{let t=await fetch("/api/plugins/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n,source:e?.source,scope:e?.scope})}),r=await t.json();if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);A(e=>{let t={...e};for(let e of r.updates??[])t[cR(e)]=e;return t})}catch(e){D(e instanceof Error?e.message:String(e))}finally{P(e=>{let n=new Set(e);for(let e of t)n.delete(e);return n}),e||O(!1)}}},[n,_]),Q=(0,i.useCallback)(async()=>{H(!0),$(null),T(null),D(null);try{let e=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"update",cwd:n})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);p(t),A({}),T(d("i18n.packagesUpdated")),o&&T(`${d("i18n.packagesUpdated")} ${d("agents.reloadRequired")}`)}catch(e){$(e instanceof Error?e.message:String(e))}finally{H(!1)}},[n,o,d]),ee=(0,i.useCallback)(async(e,t)=>{let r=cR(t);N(`${e}:${r}`),$(null),T(null),R(null);try{let i=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,source:t.source,scope:t.scope,cwd:n})}),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]?cR(o.packages[0]):o.standaloneExtensions[0]?cL(o.standaloneExtensions[0]):null),0===o.packages.length&&0===o.standaloneExtensions.length&&y(!0),T(d("i18n.packageRemoved")),A(e=>{let t={...e};return delete t[r],t});else{let t={install:d("i18n.packageInstalled"),update:d("i18n.packageUpdated"),disable:d("i18n.packageDisabled"),enable:d("i18n.packageEnabled")};T(t[e]),"update"===e&&A(e=>{let t={...e};return delete t[r],t})}}catch(e){$(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,d]),et=(0,i.useCallback)(async(e,t,r)=>{let i=ca(t,r,e=>!e.disabled,e=>e.filtered),s=r?0:t.filter(e=>!e.disabled&&e.filtered).length,l=s>0?d("plugins.bulkKeptFiltered",{count:s}):void 0;if($(null),T(null),R(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:c,...u}=s;p(u);let h=c.filter(e=>e.error);if(h.length<c.length){let e=r?d("plugins.bulkEnabled"):d("plugins.bulkDisabled");T(o?`${e} ${d("agents.reloadRequired")}`:e)}h.length>0&&R({scope:e,note:l,error:[d("plugins.bulkFailed",{count:h.length,total:c.length}),...h.map(e=>`${e.source}: ${e.error}`)].join("\n")})}catch(t){R({scope:e,note:l,error:t instanceof Error?t.message:String(t)})}finally{N(null)}},[n,o,d]),en=(0,i.useCallback)(async()=>{let e=cM(j).trim();if(!e)return;k(e);let t=`${w}\0${e}`;N(`install:${t}`),$(null),T(null),R(null);try{var r;let i,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?cR(a):t),y(!1),k(""),T(d("i18n.packageInstalled"))}catch(e){$(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,w,j,d]),er=(0,i.useCallback)(async()=>{if(o){N("reload"),$(null),T(null),R(null);try{await sT(o,{type:"reload"}),l?.(),await J(),T(d("i18n.sessionReloaded"))}catch(e){$(e instanceof Error?e.message:String(e))}finally{N(null)}}},[J,l,o,d]),ei=C?.startsWith("install:")??!1,eo=Object.values(L).filter(e=>"update-available"===e.state).length,es=_.some(e=>e.canCheckForUpdates),el=h||null!==C||z.size>0||B;return(0,r.jsxs)(l3,{embedded:a,title:d("common.plugins"),subtitle:cs(n),closeLabel:d("i18n.close"),onClose:s,children:[!Z&&(0,r.jsx)(ab,{message:d("trust.pluginsNotLoaded")}),(0,r.jsxs)(l5,{children:[(0,r.jsxs)(l6,{children:[(0,r.jsx)(l9,{children:h?(0,r.jsx)("div",{className:"config-sidebar-message",children:d("i18n.loading")}):m?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:m}):0===_.length&&0===U.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:d("i18n.noPlugins")}):(0,r.jsxs)(r.Fragment,{children:[U.length>0&&(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(l7,{children:d("i18n.extensions")}),U.map(e=>{let t=cL(e);return(0,r.jsxs)(an,{active:!b&&x===t,title:e.path,onClick:()=>{v(t),y(!1),$(null),T(null)},children:[(0,r.jsx)(aE,{active:e.enabled}),(0,r.jsx)(ar,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.name})]},t)})]}),V.map(e=>{let t=e.packages.filter(e=>!e.disabled).length,n=t===e.packages.length;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(l7,{aside:(0,r.jsx)(ae,{enabled:t,total:e.packages.length,disabled:el,loading:C===`bulk:${e.scope}`,label:d(n?"plugins.groupSwitchOn":"plugins.groupSwitchOff",{group:cA(e.scope,d)}),onChange:t=>void et(e.scope,e.packages,t)}),children:cA(e.scope,d)}),M?.scope===e.scope&&(0,r.jsx)(at,{error:M.error,note:M.note}),e.packages.map(e=>{let t=cR(e),n=!b&&x===t;return(0,r.jsxs)(an,{active:n,title:e.description??e.source,onClick:()=>{v(t),y(!1),$(null),T(null)},children:[(0,r.jsx)(aE,{active:!e.disabled,color:cW(e.status)}),(0,r.jsx)(ar,{className:`is-grow${e.disabled?" is-muted":""}`,children:e.source}),L[cR(e)]?.state==="update-available"&&(0,r.jsx)("span",{title:d("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"})]},t)})]},e.scope)})]})}),(0,r.jsx)(aN,{active:b,onClick:()=>{y(!0),$(null),T(null)},children:d("i18n.addPlugin")})]}),(0,r.jsx)(aj,{children:(0,r.jsx)(ai,{className:"is-fill",children:b?(0,r.jsx)(cF,{cwd:n,source:j,scope:w,projectResourcesLoaded:Z,busy:ei,actionError:E,onSourceChange:k,onScopeChange:S,onInstall:en}):h?null:q?(0,r.jsx)(cB,{extension:q}):K?(0,r.jsx)(cD,{pkg:K,cwd:n,busyKey:C,actionError:E,actionMessage:I,sessionId:o,updateStatus:L[cR(K)],checkingUpdate:z.has(cR(K)),updateError:F,onAction:ee,onCheckUpdate:()=>void X(K),onReloadSession:er},cR(K)):(0,r.jsx)(ay,{children:d("i18n.selectPackage")})})})]}),(0,r.jsxs)(ak,{status:eo>0?(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--accent)"},children:[eo," ",1===eo?d("i18n.update"):d("i18n.updates")]}):u?.diagnostics.length?(0,r.jsx)(aw,{tone:u.diagnostics.some(e=>"error"===e.type)?"error":"warning",summary:1===u.diagnostics.length?d("plugins.diagnostic"):d("plugins.diagnostics",{count:u.diagnostics.length}),details:u.diagnostics.map(cP)}):(0,r.jsx)(aw,{summary:u?[d("i18n.resourceCount",{count:(t=u.totals).extensions,label:d("i18n.extensionShort")}),d("i18n.resourceCount",{count:t.skills,label:d("i18n.skillShort")}),d("i18n.resourceCount",{count:t.prompts,label:d("i18n.promptShort")}),d("i18n.resourceCount",{count:t.themes,label:d("i18n.themeShort")})].join(" \xb7 "):""}),children:[!a&&(0,r.jsx)(aS,{onClick:s,children:d("i18n.close")}),es&&(0,r.jsx)(aS,{variant:eo>0?"primary":"secondary",onClick:()=>void(eo>0?Q():X()),disabled:el,title:eo>0?d("i18n.updateAllPluginsHint"):void 0,children:B?d("i18n.updating"):W?d("i18n.checking"):eo>0?`${d("i18n.updateAllPlugins")} (${eo})`:d("i18n.checkUpdates")}),(0,r.jsx)(aS,{variant:"secondary",onClick:()=>void J(),disabled:el,children:d("i18n.refresh")})]})]})}let c_={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 cU(e,t){return e.replace(/\{(\w+)\}/g,(e,n)=>void 0===t[n]?e:String(t[n]))}function cK(e){let t=e.replace(/[\\/]+$/,""),n=t.split(/[\\/]/);return n[n.length-1]||t}function cq(e){var t;let n,{onClose:o,embedded:s=!1}=e,{locale:l}=(0,eh.s)(),a=c_[l]??c_.en,[c,d]=(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,S]=(0,i.useState)(null),C=(0,i.useCallback)(async()=>{g(!1);try{let[e,t]=await Promise.all([fetch("/api/archives",{cache:"no-store"}),fetch("/api/home",{cache:"no-store"})]);if(!e.ok)throw Error("load failed");let n=await e.json(),r=await t.json().catch(()=>({}));"string"==typeof r.home&&f(r.home);let i=Array.isArray(n.projects)?n.projects:[];d(i),p(e=>e&&i.some(t=>t.key===e)?e:i[0]?.key??null)}catch{g(!0)}},[]);(0,i.useEffect)(()=>{C()},[C]);let N=c.find(e=>e.key===u)??null,E=async e=>{if(0!==e.length){v(!0),S(null);try{for(let t of R(e)){let e={action:"set",ids:t,archived:!1},n=await fetch("/api/sessions/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store"});if(!n.ok)throw Error(`unarchive failed: ${n.status}`)}y(!1),k(""),await C()}catch{S(a.loadFailed)}finally{v(!1)}}},$=async e=>{v(!0),S(null);try{let t=await fetch("/api/archives/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectKey:e.key,confirm:j.trim()})}),n=await t.json().catch(()=>({}));if(409===t.status&&n.runningSessionIds?.length)return void S(a.runningBlocked);if(!t.ok)throw Error(n.error??"delete failed");y(!1),k(""),d(t=>t.filter(t=>t.key!==e.key)),p(t=>t===e.key?null:t)}catch{S(a.deleteFailed)}finally{v(!1)}};return(0,r.jsx)(l3,{embedded:s,title:a.title,onClose:o,children:m?(0,r.jsx)(ay,{children:a.loadFailed}):0===c.length?(0,r.jsx)(ay,{children:a.empty}):(0,r.jsxs)(l5,{children:[(0,r.jsx)(l6,{children:(0,r.jsx)(l9,{children:c.map(e=>(0,r.jsx)(an,{active:e.key===u,onClick:()=>{p(e.key),y(!1),k(""),S(null)},children:(0,r.jsx)(ar,{title:e.root,children:cK(e.root)})},e.key))})}),(0,r.jsx)(aj,{children:N?(0,r.jsxs)(ai,{children:[(0,r.jsxs)(ao,{children:[(0,r.jsx)(as,{children:(0,r.jsx)(aa,{children:cK(N.root)})}),(0,r.jsxs)(al,{children:[(0,r.jsx)(aS,{variant:"secondary",size:"small",disabled:x||0===N.families.length,onClick:()=>void E(N.families.map(e=>e.id)),children:x?a.busy:a.unarchive}),!b&&(0,r.jsx)(aS,{variant:"danger",size:"small",disabled:x||0===N.families.length,onClick:()=>{y(!0),k(""),S(null)},children:a.deleteSessions})]})]}),(0,r.jsx)(ad,{label:a.path,children:(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",wordBreak:"break-all"},children:(t=N.root,h&&t.startsWith(h)?"~"+t.slice(h.length):t)})}),b&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:cU(a.deleteConfirmLead,{count:N.families.length})}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:a.deleteConfirmHint}),(0,r.jsx)("input",{value: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)(aS,{variant:"danger",size:"small",disabled:x||"confirm"!==(n=j.trim().toLowerCase())&&"确认"!==n&&"確認"!==n,onClick:()=>void $(N),children:x?a.busy:a.deleteSessions}),(0,r.jsx)(aS,{variant:"ghost",size:"small",disabled:x,onClick:()=>{y(!1),k("")},children:a.cancel})]})]}),(0,r.jsx)(ac,{children:cU(a.sessions,{count:N.families.length})}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2,minHeight:0,overflowY:"auto"},children:N.families.map(e=>{let t=function(e,t){let n=e.name?.trim();if(n)return n;let r=e.firstMessage?.replace(/\s+/g," ").trim();return r&&"(no messages)"!==r?r:t}(e,a.untitled);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3,padding:"8px 10px",borderRadius:6,background:"var(--bg-hover)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,fontSize:12,fontWeight:500,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:t,children:t}),(0,r.jsx)(aS,{variant:"ghost",size:"small",disabled:x,onClick:()=>void E([e.id]),children:x?a.busy:a.unarchive})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,fontSize:11,color:"var(--text-muted)"},children:[(0,r.jsx)("span",{children:(0,tl.fw)(new Date(e.archivedAt),l)}),(0,r.jsx)("span",{children:cU(a.messages,{count:e.messageCount})})]})]},e.id)})}),w&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:w})]}):(0,r.jsx)(ay,{children:a.empty})})]})})}let cZ="\\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",cV=RegExp(`[${cZ}]`,"gu"),cJ=RegExp(`[${cZ}]`,"u");function cY(e){return e.replace(cV,e=>{let t=e.codePointAt(0)??0;return`\\u{${t.toString(16).toUpperCase().padStart(4,"0")}}`})}let cG=/[\s"'`$|&;<>()*?#~]/;function cX(e){let t=cJ.test(e),n=cY(e);return""===n||t||cG.test(n)?`"${n.replace(/"/g,'\\"')}"`:n}function cQ(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return[e,...t].map(cX).join(" ")}function c0(e){let t=void 0!==e.command?cQ(e.command,e.args):void 0,n=void 0!==e.url?cY(e.url):void 0;return"http"===e.transport?n:"stdio"===e.transport?t:n??t}function c1(e){return[e.name,e.command,e.cwd,e.url,...e.args??[],...e.envNames,...e.headerNames].some(e=>void 0!==e&&cJ.test(e))}function c2(e){return"oauth-client-secret"===e.kind?{key:"mcp.field.oauthClientSecret"}:{key:"env"===e.kind?"mcp.field.env":"mcp.field.header",params:{name:cY(e.name??"")}}}function c4(e){return"http"===e.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables"}function c8(e){return e.length>0?{key:"mcp.server.overridesGlobal",params:{keys:e.join(", ")}}:{key:"mcp.server.overridesGlobalNothing"}}function c3(e){return e.flatMap(e=>{let{variables:t,...n}=e;return t.map(e=>({variable:e,field:n}))})}function c5(e,t){return"unparsable"===e.reason||"unreadable"===e.reason?cY(e.error):"link-outside"===e.reason?void 0===t?void 0:cY(t):void 0}let c6="codemode";function c9(e){return`${e.scope}\0${e.name}`}function c7(e){return e?.trust?.decision===!0}function de(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":"global"===e.scope&&e.overriddenByProject&&t.projectServersLoad?"overridden":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 dt={invalid:"mcp.state.invalid","web-password":"mcp.state.web-password",disabled:"mcp.state.disabled","not-trusted":"mcp.state.not-trusted",replaced:"mcp.state.replaced",overridden:"mcp.state.overridden","mcp-off":"mcp.state.mcp-off",connected:"mcp.state.connected","needs-auth":"mcp.state.needs-auth",failed:"mcp.state.failed",connecting:"mcp.state.connecting",disconnected:"mcp.state.disconnected",conflict:"mcp.state.conflict",on:"mcp.state.on"},dn={connected:"mcp.state.session.connected",failed:"mcp.state.session.failed"};function dr(e,t){return(t?.origin==="session"?dn[e]:void 0)??dt[e]}let di={disabled:"mcp.server.disabled","not-trusted":"mcp.stateDetail.not-trusted",replaced:"mcp.server.shadowedByProject",overridden:"mcp.server.overriddenByProject","mcp-off":"mcp.stateDetail.mcp-off",disconnected:"mcp.stateDetail.disconnected",conflict:"mcp.stateDetail.conflict"},ds={invalid:"mcp.stateShort.invalid","web-password":"mcp.stateShort.web-password",disabled:"mcp.stateShort.disabled","not-trusted":"mcp.stateShort.not-trusted",replaced:"mcp.stateShort.replaced",overridden:"mcp.stateShort.overridden","needs-auth":"mcp.stateShort.needs-auth",failed:"mcp.stateShort.failed",connecting:"mcp.stateShort.connecting",disconnected:"mcp.stateShort.disconnected",conflict:"mcp.stateShort.conflict"};function dl(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 da(e){return"on"===e?{active:!0}:"off"===e?{active:!1}:{color:"error"===e?"#ef4444":"#f59e0b"}}function dc(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 dd={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"},du={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"},dp={connecting:"off",connected:"on","needs-auth":"warning",failed:"error",disconnected:"warning",conflict:"error","not-trusted":"warning"},dh={codemode:"mcp.exposure.codemode",deferred:"mcp.exposure.deferred",direct:"mcp.exposure.direct",hidden:"mcp.exposure.hidden"},df=["codemode","deferred","direct","hidden"],dm={codemode:"mcp.exposureShort.codemode",deferred:"mcp.exposureShort.deferred",direct:"mcp.exposureShort.direct",hidden:"mcp.exposureShort.hidden"};function dg(e){return"auto-enable-codemode-invalid"!==e.reason}function dx(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 dv(e){return{enabled:e.filter(e=>e.enabled).length,total:e.length}}function db(e,t){let n=e.flatMap(e=>e.servers.map(c9));return t===c6||null!==t&&n.includes(t)?t:n[0]??null}function dy(e){let t=e?.trust;return void 0!==t&&t.requiresTrust&&!t.trusted}function dj(e){return e.projectOverride?.preference??e.preference}let dk={always:"mcp.codemode.projectOverride.always",automatic:"mcp.codemode.projectOverride.automatic"},dw={on:"mcp.codemode.toolMode.onDescription",only:"mcp.codemode.toolMode.onlyDescription"},dS={on:"mcp.codemode.toolMode.projectOverride.on",only:"mcp.codemode.toolMode.projectOverride.only"},dC={automatic:"mcp.codemode.automatic",always:"mcp.codemode.always",unavailable:"mcp.codemode.unavailable",unknown:"i18n.unknown"};function dN(e){return"unavailable"===e?"error":"unknown"===e?"off":"on"}let dE=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e);function d$(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}:{},...dE(n.names)?{names:n.names}:{},...dE(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 dI(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 dT(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 dM(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&&dT(i)?{ok:!0,data:i}:{ok:!1,error:d$(i,r.status)}}let dR=new Set(["cwd-invalid","cwd-denied","cwd-not-directory"]);async function dL(e,t,n){let r=await dM(e,t,n);if(r.ok||!e||!r.error.reason||!dR.has(r.error.reason))return r;let i=await dM(null,t,n);return i.ok?{...i,projectError:r.error}:i}async function dA(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 dI(n=>dL(e,t,n),()=>({ok:!1,error:{error:`GET /api/mcp did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function dz(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:d$(o,i.status)}}async function dP(e,t,n){let r=await dz({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 dW(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 dI(n=>dP(e,t,n),()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function dO(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 dI(async n=>{let r=await dz({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 dF(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 dI(async n=>{let r=await dz({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 dD(e){return!e.available&&"builtin-disabled"!==e.reason}function dB(e,t){if(dD(t.mcp))return"mcp-off";if("project"===e){if(!t.project?.trust)return"trust-unreadable";if(!c7(t.project))return"project-untrusted"}}let dH={"mcp-off":"mcp.readOnly.mcp-off","project-untrusted":"mcp.readOnly.project-untrusted","trust-unreadable":"mcp.readOnly.trust-unreadable"};function d_(e){return!0!==e.notAnObject}function dU(e){return d_(e)&&void 0===e.webPasswordField}async function dK(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&&dT(i)?{ok:!0,data:i}:{ok:!1,error:d$(i,r.status)}}async function dq(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 dI(e=>dK(o,n,e),()=>({ok:!1,error:{error:`POST /api/mcp did not answer within ${i} ms`,timedOut:!0}}),i,r)}let dZ={"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 dV(e,t){let n=dB(e.scope,t);return n||(void 0===e.invalidError&&e.validated?e.webPasswordField?"web-password":void 0:"invalid")}let dJ={"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"},dY={connected:"mcp.test.state.connected","needs-auth":"mcp.test.state.needs-auth",failed:"mcp.test.state.failed",timedOut:"mcp.test.state.timedOut"},dG={connected:"mcp.test.summary.connected","needs-auth":"mcp.test.summary.needs-auth",failed:"mcp.test.summary.failed",timedOut:"mcp.test.summary.timedOut"},dX={connected:"mcp.signIn.summary.connected","needs-auth":"mcp.signIn.summary.needs-auth",failed:"mcp.signIn.summary.failed",timedOut:"mcp.signIn.summary.timedOut"};function dQ(e){return(Math.max(0,e)/1e3).toFixed(1)}async function d0(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:d$(i,r.status)}}async function d1(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 dI(e=>d0(o,n,e),()=>({ok:!1,error:{error:`POST /api/mcp/test did not answer within ${i} ms`,timedOut:!0}}),i,r,{abortAtDeadline:!1})}let d2="•••",d4=new Set(["key","apikey","token","secret","password","passwd","passphrase","pwd","pass","credential","credentials","authorization","bearer","jwt","cookie","signature","pat"]),d8=new Set([...d4,"auth","sig","code","pw"]),d3=["token","secret","password","passwd","apikey"],d5=new Set(["file","path","dir","url","uri","endpoint","id","name","type","header","env","var","length","ttl","expiry","expires","timeout","mode","format"]),d6=new Set(["-k"]);function d9(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 d7(e,t){let n=d9(e);return!(n.length>1&&d5.has(n[n.length-1]))&&n.some(e=>t.has(e)||d3.some(t=>e.length>t.length&&e.endsWith(t)))}function ue(e){return d7(e,d4)}let ut=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,})"),un=/^eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*$/,ur=/^[A-Za-z0-9_\-+/=.~]+$/;function ui(e){return!(/\s/.test(e)||uc(e))&&(!!(ut.test(e)||un.test(e))||!(e.length<24||!ur.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 uo=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Za-z_][A-Za-z0-9_]*/,us=RegExp(uo.source,"g"),ul=/^(?:bearer|basic|token)\s+/i;function ua(e,t,n){let r=e.replace(ul,"");return t.test(r)&&/^[^A-Za-z0-9]*$/.test(r.replace(n,""))}function uc(e){return ua(e.replace(/\$[$!]/g,"_x"),uo,us)}let ud=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Z_][A-Z0-9_]*(?![A-Za-z0-9_])/,uu=RegExp(ud.source,"g");function up(e){return ua(e,ud,uu)}function uh(e,t){if(!e||""===t)return;e.push(t);let n=ug(t);n!==t&&e.push(n)}let uf=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#]*)/;function um(e,t,n){let r=!1,i=e,o="",s=uf.exec(e);if(s){let[l,a,c]=s,d=c.lastIndexOf("@");if(d>=0&&!t(ug(c.slice(0,d)))){o=`${a}${d2}${c.slice(d)}`,r=!0;let e=c.slice(0,d);uh(n,e);let t=e.indexOf(":");t>=0&&uh(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),c=l<0?"":i.slice(l),d=a.split("/").map(e=>ui(ug(e))?(r=!0,uh(n,e),d2):e).join("/");return c=c.replace(/([?&#;])([^&#;]*)/g,(e,i,o)=>{let s=o.indexOf("=");if(s<0){let s=ug(o);return!ui(s)||t(s)?e:(r=!0,uh(n,o),`${i}${d2}`)}let l=o.slice(0,s),a=ug(o.slice(s+1));return""===a||t(a)||!function(e){let t=e;try{t=decodeURIComponent(e)}catch{}return d7(t,d8)}(l)&&!ui(a)?e:(r=!0,uh(n,o.slice(s+1)),`${i}${l}=${d2}`)}),{value:`${o}${d}${c}`,masked:r}}function ug(e){try{return decodeURIComponent(e)}catch{return e}}let ux=/^(\s*[A-Za-z][A-Za-z0-9 _.-]*=)([\s\S]*)$/;function uv(e,t,n){let r=/^([A-Za-z0-9_-]+):(\s*)([\s\S]*)$/.exec(e);if(r&&""!==r[3]&&!r[3].startsWith("//")&&ue(r[1])){let[,i,o,s]=r;return t(s)?{value:e,masked:!1}:(uh(n,s.trim()),{value:`${i}:${o}${d2}`,masked:!0})}let i=e.includes(";")?function(e,t,n){let r=e.split(";");if(r.length<2||!r.every(e=>""===e.trim()||ux.test(e)))return;let i=!1;return{value:r.map(e=>{let r=ux.exec(e);if(!r)return e;let[,o,s]=r;if(""===s.trim()||t(s))return e;if(ue(o.slice(0,-1).trim()))return i=!0,uh(n,s.trim()),`${o}${d2}`;let l=uv(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]&&ue(o[1]))return t(o[2])?{value:e,masked:!1}:(uh(n,o[2]),{value:`${o[1]}=${d2}`,masked:!0});if(/\s/.test(e)){var s,l,a;let r,i;return s=e,l=t,a=n,i=uj((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 um(e,t,n);if(o&&""!==o[2]){let e=uv(o[2],t,n);return{value:`${o[1]}=${e.value}`,masked:e.masked}}return ui(e)&&!t(e)?(uh(n,e),{value:d2,masked:!0}):{value:e,masked:!1}}function ub(e){if(d6.has(e))return!0;if(!/^--?[A-Za-z]/.test(e))return!1;let t=e.replace(/^-+/,"");return ue(t)||"auth"===d9(t).at(-1)}let uy=/^(?:bearer|basic|token)$/i;function uj(e,t,n,r){let i=!1,o=!1;return{values:e.map(e=>{if(""===e)return e;if(o){if(n&&uy.test(e))return e;if(o=!1,!/^-[A-Za-z-]/.test(e))return t(e)?e:(i=!0,uh(r,e),d2)}let s=/^(--?[A-Za-z][A-Za-z0-9_.-]*)=([\s\S]*)$/.exec(e);if(s){let[,e,n]=s;if(""!==n&&ub(e)&&!t(n))return i=!0,uh(r,n),`${e}=${d2}`;let o=uv(n,t,r);return i||=o.masked,`${e}=${o.value}`}if(/^--?[A-Za-z][A-Za-z0-9_.-]*$/.test(e))return o=ub(e),e;if(n){let t=/^([A-Za-z0-9_-]+):$/.exec(e);if(uy.test(e)||t&&ue(t[1]))return o=!0,e}let l=uv(e,t,r);return i||=l.masked,l.value}),masked:i}}function uk(e){let{values:t,masked:n}=uj(e,up,!1);return{args:t,masked:n}}function uw(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function uS(e){return!e.startsWith("!")&&!uc(e)}function uC(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 uN={"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(uN);let uE={dollarBrace:!1,bareDollar:!1,percent:!1,braceEnv:!1},u$={dollarBrace:!0,bareDollar:!1,percent:!0,braceEnv:!0},uI={...u$,bareDollar:!0},uT={...uE,braceEnv:!0},uM=/^[A-Za-z_][A-Za-z0-9_]*$/,uR=/\$\{([^{}]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)|%([A-Za-z_][A-Za-z0-9_]*)%|\{(env|file):([^{}]*)\}/g;function uL(e,t){if(!t)return;let n=e[e.length-1];n?.kind==="text"?n.text+=t:e.push({kind:"text",text:t})}function uA(e,t,n){let r=[],i=0;uR.lastIndex=0;for(let o=uR.exec(e);o;o=uR.exec(e)){let[s,l,a,c,d,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(uM.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!==c&&t.percent&&n)p={kind:"env",name:c,from:s};else if(void 0!==d&&t.braceEnv)p="env"===d&&uM.test(u)?{kind:"env",name:u,from:s}:{kind:"unsupported",from:s};else if(void 0!==c||void 0!==d){uL(r,e.slice(i,o.index+1)),i=o.index+1,uR.lastIndex=o.index+1;continue}uL(r,e.slice(i,o.index)),"string"==typeof p?uL(r,p):r.push(p),i=o.index+s.length}return uL(r,e.slice(i)),r}function uz(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 uP(e){return e.startsWith("!")}function uW(e){if(uP(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);uM.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 uO=/<[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,uF=/^(?:\.\.\.|…|\*{3,}|x{3,}|TODO|FIXME|changeme|change[-_]me|replace[-_]?me|placeholder|redacted|\[[^\]]+\])$/i,uD=/(?:^|[\\/])(?:path[\\/]to(?:[\\/]|$)|Users[\\/](?:username|yourname|your[-_][A-Za-z_-]+|user[-_]?name|<[^>]+>)(?:[\\/]|$)|home[\\/](?:username|yourname|your[-_][A-Za-z_-]+|<[^>]+>)(?:[\\/]|$))/i,uB=/^(Bearer|Basic|Token|Bot|ApiKey|Api-Key)\s+(.+)$/i;function uH(e){return e.join("\0")}function u_(e){return"args"===e[0]?`args[${e[1]}]`:e.join(".")}function uU(e){return"env"===e[0]||"headers"===e[0]||"oauth"===e[0]&&"clientSecret"===e[1]}function uK(e){return"command"===e[0]||"args"===e[0]||"cwd"===e[0]}let uq=new Set(["HOME","USERPROFILE"]);class uZ{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 uV(e){return e.map(e=>"text"in e?e.text:e.from).join("")}let uJ=/\$\{[^{}]*\}/g,uY=new Set(["variable","home","workspace-basename","unsupported-variable","input"]);class uG{constructor(e){this.draft=e,this.fields=new Map,this.argTexts=e.args.map(uV),this.urlText=uV(e.url??[])}encode(e,t){let n,r=uU(e),i=u_(e),o=uV(t),s=[],l=!1,a=()=>s.every(e=>""===e),c=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=uz(e,{atStart:a()});n!==e&&(l=!0),s.push(n)},d=e=>s.push(e),u=e=>s.push({field:e});if(!r&&uK(e)&&1===t.length&&"text"in t[0]&&uD.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(uD.test(n))return t&&d(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[c,d]of function(e){let t=e.trim();if(uF.test(t)){let n=e.indexOf(t);return[[n,n+t.length]]}let n=uB.exec(t);if(n&&uF.test(n[2].trim())){let t=e.lastIndexOf(n[2].trim());return[[t,t+n[2].trim().length]]}let r=[];uO.lastIndex=0;for(let t=uO.exec(e);t;t=uO.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 c<n&&d>t}))continue;c>s&&r(t.slice(s,c)),"url"===e[0]&&uX(o,p+c)&&(n="uri-component");let h=t.slice(c,d);u(this.field(e,"placeholder",(l=e,a=h,"env"===l[0]||"headers"===l[0]?l[1]:a.replace(/^[<{\s]+|[>}\s]+$/g,"")||u_(l)),h)),s=d}s<t.length&&r(t.slice(s))};switch(s.kind){case"text":m(s.text,c,[]);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()&&uP(e)){this.draft.note("shell-command-value",{field:i}),d(e);break}let t=[...e.matchAll(uJ)].map(e=>[e.index,e.index+e[0].length]);m(e,d,t);break}case"env":r?(d(`\${${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}}`})):uK(e)&&a()&&uq.has(s.name)&&f?(d("~"),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?(d("${HOME}"),this.draft.note("home-variable-translated",{field:i,from:s.from,to:"${HOME}"})):uK(e)&&a()&&f?(d("~"),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")):(d("."),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]&&uX(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=>uH(t.path)===uH(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=uY.has(t)?`${t}.${n}`:u_(e);if(uY.has(t)){if(this.fields.has(s))return s}else for(let t=2;this.fields.has(s);t++)s=`${u_(e)}#${t}`;let l=this.isSecretContext(e,r)||ue(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 ue(e[1]);case"oauth":return"clientSecret"===e[1];case"args":{if(uk([this.argTexts[e[1]]??""]).masked)return!0;let t=this.argTexts[e[1]-1];return void 0!==t&&uk([t,"x"]).args[1]===d2}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,um(`https://host.invalid/?${n}=x`,up).masked)}default:return!1}}}function uX(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 uQ(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 u0=/^[A-Za-z0-9_-]+$/;function u1(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 u2=new Set(["mcp","server","mcp-server","mcpserver","cli","index","main","app","src","dist","build","bin","lib"]);function u4(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=u3(t);return o&&!u2.has(o.toLowerCase())?o:u3(r)||r||o||t}let u8=[/^mcp[-_]server[-_]/i,/^server[-_]/i,/^mcp[-_]/i,/[-_]mcp[-_]server$/i,/[-_]mcp$/i,/[-_]server$/i];function u3(e){let t=e;for(let e=!0;e;)for(let n of(e=!1,u8)){let r=t.replace(n,"");r!==t&&r&&(t=r,e=!0)}return t}let u5=new Set(["mcp","www","api","app","server","servers","remote","gateway"]);function u6(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=>!u5.has(e.toLowerCase()));return r[r.length-1]??n[n.length-1]??""}let u9=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 u7(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 pe(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(!u2.has(n.toLowerCase())&&"."!==n&&".."!==n)return u3(n.replace(/_/g,"-"))||n}return""}function pt(e,t){pn(e,t)&&pr(e,Math.ceil(t/1e3),t)}function pn(e,t){return!!("number"==typeof t&&Number.isFinite(t))&&t>0||(void 0!==t&&e.note("timeout-dropped",{value:String(t)}),!1)}function pr(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 pi=["codemode","deferred","direct","hidden"],po={"codemode-deferred":"codemode"},ps=["localhost","127.0.0.1","[::1]"];function pl(e){return"string"==typeof e&&pi.includes(e)?e:"string"==typeof e&&Object.hasOwn(po,e)?po[e]:void 0}function pa(e){try{return new URL(e)}catch{return}}function pc(e){let t=pa(e);return void 0!==t&&"http:"===t.protocol&&ps.includes(t.hostname)&&""===t.search&&""===t.hash}function pd(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function pu(e){return pd(e)&&Object.values(e).every(e=>"string"==typeof e)}function pp(e,t){if(!u0.test(e))return{problem:"name",name:e};if(!pd(t))return{problem:"not-an-object"};let{type:n,exposure:r,enabled:i,timeout:o,toolExposure:s,description:l}=t;if(void 0!==r&&!pl(r))return{problem:"exposure",value:String(r)};if(void 0!==s){if(!pd(s))return{problem:"tool-exposure"};for(let[e,t]of Object.entries(s))if(!pl(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=pa(t.url);if(!e||!/^https?:$/.test(e.protocol))return{problem:"url",url:t.url};if(void 0!==t.headers&&!pu(t.headers))return{problem:"headers"};let n=function(e){var t;let n;if(void 0===e)return;if(!pd(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||!pc(e.callbackUrl))return{problem:"callback-url",value:String(e.callbackUrl)};let t=new URL(e.callbackUrl).port;if(t&&void 0!==r&&Number(t)!==r)return{problem:"callback-port-mismatch",value:t}}if(void 0!==e.scope&&"string"!=typeof e.scope)return{problem:"oauth-scope"};if(void 0!==e.clientName&&("string"!=typeof e.clientName||!e.clientName.trim()))return{problem:"oauth-client-name"};if(void 0!==e.clientRegistration&&"dcr"!==e.clientRegistration){if("cimd"!==e.clientRegistration)return{problem:"oauth-client-registration",value:String(e.clientRegistration)};if(void 0!==e.clientId||void 0!==e.clientName)return{problem:"oauth-client-registration-client"};let t="string"==typeof e.callbackUrl?pa(e.callbackUrl):void 0;if(t&&("[::1]"===t.hostname||"/callback"!==t.pathname))return{problem:"oauth-client-registration-callback"}}if(void 0!==e.authServerMetadataUrl&&!(void 0!==(n="string"==typeof(t=e.authServerMetadataUrl)?pa(t):void 0)&&("https:"===n.protocol||"http:"===n.protocol&&ps.includes(n.hostname))))return{problem:"auth-server-metadata-url",value:String(e.authServerMetadataUrl)}}(t.oauth);if(n)return n;let r=t.auth;if(void 0!==r){if(!pd(r)||"string"!=typeof r.provider||!r.provider)return{problem:"auth"};if("https:"!==e.protocol&&!ps.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||pu(t.env)?void 0!==t.cwd&&"string"!=typeof t.cwd?{problem:"cwd"}:void 0:{problem:"env"}:{problem:"args"}:{problem:"no-command-or-url"}}let ph=/[A-Za-z_]/,pf=/[A-Za-z0-9_]/,pm=/^[A-Za-z_][A-Za-z0-9_]*$/,pg=new Set([..." \n'\"\\$`|&;<>()#*?[]{}!~="]),px=new Set([..."|&;<>()"]),pv=/[0-9@*#?$!-]/,pb={n:"\n",t:" ",r:"\r",a:"\x07",b:"\b",e:"\x1b",E:"\x1b",f:"\f",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function py(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 pj(e,t){return/^(?:[A-Za-z]:\\|\\\\[A-Za-z0-9.$_-])/.test(e.slice(t,t+4))}class pk{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 pw)return{ok:!1,error:e.detail};throw e}return{ok:!0,words:this.words}}fail(e){throw new pw(e)}startWord(){return this.parts||(this.lineBreak&&this.fail({code:"multiple-commands"}),this.parts=[],this.windowsWord=pj(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)&&py(e,this.index)>0)this.index+=py(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:"`"}):px.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||!pg.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=pj(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 pb?(t+=pb[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&&ph.test(n)){let n=this.index+1;for(;n<t.length&&pf.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&&pv.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}),pm.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 pw extends Error{constructor(e){super(e.code),this.detail=e}}function pS(e){return new pk(e).run()}function pC(e){return e.parts.every(e=>"text"===e.type)?e.text:void 0}function pN(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let pE=["httpUrl","trust","includeTools","excludeTools","authProviderType","targetAudience","targetServiceAccount","tcp"];function p$(e){if(pE.some(t=>t in e))return!0;let t=e.oauth;return pN(t)&&["redirectUri","authorizationUrl","tokenUrl","audiences","tokenParamName"].some(e=>e in t)}function pI(e){if(!pN(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]||pN(t)&&"string"==typeof t.path||"string"==typeof n||"string"==typeof r||"string"==typeof i}function pT(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 pM(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 pR(e,t){let n=t?pM(t):void 0;return{code:"sse-transport",params:{...e?{server:e}:{},...t?{url:t}:{},...n?{suggestedUrl:n}:{}}}}function pL(e){return e?{server:e}:{}}function pA(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?String(e):void 0}function pz(e,t,n){let r;if(!pN(t))return{note:{code:"no-command-or-url",params:pL(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 uE;case"opencode":return uT;case"vscode":return u$;default:return p$(t)?uI:u$}}(n,t),a=o("name"),c=e??("string"==typeof a?a:void 0),d=new uZ(n.source,s),u=(e,t)=>{if(s)return e?[{kind:"pi",text:e}]:[];return t&&"mcp-servers"===n.flavor&&/^!|\$\$|\$!/.test(e)&&d.note("looks-like-pi-config"),uA(e,l,t)};d.name=c,d.inputs=n.inputs;let p=o("inputs");Array.isArray(p)&&(d.inputs=new Map([...n.inputs??[],...pO(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:pL(c)}};if(void 0!==h&&"unknown"===(r="string"==typeof h?pT(h):"unknown"))return{note:{code:"unsupported-transport",params:{...pL(c),type:String(h)}}};let g="string"==typeof f&&""!==f||Array.isArray(f)||pN(f),x=void 0!==m;if("sse"===r)return{note:pR(c,m)};if("ws"===r)return{note:{code:"websocket-transport",params:{...pL(c),...m?{url:m}:{}}}};if(void 0===r){if(g&&x)return{note:{code:"ambiguous-command-and-url",params:pL(c)}};if(x){if(void 0!==pM(m))return{note:pR(c,m)};r="http","mcp-servers"===n.flavor&&"string"==typeof t.url&&"string"!=typeof t.httpUrl&&d.note("transport-guessed")}else{if(!g)return{note:{code:"no-command-or-url",params:pL(c)}};r="stdio"}}if("stdio"!==r&&"http"!==r)return{note:{code:"unsupported-transport",params:{...pL(c),type:String(h)}}};if("stdio"===r&&!g||"http"===r&&!x)return{note:{code:"no-command-or-url",params:pL(c)}};if(d.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:{...pL(e.name),problem:"args"}};s=n[0],l=[...n.slice(1),...Array.isArray(l)?l:[]]}else if(pN(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:pL(e.name)};let c=Array.isArray(l)?[...l]:[];if(void 0!==l&&!Array.isArray(l))return{code:"invalid-config",params:{...pL(e.name),problem:"args"}};if(0===c.length&&/\s/.test(s.trim())&&!/^(?:[A-Za-z]:[\\/]|[\\/]|~[\\/]|\.{1,2}[\\/])/.test(s.trim())){let t=pS(s.trim()),n=t.ok?t.words.map(pC):void 0;n&&n.length>1&&n.every(e=>void 0!==e)&&(e.note("command-split",{command:s}),s=n[0],c.push(...n.slice(1)))}for(let[t,n]of(e.command=i(s,!1),c.entries())){let r=pA(n);if(void 0===r)return{code:"invalid-config",params:{...pL(e.name),problem:"args",index:t}};e.args.push(i(r,!1))}if(void 0!==a){if(!pN(a))return{code:"invalid-config",params:{...pL(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=pA(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&&ue(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 d=r("cwd");for(let n of("string"==typeof d&&""!==d?e.cwd=i(d,!1):void 0!==d&&""!==d&&e.note("dropped-key",{key:"cwd"}),["headers","oauth","auth","url","httpUrl","serverUrl"]))n in t&&(r(n),e.note("dropped-key",{key:n}))}(d,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=pN(o)&&Object.keys(o).some(e=>"authorization"===e.toLowerCase());if(1===s.length&&"text"in s[0]?uQ(e,n,l):e.url=s,pN(o))for(let[t,n]of Object.entries(o)){let r=pA(n);if(void 0===r){e.note("dropped-key",{key:`headers.${t}`});continue}if(""===r.trim()){"authorization"===t.toLowerCase()?e.note("empty-authorization-dropped"):ue(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"),c=r("auth");if(!1===a?e.note("oauth-disable-unsupported"):pN(a)?pP(e,a,i):void 0!==a&&e.note("dropped-key",{key:"oauth"}),pN(c))for(let t of(pP(e,{...void 0!==c.CLIENT_ID?{clientId:c.CLIENT_ID}:{},...void 0!==c.CLIENT_SECRET?{clientSecret:c.CLIENT_SECRET}:{},...void 0!==c.scopes?{scopes:c.scopes}:{}},i,"auth."),Object.keys(c)))["CLIENT_ID","CLIENT_SECRET","scopes"].includes(t)||e.note("oauth-option-dropped",{key:`auth.${t}`});else void 0!==c&&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}))}(d,t,m,o,u);let v=o("timeout");if(void 0!==v)if(s)"number"==typeof v&&v>0?d.timeout=v:d.note("timeout-dropped",{value:String(v)});else if("opencode"===n.flavor)d.note("timeout-dropped",{value:String(v)});else if(p$(t))pt(d,v);else["autoApprove","alwaysAllow","transportType"].some(e=>e in t)||"streamableHttp"===t.type?pn(d,v)&&pr(d,Math.ceil(v),void 0):!function(e,t){if(!pn(e,t))return;let n=t>=1e3;e.note("timeout-unit-guessed",{value:t,unit:n?"milliseconds":"seconds"}),n?pr(e,Math.ceil(t/1e3),t):pr(e,Math.ceil(t),void 0)}(d,v);let b=o("enabled"),y=o("disabled");!1===b||!0===y?(d.enabled=!1,d.note("imported-disabled")):(void 0!==b&&"boolean"!=typeof b||void 0!==y&&"boolean"!=typeof y)&&d.note("dropped-key",{key:void 0!==b?"enabled":"disabled"});let j=o("exposure");if(void 0!==j){let e=pl(j);e?d.exposure=e:d.note("invalid-exposure-dropped",{value:String(j)})}let k=o("toolExposure");if(void 0!==k){let e=pN(k)?Object.entries(k).map(e=>{let[t,n]=e;return[t,pl(n)]}):void 0;e?.every(e=>{let[,t]=e;return void 0!==t})?d.toolExposure=Object.fromEntries(e):d.note("invalid-exposure-dropped",{value:"toolExposure"})}if(s||void 0===j&&void 0===k||d.note("looks-like-pi-config"),s){let e=o("description");"string"==typeof e?d.description=e:void 0!==e&&d.note("dropped-key",{key:"description"})}for(let e of(pW(d,o("includeTools"),o("excludeTools")),Object.keys(t)))i.has(e)||d.note("dropped-key",{key:e});return{draft:d}}function pP(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"clientRegistration":"dcr"===o||"cimd"===o?e.oauth.clientRegistration=o: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&&pc(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 pW(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 pO(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e)pN(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=>pN(e)?e.value:e).filter(e=>"string"==typeof e)}:{}});return t}function pF(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=pN(t)&&pN(t[s[1]])?t[s[1]]:{};i.push(pD(`${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 pD(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 pB(e,t,n){let r=[],i="",o=()=>{i&&("pi"===t?r.push({kind:"pi",text:i}):r.push(...uA(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 pH(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 p_=/^https?:\/\//i,pU=/^wss?:\/\//i,pK={"@earendil-works/pi-coding-agent":"pi","@anthropic-ai/claude-code":"claude","@openai/codex":"codex","@google/gemini-cli":"gemini"},pq=new Set(["pi","claude","codex","gemini"]),pZ=new Set(["install","remove","uninstall","update","list","config"]);function pV(e){return"error"in e?{error:e.error}:{entries:[e],notes:[]}}let pJ={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"},pY=new Map([["-l","--local"]]),pG=["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name"],pX=["env","cwd"];function pQ(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,c=a>0?l.slice(0,a):l,d=n[c];if(!d){if(i.positional.length>=r.asArgAfter){i.positional.push(s),i.seen.set(`as-arg:${c}`,c);continue}return{error:{code:"cli-unknown-option",params:{cli:e,option:c}}}}if(i.seen.set(d.name,c),"flag"===d.kind){i.values.set(d.name,!0);continue}let u=a>0?p0(s,a+1):void 0;if("value"===d.kind||"list"===d.kind){let n=u??t[++o];if(void 0===n)return{error:{code:"cli-option-needs-value",params:{cli:e,option:c}}};"value"===d.kind?i.values.set(d.name,n):i.lists.set(d.name,[...i.lists.get(d.name)??[],n]);continue}let p=u?[u]:[];if(!u)for(;o+1<t.length&&r.variadic(d.name,t[o+1]);)p.push(t[++o]);if(0===p.length)return{error:{code:"cli-option-needs-value",params:{cli:e,option:c}}};i.lists.set(d.name,[...i.lists.get(d.name)??[],...p])}return i}function p0(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 p1=/^[A-Za-z_][A-Za-z0-9_]*=/,p2=/^[^\s:]+:/;function p4(e,t,n,r){for(let i of t??[]){let t=pH(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],pB(t[1],n,!0)])}}function p8(e,t,n,r){for(let i of t??[]){let t=pH(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,pB(s,n,!0)])}}function p3(e){if(void 0!==e&&!0!==e){if("user"===e.text)return"global";if("project"===e.text)return"project"}}function p5(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 c=void 0===n||!0===n?void 0:n.text.toLowerCase();if(void 0===c){if("http"==(o=p_.test(l.text)?"http":pU.test(l.text)?"ws":"stdio")&&void 0!==pM(l.text))return pR(s.text,l.text);"http"===o&&"gemini"===t&&e.note("transport-assumed-http")}else o="streamable-http"===c?"http":c;return"sse"===o?pR(s.text,l.text):"ws"===o?{code:"websocket-transport",params:{server:s.text,url:l.text}}:"http"===o?(e.transport="http",e.url=pB(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=pB(l.parts,i,!1),e.args=a.map(e=>pB(e.parts,i,!1)),"stdio")}let p6={"-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 p9(e,t){return"env"===e?p1.test(t.text):p2.test(t.text)&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(t.text)}function p7(e){e.oauth.clientSecret=[{kind:"prompt",id:"oauth.clientSecret",reason:"client-secret",label:"clientSecret",from:"",secret:!0}],e.note("client-secret-prompt")}let he={"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"--client-secret":{name:"client-secret",kind:"flag"}};function ht(e){let t,n=pC(e)??e.text;try{t=uC(n)}catch(e){return{error:{code:"invalid-json",params:{detail:e instanceof Error?e.message:String(e)}}}}return pN(t)?{value:t}:{error:{code:"no-servers-found"}}}let hn={"--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"}},hr={"-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 hi(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(ho(r),ho(i))}return t}function ho(e){try{return decodeURIComponent(e)}catch{return e}}function hs(e){let t=e.trim();for(let e=0;e<4;e++)try{return uC(t)}catch{let e=ho(t);if(e===t)break;t=e.trim()}}function hl(e){return{error:{code:"install-link-invalid",params:{detail:e}}}}function ha(e){let t=e.get("config");if(!t)return hl("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:hs(n);return pN(r)?{entries:[pz(e.get("name")||void 0,r,{source:"cursor-install-link",flavor:"mcp-servers",rawPi:!1})],notes:[]}:hl("config")}function hc(e,t,n,r){return pN(e)?{entries:[pz(n,e,{source:t,flavor:"vscode",rawPi:!1,inputs:pO(r)})],notes:[]}:hl("config")}function hd(e){return{error:{code:"by-name-link",params:{name:e}}}}function hu(e){let t=e.indexOf("?");return t<0?"":e.slice(t+1)}function hp(e){let t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=e.replace(/&amp;/g,"&");try{t=new URL(r)}catch{if(/^https?:\/\/\S+$/i.test(r)&&0===n)return{entries:[hf(void 0,r)],notes:[]};return{error:{code:"unrecognized-input"}}}if(n>3)return hl("nesting");let i=t.protocol.replace(/:$/,"").toLowerCase();switch(i){case"cursor":if(/\/mcp\/install\/?$/.test(t.pathname))return ha(hi(t.search));return hl("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 hd(ho(t[1]));if(/^mcp\/api\.mcp\.github\.com\//.test(e))return hd(e.replace(/^mcp\//,""));if(/^mcp\/install\?/.test(e))return hc(hs(hu(r)),"vscode-install-link");return hl(i)}case"vsweb+mcp":return hc(hs(hu(r)),"visual-studio-install-link");case"ghapp":if(/^\/\/mcp\/install/.test(r.slice(r.indexOf(":")+1)))return hc(hs(hu(r)),"copilot-app-install-link");return hl(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 ha(hi(e.search));if("vscode.dev"===r||"insiders.vscode.dev"===r){let t=hi(e.search);if(/^\/redirect\/?$/.test(i)&&t.get("url"))return hp(t.get("url"),n+1);if(/^\/redirect\/mcp\/install\/?$/.test(i)){let e=t.get("config");return e?hc(hs(e),"vscode-install-link",t.get("name")||void 0,hs(t.get("inputs")??"[]")):hl("config")}}if("aka.ms"===r&&/^\/vs\/mcp-install\/?$/i.test(i))return hc(hs(e.search.slice(1)),"visual-studio-install-link");if("github.com"===r&&/^\/copilot\/app\/launch\/?$/.test(i)){let t=hi(e.search).get("open");return t?hp(t,n+1):hl("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:[hf(e,t)],notes:[]}}(t,r,n);default:return{error:{code:"unsupported-url-scheme",params:{scheme:i}}}}}let hh=new Set(["localhost","127.0.0.1","[::1]"]);function hf(e,t){let n=u6(t)||void 0;if(void 0!==pM(t))return{note:pR(n,t)};let r=new uZ("url",!1);return r.transport="http",uQ(r,t,!1),e?.protocol!=="http:"||hh.has(e.hostname)||r.note("insecure-http",{host:e.hostname}),{draft:r}}let hm=/[\u200B-\u200D\u2060\uFEFF]/g,hg=/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]\S*)?$/i,hx={"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 hv(e){return new Set(e.fields.flatMap(e=>e.targets.map(e=>uH(e.path))))}function hb(e){var t;let n,r,i,o,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},l=(n=e.replace(hm,"").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=uC(e)}catch(t){try{n=uC(`{${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 pz(n,r,t)});if(Array.isArray(e)){let r=e.filter(pI);return 0===r.length?{error:{code:"no-servers-found"}}:{entries:r.map(e=>pz(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})),notes:n}}if(!pN(e))return{error:{code:"no-servers-found"}};let i=pN(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?u4(t.split("/").pop()??t):void 0,r=Array.isArray(e.remotes)?e.remotes.filter(pN):[],i=r.filter(e=>"string"==typeof e.type&&"http"===pT(e.type)&&"string"==typeof e.url);if(0===i.length){let e=r.find(e=>"sse"===e.type);return e?[{note:pR(n,"string"==typeof e.url?e.url:void 0)}]:[{note:{code:"registry-packages-unsupported",params:pL(n)}}]}return i.map(e=>{let r=new uZ("registry-server-json",!1);for(let i of(r.name=n,t&&n!==t&&(r.originalName=t),r.transport="http",r.url=pF(e.url,e.variables,"url.","registry-variable"),Array.isArray(e.headers)?e.headers.filter(pN):[])){if("string"!=typeof i.name||""===i.name)continue;let e=i.name;"string"==typeof i.value&&""!==i.value?r.headers.push([e,pF(i.value,i.variables,`headers.${e}.`,"registry-header")]):r.headers.push([e,[pD(`headers.${e}`,e,"",i,"registry-header")]])}return{draft:r}})}(i),notes:n};if(pN(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(pN(e.servers)){let t=pO(e.inputs);return{entries:r(e.servers,{source:"vscode-json",flavor:"vscode",rawPi:!1,inputs:t}),notes:n}}if(pN(e.mcp)){let t=e.mcp;if(pN(t.servers)){let e=pO(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(pN(e.context_servers))return{entries:Object.entries(e.context_servers).map(e=>{let t,[n,r]=e;return pN(r)&&("extension"===r.source||!pI(r))?{note:{code:"zed-extension-server",params:{server:n}}}:pz(n,pN(r)?(t={...r},delete t.source,t):r,{source:"zed-json",flavor:"zed",rawPi:!1})}),notes:n};if(pI(e))return{entries:[pz(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})],notes:n};let o=Object.values(e);return o.length>0&&o.every(pN)&&o.some(pI)?{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(hg.test(l)){if(!("error"in(o=hp(`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)?hp(l):(e=pS(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&&pK[i]&&e[t+1]?.text==="mcp"&&(n=t,r=pK[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 pV(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=pY.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=pJ[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},c=(void 0===l?pG:pX).find(e=>r.has(e)||i.has(e));if(c)return{error:{code:"cli-option-wrong-transport",params:{cli:"pi",option:`--${c}`,transport:void 0===l?"stdio":"http"}}};let d=new uZ("pi-mcp-add",!0);d.name=o.text,d.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=pH(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){d.transport="http",d.url=pB(l.parts,"pi",!1);let e=u("header");if("error"in e)return e;for(let[t,n]of e)d.headers.push([t,pB(n,"pi",!0)]);let t=a("bearer-token-env-var");if(void 0!==t){let e=["Authorization",[{kind:"pi",text:`Bearer \${${t.text}}`}]],n=d.headers.findIndex(e=>{let[t]=e;return"Authorization"===t});n>=0?d.headers[n]=e:d.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&&(d.oauth.clientId=pB(n.parts,"pi",!1)),r&&(d.oauth.clientSecret=pB(r.parts,"pi",!0)),i&&(d.oauth.callbackPort=Number(i.text)),o&&(d.oauth.clientName=pB(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{d.transport="stdio";let e=u("env");if("error"in e)return e;for(let[t,n]of e)d.env.push([t,pB(n,"pi",!0)]);let[t,...n]=s;d.command=pB(t.parts,"pi",!1),d.args=n.map(e=>pB(e.parts,"pi",!1));let r=a("cwd");r&&(d.cwd=pB(r.parts,"pi",!1)),p.command=t.text}let h=a("exposure");void 0!==h&&(p.exposure=h.text,d.exposure=pl(h.text)??h.text);let f=a("description");void 0!==f&&(p.description=f.text,d.description=f.text);let m=pp("server",p);return m?{note:{code:"invalid-config",params:{server:o.text,...m}}}:{draft:d}}(t,i.slice(1)));if("claude"===r&&"add"===e)return pV(function(e){let t=pQ("claude",e,p6,{asArgAfter:2,variadic:p9});if("error"in t)return{error:t.error};let n=new uZ("claude-mcp-add",!1),r=p5(n,"claude",t.values.get("transport"),[...t.positional,...t.afterDashDash],u$);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=p3(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=p8(n,t.lists.get("header"),u$,"claude");if(r)return{error:r};let s=t.values.get("client-id");s&&!0!==s&&(n.oauth.clientId=pB(s.parts,u$,!1)),t.values.has("client-secret")&&p7(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=p4(n,t.lists.get("env"),u$,"claude");if(e)return{error:e}}return{draft:n}}(t));if("claude"===r&&"add-json"===e)return pV(function(e){let t=pQ("claude",e,he,{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=ht(r);if("error"in o)return o;let s=pz(n.text,o.value,{source:"claude-mcp-add-json",flavor:"mcp-servers",rawPi:!1});return"note"in s||(s.draft.scopeHint=p3(t.values.get("scope")),t.values.has("client-secret")&&"http"===s.draft.transport&&!s.draft.oauth.clientSecret&&p7(s.draft)),s}(t));if("claude"===r&&"add-from-claude-desktop"===e)return{error:{code:"claude-desktop-import"}};if("codex"===r&&"add"===e)return pV(function(e){let t=pQ("codex",e,hn,{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 uZ("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!==pM(l.text))return{note:pR(i.text,l.text)};a.transport="http",a.url=pB(l.parts,uE,!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=pB(n.parts,uE,!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=p4(a,r,uE,"codex");if(e)return{error:e};a.command=pB(s[0].parts,uE,!1),a.args=s.slice(1).map(e=>pB(e.parts,uE,!1))}return{draft:a}}(t));if("gemini"===r&&"add"===e)return pV(function(e){let t=pQ("gemini",e,hr,{asArgAfter:2});if("error"in t)return{error:t.error};let n=new uZ("gemini-mcp-add",!1),r=p5(n,"gemini",t.values.get("transport"),[...t.positional,...t.afterDashDash],uI);if("string"!=typeof r)return"cli-usage"===r.code?{error:r}:{note:r};if(n.scopeHint=p3(t.values.get("scope")),"http"===r){t.lists.has("env")&&n.note("cli-option-wrong-transport",{cli:"gemini",option:"--env",transport:"http"});let e=p8(n,t.lists.get("header"),uI,"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=p4(n,t.lists.get("env"),uI,"gemini");if(e)return{error:e}}let i=t.values.get("timeout");for(let e of(i&&!0!==i&&pt(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 pW(n,o("include-tools"),o("exclude-tools")),{draft:n}}(t));if("add"===e||"install"===e)return{error:{code:"cli-unsupported",params:{cli:r}}};if(pq.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]&&pZ.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=p0(e[n],10)}if(!r)return{error:{code:"cli-option-needs-value",params:{cli:"code",option:"--add-mcp"}}};let o=ht(r);if("error"in o)return o;t.push(pz(void 0,o.value,{source:"vscode-add-mcp",flavor:"vscode",rawPi:!1}))}return{entries:t,notes:[]}}(e.slice(1)):pV(function(e){let t=new uZ("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,pB(r.value,uE,!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=pB(i.parts,uE,!1),t.args=e.slice(n+1).map(e=>pB(e.parts,uE,!1));let o=e.slice(n+1).map(e=>e.text),s=o.some(e=>/^mcp-remote(?:@|$)/.test(e))?o.find(e=>p_.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:hx[t],params:n}:{code:hx[t]}}(e.error)}}if("error"in o)return{ok:!1,notes:[o.error]};let a=[...o.notes],c=[],d=[...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 uG(e);if("stdio"===e.transport&&e.command&&""!==uV(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||""===uV(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:c,clientRegistration:d,callbackUrl:u,scope:p,authServerMetadataUrl:h}=e.oauth;s&&(o.clientId=n.encode(["oauth","clientId"],s)),l&&(o.clientSecret=n.encode(["oauth","clientSecret"],l)),void 0!==a&&(o.callbackPort=a),c&&(o.clientName=n.encode(["oauth","clientName"],c)),d&&(o.clientRegistration=d),u&&(o.callbackUrl=n.encode(["oauth","callbackUrl"],u)),p&&(o.scope=n.encode(["oauth","scope"],p)),h&&(o.authServerMetadataUrl=n.encode(["oauth","authServerMetadataUrl"],h)),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 u6(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&&u6(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=u7(t,new Set(["-p","--package","-c","--call"]));return e?u4(e):""}case"pnpm":case"yarn":case"bun":case"npm":{let e=t.findIndex(e=>"dlx"===e||"exec"===e||"x"===e),n=e>=0?u7(t.slice(e+1),new Set(["-p","--package"])):void 0;return n?u4(n):""}case"uvx":case"pipx":{let e=u7("pipx"===n&&"run"===t[0]?t.slice(1):t,new Set(["--from","--with","--python","-p","--index-url","--spec"]));return e?u4(e):""}case"uv":{let e=t.indexOf("run"),n=e>=0?u7(t.slice(e+1),new Set(["--with","--directory","--python","-p","--from","--project"])):void 0;return n?pe(n):""}case"docker":case"podman":{let e=t.indexOf("run"),n=e>=0?u7(t.slice(e+1),u9):void 0;if(!n)return"";let r=n.split("/").pop().replace(/[:@].*$/,"");return u3(r)||r}case"python":case"python3":case"py":{let e=t.indexOf("-m");if(e>=0&&t[e+1])return u4(t[e+1].replace(/_/g,"-"));let n=u7(t,new Set(["-X","-W"]));return n?pe(n):""}case"node":case"deno":case"tsx":case"ts-node":{let e=u7("deno"===n&&"run"===t[0]?t.slice(1):t,new Set(["-r","--require","--import","--loader"]));return e?pe(e):""}default:return u3(n.replace(/_/g,"-"))||n}}(e.command,t)}(r.config))&&r.notes.push({code:"name-derived",params:{name:i}});let s=(t=i,u0.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=u1(s,o?[...d,...u]:u);l!==s&&(r.notes.push({code:"name-deduplicated",params:{original:s,name:l}}),s=l),!o&&d.includes(s)&&r.notes.push({code:"name-taken",params:{name:s,suggestedName:u1(s,[...d,...u])}}),r.name=s;let p=pp(s,function(e){let t=hv(e),n=JSON.parse(JSON.stringify(e.config));t.has(uH(["url"]))&&(n.url="https://placeholder.invalid/");let r=n.oauth;return r&&t.has(uH(["oauth","callbackUrl"]))&&delete r.callbackUrl,n}(r));if(p){a.push({code:"invalid-config",params:{server:s,...p}});continue}!function(e){let t=hv(e);for(let n of hE(e.config))t.has(uH(n))||e.notes.push({code:"literal-secret",params:{field:u_(n)}});let n=e.config;if("url"in n){for(let[t,r]of Object.entries(n.headers??{})){let n=uW(r);n.length>0&&e.notes.push({code:"header-env-reference",params:{header:t,names:n.join(", ")}})}let t=uW(n.oauth?.clientSecret??"");t.length>0&&e.notes.push({code:"client-secret-env-reference",params:{names:t.join(", ")}})}}(r),u.add(s),c.push(r)}return 0===c.length?{ok:!1,notes:a.length>0?a:[{code:"no-servers-found"}]}:{ok:!0,servers:c,notes:a}}let hy=/^[A-Za-z_][A-Za-z0-9_]*$/;function hj(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 hk(e){let t=hv(e);return hE(e.config).filter(e=>uU(e)&&!t.has(uH(e)))}function hw(e){return"string"==typeof e&&""===e.trim()?"missing":"name"}let hS=/^(?:bearer|basic|token)\s+/i;function hC(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(hk(e).map(e=>[u_(e),e])),l=[];for(let[e,t]of Object.entries(n)){let n="string"==typeof t?t.trim():"",r=s.get(e);r?hy.test(n)?l.push([r,n]):o.push({code:"field-reference-invalid",params:{field:e,problem:hw(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():"";hy.test(r)?"select"!==n.kind&&n.targets.every(e=>uU(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:hw(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,c=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(u_(e.path));let o=uH(e.path);if(c.has(o))continue;if(c.add(o),e.parts.some(e=>"string"!=typeof e&&void 0===i.get(e.field))){hj(r,e.path,void 0);continue}let s="";for(let t of e.parts){var d,u,p,h;s+="string"==typeof t?t:(d=i.get(t.field),u=e.path,p=""===s,h=e.encoding,"reference"in d?`\${${d.reference}}`:"uri-component"===h?encodeURIComponent(d.text):uU(u)?uz(d.text,{atStart:p}):d.text)}hj(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(hS)?.[0]??"":"";hj(r,e,`${i}\${${t}}`)}for(let e of hE(r))a.add(u_(e));return{ok:!0,config:r,secretPaths:[...a]}}let hN=["command","args","env","cwd","url","headers","oauth"];function hE(e){let t=[];for(let n of function(e){if(!uw(e))return[];let t=[];for(let n of["env","headers"]){let r=e[n];if(uw(r))for(let[e,i]of Object.entries(r))"string"==typeof i&&uS(i)&&""!==i&&(ue(e)||/^(?:bearer|basic|token)\s+\S/i.test(i)||uv(i,uc).masked)&&t.push({kind:"env"===n?"env":"header",name:e})}let n=uw(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&""!==n&&uS(n)&&t.push({kind:"oauth-client-secret"}),"string"==typeof e.url&&um(e.url,up).masked&&t.push({kind:"url"}),"string"==typeof e.command&&uv(e.command,up).masked&&t.push({kind:"command"}),Array.isArray(e.args)&&uk(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:""):[];uk(n).args.forEach((e,r)=>{e!==n[r]&&t.push(["args",r])})}}return t.sort((e,t)=>hN.indexOf(e[0])-hN.indexOf(t[0]))}let h$="PI_WEB_PASSWORD";function hI(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function hT(e){return hI(e)?Object.entries(e).filter(e=>"string"==typeof e[1]):[]}function hM(e){if(!hI(e))return[];if(!("url"in e))return hT(e.env).map(e=>{let[t,n]=e;return{kind:"env",name:t,value:n}});let t=hT(e.headers).map(e=>{let[t,n]=e;return{kind:"header",name:t,value:n}}),n=hI(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&t.push({kind:"oauth-client-secret",value:n}),t}let hR={text:"",rawPi:!1,server:0,values:{},references:{},secretReferences:{}};function hL(e,t,n){let r=hb(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 hA(e,t){let n={...e,...t},r=hL(e.text,e.rawPi,e.server);if(void 0!==r&&r===hL(n.text,n.rawPi,e.server))return n;let i={...n,server:0,values:{},references:{},secretReferences:{}};return delete i.name,i}function hz(e){return uN[e.code]??"warning"}function hP(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?cY(t):t;if("string"==typeof i.field&&e.code.startsWith("field-")){let e=r.find(e=>e.id===i.field);e&&(o.field=cY(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 hW={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"},hO={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"},hF=JSON.stringify({command:"uvx",args:["mcp-server-fetch"]}),hD=JSON.stringify({name:"fetch",command:"uvx",args:["mcp-server-fetch"]}),hB=[{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 '${hD}'`},{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(hF)}`},{source:"vscode-install-link",text:`vscode:mcp/install?${encodeURIComponent(hD)}`},{source:"visual-studio-install-link",text:`vsweb+mcp:/install?${encodeURIComponent(hD)}`},{source:"copilot-app-install-link",text:`ghapp://mcp/install?${encodeURIComponent(hD)}`}];function hH(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?cY(r):r.field===e.id?n:`‹${cY(t.find(e=>{let{id:t}=e;return t===r.field})?.label??r.field)}›`).join("")}))].join(", ")}function h_(e){return"select"!==e.kind&&e.targets.every(e=>uU(e.path)&&void 0===e.encoding)}let hU=/^[A-Za-z_][A-Za-z0-9_]*$/;function hK(){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 hU.test(r)?r:void 0}let hq=/^(?:proxy-)?authorization$/i;function hZ(e,t){let n=function(e,t){if(e.startsWith("env.")){let t=e.slice(4);return hU.test(t)?t:hK(t)}let n=function(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];return hK(t,...n)??hK(...n)};if(e.startsWith("headers.")){let t=e.slice(8);return n(hq.test(t)?"TOKEN":t.replace(/^x-/i,""))}if("oauth.clientSecret"===e)return n("CLIENT_SECRET")}(e,t);return n===h$?void 0:n}function hV(e){return e.startsWith("env.")||e.startsWith("headers.")||"oauth.clientSecret"===e}function hJ(e,t){let n=e;for(let e of t)n=n.split(e).join(d2);return{text:n,masked:n!==e}}function hY(e){let{kind:t,name:n}=e;return void 0===n?{kind:t}:{kind:t,name:n}}function hG(e,t){let n=t.files.find(t=>t.scope===e),r=n?.problems.find(dg);return n&&r?{kind:"file-problem",path:n.path,reason:r.reason}:void 0}function hX(e,t){return e.servers.filter(e=>e.scope===t).map(e=>e.name)}function hQ(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 h0(e,t,n){switch(e.kind){case"trust-too-broad":return t(h2[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(h1[e.kind])}}let h1={"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"},h2={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 h4(e){return cY(cs(e))}function h8(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}let h3=[{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"}],h5=new Set(["name-derived","name-sanitized","name-deduplicated","name-taken"]);function h6(e){let{notes:t,fields:n=[]}=e,{t:i}=(0,eh.s)();if(0===t.length)return null;let o={error:0,warning:1,info:2},s=[...t].sort((e,t)=>o[hz(e)]-o[hz(t)]);return(0,r.jsx)("ul",{className:"mcp-add-notes",children:s.map((e,t)=>(0,r.jsx)("li",{className:`mcp-add-note is-${hz(e)}`,children:hP(e,i,n)},`${t}\0${e.code}`))})}let h9={"server-invalid":"mcp.add.refused.server-invalid","web-password":"mcp.add.blocked.web-password"};function h7(e){let{data:t,cwd:n,draft:o,busy:s,controlsBusy:l,failure:a,onDraftChange:c,onSubmit:d,onTrustProject:u}=e,{t:p}=(0,eh.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:dy(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=>hb(t.text,{rawPi:t.rawPi,takenNames:hX(n,e)}),l=s(t.scope??"global"),a=l.ok?l.servers[Math.min(t.server,l.servers.length-1)]:void 0,c=t.scope??(a?.scopeHint==="project"&&"write"===o.kind?"project":"global");c!==(t.scope??"global")&&(a=(l=s(c)).ok?l.servers[Math.min(t.server,l.servers.length-1)]:void 0);let d={parsed:l,name:t.name??"",scope:c,projectMode:o,..."blocked"===o.kind?{projectBlock:o.block}:{},values:{},pasteSecrets:[],secretReferences:{},fieldProblems:{},secretPaths:[],trustFolder:!1},u=dD(n.mcp);if(!a)return{...d,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&&h_(r)?n[r.id]={reference:e}:void 0!==t.values[r.id]&&(n[r.id]=t.values[r.id])}return n}(a,t),f=hk(a).map(u_),m=Object.fromEntries(f.flatMap(e=>{let n=t.secretReferences[e];return void 0===n?[]:[[e,n]]})),g=hC(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]=hU.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=hC(e,r,Object.fromEntries(Object.entries(n).map(e=>{let[t,n]=e;return[t,hU.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:hM(r).filter(e=>{let{value:t}=e;return uP(t)}).map(hY),variableReferences:hM(r).map(e=>({...hY(e),variables:uW(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=hJ(r.url,i);return{...s,transport:"http",target:cY(e.text),envNames:[],headerNames:Object.keys(r.headers??{}),masked:e.masked}}let l=hJ(cQ(r.command,r.args??[]),i);return{...s,transport:"stdio",target:l.text,...void 0!==r.cwd?{cwd:cY(r.cwd)}:{},envNames:Object.keys(r.env??{}),headerNames:[],masked:l.masked}}(a,h,g),y=g.ok?pp(p,g.config):void 0,j="blocked"===o.kind?o.block:v.length>0?{kind:"secret",fields:v,fixed:!v.every(hV)}:hG("project",n),k=hX(n,c),w=n.files.find(e=>e.scope===c);if(u)i={kind:"mcp-off"};else if(u0.test(p))if(k.includes(p))i={kind:"name-taken",name:p,suggestedName:u1(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 hM(e))if(t.isCommandConfigValue(n)?n.toUpperCase().includes(h$):t.getConfigValueEnvVarNames(n).some(e=>e.toUpperCase()===h$))return r}(g.config,{isCommandConfigValue:uP,getConfigValueEnvVarNames:uW}))i={kind:"web-password"};else if("project"===c&&j)i={kind:"scope",block:j};else{let e=hG(c,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"===c&&j?e({...t,scope:"global"},n,r):{parsed:l,server:a,name:p,scope:c,projectMode:o,...j?{projectBlock:j}:{},values:h,pasteSecrets:f,secretReferences:m,fill:g,fieldProblems:x,secretPaths:v,preview:b,...i?{submitBlock:i}:{},trustFolder:"project"===c&&"trust-and-write"===o.kind}})(o,t,n),[o,t,n]),g=(0,i.useMemo)(()=>(function(e){let t=hb(e,{rawPi:!0});if(!t.ok)return!1;let n=hb(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=>h5.has(e.code)),S=k.filter(e=>!h5.has(e.code)),C=!s&&!l&&void 0===j,N=()=>{C&&d(hQ(o,m))},E=e=>c({...o,...e}),$=t.files.find(e=>e.scope===m.scope)?.path??("project"===m.scope&&n?`${n.replace(/[\\/]+$/,"")}/.pi/mcp.json`:"mcp.json"),I=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:cY(e.name),path:e.path?h4(e.path):"mcp.json"});case"fields":return t("mcp.add.blocked.fields",{fields:e.fields.map(cY).join(", ")});case"field-invalid":return t("mcp.add.blocked.fieldsInvalid",{fields:e.fields.map(cY).join(", ")});case"config-invalid":return hP(e.note,t,n);case"web-password":return t("mcp.add.blocked.web-password");case"scope":return h0(e.block,t,h4)}}(j,p,v?.fields):void 0,T=y?.kind==="project-untrusted"&&y.trustable&&u,M=b?"http"===b.transport?b.headerNames:b.envNames:[];return(0,r.jsxs)(ax,{title:p("mcp.add.title"),catalogs:h3,target:(0,r.jsxs)(am,{value:m.scope,label:p("config.saveTo"),options:[{value:"global",label:h8("global",p)},{value:"project",label:h8("project",p),disabled:void 0!==y&&"project"!==m.scope}],path:h4($),disabledReason:y?h0(y,p,h4):null,onChange:e=>E({scope:e}),children:[T&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aS,{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:h4(m.projectMode.folder)})})]}),inputLabel:p("mcp.add.inputLabel"),inputId:"mcp-add-source",placeholder:p("mcp.add.placeholder"),value:o.text,canSubmit:C,onValueChange:e=>c(hA(o,{text:e})),onSubmit:N,examplesLabel:p("mcp.add.examples"),examples:""===o.text.trim()?hB.map(e=>{let{source:t,text:n}=e;return{label:p(hO[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=>c(hA(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)(h6,{notes:x.notes}),x.ok&&x.servers.length>1&&(0,r.jsxs)(ad,{label:p("mcp.add.serverLabel"),children:[(0,r.jsx)("select",{className:"mcp-add-input","aria-label":p("mcp.add.serverLabel"),value:String(x.servers.indexOf(v??x.servers[0])),onChange:e=>E({server:Number(e.target.value),name:void 0,values:{},references:{},secretReferences:{}}),children:x.servers.map((e,t)=>(0,r.jsx)("option",{value:t,children:cY(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)(ad,{label:p("config.name"),children:(0,r.jsx)("input",{id:f,className:"mcp-add-input","aria-label":p("config.name"),value:m.name,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>E({name:e.target.value})})}),(0,r.jsx)(h6,{notes:w,fields:v.fields}),j?.kind==="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aS,{size:"small",onClick:()=>E({name:j.suggestedName}),children:p("mcp.add.useName",{name:cY(j.suggestedName)})})})]}),v&&b&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ac,{children:p("mcp.add.preview")}),(0,r.jsxs)(au,{children:[(0,r.jsx)(ap,{label:p("mcp.add.readAs"),children:p(hO[b.source])}),(0,r.jsx)(ap,{label:p("mcp.detail.transport"),children:p(`mcp.transport.${b.transport}`)}),(0,r.jsx)(ap,{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)(ap,{label:p("mcp.detail.cwd"),mono:!0,children:b.cwd}),M.length>0&&(0,r.jsx)(ap,{label:"http"===b.transport?p("mcp.detail.headers"):p("mcp.detail.env"),children:(0,r.jsx)(fe,{names:M})}),b.commandFields.length>0&&(0,r.jsx)(ap,{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=c2(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)(ap,{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:c3(b.variableReferences).map(e=>{let{variable:t,field:n}=e,i=c2(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p("mcp.server.variableIn",{variable:cY(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)(h6,{notes:S,fields:v.fields}),v.fields.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ac,{children:p("mcp.add.fields")}),v.fields.map(e=>{var t;let n;return(0,r.jsx)(ft,{field:e,fields:v.fields,draft:o,suggestedName:(t=m.name,(n=e.targets[0])?hZ(u_(n.path),t):void 0),problem:m.fieldProblems[e.id],onDraftChange:c},e.id)})]}),m.pasteSecrets.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ac,{children:p("mcp.add.secrets")}),m.pasteSecrets.map(e=>{var t,n;let i;return(0,r.jsx)(fn,{label:e,draft:o,suggestedName:hZ(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)&&uc(i)?i:void 0):void 0,problem:m.fieldProblems[e],onDraftChange:c},e)})]})]}),(0,r.jsx)(aS,{variant:"primary",className:"is-pushed-right",disabled:!C,"aria-busy":s||void 0,"aria-describedby":I?h:void 0,onClick:N,children:s?p("mcp.add.adding"):m.trustFolder?p("mcp.add.buttonTrust"):p("mcp.add.button")}),I&&(0,r.jsx)("p",{id:h,className:`mcp-config-line ${j?.kind==="scope"?"is-warning":"is-dim"}`,children:I}),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(h2[e.breadth.kind],{path:h4(e.breadth.path)});if("secret-global-only"===e.reason&&e.fields)return t(e.fields.every(hV)?"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:cY(e.name),path:e.path?h4(e.path):"mcp.json"});let n=e.reason?h9[e.reason]:void 0;return n?t(n,{error:cY(e.error)}):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):cY(e.error)}(a,p)]}),a.trustKept&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.trustKept",{folder:h4(a.trust?.decisionPath??n??"")})}),a.notes&&a.notes.length>0&&(0,r.jsx)(h6,{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)(aS,{size:"small",onClick:()=>E({name:a.suggestedName}),children:p("mcp.add.useName",{name:cY(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(cY).join(", ")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aS,{variant:"danger",size:"small",disabled:s||l||void 0!==j,onClick:()=>d(hQ(o,m,a.names)),children:p("mcp.add.hostEnv.confirm")})})]})]})]})}function fe(e){let{names:t}=e,{t:n}=(0,eh.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:cY(e)},e))}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.detail.valuesHidden")})]})}function ft(e){let t,{field:n,fields:o,draft:s,suggestedName:l,problem:a,onDraftChange:c}=e,{t:d}=(0,eh.s)(),u=(0,i.useId)(),p=a?{"aria-invalid":!0,"aria-describedby":u}:{},h=h_(n),f=h?s.references[n.id]:void 0,m=void 0!==f,g=cY(n.label),x=s.values[n.id]??n.defaultValue??"",v=hW[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?hH(n,o,"${"+f+"}",!0):void 0:hH(n,o,`‹${d("mcp.add.field.slot")}›`),j=e=>c({...s,values:{...s.values,[n.id]:e}}),k=e=>{let t={...s.references};void 0===e?delete t[n.id]:t[n.id]=e,c({...s,references:t})};return(0,r.jsxs)("div",{className:"mcp-add-field",children:[(0,r.jsx)(ad,{label:g,children:m?(0,r.jsx)("input",{className:"mcp-add-input","aria-label":d("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:d("mcp.add.field.choose")}),(n.options??[]).map(e=>(0,r.jsx)("option",{value:e,children:cY(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?cY(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:hP(a,d,[n])}),(0,r.jsxs)("span",{className:"mcp-config-lines",children:[n.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:cY(n.description)}),v&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:d(v)}),m?(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:y?d("mcp.add.field.storedAsVariable",{value:y}):d("mcp.add.field.variableHint")}):(0,r.jsxs)(r.Fragment,{children:[y&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:d("mcp.add.field.storedAs",{value:y})}),n.optional&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:b?d("mcp.add.field.optionalHeader",{name:cY(b)}):d("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:d("mcp.add.field.useVariable")})]})]})}function fn(e){let{label:t,draft:n,suggestedName:o,stored:s,problem:l,onDraftChange:a}=e,{t:c}=(0,eh.s)(),d=(0,i.useId)(),u=n.secretReferences[t],p=void 0!==u,h=cY(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})," ",c("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:c("mcp.add.field.useVariable")})]}),p&&(0,r.jsx)(ad,{label:c("mcp.add.field.variableName",{field:h}),children:(0,r.jsx)("input",{className:"mcp-add-input","aria-label":c("mcp.add.field.variableName",{field:h}),value:u,placeholder:o??"API_TOKEN",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...l?{"aria-invalid":!0,"aria-describedby":d}:{},onChange:e=>f(e.target.value)})}),l&&(0,r.jsx)("span",{id:d,className:"mcp-config-line is-error",children:hP(l,c)}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p?void 0!==s?c("mcp.add.secret.storedAs",{value:cY(s)}):c("mcp.add.field.variableHint"):c("mcp.add.secret.asPasted")})]})}let fr=new Set(["done","failed","cancelled","expired"]);function fi(e){var t;return e?.flow!==void 0&&!e.gone&&(t=e.flow.phase,!fr.has(t))}let fo={"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"},fs={"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"},fl={connecting:"mcp.signIn.phase.connecting",starting:"mcp.signIn.phase.starting",finishing:"mcp.signIn.phase.finishing"},fa={"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 fc(e,t,n){var r;let i={...e,flow:t,deadlineAt:n+t.expiresInMs,gone:!1};return r=t.phase,fr.has(r)&&(delete i.pasteError,delete i.cancelError,i.pasting&&(i.pasting=!1),i.cancelling&&(i.cancelling=!1)),i}function fd(e){return"sign-in-unknown"===e.reason}async function fu(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:d$(s,o.status)}}function fp(e,t,n,r,i){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},s=t.method??"GET";return dI(r=>fu(e,t,n,r),()=>({ok:!1,error:{error:`${s} ${e} did not answer within ${i} ms`,timedOut:!0}}),i,r,o)}function fh(e){return`/api/mcp/sign-in/${encodeURIComponent(e)}`}function ff(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?fs[e.reason]:void 0;return r?t(r):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function fm(e){let{server:t,run:n,block:o,signOutBlock:s,controlsBusy:l,signingOut:a,onSignIn:c,onSignOut:d,onPaste:u,onCancel:p}=e,{t:h}=(0,eh.s)(),f=(0,i.useId)(),m=(0,i.useId)(),g=(0,i.useId)(),x=(0,i.useRef)(null),v=(0,i.useRef)(null),b=fi(n),y=(0,i.useRef)(b);if((0,i.useEffect)(()=>{let e=y.current;y.current=b,!e&&b?ep(document,v.current):e&&!b&&ep(document,x.current)},[b]),!t.usesOAuth)return(0,r.jsx)(ap,{label:h("mcp.detail.signIn"),children:void 0!==t.authProvider?h("mcp.signIn.provider",{provider:cY(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,E=j?.phase==="finishing";return(0,r.jsx)(ap,{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:cY(j.name)})}),j&&b&&("authorize"===j.phase?(0,r.jsx)(fg,{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(fl[j.phase]??"mcp.signIn.phase.connecting")})),j&&b&&E&&(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)(fx,{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")," ",ff(n.error,h)]}),b&&n?.cancelError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.cancelFailed")," ",ff(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")," ",ff(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(fo[o])}),!o&&s&&S&&!b&&(0,r.jsx)("span",{id:m,className:"mcp-config-line is-dim",children:h(fo[s])}),(0,r.jsxs)("div",{className:"mcp-sign-in-actions",children:[b&&j?(0,r.jsx)(aS,{ref:v,size:"small",disabled:n?.cancelling===!0||E,"aria-busy":n?.cancelling===!0||void 0,"aria-describedby":E?g:void 0,onClick:()=>p(t,j.flowId),children:h(n?.cancelling?"mcp.signIn.cancelling":"mcp.signIn.cancel")}):(0,r.jsx)(aS,{ref:x,size:"small",variant:"primary",disabled:C,"aria-busy":k||void 0,"aria-describedby":o?f:void 0,onClick:()=>c(t),children:h(k?"mcp.signIn.starting":"mcp.signIn.button")}),S&&!b&&(0,r.jsx)(aS,{size:"small",disabled:N,"aria-busy":a||void 0,"aria-describedby":s?o?f:m:void 0,onClick:()=>d(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 fg(e){let{flow:t,pasting:n,pasteError:o,onPaste:s}=e,{t:l}=(0,eh.s)(),[a,c]=(0,i.useState)(""),d=(0,i.useRef)(null),u=(0,i.useRef)(n);(0,i.useEffect)(()=>{let e=u.current;u.current=n,e&&!n&&ep(document,d.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)(aO,{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:cY(p)})]}):(0,r.jsxs)(r.Fragment,{children:[l("mcp.signIn.authorize.notALink")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:cY(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:d,onValueChange:c,onSubmit:()=>s(a)}),o&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[l("mcp.signIn.paste.refused")," ",ff(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:cY(o.error)})]})]}),t.redirectUrl&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:l("mcp.signIn.authorize.redirect",{url:cY(t.redirectUrl)})}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:l("mcp.signIn.authorize.wait")})]})}function fx(e){let{flow:t,shared:n}=e,{t:i}=(0,eh.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 fa[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:cY(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:cY(t.error)})]})]})}function fv(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function fb(e){return cY(cs(e))}function fy(e,t){let{key:n,params:r}=e;return r?t(n,void 0===r.path?r:{...r,path:fb(r.path)}):t(n)}function fj(e,t){return e.timedOut?t("mcp.loadTimedOut"):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function fk(e,t){return e.timedOut?t("mcp.actionTimedOut"):fj(e,t)}function fw(){if("u"<typeof document)return null;let e=document.activeElement;return e instanceof HTMLButtonElement||e instanceof HTMLSelectElement?e:null}function fS(e){let{cwd:t,onClose:n,embedded:o=!1,trust:s,onTrustProject:l,onProjectTrustChanged:a}=e,[c,d]=(0,i.useState)({state:"loading"}),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(()=>lG("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,N]=(0,i.useState)(null),[E,$]=(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),[A,z]=(0,i.useState)({}),P=(0,i.useRef)(A);P.current=A;let[W,O]=(0,i.useState)(0),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)(hR),_=(0,i.useRef)(B);_.current=B;let[U,K]=(0,i.useState)(null),[q,Z]=(0,i.useState)(null),V=(0,i.useRef)(!0),J=(0,i.useRef)(c);J.current=c;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 dA(t,void 0,n.signal);if(e===I.current){if(p(!1),!r.ok)return void d({state:"failed",error:r.error});d({state:"loaded",data:r.data,...r.projectError?{projectError:r.projectError}:{}}),f(e=>db(dx(r.data,!!t),e))}},[t]),G=cc(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 dW(e,void 0,t.signal);M.current===t&&(M.current=null,g({saving:!1,error:n.ok?null:n.error,target:"preference"}),n.ok&&d(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 dO(e,void 0,t.signal);M.current===t&&(M.current=null,g({saving:!1,error:n.ok?null:n.error,target:"mode"}),n.ok&&d(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 dF(e,void 0,t.signal);M.current===t&&(M.current=null,g({saving:!1,error:n.ok?null:n.error,target:"inlineBudget"}),n.ok&&d(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=c9(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 d1({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=>c9(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),d(t=>({state:"loaded",data:e,..."loaded"===t.state&&t.projectError?{projectError:t.projectError}:{}})),f(r=>db(dx(e,!!t),n??r))},[t]),er=(0,i.useCallback)(async e=>{let n=c9(e),r=P.current[n];if(r?.starting||fi(r))return;z(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 fp("/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&&(z(e=>({...e,[n]:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();return e.ok?fc({},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=c9(e);z(e=>e[r]?.flow?.flowId===t?{...e,[r]:{...e[r],pasting:!0,pasteError:void 0}}:e);let i=await function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(e,t)=>fetch(e,t),r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:15e3;return fp(fh(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirectUrl:t})},n,r,i)}(t,n);V.current&&z(e=>{let n=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Date.now();if(!e?.flow||e.flow.flowId!==t)return e;let i={...e,pasting:!1,version:(e.version??0)+1};return n.ok?{...fc(i,n.data,r),pasteError:void 0}:fd(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=c9(e);z(e=>e[n]?.flow?.flowId===t?{...e,[n]:{...e[n],cancelling:!0}}:e);let r=await function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return fp(fh(e),{method:"DELETE"},t,n,r)}(t);V.current&&z(e=>{let i=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Date.now();if(!e?.flow||e.flow.flowId!==t)return e;let i={...e,cancelling:!1,cancelError:void 0,version:(e.version??0)+1};return n.ok?fc(i,n.data,r):fd(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(A).flatMap(e=>{let[t,n]=e;return fi(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=P.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 fp(fh(e),{},t,n,r)}(r,void 0,e.signal);if(e.signal.aborted)return;z(e=>{let t=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Date.now(),i=arguments.length>4?arguments[4]:void 0;return e?.flow&&e.flow.flowId===t&&(void 0===i||(e.version??0)===i)?n.ok?fc(e,n.data,r):fd(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,W]);let el=(0,i.useRef)(A);(0,i.useEffect)(()=>{let e=el.current;el.current=A,Object.keys(A).some(t=>{var n,r;return n=e[t],r=A[t],fi(n)&&!fi(r)})&&Y()},[A,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 dq(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]),ec=(0,i.useCallback)(async(e,t)=>{let n=c9(e),r=fw();y(null),k(null);let i=await ea({action:t?"enable":"disable",scope:e.scope,name:e.name},`switch:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[ea]),ed=(0,i.useCallback)(async(e,t)=>{let n=c9(e),r=fw();y(null),k(null);let i=await ea({action:"set-in-project",name:e.name,enabled:t},`in-project:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[ea]),eu=(0,i.useCallback)(async(e,t)=>{let n=c9(e),r=fw();y(null),k(null);let i=await ea({action:"set-exposure",scope:e.scope,name:e.name,exposure:t},`exposure:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[ea]),ep=(0,i.useCallback)(async e=>{let t=c9(e),n=fw();y(null),k(null);let r=await ea({action:"remove",scope:e.scope,name:e.name},`remove:${t}`);if(!r)return;if(!r.ok){y({key:t,failure:r.error}),N({control:n});return}let i=r.data.undo;i&&S({...i,undoing:!1})},[ea]),eh=(0,i.useCallback)(async()=>{if(!w)return;let e=fw();y(null),k(null),S({...w,undoing:!0,error:void 0});let t=await ea({action:"undo",token:w.token},"undo",e=>e.restored?c9(e.restored):void 0);t&&(S(e=>e?.token!==w.token?e:t.ok?null:{...e,undoing:!1,error:t.error}),t.ok||N({control:e}))},[ea,w]),ef=(0,i.useCallback)(async e=>{let t=c9(e),n=fw();y(null),k(null),z(e=>({...e,[t]:{...e[t],signOutError:void 0,signedOut:void 0}}));let r=await ea({action:"sign-out",scope:e.scope,name:e.name},`sign-out:${t}`);if(r){if(z(e=>({...e,[t]:r.ok?{signedOut:{removed:r.data.signedOut?.removed===!0}}:{...e[t],signOutError:r.error}})),r.ok){let e=Date.now();$(n=>{let r=function(e,t){if(e)return{running:e.running,...void 0!==e.startedAt?{startedAt:e.startedAt}:{},signedOutAt:t}}(n[t],e);return r?{...n,[t]:r}:n})}N({control:n})}},[ea]),em=(0,i.useCallback)(async e=>{let n=fw(),r=_.current;y(null),k(null),K(null);let i=await ea(e,"add",e=>e.added?c9(e.added):void 0);if(!i)return;let o=_.current!==r;if(!i.ok){o||K(i.error),i.error.trust&&t&&a?.(t,i.error.trust),N({control:n});return}let{added:s,trust:l,trustedFolder:c}=i.data;if(D(!1),o||H(hR),N({control:null,toSelectedRow:!0}),!s)return;Z({...s,key:c9(s),...c&&t?{trustedFolder:t}:{}}),l&&t&&a?.(t,l);let d=i.data.servers.find(e=>c9(e)===c9(s));d&&!dV(d,i.data)&&et(d)},[t,a,ea,et]),eg=w?.token,ex=w?.expiresInMs;(0,i.useEffect)(()=>{if(void 0===eg||void 0===ex)return;let e=setTimeout(()=>S(e=>e?.token===eg?null:e),ex);return()=>clearTimeout(e)},[eg,ex]);let ev=(0,i.useCallback)(async(e,t,n)=>{let{targets:r,keptOff:i}={targets:ca(t,n,e=>e.enabled).filter(n?dU:d_),keptOff:n?t.filter(e=>!e.enabled&&d_(e)&&!dU(e)).length:0},o=fw();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(N({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&&lX("mcp",h,t)},[t,h]),(0,r.jsx)(fC,{cwd:t,load:c,selected:h,refreshing:u,embedded:o,codemodeSave:m,busy:x,actionError:b,groupStatus:j,undo:w,focusBack:C,tests:E,signIns:A,adding:F,addDraft:B,addFailure:U,added:q,onAddOpen:()=>{D(!0),Z(null),y(null)},onAddDraftChange:e=>{_.current=e,H(e),K(null)},onAddSubmit:e=>void em(e),onTest:e=>void et(e),onSignIn:e=>void er(e),onSignOut:e=>void ef(e),onSignInPaste:(e,t,n)=>void ei(e,t,n),onSignInCancel:(e,t)=>void eo(e,t),onSelect:e=>{f(e),y(null),D(!1),Z(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 ec(e,t),onServerSwitchInProject:(e,t)=>void ed(e,t),onExposureChange:(e,t)=>void eu(e,t),onGroupSwitch:(e,t,n)=>void ev(e,t,n),onRemove:e=>void ep(e),onUndo:()=>void eh(),onTrustProject:l,onClose:n})}function fC(e){var t,n,o,s;let l,a,c,{cwd:d,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=hR,addFailure:C=null,added:N=null,onAddOpen:E=()=>{},onAddDraftChange:$=()=>{},onAddSubmit:I=()=>{},onSelect:T,onRefresh:M,onCodemodeChange:R,onCodemodeModeChange:L=()=>{},onCodemodeInlineBudgetSave:A=()=>{},onServerSwitch:z=()=>{},onServerSwitchInProject:P=()=>{},onExposureChange:W=()=>{},onGroupSwitch:O=()=>{},onRemove:F=()=>{},onUndo:D=()=>{},onTest:B=()=>{},onSignIn:H=()=>{},onSignOut:_=()=>{},onSignInPaste:U=()=>{},onSignInCancel:K=()=>{},onTrustProject:q,onClose:Z}=e,{t:V}=(0,eh.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[c9(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?dx(G,!!d):[],Q=G?{mcpAvailable:G.mcp.available,projectServersLoad:c7(G.project)}:void 0,ee=X.flatMap(e=>e.servers),et=ee.find(e=>c9(e)===p),en=N?ee.find(e=>c9(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=q&&dy(G?.project)?q:void 0,ea=es?.kind==="untrusted"&&void 0!==el,ec=(0,i.useRef)(null),ed=(0,i.useRef)(null),eu=(0,i.useRef)(ea);(0,i.useEffect)(()=>{let e=eu.current;eu.current=ea,e&&!ea&&ep(document,ec.current??ed.current)},[ea]);let ef=(0,i.useRef)(null),em=b?.token,eg=(0,i.useRef)(em);(0,i.useEffect)(()=>{let e=eg.current;eg.current=em,void 0!==em&&em!==e?ep(document,ef.current):void 0!==e&&void 0===em&&ep(document,ec.current??ed.current)},[em]);let ex=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}))):[],ev=dv(ee),eb=G?.files.find(e=>"global"===e.scope),ey=G?function(e){let t=e.files.find(e=>"project"===e.scope);if(t?.autoEnableCodemode!==void 0&&c7(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,ej=G?(n=ee.length,o=G.files,n>0?"mcp.selectItem":o.some(e=>e.problems.some(dg))?"mcp.emptyFileProblem":"mcp.empty"):void 0,ek=null!==g||h||m.saving,ew=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(y&&!ek&&ew.current!==y)if(ew.current=y,y.toSelectedRow)ep(document,ec.current??ed.current);else{var e,t,n;e=document,t=y.control,n=ec.current??ed.current,t&&ep(e,t.isConnected&&!t.disabled?t:n)}},[y,ek]);let eS=e=>G?dB(e,G):void 0,eC=!!G&&dD(G.mcp),eN=X.find(e=>"project"===e.scope)?.servers??[],eE=eS("project"),e$=es?.kind==="untrusted"?[fy(es,V),eE&&"mcp-off"!==eE&&eN.length>0?V(dH[eE]):null].filter(Boolean).join(" "):"";return(0,r.jsxs)(l3,{embedded:f,title:V("settings.mcp"),subtitle:d?cs(d):void 0,closeLabel:V("i18n.close"),onClose:Z,children:[(0,r.jsxs)("div",{className:"mcp-config-notices",children:[er&&(0,r.jsxs)(av,{id:J,children:[fy(er,V),eC&&(0,r.jsxs)(r.Fragment,{children:[" ",V(dH["mcp-off"])]}),G&&!G.mcp.available&&G.mcp.detail&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:cY(G.mcp.detail)})]})]}),ei&&(0,r.jsx)(av,{children:V("mcp.hostInactive",{path:fb(ei.cwd),owner:fb(ei.owner)})}),"loaded"===u.state&&u.projectError&&(0,r.jsx)(av,{children:V("mcp.projectNotListed",{reason:fj(u.projectError,V)})}),es?.kind==="untrusted"&&(0,r.jsx)(ab,{id:Y,message:e$,trustLabel:V("mcp.trust.trustButton"),onTrust:el}),es?.kind==="inherited"&&(0,r.jsx)(av,{children:fy(es,V)}),b&&(0,r.jsxs)(av,{action:b.error?.reason==="undo-unavailable"?void 0:(0,r.jsx)(aS,{ref:ef,size:"small",onClick:D,disabled:b.undoing||ek,children:b.undoing?V("mcp.undoing"):V("mcp.undo")}),children:[V("mcp.removed",{name:cY(b.name),path:fb(b.path)}),b.error&&(0,r.jsxs)(r.Fragment,{children:[" ",V("mcp.undoFailed")," ",fk(b.error,V)]})]}),N&&G&&en&&(0,r.jsx)(fN,{added:N,cwd:d,server:en,testing:j[N.key]?.running===!0,signIn:k[N.key],signingOut:g===`sign-out:${N.key}`,signInBlock:en?dV(en,G):void 0,onSignIn:H})]}),(0,r.jsxs)(l5,{children:[(0,r.jsxs)(l6,{children:[(0,r.jsx)(l9,{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")," ",fj(u.error,V)]}):G&&Q?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-sidebar-group",children:(0,r.jsx)(fE,{codemode:G.codemode,active:!w&&p===c6,rowRef:ec,onSelect:T})}),X.map(e=>{let t=eS(e.scope);return(0,r.jsx)(f$,{group:e,context:Q,selected:w?null:p,selectedRowRef:ec,block:t,blockNoticeId:"mcp-off"===t?er?J:void 0:t&&es?.kind==="untrusted"?Y:void 0,busy:g,controlsBusy:ek,status:v?.scope===e.scope?v:null,onSelect:T,onGroupSwitch:O},e.scope)})]}):null}),G&&(0,r.jsx)(aN,{ref:ed,active:w,onClick:E,children:V("mcp.add.action")})]}),(0,r.jsx)(aj,{children:(0,r.jsx)(ai,{className:"is-fill",children:G&&Q&&ey&&ej?w?(0,r.jsx)(h7,{data:G,cwd:d,draft:S,busy:"add"===g,controlsBusy:ek,failure:C,onDraftChange:$,onSubmit:I,onTrustProject:el}):p===c6?(0,r.jsx)(fD,{codemode:G.codemode,autoEnable:ey,save:m,serverBusy:null!==g,onChange:R,onModeChange:L,onInlineBudgetSave:A}):et?(0,r.jsx)(fR,{server:et,context:Q,codemode:G.codemode,toolSearchDisabled:G.toolSearchDisabled,autoEnable:ey,block:eS(et.scope),inProject:function(e,t){if("global"!==e.scope||void 0!==e.invalidError||e.notAnObject||!c7(t.project))return;let n=t.files.find(e=>"project"===e.scope);if(!n||n.problems.some(e=>"auto-enable-codemode-invalid"!==e.reason))return;let r=t.servers.find(t=>"project"===t.scope&&t.name===e.name);return r?r.override?{kind:"override",key:c9(r),keys:r.override.keys,applies:!0===e.overriddenByProject}:void 0:{kind:"switch"}}(et,G),inProjectBlock:eS("project"),savedWhileOff:!G.mcp.available&&!eC,busy:g,controlsBusy:ek,actionError:x?.key===c9(et)?x.failure:null,test:(s=j[c9(et)],s&&void 0!==s.configKey&&s.configKey!==et.configKey?{running:s.running,...s.response?{response:s.response}:{}}:s),testBlock:dV(et,G),signIn:k[c9(et)],signInBlock:dV(et,G),signOutBlock:(c=dB(et.scope,G))||(void 0===et.invalidError&&et.validated?void 0:"invalid"),onSwitch:z,onSwitchInProject:P,onShowServer:e=>{T(e),requestAnimationFrame(()=>ep(document,ec.current??ed.current))},onExposureChange:W,onRemove:F,onTest:B,onSignIn:H,onSignOut:_,onSignInPaste:U,onSignInCancel:K},c9(et)):(0,r.jsx)(ay,{children:"mcp.empty"===ej?V(ej,{globalPath:fb(eb?.path??"~/.pi/agent/mcp.json")}):V(ej)}):null})})]}),(0,r.jsxs)(ak,{status:ex.length>0?(0,r.jsx)(aw,{tone:ex.some(e=>{let{problem:t}=e;return dg(t)})?"error":"warning",summary:1===ex.length?V("mcp.footer.fileProblem"):V("mcp.footer.fileProblems",{count:ex.length}),details:ex.map(e=>{let{file:t,problem:n}=e,i=c5(n,t.realPath);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:fb(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)(aw,{summary:ev.total>0?V("mcp.serverCount",{enabled:ev.enabled,total:ev.total}):""}),children:[!f&&(0,r.jsx)(aS,{onClick:Z,children:V("i18n.close")}),(0,r.jsx)(aS,{variant:"secondary",onClick:M,disabled:ek,children:V("i18n.refresh")})]})]})}function fN(e){let{added:t,cwd:n,server:i,testing:o,signIn:s,signingOut:l,signInBlock:a,onSignIn:c}=e,{t:d}=(0,eh.s)(),u=cY(t.name),p="project"===t.scope&&n?cY(cl(t.path,n)):fb(t.path),h=i.status,f=!o&&h?.origin==="test"&&"needs-auth"===h.state&&i.usesOAuth,m=s?.starting===!0||fi(s);return(0,r.jsxs)(av,{action:!f||m||l||a?void 0:(0,r.jsx)(aS,{size:"small",variant:"primary",onClick:()=>c(i),children:d("mcp.signIn.button")}),children:[void 0===t.trustedFolder?d("mcp.add.added",{name:u,path:p}):t.trustedFolder===n?d("mcp.add.addedTrustedHere",{name:u,path:p}):d("mcp.add.addedTrusted",{name:u,path:p,folder:fb(t.trustedFolder)}),o&&(0,r.jsxs)(r.Fragment,{children:[" ",d("mcp.add.testing")]}),f&&(0,r.jsxs)(r.Fragment,{children:[" ",d("mcp.add.needsSignIn")]})]})}function fE(e){let{codemode:t,active:n,rowRef:i,onSelect:o}=e,{t:s}=(0,eh.s)(),l=t.builtinDisabled||"unavailable"===t.sandbox.state?"unavailable":t.preference??"unknown",a=s(dC[l]);return(0,r.jsxs)(an,{ref:n?i:void 0,active:n,"aria-label":s("mcp.codemode.rowLabel",{state:a}),onClick:()=>o(c6),children:[(0,r.jsx)(aE,{...da(dN(l))}),(0,r.jsx)(ar,{className:"is-grow",children:s("mcp.codemode.title")}),(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${dN(l)}`,children:a})]})}function f$(e){var t;let n,i,{group:o,context:s,selected:l,selectedRowRef:a,block:c,blockNoticeId:d,busy:u,controlsBusy:p,status:h,onSelect:f,onGroupSwitch:m}=e,{t:g}=(0,eh.s)(),{enabled:x,total:v}=dv(o.servers),b=(t=o.servers).some(e=>e.enabled&&d_(e))&&t.every(e=>e.enabled||!dU(e)),y=function(e){if(!(e.servers.length>0))return e.file?e.file.problems.some(dg)?"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")} ${fk(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`${cY(t)}: ${fk(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)(l7,{aside:v>0?(0,r.jsx)(ae,{enabled:x,total:v,checked:b,disabled:p||void 0!==c,loading:u===`group:${o.scope}`,describedBy:c?d:void 0,label:g(b?"mcp.groupSwitchOn":"mcp.groupSwitchOff",{group:fv(o.scope,g)}),onChange:e=>m(o.scope,o.servers,e)}):void 0,children:fv(o.scope,g)}),j&&(0,r.jsx)(at,{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=c9(e),n=de(e,s),i=dl(n),o=ds[n],c=cY(e.name);return(0,r.jsxs)(an,{ref:l===t?a:void 0,active:l===t,"aria-label":g("mcp.rowLabel",{name:c,state:g(dr(n,e.status))}),onClick:()=>f(t),children:[(0,r.jsx)(aE,{...da(i)}),(0,r.jsx)(ar,{className:`is-grow${"on"===i?"":" is-muted"}`,children:c}),o&&(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${i}`,children:g(o)})]},t)})]})}function fI(e){let{fields:t}=e,{t:n}=(0,eh.s)();return(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>{let t=c2(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function fT(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:cY(e)},e))})}function fM(e){let{server:t,state:n}=e,{t:i}=(0,eh.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:cY(t.invalidError??"")})]});let o=di[n];return o?(0,r.jsx)("span",{className:"mcp-config-line",children:i(o)}):null}function fR(e){let{server:t,context:n,codemode:o,toolSearchDisabled:s,autoEnable:l,block:a,inProject:c,inProjectBlock:d,savedWhileOff:u,busy:p,controlsBusy:h,actionError:f,test:m,testBlock:g,signIn:x,signInBlock:v,signOutBlock:b,onSwitch:y,onSwitchInProject:j,onShowServer:k,onExposureChange:w,onRemove:S,onTest:C,onSignIn:N,onSignOut:E,onSignInPaste:$,onSignInCancel:I}=e,{t:T}=(0,eh.s)(),M=(0,i.useId)(),R=(0,i.useId)(),L=de(t,n),A=dl(L),z=c0(t),P=void 0===t.invalidError,W="http"===t.transport||void 0===t.transport&&void 0!==t.url,O=!W&&("stdio"===t.transport||void 0!==t.command),F=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"===dj(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,D=(0,i.useId)(),B=(0,i.useId)(),H=c9(t),_=cY(t.name),U=!t.enabled&&void 0!==t.webPasswordField,K=!0===t.notAnObject,q=a?T(`mcp.reason.${a}`):K?T("mcp.reason.entry-not-object"):U?T("mcp.reason.web-password"):u?T("mcp.write.savedWhileOff"):void 0;return(0,r.jsxs)(ai,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(ao,{children:[(0,r.jsxs)(as,{children:[(0,r.jsx)(ah,{scope:t.scope,children:fv(t.scope,T)}),(0,r.jsx)(aa,{children:_})]}),(0,r.jsxs)(al,{children:[(0,r.jsx)(fO,{server:t,test:m,testBlock:g,describedBy:R,onTest:C}),(0,r.jsx)(aS,{variant:"danger",size:"small",disabled:h||void 0!==a,"aria-describedby":a?M:void 0,onClick:()=>S(t),children:p===`remove:${H}`?T("i18n.removing"):T("i18n.remove")}),(0,r.jsx)(aC,{checked:t.enabled,disabled:h||void 0!==a||K||U,loading:p===`switch:${H}`,describedBy:q?M:void 0,label:T(t.enabled?"mcp.server.switchOff":"mcp.server.switchOn",{name:_}),onChange:e=>y(t,e)})]})]}),q&&(0,r.jsx)("div",{id:M,className:"config-detail-heading-note",children:q})]}),f&&(0,r.jsxs)("p",{role:"alert",className:"mcp-config-line is-error",children:[T("mcp.actionFailed")," ",fk(f,T)]}),(0,r.jsxs)(au,{children:[(0,r.jsx)(ap,{label:T("i18n.status"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:`mcp-config-state is-${A}`,children:T(dr(L,t.status))}),(0,r.jsx)(fM,{server:t,state:L}),t.webPasswordField&&(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[T("mcp.server.webPassword")," ",(0,r.jsx)(fI,{fields:[t.webPasswordField]})]})]})}),(0,r.jsx)(fF,{server:t,test:m,testBlock:g,testBlockId:R}),void 0!==t.description&&(0,r.jsx)(ap,{label:T("mcp.detail.description"),tone:"plain",children:cY(t.description)}),t.transport&&(0,r.jsx)(ap,{label:T("mcp.detail.transport"),children:T(`mcp.transport.${t.transport}`)}),void 0!==z&&(0,r.jsx)(ap,{label:W?T("mcp.detail.url"):T("mcp.detail.command"),tone:"plain",mono:!0,children:z}),O&&void 0!==t.cwd&&(0,r.jsx)(ap,{label:T("mcp.detail.cwd"),mono:!0,children:cY(t.cwd)}),O&&t.envNames.length>0&&(0,r.jsx)(ap,{label:T("mcp.detail.env"),children:(0,r.jsx)(fT,{names:t.envNames})}),W&&t.headerNames.length>0&&(0,r.jsx)(ap,{label:T("mcp.detail.headers"),children:(0,r.jsx)(fT,{names:t.headerNames})}),P&&t.commandFields.length>0&&(0,r.jsx)(ap,{label:T("mcp.detail.shellCommands"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:T("mcp.server.commandFields")}),(0,r.jsx)(fI,{fields:t.commandFields})]})}),P&&t.variableReferences.length>0&&(0,r.jsx)(ap,{label:T("mcp.detail.variables"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:T(c4(t))}),(0,r.jsx)("span",{className:"mcp-config-chips",children:c3(t.variableReferences).map(e=>{let{variable:t,field:n}=e,i=c2(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:T("mcp.server.variableIn",{variable:t,field:T(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})}),W&&P&&(0,r.jsx)(fm,{server:t,run:x,block:v,signOutBlock:b,controlsBusy:h,signingOut:p===`sign-out:${H}`,onSignIn:N,onSignOut:E,onPaste:$,onCancel:I}),t.exposure&&(0,r.jsx)(ap,{label:T("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":T("mcp.exposure.label",{name:_}),"aria-describedby":[D,a?M:null].filter(Boolean).join(" "),value:t.exposure,disabled:h||void 0!==a,onChange:e=>{let n=e.target.value;n!==t.exposure&&w(t,n)},children:df.map(e=>(0,r.jsx)("option",{value:e,children:"codemode"===e?T("mcp.exposure.optionDefault",{label:T(dm[e])}):T(dm[e])},e))}),p===`exposure:${H}`&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:T("i18n.saving")})]}),(0,r.jsx)("span",{id:D,className:"mcp-config-line",children:T(dh[t.exposure])}),void 0!==t.toolExposureCount&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:T("mcp.exposure.toolOverrides",{count:t.toolExposureCount})}),F&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:fy(F,T)})]})}),c&&(0,r.jsx)(ap,{label:T("mcp.detail.inProject"),tone:"plain",children:(0,r.jsx)("span",{className:"mcp-config-lines",children:"override"===c.kind?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"mcp-config-line",children:c.applies?T("mcp.inProject.overridden",{keys:c.keys.join(", ")}):T("mcp.inProject.refused")}),(0,r.jsx)("span",{children:(0,r.jsx)(aS,{size:"small",onClick:()=>k(c.key),children:T("mcp.inProject.show")})})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:(0,r.jsx)(aS,{size:"small",disabled:h||void 0!==d||U,"aria-describedby":[B,d||U?M:null].filter(Boolean).join(" "),onClick:()=>j(t,!t.enabled),children:p===`in-project:${H}`?T("i18n.saving"):T(t.enabled?"mcp.inProject.turnOff":"mcp.inProject.turnOn")})}),(0,r.jsx)("span",{id:B,className:"mcp-config-line is-dim",children:T("mcp.inProject.saved")})]})})}),(0,r.jsx)(ap,{label:T("mcp.detail.file"),tone:"dim",mono:!0,children:fb(t.sourcePath)})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[c1(t)&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:T("mcp.server.hiddenCharacters")}),!t.validated&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:T("mcp.server.unchecked")}),t.replacesGlobal&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:T("mcp.server.replacesGlobal")}),t.override&&(0,r.jsx)("p",{className:"mcp-config-line",children:fy(c8(t.override.keys),T)}),t.shadowedByProject&&"replaced"!==L&&(0,r.jsx)("p",{className:"mcp-config-line",children:T("mcp.server.shadowedByProject")}),t.overriddenByProject&&"overridden"!==L&&(0,r.jsx)("p",{className:"mcp-config-line",children:T("mcp.server.overriddenByProject")}),t.masked&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:T("mcp.server.masked")})]})]})}function fL(e){let{error:t,stderr:n}=e,{t:i}=(0,eh.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:cY(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(cY).join("\n")})]})]})}function fA(e){let{status:t}=e;return"session"===t.origin?(0,r.jsx)(fP,{status:t}):(0,r.jsx)(fz,{status:t})}function fz(e){let{status:t}=e,{t:n,locale:i}=(0,eh.s)(),o=t.timedOut?{key:dY.timedOut,tone:"error"}:{key:dY[t.state],tone:dl(t.state)},s=dc(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?dX:dG)[t.timedOut?"timedOut":t.state],{count:t.toolCount,seconds:dQ(t.durationMs),time:s})]}),(0,r.jsx)(fL,{error:t.error,stderr:t.stderr}),l&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.test.serverInfo",{name:cY(l.title??l.name),version:cY(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:fb(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:dQ(t.queuedMs)})})]})}function fP(e){let{status:t}=e,{t:n,locale:i}=(0,eh.s)(),o=void 0!==t.closedAt?{key:"mcp.session.state.closed",tone:"off"}:{key:dd[t.state],tone:dp[t.state]},s=dc(t.updatedAt,i),l=void 0===t.closedAt?void 0:dc(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":du[t.state],{path:fb(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:fb(t.conflict)})]}),(0,r.jsx)(fL,{error:t.error,stderr:t.stderr})]})}function fW(e){let{status:t,serverExposure:n}=e,{t:i}=(0,eh.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:cY(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(dm[e.exposure])})]}),e.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:cY(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 fO(e){let{server:t,test:n,testBlock:o,describedBy:s,onTest:l}=e,{t:a}=(0,eh.s)(),c=(0,i.useRef)(null),d=n?.running===!0,u=(0,i.useRef)(d);return(0,i.useEffect)(()=>{let e=u.current;u.current=d,e&&!d&&ep(document,c.current)},[d]),(0,r.jsx)(aS,{ref:c,size:"small",disabled:d||void 0!==o,"aria-busy":d||void 0,"aria-describedby":o?s:void 0,onClick:()=>l(t),children:a(d?"mcp.test.testing":"mcp.test.button")})}function fF(e){let{server:t,test:n,testBlock:i,testBlockId:o}=e,{t:s}=(0,eh.s)(),l=t.status;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ap,{label:s("mcp.detail.connection"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[l?(0,r.jsx)(fA,{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?dJ[e.reason]:void 0;return n?t(n):fj(e,t)}(n.error,s)]}),i&&(0,r.jsx)("span",{id:o,className:"mcp-config-line is-dim",children:s(dZ[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)(ap,{label:s("mcp.detail.listedTools"),tone:"plain",children:(0,r.jsx)(fW,{status:l,serverExposure:t.exposure})})]})}function fD(e){let{codemode:t,autoEnable:n,save:i,serverBusy:o,onChange:s,onModeChange:l,onInlineBudgetSave:a}=e,{t:c}=(0,eh.s)(),d=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"===dj(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:dk[t.preference],params:{path:t.settingsPath}}}(t);return(0,r.jsxs)(ai,{children:[(0,r.jsx)(ao,{children:(0,r.jsx)(as,{children:(0,r.jsx)(aa,{children:c("mcp.codemode.title")})})}),(0,r.jsx)("p",{className:"mcp-config-line",children:c("mcp.codemode.intro")}),(0,r.jsxs)(au,{children:[(0,r.jsx)(ap,{label:c("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)(af,{value:u,label:c("mcp.codemode.title"),options:[{value:"automatic",label:c(dC.automatic),disabled:p},{value:"always",label:c(dC.always),disabled:p||void 0!==m}],disabledReason:m?fy(m,c):null,onChange:e=>{e!==u&&s(e)},children:h.saving&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:c("i18n.saving")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:c("always"===u?"mcp.codemode.alwaysDescription":"mcp.codemode.automaticDescription")})]}):(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[c("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:cY(t.preferenceError??"")})]}),h.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[c("mcp.codemode.saveFailed")," ",(0,r.jsx)(fB,{error:h.error})]}),x&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:fy(x,c)}),f&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:fy(f,c)})]})}),t.mode?(0,r.jsx)(fH,{mode:t.mode,codemode:t,save:i,waiting:p,onChange:l}):void 0!==t.modeError&&(0,r.jsx)(ap,{label:c("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[c("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:cY(t.modeError)})]})}),t.inlineBudget?(0,r.jsx)(f_,{budget:t.inlineBudget,save:i,waiting:p,onSave:a}):void 0!==t.inlineBudgetError&&(0,r.jsx)(ap,{label:c("mcp.codemode.inlineBudget"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[c("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:cY(t.inlineBudgetError)})]})}),(0,r.jsx)(ap,{label:c("mcp.codemode.sandbox"),tone:"plain",children:"unavailable"===d.state?(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[c("mcp.codemode.sandbox.unavailable")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:cY(d.error)})]}):(0,r.jsx)("span",{className:"mcp-config-line",children:c("available"===d.state?"mcp.codemode.sandbox.available":"mcp.codemode.sandbox.not-checked")})}),g&&(0,r.jsx)(ap,{label:c("mcp.codemode.builtin"),tone:"error",children:fy(g,c)})]})]})}function fB(e){let{error:t}=e,{t:n}=(0,eh.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:cY(t.error)})}function fH(e){let{mode:t,codemode:n,save:i,waiting:o,onChange:s}=e,{t:l}=(0,eh.s)(),a="mode"===i.target,c=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:dS[r.value],params:{path:r.settingsPath}}),"only"===(r??t).value&&"automatic"===dj(e)&&n.push({key:"mcp.codemode.toolMode.automaticNote"}),n}(n);return(0,r.jsx)(ap,{label:l("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)(af,{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(dw[t.value])}),c.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:fy(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)(fB,{error:i.error})]})]})})}function f_(e){let t,n,{budget:o,save:s,waiting:l,onSave:a}=e,{t:c}=(0,eh.s)(),d=(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&&ep(document,d.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)(ap,{label:c("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:d,className:"mcp-add-input mcp-codemode-budget-input",inputMode:"numeric","aria-label":c("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:c("mcp.codemode.inlineBudget.unit")}),(0,r.jsx)(aS,{type:"submit",size:"small",disabled:!g||l,children:c("mcp.codemode.inlineBudget.save")}),v&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:c("i18n.saving")})]}),!m.ok&&(0,r.jsx)("span",{className:"mcp-config-line is-error",children:c("mcp.codemode.inlineBudget.invalidDraft",{max:String(o.max)})}),(0,r.jsx)("span",{id:u,className:"mcp-config-line",children:c("mcp.codemode.inlineBudget.description",{default:String(o.default)})}),y.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:fy(e,c)},e.key)),x&&s.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[c("mcp.codemode.inlineBudget.saveFailed")," ",(0,r.jsx)(fB,{error:s.error})]})]})})}let fU=[{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 fK(){let{t:e}=(0,eh.s)(),t=oB();return(0,r.jsx)("div",{className:"settings-font-rows",children:fU.map(n=>{let{kind:i,label:o,placeholder:s,reset:l,weightLabel:a}=n,c=t[`${i}Weight`],d=oj.findIndex(e=>e.value===c);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:c}),(0,r.jsx)(aS,{variant:"ghost",size:"small",className:"settings-chat-reset",title:e(l),"aria-label":e(l),disabled:!t[i]&&400===c,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:oj[0].value,max:oj[oj.length-1].value,step:100,value:c,"aria-label":e(a),"aria-valuetext":`${c} ${e(oj[d].label)}`,onChange:e=>t.setFontWeight(i,Number(e.target.value))})]},i)})})}function fq(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 fZ(e){let{sessionId:t,onSessionReloaded:n,quoteSelectionEnabled:o,onQuoteSelectionChange:s}=e,{locale:l,setLocale:a,supportedLocales:c,t:d}=(0,eh.s)(),{preference:u,setThemePreference:p}=rU(),{width:h,setWidth:f,fontSize:m,setFontSize:g}=oy(),x=oo(),[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,E]=(0,i.useState)(!1),[$,I]=(0,i.useState)(null),[T,M]=(0,i.useState)(!1),[R,L]=(0,i.useState)(!1),[A,z]=(0,i.useState)("");(0,i.useEffect)(()=>{C(r6()),fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>M(e?.enabled===!0)).catch(()=>{})},[]);let P=async()=>{L(!0),z("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.replace("/login")}catch{z(d("auth.logoutFailed"))}finally{L(!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 W=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 sT(t,{type:"reload"}),n())}catch(e){w(e instanceof Error?e.message:String(e))}finally{j(!1)}},O=async()=>{if(!N){E(!0),I(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 co(l))throw Error("unsupported or not permitted");I({kind:"ok",message:d("settings.pushRegistered")})}catch(e){I({kind:"error",message:`${d("settings.pushRegisterFailed")} ${e instanceof Error?e.message:String(e)}`})}finally{E(!1)}}};return(0,r.jsxs)("div",{className:"settings-general",children:[(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.appearance")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":d("settings.appearance"),className:"settings-theme-options",children:r$.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)(lH,{preference:e.id}),(0,r.jsx)("span",{className:"settings-theme-option-label",children:d(e.label)})]},e.id)})})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.typography")}),(0,r.jsx)("p",{id:"settings-typography-description",className:"settings-general-description",children:d("settings.fontDescription")}),(0,r.jsxs)("div",{className:"settings-chat-options",children:[(0,r.jsx)(fK,{}),(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:d("settings.chatContentFontSize")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-font-size",children:[m,"px"]}),(0,r.jsx)(aS,{variant:"ghost",size:"small",className:"settings-chat-reset",title:d("settings.resetChatContentFontSize"),"aria-label":d("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:d("settings.chatContentWidth")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-width",children:[h,"px"]}),(0,r.jsx)(aS,{variant:"ghost",size:"small",className:"settings-chat-reset",title:d("settings.resetChatContentWidth"),"aria-label":d("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:d("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:d("settings.thinkingExpandedDefault")}),(0,r.jsx)(aC,{checked:S,label:d("settings.thinkingExpandedDefault"),onChange:e=>{window.localStorage.setItem(r3,String(e)),window.dispatchEvent(new Event(r5)),C(e)}})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:d("settings.quoteSelection")}),(0,r.jsx)(aC,{checked:o,label:d("settings.quoteSelection"),onChange:s})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",role:"radiogroup","aria-label":d("settings.enterSendMode"),children:[(0,r.jsx)("span",{children:d("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:()=>oi("enter"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:d("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:()=>oi("ctrlEnter"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:d("settings.enterSendModeCtrlEnter")})]})]})]})]})]}),v?.isWindows&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.shellTool")}),(0,r.jsx)("p",{className:"settings-general-description",children:d("settings.shellToolDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:d("settings.usePowerShell")}),(0,r.jsx)(aC,{checked:v.powerShellEnabled,loading:y,label:d("settings.usePowerShell"),onChange:e=>void W(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:d("settings.pushPermission")}),(0,r.jsx)("p",{className:"settings-general-description",children:d("settings.pushPermissionDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:d("settings.pushPermission")}),(0,r.jsx)("button",{type:"button",className:"config-button config-button-small config-button-secondary",disabled:N,onClick:()=>void O(),children:N?d("settings.pushRegisterLoading"):d("settings.pushRegister")})]}),$&&(0,r.jsx)("p",{role:"status",className:"settings-general-error",style:"ok"===$.kind?{color:"var(--accent)"}:void 0,children:$.message})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("common.language")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":d("common.language"),className:"settings-language-options",children:c.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)})})]}),T&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsxs)(aS,{variant:"secondary",disabled:R,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"})}),R?d("auth.loggingOut"):d("auth.logOut")]}),A&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:A})]})]})}let fV={en:"Archives","zh-CN":"归档","zh-TW":"封存"};function fJ(e){let{cwd:t,sessionId:n,initialSection:o,onClose:s,onSessionReloaded:l,quoteSelectionEnabled:a,onQuoteSelectionChange:c,projectTrust:d,onOpenTrustDialog:u,onProjectTrustChanged:p}=e,{t:h,locale:f}=(0,eh.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:fV[f]??fV.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:lq(e.id)})),y=lq(m);(0,i.useEffect)(()=>lY(o),[o]),(0,i.useEffect)(()=>{var e;let t;return e=document,t=e=>{"Escape"!==e.key||e.defaultPrevented||eu(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")),lY("general"))},[t,y]);let k=e=>{v(t=>new Set(t).add(e)),g(e),lY(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)(fq,{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)(fZ,{sessionId:n,onSessionReloaded:l,quoteSelectionEnabled:a,onQuoteSelectionChange:c})),w("models",(0,r.jsx)(cr,{embedded:!0,cwd:t,onClose:s})),w("archives",(0,r.jsx)(cq,{embedded:!0,onClose:s})),t&&w("skills",(0,r.jsx)(cg,{embedded:!0,cwd:t,trust:d,onClose:s},t)),t&&w("agents",(0,r.jsx)(cI,{embedded:!0,cwd:t,sessionId:n,trust:d,onClose:s,onReloaded:l},t)),t&&w("plugins",(0,r.jsx)(cH,{embedded:!0,cwd:t,sessionId:n,trust:d,onClose:s,onReloaded:l},t)),w("mcp",(0,r.jsx)(fS,{embedded:!0,cwd:t,trust:d,onTrustProject:u,onProjectTrustChanged:p,onClose:s},t??""))]})]})})}let fY="project-trust-mcp-status";function fG(e){let{cwd:t,busy:n,error:o,onCancel:s,onConfirm:l,onStatus:a}=e,[c,d]=(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;d({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);d(r),"loaded"===r.state&&r.status&&u.current?.(r.status)}).catch(t=>{e&&d(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)(fX,{cwd:t,busy:n,error:o,listing:c,onCancel:s,onConfirm:l})}function fX(e){let{cwd:t,busy:n,error:o,listing:s,onCancel:l,onConfirm:a}=e,{t:c}=(0,eh.s)(),d="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(),eu(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:c("trust.dialogTitle")}),(0,r.jsx)("div",{id:"project-trust-description",className:"project-trust-text",children:c("trust.dialogBody")}),(0,r.jsx)("code",{className:"project-trust-path",children:cY(t)}),u&&(0,r.jsx)("p",{id:"project-trust-notice",role:"status",className:"project-trust-notice",children:c(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:c("mcp.reason.trust-unreadable")}),(0,r.jsx)("code",{className:"project-trust-mcp-detail",children:cY(s.statusError)})]}),(0,r.jsx)(f0,{listing:s})]})]}),o&&(0,r.jsx)(fQ,{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:c(u?"trust.close":"trust.cancel")}),!u&&(0,r.jsx)("button",{type:"button",className:"project-trust-button is-primary",onClick:a,disabled:n||d,"aria-busy":n||void 0,"aria-describedby":d?fY:void 0,children:c(n?"trust.trusting":"trust.trustProject")})]})]})})}function fQ(e){let{error:t}=e,{t:n}=(0,eh.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:cY(t.error)})]})}function f0(e){let{listing:t}=e,{t:n}=(0,eh.s)();if("loading"===t.state)return(0,r.jsx)("p",{id:fY,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:cY(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)(f1,{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)(f8,{server:e},e.name))})]}):null}function f1(e){let{file:t}=e,{t:n}=(0,eh.s)();return(0,r.jsx)(r.Fragment,{children:t.problems.map(e=>{let i=c5(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 f2(e){let{fields:t}=e,{t:n}=(0,eh.s)();return(0,r.jsx)(r.Fragment,{children:t.map(e=>{let t=c2(e);return(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function f4(e){let{server:t}=e,{t:n}=(0,eh.s)();return(0,r.jsx)(r.Fragment,{children:c3(t.variableReferences).map(e=>{let{variable:t,field:i}=e,o=c2(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 f8(e){let t,{server:n}=e,{t:i}=(0,eh.s)(),o=c0(n),s=void 0===n.invalidError;return(0,r.jsxs)("li",{className:"project-trust-mcp-server",children:[(0,r.jsxs)("div",{className:"project-trust-mcp-server-head",children:[(0,r.jsx)("span",{className:"project-trust-mcp-server-name",children:cY(n.name)}),n.transport&&(0,r.jsx)("span",{className:"project-trust-mcp-tag",children:i(`mcp.transport.${n.transport}`)})]}),void 0!==o&&(0,r.jsx)("code",{className:"project-trust-mcp-target",children:o}),void 0!==n.cwd&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:i("trust.mcp.cwd",{path:cY(n.cwd)})}),c1(n)&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:i("mcp.server.hiddenCharacters")}),void 0!==n.invalidError&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.invalid")," ",(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:cY(n.invalidError)})]}),n.webPasswordField&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.webPassword")," ",(0,r.jsx)(f2,{fields:[n.webPasswordField]})]}),!n.enabled&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:i("mcp.server.disabled")}),s&&n.commandFields.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.commandFields")," ",(0,r.jsx)(f2,{fields:n.commandFields})]}),s&&n.variableReferences.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i(c4(n))," ",(0,r.jsx)(f4,{server:n})]}),n.replacesGlobal&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:i("mcp.server.replacesGlobal")}),n.override&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:i((t=c8(n.override.keys)).key,t.params)}),n.masked&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-dim",children:i("mcp.server.masked")})]})}function f3(e){return"message"===e.type&&"message"in e&&"system"!==e.message.role}function f5(e){let t=e,n=t.branchPreview,r=f3(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&f3(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function f6(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 f9(e){let{node:t,activePathIds:n,depth:i,isLast:o,parentLines:s,onSelect:l}=e,{node:a,skipped:c,branchPreview:d,labelEntry:u}=f5(t),p=n.has(a.entry.id),h=n.has(t.entry.id)||n.has(a.entry.id),f=d?.text??function(e){if("message"===e.type&&f3(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=d?d.role??null:f3(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"}),c>0&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",c]}),(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)(f9,{node:e,activePathIds:n,depth:i+1,isLast:t===a.children.length-1,parentLines:[...s,!o],onSelect:l},e.entry.id))]})}function f7(e){let{tree:t,activeLeafId:n,onLeafChange:o,inline:s,containerRef:l,open:a,onToggle:c,hasSession:d,compact:u,hideInlineButton:p,locked:h=!1}=e,{t:f}=(0,eh.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=d?f6(t)?null:f("i18n.noBranches"):f("i18n.noActiveSession"),N=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=f5(e[0]).node;return t.children.length>1?t.children:[]}(t),E=!C&&N.length>0,$=(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:E?"var(--accent)":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),I=(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{marginLeft:2,transform:x?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})});return s?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"stretch"},children:[(0,r.jsxs)("button",{ref:v,onClick:()=>c?c():g(e=>!e),style:{display:p?"none":"flex",alignItems:"center",gap:6,height:"100%",padding:"0 12px",background:x?"var(--bg-selected)":"none",border:"none",borderTop:x?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:"pointer",color:x?"var(--text)":"var(--text-muted)",fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color=x?"var(--text)":"var(--text-muted)"},title:f("i18n.branches"),"aria-label":f("i18n.branches"),"aria-pressed":x,children:[$,!u&&(0,r.jsx)("span",{children:f("i18n.branches")})]}),x&&b&&(0,r.jsx)("div",{style:{position:"fixed",top:b.top,left:b.left,width:b.width,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",zIndex:500},children:E?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(f9,{node:e,activePathIds:j,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:w},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C})})]}):(0,r.jsxs)("div",{style:{borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>g(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"5px 12px",background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",fontSize:11,textAlign:"left"},children:[$,(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:f("i18n.branches")}),I]}),x&&(0,r.jsx)("div",{style:{position:"absolute",top:"100%",left:0,right:0,background:"var(--bg)",borderBottom:"1px solid var(--border)",boxShadow:"0 4px 12px rgba(0,0,0,0.1)",zIndex:100},children:E?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(f9,{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 me(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:`
12
12
  .system-prompt-panel {
13
13
  display: flex;
14
14
  height: min(600px, 75dvh);