cuelo 0.10.0 → 0.10.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/BUILD_ID +1 -1
- package/.next/app-path-routes-manifest.json +9 -9
- package/.next/build-manifest.json +2 -2
- package/.next/prerender-manifest.json +3 -3
- package/.next/required-server-files.js +2 -2
- package/.next/required-server-files.json +2 -2
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +2 -2
- package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
- package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/api/updates/route.js +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +4 -4
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
- package/.next/server/app/index.segments/_full.segment.rsc +4 -4
- package/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/.next/server/app/index.segments/_index.segment.rsc +2 -2
- package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/office/page_client-reference-manifest.js +1 -1
- package/.next/server/app/office-preview/page_client-reference-manifest.js +1 -1
- package/.next/server/app/office-preview.html +1 -1
- package/.next/server/app/office-preview.rsc +2 -2
- package/.next/server/app/office-preview.segments/_full.segment.rsc +2 -2
- package/.next/server/app/office-preview.segments/_head.segment.rsc +1 -1
- package/.next/server/app/office-preview.segments/_index.segment.rsc +2 -2
- package/.next/server/app/office-preview.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/office-preview.segments/office-preview/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/office-preview.segments/office-preview.segment.rsc +1 -1
- package/.next/server/app/office.html +1 -1
- package/.next/server/app/office.rsc +4 -4
- package/.next/server/app/office.segments/_full.segment.rsc +4 -4
- package/.next/server/app/office.segments/_head.segment.rsc +1 -1
- package/.next/server/app/office.segments/_index.segment.rsc +2 -2
- package/.next/server/app/office.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/office.segments/office/__PAGE__.segment.rsc +3 -3
- package/.next/server/app/office.segments/office.segment.rsc +1 -1
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app/recover/page_client-reference-manifest.js +1 -1
- package/.next/server/app/recover.html +1 -1
- package/.next/server/app/recover.rsc +2 -2
- package/.next/server/app/recover.segments/_full.segment.rsc +2 -2
- package/.next/server/app/recover.segments/_head.segment.rsc +1 -1
- package/.next/server/app/recover.segments/_index.segment.rsc +2 -2
- package/.next/server/app/recover.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/recover.segments/recover/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/recover.segments/recover.segment.rsc +1 -1
- package/.next/server/app-paths-manifest.json +9 -9
- package/.next/server/chunks/1008.js +1 -1
- package/.next/server/chunks/5489.js +2 -2
- package/.next/server/chunks/6429.js +1 -1
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/chunks/{9575-6f450839544bc6b3.js → 9575-9196474bb9e5c752.js} +2 -2
- package/.next/static/chunks/app/{layout-d8c1b10303bcd958.js → layout-713017c65de14601.js} +1 -1
- package/.next/trace +108 -108
- package/.next/trace-build +1 -1
- package/README.md +4 -1
- package/Tools/CUELO_Setup/files/native-runtime-patch.js +3 -3
- package/Tools/OMP_Global_Config/agent/RULES.md +4 -0
- package/Tools/OMP_Global_Config/agent/agents/maker.md +12 -6
- package/Tools/OMP_Global_Config/agent/extensions/character-voice.ts +3 -3
- package/Tools/OMP_Global_Config/agent/extensions/command-guard/index.ts +16 -1
- package/Tools/OMP_Global_Config/agent/extensions/command-guard/powershell-syntax.ts +5 -4
- package/Tools/OMP_Global_Config/agent/extensions/draft/markdown.ts +226 -0
- package/Tools/OMP_Global_Config/agent/extensions/draft/ooxml.ts +222 -0
- package/Tools/OMP_Global_Config/agent/extensions/draft/pdf.ts +63 -0
- package/Tools/OMP_Global_Config/agent/extensions/draft/zip.ts +73 -0
- package/Tools/OMP_Global_Config/agent/extensions/draft.ts +211 -0
- package/Tools/OMP_Global_Config/agent/extensions/jev-runtime.ts +1 -1
- package/Tools/OMP_Global_Config/agent/extensions/lib/maker-routing.ts +16 -47
- package/Tools/OMP_Global_Config/agent/extensions/mcp-selection.ts +32 -8
- package/Tools/OMP_Global_Config/agent/extensions/skim.ts +75 -43
- package/Tools/OMP_Global_Config/agent/prompt-copies/RULES.en.md +2 -1
- package/Tools/OMP_Global_Config/agent/rules/harness-policy.json +5 -6
- package/Tools/OMP_Global_Config/agent/rules/omp-harness.md +1 -1
- package/Tools/OMP_Global_Config/agent/rules/subagent.md +18 -14
- package/Tools/OMP_Global_Config/agent/sop/_common.md +4 -4
- package/Tools/OMP_Global_Config/agent/sop/_writer.md +6 -0
- package/Tools/OMP_Global_Config/agent/sop/maker.md +1 -1
- package/Tools/OMP_Global_Config/agent/tools/git-finalizer/index.ts +46 -3
- package/Tools/OMP_Global_Config/patches/apply-core-patch.mjs +182 -0
- package/bin/cuelo.js +5 -0
- package/package.json +7 -7
- /package/.next/static/{MYIe6QFbh4yP3_wc_Fetr → S8tJkE71e2D0DgH4X1s0S}/_buildManifest.js +0 -0
- /package/.next/static/{MYIe6QFbh4yP3_wc_Fetr → S8tJkE71e2D0DgH4X1s0S}/_ssgManifest.js +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
exports.id=5489,exports.ids=[5489],exports.modules={13689:(a,b,c)=>{Promise.resolve().then(c.bind(c,65857)),Promise.resolve().then(c.bind(c,54719))},29947:(a,b,c)=>{"use strict";c.d(b,{C1:()=>f,IN:()=>e,getPresetFromTools:()=>h,xG:()=>i});let d=[],e=["read","bash","edit","write"],f=["read","bash","edit","write","grep","glob"],g=Object.fromEntries(f.map(a=>[a,!0]));function h(a){let b=a.filter(a=>a.active);if(0===b.length)return"none";let c=b.map(a=>a.name).filter(a=>!0===g[a]).sort().join(",");return c===[...e].sort().join(",")?"default":c===[...f].sort().join(",")?"full":"default"}function i(a){return"none"===a?[...d]:"full"===a?[...f]:[...e]}},35790:(a,b,c)=>{"use strict";c.d(b,{AppShell:()=>d});let d=(0,c(77943).registerClientReference)(function(){throw Error("Attempted to call AppShell() from the server but AppShell is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"D:\\a\\CUELO\\CUELO\\components\\AppShell.tsx","AppShell")},35836:a=>{a.exports={root:"SearchableSelect_root__FMhaH",trigger:"SearchableSelect_trigger__eqMdt",value:"SearchableSelect_value__eJ2RU",placeholder:"SearchableSelect_placeholder__Hkg33",chevron:"SearchableSelect_chevron__DSTnM",popover:"SearchableSelect_popover__5VxMd",searchWrap:"SearchableSelect_searchWrap__IoKKk",searchIcon:"SearchableSelect_searchIcon__A6f0C",search:"SearchableSelect_search__W_1al",options:"SearchableSelect_options__tjHyi",option:"SearchableSelect_option__LRRH9",optionCopy:"SearchableSelect_optionCopy__W87H8",optionLabel:"SearchableSelect_optionLabel__G7jIg",optionDescription:"SearchableSelect_optionDescription__cE_cC",check:"SearchableSelect_check__1Likw",empty:"SearchableSelect_empty__vZzXQ"}},43065:(a,b,c)=>{Promise.resolve().then(c.bind(c,35790)),Promise.resolve().then(c.bind(c,73884))},51768:a=>{a.exports={dialog:"CloudProjectPicker_dialog__Dx2Dt",form:"CloudProjectPicker_form__MpEsn",header:"CloudProjectPicker_header__UcYbB",sources:"CloudProjectPicker_sources__6cl_0",activeSource:"CloudProjectPicker_activeSource__NptfQ",body:"CloudProjectPicker_body__vKMBC",account:"CloudProjectPicker_account__gb9Qo",repositories:"CloudProjectPicker_repositories__WSBt6",secondary:"CloudProjectPicker_secondary__hlaFU",primary:"CloudProjectPicker_primary__voWx5",loginLink:"CloudProjectPicker_loginLink__Gu5XC",login:"CloudProjectPicker_login__c0qSl",codeRow:"CloudProjectPicker_codeRow__jo8vy",repositoryInput:"CloudProjectPicker_repositoryInput__HWhvu",list:"CloudProjectPicker_list__0BSYU",repo:"CloudProjectPicker_repo__L4VaW",repoHeading:"CloudProjectPicker_repoHeading__3Pnq1",repoDescription:"CloudProjectPicker_repoDescription__YzPtB",error:"CloudProjectPicker_error__dAVsm",progress:"CloudProjectPicker_progress__OwvG9",footer:"CloudProjectPicker_footer__mmrGI"}},57582:()=>{},65857:(a,b,c)=>{"use strict";c.d(b,{AppShell:()=>kK});var d=c(48249),e=c(67484),f=c.n(e),g=c(19099),h=c(25955),i=c(2586),j=c(86592),k=c(58474);let l=["chat","process","subagents","files","resource","sidechat","efficiency"],m=["characters","usage","models"];Object.freeze({transcript:550,composer:384,navigator:240,deck:384});let n=Object.freeze({navigator:791,deck:1176}),o=Object.freeze({activeView:"chat",transientLayer:null}),p=Object.fromEntries(l.map(a=>[a,!0]));function q(a){return"string"==typeof a&&!0===p[a]?a:o.activeView}function r(a,b){switch(b.type){case"select-view":return{activeView:q(b.view),transientLayer:null};case"open-layer":return{activeView:q(a.activeView),transientLayer:b.layer};case"toggle-layer":return{activeView:q(a.activeView),transientLayer:a.transientLayer===b.layer?null:b.layer};case"close-layer":return{activeView:q(a.activeView),transientLayer:null}}}let s=["projects","priority"],t=["omp-relay-session-","omp-cwd-","ompscope_"];function u(a){let b=a.trim().replace(/\\/g,"/");return"/"===(b=b.startsWith("//")?`//${b.slice(2).replace(/\/{2,}/g,"/")}`:b.replace(/\/{2,}/g,"/"))||/^[a-zA-Z]:\/$/.test(b)||(b=b.replace(/\/+$/,"")),/^[a-zA-Z]:\//.test(b)||b.startsWith("//")?b.toLowerCase():b}let v=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function w(a){let b=a.match(v);if(!b)return null;let[,c,,,d]=b;return d?`/skill:${c} ${d}`:`/skill:${c}`}var x=c(54719);let y=`(max-width: ${n.navigator-1}px)`;function z(a){return{subscribe:a=>()=>{},getSnapshot:()=>!1}}let A=z("(max-width: 640px)"),B=z(y);function C(){return!1}function D(){return(0,e.useSyncExternalStore)(A.subscribe,A.getSnapshot,C)}var E=c(74429);async function F(a){let b=a?`?path=${encodeURIComponent(a)}`:"",c=await fetch(`/api/cwd/browse${b}`),d=await c.json();if(!c.ok||d.error)throw Error(d.error??`HTTP ${c.status}`);return d}function G(){return(0,d.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function H(){return(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,d.jsx)("path",{d:"M2 9h12"}),(0,d.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function I({onCancel:a,onSelect:b,busy:c=!1,error:f}){let{t:g}=(0,x.s)(),[h,i]=(0,e.useState)(null),[j,k]=(0,e.useState)(""),[l,m]=(0,e.useState)(null),[n,o]=(0,e.useState)(""),[p,q]=(0,e.useState)([]),[r,s]=(0,e.useState)(null),[t,u]=(0,e.useState)(null),[v,w]=(0,e.useState)(!0),y=(0,e.useCallback)(async a=>{w(!0),u(null);try{let b=await F(a),c=b.path??a??"/";k(c),m(b.parentPath??null),o(c),q(b.directories??[]),s(b.drives??null)}catch(a){u(a instanceof Error?a.message:String(a))}finally{w(!1)}},[]),z=n.trim()!==j,A=!!j&&!z&&!c,B=!!l||/^[a-zA-Z]:[\\/]?$/.test(j);return h?(0,E.createPortal)((0,d.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":g("directoryPicker.selectDirectory"),onClick:b=>{b.target!==b.currentTarget||c||a()},onKeyDown:b=>{"Escape"!==b.key||c||a()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,d.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,d.jsx)("div",{style:{minWidth:0,flex:1},children:(0,d.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:g("directoryPicker.selectDirectory")})}),(0,d.jsx)("button",{type:"button",onClick:a,disabled:c,title:g("i18n.close"),"aria-label":g("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:c?"default":"pointer",opacity:c?.5:1},children:"\xd7"})]}),(0,d.jsxs)("form",{onSubmit:a=>{a.preventDefault();let b=n.trim();b&&y(b)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,d.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void y(l??void 0),disabled:v||!B,title:g("directoryPicker.goToParent"),"aria-label":g("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:B?"pointer":"default",opacity:B?1:.45},children:(0,d.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,d.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:g("directoryPicker.directoryPath")}),(0,d.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:n,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:a=>{o(a.target.value),u(null)},style:{minWidth:0,flex:1,height:36,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12}}),(0,d.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:v||!n.trim(),title:g("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:v||!n.trim()?"default":"pointer",opacity:v||!n.trim()?.6:1},children:g("directoryPicker.go")})]}),(0,d.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[v?(0,d.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:g("directoryPicker.loadingDirectories")}):null!==r?(0,d.jsx)(d.Fragment,{children:r.length>0?r.map(a=>(0,d.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void y(a.path),title:a.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,d.jsx)(H,{}),(0,d.jsx)("span",{children:a.name})]},a.path)):(0,d.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:g("directoryPicker.noDrives")})}):p.length>0?p.map(a=>(0,d.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void y(a.path),title:a.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,d.jsx)(G,{}),(0,d.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.name})]},a.path)):(0,d.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:g("directoryPicker.noSubdirectories")}),(t||f)&&(0,d.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:t??f})]}),(0,d.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,d.jsx)("button",{className:"directory-picker-action",type:"button",onClick:a,disabled:c,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text-muted)",cursor:c?"default":"pointer",fontSize:13},children:g("i18n.cancel")}),(0,d.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>b(j),disabled:!A,title:g(z?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",border:0,borderRadius:6,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontSize:13,fontWeight:600,opacity:A?1:.6,cursor:A?"pointer":"default"},children:g(c?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),h):null}var J=c(51768),K=c.n(J);async function L(a,b){let c=await fetch(a,b?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)}:void 0),d=await c.json();if(!c.ok)throw Error(d.error||`HTTP ${c.status}`);return d}function M({onCancel:a,onSelect:b,busy:c=!1,error:f}){let{t:g}=(0,x.s)(),h=(0,e.useRef)(null),[i,j]=(0,e.useState)(!1),[k,l]=(0,e.useState)(!1),[m,n]=(0,e.useState)(null),[o,p]=(0,e.useState)([]),[q,r]=(0,e.useState)(""),[s,t]=(0,e.useState)(""),[u,v]=(0,e.useState)(!0),[w,y]=(0,e.useState)(!1),[z,A]=(0,e.useState)(!1),[B,C]=(0,e.useState)(null),[D,F]=(0,e.useState)(!1),[G,H]=(0,e.useState)(50),J=m?.device?.state==="pending",N=c||z,O=(0,e.useCallback)(async()=>{v(!0),C(null);try{let a=await L("/api/github/projects");n(a),a.connected&&p((await L("/api/github/projects?view=repositories")).repositories)}catch(a){C(a instanceof Error?a.message:String(a))}finally{v(!1)}},[]);async function P(){y(!0),C(null);try{let{device:a}=await L("/api/github/projects",{action:"login"});n({connected:!1,login:null,device:a})}catch(a){C(a instanceof Error?a.message:String(a))}finally{y(!1)}}async function Q(a){if(a.preventDefault(),s.trim()&&!N){A(!0),C(null);try{let{cwd:a}=await L("/api/github/projects",{action:"open",repository:s});b(a)}catch(a){C(a instanceof Error?a.message:String(a))}finally{A(!1)}}}if(!i)return null;if(k)return(0,d.jsx)(I,{onCancel:()=>l(!1),onSelect:b,busy:c,error:f});let R=o.filter(a=>`${a.fullName} ${a.description??""}`.toLowerCase().includes(q.toLowerCase())),S=B??f??m?.device?.error;return(0,E.createPortal)((0,d.jsx)("dialog",{ref:h,className:K().dialog,"aria-labelledby":"cloud-project-title",onCancel:b=>{b.preventDefault(),N||a()},children:(0,d.jsxs)("form",{onSubmit:Q,className:K().form,children:[(0,d.jsxs)("header",{className:K().header,children:[(0,d.jsx)("h2",{id:"cloud-project-title",children:g("cloudProjects.title")}),(0,d.jsx)("p",{children:g("cloudProjects.description")})]}),(0,d.jsxs)("div",{className:K().sources,children:[(0,d.jsx)("span",{className:K().activeSource,children:g("cloudProjects.github")}),(0,d.jsx)("button",{type:"button",onClick:()=>l(!0),disabled:N,children:g("cloudProjects.serverFolder")})]}),(0,d.jsxs)("div",{className:K().body,children:[(0,d.jsxs)("section",{className:K().account,"aria-label":g("cloudProjects.account"),children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("strong",{children:m?.connected?m.login:g("cloudProjects.connectTitle")}),(0,d.jsx)("p",{children:m?.connected?g("cloudProjects.connected"):g("cloudProjects.connectHelp")})]}),m?.connected?(0,d.jsx)("button",{type:"button",className:K().secondary,onClick:()=>void O(),disabled:u||N,children:g("cloudProjects.refresh")}):(0,d.jsx)("button",{type:"button",className:K().secondary,onClick:()=>void P(),disabled:u||w||J||N,children:w||J?g("cloudProjects.waiting"):g("cloudProjects.connect")})]}),J&&(0,d.jsxs)("div",{className:K().login,role:"status",children:[(0,d.jsx)("p",{children:g("cloudProjects.deviceHelp")}),m.device?.code?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{className:K().codeRow,children:[(0,d.jsx)("code",{children:m.device.code}),(0,d.jsx)("button",{type:"button",className:K().secondary,onClick:()=>{navigator.clipboard.writeText(m.device.code).then(()=>F(!0)).catch(()=>C(g("cloudProjects.copyFailure")))},children:D?g("cloudProjects.copied"):g("cloudProjects.copyCode")})]}),(0,d.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:K().loginLink,children:g("cloudProjects.openLogin")}),(0,d.jsx)("small",{children:g("cloudProjects.permissionHelp")})]}):(0,d.jsx)("p",{children:g("cloudProjects.preparingCode")})]}),m?.connected&&(0,d.jsxs)("section",{className:K().repositories,"aria-label":g("cloudProjects.repositories"),children:[(0,d.jsx)("label",{htmlFor:"cloud-repo-search",children:g("cloudProjects.search")}),(0,d.jsx)("input",{id:"cloud-repo-search",value:q,onChange:a=>{r(a.target.value),H(50)},placeholder:g("cloudProjects.searchPlaceholder"),type:"search",disabled:N}),u?(0,d.jsx)("p",{role:"status",children:g("cloudProjects.loading")}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("ul",{className:K().list,children:R.slice(0,G).map(a=>(0,d.jsx)("li",{children:(0,d.jsxs)("button",{type:"button",className:K().repo,"aria-pressed":s===a.fullName,disabled:N,onClick:()=>t(a.fullName),children:[(0,d.jsxs)("span",{className:K().repoHeading,children:[(0,d.jsx)("strong",{children:a.fullName}),(0,d.jsx)("small",{children:a.private?g("cloudProjects.private"):g("cloudProjects.public")})]}),a.description&&(0,d.jsx)("span",{className:K().repoDescription,children:a.description})]})},a.fullName))}),!R.length&&(0,d.jsx)("p",{children:g("cloudProjects.empty")}),R.length>G&&(0,d.jsx)("button",{type:"button",className:K().secondary,onClick:()=>H(a=>a+50),children:g("cloudProjects.more")})]})]}),(0,d.jsxs)("div",{className:K().repositoryInput,children:[(0,d.jsx)("label",{htmlFor:"cloud-repository",children:g("cloudProjects.urlLabel")}),(0,d.jsx)("input",{id:"cloud-repository",value:s,onChange:a=>t(a.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:N,"aria-describedby":"cloud-repo-help"}),(0,d.jsx)("small",{id:"cloud-repo-help",children:g("cloudProjects.publicHelp")})]}),S&&(0,d.jsxs)("div",{className:K().error,role:"alert",children:[(0,d.jsx)("strong",{children:g("cloudProjects.error")}),(0,d.jsx)("p",{children:S}),(0,d.jsx)("button",{type:"button",className:K().secondary,onClick:()=>void O(),disabled:N,children:g("cloudProjects.refresh")})]}),z&&(0,d.jsx)("p",{role:"status",className:K().progress,children:g("cloudProjects.openingHelp")})]}),(0,d.jsxs)("footer",{className:K().footer,children:[(0,d.jsx)("button",{type:"button",className:K().secondary,onClick:a,disabled:N,children:g("i18n.cancel")}),(0,d.jsx)("button",{type:"submit",className:K().primary,disabled:N||!s.trim(),children:N?g("cloudProjects.opening"):g("cloudProjects.open")})]})]})}),document.body)}function N({label:a="CUELO",markSize:b=22,gap:c=10,style:e,labelStyle:f}){return(0,d.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:c,minWidth:0,color:"var(--text)",...e},children:[(0,d.jsxs)("svg",{viewBox:"0 0 100 100",width:b,height:b,"aria-hidden":"true",style:{flexShrink:0},children:[(0,d.jsx)("path",{d:"M77.9 30.5 A34 34 0 0 0 16 50 A26 26 0 0 0 68 50",fill:"none",stroke:"currentColor",strokeWidth:"10",strokeLinecap:"round"}),(0,d.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,d.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:'"Plus Jakarta Sans", Geist, ui-sans-serif, system-ui, sans-serif',fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...f},children:a})]})}var O=c(13928);function P(a,b){return{minHeight:b?36:30,padding:"3px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:a?"var(--text-dim)":"var(--text-muted)",cursor:a?"default":"pointer",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.3,textAlign:"left",whiteSpace:"normal",overflowWrap:"anywhere"}}function Q(a,b){return b&&a.startsWith(b)?"~"+a.slice(b.length):a}function R({text:a,style:b}){return(0,d.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...b},children:(0,d.jsx)("span",{style:{unicodeBidi:"plaintext"},children:a})})}function S({open:a,children:b,style:c}){let[f,g]=(0,e.useState)(a),[h,i]=(0,e.useState)(a);return f?(0,d.jsx)("div",{style:{...c,opacity:+!!h,transform:h?"translateY(0) scale(1)":"translateY(-8px) scale(0.96)",transformOrigin:"top center",transition:"opacity 140ms ease, transform 140ms ease",pointerEvents:a?"auto":"none"},children:b}):null}function T(){let[a,b]=(0,e.useState)(!1),[c,f]=(0,e.useState)(!1),g=(0,e.useRef)(null),h=function(a){let[b,c]=(0,e.useState)(a);return(0,e.useRef)(null),(0,e.useRef)(0),b}(a?"0.10.0/18.8.0":"CUELO"),i=(0,e.useCallback)(a=>{b(a),f(!0),setTimeout(()=>f(!1),(a?6:8)*4*(1e3/60)+100)},[]),j=(0,e.useCallback)(()=>{g.current&&clearTimeout(g.current);let b=!a;i(b),b&&(g.current=setTimeout(()=>i(!1),3e3))},[a,i]);return(0,d.jsx)("button",{className:"navigator-brand",onClick:j,style:{display:"flex",alignItems:"center",background:"none",border:"none",padding:0,cursor:"default",color:a?"var(--accent)":"var(--text)",minWidth:"6ch"},children:(0,d.jsx)(N,{label:h,labelStyle:a?{fontFamily:"var(--font-mono)",letterSpacing:"-0.01em"}:void 0})})}async function U(a){let b=await fetch("/api/projects",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:a})});if(!b.ok)throw Error(`HTTP ${b.status}`)}function V({selectedSessionId:a,optimisticSession:b,onSelectSession:c,onNewSession:f,initialSessionId:g,skipInitialProjectSelection:h,onInitialRestoreDone:i,refreshKey:j,onSessionDeleted:k,selectedCwd:l,onCwdChange:m,onBackgroundTaskDone:n,loungePanel:o,loungeActive:p=!1,onLoungeActiveChange:q}){let r,{lt:v}=(0,O.H)(),{t:w,locale:y}=(0,x.s)(),z=D(),[A,B]=(0,e.useState)([]),C=b&&!A.some(a=>a.id===b.id)?[b,...A]:A,[E,F]=(0,e.useState)(!0),[G,H]=(0,e.useState)(null),[J,K]=(0,e.useState)(null),[L,N]=(0,e.useState)(""),[X,_]=(0,e.useState)(!1),[aa,ac]=(0,e.useState)(""),[ad,ae]=(0,e.useState)("projects"),[af,ag]=(0,e.useState)(()=>new Set),[ah,ai]=(0,e.useState)(()=>new Set),[aj,ak]=(0,e.useState)(null),[al,am]=(0,e.useState)(null),[an,ao]=(0,e.useState)({version:1,projects:[]}),[ap,aq]=(0,e.useState)(!1),[ar,as]=(0,e.useState)(!1),[at,au]=(0,e.useState)(!1),[av,aw]=(0,e.useState)(null),[ax,ay]=(0,e.useState)(""),[az,aA]=(0,e.useState)(!1),[aB,aC]=(0,e.useState)(null),[aD,aE]=(0,e.useState)(""),[aF,aG]=(0,e.useState)(!1),[aH,aI]=(0,e.useState)(null),[aJ,aK]=(0,e.useState)(!1),[aL,aM]=(0,e.useState)(null),[aN,aO]=(0,e.useState)(!1),[aP,aQ]=(0,e.useState)(!1),[aR,aS]=(0,e.useState)(""),[aT,aU]=(0,e.useState)(null),[aV,aW]=(0,e.useState)(!1),[aX,aY]=(0,e.useState)(null),aZ=(0,e.useRef)(null),a$=(0,e.useRef)(null),a_=(0,e.useRef)(null),a0=(0,e.useRef)(!1),a1=(0,e.useRef)(!1),[a2,a3]=(0,e.useState)(!1),[a4,a5]=(0,e.useState)(()=>new Set),[a6,a7]=(0,e.useState)(()=>new Set),[a8,a9]=(0,e.useState)(()=>new Set);(0,e.useRef)(new Set);let ba=(0,e.useRef)(!1),bb=(0,e.useRef)(null),bc=(0,e.useCallback)(async()=>{try{let a=await fetch("/api/projects",{cache:"no-store",signal:AbortSignal.timeout(5e3)});if(!a.ok)throw Error(`HTTP ${a.status}`);ao(await a.json())}catch{ao({version:1,projects:[]})}finally{aq(!0)}},[]),bd=(0,e.useCallback)(async a=>{if(a1.current)throw Error("Project update in progress");a1.current=!0,aA(!0);try{await U(a),await bc()}finally{a1.current=!1,aA(!1)}},[bc]),be=(0,e.useCallback)(async(a=!1,b=!1)=>{try{a&&F(!0);let c=await fetch(b?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!c.ok)throw Error(`HTTP ${c.status}`);let d=await c.json();B(d.sessions),ba.current||a5(new Set(d.runningSessionIds??[])),H(null),a||(a3(!0),bb.current&&clearTimeout(bb.current),bb.current=setTimeout(()=>a3(!1),2e3))}catch(a){H(String(a))}finally{a&&F(!1)}},[]),bf=(0,e.useCallback)(a=>{a7(b=>{if(!b.has(a))return b;let c=new Set(b);return c.delete(a),c}),a9(b=>{if(!b.has(a))return b;let c=new Set(b);return c.delete(a),c}),k?.(a),be()},[be,k]),[bg,bh]=(0,e.useState)(null),[bi,bj]=(0,e.useState)(!1),[bk,bl]=(0,e.useState)(null),bm=(0,e.useCallback)(()=>{bi||(bh(null),bl(null))},[bi]),bn=(0,e.useCallback)(async a=>{bj(!0),bl(null);let b=[],c=[],d=[];for(let e of a)if(!e.transient)try{let a=await fetch(`/api/sessions/${encodeURIComponent(e.id)}?skipRunning=1`,{method:"DELETE"});if(409===a.status){c.push(e.id);continue}if(!a.ok)throw Error(`HTTP ${a.status}`);b.push(e.id)}catch{d.push(e.name?.trim()||e.id.slice(0,8))}if(c.length>0&&(ba.current=!0,a5(a=>{if(c.every(b=>a.has(b)))return a;let b=new Set(a);for(let a of c)b.add(a);return b})),b.length>0){let a=new Set(b),c=c=>b.some(a=>c.has(a))?new Set([...c].filter(b=>!a.has(b))):c;for(let a of(a7(c),a9(c),b))k?.(a)}(await be(),bj(!1),d.length>0)?bl(w("sidebar.clearSessionsFailed",{count:d.length,names:d.join(", ")})):c.length>0||bh(null)},[be,k,w]),[bo,bp]=(0,e.useState)(0),bq=(0,e.useCallback)(()=>{bp(a=>a+1),be()},[be]);(0,e.useRef)(!1);let br=(0,e.useCallback)(a=>{ae(a);try{window.localStorage.setItem("omp-web:navigator-mode",a),window.localStorage.setItem("omp-prio-on","priority"===a?"1":"0")}catch{}},[]),bs=(0,e.useCallback)(a=>{a9(b=>{let c=new Set(b);return c.has(a)?c.delete(a):c.add(a),c})},[]);(0,e.useRef)(!1);let bt=(0,e.useCallback)(a=>{if(!a)return null;if(aL&&aL.forCwd===a||aL?.worktrees.some(b=>b.path===a))return aL.projectRoot;let b=C.find(b=>b.cwd===a);return b?.projectRoot??a},[aL,C]);(0,e.useRef)(null),(0,e.useRef)(null);let[bu,bv]=(0,e.useState)(0),bw=(0,e.useCallback)(async a=>{let b=a.trim();if(b&&!aJ){aK(!0),aI(null);try{let a=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:b})}),c=await a.json().catch(()=>({}));if(!a.ok||c.error)return void aI(c.error??w("workspace.unable"));let d=c.cwd??b,e=u(d),f=an.projects.find(a=>a.key===e);if(f?.hidden===!0)try{await bd([{key:e,path:d,hidden:!1}])}catch{}K(d),aG(!1)}catch{aI(w("workspace.unable"))}finally{aK(!1)}}},[bd,aJ,an.projects,w]),bx=(0,e.useCallback)(()=>{aG(!0),aI(null)},[]),by=(0,e.useCallback)(async()=>{let a=aR.trim();if(a&&!aV&&aL){aW(!0),aU(null);try{let b=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:aL.projectRoot,branch:a})}),c=await b.json().catch(()=>({}));if(!b.ok||c.error||!c.path)return void aU(c.error??`HTTP ${b.status}`);aQ(!1),aS(""),aO(!1),aM(b=>b?{...b,forCwd:c.path,worktrees:[...b.worktrees,{path:c.path,branch:a,isMain:!1}]}:b),K(c.path),bv(a=>a+1)}catch(a){aU(a instanceof Error?a.message:String(a))}finally{aW(!1)}}},[aR,aV,aL]),bz=(0,e.useCallback)(async(a,b)=>{if(aL&&!aV){aW(!0),aU(null);try{let c=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:aL.projectRoot,path:a,force:b})}),d=await c.json().catch(()=>({}));if(!c.ok){if(d.dirty&&!b)return void aY(a);aU(d.error??`HTTP ${c.status}`);return}aY(null),J===a&&K(aL.projectRoot),bv(a=>a+1)}catch(a){aU(a instanceof Error?a.message:String(a))}finally{aW(!1)}}},[aL,aV,J]),bA=(0,e.useCallback)(a=>{a.cwd&&K(a.cwd),c(a)},[c]),bB=(0,e.useCallback)((a=J)=>{if(!a)return;let b="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;K(a),f?.(b,a)},[J,f]),[bC,bD]=(0,e.useState)(!1),[bE,bF]=(0,e.useState)(null),bG=(0,e.useCallback)(async()=>{bD(!0),bF(null);try{let a=await fetch("/api/default-cwd",{method:"POST"}),b=await a.json().catch(()=>({}));if(!a.ok||!b.cwd)throw Error(b.error??`HTTP ${a.status}`);bB(b.cwd)}catch(a){bF(w("sidebar.newScratchSessionFailed",{error:a instanceof Error?a.message:String(a)}))}finally{bD(!1)}},[bB,w]),bH=(0,e.useCallback)(a=>{ai(b=>{let c=new Set(b);return c.has(a)?c.delete(a):c.add(a),c})},[]),bI=bt(J),bJ=null===bI?null:u(bI),bK=(0,e.useMemo)(()=>new Map(an.projects.map(a=>[a.key,a])),[an.projects]),bL=function(a){let b=new Map;for(let c of a){let a=c.projectRoot??c.cwd;if(!a)continue;let d=u(a),e=b.get(d);(!e||c.modified>e.modified)&&b.set(d,{project:a,modified:c.modified})}return[...b.values()].sort((a,b)=>b.modified.localeCompare(a.modified)).map(a=>a.project)}(C);if(null!==bI){let a=u(bI);bL.some(b=>u(b)===a)||bL.unshift(bI)}let bM=function(a,b){let c=new Map;for(let a of b)"number"==typeof a.order&&Number.isFinite(a.order)&&c.set(u(a.key),a.order);let d=[...a],e=new Set(a.map(u));for(let a of b){let b=u(a.key);!b||e.has(b)||(d.push(a.path??a.key),e.add(b))}return d.map((a,b)=>({project:a,defaultIndex:b,order:c.get(u(a))})).sort((a,b)=>{let c=void 0!==a.order,d=void 0!==b.order;return c!==d?c?-1:1:c&&d&&a.order!==b.order?a.order-b.order:a.defaultIndex-b.defaultIndex}).map(({project:a})=>a)}(bL,an.projects),bN=bM.filter(a=>ar||!bK.get(u(a))?.hidden),bO=bM.some(a=>bK.get(u(a))?.hidden),bP=()=>{am(null),aO(!1),aQ(!1),aS(""),aU(null),aY(null),aE("")},bQ=async(a,b)=>{bP();try{await bd([{key:u(a),path:a,hidden:b}]),b&&bJ&&bJ===u(a)&&K(null),b||bM.some(b=>u(b)!==u(a)&&bK.get(u(b))?.hidden)||as(!1)}catch{}},bR=async a=>{if(a0.current){a0.current=!1,aw(null);return}let b=ax.trim();if(b===(bK.get(u(a))?.alias??""))return void aw(null);aC(null);try{await bd([{key:u(a),path:a,alias:b||null}]),aw(null)}catch{aC(w("sidebar.projectUpdateFailed"))}},bS=async(a,b)=>{if(aa)return;let c=bN.indexOf(a),d=c+b;if(c<0||d<0||d>=bN.length)return;let e=new Set(bN),f=bM.map((a,b)=>e.has(a)?b:-1).filter(a=>a>=0),g=[...bM],h=f[c],i=f[d];[g[h],g[i]]=[g[i],g[h]],bP();try{await bd(g.map((a,b)=>({key:u(a),path:a,order:b})))}catch{}},bT=new Map;for(let a of C){let b=a.projectRoot??a.cwd;if(!b)continue;let c=u(b),d=bT.get(c);d?d.push(a):bT.set(c,[a])}let bU=(0,e.useMemo)(()=>{let a=new Map;for(let b of C){let c=b.projectRoot??b.cwd;if(!c)continue;let d=u(c),e=a.get(d);e||(e={running:0,unread:0},a.set(d,e)),a4.has(b.id)&&e.running++,a6.has(b.id)&&e.unread++}return a},[C,a4,a6]),bV=aa.trim().toLowerCase(),bW=aa.length>0,bX=bN.flatMap(a=>{let b=a.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||a,c=u(a),d=bK.get(c),e=d?.alias??b,f=(bT.get(c)??[]).slice().sort((a,b)=>{let c=Number(a8.has(b.id))-Number(a8.has(a.id));return 0!==c?c:b.modified.localeCompare(a.modified)});if(!bV)return[{project:a,key:c,name:e,sessions:f,hidden:d?.hidden===!0}];let g=e.toLowerCase().includes(bV)||b.toLowerCase().includes(bV),h=f.filter(a=>(a.name||a.firstMessage.slice(0,50)||a.id.slice(0,12)).toLowerCase().includes(bV));return g||0!==h.length?[{project:a,key:c,name:e,sessions:g?f:h,hidden:d?.hidden===!0}]:[]}),bY=[],bZ=[];for(let a of bX){let b=a.key===bJ||(bU.get(a.key)?.running??0)>0;(function(a){let b=a.trim().replace(/\\/g,"/").toLowerCase();return!!(/^[a-z]:\/?$/.test(b)||"/"===b||/(^|\/)appdata\/local\/temp(\/|$)/.test(b)||/^\/(?:var\/|private\/)?tmp(?:\/|$)/.test(b)||/^[a-z]:\/(?:tmp|temp)(?:\/|$)/.test(b)||/(^|\/)(?:users|home)\/[^/]+\/\.omp(\/|$)/.test(b))||b.split("/").some(a=>t.some(b=>a.startsWith(b)))})(a.project)&&!b?bZ.push(a):bY.push(a)}let b$={running:0,unread:0};for(let a of bZ){let b=bU.get(a.key);b&&(b$.running+=b.running,b$.unread+=b.unread)}let b_=bW||at,b0=[...bY.map(a=>({kind:"project",group:a})),...bZ.length>0?[{kind:"temporary"}]:[],...b_?bZ.map(a=>({kind:"project",group:a})):[]],b1=function(a){let b=new Map;for(let c of a){let a=c.toLowerCase();b.set(a,(b.get(a)??0)+1)}return new Set([...b].filter(([,a])=>a>1).map(([a])=>a))}(b0.flatMap(a=>"project"===a.kind?[a.group.name]:[])),b2=(0,e.useMemo)(()=>(function(a,b,c,d,e="Priority",f=new Set,g="Pinned"){let h=a.filter(a=>!a.transient).slice().sort((a,b)=>{let c=Date.parse(a.modified),d=Date.parse(b.modified);return(Number.isFinite(d)?d:0)-(Number.isFinite(c)?c:0)}),i=h.filter(a=>f.has(a.id)),j=[],k=new Map,l=0;for(let a of h){if(f.has(a.id))continue;if(b.has(a.id)){j.push(a);continue}let c=new Date(a.modified);if(l>=10)continue;l+=1;let d=[c.getFullYear(),String(c.getMonth()+1).padStart(2,"0"),String(c.getDate()).padStart(2,"0")].join("-"),e=k.get(d);e?e.push(a):k.set(d,[a])}let m=[];for(let a of(i.length>0&&m.push({key:"pinned",label:g,running:!1,sessions:i}),j.length>0&&m.push({key:"priority",label:e,running:!0,sessions:j}),[...k.keys()].sort().reverse()))m.push({key:a,label:function(a,b,c){let[d,e,f]=a.split("-").map(Number),g=new Date(d,e-1,f),h=Math.round((Date.UTC(b.getFullYear(),b.getMonth(),b.getDate())-Date.UTC(g.getFullYear(),g.getMonth(),g.getDate()))/864e5);return 0===h||1===h?new Intl.RelativeTimeFormat(c,{numeric:"auto"}).format(-h,"day"):h>=0&&h<7?new Intl.DateTimeFormat(c,{weekday:"long"}).format(g):new Intl.DateTimeFormat(c,{month:"short",day:"numeric"}).format(g)}(a,c,d),running:!1,sessions:k.get(a)??[]});return m})(C,a4,new Date,y,w("navigator.priority"),a8,w("sidebar.pinned")),[y,a8,a4,C,w]),b3=!!(aL?.isGit&&aL.isTopLevel&&J&&bI===aL.projectRoot),b4=aL?.worktrees.find(a=>a.path===J)??aL?.worktrees.find(a=>a.isMain),b5=(aL?.worktrees.length??0)>=8,b6=b5&&aD.trim()?(aL?.worktrees??[]).filter(a=>(a.branch??Q(a.path,L)).toLowerCase().includes(aD.trim().toLowerCase())):aL?.worktrees??[],b7=(()=>{if(!bg)return[];let a="project"===bg.kind?bT.get(u(bg.project))??[]:b2.flatMap(a=>a.sessions),b=new Set;return a.filter(a=>!(a.transient||b.has(a.id))&&(b.add(a.id),!0))})(),b8=b7.filter(a=>!a4.has(a.id)),b9=a=>{let b=new Set;for(let c of a)c.transient||a4.has(c.id)||b.has(c.id)||b.add(c.id);return b.size},ca=void 0!==o&&p;return(0,d.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[aF&&(0,d.jsx)(X?M:I,{busy:aJ,error:aH,onCancel:()=>{aG(!1),aI(null)},onSelect:a=>void bw(a)}),bg&&(0,d.jsx)(W,{scope:bg,eligible:b8.length,runningExcluded:b7.length-b8.length,busy:bi,error:bk,onCancel:bm,onConfirm:()=>void bn(b8)}),(0,d.jsx)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,d.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,d.jsx)(T,{}),(0,d.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,d.jsx)("button",{className:"navigator-icon-action",onClick:()=>bB(),disabled:!J,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:"1px solid var(--border)",color:J?"var(--text-muted)":"var(--text-dim)",cursor:J?"pointer":"not-allowed",width:32,height:32,padding:0,borderRadius:7,fontSize:12,flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},title:J?w("sidebar.newSessionTitle",{path:J}):w("sidebar.selectProject"),"aria-label":J?w("sidebar.newSessionTitle",{path:J}):w("sidebar.selectProject"),onMouseEnter:a=>{J&&(a.currentTarget.style.background="var(--bg-selected)",a.currentTarget.style.color="var(--accent)")},onMouseLeave:a=>{a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color=J?"var(--text-muted)":"var(--text-dim)",a.currentTarget.style.borderColor="var(--border)"},children:(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,d.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]})}),(0,d.jsx)("button",{className:`navigator-icon-action${a2?" is-success":""}`,onClick:()=>be(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:a2?"rgba(74,222,128,0.18)":"var(--bg-hover)",border:`1px solid ${a2?"rgba(74,222,128,0.4)":"var(--border)"}`,color:a2?"#4ade80":"var(--text-muted)",cursor:"pointer",width:32,height:32,borderRadius:7,padding:0,flexShrink:0,transition:"background 0.3s, color 0.3s, border-color 0.3s"},onMouseEnter:a=>{a2||(a.currentTarget.style.background="var(--bg-selected)",a.currentTarget.style.color="var(--accent)")},onMouseLeave:a=>{a2||(a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color="var(--text-muted)",a.currentTarget.style.borderColor="var(--border)")},title:w("sidebar.refresh"),children:a2?(0,d.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"var(--success)",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,d.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,d.jsx)("path",{d:"M3 3v5h5"})]})})]})]})}),X&&!ca&&(0,d.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:bx,style:{margin:"10px 12px 0",minHeight:44,flexShrink:0,border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text)",fontSize:13,fontWeight:600,cursor:"pointer"},children:w("cloudProjects.launch")}),(0,d.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,d.jsxs)("div",{className:"navigator-mode-switcher",role:"toolbar","aria-label":w("navigator.toolbar"),style:{display:"flex",alignItems:"center",gap:2,flex:1,minWidth:0,padding:2,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[s.map(a=>{let b="projects"===a?w("sidebar.projects"):w("navigator.priority"),c=!ca&&ad===a;return(0,d.jsx)("button",{type:"button","aria-label":w("navigator.view",{label:b}),"aria-pressed":c,"aria-controls":`navigator-${a}-panel`,"data-navigator-mode":a,onClick:()=>{br(a),ca&&q?.(!1)},style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:c?"var(--bg-selected)":"transparent",color:c?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:c?600:500,whiteSpace:"nowrap"},children:b},a)}),void 0!==o&&(0,d.jsx)("button",{type:"button","aria-label":w("navigator.view",{label:v("lounge.tab")}),"aria-pressed":ca,"aria-controls":"navigator-lounge-panel","data-navigator-mode":"lounge",onClick:()=>q?.(!ca),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:ca?"var(--bg-selected)":"transparent",color:ca?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:ca?600:500,whiteSpace:"nowrap"},children:v("lounge.tab")})]}),!ca&&"projects"===ad&&(0,d.jsx)("button",{type:"button",onClick:()=>as(a=>!a),disabled:!bO,title:w("sidebar.projectShowHidden"),"aria-label":w("sidebar.projectShowHidden"),"aria-pressed":ar,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:5,background:ar?"var(--bg-selected)":"transparent",color:ar?"var(--accent)":"var(--text-dim)",cursor:bO?"pointer":"default",opacity:bO?1:.45,flexShrink:0},children:(0,d.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,d.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,d.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!ar&&(0,d.jsx)("path",{d:"m4 4 16 16"})]})}),!ca&&"projects"===ad&&(0,d.jsx)("button",{className:"navigator-add-project",type:"button",onClick:bx,title:w("sidebar.addProject"),"aria-label":w("sidebar.addProject"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:a=>{a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color="var(--text)"},onMouseLeave:a=>{a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color="var(--text-muted)"},children:(0,d.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"}),(0,d.jsx)("path",{d:"M15.5 10.5v5M13 13h5"})]})})]}),ca&&o,!ca&&"projects"===ad&&(0,d.jsxs)("label",{className:"navigator-search",style:{position:"relative",display:"block",margin:"0 8px 8px"},children:[(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",style:{position:"absolute",left:10,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,d.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,d.jsx)("path",{d:"m20 20-3.5-3.5"})]}),(0,d.jsx)("input",{className:"navigator-search-input",type:"search",value:aa,onChange:a=>ac(a.target.value),onKeyDown:a=>{"Escape"===a.key&&(a.preventDefault(),ac(""),a.currentTarget.blur())},placeholder:w("sidebar.searchProjectsAndSessions"),"aria-label":w("sidebar.searchProjectsAndSessions"),style:{width:"100%",height:34,padding:"0 10px 0 32px",border:"1px solid var(--border)",borderRadius:7,outline:"none",background:"var(--bg-hover)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})]}),!ca&&"projects"===ad&&(0,d.jsxs)("div",{id:"navigator-projects-panel",className:"navigator-session-list",style:{flex:"1 1 auto",overflowY:"auto",minHeight:80,padding:"0 6px 10px"},children:[(E||!ap)&&(0,d.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:w("sidebar.loading")}),G&&(0,d.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:G}),aB&&(0,d.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:aB}),!E&&ap&&!G&&0===bX.length&&(0,d.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:bV?w("sidebar.noMatchingProjects"):w("sidebar.noSessions")}),!E&&ap&&!G&&b0.map(b=>{let c,e,f;if("temporary"===b.kind)return(0,d.jsx)("div",{className:"navigator-project-group",children:(0,d.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":b_,title:w("sidebar.temporaryProjects"),onClick:()=>au(a=>!a),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:34,padding:"0 6px 0 2px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:[(0,d.jsx)("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,flexShrink:0,color:"var(--text-dim)"},children:(0,d.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:{transform:b_?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.12s"},children:(0,d.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),(0,d.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:w("sidebar.temporaryProjects")}),(0,d.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10,flexShrink:0},children:bZ.length}),ab(b$,w)]})},"navigator-temporary-projects");let{project:g,key:h,name:i,sessions:j,hidden:k}=b.group,l=h===bJ,m=b1.has(i.toLowerCase())&&Q((e=Math.max((c=g.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),c.lastIndexOf("/")))<=0?"":c.slice(0,e),L)||null,n=!ah.has(g)&&!bV,o=af.has(g),p=av===g,q=bN.indexOf(g),r=az||bW||q<=0,s=az||bW||q>=bN.length-1,t=function(a){let b=new Map;for(let c of a)b.set(c.id,{session:c,children:[]});let c=new Map;for(let b of a)b.parentSessionId&&c.set(b.id,b.parentSessionId);let d=[];for(let a of b.values()){let e=function(a){let d=c.get(a),e=new Set;for(;d&&!e.has(d);){if(e.add(d),b.has(d))return d;d=c.get(d)}return null}(a.session.id);e?b.get(e).children.push(a):d.push(a)}let e=a=>{a.sort((a,b)=>b.session.modified.localeCompare(a.session.modified)),a.forEach(a=>e(a.children))};return e(d),d}(o?j:j.slice(0,5)),v=j.length>5;return(0,d.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:n?3:9},children:[(0,d.jsxs)("div",{className:`navigator-project-row${l?" is-selected":""}`,ref:al===g?aZ:void 0,onMouseEnter:()=>ak(g),onMouseLeave:()=>ak(a=>a===g&&al!==g?null:a),style:{display:"flex",alignItems:"center",minHeight:34,position:"relative",borderRadius:6,background:l?"var(--bg-hover)":"transparent",opacity:k?.55:1},children:[(0,d.jsx)("button",{type:"button",onClick:()=>bH(g),title:n?w("sidebar.expandProject"):w("sidebar.collapseProject"),"aria-label":n?w("sidebar.expandProject"):w("sidebar.collapseProject"),"aria-expanded":!n,style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,marginLeft:2,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,d.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:{transform:n?"rotate(-90deg)":"rotate(0deg)",transition:"transform 0.12s"},children:(0,d.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),p?(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px"},children:[(0,d.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--accent)"},children:(0,d.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,d.jsx)("input",{ref:a_,value:ax,onChange:a=>ay(a.target.value),onBlur:()=>void bR(g),onKeyDown:a=>{"Enter"===a.key?(a.preventDefault(),a.currentTarget.blur()):"Escape"===a.key&&(a.preventDefault(),a0.current=!0,aw(null))},"aria-label":w("sidebar.projectAlias"),style:{flex:1,minWidth:0,height:24,padding:"2px 6px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12,fontWeight:600}})]}):(0,d.jsxs)("button",{className:"navigator-project-name",type:"button",onClick:()=>K(g),title:g,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:l?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:l?600:500},children:[(0,d.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:l?"var(--accent)":"var(--text-dim)"},children:(0,d.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,d.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),null===m?null:(0,d.jsx)("span",{style:{flexShrink:2,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:m}),ab(bU.get(h),w)]}),(0,d.jsx)("button",{type:"button",onClick:()=>bB(g),title:w("sidebar.newSessionTitle",{path:g}),"aria-label":w("sidebar.newSessionTitle",{path:g}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:5,background:"transparent",color:"var(--text-dim)",cursor:"pointer",opacity:z||aj===g?1:0,pointerEvents:z||aj===g?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>ak(g),onMouseEnter:a=>{a.currentTarget.style.background="var(--bg-selected)",a.currentTarget.style.color="var(--accent)"},onMouseLeave:a=>{a.currentTarget.style.background="transparent",a.currentTarget.style.color="var(--text-dim)"},children:(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,d.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,d.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,d.jsx)("button",{type:"button",onClick:()=>{am(al===g?null:g),aO(!1),aQ(!1),aU(null),l||K(g)},title:w("sidebar.projectActions"),"aria-label":w("sidebar.projectActions"),"aria-expanded":al===g,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:5,background:al===g?"var(--bg-selected)":"transparent",color:l&&b4&&!b4.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:z||aj===g||al===g?1:0,pointerEvents:z||aj===g||al===g?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>ak(g),children:(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,d.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,d.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,d.jsxs)(S,{open:al===g,style:{position:"absolute",top:"calc(100% + 4px)",right:3,width:"min(260px, calc(100vw - 24px))",zIndex:110,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"var(--shadow-float)",boxSizing:"border-box",overflow:"hidden"},children:[b3&&aL&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("button",{type:"button",onClick:()=>aO(a=>!a),title:b4?w("sidebar.switchWorktreeTitle",{path:b4.path}):w("sidebar.switchWorktree"),"aria-label":w("sidebar.worktrees"),"aria-expanded":aN,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderBottom:aN?"1px solid var(--border)":"none",background:aN?"var(--bg-selected)":"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,d.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,d.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,d.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,d.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,d.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,d.jsx)("span",{style:{flex:1},children:w("sidebar.worktrees")}),(0,d.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("polyline",{points:"4 2.5 8 6 4 9.5"})})]}),(0,d.jsxs)(S,{open:aN,style:{position:"static",width:"auto",zIndex:100,background:"var(--bg)",border:"none",borderTop:"1px solid var(--border)",borderRadius:0,boxShadow:"none",boxSizing:"border-box",overflow:"hidden"},children:[b5&&(0,d.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,d.jsx)("input",{value:aD,onChange:a=>aE(a.target.value),onKeyDown:a=>{"Escape"===a.key&&(aE(""),aO(!1))},placeholder:w("sidebar.filterWorktrees"),autoFocus:!0,style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,d.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[b6.map(a=>{let b=a.path===J||a.isMain&&!aL.worktrees.some(a=>a.path===J);return aX===a.path?(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.06)"},children:[(0,d.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:w("sidebar.forceRemoveCheckout")}),(0,d.jsx)("button",{onClick:()=>void bz(a.path,!0),disabled:aV,style:{padding:"3px 9px",background:"var(--danger)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:w("sidebar.force")}),(0,d.jsx)("button",{onClick:()=>aY(null),style:{padding:"3px 9px",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer",flexShrink:0},children:w("sidebar.cancel")})]},a.path):(0,d.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,d.jsxs)("button",{onClick:()=>{K(a.path),aO(!1),aU(null),aE("")},title:a.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:b?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[b?(0,d.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,d.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,d.jsx)("span",{style:{width:10,flexShrink:0}}),(0,d.jsx)(R,{text:a.branch??Q(a.path,L),style:{flex:1}}),a.isMain&&(0,d.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:w("sidebar.main")})]}),!a.isMain&&(0,d.jsx)("button",{onClick:()=>void bz(a.path,!1),disabled:aV,title:w("sidebar.removeWorktreeTitle",{path:a.path}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:34,height:28,padding:0,marginRight:4,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",borderRadius:5,flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:a=>{a.currentTarget.style.color="#ef4444",a.currentTarget.style.background="rgba(239,68,68,0.08)"},onMouseLeave:a=>{a.currentTarget.style.color="var(--text-dim)",a.currentTarget.style.background="none"},children:(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,d.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,d.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,d.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},a.path)}),b5&&0===b6.length&&aD.trim()&&(0,d.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:w("sidebar.noMatchingWorktrees")})]}),aP?(0,d.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,d.jsx)("input",{ref:a$,value:aR,onChange:a=>{aS(a.target.value),aU(null)},onKeyDown:a=>{"Enter"===a.key&&(a.preventDefault(),by()),"Escape"===a.key&&(aQ(!1),aS(""),aU(null))},placeholder:w("sidebar.branchName"),style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}}),(0,d.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,d.jsx)("button",{onClick:()=>void by(),disabled:aV||!aR.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:aV||!aR.trim()?"not-allowed":"pointer",opacity:aV||!aR.trim()?.65:1},children:aV?w("sidebar.creating"):w("sidebar.create")}),(0,d.jsx)("button",{onClick:()=>{aQ(!1),aS(""),aU(null)},style:{flex:1,padding:"4px 0",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer"},children:w("sidebar.cancel")})]})]}):(0,d.jsxs)("button",{onClick:a=>{a.stopPropagation(),aQ(!0),aU(null),setTimeout(()=>a$.current?.focus(),0)},title:w("sidebar.createWorktreeTitle"),style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,d.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,d.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,d.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,d.jsx)("span",{children:w("sidebar.newWorktree")})]}),aT&&(0,d.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:aT})]})]}),(0,d.jsxs)("button",{type:"button",disabled:az,onClick:()=>{let a;return a=bK.get(u(g))?.alias??"",void(a0.current=!1,aC(null),ay(a),aw(g),bP())},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:az?"default":"pointer",textAlign:"left",fontSize:11,opacity:az?.55:1},children:[(0,d.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,d.jsx)("path",{d:"m4 20 4.5-1 10-10a2.1 2.1 0 0 0-3-3l-10 10L4 20Z"}),(0,d.jsx)("path",{d:"m13.5 8 3 3"})]}),w(bK.get(u(g))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,d.jsxs)("button",{type:"button",disabled:r,title:bW?w("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void bS(g,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:r?"default":"pointer",textAlign:"left",fontSize:11,opacity:r?.55:1},children:[(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m6 15 6-6 6 6"})}),w("sidebar.projectMoveUp")]}),(0,d.jsxs)("button",{type:"button",disabled:s,title:bW?w("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void bS(g,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:s?"default":"pointer",textAlign:"left",fontSize:11,opacity:s?.55:1},children:[(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m6 9 6 6 6-6"})}),w("sidebar.projectMoveDown")]}),(0,d.jsxs)("button",{type:"button",disabled:az,onClick:()=>void bQ(g,!k),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:az?"default":"pointer",textAlign:"left",fontSize:11,opacity:az?.55:1},children:[(0,d.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,d.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,d.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!k&&(0,d.jsx)("path",{d:"m4 4 16 16"})]}),w(k?"sidebar.projectUnhide":"sidebar.projectHide")]}),(f=0===b9(bT.get(h)??[])||bi,(0,d.jsxs)("button",{type:"button",disabled:f,onClick:()=>{bP(),bl(null),bh({kind:"project",project:g,label:i})},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:f?"default":"pointer",textAlign:"left",fontSize:11,opacity:f?.55:1},children:[(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),w("sidebar.clearProjectSessions")]}))]})]})]}),!n&&0===j.length&&l&&(0,d.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:w("sidebar.noSessions")}),!n&&t.length>0&&(0,d.jsx)("div",{style:{paddingLeft:12},children:t.map(b=>(0,d.jsx)($,{node:b,selectedSessionId:a,runningSessionIds:a4,unreadSessionIds:a6,pinnedSessionIds:a8,onSelectSession:bA,onTogglePinnedSession:bs,onRenamed:be,onSessionDeleted:bf,onSessionArchived:bq,depth:0},b.session.id))}),!n&&v&&(0,d.jsx)("button",{type:"button",onClick:()=>{ag(a=>{let b=new Set(a);return b.has(g)?b.delete(g):b.add(g),b})},style:{display:"block",margin:"3px 0 3px 32px",padding:"5px 8px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:o?w("sidebar.showLess"):w("sidebar.showMore")})]},g)})]}),!ca&&(0,d.jsx)(Z,{refreshKey:bo,selectedSessionId:a,onSelectSession:bA,onRestored:bq}),!ca&&"priority"===ad&&(0,d.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[E&&(0,d.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:w("sidebar.loading")}),G&&(0,d.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:G}),!E&&!G&&(r=b9(b2.flatMap(a=>a.sessions)),(0,d.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"8px 2px 2px"},children:[(0,d.jsx)("button",{type:"button",disabled:bC,onClick:()=>void bG(),title:w("sidebar.newScratchSessionTitle"),style:P(bC,z),children:w("sidebar.newScratchSession")}),b2.length>0&&(0,d.jsx)("button",{type:"button",disabled:0===r||bi,onClick:()=>{bl(null),bh({kind:"priority"})},style:P(0===r||bi,z),children:w("sidebar.clearPriorityList")})]})),bE&&(0,d.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:bE}),!E&&!G&&0===b2.length&&(0,d.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:w("sidebar.noSessions")}),!E&&!G&&b2.map((b,c)=>(0,d.jsxs)("section",{"aria-labelledby":`priority-group-${b.key}`,children:[(0,d.jsx)("h2",{id:`priority-group-${b.key}`,style:{margin:0,padding:0===c?"2px 8px 4px":"14px 8px 4px",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:b.label}),b.sessions.map(b=>(0,d.jsx)(Y,{session:b,selected:b.id===a,running:a4.has(b.id),unread:a6.has(b.id),pinned:a8.has(b.id),onSelect:bA,onTogglePin:bs},b.id))]},b.key))]})]})}function W({scope:a,eligible:b,runningExcluded:c,busy:f,error:g,onCancel:h,onConfirm:i}){let{t:j}=(0,x.s)(),k=f||0===b,l=(0,e.useRef)(null),m=(0,e.useRef)(null);return(0,e.useRef)(f).current=f,(0,e.useRef)(h).current=h,(0,d.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:a=>{f||a.target!==a.currentTarget||h()},children:(0,d.jsxs)("div",{ref:l,role:"alertdialog","aria-modal":"true","aria-labelledby":"bulk-clear-title","aria-describedby":"bulk-clear-body",tabIndex:-1,style:{width:420,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"var(--shadow-float)",overflow:"hidden"},children:[(0,d.jsxs)("div",{style:{padding:"18px 18px 14px"},children:[(0,d.jsx)("div",{id:"bulk-clear-title",style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:j("sidebar.clearSessionsTitle")}),(0,d.jsxs)("div",{id:"bulk-clear-body",style:{marginTop:8,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,overflowWrap:"anywhere"},children:["project"===a.kind?j("sidebar.clearSessionsProjectBody",{project:a.label,count:b}):j("sidebar.clearSessionsPriorityBody",{count:b}),c>0&&(0,d.jsx)("div",{style:{marginTop:6},children:j("sidebar.clearSessionsRunningExcluded",{count:c})}),0===b&&(0,d.jsx)("div",{style:{marginTop:6},children:j("sidebar.clearSessionsNone")})]}),g&&(0,d.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:g})]}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,d.jsx)("button",{ref:m,type:"button",onClick:h,disabled:f,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:f?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:j("sidebar.clearSessionsCancel")}),(0,d.jsx)("button",{type:"button",onClick:i,disabled:k,"aria-busy":f,style:{minHeight:36,padding:"0 14px",border:"1px solid var(--danger)",borderRadius:"var(--radius-control)",background:"transparent",color:k?"var(--text-dim)":"var(--danger)",cursor:k?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:j(f?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function X({filled:a=!1}){return(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:a?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M12 17v5"}),(0,d.jsx)("path",{d:"M5 17h14"}),(0,d.jsx)("path",{d:"M6 3h12l-1 8 2 3H5l2-3-1-8z"})]})}function Y({session:a,selected:b,running:c,unread:e,pinned:f,onSelect:g,onTogglePin:h}){let{t:i}=(0,x.s)(),j=(a.name||a.firstMessage||a.id.slice(0,8)).replace(/\s+/g," ").trim(),k=a.cwd.split(/[\\/]/).filter(Boolean).at(-1)??"";return(0,d.jsxs)("div",{className:`priority-session-row${b?" is-selected":""}${c?" is-running":""}${e?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:5,background:b?"var(--bg-selected)":"transparent"},children:[(0,d.jsxs)("button",{type:"button","aria-current":b?"page":void 0,onClick:()=>g(a),title:`${j}
|
|
1
|
+
exports.id=5489,exports.ids=[5489],exports.modules={13689:(a,b,c)=>{Promise.resolve().then(c.bind(c,65857)),Promise.resolve().then(c.bind(c,54719))},29947:(a,b,c)=>{"use strict";c.d(b,{C1:()=>f,IN:()=>e,getPresetFromTools:()=>h,xG:()=>i});let d=[],e=["read","bash","edit","write"],f=["read","bash","edit","write","grep","glob"],g=Object.fromEntries(f.map(a=>[a,!0]));function h(a){let b=a.filter(a=>a.active);if(0===b.length)return"none";let c=b.map(a=>a.name).filter(a=>!0===g[a]).sort().join(",");return c===[...e].sort().join(",")?"default":c===[...f].sort().join(",")?"full":"default"}function i(a){return"none"===a?[...d]:"full"===a?[...f]:[...e]}},35790:(a,b,c)=>{"use strict";c.d(b,{AppShell:()=>d});let d=(0,c(77943).registerClientReference)(function(){throw Error("Attempted to call AppShell() from the server but AppShell is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"D:\\a\\CUELO\\CUELO\\components\\AppShell.tsx","AppShell")},35836:a=>{a.exports={root:"SearchableSelect_root__FMhaH",trigger:"SearchableSelect_trigger__eqMdt",value:"SearchableSelect_value__eJ2RU",placeholder:"SearchableSelect_placeholder__Hkg33",chevron:"SearchableSelect_chevron__DSTnM",popover:"SearchableSelect_popover__5VxMd",searchWrap:"SearchableSelect_searchWrap__IoKKk",searchIcon:"SearchableSelect_searchIcon__A6f0C",search:"SearchableSelect_search__W_1al",options:"SearchableSelect_options__tjHyi",option:"SearchableSelect_option__LRRH9",optionCopy:"SearchableSelect_optionCopy__W87H8",optionLabel:"SearchableSelect_optionLabel__G7jIg",optionDescription:"SearchableSelect_optionDescription__cE_cC",check:"SearchableSelect_check__1Likw",empty:"SearchableSelect_empty__vZzXQ"}},43065:(a,b,c)=>{Promise.resolve().then(c.bind(c,35790)),Promise.resolve().then(c.bind(c,73884))},51768:a=>{a.exports={dialog:"CloudProjectPicker_dialog__Dx2Dt",form:"CloudProjectPicker_form__MpEsn",header:"CloudProjectPicker_header__UcYbB",sources:"CloudProjectPicker_sources__6cl_0",activeSource:"CloudProjectPicker_activeSource__NptfQ",body:"CloudProjectPicker_body__vKMBC",account:"CloudProjectPicker_account__gb9Qo",repositories:"CloudProjectPicker_repositories__WSBt6",secondary:"CloudProjectPicker_secondary__hlaFU",primary:"CloudProjectPicker_primary__voWx5",loginLink:"CloudProjectPicker_loginLink__Gu5XC",login:"CloudProjectPicker_login__c0qSl",codeRow:"CloudProjectPicker_codeRow__jo8vy",repositoryInput:"CloudProjectPicker_repositoryInput__HWhvu",list:"CloudProjectPicker_list__0BSYU",repo:"CloudProjectPicker_repo__L4VaW",repoHeading:"CloudProjectPicker_repoHeading__3Pnq1",repoDescription:"CloudProjectPicker_repoDescription__YzPtB",error:"CloudProjectPicker_error__dAVsm",progress:"CloudProjectPicker_progress__OwvG9",footer:"CloudProjectPicker_footer__mmrGI"}},57582:()=>{},65857:(a,b,c)=>{"use strict";c.d(b,{AppShell:()=>kK});var d=c(48249),e=c(67484),f=c.n(e),g=c(19099),h=c(25955),i=c(2586),j=c(86592),k=c(58474);let l=["chat","process","subagents","files","resource","sidechat","efficiency"],m=["characters","usage","models"];Object.freeze({transcript:550,composer:384,navigator:240,deck:384});let n=Object.freeze({navigator:791,deck:1176}),o=Object.freeze({activeView:"chat",transientLayer:null}),p=Object.fromEntries(l.map(a=>[a,!0]));function q(a){return"string"==typeof a&&!0===p[a]?a:o.activeView}function r(a,b){switch(b.type){case"select-view":return{activeView:q(b.view),transientLayer:null};case"open-layer":return{activeView:q(a.activeView),transientLayer:b.layer};case"toggle-layer":return{activeView:q(a.activeView),transientLayer:a.transientLayer===b.layer?null:b.layer};case"close-layer":return{activeView:q(a.activeView),transientLayer:null}}}let s=["projects","priority"],t=["omp-relay-session-","omp-cwd-","ompscope_"];function u(a){let b=a.trim().replace(/\\/g,"/");return"/"===(b=b.startsWith("//")?`//${b.slice(2).replace(/\/{2,}/g,"/")}`:b.replace(/\/{2,}/g,"/"))||/^[a-zA-Z]:\/$/.test(b)||(b=b.replace(/\/+$/,"")),/^[a-zA-Z]:\//.test(b)||b.startsWith("//")?b.toLowerCase():b}let v=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function w(a){let b=a.match(v);if(!b)return null;let[,c,,,d]=b;return d?`/skill:${c} ${d}`:`/skill:${c}`}var x=c(54719);let y=`(max-width: ${n.navigator-1}px)`;function z(a){return{subscribe:a=>()=>{},getSnapshot:()=>!1}}let A=z("(max-width: 640px)"),B=z(y);function C(){return!1}function D(){return(0,e.useSyncExternalStore)(A.subscribe,A.getSnapshot,C)}var E=c(74429);async function F(a){let b=a?`?path=${encodeURIComponent(a)}`:"",c=await fetch(`/api/cwd/browse${b}`),d=await c.json();if(!c.ok||d.error)throw Error(d.error??`HTTP ${c.status}`);return d}function G(){return(0,d.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function H(){return(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,d.jsx)("path",{d:"M2 9h12"}),(0,d.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function I({onCancel:a,onSelect:b,busy:c=!1,error:f}){let{t:g}=(0,x.s)(),[h,i]=(0,e.useState)(null),[j,k]=(0,e.useState)(""),[l,m]=(0,e.useState)(null),[n,o]=(0,e.useState)(""),[p,q]=(0,e.useState)([]),[r,s]=(0,e.useState)(null),[t,u]=(0,e.useState)(null),[v,w]=(0,e.useState)(!0),y=(0,e.useCallback)(async a=>{w(!0),u(null);try{let b=await F(a),c=b.path??a??"/";k(c),m(b.parentPath??null),o(c),q(b.directories??[]),s(b.drives??null)}catch(a){u(a instanceof Error?a.message:String(a))}finally{w(!1)}},[]),z=n.trim()!==j,A=!!j&&!z&&!c,B=!!l||/^[a-zA-Z]:[\\/]?$/.test(j);return h?(0,E.createPortal)((0,d.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":g("directoryPicker.selectDirectory"),onClick:b=>{b.target!==b.currentTarget||c||a()},onKeyDown:b=>{"Escape"!==b.key||c||a()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,d.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,d.jsx)("div",{style:{minWidth:0,flex:1},children:(0,d.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:g("directoryPicker.selectDirectory")})}),(0,d.jsx)("button",{type:"button",onClick:a,disabled:c,title:g("i18n.close"),"aria-label":g("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:c?"default":"pointer",opacity:c?.5:1},children:"\xd7"})]}),(0,d.jsxs)("form",{onSubmit:a=>{a.preventDefault();let b=n.trim();b&&y(b)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,d.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void y(l??void 0),disabled:v||!B,title:g("directoryPicker.goToParent"),"aria-label":g("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:B?"pointer":"default",opacity:B?1:.45},children:(0,d.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,d.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:g("directoryPicker.directoryPath")}),(0,d.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:n,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:a=>{o(a.target.value),u(null)},style:{minWidth:0,flex:1,height:36,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12}}),(0,d.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:v||!n.trim(),title:g("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:v||!n.trim()?"default":"pointer",opacity:v||!n.trim()?.6:1},children:g("directoryPicker.go")})]}),(0,d.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[v?(0,d.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:g("directoryPicker.loadingDirectories")}):null!==r?(0,d.jsx)(d.Fragment,{children:r.length>0?r.map(a=>(0,d.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void y(a.path),title:a.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,d.jsx)(H,{}),(0,d.jsx)("span",{children:a.name})]},a.path)):(0,d.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:g("directoryPicker.noDrives")})}):p.length>0?p.map(a=>(0,d.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void y(a.path),title:a.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,d.jsx)(G,{}),(0,d.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.name})]},a.path)):(0,d.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:g("directoryPicker.noSubdirectories")}),(t||f)&&(0,d.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:t??f})]}),(0,d.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,d.jsx)("button",{className:"directory-picker-action",type:"button",onClick:a,disabled:c,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text-muted)",cursor:c?"default":"pointer",fontSize:13},children:g("i18n.cancel")}),(0,d.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>b(j),disabled:!A,title:g(z?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",border:0,borderRadius:6,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontSize:13,fontWeight:600,opacity:A?1:.6,cursor:A?"pointer":"default"},children:g(c?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),h):null}var J=c(51768),K=c.n(J);async function L(a,b){let c=await fetch(a,b?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)}:void 0),d=await c.json();if(!c.ok)throw Error(d.error||`HTTP ${c.status}`);return d}function M({onCancel:a,onSelect:b,busy:c=!1,error:f}){let{t:g}=(0,x.s)(),h=(0,e.useRef)(null),[i,j]=(0,e.useState)(!1),[k,l]=(0,e.useState)(!1),[m,n]=(0,e.useState)(null),[o,p]=(0,e.useState)([]),[q,r]=(0,e.useState)(""),[s,t]=(0,e.useState)(""),[u,v]=(0,e.useState)(!0),[w,y]=(0,e.useState)(!1),[z,A]=(0,e.useState)(!1),[B,C]=(0,e.useState)(null),[D,F]=(0,e.useState)(!1),[G,H]=(0,e.useState)(50),J=m?.device?.state==="pending",N=c||z,O=(0,e.useCallback)(async()=>{v(!0),C(null);try{let a=await L("/api/github/projects");n(a),a.connected&&p((await L("/api/github/projects?view=repositories")).repositories)}catch(a){C(a instanceof Error?a.message:String(a))}finally{v(!1)}},[]);async function P(){y(!0),C(null);try{let{device:a}=await L("/api/github/projects",{action:"login"});n({connected:!1,login:null,device:a})}catch(a){C(a instanceof Error?a.message:String(a))}finally{y(!1)}}async function Q(a){if(a.preventDefault(),s.trim()&&!N){A(!0),C(null);try{let{cwd:a}=await L("/api/github/projects",{action:"open",repository:s});b(a)}catch(a){C(a instanceof Error?a.message:String(a))}finally{A(!1)}}}if(!i)return null;if(k)return(0,d.jsx)(I,{onCancel:()=>l(!1),onSelect:b,busy:c,error:f});let R=o.filter(a=>`${a.fullName} ${a.description??""}`.toLowerCase().includes(q.toLowerCase())),S=B??f??m?.device?.error;return(0,E.createPortal)((0,d.jsx)("dialog",{ref:h,className:K().dialog,"aria-labelledby":"cloud-project-title",onCancel:b=>{b.preventDefault(),N||a()},children:(0,d.jsxs)("form",{onSubmit:Q,className:K().form,children:[(0,d.jsxs)("header",{className:K().header,children:[(0,d.jsx)("h2",{id:"cloud-project-title",children:g("cloudProjects.title")}),(0,d.jsx)("p",{children:g("cloudProjects.description")})]}),(0,d.jsxs)("div",{className:K().sources,children:[(0,d.jsx)("span",{className:K().activeSource,children:g("cloudProjects.github")}),(0,d.jsx)("button",{type:"button",onClick:()=>l(!0),disabled:N,children:g("cloudProjects.serverFolder")})]}),(0,d.jsxs)("div",{className:K().body,children:[(0,d.jsxs)("section",{className:K().account,"aria-label":g("cloudProjects.account"),children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("strong",{children:m?.connected?m.login:g("cloudProjects.connectTitle")}),(0,d.jsx)("p",{children:m?.connected?g("cloudProjects.connected"):g("cloudProjects.connectHelp")})]}),m?.connected?(0,d.jsx)("button",{type:"button",className:K().secondary,onClick:()=>void O(),disabled:u||N,children:g("cloudProjects.refresh")}):(0,d.jsx)("button",{type:"button",className:K().secondary,onClick:()=>void P(),disabled:u||w||J||N,children:w||J?g("cloudProjects.waiting"):g("cloudProjects.connect")})]}),J&&(0,d.jsxs)("div",{className:K().login,role:"status",children:[(0,d.jsx)("p",{children:g("cloudProjects.deviceHelp")}),m.device?.code?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{className:K().codeRow,children:[(0,d.jsx)("code",{children:m.device.code}),(0,d.jsx)("button",{type:"button",className:K().secondary,onClick:()=>{navigator.clipboard.writeText(m.device.code).then(()=>F(!0)).catch(()=>C(g("cloudProjects.copyFailure")))},children:D?g("cloudProjects.copied"):g("cloudProjects.copyCode")})]}),(0,d.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:K().loginLink,children:g("cloudProjects.openLogin")}),(0,d.jsx)("small",{children:g("cloudProjects.permissionHelp")})]}):(0,d.jsx)("p",{children:g("cloudProjects.preparingCode")})]}),m?.connected&&(0,d.jsxs)("section",{className:K().repositories,"aria-label":g("cloudProjects.repositories"),children:[(0,d.jsx)("label",{htmlFor:"cloud-repo-search",children:g("cloudProjects.search")}),(0,d.jsx)("input",{id:"cloud-repo-search",value:q,onChange:a=>{r(a.target.value),H(50)},placeholder:g("cloudProjects.searchPlaceholder"),type:"search",disabled:N}),u?(0,d.jsx)("p",{role:"status",children:g("cloudProjects.loading")}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("ul",{className:K().list,children:R.slice(0,G).map(a=>(0,d.jsx)("li",{children:(0,d.jsxs)("button",{type:"button",className:K().repo,"aria-pressed":s===a.fullName,disabled:N,onClick:()=>t(a.fullName),children:[(0,d.jsxs)("span",{className:K().repoHeading,children:[(0,d.jsx)("strong",{children:a.fullName}),(0,d.jsx)("small",{children:a.private?g("cloudProjects.private"):g("cloudProjects.public")})]}),a.description&&(0,d.jsx)("span",{className:K().repoDescription,children:a.description})]})},a.fullName))}),!R.length&&(0,d.jsx)("p",{children:g("cloudProjects.empty")}),R.length>G&&(0,d.jsx)("button",{type:"button",className:K().secondary,onClick:()=>H(a=>a+50),children:g("cloudProjects.more")})]})]}),(0,d.jsxs)("div",{className:K().repositoryInput,children:[(0,d.jsx)("label",{htmlFor:"cloud-repository",children:g("cloudProjects.urlLabel")}),(0,d.jsx)("input",{id:"cloud-repository",value:s,onChange:a=>t(a.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:N,"aria-describedby":"cloud-repo-help"}),(0,d.jsx)("small",{id:"cloud-repo-help",children:g("cloudProjects.publicHelp")})]}),S&&(0,d.jsxs)("div",{className:K().error,role:"alert",children:[(0,d.jsx)("strong",{children:g("cloudProjects.error")}),(0,d.jsx)("p",{children:S}),(0,d.jsx)("button",{type:"button",className:K().secondary,onClick:()=>void O(),disabled:N,children:g("cloudProjects.refresh")})]}),z&&(0,d.jsx)("p",{role:"status",className:K().progress,children:g("cloudProjects.openingHelp")})]}),(0,d.jsxs)("footer",{className:K().footer,children:[(0,d.jsx)("button",{type:"button",className:K().secondary,onClick:a,disabled:N,children:g("i18n.cancel")}),(0,d.jsx)("button",{type:"submit",className:K().primary,disabled:N||!s.trim(),children:N?g("cloudProjects.opening"):g("cloudProjects.open")})]})]})}),document.body)}function N({label:a="CUELO",markSize:b=22,gap:c=10,style:e,labelStyle:f}){return(0,d.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:c,minWidth:0,color:"var(--text)",...e},children:[(0,d.jsxs)("svg",{viewBox:"0 0 100 100",width:b,height:b,"aria-hidden":"true",style:{flexShrink:0},children:[(0,d.jsx)("path",{d:"M77.9 30.5 A34 34 0 0 0 16 50 A26 26 0 0 0 68 50",fill:"none",stroke:"currentColor",strokeWidth:"10",strokeLinecap:"round"}),(0,d.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,d.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:'"Plus Jakarta Sans", Geist, ui-sans-serif, system-ui, sans-serif',fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...f},children:a})]})}var O=c(13928);function P(a,b){return{minHeight:b?36:30,padding:"3px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:a?"var(--text-dim)":"var(--text-muted)",cursor:a?"default":"pointer",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.3,textAlign:"left",whiteSpace:"normal",overflowWrap:"anywhere"}}function Q(a,b){return b&&a.startsWith(b)?"~"+a.slice(b.length):a}function R({text:a,style:b}){return(0,d.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...b},children:(0,d.jsx)("span",{style:{unicodeBidi:"plaintext"},children:a})})}function S({open:a,children:b,style:c}){let[f,g]=(0,e.useState)(a),[h,i]=(0,e.useState)(a);return f?(0,d.jsx)("div",{style:{...c,opacity:+!!h,transform:h?"translateY(0) scale(1)":"translateY(-8px) scale(0.96)",transformOrigin:"top center",transition:"opacity 140ms ease, transform 140ms ease",pointerEvents:a?"auto":"none"},children:b}):null}function T(){let[a,b]=(0,e.useState)(!1),[c,f]=(0,e.useState)(!1),g=(0,e.useRef)(null),h=function(a){let[b,c]=(0,e.useState)(a);return(0,e.useRef)(null),(0,e.useRef)(0),b}(a?"0.10.2/18.8.6":"CUELO"),i=(0,e.useCallback)(a=>{b(a),f(!0),setTimeout(()=>f(!1),(a?6:8)*4*(1e3/60)+100)},[]),j=(0,e.useCallback)(()=>{g.current&&clearTimeout(g.current);let b=!a;i(b),b&&(g.current=setTimeout(()=>i(!1),3e3))},[a,i]);return(0,d.jsx)("button",{className:"navigator-brand",onClick:j,style:{display:"flex",alignItems:"center",background:"none",border:"none",padding:0,cursor:"default",color:a?"var(--accent)":"var(--text)",minWidth:"6ch"},children:(0,d.jsx)(N,{label:h,labelStyle:a?{fontFamily:"var(--font-mono)",letterSpacing:"-0.01em"}:void 0})})}async function U(a){let b=await fetch("/api/projects",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:a})});if(!b.ok)throw Error(`HTTP ${b.status}`)}function V({selectedSessionId:a,optimisticSession:b,onSelectSession:c,onNewSession:f,initialSessionId:g,skipInitialProjectSelection:h,onInitialRestoreDone:i,refreshKey:j,onSessionDeleted:k,selectedCwd:l,onCwdChange:m,onBackgroundTaskDone:n,loungePanel:o,loungeActive:p=!1,onLoungeActiveChange:q}){let r,{lt:v}=(0,O.H)(),{t:w,locale:y}=(0,x.s)(),z=D(),[A,B]=(0,e.useState)([]),C=b&&!A.some(a=>a.id===b.id)?[b,...A]:A,[E,F]=(0,e.useState)(!0),[G,H]=(0,e.useState)(null),[J,K]=(0,e.useState)(null),[L,N]=(0,e.useState)(""),[X,_]=(0,e.useState)(!1),[aa,ac]=(0,e.useState)(""),[ad,ae]=(0,e.useState)("projects"),[af,ag]=(0,e.useState)(()=>new Set),[ah,ai]=(0,e.useState)(()=>new Set),[aj,ak]=(0,e.useState)(null),[al,am]=(0,e.useState)(null),[an,ao]=(0,e.useState)({version:1,projects:[]}),[ap,aq]=(0,e.useState)(!1),[ar,as]=(0,e.useState)(!1),[at,au]=(0,e.useState)(!1),[av,aw]=(0,e.useState)(null),[ax,ay]=(0,e.useState)(""),[az,aA]=(0,e.useState)(!1),[aB,aC]=(0,e.useState)(null),[aD,aE]=(0,e.useState)(""),[aF,aG]=(0,e.useState)(!1),[aH,aI]=(0,e.useState)(null),[aJ,aK]=(0,e.useState)(!1),[aL,aM]=(0,e.useState)(null),[aN,aO]=(0,e.useState)(!1),[aP,aQ]=(0,e.useState)(!1),[aR,aS]=(0,e.useState)(""),[aT,aU]=(0,e.useState)(null),[aV,aW]=(0,e.useState)(!1),[aX,aY]=(0,e.useState)(null),aZ=(0,e.useRef)(null),a$=(0,e.useRef)(null),a_=(0,e.useRef)(null),a0=(0,e.useRef)(!1),a1=(0,e.useRef)(!1),[a2,a3]=(0,e.useState)(!1),[a4,a5]=(0,e.useState)(()=>new Set),[a6,a7]=(0,e.useState)(()=>new Set),[a8,a9]=(0,e.useState)(()=>new Set);(0,e.useRef)(new Set);let ba=(0,e.useRef)(!1),bb=(0,e.useRef)(null),bc=(0,e.useCallback)(async()=>{try{let a=await fetch("/api/projects",{cache:"no-store",signal:AbortSignal.timeout(5e3)});if(!a.ok)throw Error(`HTTP ${a.status}`);ao(await a.json())}catch{ao({version:1,projects:[]})}finally{aq(!0)}},[]),bd=(0,e.useCallback)(async a=>{if(a1.current)throw Error("Project update in progress");a1.current=!0,aA(!0);try{await U(a),await bc()}finally{a1.current=!1,aA(!1)}},[bc]),be=(0,e.useCallback)(async(a=!1,b=!1)=>{try{a&&F(!0);let c=await fetch(b?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!c.ok)throw Error(`HTTP ${c.status}`);let d=await c.json();B(d.sessions),ba.current||a5(new Set(d.runningSessionIds??[])),H(null),a||(a3(!0),bb.current&&clearTimeout(bb.current),bb.current=setTimeout(()=>a3(!1),2e3))}catch(a){H(String(a))}finally{a&&F(!1)}},[]),bf=(0,e.useCallback)(a=>{a7(b=>{if(!b.has(a))return b;let c=new Set(b);return c.delete(a),c}),a9(b=>{if(!b.has(a))return b;let c=new Set(b);return c.delete(a),c}),k?.(a),be()},[be,k]),[bg,bh]=(0,e.useState)(null),[bi,bj]=(0,e.useState)(!1),[bk,bl]=(0,e.useState)(null),bm=(0,e.useCallback)(()=>{bi||(bh(null),bl(null))},[bi]),bn=(0,e.useCallback)(async a=>{bj(!0),bl(null);let b=[],c=[],d=[];for(let e of a)if(!e.transient)try{let a=await fetch(`/api/sessions/${encodeURIComponent(e.id)}?skipRunning=1`,{method:"DELETE"});if(409===a.status){c.push(e.id);continue}if(!a.ok)throw Error(`HTTP ${a.status}`);b.push(e.id)}catch{d.push(e.name?.trim()||e.id.slice(0,8))}if(c.length>0&&(ba.current=!0,a5(a=>{if(c.every(b=>a.has(b)))return a;let b=new Set(a);for(let a of c)b.add(a);return b})),b.length>0){let a=new Set(b),c=c=>b.some(a=>c.has(a))?new Set([...c].filter(b=>!a.has(b))):c;for(let a of(a7(c),a9(c),b))k?.(a)}(await be(),bj(!1),d.length>0)?bl(w("sidebar.clearSessionsFailed",{count:d.length,names:d.join(", ")})):c.length>0||bh(null)},[be,k,w]),[bo,bp]=(0,e.useState)(0),bq=(0,e.useCallback)(()=>{bp(a=>a+1),be()},[be]);(0,e.useRef)(!1);let br=(0,e.useCallback)(a=>{ae(a);try{window.localStorage.setItem("omp-web:navigator-mode",a),window.localStorage.setItem("omp-prio-on","priority"===a?"1":"0")}catch{}},[]),bs=(0,e.useCallback)(a=>{a9(b=>{let c=new Set(b);return c.has(a)?c.delete(a):c.add(a),c})},[]);(0,e.useRef)(!1);let bt=(0,e.useCallback)(a=>{if(!a)return null;if(aL&&aL.forCwd===a||aL?.worktrees.some(b=>b.path===a))return aL.projectRoot;let b=C.find(b=>b.cwd===a);return b?.projectRoot??a},[aL,C]);(0,e.useRef)(null),(0,e.useRef)(null);let[bu,bv]=(0,e.useState)(0),bw=(0,e.useCallback)(async a=>{let b=a.trim();if(b&&!aJ){aK(!0),aI(null);try{let a=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:b})}),c=await a.json().catch(()=>({}));if(!a.ok||c.error)return void aI(c.error??w("workspace.unable"));let d=c.cwd??b,e=u(d),f=an.projects.find(a=>a.key===e);if(f?.hidden===!0)try{await bd([{key:e,path:d,hidden:!1}])}catch{}K(d),aG(!1)}catch{aI(w("workspace.unable"))}finally{aK(!1)}}},[bd,aJ,an.projects,w]),bx=(0,e.useCallback)(()=>{aG(!0),aI(null)},[]),by=(0,e.useCallback)(async()=>{let a=aR.trim();if(a&&!aV&&aL){aW(!0),aU(null);try{let b=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:aL.projectRoot,branch:a})}),c=await b.json().catch(()=>({}));if(!b.ok||c.error||!c.path)return void aU(c.error??`HTTP ${b.status}`);aQ(!1),aS(""),aO(!1),aM(b=>b?{...b,forCwd:c.path,worktrees:[...b.worktrees,{path:c.path,branch:a,isMain:!1}]}:b),K(c.path),bv(a=>a+1)}catch(a){aU(a instanceof Error?a.message:String(a))}finally{aW(!1)}}},[aR,aV,aL]),bz=(0,e.useCallback)(async(a,b)=>{if(aL&&!aV){aW(!0),aU(null);try{let c=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:aL.projectRoot,path:a,force:b})}),d=await c.json().catch(()=>({}));if(!c.ok){if(d.dirty&&!b)return void aY(a);aU(d.error??`HTTP ${c.status}`);return}aY(null),J===a&&K(aL.projectRoot),bv(a=>a+1)}catch(a){aU(a instanceof Error?a.message:String(a))}finally{aW(!1)}}},[aL,aV,J]),bA=(0,e.useCallback)(a=>{a.cwd&&K(a.cwd),c(a)},[c]),bB=(0,e.useCallback)((a=J)=>{if(!a)return;let b="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;K(a),f?.(b,a)},[J,f]),[bC,bD]=(0,e.useState)(!1),[bE,bF]=(0,e.useState)(null),bG=(0,e.useCallback)(async()=>{bD(!0),bF(null);try{let a=await fetch("/api/default-cwd",{method:"POST"}),b=await a.json().catch(()=>({}));if(!a.ok||!b.cwd)throw Error(b.error??`HTTP ${a.status}`);bB(b.cwd)}catch(a){bF(w("sidebar.newScratchSessionFailed",{error:a instanceof Error?a.message:String(a)}))}finally{bD(!1)}},[bB,w]),bH=(0,e.useCallback)(a=>{ai(b=>{let c=new Set(b);return c.has(a)?c.delete(a):c.add(a),c})},[]),bI=bt(J),bJ=null===bI?null:u(bI),bK=(0,e.useMemo)(()=>new Map(an.projects.map(a=>[a.key,a])),[an.projects]),bL=function(a){let b=new Map;for(let c of a){let a=c.projectRoot??c.cwd;if(!a)continue;let d=u(a),e=b.get(d);(!e||c.modified>e.modified)&&b.set(d,{project:a,modified:c.modified})}return[...b.values()].sort((a,b)=>b.modified.localeCompare(a.modified)).map(a=>a.project)}(C);if(null!==bI){let a=u(bI);bL.some(b=>u(b)===a)||bL.unshift(bI)}let bM=function(a,b){let c=new Map;for(let a of b)"number"==typeof a.order&&Number.isFinite(a.order)&&c.set(u(a.key),a.order);let d=[...a],e=new Set(a.map(u));for(let a of b){let b=u(a.key);!b||e.has(b)||(d.push(a.path??a.key),e.add(b))}return d.map((a,b)=>({project:a,defaultIndex:b,order:c.get(u(a))})).sort((a,b)=>{let c=void 0!==a.order,d=void 0!==b.order;return c!==d?c?-1:1:c&&d&&a.order!==b.order?a.order-b.order:a.defaultIndex-b.defaultIndex}).map(({project:a})=>a)}(bL,an.projects),bN=bM.filter(a=>ar||!bK.get(u(a))?.hidden),bO=bM.some(a=>bK.get(u(a))?.hidden),bP=()=>{am(null),aO(!1),aQ(!1),aS(""),aU(null),aY(null),aE("")},bQ=async(a,b)=>{bP();try{await bd([{key:u(a),path:a,hidden:b}]),b&&bJ&&bJ===u(a)&&K(null),b||bM.some(b=>u(b)!==u(a)&&bK.get(u(b))?.hidden)||as(!1)}catch{}},bR=async a=>{if(a0.current){a0.current=!1,aw(null);return}let b=ax.trim();if(b===(bK.get(u(a))?.alias??""))return void aw(null);aC(null);try{await bd([{key:u(a),path:a,alias:b||null}]),aw(null)}catch{aC(w("sidebar.projectUpdateFailed"))}},bS=async(a,b)=>{if(aa)return;let c=bN.indexOf(a),d=c+b;if(c<0||d<0||d>=bN.length)return;let e=new Set(bN),f=bM.map((a,b)=>e.has(a)?b:-1).filter(a=>a>=0),g=[...bM],h=f[c],i=f[d];[g[h],g[i]]=[g[i],g[h]],bP();try{await bd(g.map((a,b)=>({key:u(a),path:a,order:b})))}catch{}},bT=new Map;for(let a of C){let b=a.projectRoot??a.cwd;if(!b)continue;let c=u(b),d=bT.get(c);d?d.push(a):bT.set(c,[a])}let bU=(0,e.useMemo)(()=>{let a=new Map;for(let b of C){let c=b.projectRoot??b.cwd;if(!c)continue;let d=u(c),e=a.get(d);e||(e={running:0,unread:0},a.set(d,e)),a4.has(b.id)&&e.running++,a6.has(b.id)&&e.unread++}return a},[C,a4,a6]),bV=aa.trim().toLowerCase(),bW=aa.length>0,bX=bN.flatMap(a=>{let b=a.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||a,c=u(a),d=bK.get(c),e=d?.alias??b,f=(bT.get(c)??[]).slice().sort((a,b)=>{let c=Number(a8.has(b.id))-Number(a8.has(a.id));return 0!==c?c:b.modified.localeCompare(a.modified)});if(!bV)return[{project:a,key:c,name:e,sessions:f,hidden:d?.hidden===!0}];let g=e.toLowerCase().includes(bV)||b.toLowerCase().includes(bV),h=f.filter(a=>(a.name||a.firstMessage.slice(0,50)||a.id.slice(0,12)).toLowerCase().includes(bV));return g||0!==h.length?[{project:a,key:c,name:e,sessions:g?f:h,hidden:d?.hidden===!0}]:[]}),bY=[],bZ=[];for(let a of bX){let b=a.key===bJ||(bU.get(a.key)?.running??0)>0;(function(a){let b=a.trim().replace(/\\/g,"/").toLowerCase();return!!(/^[a-z]:\/?$/.test(b)||"/"===b||/(^|\/)appdata\/local\/temp(\/|$)/.test(b)||/^\/(?:var\/|private\/)?tmp(?:\/|$)/.test(b)||/^[a-z]:\/(?:tmp|temp)(?:\/|$)/.test(b)||/(^|\/)(?:users|home)\/[^/]+\/\.omp(\/|$)/.test(b))||b.split("/").some(a=>t.some(b=>a.startsWith(b)))})(a.project)&&!b?bZ.push(a):bY.push(a)}let b$={running:0,unread:0};for(let a of bZ){let b=bU.get(a.key);b&&(b$.running+=b.running,b$.unread+=b.unread)}let b_=bW||at,b0=[...bY.map(a=>({kind:"project",group:a})),...bZ.length>0?[{kind:"temporary"}]:[],...b_?bZ.map(a=>({kind:"project",group:a})):[]],b1=function(a){let b=new Map;for(let c of a){let a=c.toLowerCase();b.set(a,(b.get(a)??0)+1)}return new Set([...b].filter(([,a])=>a>1).map(([a])=>a))}(b0.flatMap(a=>"project"===a.kind?[a.group.name]:[])),b2=(0,e.useMemo)(()=>(function(a,b,c,d,e="Priority",f=new Set,g="Pinned"){let h=a.filter(a=>!a.transient).slice().sort((a,b)=>{let c=Date.parse(a.modified),d=Date.parse(b.modified);return(Number.isFinite(d)?d:0)-(Number.isFinite(c)?c:0)}),i=h.filter(a=>f.has(a.id)),j=[],k=new Map,l=0;for(let a of h){if(f.has(a.id))continue;if(b.has(a.id)){j.push(a);continue}let c=new Date(a.modified);if(l>=10)continue;l+=1;let d=[c.getFullYear(),String(c.getMonth()+1).padStart(2,"0"),String(c.getDate()).padStart(2,"0")].join("-"),e=k.get(d);e?e.push(a):k.set(d,[a])}let m=[];for(let a of(i.length>0&&m.push({key:"pinned",label:g,running:!1,sessions:i}),j.length>0&&m.push({key:"priority",label:e,running:!0,sessions:j}),[...k.keys()].sort().reverse()))m.push({key:a,label:function(a,b,c){let[d,e,f]=a.split("-").map(Number),g=new Date(d,e-1,f),h=Math.round((Date.UTC(b.getFullYear(),b.getMonth(),b.getDate())-Date.UTC(g.getFullYear(),g.getMonth(),g.getDate()))/864e5);return 0===h||1===h?new Intl.RelativeTimeFormat(c,{numeric:"auto"}).format(-h,"day"):h>=0&&h<7?new Intl.DateTimeFormat(c,{weekday:"long"}).format(g):new Intl.DateTimeFormat(c,{month:"short",day:"numeric"}).format(g)}(a,c,d),running:!1,sessions:k.get(a)??[]});return m})(C,a4,new Date,y,w("navigator.priority"),a8,w("sidebar.pinned")),[y,a8,a4,C,w]),b3=!!(aL?.isGit&&aL.isTopLevel&&J&&bI===aL.projectRoot),b4=aL?.worktrees.find(a=>a.path===J)??aL?.worktrees.find(a=>a.isMain),b5=(aL?.worktrees.length??0)>=8,b6=b5&&aD.trim()?(aL?.worktrees??[]).filter(a=>(a.branch??Q(a.path,L)).toLowerCase().includes(aD.trim().toLowerCase())):aL?.worktrees??[],b7=(()=>{if(!bg)return[];let a="project"===bg.kind?bT.get(u(bg.project))??[]:b2.flatMap(a=>a.sessions),b=new Set;return a.filter(a=>!(a.transient||b.has(a.id))&&(b.add(a.id),!0))})(),b8=b7.filter(a=>!a4.has(a.id)),b9=a=>{let b=new Set;for(let c of a)c.transient||a4.has(c.id)||b.has(c.id)||b.add(c.id);return b.size},ca=void 0!==o&&p;return(0,d.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[aF&&(0,d.jsx)(X?M:I,{busy:aJ,error:aH,onCancel:()=>{aG(!1),aI(null)},onSelect:a=>void bw(a)}),bg&&(0,d.jsx)(W,{scope:bg,eligible:b8.length,runningExcluded:b7.length-b8.length,busy:bi,error:bk,onCancel:bm,onConfirm:()=>void bn(b8)}),(0,d.jsx)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,d.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,d.jsx)(T,{}),(0,d.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,d.jsx)("button",{className:"navigator-icon-action",onClick:()=>bB(),disabled:!J,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:"1px solid var(--border)",color:J?"var(--text-muted)":"var(--text-dim)",cursor:J?"pointer":"not-allowed",width:32,height:32,padding:0,borderRadius:7,fontSize:12,flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},title:J?w("sidebar.newSessionTitle",{path:J}):w("sidebar.selectProject"),"aria-label":J?w("sidebar.newSessionTitle",{path:J}):w("sidebar.selectProject"),onMouseEnter:a=>{J&&(a.currentTarget.style.background="var(--bg-selected)",a.currentTarget.style.color="var(--accent)")},onMouseLeave:a=>{a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color=J?"var(--text-muted)":"var(--text-dim)",a.currentTarget.style.borderColor="var(--border)"},children:(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,d.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]})}),(0,d.jsx)("button",{className:`navigator-icon-action${a2?" is-success":""}`,onClick:()=>be(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:a2?"rgba(74,222,128,0.18)":"var(--bg-hover)",border:`1px solid ${a2?"rgba(74,222,128,0.4)":"var(--border)"}`,color:a2?"#4ade80":"var(--text-muted)",cursor:"pointer",width:32,height:32,borderRadius:7,padding:0,flexShrink:0,transition:"background 0.3s, color 0.3s, border-color 0.3s"},onMouseEnter:a=>{a2||(a.currentTarget.style.background="var(--bg-selected)",a.currentTarget.style.color="var(--accent)")},onMouseLeave:a=>{a2||(a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color="var(--text-muted)",a.currentTarget.style.borderColor="var(--border)")},title:w("sidebar.refresh"),children:a2?(0,d.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"var(--success)",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,d.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,d.jsx)("path",{d:"M3 3v5h5"})]})})]})]})}),X&&!ca&&(0,d.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:bx,style:{margin:"10px 12px 0",minHeight:44,flexShrink:0,border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text)",fontSize:13,fontWeight:600,cursor:"pointer"},children:w("cloudProjects.launch")}),(0,d.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,d.jsxs)("div",{className:"navigator-mode-switcher",role:"toolbar","aria-label":w("navigator.toolbar"),style:{display:"flex",alignItems:"center",gap:2,flex:1,minWidth:0,padding:2,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[s.map(a=>{let b="projects"===a?w("sidebar.projects"):w("navigator.priority"),c=!ca&&ad===a;return(0,d.jsx)("button",{type:"button","aria-label":w("navigator.view",{label:b}),"aria-pressed":c,"aria-controls":`navigator-${a}-panel`,"data-navigator-mode":a,onClick:()=>{br(a),ca&&q?.(!1)},style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:c?"var(--bg-selected)":"transparent",color:c?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:c?600:500,whiteSpace:"nowrap"},children:b},a)}),void 0!==o&&(0,d.jsx)("button",{type:"button","aria-label":w("navigator.view",{label:v("lounge.tab")}),"aria-pressed":ca,"aria-controls":"navigator-lounge-panel","data-navigator-mode":"lounge",onClick:()=>q?.(!ca),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:ca?"var(--bg-selected)":"transparent",color:ca?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:ca?600:500,whiteSpace:"nowrap"},children:v("lounge.tab")})]}),!ca&&"projects"===ad&&(0,d.jsx)("button",{type:"button",onClick:()=>as(a=>!a),disabled:!bO,title:w("sidebar.projectShowHidden"),"aria-label":w("sidebar.projectShowHidden"),"aria-pressed":ar,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:5,background:ar?"var(--bg-selected)":"transparent",color:ar?"var(--accent)":"var(--text-dim)",cursor:bO?"pointer":"default",opacity:bO?1:.45,flexShrink:0},children:(0,d.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,d.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,d.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!ar&&(0,d.jsx)("path",{d:"m4 4 16 16"})]})}),!ca&&"projects"===ad&&(0,d.jsx)("button",{className:"navigator-add-project",type:"button",onClick:bx,title:w("sidebar.addProject"),"aria-label":w("sidebar.addProject"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:a=>{a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color="var(--text)"},onMouseLeave:a=>{a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color="var(--text-muted)"},children:(0,d.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"}),(0,d.jsx)("path",{d:"M15.5 10.5v5M13 13h5"})]})})]}),ca&&o,!ca&&"projects"===ad&&(0,d.jsxs)("label",{className:"navigator-search",style:{position:"relative",display:"block",margin:"0 8px 8px"},children:[(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",style:{position:"absolute",left:10,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,d.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,d.jsx)("path",{d:"m20 20-3.5-3.5"})]}),(0,d.jsx)("input",{className:"navigator-search-input",type:"search",value:aa,onChange:a=>ac(a.target.value),onKeyDown:a=>{"Escape"===a.key&&(a.preventDefault(),ac(""),a.currentTarget.blur())},placeholder:w("sidebar.searchProjectsAndSessions"),"aria-label":w("sidebar.searchProjectsAndSessions"),style:{width:"100%",height:34,padding:"0 10px 0 32px",border:"1px solid var(--border)",borderRadius:7,outline:"none",background:"var(--bg-hover)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})]}),!ca&&"projects"===ad&&(0,d.jsxs)("div",{id:"navigator-projects-panel",className:"navigator-session-list",style:{flex:"1 1 auto",overflowY:"auto",minHeight:80,padding:"0 6px 10px"},children:[(E||!ap)&&(0,d.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:w("sidebar.loading")}),G&&(0,d.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:G}),aB&&(0,d.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:aB}),!E&&ap&&!G&&0===bX.length&&(0,d.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:bV?w("sidebar.noMatchingProjects"):w("sidebar.noSessions")}),!E&&ap&&!G&&b0.map(b=>{let c,e,f;if("temporary"===b.kind)return(0,d.jsx)("div",{className:"navigator-project-group",children:(0,d.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":b_,title:w("sidebar.temporaryProjects"),onClick:()=>au(a=>!a),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:34,padding:"0 6px 0 2px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:[(0,d.jsx)("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,flexShrink:0,color:"var(--text-dim)"},children:(0,d.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:{transform:b_?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.12s"},children:(0,d.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),(0,d.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:w("sidebar.temporaryProjects")}),(0,d.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10,flexShrink:0},children:bZ.length}),ab(b$,w)]})},"navigator-temporary-projects");let{project:g,key:h,name:i,sessions:j,hidden:k}=b.group,l=h===bJ,m=b1.has(i.toLowerCase())&&Q((e=Math.max((c=g.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),c.lastIndexOf("/")))<=0?"":c.slice(0,e),L)||null,n=!ah.has(g)&&!bV,o=af.has(g),p=av===g,q=bN.indexOf(g),r=az||bW||q<=0,s=az||bW||q>=bN.length-1,t=function(a){let b=new Map;for(let c of a)b.set(c.id,{session:c,children:[]});let c=new Map;for(let b of a)b.parentSessionId&&c.set(b.id,b.parentSessionId);let d=[];for(let a of b.values()){let e=function(a){let d=c.get(a),e=new Set;for(;d&&!e.has(d);){if(e.add(d),b.has(d))return d;d=c.get(d)}return null}(a.session.id);e?b.get(e).children.push(a):d.push(a)}let e=a=>{a.sort((a,b)=>b.session.modified.localeCompare(a.session.modified)),a.forEach(a=>e(a.children))};return e(d),d}(o?j:j.slice(0,5)),v=j.length>5;return(0,d.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:n?3:9},children:[(0,d.jsxs)("div",{className:`navigator-project-row${l?" is-selected":""}`,ref:al===g?aZ:void 0,onMouseEnter:()=>ak(g),onMouseLeave:()=>ak(a=>a===g&&al!==g?null:a),style:{display:"flex",alignItems:"center",minHeight:34,position:"relative",borderRadius:6,background:l?"var(--bg-hover)":"transparent",opacity:k?.55:1},children:[(0,d.jsx)("button",{type:"button",onClick:()=>bH(g),title:n?w("sidebar.expandProject"):w("sidebar.collapseProject"),"aria-label":n?w("sidebar.expandProject"):w("sidebar.collapseProject"),"aria-expanded":!n,style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,marginLeft:2,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,d.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:{transform:n?"rotate(-90deg)":"rotate(0deg)",transition:"transform 0.12s"},children:(0,d.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),p?(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px"},children:[(0,d.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--accent)"},children:(0,d.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,d.jsx)("input",{ref:a_,value:ax,onChange:a=>ay(a.target.value),onBlur:()=>void bR(g),onKeyDown:a=>{"Enter"===a.key?(a.preventDefault(),a.currentTarget.blur()):"Escape"===a.key&&(a.preventDefault(),a0.current=!0,aw(null))},"aria-label":w("sidebar.projectAlias"),style:{flex:1,minWidth:0,height:24,padding:"2px 6px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12,fontWeight:600}})]}):(0,d.jsxs)("button",{className:"navigator-project-name",type:"button",onClick:()=>K(g),title:g,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:l?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:l?600:500},children:[(0,d.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:l?"var(--accent)":"var(--text-dim)"},children:(0,d.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,d.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),null===m?null:(0,d.jsx)("span",{style:{flexShrink:2,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:m}),ab(bU.get(h),w)]}),(0,d.jsx)("button",{type:"button",onClick:()=>bB(g),title:w("sidebar.newSessionTitle",{path:g}),"aria-label":w("sidebar.newSessionTitle",{path:g}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:5,background:"transparent",color:"var(--text-dim)",cursor:"pointer",opacity:z||aj===g?1:0,pointerEvents:z||aj===g?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>ak(g),onMouseEnter:a=>{a.currentTarget.style.background="var(--bg-selected)",a.currentTarget.style.color="var(--accent)"},onMouseLeave:a=>{a.currentTarget.style.background="transparent",a.currentTarget.style.color="var(--text-dim)"},children:(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,d.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,d.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,d.jsx)("button",{type:"button",onClick:()=>{am(al===g?null:g),aO(!1),aQ(!1),aU(null),l||K(g)},title:w("sidebar.projectActions"),"aria-label":w("sidebar.projectActions"),"aria-expanded":al===g,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:5,background:al===g?"var(--bg-selected)":"transparent",color:l&&b4&&!b4.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:z||aj===g||al===g?1:0,pointerEvents:z||aj===g||al===g?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>ak(g),children:(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,d.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,d.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,d.jsxs)(S,{open:al===g,style:{position:"absolute",top:"calc(100% + 4px)",right:3,width:"min(260px, calc(100vw - 24px))",zIndex:110,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"var(--shadow-float)",boxSizing:"border-box",overflow:"hidden"},children:[b3&&aL&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("button",{type:"button",onClick:()=>aO(a=>!a),title:b4?w("sidebar.switchWorktreeTitle",{path:b4.path}):w("sidebar.switchWorktree"),"aria-label":w("sidebar.worktrees"),"aria-expanded":aN,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderBottom:aN?"1px solid var(--border)":"none",background:aN?"var(--bg-selected)":"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,d.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,d.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,d.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,d.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,d.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,d.jsx)("span",{style:{flex:1},children:w("sidebar.worktrees")}),(0,d.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("polyline",{points:"4 2.5 8 6 4 9.5"})})]}),(0,d.jsxs)(S,{open:aN,style:{position:"static",width:"auto",zIndex:100,background:"var(--bg)",border:"none",borderTop:"1px solid var(--border)",borderRadius:0,boxShadow:"none",boxSizing:"border-box",overflow:"hidden"},children:[b5&&(0,d.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,d.jsx)("input",{value:aD,onChange:a=>aE(a.target.value),onKeyDown:a=>{"Escape"===a.key&&(aE(""),aO(!1))},placeholder:w("sidebar.filterWorktrees"),autoFocus:!0,style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,d.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[b6.map(a=>{let b=a.path===J||a.isMain&&!aL.worktrees.some(a=>a.path===J);return aX===a.path?(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.06)"},children:[(0,d.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:w("sidebar.forceRemoveCheckout")}),(0,d.jsx)("button",{onClick:()=>void bz(a.path,!0),disabled:aV,style:{padding:"3px 9px",background:"var(--danger)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:w("sidebar.force")}),(0,d.jsx)("button",{onClick:()=>aY(null),style:{padding:"3px 9px",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer",flexShrink:0},children:w("sidebar.cancel")})]},a.path):(0,d.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,d.jsxs)("button",{onClick:()=>{K(a.path),aO(!1),aU(null),aE("")},title:a.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:b?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[b?(0,d.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,d.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,d.jsx)("span",{style:{width:10,flexShrink:0}}),(0,d.jsx)(R,{text:a.branch??Q(a.path,L),style:{flex:1}}),a.isMain&&(0,d.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:w("sidebar.main")})]}),!a.isMain&&(0,d.jsx)("button",{onClick:()=>void bz(a.path,!1),disabled:aV,title:w("sidebar.removeWorktreeTitle",{path:a.path}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:34,height:28,padding:0,marginRight:4,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",borderRadius:5,flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:a=>{a.currentTarget.style.color="#ef4444",a.currentTarget.style.background="rgba(239,68,68,0.08)"},onMouseLeave:a=>{a.currentTarget.style.color="var(--text-dim)",a.currentTarget.style.background="none"},children:(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,d.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,d.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,d.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},a.path)}),b5&&0===b6.length&&aD.trim()&&(0,d.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:w("sidebar.noMatchingWorktrees")})]}),aP?(0,d.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,d.jsx)("input",{ref:a$,value:aR,onChange:a=>{aS(a.target.value),aU(null)},onKeyDown:a=>{"Enter"===a.key&&(a.preventDefault(),by()),"Escape"===a.key&&(aQ(!1),aS(""),aU(null))},placeholder:w("sidebar.branchName"),style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}}),(0,d.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,d.jsx)("button",{onClick:()=>void by(),disabled:aV||!aR.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:aV||!aR.trim()?"not-allowed":"pointer",opacity:aV||!aR.trim()?.65:1},children:aV?w("sidebar.creating"):w("sidebar.create")}),(0,d.jsx)("button",{onClick:()=>{aQ(!1),aS(""),aU(null)},style:{flex:1,padding:"4px 0",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer"},children:w("sidebar.cancel")})]})]}):(0,d.jsxs)("button",{onClick:a=>{a.stopPropagation(),aQ(!0),aU(null),setTimeout(()=>a$.current?.focus(),0)},title:w("sidebar.createWorktreeTitle"),style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,d.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,d.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,d.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,d.jsx)("span",{children:w("sidebar.newWorktree")})]}),aT&&(0,d.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:aT})]})]}),(0,d.jsxs)("button",{type:"button",disabled:az,onClick:()=>{let a;return a=bK.get(u(g))?.alias??"",void(a0.current=!1,aC(null),ay(a),aw(g),bP())},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:az?"default":"pointer",textAlign:"left",fontSize:11,opacity:az?.55:1},children:[(0,d.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,d.jsx)("path",{d:"m4 20 4.5-1 10-10a2.1 2.1 0 0 0-3-3l-10 10L4 20Z"}),(0,d.jsx)("path",{d:"m13.5 8 3 3"})]}),w(bK.get(u(g))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,d.jsxs)("button",{type:"button",disabled:r,title:bW?w("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void bS(g,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:r?"default":"pointer",textAlign:"left",fontSize:11,opacity:r?.55:1},children:[(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m6 15 6-6 6 6"})}),w("sidebar.projectMoveUp")]}),(0,d.jsxs)("button",{type:"button",disabled:s,title:bW?w("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void bS(g,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:s?"default":"pointer",textAlign:"left",fontSize:11,opacity:s?.55:1},children:[(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m6 9 6 6 6-6"})}),w("sidebar.projectMoveDown")]}),(0,d.jsxs)("button",{type:"button",disabled:az,onClick:()=>void bQ(g,!k),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:az?"default":"pointer",textAlign:"left",fontSize:11,opacity:az?.55:1},children:[(0,d.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,d.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,d.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!k&&(0,d.jsx)("path",{d:"m4 4 16 16"})]}),w(k?"sidebar.projectUnhide":"sidebar.projectHide")]}),(f=0===b9(bT.get(h)??[])||bi,(0,d.jsxs)("button",{type:"button",disabled:f,onClick:()=>{bP(),bl(null),bh({kind:"project",project:g,label:i})},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:f?"default":"pointer",textAlign:"left",fontSize:11,opacity:f?.55:1},children:[(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),w("sidebar.clearProjectSessions")]}))]})]})]}),!n&&0===j.length&&l&&(0,d.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:w("sidebar.noSessions")}),!n&&t.length>0&&(0,d.jsx)("div",{style:{paddingLeft:12},children:t.map(b=>(0,d.jsx)($,{node:b,selectedSessionId:a,runningSessionIds:a4,unreadSessionIds:a6,pinnedSessionIds:a8,onSelectSession:bA,onTogglePinnedSession:bs,onRenamed:be,onSessionDeleted:bf,onSessionArchived:bq,depth:0},b.session.id))}),!n&&v&&(0,d.jsx)("button",{type:"button",onClick:()=>{ag(a=>{let b=new Set(a);return b.has(g)?b.delete(g):b.add(g),b})},style:{display:"block",margin:"3px 0 3px 32px",padding:"5px 8px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:o?w("sidebar.showLess"):w("sidebar.showMore")})]},g)})]}),!ca&&(0,d.jsx)(Z,{refreshKey:bo,selectedSessionId:a,onSelectSession:bA,onRestored:bq}),!ca&&"priority"===ad&&(0,d.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[E&&(0,d.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:w("sidebar.loading")}),G&&(0,d.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:G}),!E&&!G&&(r=b9(b2.flatMap(a=>a.sessions)),(0,d.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"8px 2px 2px"},children:[(0,d.jsx)("button",{type:"button",disabled:bC,onClick:()=>void bG(),title:w("sidebar.newScratchSessionTitle"),style:P(bC,z),children:w("sidebar.newScratchSession")}),b2.length>0&&(0,d.jsx)("button",{type:"button",disabled:0===r||bi,onClick:()=>{bl(null),bh({kind:"priority"})},style:P(0===r||bi,z),children:w("sidebar.clearPriorityList")})]})),bE&&(0,d.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:bE}),!E&&!G&&0===b2.length&&(0,d.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:w("sidebar.noSessions")}),!E&&!G&&b2.map((b,c)=>(0,d.jsxs)("section",{"aria-labelledby":`priority-group-${b.key}`,children:[(0,d.jsx)("h2",{id:`priority-group-${b.key}`,style:{margin:0,padding:0===c?"2px 8px 4px":"14px 8px 4px",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:b.label}),b.sessions.map(b=>(0,d.jsx)(Y,{session:b,selected:b.id===a,running:a4.has(b.id),unread:a6.has(b.id),pinned:a8.has(b.id),onSelect:bA,onTogglePin:bs},b.id))]},b.key))]})]})}function W({scope:a,eligible:b,runningExcluded:c,busy:f,error:g,onCancel:h,onConfirm:i}){let{t:j}=(0,x.s)(),k=f||0===b,l=(0,e.useRef)(null),m=(0,e.useRef)(null);return(0,e.useRef)(f).current=f,(0,e.useRef)(h).current=h,(0,d.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:a=>{f||a.target!==a.currentTarget||h()},children:(0,d.jsxs)("div",{ref:l,role:"alertdialog","aria-modal":"true","aria-labelledby":"bulk-clear-title","aria-describedby":"bulk-clear-body",tabIndex:-1,style:{width:420,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"var(--shadow-float)",overflow:"hidden"},children:[(0,d.jsxs)("div",{style:{padding:"18px 18px 14px"},children:[(0,d.jsx)("div",{id:"bulk-clear-title",style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:j("sidebar.clearSessionsTitle")}),(0,d.jsxs)("div",{id:"bulk-clear-body",style:{marginTop:8,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,overflowWrap:"anywhere"},children:["project"===a.kind?j("sidebar.clearSessionsProjectBody",{project:a.label,count:b}):j("sidebar.clearSessionsPriorityBody",{count:b}),c>0&&(0,d.jsx)("div",{style:{marginTop:6},children:j("sidebar.clearSessionsRunningExcluded",{count:c})}),0===b&&(0,d.jsx)("div",{style:{marginTop:6},children:j("sidebar.clearSessionsNone")})]}),g&&(0,d.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:g})]}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,d.jsx)("button",{ref:m,type:"button",onClick:h,disabled:f,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:f?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:j("sidebar.clearSessionsCancel")}),(0,d.jsx)("button",{type:"button",onClick:i,disabled:k,"aria-busy":f,style:{minHeight:36,padding:"0 14px",border:"1px solid var(--danger)",borderRadius:"var(--radius-control)",background:"transparent",color:k?"var(--text-dim)":"var(--danger)",cursor:k?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:j(f?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function X({filled:a=!1}){return(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:a?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M12 17v5"}),(0,d.jsx)("path",{d:"M5 17h14"}),(0,d.jsx)("path",{d:"M6 3h12l-1 8 2 3H5l2-3-1-8z"})]})}function Y({session:a,selected:b,running:c,unread:e,pinned:f,onSelect:g,onTogglePin:h}){let{t:i}=(0,x.s)(),j=(a.name||a.firstMessage||a.id.slice(0,8)).replace(/\s+/g," ").trim(),k=a.cwd.split(/[\\/]/).filter(Boolean).at(-1)??"";return(0,d.jsxs)("div",{className:`priority-session-row${b?" is-selected":""}${c?" is-running":""}${e?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:5,background:b?"var(--bg-selected)":"transparent"},children:[(0,d.jsxs)("button",{type:"button","aria-current":b?"page":void 0,onClick:()=>g(a),title:`${j}
|
|
2
2
|
${a.cwd}
|
|
3
3
|
${new Date(a.modified).toLocaleString()}`,style:{minWidth:0,flex:1,display:"block",padding:"7px 8px",border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,d.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[(0,d.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12.5,fontWeight:500,lineHeight:1.4},children:j}),c&&(0,d.jsx)(_,{}),!c&&e&&(0,d.jsx)(aa,{})]}),(0,d.jsx)("span",{style:{display:"block",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:k})]}),(0,d.jsx)("button",{type:"button","aria-pressed":f,"aria-label":i(f?"sidebar.unpin":"sidebar.pin"),title:i(f?"sidebar.unpin":"sidebar.pin"),onClick:()=>h(a.id),style:{width:30,border:"none",background:"transparent",color:f?"var(--accent)":"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,d.jsx)(X,{filled:f})})]})}function Z({refreshKey:a,selectedSessionId:b,onSelectSession:c,onRestored:f}){let{t:g}=(0,x.s)(),[h,i]=(0,e.useState)(!1),[j,k]=(0,e.useState)([]),l=(0,e.useCallback)(async(a,b)=>{a.stopPropagation();try{await fetch(`/api/sessions/${encodeURIComponent(b)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:!1})}),f(b)}catch{}},[f]);return 0!==j.length||h?(0,d.jsxs)("section",{style:{borderTop:"1px solid var(--border)",marginTop:4},children:[(0,d.jsxs)("button",{type:"button",onClick:()=>i(a=>!a),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"7px 12px",background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:600,textAlign:"left"},children:[(0,d.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:h?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.1s"},children:(0,d.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})}),g("sidebar.archived")," (",j.length,")"]}),h&&(0,d.jsxs)("div",{style:{paddingLeft:12},children:[0===j.length&&(0,d.jsx)("div",{style:{padding:"4px 12px 8px 20px",color:"var(--text-dim)",fontSize:11},children:g("sidebar.noArchivedSessions")}),j.map(a=>{let e=w(a.firstMessage)??a.firstMessage,f=a.name||e.slice(0,50)||a.id.slice(0,12);return(0,d.jsxs)("div",{onClick:()=>c(a),style:{height:40,display:"flex",alignItems:"center",paddingLeft:20,paddingRight:4,gap:4,cursor:"pointer",overflow:"hidden",borderLeft:a.id===b?"2px solid var(--accent)":"2px solid transparent",background:a.id===b?"var(--bg-selected)":"transparent"},children:[(0,d.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:f}),(0,d.jsx)("button",{onClick:b=>l(b,a.id),title:g("sidebar.restore"),style:{display:"flex",alignItems:"center",justifyContent:"center",height:24,padding:"0 8px",flexShrink:0,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:500},children:g("sidebar.restore")})]},a.id)})]})]}):null}function $({node:a,selectedSessionId:b,runningSessionIds:c,unreadSessionIds:f,pinnedSessionIds:g,onSelectSession:h,onRenamed:i,onSessionDeleted:j,onTogglePinnedSession:k,onSessionArchived:l,depth:m}){let[n,o]=(0,e.useState)(!1),p=a.children.length>0;return(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{style:{position:"relative"},children:[m>0&&(0,d.jsx)("div",{style:{position:"absolute",left:10*m+6,top:0,bottom:0,width:1,background:"var(--border)",pointerEvents:"none"}}),(0,d.jsx)(ac,{session:a.session,isSelected:a.session.id===b,isRunning:c.has(a.session.id),isUnread:f.has(a.session.id),isPinned:g.has(a.session.id),onClick:()=>h(a.session),onTogglePin:()=>k(a.session.id),onRenamed:i,onDeleted:a=>j?.(a),onArchived:a=>l?.(a),depth:m,hasChildren:p,collapsed:n,onToggleCollapse:()=>o(a=>!a)})]}),p&&!n&&(0,d.jsx)("div",{children:a.children.map(a=>(0,d.jsx)($,{node:a,selectedSessionId:b,runningSessionIds:c,unreadSessionIds:f,pinnedSessionIds:g,onSelectSession:h,onTogglePinnedSession:k,onRenamed:i,onSessionDeleted:j,onSessionArchived:l,depth:m+1},a.session.id))})]})}function _(){let{t:a}=(0,x.s)();return(0,d.jsx)("span",{title:a("sidebar.agentRunning"),"aria-label":a("sidebar.agentRunning"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,d.jsx)("svg",{className:"session-running-spinner",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,d.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})})})}function aa(){let{t:a}=(0,x.s)();return(0,d.jsx)("span",{title:a("sidebar.newActivity"),"aria-label":a("sidebar.newSessionActivity"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",style:{display:"block"},children:[(0,d.jsx)("circle",{cx:"7",cy:"7",r:"2.5",fill:"currentColor"}),(0,d.jsx)("circle",{className:"session-unread-ring",cx:"7",cy:"7",r:"3",stroke:"currentColor",strokeWidth:"1.4"})]})})}function ab(a,b){return a&&(0!==a.running||0!==a.unread)?(0,d.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,flexShrink:0,marginLeft:6},children:[a.running>0&&(0,d.jsxs)("span",{title:b("sidebar.agentRunning"),"aria-label":`${b("sidebar.agentRunning")} (${a.running})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,d.jsx)("svg",{className:"session-running-spinner",width:"10",height:"10",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,d.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})}),a.running]}),a.unread>0&&(0,d.jsxs)("span",{title:b("sidebar.newSessionActivity"),"aria-label":`${b("sidebar.newSessionActivity")} (${a.unread})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,d.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"currentColor",display:"inline-block"}}),a.unread]})]}):null}function ac({session:a,isSelected:b,isRunning:c,isUnread:f,isPinned:g,onClick:h,onTogglePin:i,onRenamed:j,onDeleted:k,onArchived:l,depth:m=0,hasChildren:n=!1,collapsed:o=!1,onToggleCollapse:p}){let{t:q}=(0,x.s)(),[r,s]=(0,e.useState)(!1),[t,u]=(0,e.useState)(!1),[v,y]=(0,e.useState)(""),[z,A]=(0,e.useState)(!1),[B,C]=(0,e.useState)(!1),D=(0,e.useRef)(null),E=w(a.firstMessage)??a.firstMessage,F=a.name||E.slice(0,50)||a.id.slice(0,12),G=(0,e.useCallback)(b=>{b.stopPropagation(),a.transient||(y(a.name||E.slice(0,50)||a.id.slice(0,12)),u(!0))},[a.name,a.transient,E,a.id]),H=(0,e.useCallback)(async()=>{let b=v.trim();if(u(!1),v!==F&&b!==(a.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(a.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:b})}),j?.()}catch{}},[v,a.id,a.name,j,F]),I=(0,e.useCallback)(async()=>{if(!a.transient){A(!1),C(!0);try{await fetch(`/api/sessions/${encodeURIComponent(a.id)}`,{method:"DELETE"}),k?.(a.id)}catch{C(!1)}}},[a.id,a.transient,k]),J=(0,e.useCallback)(async b=>{if(b.stopPropagation(),!a.transient)try{await fetch(`/api/sessions/${encodeURIComponent(a.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:!0})}),l?.(a.id)}catch{}},[a.id,a.transient,l]),K=(0,e.useCallback)(a=>{a.stopPropagation(),a.shiftKey?I():A(!0)},[I]),L=(0,e.useCallback)(a=>{a.stopPropagation(),I()},[I]),M=(0,e.useCallback)(a=>{a.stopPropagation(),A(!1)},[]),N=(0,e.useCallback)(b=>{(function(a,b=window){let c=new CustomEvent("pi-web:session-row-contextmenu",{cancelable:!0,detail:a});return!b.dispatchEvent(c)})({id:a.id,path:a.path,cwd:a.cwd,name:a.name,clientX:b.clientX,clientY:b.clientY,refresh:()=>{j?.()}})&&(b.preventDefault(),b.stopPropagation())},[j,a.cwd,a.id,a.name,a.path]);return(0,d.jsx)("div",{className:`navigator-session-row${b?" is-selected":""}${c?" is-running":""}${f?" is-unread":""}${z?" is-confirming":""}`,onClick:z||t?void 0:h,onContextMenu:z||t?void 0:N,onMouseEnter:()=>s(!0),onMouseLeave:()=>{s(!1)},style:{height:40,display:"flex",alignItems:"center",paddingLeft:m>0?10*m+8:8,paddingRight:4,cursor:z||t?"default":"pointer",background:b?"var(--bg-selected)":r?"var(--bg-hover)":"transparent",borderLeft:"2px solid transparent",transition:"background 0.1s",opacity:B?.5:1,gap:4,overflow:"hidden"},children:z?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:q("sidebar.deleteSession",{title:F.slice(0,22)+(F.length>22?"…":"")})}),(0,d.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,d.jsxs)("button",{onClick:L,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,height:30,padding:"0 11px",background:"var(--danger)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap"},children:[(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,d.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,d.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,d.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),q("sidebar.delete")]}),(0,d.jsx)("button",{onClick:M,style:{display:"flex",alignItems:"center",justifyContent:"center",height:30,padding:"0 11px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:500,whiteSpace:"nowrap"},children:q("sidebar.cancel")})]})]}):t?(0,d.jsx)("input",{ref:D,value:v,onChange:a=>y(a.target.value),onBlur:H,onKeyDown:a=>{"Enter"===a.key&&H(),"Escape"===a.key&&u(!1)},autoFocus:!0,style:{flex:1,fontSize:12,padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",height:30}}):(0,d.jsxs)(d.Fragment,{children:[m>0&&(0,d.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,d.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,d.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,d.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,d.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,d.jsxs)("button",{type:"button",onClick:a=>{a.stopPropagation(),h()},"aria-current":b?"page":void 0,title:F,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,color:"var(--text)",fontSize:12.5,fontWeight:b?500:400,lineHeight:1.35,padding:0,border:"none",background:"transparent",fontFamily:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,d.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:F}),c&&(0,d.jsx)(_,{}),!c&&f&&(0,d.jsx)(aa,{}),a.worktreeBranch&&(0,d.jsx)("span",{title:q("sidebar.worktreePath",{path:a.cwd}),style:{display:"flex",color:"var(--accent)",flexShrink:0},children:(0,d.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,d.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,d.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,d.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})})]}),n&&(0,d.jsx)("button",{onClick:a=>{a.stopPropagation(),p?.()},title:q(o?"sidebar.expandForks":"sidebar.collapseForks"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",transform:o?"rotate(-90deg)":"none",transition:"transform 0.15s"},children:(0,d.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),!a.transient&&(0,d.jsxs)("div",{style:{display:"flex",gap:4,flexShrink:0},children:[(0,d.jsx)("button",{onClick:a=>{a.stopPropagation(),i?.()},title:q(g?"sidebar.unpin":"sidebar.pin"),"aria-label":q(g?"sidebar.unpin":"sidebar.pin"),"aria-pressed":g,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:g?"var(--bg-selected)":"transparent",border:"none",borderRadius:5,color:g?"var(--accent)":"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:r||g?1:0,pointerEvents:r||g?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>s(!0),children:(0,d.jsx)(X,{filled:g})}),(0,d.jsx)("button",{onClick:G,title:q("sidebar.rename"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:+!!r,pointerEvents:r?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>s(!0),onMouseEnter:a=>{a.currentTarget.style.background="var(--bg-selected)",a.currentTarget.style.color="var(--accent)"},onMouseLeave:a=>{a.currentTarget.style.background="transparent",a.currentTarget.style.color="var(--text-muted)",a.currentTarget.style.borderColor="transparent"},children:(0,d.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),(0,d.jsx)("button",{onClick:J,title:q("sidebar.archive"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:a=>{a.currentTarget.style.background="var(--bg-selected)",a.currentTarget.style.color="var(--accent)"},onMouseLeave:a=>{a.currentTarget.style.background="transparent",a.currentTarget.style.color="var(--text-muted)"},children:(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("rect",{x:"3",y:"4",width:"18",height:"4",rx:"1"}),(0,d.jsx)("path",{d:"M5 8v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"}),(0,d.jsx)("path",{d:"M10 12h4"})]})}),(0,d.jsx)("button",{onClick:K,title:q("sidebar.deleteWithShiftClick"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:+!!r,pointerEvents:r?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>s(!0),onMouseEnter:a=>{a.currentTarget.style.background="rgba(239,68,68,0.08)",a.currentTarget.style.color="#ef4444",a.currentTarget.style.borderColor="rgba(239,68,68,0.35)"},onMouseLeave:a=>{a.currentTarget.style.background="transparent",a.currentTarget.style.color="var(--text-muted)",a.currentTarget.style.borderColor="transparent"},children:(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,d.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,d.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,d.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]})]})})}let ad=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,ae=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,af=/\x1B\[([0-9;]*)m/g,ag=/\x1B_pi:c\x07/g,ah=["#1f2937","#dc2626","#16a34a","#d97706","#2563eb","#9333ea","#0891b2","#6b7280"],ai=["#9ca3af","#ef4444","#22c55e","#f59e0b","#3b82f6","#a855f7","#06b6d4","#e5e7eb"];function aj(a){return a.replace(ag,"").replace(ad,"")}function ak(a){let b=[],c=0;for(;c<a.length;){if(27===a.charCodeAt(c)){let b=a.slice(c).match(ae);if(b){c+=b[0].length;continue}}let d=a.codePointAt(c);if(void 0===d)break;let e=String.fromCodePoint(d);b.push({start:c,end:c+e.length,char:e}),c+=e.length}return b}function al(a,b){let c=ak(a)[b];return c?a.slice(0,c.start)+a.slice(c.end):a}function am(a){return ak(a)[0]?.char}function an(a){let b=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,c=[];for(let d of a){let a=d.replace(ag,""),e=aj(a).trimEnd();if(b.test(e))continue;let f=a,g=am(f);("│"===g||"┃"===g)&&" "===am(f=al(f,0))&&(f=al(f,0));let h=function(a){let b=ak(a);for(let a=b.length-1;a>=0;a--)if(""!==b[a].char.trim())return a;return -1}(f),i=h>=0?ak(f)[h]?.char:void 0;("│"===i||"┃"===i)&&(f=al(f,h)),c.push(function(a){let b=a;for(;;){let a=ak(b),c=a[a.length-1];if(!c||""!==c.char.trim())return b;b=b.slice(0,c.start)+b.slice(c.end)}}(f))}for(;c.length>0&&""===aj(c[0]).trim();)c.shift();for(;c.length>0&&""===aj(c[c.length-1]).trim();)c.pop();return c.length?c:a}function ao(a){let b,c=[],d={},e=0;for(af.lastIndex=0;null!==(b=af.exec(a));)b.index>e&&c.push({text:a.slice(e,b.index),style:d}),d=function(a,b){let c={...a};for(let a=0;a<b.length;a++){let d=b[a];if(0===d)for(let a of Object.keys(c))delete c[a];else if(1===d)c.fontWeight=700;else if(2===d)c.opacity=.65;else if(3===d)c.fontStyle="italic";else if(4===d)c.textDecoration="underline";else if(22===d)delete c.fontWeight,delete c.opacity;else if(23===d)delete c.fontStyle;else if(24===d)delete c.textDecoration;else if(39===d)delete c.color;else if(49===d)delete c.backgroundColor;else if(d>=30&&d<=37)c.color=ah[d-30];else if(d>=90&&d<=97)c.color=ai[d-90];else if(d>=40&&d<=47)c.backgroundColor=ah[d-40];else if(d>=100&&d<=107)c.backgroundColor=ai[d-100];else if((38===d||48===d)&&2===b[a+1]){let[e,f,g]=[b[a+2],b[a+3],b[a+4]];[e,f,g].every(a=>"number"==typeof a&&Number.isFinite(a))&&(38===d?c.color=`rgb(${e}, ${f}, ${g})`:c.backgroundColor=`rgb(${e}, ${f}, ${g})`),a+=4}else if((38===d||48===d)&&5===b[a+1]){let e=function(a){if(a>=0&&a<8)return ah[a];if(a>=8&&a<16)return ai[a-8];if(a>=16&&a<=231){let b=a-16,c=Math.floor(b/36),d=Math.floor(b%36/6),e=a=>0===a?0:55+40*a;return`rgb(${e(c)}, ${e(d)}, ${e(b%6)})`}if(a>=232&&a<=255){let b=8+(a-232)*10;return`rgb(${b}, ${b}, ${b})`}}(b[a+2]);e&&(38===d?c.color=e:c.backgroundColor=e),a+=2}}return c}(d,b[1]?b[1].split(";").map(a=>Number(a||"0")):[0]),e=b.index+b[0].length;return e<a.length&&c.push({text:a.slice(e),style:d}),c}let ap={ArrowUp:"\x1b[A",ArrowDown:"\x1b[B",ArrowRight:"\x1b[C",ArrowLeft:"\x1b[D",Home:"\x1b[H",End:"\x1b[F",Insert:"\x1b[2~",Delete:"\x1b[3~",PageUp:"\x1b[5~",PageDown:"\x1b[6~",Escape:"\x1b",Backspace:""},aq={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"},ar={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"},as={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",webm:"audio/webm"};function at(a){return(a.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function au(a){return null!==(ar[at(a)]??null)}function av(a,b,c={}){let d={...a,content:b};return c.omitUsage&&(d.usage=void 0),d}function aw(a,b={}){return!!b.hideThinking&&"thinking"===a.type||function(a,b={}){return"thinking"===a.type&&!a.deferred&&!b.isStreaming&&""===a.thinking.trim()}(a,b)}function ax(a,b={}){return b.isStreaming||"error"!==a.stopReason?null:a.errorMessage?.trim()||"Unknown provider error"}function ay(a,b={}){let c=[];for(let d of function(a,b={}){return(a.content??[]).filter(a=>!aw(a,b))}(a,b)){let a="image"===d.type||"text"===d.type&&d.text.trim().length>0?"answer":"process",b=c[c.length-1];b?.kind===a?b.blocks.push(d):c.push({kind:a,blocks:[d]})}return c}function az(a){return a.filter(a=>"toolCall"===a.type).length}function aA(a,b,c){let d=new URLSearchParams({sessionId:a,toolCallId:b});return void 0!==c&&d.set("index",String(c)),`/api/tool-image?${d}`}function aB(a){let b=new Map;for(let c of a)"toolResult"===c.role&&b.set(c.toolCallId,c);let c=[],d=-1;return{collect(a,e){for(let f of e)"toolCall"===f.type&&function(a,b){if(!b||b.isError)return!1;if(b.content?.some(a=>"image"===a.type))return!0;let c=a.input??{};return"generate_image"===a.toolName||("write"===a.toolName?"xd://generate_image"===c.path:"read"===a.toolName&&"string"==typeof c.path&&au(c.path))}(f,b.get(f.toolCallId))&&(c.push({type:"image",source:{type:"url",url:""},toolImage:{toolCallId:f.toolCallId}}),d=a)},attach(a){if(0===c.length)return a;let b=[...c,...a];return c=[],b},takeRemaining(){if(0===c.length)return null;let a={idx:d,blocks:c};return c=[],a}}}let aC=new Map,aD="command",aE="autolearn-saved";function aF(a){return"custom"===a.role&&(a.customType===aD||a.customType===aE&&!1!==a.display)}let aG="local-command:";function aH(a){return a?.startsWith(aG)===!0}function aI(a,b,c){let d=new Set(c.map(a=>a.message)),e=[],f=[];for(let c=0;c<a.length;c++){let g=c<b.length;!(d.has(a[c])||g&&aH(b[c]))&&(e.push(a[c]),g&&f.push(b[c]))}for(let a of c){let b=0;if(null!==a.baseEntryId){let c=f.indexOf(a.baseEntryId);if(-1===c)continue;b=c+1}let c=a.message.timestamp??0;for(;b<e.length;){let a=e[b];if(!d.has(a)&&"number"==typeof a.timestamp&&a.timestamp>c)break;b+=1}e.splice(b,0,a.message),b<=f.length&&f.splice(b,0,a.entryId)}return{messages:e,entryIds:f}}function aJ(a){return"user"===a.role||"custom"===a.role&&"compaction"===a.customType}let aK={create:!0,update:!0};function aL(a){return"string"==typeof a?a.replace(/\s+/g," ").trim():""}function aM(a){if("string"==typeof a)return a;if(!Array.isArray(a))return"";let b=[];for(let c of a)c&&"object"==typeof c&&"type"in c&&"text"===c.type&&"text"in c&&"string"==typeof c.text&&b.push(c.text);return b.join("\n")}function aN(a){try{return decodeURIComponent(a)}catch{return a}}function aO(a){return/^[a-zA-Z]:[\\/]/.test(a)||a.startsWith("\\\\")?a.replace(/\\/g,"/"):a}function aP(a){let b=aO(a),c=/^[a-zA-Z]:\//.test(b),d=b.startsWith("//"),e=b.startsWith("/")&&!c&&!d,f=[];for(let a of b.split("/"))if(a&&"."!==a){if(".."===a){f.length>0&&".."!==f[f.length-1]?f.pop():e||c||d||f.push(a);continue}f.push(a)}let g=f.join("/");return c?g:d?`//${g}`:e?`/${g}`:g}function aQ(a,b,c=b){let d,e,f,g,h;if(!a)return null;let i=a.split("#",1)[0].split("?",1)[0].trim();if(!i)return null;let j=null,k=null,l=aN(i),m=l.startsWith("\\\\"),n=aO(l),o=n.toLowerCase();if(o.startsWith("/api/")||o.startsWith("/_next/")||!m&&n.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(n)&&!o.startsWith("file:")&&!/^[a-zA-Z]:\//.test(n))return null;if(o.startsWith("file:")?k=(j=function(a){try{let b=new URL(a);if("file:"!==b.protocol)return null;let c=aN(b.pathname);if(b.hostname)return`//${b.hostname}${c.startsWith("/")?c:`/${c}`}`;if(/^\/[a-zA-Z]:\//.test(c))return c.slice(1);return c}catch{return null}}(n))?"absolute":null:/^[a-zA-Z]:\//.test(n)||n.startsWith("/")?(j=n,k="absolute"):b&&!(n.startsWith("#")||n.startsWith("?"))&&(n.startsWith("./")||n.startsWith("../")||n.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(n))&&(j=`${aO(b).replace(/\/+$/,"")}/${n}`,k="relative"),!j)return null;let p=aP(j).replace(/:\d+(?::\d+)?$/,"");return"relative"===k&&c&&(d=aP(p).replace(/\/+$/,""),e=aP(c).replace(/\/+$/,""),g=(f=/^[a-zA-Z]:\//.test(d)||/^[a-zA-Z]:\//.test(e))?d.toLowerCase():d,!(g===(h=f?e.toLowerCase():e)||g.startsWith(`${h}/`)))?null:p}function aR(a,b,c){let d=new Set,e=[];for(let f of a){if("toolCall"!==f.type||!function(a){let b,c;return"write"===(b=a.toLowerCase())||b.startsWith("write_")||b.endsWith(".write")||b.endsWith("_write")||"edit"===(c=a.toLowerCase())||c.startsWith("edit_")||c.endsWith(".edit")||c.endsWith("_edit")||c.includes("str_replace")||c.includes("replace_editor")}(f.toolName))continue;let a=b?.get(f.toolCallId);if(!a||a.isError)continue;let g=function(a){if(!a)return null;let b=a.file_path??a.path;return"string"==typeof b&&b.length>0?b:null}(f.input);if(!g||!/^[a-zA-Z]:[\\/]/.test(g)&&/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(g))continue;let h=function(a,b){let c;if(!a)return null;let d=/^[a-zA-Z]:[\\/]/.test(a)||a.startsWith("\\\\")||void 0!==b&&(/^[a-zA-Z]:[\\/]/.test(b)||b.startsWith("\\\\")),e=a=>d?a.replace(/\\/g,"/"):a,f=e(a),g=b?e(b).replace(/\/+$/,""):void 0,h=/^[a-zA-Z]:\//.test(f),i=f.startsWith("//");if(h||i)c=f;else if(f.startsWith("/")){let a=g?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??g?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];c=a?`${a}${f}`:f}else{if(!g)return null;c=`${g}/${f}`}return aP(c)}(g,c);h&&(d.has(h)||(d.add(h),e.push({filePath:h})))}return e}function aS(a,b){var c;let d;if(b){let a=b.details,c=a&&"object"==typeof a&&"phases"in a?a.phases:void 0;if(!Array.isArray(c))return{kind:"unknown"};let{phases:d,malformed:e}=function(a){let b=[];for(let c of a){if(!c||"object"!=typeof c||!("name"in c)||!("tasks"in c))return{phases:b,malformed:!0};let{name:a,tasks:d}=c;if("string"!=typeof a||!Array.isArray(d))return{phases:b,malformed:!0};let e=Array.isArray(d)?d.flatMap(a=>{if(!a||"object"!=typeof a||!("content"in a)||!("status"in a))return[];let{content:b,status:c}=a;return"string"!=typeof b||"pending"!==c&&"in_progress"!==c&&"completed"!==c&&"abandoned"!==c&&"blocked"!==c?[]:[{content:b,status:c,blocker:"blocker"in a&&"string"==typeof a.blocker?a.blocker:void 0}]}):[];if(e.length!==d.length)return{phases:b,malformed:!0};e.length>0&&b.push({name:a,tasks:e})}return{phases:b,malformed:!1}}(c);return e?{kind:"unknown"}:{kind:"authoritative",phases:d}}let e=Array.isArray(d=(c=a.input)&&"object"==typeof c&&"list"in c?c.list:void 0)?d.flatMap(a=>{if(!a||"object"!=typeof a||!("phase"in a)||!("items"in a))return[];let{phase:b,items:c}=a;if("string"!=typeof b||!Array.isArray(c))return[];let d=c.filter(a=>"string"==typeof a).map(a=>({content:a,status:"pending"}));return d.length>0?[{name:b,tasks:d}]:[]}):[];return e.length>0?{kind:"preview",phases:e}:{kind:"unknown"}}var aT=c(26744),aU=c(74042),aV=c(98051);function aW(a){return/^[a-zA-Z]:[\\/]/.test(a)||a.startsWith("\\\\")?a.replace(/\\/g,"/"):a}function aX(a){return aW(a).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function aY(a){let b=aW(a).replace(/\/+$/,"");return b.split("/").pop()??b}function aZ(a,b){if(!b)return a;let c=aW(a),d=aW(b).replace(/\/$/,"");return c.startsWith(d+"/")?c.slice(d.length+1):a}var a$=c(61003),a_=c(99773),a0=c(62344),a1=c(1358),a2=c(4014),a3=c(38368),a4=c(33972);let a5={...a0.j,attributes:{...a0.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},strip:[...a0.j.strip||[],"iframe","object","style","form"]};function a6(a){let b=a.includes("\r\n")?"\r\n":"\n",c=a.split(/\r?\n/),d=[],e=null,f=0,g=null,h=new Map;for(let a=0;a<c.length;a++){var i;let b=c[a];if(g){d.push(b),RegExp(`</${g}\\s*>`,"i").test(b)&&(g=null);continue}let j=b.match(/^ {0,3}(`{3,}|~{3,})/);if(j){let a=j[1][0],c=j[1].length;e?a===e.marker&&c>=e.size&&(e=null):e={marker:a,size:c},f=0,d.push(b);continue}if(e){d.push(b);continue}let k=b.match(/<(code|pre|script|style)\b/i);if(k){let a=k[1].toLowerCase(),c=b.slice((k.index??0)+k[0].length);RegExp(`</${a}\\s*>`,"i").test(c)||(g=a),f=0,d.push(b);continue}if(/^(?: {4}|\t)/.test(b)||""===b.trim()){f=0,d.push(b);continue}if(f||b.includes("`")){f=function(a,b){let c=b;for(let b=0;b<a.length;){if("`"!==a[b]){b++;continue}let d=b+1;for(;"`"===a[d];)d++;let e=d-b;0===c?c=e:e===c&&(c=0),b=d}return c}(b,f),d.push(b);continue}let l=b.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(l){let a=l[2].trim();if(a){d.push(`${l[1]}$$`,`${l[1]}${a}`,`${l[1]}$$`);continue}}let m=b.match(/^([ ]{0,3})\\\[[ \t]*$/);if(m){let b=function(a,b){for(let c=b;c<a.length;c++){let b=a[c];if(/^ {0,3}\\\][ \t]*$/.test(b))return c;if(/^ {0,3}(`{3,}|~{3,})/.test(b)||/^ {0,3}\\\[[ \t]*$/.test(b)||/<(code|pre|script|style)\b/i.test(b))break}return -1}(c,a+1);if(-1!==b){d.push(`${m[1]}$$`,...c.slice(a+1,b).map(a=>a8(a,m[1])),`${m[1]}$$`),a=b;continue}}let n=b.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \t]*$/);if(n){let a=n[2].trim();if(a){d.push(`${n[1]}$$`,`${n[1]}${a}`,`${n[1]}$$`);continue}}let o=b.match(/^([ \t]{0,3})\$\$(.+)$/);if(o){let b=o[1],e=o[2].trimEnd();if(e&&!e.includes("$$")){let f=a7(c,a+1,b,h);if(f){d.push(`${b}$$`,`${b}${e}`);for(let e=a+1;e<f.index;e++)d.push(a8(c[e],b));f.content&&d.push(`${b}${f.content}`),d.push(`${b}$$`),a=f.index;continue}}}let p=b.match(/^([ \t]{0,3})\$\$\s*$/);if(p){let b=p[1],e=a7(c,a+1,b,h);if(e&&(e.glued||""!==b)){d.push(`${b}$$`);for(let f=a+1;f<e.index;f++)d.push(a8(c[f],b));e.content&&d.push(`${b}${e.content}`),d.push(`${b}$$`),a=e.index;continue}}d.push((i=b,/^\s{0,3}\[[^\]]+\]:/.test(i)||/]\s*\(/.test(i)||/<(?:!--|\/?[A-Za-z][^>]*>)/.test(i)||/\b(?:https?|file|mailto):/i.test(i)||/\b[A-Za-z]:\\/.test(i)?i:i.replace(/(?<!\\)\\\(([^`\r\n$]+?)(?<!\\)\\\)/g,(a,b)=>b.trim()?`$${b}$`:a)))}return d.join(b)}function a7(a,b,c,d){let e=d.get(c);if(void 0!==e&&b<e)return null;for(let e=b;e<a.length;e++){var f,g,h,i;let b=a[e];if(f=b,""===(g=c)?/^ {0,3}\$\$\s*$/.test(f):f.startsWith(g)&&/^\$\$\s*$/.test(f.slice(g.length)))return{index:e,content:"",glued:!1};if(h=b,/^ {0,3}(`{3,}|~{3,})/.test(h)||/^[ \t]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/.test(h)||/^ {0,3}#{1,6}(?:[ \t]+|$)/.test(h)||/^ {0,3}>/.test(h)||/<(code|pre|script|style)\b/i.test(h)||(i=b,/^ {0,3}\$\$(?:\S|[ \t]+\S)/.test(i)))return d.set(c,e),null;let j=function(a,b){if(!a.startsWith(b))return null;let c=a.slice(b.length).match(/^(.+?)\$\$\s*$/);if(!c)return null;let d=c[1].trimEnd();return d&&!d.includes("$$")?d:null}(b,c);if(null!==j)return{index:e,content:j,glued:!0}}return d.set(c,a.length),null}function a8(a,b){if(!b||!a||a.startsWith(" "))return a;let c=a.match(/^ */)?.[0].length??0;return c>=b.length?a:`${b.slice(c)}${a}`}let a9={singleTilde:!1},ba=[[a2.A,["yaml"]],[a3.A,a9],a4.A],bb=[[a2.A,["yaml"]],[a3.A,a9],a4.A],bc=[a_.A,[a1.A,a5],[a$.A,{throwOnError:!1,strict:!1}]],bd=[a_.A,[a1.A,a5],[a$.A,{throwOnError:!1,strict:!1}]],be=["light","dark","auto"],bf={preference:"auto",theme:"light"},bg=null,bh=0,bi=new Set,bj="--omp-md-";function bk(a){let b=document.documentElement,c=bg?.palettes[a];b.dataset.ompThemeMode=a,b.setAttribute("data-seed-color-mode","dark"===a?"dark-only":"light-only"),b.classList.toggle("dark","dark"===a);for(let a=b.style.length-1;a>=0;a-=1){let c=b.style.item(a);c.startsWith("--")&&!c.startsWith(bj)&&b.style.removeProperty(c)}if(c){for(let[a,d]of Object.entries(c.variables))a.startsWith(bj)&&b.style.setProperty(a,d);b.dataset.ompThemeName=c.name}try{localStorage.setItem("omp-theme",a)}catch{}}function bl(a,b,c){if(bk(b),c)try{localStorage.setItem("pi-theme",a)}catch{}bi.forEach(a=>a())}function bm(a){return bi.add(a),!function(){if("auto"!==bf.preference)return;let a="light";a!==bf.theme&&bl("auto",a,!1)}(),()=>{bi.delete(a)}}function bn(){return bf}function bo(){return bf}async function bp(a){let b=++bh,c=a?`?cwd=${encodeURIComponent(a)}`:"",d=await fetch(`/api/theme${c}`,{cache:"no-store"});if(!d.ok)throw Error(`Theme request failed (${d.status})`);let e=await d.json();if(b===bh){bg=e;try{localStorage.setItem("omp-theme-config",JSON.stringify(bg))}catch{}bk(bf.theme)}}function bq(a){let b=(0,e.useSyncExternalStore)(bm,bn,bo),c=(0,e.useCallback)((a,b)=>{let c="auto"===a?"light":a,d=()=>{bl(a,c,!0)},e=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||e)return void d();let f=b?.x??window.innerWidth/2,g=b?.y??window.innerHeight/2,h=Math.hypot(Math.max(f,window.innerWidth-f),Math.max(g,window.innerHeight-g));document.startViewTransition(d).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${f}px ${g}px)`,`circle(${h}px at ${f}px ${g}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]),d=(0,e.useCallback)(a=>{var b;let d;c((b=bf.preference,d=be.indexOf(b),be[(d+1)%be.length]),a)},[c]),f=(0,e.useCallback)((a,b)=>{c(a,b)},[c]);return{theme:b.theme,preference:b.preference,toggleTheme:d,setPreference:f,isDark:"dark"===b.theme}}function br(a){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(a);try{let b=document.createElement("textarea");return b.value=a,b.style.position="fixed",b.style.opacity="0",document.body.appendChild(b),b.select(),document.execCommand("copy"),document.body.removeChild(b),Promise.resolve()}catch{return Promise.reject()}}let bs={...aU.vs,...Object.fromEntries(["url","symbol","number","boolean","variable","constant","inserted"].map(a=>[a,{...aU.vs[a],color:"var(--seed-color-palette-green-800)"}]))};function bt({code:a,isStreaming:b,defaultPreview:c=!1}){let{isDark:f}=bq(),{t:g}=(0,x.s)(),[h,i]=(0,e.useState)(c),[j,k]=(0,e.useState)(null),[l,m]=(0,e.useState)(!1),n=`${f?"dark":"light"}
|
|
4
4
|
${a}`,o=h&&!b,p=(0,e.useMemo)(()=>(0,d.jsx)("button",{type:"button",onClick:()=>i(a=>!a),disabled:b,title:b?g("i18n.previewAfterStreaming"):o?g("i18n.showMermaidSource"):g("i18n.previewMermaid"),className:["markdown-code-action",o?"is-active":""].filter(Boolean).join(" "),children:o?g("i18n.source"):g("i18n.preview")}),[b,o,g]);if(!o)return(0,d.jsx)(bv,{code:a,lang:"mermaid",headerAction:p,isStreaming:b});let q=j?.key===n&&"error"===j.status?(0,d.jsx)("div",{className:"mermaid-block mermaid-block-error",children:g("i18n.invalidMermaid")}):j?.key!==n||"ready"!==j.status?(0,d.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":g("i18n.renderingMermaid")}):(0,d.jsxs)(d.Fragment,{children:[!l&&(0,d.jsx)("button",{type:"button",className:"mermaid-block mermaid-preview-button",title:g("i18n.openMermaidViewer"),"aria-label":g("i18n.openMermaidViewer"),onClick:()=>m(!0),dangerouslySetInnerHTML:{__html:j.svg}}),l&&(0,d.jsx)(bu,{svg:j.svg,onClose:()=>m(!1)})]});return(0,d.jsxs)("div",{className:"markdown-code-block",children:[(0,d.jsxs)("div",{className:"markdown-code-header",children:[(0,d.jsx)("span",{className:"markdown-code-lang",children:"mermaid"}),p]}),q]})}function bu({svg:a,onClose:b}){let{t:c}=(0,x.s)(),f=(0,e.useRef)(null),[g,h]=(0,e.useState)(1);return(0,d.jsx)("dialog",{ref:f,className:"mermaid-zoom-dialog","aria-label":c("i18n.mermaidViewer"),onCancel:a=>{a.preventDefault(),b()},onKeyDown:a=>{"Escape"===a.key&&(a.preventDefault(),b())},children:(0,d.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,d.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,d.jsx)("span",{className:"mermaid-zoom-title",children:c("i18n.mermaidDiagram")}),(0,d.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,d.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,d.jsx)("button",{type:"button",onClick:()=>h(a=>Math.max(.5,a-.25)),disabled:g<=.5,title:c("i18n.zoomOut"),"aria-label":c("i18n.zoomOut"),children:(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M5 12h14"})})}),(0,d.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*g),"%"]}),(0,d.jsx)("button",{type:"button",onClick:()=>h(a=>Math.min(3,a+.25)),disabled:g>=3,title:c("i18n.zoomIn"),"aria-label":c("i18n.zoomIn"),children:(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,d.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>h(1),title:c("i18n.fitToWidth"),"aria-label":c("i18n.fitToWidth"),children:(0,d.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,d.jsx)("path",{d:"M8 3H3v5M16 3h5v5M8 21H3v-5M16 21h5v-5"})})}),(0,d.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:b,title:c("i18n.close"),"aria-label":c("i18n.close"),children:(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]}),(0,d.jsx)("div",{className:"mermaid-zoom-viewport",onClick:a=>{a.target===a.currentTarget&&b()},children:(0,d.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*g}%`},dangerouslySetInnerHTML:{__html:a}})})]})})}let bv=(0,e.memo)(function({code:a,lang:b,headerAction:c,isStreaming:f}){let{isDark:g}=bq(),{t:h}=(0,x.s)(),[i,j]=(0,e.useState)(!1);return(0,d.jsxs)("div",{className:"markdown-code-block",children:[(0,d.jsxs)("div",{className:"markdown-code-header",children:[(0,d.jsx)("span",{className:"markdown-code-lang",children:b||"text"}),(0,d.jsxs)("div",{className:"markdown-code-actions",children:[c,(0,d.jsx)("button",{onClick:()=>{br(a).then(()=>{j(!0),setTimeout(()=>j(!1),1500)})},className:"markdown-code-action",children:h(i?"i18n.copied":"i18n.copy")})]})]}),f?(0,d.jsx)("pre",{style:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,overflowX:"auto",background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},children:(0,d.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:a})}):(0,d.jsx)(aT.A,{language:b||"text",style:g?aU.xJ:bs,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-muted)",fontStyle:"normal"},customStyle:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,borderRadius:0,background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:a})]})});function bw({children:a,className:b,isStreaming:c,cwd:f,onOpenFile:g}){let h=(0,e.useMemo)(()=>a6(a),[a]),i=(0,e.useMemo)(()=>({code({className:a,children:b,...e}){let f=a?.replace("language-","").toLowerCase()??"",g=String(b);return a?.includes("language-")||g.includes("\n")?"mermaid"===f?(0,d.jsx)(bt,{code:g.replace(/\n$/,""),isStreaming:c}):(0,d.jsx)(bv,{code:g.replace(/\n$/,""),lang:f,isStreaming:c}):(0,d.jsx)("code",{className:"markdown-inline-code",...e,children:b})},pre:({children:a})=>(0,d.jsx)(d.Fragment,{children:a}),a({href:a,children:b,...c}){delete c.node;let e=g?aQ(a,f):null;return e&&g?(0,d.jsx)("a",{href:a,...c,onClick:a=>{if(a.defaultPrevented||0!==a.button||a.metaKey||a.ctrlKey||a.shiftKey||a.altKey)return;let b=a.currentTarget.getAttribute("target");b&&"_self"!==b||(a.preventDefault(),g(e))},children:b}):(0,d.jsx)("a",{href:a,...c,target:"_blank",rel:"noopener noreferrer",children:b})},img({src:a,alt:b,...c}){delete c.node;let e="string"==typeof a?aQ(a,f):null,g=e?`/api/files/${aX(e)}?type=read`:a;return(0,d.jsx)("img",{src:g,alt:b??"",loading:"lazy",...c})},table:({children:a})=>(0,d.jsx)("div",{className:"markdown-table-wrap",children:(0,d.jsx)("table",{children:a})})}),[f,c,g]);return(0,d.jsx)("div",{className:["markdown-body",b].filter(Boolean).join(" "),children:(0,d.jsx)(aV.oz,{remarkPlugins:ba,rehypePlugins:bc,components:i,children:h})})}let bx=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,by=/(?:\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 bz(a){return a>=1e6?`${(a/1e6).toFixed(1)}M`:a>=1e3?`${Math.round(a/1e3)}k`:a.toLocaleString()}let bA={hideThinkingBlock:!1},bB=new Set,bC=bA,bD=0;function bE(a){return bB.add(a),()=>{bB.delete(a)}}function bF(){return bC}function bG(){return bA}async function bH(a){let b=++bD,c=a?`?cwd=${encodeURIComponent(a)}`:"",d=await fetch(`/api/display-settings${c}`,{cache:"no-store"});if(!d.ok)throw Error(`Display settings request failed (${d.status})`);let e=await d.json();b!==bD||e.hideThinkingBlock!==bC.hideThinkingBlock&&(bC={hideThinkingBlock:!0===e.hideThinkingBlock},bB.forEach(a=>a()))}function bI(){return(0,e.useSyncExternalStore)(bE,bF,bG)}var bJ=c(16812);let bK={faces:new Map,pins:new Map},bL=new Set;function bM(a){return bL.add(a),()=>{bL.delete(a)}}function bN(a){return Number.isSafeInteger(a)&&a>0}function bO(a,b,c){var d;if(!b)return null;if(bN(c)){let a=bK.faces.get(`${b}:${c}`);if(a)return a}let e=a?bK.pins.get(a):void 0;if(e&&e.provider===b){let a=bK.faces.get((d=e.credentialId,`${b}:${d}`));if(a)return a}return(0,bJ.e$)(b)}async function bP(a,b,c){if(!b||bN(c)||(0,bJ.e$)(b))return bO(a,b,c);try{let{data:c}=await (0,bJ.ST)(a);if(c?.state==="resolved"&&c.provider===b&&bN(c.credentialId)){let d=new Map(bK.pins);d.set(a,{provider:b,credentialId:c.credentialId,observedAt:Date.now()}),bK={faces:bK.faces,pins:d},bL.forEach(a=>a())}}catch{}return bO(a,b,void 0)}function bQ(a,b,c){return b&&bN(c),(0,e.useSyncExternalStore)(bM,()=>bO(a,b,c),()=>null)}var bR=c(81996);let bS={ko:{"dispatch.title":"서브에이전트 {count}명","dispatch.tally":"실행 중 {running} \xb7 실행 완료 {done} \xb7 Main 수용 {accepted}","dispatch.expand":"발주 상세 펼치기","dispatch.collapse":"발주 상세 접기","dock.label":"서브에이전트","dock.running":"실행 중 {count}","dock.awaiting":"판정 대기 {count}","dock.jump":"발주 카드로 이동 — {title}","dock.openPanel":"서브에이전트 상세 열기 — {title}","run.dispatching":"발주 중","run.pending":"대기","run.running":"실행 중","run.completed":"실행 완료","run.failed":"실행 실패","run.aborted":"중단됨","run.unobserved":"실행 상태 미관측","verdict.accepted":"Main 수용","verdict.rework":"Main 재작업 요청","verdict.held":"Main 보류","verdict.none":"검수 미기록","verdict.attempt":"{attempt}차","detail.stage":"현재 단계","detail.stageNone":"기록 없음","detail.model":"모델","detail.modelNone":"미관측","detail.fallback":"대체 모델","detail.agentId":"담당 ID","detail.reason":"판정 사유","detail.source.live":"실시간 관측","detail.source.record":"세션 기록","detail.openSubagents":"서브에이전트 상세 열기","detail.openProcess":"작업 기록 열기","summary.files":"변경 파일 {count}","summary.checks":"검사 {count}","summary.checksFailed":"실패 {count}","summary.unverified":"미확인 {count}","summary.expand":"턴 요약 펼치기","summary.collapse":"턴 요약 접기","summary.heading.files":"변경 파일","summary.heading.checks":"실행한 검사","summary.heading.unverified":"미확인","summary.check.exit":"exit {code}","summary.check.error":"오류로 끝남","summary.check.unobserved":"결과 미관측","summary.u.checkFailed":"검사 실패 — {command}","summary.u.checkUnobserved":"검사 결과 미관측 — {command}","delivery.title":"보낸 입력 {count}","delivery.kind.steer":"지금 지시","delivery.kind.followUp":"완료 후 요청","delivery.stage.sending":"보내는 중","delivery.stage.accepted":"접수됨 \xb7 전달 대기","delivery.stage.delivered":"전달됨 \xb7 대화에 들어감","delivery.stage.failed":"보내지 못함 \xb7 입력창에 되돌림","delivery.stage.unconfirmed":"전달 확인 못 함 \xb7 큐에서 빠짐","delivery.images":"이미지 {count}개","delivery.showOlder":"이전 {count}개 더 보기","delivery.showRecent":"최근 {count}개만 보기","live.nativeVoice":"기본 음성"},en:{"dispatch.title":"Subagents: {count}","dispatch.tally":"{running} running \xb7 {done} finished \xb7 {accepted} accepted by Main","dispatch.expand":"Show dispatch details","dispatch.collapse":"Hide dispatch details","dock.label":"Subagents","dock.running":"{count} running","dock.awaiting":"{count} awaiting verdict","dock.jump":"Go to the dispatch card — {title}","dock.openPanel":"Open subagent details — {title}","run.dispatching":"Dispatching","run.pending":"Queued","run.running":"Running","run.completed":"Run finished","run.failed":"Run failed","run.aborted":"Stopped","run.unobserved":"Run state not observed","verdict.accepted":"Accepted by Main","verdict.rework":"Main asked for rework","verdict.held":"Held by Main","verdict.none":"No review recorded","verdict.attempt":"attempt {attempt}","detail.stage":"Current step","detail.stageNone":"Not recorded","detail.model":"Model","detail.modelNone":"Not observed","detail.fallback":"fallback","detail.agentId":"Agent ID","detail.reason":"Review note","detail.source.live":"live","detail.source.record":"session record","detail.openSubagents":"Open subagent details","detail.openProcess":"Open work log","summary.files":"{count} files changed","summary.checks":"{count} checks","summary.checksFailed":"{count} failed","summary.unverified":"{count} unverified","summary.expand":"Show turn summary","summary.collapse":"Hide turn summary","summary.heading.files":"Files changed","summary.heading.checks":"Checks run","summary.heading.unverified":"Unverified","summary.check.exit":"exit {code}","summary.check.error":"ended with an error","summary.check.unobserved":"result not observed","summary.u.checkFailed":"Check failed — {command}","summary.u.checkUnobserved":"Check result not observed — {command}","delivery.title":"{count} sent","delivery.kind.steer":"Now","delivery.kind.followUp":"After this run","delivery.stage.sending":"Sending","delivery.stage.accepted":"Received \xb7 waiting to deliver","delivery.stage.delivered":"Delivered \xb7 in the conversation","delivery.stage.failed":"Not sent \xb7 back in the composer","delivery.stage.unconfirmed":"Delivery not confirmed \xb7 left the queue","delivery.images":"{count} image(s)","delivery.showOlder":"Show {count} earlier","delivery.showRecent":"Show only the latest {count}","live.nativeVoice":"default voice"},"zh-CN":{"dispatch.title":"{count} 个子代理","dispatch.tally":"运行中 {running} \xb7 运行完成 {done} \xb7 Main 已接受 {accepted}","dispatch.expand":"展开派发详情","dispatch.collapse":"收起派发详情","dock.label":"子代理","dock.running":"运行中 {count}","dock.awaiting":"等待判定 {count}","dock.jump":"转到派发卡片 — {title}","dock.openPanel":"打开子代理详情 — {title}","run.dispatching":"派发中","run.pending":"等待中","run.running":"运行中","run.completed":"运行完成","run.failed":"运行失败","run.aborted":"已中止","run.unobserved":"未观测到运行状态","verdict.accepted":"Main 已接受","verdict.rework":"Main 要求返工","verdict.held":"Main 暂缓","verdict.none":"未记录审查","verdict.attempt":"第 {attempt} 次","detail.stage":"当前步骤","detail.stageNone":"无记录","detail.model":"模型","detail.modelNone":"未观测","detail.fallback":"备用模型","detail.agentId":"代理 ID","detail.reason":"审查说明","detail.source.live":"实时观测","detail.source.record":"会话记录","detail.openSubagents":"打开子代理详情","detail.openProcess":"打开工作记录","summary.files":"变更文件 {count}","summary.checks":"检查 {count}","summary.checksFailed":"失败 {count}","summary.unverified":"未确认 {count}","summary.expand":"展开本轮摘要","summary.collapse":"收起本轮摘要","summary.heading.files":"变更文件","summary.heading.checks":"已运行的检查","summary.heading.unverified":"未确认","summary.check.exit":"exit {code}","summary.check.error":"以错误结束","summary.check.unobserved":"未观测到结果","summary.u.checkFailed":"检查失败 — {command}","summary.u.checkUnobserved":"未观测到检查结果 — {command}","delivery.title":"已发送 {count}","delivery.kind.steer":"立即指示","delivery.kind.followUp":"完成后请求","delivery.stage.sending":"发送中","delivery.stage.accepted":"已接收 \xb7 等待送达","delivery.stage.delivered":"已送达 \xb7 已进入对话","delivery.stage.failed":"未发送 \xb7 已退回输入框","delivery.stage.unconfirmed":"未能确认送达 \xb7 已离开队列","delivery.images":"图片 {count} 张","delivery.showOlder":"显示更早的 {count} 条","delivery.showRecent":"仅显示最近 {count} 条","live.nativeVoice":"默认语音"}};function bT(){let{locale:a}=(0,x.s)();return{st:(0,e.useCallback)((b,c)=>(0,bR.u0)(a,b,bS,c),[a]),locale:a}}function bU({seed:a,size:b,provider:c}){let[f,g]=(0,e.useState)(!1),[h,i]=(0,e.useState)(!1);return f?(0,d.jsx)("span",{className:"account-avatar account-avatar-mono","data-tone":a%6,style:{width:b,height:b,fontSize:Math.round(.46*b)},"aria-hidden":"true",children:(0,bJ.xl)(a).slice(0,1)}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("button",{type:"button",className:"account-avatar-button",style:{width:b,height:b},onClick:a=>{a.stopPropagation(),i(!0)},"aria-label":(0,bJ.xl)(a),children:(0,d.jsx)("img",{className:"account-avatar",src:(0,bJ.uk)(a),width:b,height:b,alt:"","aria-hidden":"true",draggable:!1,onError:()=>g(!0)})}),h&&(0,d.jsx)(bV,{seed:a,provider:c,onClose:()=>i(!1)})]})}function bV({seed:a,provider:b,onClose:c}){let{t:f}=(0,x.s)(),g=(0,e.useRef)(null),h=(0,bJ.xl)(a);return(0,E.createPortal)((0,d.jsxs)("dialog",{ref:g,className:"account-avatar-dialog","aria-label":h,onCancel:a=>{a.preventDefault(),c()},onKeyDown:a=>{"Escape"===a.key&&(a.preventDefault(),c())},onClick:a=>{a.stopPropagation(),a.target===a.currentTarget&&c()},children:[(0,d.jsx)("img",{className:"account-avatar-full",src:(0,bJ.uk)(a),width:256,height:256,alt:h,draggable:!1}),(0,d.jsxs)("p",{className:"account-avatar-caption",children:[(0,d.jsx)("span",{className:"account-avatar-caption-alias",children:h}),b?(0,d.jsx)("span",{className:"account-avatar-caption-provider",children:(0,bJ.bN)(b)}):null]}),(0,d.jsx)("button",{type:"button",className:"account-avatar-close",onClick:c,children:f("i18n.close")})]}),document.body)}function bW(a){let b,c=[],d=null,e=0,f=0,g=0,h=0,i=[],j=[],k=()=>({lineNo:null,text:"",type:"empty"}),l=()=>{if(!d){i=[],j=[];return}let a=Math.max(i.length,j.length);for(let b=0;b<a;b++){let a=i[b]?{lineNo:i[b].lineNo,text:i[b].text,type:"removed"}:k(),c=j[b]?{lineNo:j[b].lineNo,text:j[b].text,type:"added"}:k();d.rows.push({type:"line",left:a,right:c})}i=[],j=[]};for(let k of a.split(/\r?\n/)){if(!(g>0||h>0)){if(k.startsWith("--- ")){l(),b=bX(k.slice(4));continue}if(k.startsWith("+++ ")){l(),d={oldPath:b,newPath:bX(k.slice(4)),rows:[]},c.push(d);continue}}let a=k.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(a){d||(d={rows:[]},c.push(d)),l(),e=Number(a[1]),f=Number(a[3]),g=void 0===a[2]?1:Number(a[2]),h=void 0===a[4]?1:Number(a[4]),d.rows.push({type:"hunk",text:k});continue}if(!d)continue;if(k.startsWith("\\ ")){l(),d.rows.push({type:"hunk",text:k});continue}let m=k[0],n=k.slice(1);" "===m?(l(),d.rows.push({type:"line",left:{lineNo:e++,text:n,type:"context"},right:{lineNo:f++,text:n,type:"context"}}),g>0&&g--,h>0&&h--):"-"===m?(i.push({lineNo:e++,text:n}),g>0&&g--):"+"===m?(j.push({lineNo:f++,text:n}),h>0&&h--):""!==k&&(l(),d.rows.push({type:"hunk",text:k}))}l();let m=c.filter(a=>a.rows.some(a=>"line"===a.type));return m.length>0?m:null}function bX(a){return a.split(" ")[0].trim()}function bY({task:a}){let b="completed"===a.status,c="abandoned"===a.status,e="in_progress"===a.status,f="blocked"===a.status;return(0,d.jsxs)("div",{role:"listitem","aria-label":`${a.status}: ${a.content}`,className:`todo-checklist-row ${b?"is-completed":c?"is-abandoned":f?"is-blocked":e?"is-active":"is-pending"}`,children:[(0,d.jsx)("span",{"aria-hidden":"true",className:"todo-checklist-marker",children:b?"✓":c?"\xd7":f?"!":e?"›":""}),(0,d.jsxs)("span",{className:"todo-checklist-content",children:[a.content,f&&a.blocker?(0,d.jsxs)("span",{className:"todo-checklist-blocker",children:[" (",a.blocker,")"]}):null]})]})}let bZ="/icons/catppuccin";function b$({name:a,size:b=14}){let c={width:b,height:b,"--catppuccin-icon-light":`url(${bZ}/latte/${a}.svg)`,"--catppuccin-icon-dark":`url(${bZ}/mocha/${a}.svg)`};return(0,d.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:c})}function b_({size:a=14,open:b=!1}){return(0,d.jsx)(b$,{name:b?"_folder_open":"_folder",size:a})}function b0({size:a=14}){return(0,d.jsx)(b$,{name:"_file",size:a})}let b1={ts:"typescript",tsx:"typescript-react",js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"javascript-react",py:"python",json:"json",jsonl:"json",css:"css",less:"css",scss:"sass",html:"html",htm:"html",md:"markdown",markdown:"markdown",mdx:"markdown",yaml:"yaml",yml:"yaml",toml:"toml",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",rs:"rust",go:"go",sql:"database",graphql:"graphql",gql:"graphql",tf:"terraform",hcl:"terraform",docx:"ms-word",pdf:"pdf",lock:"lock"};function b2(a,b=14){let c=a.toLowerCase(),e="dockerfile"===c||c.startsWith("dockerfile.")?"docker":".env"===c||c.startsWith(".env.")?"env":[".gitignore",".gitattributes",".gitmodules"].includes(c)?"git":"package-lock.json"===c?"npm-lock":"bun.lock"===c?"bun-lock":["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"].includes(c)?"next":[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(c)?"eslint":["yarn.lock","pnpm-lock.yaml","cargo.lock"].includes(c)?"lock":c.endsWith(".config.ts")||c.endsWith(".config.js")||c.endsWith(".config.mjs")||c.endsWith(".config.cjs")?"config":void 0;if(e)return(0,d.jsx)(b$,{name:e,size:b});let f=b1[c.split(".").pop()??""];return f?(0,d.jsx)(b$,{name:f,size:b}):(0,d.jsx)(b0,{size:b})}function b3({files:a,onOpenFile:b}){let{t:c}=(0,x.s)();return 0===a.length?null:(0,d.jsx)("div",{"aria-label":c("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:a.map(({filePath:a})=>{let e=aY(a);return(0,d.jsxs)("button",{type:"button",title:a,"aria-label":c("chat.openWrittenFile",{name:e}),onClick:()=>b?.(a),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:[b2(e,12),(0,d.jsx)("span",{children:e})]},a)})})}var b4=c(29821);let b5={verdicts:new Map,runs:new Map,latestByAgent:new Map};function b6(a){return Array.isArray(a)?a.filter(a=>"object"==typeof a&&null!==a):[]}function b7(a){return"string"==typeof a&&a.trim()?a:null}function b8(a){switch(a){case"pending":case"queued":return"pending";case"running":return"running";case"completed":case"success":return"completed";case"failed":case"error":return"failed";case"aborted":case"cancelled":case"canceled":return"aborted";default:return null}}function b9(a){return"string"==typeof a?a:a.map(a=>"text"===a.type?a.text:"").join("\n")}function ca(a,b){if(b?.isError)return null;let c=b6(a.input.tasks),d=b6(b?.details?.progress),e=Math.max(c.length,d.length),f=[];for(let g=0;g<e;g++){let e=d.find(a=>a.index===g)??d[g],h=c[g],i=b7(e?.id)??b7(h?.name);i&&f.push({key:`${a.toolCallId}#${g}`,toolCallId:a.toolCallId,index:g,agentId:i,agent:b7(e?.agent)??b7(h?.agent),task:b7(e?.task)??b7(h?.task)??"",spawned:!!b})}return f}let cb=/<task-result\b([^>]*)>/g,cc=/(\w+)="([^"]*)"/g;function cd(a,b,c){let d,e=b.find(b=>b.parentToolCallId?b.parentToolCallId===a.toolCallId&&b.id===a.agentId:b.id===a.agentId&&c.latestByAgent.get(a.agentId)===a.key),f=e?{key:a.key,identity:"live",live:e.assignment?e:{...e,assignment:a.task}}:{key:a.key,identity:"live",live:{id:a.agentId,index:a.index,agent:a.agent??"",agentSource:"user",status:"unknown",task:a.task,lastUpdate:0}},g=(0,b4.$V)(f),h=c.runs.get(a.key),i=null;e&&"unknown"!==e.status?(d=e.status,i="live"):h&&"unknown"!==h.status?(d=h.status,i="record"):d=a.spawned?"unobserved":"dispatching";let j=c.verdicts.get(a.key);return{member:a,title:g.title,explicitTitle:g.explicitTitle,stage:e?g.stage:null,model:e?(0,b4.A7)(f):null,run:d,runSource:i,verdict:j&&j.length>0?j[j.length-1]:null}}function ce(a){return"assistant"!==a.role?[]:a.content?.filter(a=>"toolCall"===a.type&&"task"===a.toolName)??[]}function cf(a,b,c){let d=-1;c.forEach((a,b)=>{"user"===a.role&&(d=b)});let e=c.slice(0,d+1).flatMap(ce),f=c.slice(d+1).flatMap(ce),g=b.findIndex(a=>"user"===a.role),h=0===f.length?-1:a.findIndex(a=>"answer"===a.kind&&(-1===g||a.idx<g));return -1===h?{continuing:null,atCompaction:[...e,...f]}:{continuing:{position:h,calls:f},atCompaction:e}}let cg={dispatching:"running",pending:"running",running:"running",completed:"awaiting",failed:"awaiting",aborted:"awaiting",unobserved:null},ch=(0,e.createContext)({ledger:b5,subagents:[],toolResults:new Map}),ci={dispatching:"run.dispatching",pending:"run.pending",running:"run.running",completed:"run.completed",failed:"run.failed",aborted:"run.aborted",unobserved:"run.unobserved"},cj={accepted:"verdict.accepted",rework:"verdict.rework",held:"verdict.held",none:"verdict.none"};function ck({maker:a,st:b}){let c=a.verdict?.verdict??"none",e=a.verdict?.attempt;return(0,d.jsxs)("span",{className:"answer-status-pair",children:[(0,d.jsx)("span",{className:"answer-status-run","data-state":a.run,children:b(ci[a.run])}),(0,d.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→"}),(0,d.jsxs)("span",{className:"answer-status-verdict","data-verdict":c,children:[b(cj[c]),null!=e&&e>1?` \xb7 ${b("verdict.attempt",{attempt:e})}`:null]})]})}function cl({calls:a}){let{ledger:b,subagents:c,toolResults:f,onOpenPanel:g,focusedDispatch:h}=(0,e.useContext)(ch),{st:i}=bT(),[j,k]=(0,e.useState)(!1),l=(0,e.useId)(),m=(0,e.useMemo)(()=>a.flatMap(a=>ca(a,f.get(a.toolCallId))??[]).map(a=>cd(a,c,b)),[a,f,c,b]);if(0===m.length)return null;let n=0,o=0,p=0;for(let a of m)("dispatching"===a.run||"pending"===a.run||"running"===a.run)&&(n+=1),"completed"===a.run&&(o+=1),a.verdict?.verdict==="accepted"&&(p+=1);return(0,d.jsxs)("section",{className:h&&m.some(a=>a.member.key===h)?"answer-dispatch answer-dispatch-flash":"answer-dispatch","aria-label":i("dispatch.title",{count:m.length}),children:[(0,d.jsxs)("button",{type:"button",className:"answer-dispatch-toggle","aria-expanded":j,"aria-controls":l,title:i(j?"dispatch.collapse":"dispatch.expand"),onClick:()=>k(a=>!a),children:[(0,d.jsx)("span",{className:"answer-dispatch-heading",children:i("dispatch.title",{count:m.length})}),(0,d.jsx)("span",{className:"answer-dispatch-tally",children:i("dispatch.tally",{running:n,done:o,accepted:p})}),(0,d.jsx)("svg",{className:"answer-chevron",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),(0,d.jsx)("ul",{className:"answer-dispatch-list",id:l,children:m.map(a=>(0,d.jsxs)("li",{className:"answer-dispatch-row","data-focused":a.member.key===h?"":void 0,children:[(0,d.jsxs)("div",{className:"answer-dispatch-line",children:[(0,d.jsx)("span",{className:"answer-dispatch-name",title:a.title,children:a.title}),(0,d.jsx)(ck,{maker:a,st:i})]}),j&&(0,d.jsxs)("dl",{className:"answer-dispatch-detail",children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("dt",{children:i("detail.stage")}),(0,d.jsx)("dd",{children:a.stage??i("detail.stageNone")})]}),(0,d.jsxs)("div",{children:[(0,d.jsx)("dt",{children:i("detail.model")}),(0,d.jsx)("dd",{title:a.model?.model??void 0,children:a.model?.modelShort?`${a.model.modelShort}${a.model.effort?` \xb7 ${a.model.effort}`:""}${a.model.modelIsFallback?` \xb7 ${i("detail.fallback")}`:""}`:i("detail.modelNone")})]}),(0,d.jsxs)("div",{children:[(0,d.jsx)("dt",{children:i("detail.agentId")}),(0,d.jsxs)("dd",{children:[(0,d.jsx)("span",{className:"answer-mono",children:a.member.agentId}),a.runSource?` \xb7 ${i("live"===a.runSource?"detail.source.live":"detail.source.record")}`:""]})]}),a.verdict?.reason&&(0,d.jsxs)("div",{children:[(0,d.jsx)("dt",{children:i("detail.reason")}),(0,d.jsx)("dd",{children:a.verdict.reason})]})]})]},a.member.key))}),j&&g&&(0,d.jsxs)("div",{className:"answer-dispatch-links",children:[(0,d.jsx)("button",{type:"button",className:"answer-link",onClick:()=>g("subagents"),children:i("detail.openSubagents")}),(0,d.jsx)("button",{type:"button",className:"answer-link",onClick:()=>g("process"),children:i("detail.openProcess")})]})]})}function cm({summary:a,onOpenFile:b}){let{ledger:c,subagents:f,toolResults:g}=(0,e.useContext)(ch),{st:h}=bT(),[i,j]=(0,e.useState)(!1),k=(0,e.useId)(),l=(0,e.useMemo)(()=>a.dispatchCalls.flatMap(a=>ca(a,g.get(a.toolCallId))??[]).map(a=>cd(a,f,c)),[a.dispatchCalls,g,f,c]),m=a.checks.filter(a=>"failed"===a.state),n=a.checks.filter(a=>"passed"!==a.state),o=l.filter(a=>"failed"===a.run||"aborted"===a.run||"unobserved"===a.run||a.verdict?.verdict!=="accepted"),p=n.length+o.length;if(0===a.files.length&&0===a.checks.length&&0===l.length)return null;let q=[h("summary.files",{count:a.files.length}),h("summary.checks",{count:a.checks.length})];return m.length>0&&q.push(h("summary.checksFailed",{count:m.length})),p>0&&q.push(h("summary.unverified",{count:p})),(0,d.jsxs)("div",{className:"answer-summary",children:[(0,d.jsxs)("button",{type:"button",className:"answer-summary-toggle","aria-expanded":i,"aria-controls":k,title:h(i?"summary.collapse":"summary.expand"),onClick:()=>j(a=>!a),children:[(0,d.jsx)("span",{className:"answer-summary-text","data-unverified":p>0?"":void 0,children:q.join(" \xb7 ")}),(0,d.jsx)("svg",{className:"answer-chevron",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),i&&(0,d.jsxs)("div",{className:"answer-summary-body",id:k,children:[a.files.length>0&&(0,d.jsxs)("section",{children:[(0,d.jsx)("h4",{className:"answer-summary-heading",children:h("summary.heading.files")}),(0,d.jsx)(b3,{files:a.files,onOpenFile:b})]}),a.checks.length>0&&(0,d.jsxs)("section",{children:[(0,d.jsx)("h4",{className:"answer-summary-heading",children:h("summary.heading.checks")}),(0,d.jsx)("ul",{className:"answer-summary-list",children:a.checks.map(a=>(0,d.jsxs)("li",{className:"answer-check","data-state":a.state,children:[(0,d.jsx)("code",{className:"answer-check-command",title:a.command,children:a.command}),(0,d.jsx)("span",{className:"answer-check-result",children:null!==a.exitCode?h("summary.check.exit",{code:a.exitCode}):h("failed"===a.state?"summary.check.error":"summary.check.unobserved")})]},a.toolCallId))})]}),p>0&&(0,d.jsxs)("section",{children:[(0,d.jsx)("h4",{className:"answer-summary-heading",children:h("summary.heading.unverified")}),(0,d.jsxs)("ul",{className:"answer-summary-list",children:[n.map(a=>(0,d.jsx)("li",{children:h("failed"===a.state?"summary.u.checkFailed":"summary.u.checkUnobserved",{command:a.command})},`check-${a.toolCallId}`)),o.map(a=>(0,d.jsxs)("li",{className:"answer-summary-maker",children:[(0,d.jsx)("span",{className:"answer-dispatch-name",title:a.title,children:a.title}),(0,d.jsx)(ck,{maker:a,st:h})]},`maker-${a.member.key}`))]})]})]})]})}let cn=/^att_[0-9a-f]{32}$/,co=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function cp(a){return"string"==typeof a&&cn.test(a)}class cq extends Error{constructor(a,b){super(b),this.code=a,this.name="DocumentAttachmentError"}}let cr={markdown:"text/markdown",text:"text/plain",pdf:"application/pdf"},cs={".txt":!0,".csv":!0,".tsv":!0,".json":!0,".log":!0},ct={"text/plain":!0,"text/csv":!0,"text/tab-separated-values":!0,"application/json":!0,"text/json":!0};function cu(a){let b=a.name.toLocaleLowerCase();if(b.endsWith(".md")||b.endsWith(".markdown"))return"markdown";if(b.endsWith(".pdf"))return"pdf";let c=b.lastIndexOf(".");if(c>0&&cs[b.slice(c)])return"text";let d=a.type.toLocaleLowerCase().split(";",1)[0]?.trim();return"text/markdown"===d?"markdown":"application/pdf"===d?"pdf":d&&ct[d]?"text":null}let cv={".mp3":"audio/mpeg",".wav":"audio/wav",".wave":"audio/wav",".m4a":"audio/mp4",".ogg":"audio/ogg",".oga":"audio/ogg",".opus":"audio/ogg",".flac":"audio/flac",".webm":"audio/webm",".aac":"audio/aac",".aif":"audio/aiff",".aiff":"audio/aiff"};function cw(a){let b=a.name.toLocaleLowerCase(),c=b.lastIndexOf("."),d=c>0?cv[b.slice(c)]:void 0;if(d)return d;let e=a.type.toLocaleLowerCase().split(";",1)[0]?.trim();return e?.startsWith("audio/")?e:null}function cx(a,b){try{let c=new TextDecoder(a,{fatal:!0}).decode(b);return c.includes("\0")?null:c}catch{return null}}function cy(a){if(!Array.isArray(a))return[];let b=[],c=0,d=0;for(let e of a){if(e&&"object"==typeof e&&"string"==typeof e.name&&e.name.length>0&&("text/markdown"===e.mimeType||"text/plain"===e.mimeType||"application/pdf"===e.mimeType)&&"number"==typeof e.size&&Number.isSafeInteger(e.size)&&e.size>=0&&e.size<=8388608&&"string"==typeof e.text&&e.text.length<=12e4){if(b.length>=3)break;!(c+e.size>0x1000000)&&(d+e.text.length>24e4||(b.push({name:e.name,mimeType:e.mimeType,size:e.size,text:e.text,...cp(e.attachmentId)?{attachmentId:e.attachmentId}:{}}),c+=e.size,d+=e.text.length))}}return b}async function cz(a){let b,c=cu(a);if(!c)throw new cq("unsupported",`Unsupported document type: ${a.name}`);if(a.size>8388608)throw new cq("file_too_large",`${a.name} exceeds the document size limit`);if("pdf"===c)b=await cI(a);else{try{b=await a.text()}catch(a){throw new cq("read_failed",a instanceof Error?a.message:String(a))}cJ(b)}return{name:a.name,mimeType:cr[c],size:a.size,text:b}}function cA(a,b){let c=cy(b);if(0===c.length)return a;let d={userMessageLength:a.length,documents:c.map(({name:a,mimeType:b,size:c,text:d})=>({name:a,mimeType:b,size:c,textLength:d.length}))},e=`${cK}${JSON.stringify(d)}${cL}
|
|
@@ -15,7 +15,7 @@ The audio could not be transcribed: ${a.transcriptError}`:c}async function cH(a,
|
|
|
15
15
|
Attached: ${c}`:`Attached: ${c}`}(q)).then(()=>{p(!0),setTimeout(()=>p(!1),1500)})},title:l("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:o?"var(--accent)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:a=>{o||(a.currentTarget.style.color="var(--accent)")},onMouseLeave:a=>{o||(a.currentTarget.style.color="var(--text-muted)")},children:[o?(0,d.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,d.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,d.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),o?l("i18n.copied"):l("i18n.copy")]})}),(w||y)&&(0,d.jsxs)("div",{style:{display:"flex",gap:3,opacity:m||h?1:0,pointerEvents:m||h?"auto":"none",transition:"opacity 0.12s"},children:[y&&(0,d.jsxs)("button",{onClick:()=>{i(j),k?.(a)},title:l("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:a=>{a.currentTarget.style.color="var(--accent)"},onMouseLeave:a=>{a.currentTarget.style.color="var(--text-dim)"},children:[(0,d.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("polyline",{points:"15 10 20 15 15 20"}),(0,d.jsx)("path",{d:"M4 4v7a4 4 0 0 0 4 4h12"})]}),l("i18n.editFromHere")]}),w&&(0,d.jsxs)("button",{onClick:()=>{g(f)},disabled:h,title:h?l("i18n.creatingSession"):l("i18n.newSessionTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:h?"var(--accent)":"var(--text-dim)",cursor:h?"not-allowed":"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:a=>{h||(a.currentTarget.style.color="var(--accent)")},onMouseLeave:a=>{h||(a.currentTarget.style.color="var(--text-dim)")},children:[(0,d.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,d.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,d.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,d.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),h?l("i18n.creating"):l("i18n.newSession")]})]}),v&&(0,d.jsx)("span",{style:{fontSize:10,color:"var(--text-muted)"},children:v})]})]})}function cZ({message:a,isStreaming:b,toolResults:c,modelNames:f,cwd:g,onOpenFile:h,showTimestamp:i,prevTimestamp:j,sessionId:k,entryId:l,writtenFiles:m,dispatchSlot:n,turnSummary:o}){var p;let q,{t:r}=(0,x.s)(),{hideThinkingBlock:s}=bI(),t=i?cW(a.timestamp):null,u=bQ(k,a.provider,a.credentialId),v=a.liveSpeaker?bJ.o.find(b=>b.alias===a.liveSpeaker?.alias):void 0,w=v?{seed:v.seed,alias:v.alias}:u,y=!!v&&a.liveSpeaker?.mode==="native",{st:z}=bT(),A=f?.[`${a.provider}:${a.model}`]??f?.[a.model]??a.model,B=(0,e.useMemo)(()=>(a.content??[]).map((a,b)=>({block:a,originalIndex:b})).filter(({block:a})=>!aw(a,{isStreaming:b,hideThinking:s})),[a.content,b,s]),C=(0,e.useMemo)(()=>B.map(({block:a})=>a),[B]),D=ax(a,{isStreaming:b}),[E,F]=(0,e.useState)(!1),[G,H]=(0,e.useState)(!1),[I,J]=(0,e.useState)(!1);(0,e.useRef)(null);let[K,L]=(0,e.useState)(null);(0,e.useRef)(B).current=B;let M=(0,e.useRef)(new Map),N=(0,e.useMemo)(()=>{if(!b)return M.current=new Map,0;let a=new Map,c=0;for(let{block:b,originalIndex:d}of B){let e="text"===b.type?b.text:"thinking"===b.type?b.thinking:"toolCall"===b.type?JSON.stringify(b.input??{})??"":null;if(null===e)continue;let f=function(a,b){var c,d;if(!a||!b.startsWith(a.text))return cR(b);let e=a.tokens,f=a.text.length;return f>0&&f<b.length&&(c=a.text.charCodeAt(f-1))>=55296&&c<=56319&&(d=b.charCodeAt(f))>=56320&&d<=57343&&(e-=1/4,f--),e+cR(b.slice(f))}(M.current.get(d),e);a.set(d,{text:e,tokens:f}),c+=f}return M.current=a,c},[B,b]);(0,e.useRef)(N).current=N,(0,e.useRef)(new Map);let[O,P]=(0,e.useState)(new Map),Q=(0,e.useMemo)(()=>{if(!a.timestamp||!j)return;let b=Math.round((a.timestamp-j)/1e3);return b>0?b:void 0},[a.timestamp,j]),R=(0,e.useMemo)(()=>(function(a,b){let c=new Map,d=a.completedAt;if(!b||!d)return c;for(let[a,e]of b){if(!e.timestamp||e.details?.executed===!1)continue;let b=Math.round((e.timestamp-d)/1e3);b>0&&c.set(a,b)}return c})(a,c),[a,c]),S=C.filter(a=>"text"===a.type).map(a=>a.text).join("\n");return 0!==C.length||b||D?(0,d.jsxs)("div",{className:`message-assistant${b?" is-streaming":""}`,style:{marginBottom:16},onMouseEnter:()=>F(!0),onMouseLeave:()=>F(!1),children:[(0,d.jsx)("div",{className:"message-assistant-role",style:{fontSize:11,color:"var(--text-dim)",marginBottom:2,display:"flex",alignItems:"center",gap:9,...w?{minHeight:40}:null},children:a.provider&&(0,d.jsxs)(d.Fragment,{children:[w&&(0,d.jsx)(bU,{seed:w.seed,size:40,provider:a.provider}),w&&(0,d.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:w.alias}),y&&(0,d.jsx)("span",{children:z("live.nativeVoice")}),(0,d.jsx)("span",{children:`${(0,bJ.bN)(a.provider)} \xb7 ${A}`})]})}),n?.placement==="before"&&(0,d.jsx)(cl,{calls:n.calls}),(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:B.map(({block:a,originalIndex:e})=>(0,d.jsx)(c$,{block:a,toolResults:c,isStreaming:b,streamingDuration:O.get(e)??("thinking"===a.type?Q:void 0),toolCallDurations:R,cwd:g,onOpenFile:h,sessionId:k,entryId:l,blockIndex:e},`${l??"stream"}-${e}`))}),n?.placement==="after"&&(0,d.jsx)(cl,{calls:n.calls}),D&&(0,d.jsxs)("div",{role:"alert",style:{marginTop:8*(C.length>0),padding:"7px 10px",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",background:"var(--danger-soft)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Error: ",D]}),o?(0,d.jsx)(cm,{summary:o,onOpenFile:h}):m&&m.length>0&&(0,d.jsx)(b3,{files:m,onOpenFile:h}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:4},children:[a.usage&&!b&&(0,d.jsx)("button",{type:"button",onClick:()=>J(a=>!a),onFocus:()=>F(!0),onBlur:()=>F(!1),"aria-expanded":I,title:r("i18n.messageUsageTitle"),style:{padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:I?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:E||I?1:0,pointerEvents:E||I?"auto":"none",transition:"opacity 0.12s, color 0.12s"},children:I?(p=a.usage,q=[],p.input&&q.push(`${p.input.toLocaleString()} in`),p.output&&q.push(`${p.output.toLocaleString()} out`),p.cacheRead&&q.push(`${p.cacheRead.toLocaleString()} cache R`),p.cacheWrite&&q.push(`${p.cacheWrite.toLocaleString()} cache W`),p.cost?.total&&q.push(`$${p.cost.total.toFixed(4)}`),q.join(" \xb7 ")):r("i18n.messageUsage")}),b&&Math.round(N)>0&&(0,d.jsx)("button",{type:"button",onClick:()=>J(a=>!a),"aria-expanded":I,title:r("i18n.estimatedTokens"),style:{padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:I?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},children:I?`~${Math.round(N)}${null!==K?` \xb7 ${K.toFixed(1)} t/s`:""}`:r("i18n.messageUsage")}),S&&!b&&(0,d.jsxs)("button",{onClick:()=>{br(S).then(()=>{H(!0),setTimeout(()=>H(!1),1500)})},title:r("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:G?"var(--accent)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:+!!E,pointerEvents:E?"auto":"none",transition:"opacity 0.12s, color 0.12s"},onMouseEnter:a=>{G||(a.currentTarget.style.color="var(--accent)")},onMouseLeave:a=>{G||(a.currentTarget.style.color="var(--text-muted)")},children:[G?(0,d.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,d.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,d.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),r(G?"i18n.copied":"i18n.copy")]}),t&&!b&&(0,d.jsx)("span",{style:{fontSize:10,color:"var(--text-muted)",marginLeft:"auto"},children:t})]})]}):null}function c$({block:a,toolResults:b,isStreaming:c,streamingDuration:e,toolCallDurations:f,cwd:g,onOpenFile:h,sessionId:i,entryId:j,blockIndex:k}){if("text"===a.type)return(0,d.jsx)(c2,{block:a,isStreaming:c,cwd:g,onOpenFile:h});if("thinking"===a.type)return(0,d.jsx)(c3,{block:a,duration:e,sessionId:i,entryId:j,blockIndex:k});if("toolCall"===a.type){let c=b?.get(a.toolCallId),e=f?.get(a.toolCallId);return(0,d.jsx)(c4,{block:a,result:c,duration:e})}if("image"===a.type)return"image"===a.type&&"toolImage"in a?i?(0,d.jsx)(c0,{sessionId:i,toolCallId:a.toolImage.toolCallId}):null:(0,d.jsx)(c_,{block:a});return null}function c_({block:a}){let b=dn(a);return b?(0,d.jsx)("img",{src:b,alt:"",style:{maxWidth:"100%",maxHeight:420,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}}):null}function c0({sessionId:a,toolCallId:b}){let{t:c}=(0,x.s)(),[f,g]=(0,e.useState)(()=>aC.get(`${a}
|
|
16
16
|
${b}`)),[h,i]=(0,e.useState)(null),[j,k]=(0,e.useState)(()=>new Set);if(!f)return null;let l=Array.from({length:f},(a,b)=>b).filter(a=>!j.has(a));return 0===l.length?null:(0,d.jsxs)("div",{className:"tool-image-strip","data-tool-call-id":b,children:[l.map(e=>(0,d.jsx)("button",{type:"button",className:"tool-image-thumb","aria-label":c("i18n.zoomIn"),onClick:()=>i(e),children:(0,d.jsx)("img",{src:aA(a,b,e),alt:"",loading:"lazy",draggable:!1,onError:()=>k(a=>new Set(a).add(e))})},e)),null!==h&&(0,d.jsx)(c1,{src:aA(a,b,h),onClose:()=>i(null)})]})}function c1({src:a,onClose:b}){let{t:c}=(0,x.s)(),f=(0,e.useRef)(null);return(0,E.createPortal)((0,d.jsxs)("dialog",{ref:f,className:"tool-image-dialog",onCancel:a=>{a.preventDefault(),b()},onClick:a=>{a.target===a.currentTarget&&b()},children:[(0,d.jsx)("img",{className:"tool-image-full",src:a,alt:"",draggable:!1}),(0,d.jsx)("button",{type:"button",className:"tool-image-close",onClick:b,children:c("i18n.close")})]}),document.body)}function c2({block:a,isStreaming:b,cwd:c,onOpenFile:e}){return(0,d.jsx)(cS,{isStreaming:b,cwd:c,onOpenFile:e,children:a.text})}function c3({block:a,duration:b,sessionId:c,entryId:f,blockIndex:g}){let{t:h}=(0,x.s)(),[i,j]=(0,e.useState)(null),[k,l]=(0,e.useState)(!0===a.deferred),[m,n]=(0,e.useState)(null),o=a.deferred?i:a.thinking,p="string"==typeof o&&o.trim().length>0;return(0,d.jsxs)("div",{className:"markdown-thinking","aria-label":h("i18n.thinking"),children:[(0,d.jsx)("div",{className:"markdown-thinking-content",children:k?(0,d.jsx)("span",{className:"markdown-thinking-status",children:h("i18n.loadingThinking")}):m?(0,d.jsx)("span",{className:"markdown-thinking-error",children:m}):p?(0,d.jsx)(bw,{className:"markdown-thinking-body",children:o}):(0,d.jsx)("span",{className:"markdown-thinking-status",children:h("chat.thinking")})}),void 0!==b&&p&&(0,d.jsxs)("span",{className:"markdown-thinking-duration",children:[b,"s"]})]})}function c4({block:a,result:b,duration:c}){let f,g=a.toolName.toLowerCase(),h="edit"===g||g.startsWith("edit_")||g.endsWith(".edit")||g.endsWith("_edit")||g.includes("str_replace")||g.includes("replace_editor"),[i,j]=(0,e.useState)(h),k=JSON.stringify(a.input,null,2),l="todo"===g||g.endsWith(".todo")||g.endsWith("_todo"),m="bash"===g||g.startsWith("bash ")||g.endsWith(".bash")||g.endsWith("_bash"),n=b&&!b.isError?function(a){let b=a.details;if(!dg(b))return null;let c="string"==typeof b.patch?b.patch:null;if(c)return{text:c};let d="string"==typeof b.diff?b.diff:null;return d?{text:d}:null}(b):null,o=l?"unknown"===(f=aS(a,b)).kind||0===f.phases.length?null:f.phases:null,p=n?n.text.split(/\r?\n/).reduce((a,b)=>(b.startsWith("+")&&!b.startsWith("+++")&&(a.added+=1),b.startsWith("-")&&!b.startsWith("---")&&(a.removed+=1),a),{added:0,removed:0}):null,q=b?b.content.filter(a=>"text"===a.type).map(a=>a.text).join("\n"):null,r=null!==q&&("(no output)"===q.trim()||""===q.trim()),s=b?.isError??!1;if(m)return(0,d.jsx)(da,{command:dg(a.input)&&"string"==typeof a.input.command?a.input.command:"",output:q??"",pending:!b,isError:s,duration:c,local:g.includes("(local)")});if(l&&o)return(0,d.jsx)(c9,{phases:o});let t=!!(o||n),u=function(a,b){if(b){let a=b.flatMap(a=>a.tasks),c=a.filter(a=>"completed"===a.status||"abandoned"===a.status).length;return`${c}/${a.length} tasks`}return function(a){var b;let c=a.input;if(!c||"object"!=typeof c)return"";let d=Object.keys(c);if(0===d.length)return"";let e=a.toolName.toLowerCase();if(b=e,["grep","read","write","glob"].some(a=>b===a||b.endsWith(`.${a}`)||b.endsWith(`_${a}`))&&"string"==typeof c.i){let a=c.i.trim();if(a)return a.slice(0,120)}if(("eval"===e||e.endsWith(".eval")||e.endsWith("_eval"))&&"string"==typeof c.title){let a=c.title.trim();if(a)return a.slice(0,120)}if("command"in c)return String(c.command).slice(0,120);if("path"in c)return String(c.path).slice(0,120);if("file_path"in c)return String(c.file_path).slice(0,120);if("pattern"in c)return String(c.pattern).slice(0,120);if("query"in c)return String(c.query).slice(0,120);let f=d.map(a=>c[a]).find(a=>"string"==typeof a||"number"==typeof a||"boolean"==typeof a);if(void 0!==f)return String(f).slice(0,120);try{return JSON.stringify(c).slice(0,120)}catch{return d.join(", ").slice(0,120)}}(a)}(a,o);return(0,d.jsxs)("div",{className:`tool-call-card${s?" is-error":" is-success"}`,style:{borderRadius:7,overflow:"hidden",fontSize:12,border:s?"1px solid var(--danger-line)":"1px solid var(--success-line)",background:s?"var(--danger-soft)":"var(--success-soft)"},children:[(0,d.jsxs)("button",{className:"tool-call-header",onClick:()=>j(a=>!a),"aria-expanded":i,style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"6px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",minWidth:0},children:[(0,d.jsx)(c7,{toolName:a.toolName,isError:s}),(0,d.jsx)("span",{className:"tool-call-name",style:{color:s?"var(--danger)":"var(--success)",fontFamily:"var(--font-mono)",fontWeight:600,fontSize:11,flexShrink:0},children:a.toolName}),(0,d.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:u}),p&&(0,d.jsxs)("span",{title:`${p.added} lines added, ${p.removed} lines removed`,"aria-label":`${p.added} lines added, ${p.removed} lines removed`,style:{display:"inline-flex",alignItems:"center",gap:6,flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,fontVariantNumeric:"tabular-nums"},children:[(0,d.jsxs)("span",{style:{color:"var(--success)"},children:["+",p.added]}),(0,d.jsxs)("span",{style:{color:"var(--danger)"},children:["−",p.removed]})]}),void 0!==c&&(0,d.jsxs)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:[c,"s"]}),(0,d.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:i?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,d.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),n&&(0,d.jsx)("div",{style:{maxHeight:i?560:260,overflowY:"auto",overflowX:"hidden",borderTop:"1px solid var(--success-line)"},children:(0,d.jsx)(db,{diff:n})}),b&&s&&(0,d.jsx)(dh,{text:q??"",isEmpty:r,isError:!0}),i&&!t&&(0,d.jsx)("pre",{className:"tool-call-input",style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",background:"var(--bg-subtle)",borderTop:s?"1px solid var(--danger-line)":"1px solid var(--success-line)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:k}),i&&b&&!t&&!s&&(0,d.jsx)(dh,{text:q??"",isEmpty:r,isError:!1})]})}let c5={read:"var(--accent)",write:"var(--warning)",glob:"var(--accent-hover)",grep:"var(--accent)",edit:"var(--warning)",bash:"var(--success)",todo:"var(--warning)",eval:"var(--accent-hover)",task:"var(--accent)",browser:"var(--accent-hover)",image:"var(--success)",generic:"var(--text-dim)"};function c6(a,b){let c=a.trim().toLowerCase();return c===b||c.endsWith(`.${b}`)||c.endsWith(`_${b}`)||c.split(/[.\s:_-]+/).includes(b)}function c7({toolName:a,isError:b}){let c,e=(c=a.trim().toLowerCase()).includes("str_replace")||c.includes("replace_editor")||c6(c,"edit")?"edit":c6(c,"read")||c6(c,"cat")?"read":c6(c,"write")||c6(c,"save")?"write":c6(c,"glob")||c6(c,"find")?"glob":c6(c,"grep")||c6(c,"search")?"grep":c6(c,"bash")||c6(c,"shell")||c6(c,"exec")?"bash":c6(c,"todo")?"todo":c6(c,"eval")?"eval":c6(c,"task")||c6(c,"agent")?"task":c6(c,"browser")||c6(c,"web_search")||c6(c,"fetch")?"browser":c6(c,"image")||c6(c,"inspect_image")?"image":"generic",f=b?"var(--danger)":c5[e];return(0,d.jsx)("span",{"aria-hidden":"true","data-tool-icon":e,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0,color:f},children:(0,d.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.15",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)(c8,{kind:e})})})}function c8({kind:a}){switch(a){case"read":return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,d.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,d.jsx)("path",{d:"M4.2 9.1c1.1-1.4 3.6-1.4 4.7 0-1.1 1.4-3.6 1.4-4.7 0Z"}),(0,d.jsx)("circle",{cx:"6.55",cy:"9.1",r:"0.7",fill:"currentColor",stroke:"none"})]});case"write":return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,d.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,d.jsx)("path",{d:"M6.55 6.25v4.15m-1.7-1.55 1.7 1.7 1.7-1.7"})]});case"glob":return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"M1.75 4.5A1.25 1.25 0 0 1 3 3.25h2.25l1.35 1.35h4.4A1.25 1.25 0 0 1 12.25 5.85v5.1A1.25 1.25 0 0 1 11 12.2H3a1.25 1.25 0 0 1-1.25-1.25V4.5Z"}),(0,d.jsx)("path",{d:"M9 7.1v3.8M7.1 9h3.8M7.65 7.65l2.7 2.7m0-2.7-2.7 2.7"})]});case"grep":return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("circle",{cx:"5.9",cy:"5.9",r:"3.25"}),(0,d.jsx)("path",{d:"m8.35 8.35 3.25 3.25"}),(0,d.jsx)("path",{d:"M4.6 5.2h2.5M4.6 6.8h1.7"})]});case"edit":return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,d.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,d.jsx)("path",{d:"m4.45 10.55 4.75-4.75 1.45 1.45-4.75 4.75-1.95.5.5-1.95Z"}),(0,d.jsx)("path",{d:"m8.45 6.55 1.45 1.45"})]});case"bash":return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("rect",{x:"1.5",y:"2.1",width:"11",height:"9.8",rx:"1.3"}),(0,d.jsx)("path",{d:"m4 5.2 1.8 1.8L4 8.8M7.2 8.8h2.3"})]});case"todo":return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7"}),(0,d.jsx)("path",{d:"m1.5 3.1 1 1 1.7-1.9M1.5 6.85l1 1 1.7-1.9M1.5 10.6l1 1 1.7-1.9"})]});case"eval":return(0,d.jsx)(d.Fragment,{children:(0,d.jsx)("path",{d:"m5 2.5-3 4.5 3 4.5M9 2.5l3 4.5-3 4.5M7.8 2 6.2 12"})});case"task":return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("circle",{cx:"3.1",cy:"3.2",r:"1.25"}),(0,d.jsx)("circle",{cx:"10.9",cy:"3.2",r:"1.25"}),(0,d.jsx)("circle",{cx:"10.9",cy:"10.8",r:"1.25"}),(0,d.jsx)("path",{d:"M4.35 3.2h2.1a2.9 2.9 0 0 1 2.9 2.9v3.45"}),(0,d.jsx)("path",{d:"M9.35 3.2h-1.1"})]});case"browser":return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("circle",{cx:"7",cy:"7",r:"5.2"}),(0,d.jsx)("path",{d:"M1.9 7h10.2M7 1.8c1.45 1.4 2.2 3.15 2.2 5.2S8.45 10.8 7 12.2C5.55 10.8 4.8 9.05 4.8 7S5.55 3.2 7 1.8Z"})]});case"image":return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("rect",{x:"1.75",y:"2.25",width:"10.5",height:"9.5",rx:"1.15"}),(0,d.jsx)("circle",{cx:"4.8",cy:"5.1",r:"1"}),(0,d.jsx)("path",{d:"m2.6 10 2.6-2.7 1.8 1.8 1.45-1.45 2.95 2.95"})]});case"generic":return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("rect",{x:"1.75",y:"2",width:"10.5",height:"10",rx:"1.3"}),(0,d.jsx)("path",{d:"M4.35 5h5.3M4.35 7.35h3.8M4.35 9.7h4.6"})]})}}function c9({phases:a}){let b=a.reduce((a,b)=>a+b.tasks.length,0),c=a.reduce((a,b)=>a+b.tasks.filter(a=>"completed"===a.status).length,0);return(0,d.jsxs)("div",{className:"todo-checklist-preview",role:"list","aria-label":`Todo ${b} tasks`,children:[(0,d.jsxs)("div",{className:"todo-checklist-header",children:[(0,d.jsxs)("svg",{className:"todo-checklist-icon",width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"}),(0,d.jsx)("path",{d:"m1.5 3.1 1 1 1.7-1.9M1.5 6.85l1 1 1.7-1.9M1.5 10.6l1 1 1.7-1.9",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]}),(0,d.jsx)("span",{className:"todo-checklist-title",children:"Todo"}),(0,d.jsxs)("span",{className:"todo-checklist-count",children:[b," ",1===b?"task":"tasks"]}),c>0&&c<b&&(0,d.jsxs)("span",{className:"todo-checklist-progress",children:[c,"/",b]})]}),(0,d.jsx)("div",{className:"todo-checklist-body",children:a.map((b,c)=>(0,d.jsxs)("div",{className:"todo-checklist-phase",children:[a.length>1&&(0,d.jsx)("div",{className:"todo-checklist-phase-name",children:b.name}),b.tasks.map((a,b)=>(0,d.jsx)(bY,{task:a},`${a.content}-${b}`))]},`${b.name}-${c}`))})]})}function da({command:a,output:b,pending:c,isError:e,duration:f,local:g}){let{isDark:h}=bq(),{t:i}=(0,x.s)(),j=an(b.split(/\r?\n/)),k=1===j.length&&""===j[0]?[]:j,l=c?i("chat.runningCommand"):e?"failed":"";return(0,d.jsxs)("div",{className:`shell-output-preview${e?" is-error":""}`,children:[(0,d.jsxs)("div",{className:"shell-command-line",children:[(0,d.jsx)("span",{className:"shell-command-prompt","aria-hidden":"true",children:"$"}),(0,d.jsx)(aT.A,{className:"shell-command-code",language:"bash",style:h?aU.xJ:aU.vs,PreTag:"span",CodeTag:"span",wrapLongLines:!0,customStyle:{flex:1,minWidth:0,margin:0,padding:0,border:"none",overflow:"visible",background:"transparent",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.55,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:a||" "}),g&&(0,d.jsx)("span",{className:"shell-local-label",children:"local"})]}),(0,d.jsxs)("div",{className:"shell-output-panel",children:[(0,d.jsxs)("div",{className:"shell-output-divider",children:[(0,d.jsx)("span",{className:"shell-output-label",children:"Output"}),l&&(0,d.jsx)("span",{className:`shell-output-status${e?" is-error":c?" is-pending":""}`,children:l})]}),(0,d.jsxs)("div",{className:"shell-output-body","aria-live":c?"polite":void 0,children:[0===k.length&&!c&&(0,d.jsx)("span",{className:"shell-output-empty",children:i("i18n.noOutput")}),k.map((a,b)=>{let c=aj(a).trimStart(),f=e||/^(?:error|fatal|failed|failure|✖|x\b)/i.test(c)?"is-error":/^(?:warning|warn|!)/i.test(c)?"is-warning":/^(?:success|passed|ok\b|✓|\+)/i.test(c)?"is-success":"";return(0,d.jsxs)("div",{className:`shell-output-line ${f}`.trim(),children:[ao(a).map((a,b)=>Object.keys(a.style).length>0?(0,d.jsx)("span",{style:a.style,children:a.text},b):(0,d.jsx)("span",{children:a.text},b)),""===a?"\xa0":null]},b)}),c&&(0,d.jsx)("span",{className:"shell-output-pending","aria-label":i("chat.runningCommand"),children:"▋"})]})]}),void 0!==f&&(0,d.jsxs)("div",{className:"shell-output-footer",children:[f,"s"]})]})}function db({diff:a}){return(0,d.jsx)("div",{style:{borderTop:"1px solid var(--success-line)",background:"var(--bg)"},children:(0,d.jsx)(dc,{text:a.text})})}function dc({text:a}){let{t:b}=(0,x.s)(),c=(0,e.useMemo)(()=>bW(a),[a]);if(!c)return(0,d.jsx)(df,{text:a});let f=c.length>1;return(0,d.jsx)("div",{style:{background:"var(--bg)"},children:c.map((a,c)=>(0,d.jsxs)("div",{style:{minWidth:0,borderTop:0===c?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55},children:[f&&(0,d.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,d.jsx)(dd,{title:a.oldPath||b("i18n.before"),side:"left"}),(0,d.jsx)(dd,{title:a.newPath||b("i18n.after"),side:"right"})]}),(0,d.jsx)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)"},children:a.rows.map((a,b)=>"hunk"===a.type?null:(0,d.jsxs)("div",{style:{display:"contents"},children:[(0,d.jsx)(de,{cell:a.left,side:"left"}),(0,d.jsx)(de,{cell:a.right,side:"right"})]},b))})]},c))})}function dd({title:a,side:b}){return(0,d.jsx)("div",{title:a,style:{padding:"5px 10px",color:"var(--text-dim)",borderRight:"left"===b?"1px solid var(--border)":"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a})}function de({cell:a,side:b}){let c="added"===a.type?"var(--success-soft)":"removed"===a.type?"var(--danger-soft)":"empty"===a.type?"var(--bg-subtle)":"transparent",e="added"===a.type?"+":"removed"===a.type?"-":" ",f="added"===a.type?"var(--success)":"removed"===a.type?"var(--danger)":"var(--text-dim)";return(0,d.jsxs)("div",{style:{display:"flex",minWidth:0,background:c,borderRight:"left"===b?"1px solid var(--border)":"none"},children:[(0,d.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:a.lineNo??""}),(0,d.jsx)("span",{style:{width:18,padding:"0 5px",color:f,userSelect:"none",fontWeight:"context"===a.type||"empty"===a.type?400:700,flexShrink:0},children:e}),(0,d.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===a.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:a.text||"\xa0"})]})}function df({text:a}){let b=a.split(/\r?\n/);return(0,d.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55,minWidth:0},children:b.map((a,b)=>{let c=a.startsWith("@@")?"hunk":a.startsWith("+")&&!a.startsWith("+++")?"added":a.startsWith("-")&&!a.startsWith("---")?"removed":"context";return(0,d.jsxs)("div",{style:{display:"flex",background:"added"===c?"var(--success-soft)":"removed"===c?"var(--danger-soft)":"hunk"===c?"var(--accent-soft)":"transparent",borderLeft:"added"===c?"3px solid var(--success)":"removed"===c?"3px solid var(--danger)":"hunk"===c?"3px solid var(--accent)":"3px solid transparent"},children:[(0,d.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:b+1}),(0,d.jsx)("span",{style:{padding:"0 10px",whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:"added"===c?"var(--success)":"removed"===c?"var(--danger)":"hunk"===c?"var(--accent)":"var(--text)"},children:a||"\xa0"})]},b)})})}function dg(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function dh({text:a,isEmpty:b,isError:c}){let{t:e}=(0,x.s)();return(0,d.jsx)("div",{style:{borderTop:`1px solid ${c?"var(--danger-line)":"var(--success-line)"}`,background:c?"var(--danger-soft)":"var(--bg-subtle)"},children:(0,d.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:c?"var(--danger)":b?"var(--text-dim)":"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",maxHeight:400,background:"var(--bg)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontStyle:b?"italic":"normal",opacity:b?.6:1},children:b?e("i18n.noOutput"):a})})}function di({message:a}){let{t:b}=(0,x.s)(),c=dm(a.content),f=(0,e.useMemo)(()=>{let a,b,d,e,f;return a=[],b=[],d=c.match(by),e=d?.[1]??"",f=d?.index===void 0?c:c.slice(0,d.index),e.replace(bx,(c,d,e)=>{let f=e.split(/\r?\n/).map(a=>a.trim()).filter(Boolean);return"read-files"===d?a.push(...f):b.push(...f),""}),{body:f.trim(),readFiles:a,modifiedFiles:b}},[c]),g=cW(a.timestamp),h=a.details&&"object"==typeof a.details&&"tokensBefore"in a.details&&"number"==typeof a.details.tokensBefore&&a.details.tokensBefore>0?a.details.tokensBefore:null;return(0,d.jsx)("div",{style:{marginBottom:16},children:(0,d.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,d.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,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:"compaction"}),null!==h&&(0,d.jsx)("span",{style:{fontSize:11},children:b("chat.compactedFrom",{tokens:bz(h)})}),g&&(0,d.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:g})]}),(0,d.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,d.jsx)("div",{style:{color:"var(--text)",fontSize:15,fontWeight:700,lineHeight:1.35},children:b("i18n.conversationCompacted")}),(0,d.jsx)("div",{style:{marginTop:3,marginBottom:10,color:"var(--text)",fontSize:14,lineHeight:1.5},children:b("i18n.compactionDescription")}),f.body?(0,d.jsx)(bw,{className:"markdown-compaction-message",children:f.body}):(0,d.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:b("i18n.noSummary")}),(0,d.jsx)(dj,{readFiles:f.readFiles,modifiedFiles:f.modifiedFiles})]})]})})}function dj({readFiles:a,modifiedFiles:b}){let{t:c}=(0,x.s)();if(0===a.length+b.length)return null;let e=[];return a.length>0&&e.push(`${a.length} read`),b.length>0&&e.push(`${b.length} modified`),(0,d.jsxs)("details",{className:"compaction-file-details",children:[(0,d.jsx)("summary",{children:c("i18n.fileContext",{details:e.join(", ")})}),b.length>0&&(0,d.jsx)(dk,{title:c("i18n.modifiedFiles"),files:b}),a.length>0&&(0,d.jsx)(dk,{title:c("i18n.readFiles"),files:a})]})}function dk({title:a,files:b}){return(0,d.jsxs)("div",{className:"compaction-file-section",children:[(0,d.jsx)("div",{className:"compaction-file-title",children:a}),(0,d.jsx)("ul",{className:"compaction-file-list",children:b.map(a=>(0,d.jsx)("li",{children:a},a))})]})}function dl({message:a,cwd:b,onOpenFile:c}){var f;let g,{t:h}=(0,x.s)(),i=!1===a.display,[j,k]=(0,e.useState)(!i),[l,m]=(0,e.useState)(!1),[n,o]=(0,e.useState)(!1),p=dm(a.content),q="string"==typeof(f=a.content)?[]:f.filter(a=>"image"===a.type),r=void 0!==a.details,s=r?function(a){try{return JSON.stringify(a,null,2)}catch{return String(a)}}(a.details):"",t=a.customType||"extension",u=cW(a.timestamp);return(0,d.jsx)("div",{style:{marginBottom:16},children:(0,d.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:i?"var(--bg-subtle)":"var(--bg)",opacity:i&&!j?.82:1},children:[(0,d.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,d.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:t}),i&&(0,d.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:h("i18n.hiddenExtensionMessage")}),u&&(0,d.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:u})]}),j?(0,d.jsxs)("div",{style:{padding:"6px 9px"},children:[q.length>0&&(0,d.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!p},children:q.map((a,b)=>{let c=dn(a);return c?(0,d.jsx)("img",{src:c,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}},b):null})}),p?(0,d.jsx)(bw,{className:"markdown-custom-message",cwd:b,onOpenFile:c,children:p}):(0,d.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:h("i18n.noMessage")})]}):(0,d.jsx)("button",{onClick:()=>k(!0),style:{display:"block",width:"100%",padding:"8px 10px",border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:12,textAlign:"left"},children:p?(g=p.replace(/\s+/g," ").trim())?g.length>140?`${g.slice(0,140)}...`:g:"Show extension message":h("i18n.showExtensionMessage")}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[p||s?(0,d.jsx)("button",{onClick:()=>{br(p||s).then(()=>{o(!0),setTimeout(()=>o(!1),1500)})},style:{padding:"3px 7px",border:"none",background:"none",color:n?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:h(n?"i18n.copied":"i18n.copy")}):null,(r||i)&&(0,d.jsx)("button",{onClick:()=>{i?k(a=>!a):m(a=>!a)},style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:h(i?j?"i18n.collapse":"i18n.expand":l?"i18n.hideDetails":"i18n.showDetails")})]}),r&&(i&&j||!i&&l)&&(0,d.jsx)("pre",{style:{margin:0,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto",fontFamily:"var(--font-mono)"},children:s})]})})}function dm(a){return"string"==typeof a?a:a.filter(a=>"text"===a.type).map(a=>a.text).join("\n")}function dn(a){return a.source?"base64"===a.source.type?`data:${a.source.media_type};base64,${a.source.data}`:a.source.url??"":a.data?`data:${a.mimeType};base64,${a.data}`:""}function dp({message:a,sessionId:b}){let[c,f]=(0,e.useState)(null),[g,h]=(0,e.useState)(!1),[i,j]=(0,e.useState)(null),k=!a.output&&void 0===a.exitCode&&!a.cancelled,l=a.cancelled||void 0!==a.exitCode&&0!==a.exitCode,m=b&&a.fullOutputPath?`/api/agent/${encodeURIComponent(b)}/bash-output?path=${encodeURIComponent(a.fullOutputPath)}`:null,n=a.truncated&&m&&null===c,o=c??a.output;async function p(){if(m){h(!0),j(null);try{let a=await fetch(m),b=await a.json();b.success?f(b.data?.output??""):j(b.error??"failed")}catch(a){j(String(a))}finally{h(!1)}}}let q=a.excludeFromContext?"bash (local)":"bash",r={type:"toolCall",toolCallId:`bash-${a.timestamp??""}`,toolName:q,input:{command:a.command}},s=k?void 0:{role:"toolResult",toolCallId:r.toolCallId,toolName:q,content:o?[{type:"text",text:o}]:[],isError:l,timestamp:a.timestamp};return(0,d.jsxs)("div",{style:{margin:"6px 0"},children:[(0,d.jsx)(c4,{block:r,result:s}),a.truncated&&m&&(0,d.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[n&&(0,d.jsx)("button",{onClick:p,disabled:g,style:{background:"none",border:"none",color:"var(--accent)",cursor:g?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:g?"loading…":"view full output"}),(0,d.jsx)("a",{href:`${m}&download=1`,style:{marginLeft:10*!!n,color:"var(--accent)",fontSize:11,textDecoration:"underline"},children:"download full output"}),i&&(0,d.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:["(",i,")"]})]})]})}function dq({summary:a,onJump:b,onOpenPanel:c}){let{st:e}=bT();if(!a)return null;let{target:f}=a,g=f.position;if(null===g&&!c)return null;let h=e(null!==g?"dock.jump":"dock.openPanel",{title:f.maker.title});return(0,d.jsxs)("button",{type:"button",className:"run-status-line answer-dock-line","data-tone":"accent",title:h,onClick:()=>{null!==g?b(g,f.maker.member.key):c?.()},children:[(0,d.jsx)("span",{className:"run-status-label",children:e("dock.label")}),(0,d.jsxs)("span",{className:"answer-dock-counts",children:[a.running>0&&(0,d.jsx)("span",{className:"answer-dock-count","data-phase":"running",children:e("dock.running",{count:a.running})}),a.awaiting>0&&(0,d.jsx)("span",{className:"answer-dock-count","data-phase":"awaiting",children:e("dock.awaiting",{count:a.awaiting})})]}),(0,d.jsx)("span",{className:"answer-dock-title",children:f.maker.title}),(0,d.jsx)("svg",{className:"answer-dock-go",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("polyline",{points:"18 15 12 9 6 15"})})]})}c(57582);let dr=/(?:^|[^\w-])(?:tests?|typecheck|tsc|lint|eslint|vitest|jest|pytest|build|check|verify|smoke)(?![\w])/i;function ds({open:a,onClose:b,containerRef:c,index:f,renderedStart:g,renderedEnd:h,contentKey:i,onReveal:j,onProgrammaticScroll:k,focusRequest:l,t:m}){let n=(0,e.useRef)(null),[o,p]=(0,e.useState)(""),[q,r]=(0,e.useState)(null),[s,t]=(0,e.useState)({index:-1,total:0}),u=(0,e.useDeferredValue)(o);a&&u.trim().toLowerCase();let v=(0,e.useRef)(q);v.current=q;let w=(0,e.useRef)([]);(0,e.useRef)({key:null,needle:"",rendered:!1});let x=(0,e.useCallback)(a=>{let b=w.current;if(0===b.length)return;let c=function(a,b){if(0===a.length)return -1;if(!b)return 0;let c=-1;for(let d=0;d<a.length;d++){let e=a[d];if(e.item===b.item){if(e.k===b.k)return d;c=d}}return -1===c?0:c}(b,v.current);r(b[(c+a+b.length)%b.length])},[]);if(!a)return null;let y=o.trim().length>0?0===s.total?m("chat.searchNoResults"):m("chat.searchCount",{index:s.index+1,total:s.total}):"";return(0,d.jsxs)("div",{className:"chat-find-bar",role:"search","data-dismissible-layer":"",onKeyDown:a=>{"Escape"===a.key&&(a.preventDefault(),a.stopPropagation(),b())},children:[(0,d.jsx)("input",{ref:n,type:"search",value:o,onChange:a=>p(a.target.value),onKeyDown:a=>{"Enter"!==a.key||a.nativeEvent.isComposing||(a.preventDefault(),x(a.shiftKey?-1:1))},placeholder:m("chat.searchPlaceholder"),"aria-label":m("chat.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),(0,d.jsx)("span",{className:"chat-find-count","aria-live":"polite",children:y}),(0,d.jsx)("button",{type:"button",onClick:()=>x(-1),disabled:0===s.total,"aria-label":m("chat.searchPrevious"),title:`${m("chat.searchPrevious")} (Shift+Enter)`,children:(0,d.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,d.jsx)("button",{type:"button",onClick:()=>x(1),disabled:0===s.total,"aria-label":m("chat.searchNext"),title:`${m("chat.searchNext")} (Enter)`,children:(0,d.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m6 9 6 6 6-6"})})}),(0,d.jsx)("button",{type:"button",onClick:b,"aria-label":m("chat.searchClose"),title:`${m("chat.searchClose")} (Esc)`,children:(0,d.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,d.jsx)("path",{d:"M18 6 6 18"}),(0,d.jsx)("path",{d:"m6 6 12 12"})]})})]})}function dt({questions:a,containerRef:b,layoutKey:c,onJump:f,label:g}){let h=(0,e.useRef)(null),[i,j]=(0,e.useState)(-1),[k,l]=(0,e.useState)(!1),m=k&&a.length>=2,n=a.length,o=(0,e.useCallback)((a,b)=>{let c="ArrowUp"===a.key?b-1:"ArrowDown"===a.key?b+1:"Home"===a.key?0:"End"===a.key?n-1:null;if(null===c)return;a.preventDefault();let d=Math.max(0,Math.min(n-1,c));h.current?.querySelectorAll("button")[d]?.focus()},[n]);if(!m)return null;let p=a.some(a=>a.item===i)?i:a[0].item;return(0,d.jsx)("nav",{className:"question-rail","aria-label":g,children:(0,d.jsx)("div",{ref:h,className:"question-rail-list",children:a.map((a,b)=>(0,d.jsx)(du,{question:a,position:b,count:n,active:a.item===i,focusable:a.item===p,onJump:f,onMoveFocus:o},a.item))})})}let du=(0,e.memo)(function({question:a,position:b,count:c,active:e,focusable:f,onJump:g,onMoveFocus:h}){let i=a.text.length>140?`${a.text.slice(0,140)}…`:a.text;return(0,d.jsx)("button",{type:"button",className:"question-rail-tick",tabIndex:f?0:-1,"aria-current":e?"true":void 0,"aria-label":`${b+1}/${c} ${i}`,title:i,onClick:()=>g(a.item),onKeyDown:a=>h(a,b),children:(0,d.jsx)("span",{"aria-hidden":"true"})})});function dv({label:a,tone:b,children:c}){return(0,d.jsxs)("div",{className:"run-status-line","data-tone":b,role:"status","aria-live":"polite",children:[(0,d.jsx)("span",{className:"run-status-label",children:a}),(0,d.jsx)("span",{className:"run-status-text",children:c})]})}let dw={manual:!0,threshold:!0,overflow:!0,idle:!0,incomplete:!0};function dx({compaction:a,t:b}){let[c,f]=(0,e.useState)(()=>Date.now());if(!a)return null;let g=Math.max(0,Math.floor((c-a.startedAt)/1e3)),h=a.reason&&!0===dw[a.reason]?b(`chat.compactionReason.${a.reason}`):null;return(0,d.jsxs)(dv,{label:b("chat.compactionLabel"),tone:"accent",children:[b("chat.compactionProgress",{seconds:g}),h?` \xb7 ${h}`:""]})}function dy({onDismiss:a,t:b}){return(0,d.jsxs)("div",{className:"interrupted-run-notice",role:"status",children:[(0,d.jsx)("span",{className:"interrupted-run-mark","aria-hidden":"true"}),(0,d.jsxs)("span",{className:"interrupted-run-text",children:[(0,d.jsx)("strong",{children:b("chat.interruptedTitle")}),(0,d.jsx)("span",{children:b("chat.interruptedDetail")})]}),(0,d.jsx)("button",{type:"button",onClick:a,"aria-label":b("chat.interruptedDismiss"),title:b("chat.interruptedDismiss"),children:(0,d.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,d.jsx)("path",{d:"M18 6 6 18"}),(0,d.jsx)("path",{d:"m6 6 12 12"})]})})]})}var dz=c(50761),dA=c.n(dz);let dB=["YUKI(유키)","ISANA(이사나)","MIO(미오)","RIN(린)","NOVA(노바)","SHION(시온)","HIKARI(히카리)"],dC={"YUKI(유키)":"yuki","ISANA(이사나)":"isana","MIO(미오)":"mio","RIN(린)":"rin","NOVA(노바)":"nova","SHION(시온)":"shion","HIKARI(히카리)":"hikari"},dD=["approval","choice","done","failed","blocked","working"],dE={approval:"부름",choice:"물음",done:"기쁨",failed:"사과",blocked:"난처",working:"시작"},dF={approval:!1,choice:!1,done:!1,failed:!1,blocked:!1,working:!0};function dG(a){return void 0===a?"done":"string"==typeof a&&Object.hasOwn(dE,a)?a:null}function dH(a,b){let c=new Map,d=new Map;if(!Array.isArray(a))return{files:c,lines:d};for(let e of a){if("object"!=typeof e||null===e)continue;let{file:a,tag:f,ko:g}=e;if("string"!=typeof a||""===a)continue;let h=dG(f);if(null===h)continue;let i=b+a.replace(/^\/+/,""),j=c.get(h);j?j.push(i):c.set(h,[i]),"string"==typeof g&&""!==g.trim()&&d.set(i,g.trim())}return{files:c,lines:d}}async function dI(a=fetch){try{let b=await a("/audio/completion/voices.json");if(!b.ok)return new Map;return function(a){let b=new Map;if("object"!=typeof a||null===a)return b;let{characters:c}=a;if(!Array.isArray(c))return b;for(let a of c){if("object"!=typeof a||null===a)continue;let{id:c,clips:d,stickers:e,captions:f}=a;if("string"!=typeof c||""===c)continue;let g=dH(d,"/audio/completion/"),h=dH(e,"/stickers/"),i=function(a){let b=new Map;if(!Array.isArray(a))return b;for(let c of a){if("object"!=typeof c||null===c)continue;let{tag:a,ko:d}=c;if("string"!=typeof d||""===d.trim())continue;let e=dG(a);if(null===e)continue;let f=b.get(e);f?f.push(d.trim()):b.set(e,[d.trim()])}return b}(f),j=new Map;for(let a of dD){let b=g.files.get(a)??[],c=new Map;for(let a of b){let b=g.lines.get(a);void 0!==b&&c.set(a,b)}j.set(a,{voices:b,stickers:h.files.get(a)??[],lines:c,captions:i.get(a)??[]})}b.set(c,j)}return b}(await b.json())}catch{return new Map}}function dJ(a,b,c=Math.random){if(0===a.length)return null;if(1===a.length)return a[0];let d=null===b?-1:a.indexOf(b),e=-1===d?a.length:a.length-1,f=Math.min(e-1,Math.max(0,Math.floor(c()*e)));return a[-1!==d&&f>=d?f+1:f]}function dK(a){let b=[];if("bashExecution"!==a.role){if("string"==typeof a.content)b.push(a.content.trim());else for(let c of a.content)if("text"===c.type)b.push(c.text.trim());else if("toolCall"===c.type){let a="id"in c&&"string"==typeof c.id?c.id:"";b.push(`toolCall:${c.toolCallId||a}`)}}let c="toolResult"===a.role?a.toolCallId:"custom"===a.role?a.customType:"bashExecution"===a.role?a.command:null;return JSON.stringify([a.role,c,b.filter(Boolean)])}let dL=["01","02","03"];function dM(a,b,c){if(!a||"streaming"===b||!dB.includes(a))return null;let d="failed"===b?"failed":"done",e=a.slice(0,a.indexOf("(")).toLowerCase(),f=dJ(dL.map(a=>`/stickers/${e}/${d}/${a}.webp`),null,()=>(function(a){let b=0x811c9dc5;for(let c=0;c<a.length;c+=1)b=Math.imul(b^a.charCodeAt(c),0x1000193);return(b>>>0)/0x100000000})(c));return f?{src:f,alt:dE[d]}:null}let dN=new Map,dO=(0,e.createContext)(dN);function dP({utterances:a,children:b}){return(0,d.jsx)(dO.Provider,{value:a,children:b})}function dQ({turnIndex:a,turnEntryId:b,sessionId:c,cwd:f,onOpenFile:g}){let h=(0,e.useContext)(dO).get(a);return h&&0!==h.length?(0,d.jsx)("div",{className:"inline-utterance-thread","data-turn":a,"data-turn-entry":b,style:{display:"contents"},children:h.map(a=>(0,d.jsx)(dR,{utterance:a,sessionId:c,cwd:f,onOpenFile:g},a.key))}):null}function dR({utterance:a,sessionId:b,cwd:c,onOpenFile:f}){let g=bQ(null===a.accountSessionId?void 0:a.accountSessionId??b,a.provider,a.credentialId),[h,i]=(0,e.useState)(!1),[j,k]=(0,e.useState)(!1),l=(0,e.useRef)(null),m=a.text.trim().length>0,n=a.label?.trim(),o=g?.alias??n??(0,bJ.bN)(a.provider),p=g?.alias.split("(",1)[0]?.trim(),q=g&&n&&n!==g.alias&&n!==p?`작업 \xb7 ${n}`:null,r=dM(g?.alias,a.status,a.key),s="failed"===a.status?"중단됨":"streaming"===a.status&&m?"작업 중":null;return(0,d.jsxs)("div",{className:"inline-utterance","data-status":a.status,style:{marginBottom:16},children:[(0,d.jsxs)("div",{className:"inline-utterance-role",style:{display:"flex",alignItems:"center",gap:9,marginBottom:2,fontSize:11,color:"var(--text-dim)",...g?{minHeight:40}:null},children:[g&&(0,d.jsx)(bU,{seed:g.seed,size:40,provider:a.provider}),(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[(0,d.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:o}),s&&(0,d.jsx)("span",{style:{color:"failed"===a.status?"var(--danger)":"var(--text-dim)"},children:s})]}),q&&(0,d.jsx)("div",{style:{marginTop:1,fontSize:11,lineHeight:1.35,color:"var(--text-muted)",overflowWrap:"anywhere"},children:q})]})]}),m?(0,d.jsx)("div",{ref:l,style:{fontSize:12.5,lineHeight:1.6,...h?null:{maxHeight:240,overflow:"hidden"}},children:(0,d.jsx)(bw,{isStreaming:"streaming"===a.status,cwd:c,onOpenFile:f,children:a.text})}):(0,d.jsx)("div",{role:"status",style:{color:"var(--text-muted)",fontSize:11.5,lineHeight:1.6},children:"failed"===a.status?"발화 없이 중단되었습니다":"아직 발화가 없습니다"}),m&&(j||h)&&(0,d.jsx)("button",{type:"button",onClick:()=>i(a=>!a),"aria-expanded":h,style:{marginTop:4,padding:"3px 9px",height:22,border:"1px solid var(--border)",borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:h?"접기":"더보기"}),r&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("img",{src:r.src,alt:r.alt,style:{display:"block",width:"min(148px, 34vw)",maxWidth:"100%",height:"auto"},className:"jsx-8e1a78d1ba768be9 inline-utterance-sticker"}),(0,d.jsx)(dA(),{id:"8e1a78d1ba768be9",children:".inline-utterance-sticker{transform-origin:center 75%;animation:inline-utterance-sticker-pop 200ms cubic-bezier(0,0,.15,1)both}@keyframes inline-utterance-sticker-pop{from{opacity:0;transform:scale(.88)}to{opacity:1;transform:scale(1)}}@media(prefers-reduced-motion:reduce){.inline-utterance-sticker{animation:none}}"})]})]})}let dS=/^\[character-summon alias="([^"\r\n]+)" model="([^"\r\n]+)"(?: oauth-position="\d+")?\]\r?$/mu;function dT(a,b,c,d){if("string"!=typeof c)return[];let e=dS.exec(c),f=e?.[1],g=e?.[2];return f&&g?[{toolCallId:a,...b?{name:b}:{},alias:f,model:g,batchSize:d}]:[]}function dU(a){if(!a||"assistant"!==a.role)return[];let b=[];for(let c of a.content??[]){if("toolCall"!==c.type||"task"!==c.toolName)continue;let a=c.input,d=+(void 0!==a.task)+(Array.isArray(a.tasks)?a.tasks.length:0);if(b.push(...dT(c.toolCallId,"string"==typeof a.name?a.name:void 0,a.task,d)),Array.isArray(a.tasks))for(let e of a.tasks)!e||"object"!=typeof e||Array.isArray(e)||b.push(...dT(c.toolCallId,"name"in e&&"string"==typeof e.name?e.name:void 0,"task"in e?e.task:void 0,d))}return b}function dV(a){if(!a||"assistant"!==a.role)return[];let b=[];for(let c of a.content??[])"toolCall"===c.type&&"task"===c.toolName&&b.push(c.toolCallId);return b}let dW=/^agent:\/\/([^/?#]+)\/?$/i;function dX(a,b){if(!a||"assistant"!==a.role)return[];let c=[];for(let d of a.content??[]){if("toolCall"!==d.type||"write"!==d.toolName)continue;let a=d.input,e="string"==typeof a.path?dW.exec(a.path):null,f=e?.[1],g=a.content;if(!f||"string"!=typeof g)continue;let h=b?.get(d.toolCallId);c.push({toolCallId:d.toolCallId,to:f,message:g,...h?.from?{from:h.from}:{},...h?.receipts?{receipts:h.receipts}:{}})}return c}var dY=c(38662);let dZ=["greeting","utterance","message","text"],d$=function(a){let b=(0,e.useMemo)(()=>(0,b4.Et)(),[]),c=function(a){let[b,c]=(0,e.useState)(null);return b}(a.sessionId),d=(0,e.useMemo)(()=>{let b=new Set(a.subagents.map(a=>a.id)),d=[];if(c&&c.sessionId===a.sessionId){let e=a.turns.flatMap(a=>a.characterSummons);for(let f of c.subagents){if(b.has(f.name))continue;let c=[...e].reverse().find(a=>a.name===f.name);c&&d.push(function(a,b,c){let d=a.status??"unknown",e={id:a.name,index:c,agent:"",agentSource:"bundled",status:d,task:a.firstTask||void 0,lastUpdate:a.modified,parentToolCallId:b.toolCallId},f="string"==typeof a.model&&a.model.trim()?a.model.trim():void 0,g="string"==typeof a.errorMessage&&a.errorMessage.trim()?a.errorMessage.trim():void 0;return(void 0!==f||void 0!==g)&&(e.progress={index:c,id:a.name,agent:"",status:d,task:a.firstTask,recentTools:[],recentOutput:[],toolCount:0,requests:0,tokens:0,cost:0,durationMs:0,...void 0!==f?{resolvedModel:f,resolvedModelIsFallback:!0===a.modelIsFallback}:{},...void 0!==g?{retryFailure:{attempt:0,errorMessage:g}}:{}}),e}(f,c,a.subagents.length+d.length))}}return function(a,b){let c=new Map;for(let b of a)for(let a of b.characterSummons){let d=c.get(a.toolCallId)??{turnIndex:b.index,requests:[]};d.requests.push(a),c.set(a.toolCallId,d)}return b.flatMap(b=>{let d=b.parentToolCallId?c.get(b.parentToolCallId):void 0;if(!d)return[];let e=d.requests.filter(a=>a.name),f="string"==typeof b.task?dS.exec(b.task):null,g=f?.[1],h=f?.[2],i=e.find(a=>a.name===b.id)??(g&&h?d.requests.find(a=>a.alias===g&&a.model===h):void 0)??(1===d.requests.length&&1===d.requests[0].batchSize?d.requests[0]:void 0);if(!i)return[];let j=a.flatMap(a=>a.peerSends.filter(a=>a.to===b.id||"all"===a.to).map(b=>({turnIndex:a.index,send:b})));return[{snapshot:b,turnIndex:d.turnIndex,summon:i,sends:j}]})}(a.turns,[...a.subagents,...d])},[a.subagents,a.turns,a.sessionId,c]),f=(0,e.useMemo)(()=>d.map(({snapshot:b})=>{let c=b.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||b.id;return a.subagents.some(a=>a.id===b.id)?{key:b.id,liveId:b.id,status:b.status,archiveName:c}:{key:b.id,status:b.status,archiveName:c}}),[d,a.subagents]),g=(0,dY._Z)(f,{sessionId:a.sessionId??"",client:b,enabled:!!a.sessionId&&f.length>0});return(0,e.useMemo)(()=>d.flatMap(b=>(function(a,b,c){var d;let{snapshot:e,summon:f}=a,g="completed"===(d=e.status)||"unknown"===d?"settled":"failed"===d||"aborted"===d?"failed":"streaming",h="failed"===g,i=f?.model.split("/",1)[0]?.trim()||void 0,j=h&&i?i:function(a,b,c){let d="string"==typeof a.progress?.resolvedModel?a.progress.resolvedModel.trim():"",e=d.indexOf("/");if(e>0)return d.slice(0,e);let f=b?.model.trim()??"",g=f.indexOf("/");return g>0?f.slice(0,g):c?.trim()||void 0}(e,f,c),k=e.id.trim()||void 0,l=`subagent:${e.id}`,m=[],n=a.turnIndex,o=0;if((b?.entries??[]).forEach((b,c)=>{var d;let p;if("irc"in b){let{from:c,message:d,truncated:f}=b.irc;if(f||"string"!=typeof c||"string"!=typeof d)return;for(let b=o;b<a.sends.length;b+=1){let f=a.sends[b];if(f.send.message===d&&function(a,b){if(!a.from)return!1;let c=a.receipts;return!!c&&c.some(a=>a.to===b&&("injected"===a.outcome||"woken"===a.outcome||"revived"===a.outcome))}(f.send,e.id)&&f.send.from===c){n=f.turnIndex,o=b+1;break}}return}if("assistant"!==b.message.role)return;let q=b.message.provider||j;if(!q||h&&i&&q!==i)return;let r=((p=((d=b.message).content??[]).filter(a=>"text"===a.type).map(a=>a.text.trim()).filter(a=>a.length>0).join("\n\n")).length>0?p:function(a){let b="";for(let c of a.content??[]){if("toolCall"!==c.type||"yield"!==c.toolName)continue;let a=c.input.data,d="";if("string"==typeof a)d=a;else if("object"==typeof a&&null!==a&&!Array.isArray(a))for(let b of["report",...dZ]){let c=a[b];if("string"==typeof c&&c.trim().length>0){d=c;break}}let e=d.trim();e.length>0&&(b=e)}return b}(d))||(h?b.message.errorMessage?.trim()??"":"");0!==r.length&&m.push({key:`${e.id}:${c}`,turnIndex:n,speakerId:l,provider:q,credentialId:b.message.credentialId,accountSessionId:null,label:h&&f?f.alias:k,text:r,status:g})}),0===m.length&&"settled"!==g&&j){let a=h?e.progress?.retryFailure?.errorMessage?.trim():void 0;m.push({key:`${e.id}:pending`,turnIndex:n,speakerId:l,provider:j,accountSessionId:null,label:h&&f?f.alias:k,text:a||"",status:g})}return m})(b,g.get(b.snapshot.id),a.sessionProvider)),[d,g,a.sessionProvider])},d_="web6",d0=[],d1=[],d2=function(a){(0,e.useMemo)(()=>(function(a=(a,b)=>fetch(a,b),b="/api/web6/consults"){return{async listConsults(c,d){let e=c.trim();if(!e)throw Error("sessionId가 필요하다");let f=`${b}?sessionId=${encodeURIComponent(e)}`,g=await a(f,{signal:d});if(!g.ok)throw Error(`HTTP ${g.status}`);let h=await g.json(),i=h&&"object"==typeof h&&"consults"in h?h.consults:null;if(!Array.isArray(i))throw Error("consults 배열이 아니다");return i.flatMap(a=>{let b=function(a){if(!a||"object"!=typeof a||Array.isArray(a))return null;let b="string"==typeof a.sessionId?a.sessionId.trim():"";if(!b)return null;let c=a.startedAt;if("number"!=typeof c||!Number.isFinite(c))return null;let d=a.status;if("ok"!==d&&"failed"!==d)return null;let e="number"==typeof a.finishedAt&&Number.isFinite(a.finishedAt)?a.finishedAt:c,{conversationId:f,text:g,error:h}=a;return{sessionId:b,startedAt:c,finishedAt:e,elapsedMs:"number"==typeof a.elapsedMs&&Number.isFinite(a.elapsedMs)?a.elapsedMs:e-c,model:"string"==typeof a.model?a.model:"",status:d,conversationId:"string"==typeof f&&""!==f?f:void 0,text:"string"==typeof g&&""!==g?g:void 0,error:"string"==typeof h&&""!==h?h:void 0}}(a);return b?.sessionId===e?[b]:[]})}}})(),[]);let[b,c]=(0,e.useState)(d1);(0,e.useRef)("");let d=a.sessionId??"";return d.length,(0,e.useMemo)(()=>(function(a,b,c){if(0===a.length)return d0;let d=function(a){let b=[];for(let c=0;c<a.length;c+=1){let d=a[c];if("user"!==d.role)continue;let e=d.timestamp;"number"==typeof e&&Number.isFinite(e)&&b.push({index:c,openedAt:e})}return b}(b);if(0===d.length)return d0;let e=[];for(let b of[...a].sort((a,b)=>a.startedAt-b.startedAt)){if(b.sessionId!==c||"failed"!==b.status)continue;let a=function(a,b){let c;for(let d of a)d.openedAt>b||(!c||d.openedAt>=c.openedAt)&&(c=d);return c?.index}(d,b.startedAt);if(void 0===a)continue;let f=b.error??"";0!==f.trim().length&&e.push({key:`${d_}:${b.startedAt}:${b.finishedAt}`,turnIndex:a,provider:"web6",speakerId:`${d_}:${b.conversationId??"unknown"}`,text:f,status:"failed"})}return e.length>0?e:d0})(b,a.messages,d),[b,a.messages,d])},d3={sending:!0,accepted:!0,delivered:!1,unconfirmed:!1,failed:!1};function d4(a){return a.trim()}function d5(a){return d4(a.text)||(a.images>0?"[Image]":"")}function d6(a){let b=a.filter(a=>!d3[a.stage]);if(b.length<=4)return a;let c=new Set(b.slice(0,b.length-4).map(a=>a.id));return a.filter(a=>!c.has(a.id))}function d7(a,b){switch(b.type){case"submit":return d6([...a,{id:b.id,kind:b.kind,text:b.text,images:b.images??0,stage:"sending",inQueue:!1}]);case"ack":return a.map(a=>a.id===b.id&&"sending"===a.stage?{...a,stage:"accepted"}:a);case"fail":return d6(a.map(a=>a.id===b.id&&d3[a.stage]?{...a,stage:"failed",inQueue:!1}:a));case"queue":return function(a,b,c){let d=new Map,e=(a,b)=>{let c=`${a}\u0000${d4(b)}`;d.set(c,(d.get(c)??0)+1)};for(let a of b)e("steer",a);for(let a of c)e("followUp",a);let f=!1,g=a.map(a=>{if(!d3[a.stage])return a;let b=`${a.kind}\u0000${d5(a)}`,c=d.get(b)??0;return c>0?(d.set(b,c-1),a.inQueue&&"accepted"===a.stage)?a:(f=!0,{...a,stage:"accepted",inQueue:!0}):a.inQueue?(f=!0,{...a,stage:"unconfirmed",inQueue:!1}):a});return f?g:a}(a,b.steering,b.followUp);case"user-message":{let c=d4(b.text);if(!c&&0===b.images)return a;let d=a.find(a=>(d3[a.stage]||"unconfirmed"===a.stage)&&a.kind===b.kind&&d4(a.text)===c&&a.images===b.images);if(!d)return a;return d6(a.map(a=>a===d?{...a,stage:"delivered",inQueue:!1}:a))}case"withdraw":{let c=a=>d3[a.stage]||"unconfirmed"===a.stage;if(void 0===b.text)return a.filter(a=>!c(a));let d=d4(b.text),e=a.find(a=>c(a)&&a.kind===b.kind&&(d4(a.text)===d||d5(a)===d));return e?a.filter(a=>a!==e):a}case"idle":{let b=a.filter(a=>a.inQueue);return b.length===a.length?a:b}case"reset":return 0===a.length?a:[]}}let d8={steer:"delivery.kind.steer",followUp:"delivery.kind.followUp"},d9={sending:"delivery.stage.sending",accepted:"delivery.stage.accepted",delivered:"delivery.stage.delivered",unconfirmed:"delivery.stage.unconfirmed",failed:"delivery.stage.failed"};function ea({rows:a,removeLabel:b,onRemove:c}){let f,{st:g}=bT(),[h,i]=(0,e.useState)(!1),{rows:j,hidden:k}=(f=Math.max(0,a.length-4),h||0===f?{rows:a,hidden:f}:{rows:a.slice(f),hidden:f}),l=a.length>4;return(0,d.jsxs)(d.Fragment,{children:[l&&(0,d.jsx)("button",{type:"button",className:"answer-delivery-toggle","aria-expanded":h,onClick:()=>i(a=>!a),children:h?g("delivery.showRecent",{count:4}):g("delivery.showOlder",{count:k})}),(0,d.jsx)("ul",{className:"answer-delivery-list","aria-live":"polite",children:j.map(a=>{let e=cB(a.text),f=[e?[e.message,e.documents.map(a=>a.name).join(", ")].filter(Boolean).join(" \xb7 "):a.text.trim(),a.images>0?g("delivery.images",{count:a.images}):""].filter(Boolean).join(" \xb7 ");return(0,d.jsxs)("li",{className:"answer-delivery-row","data-kind":a.kind,"data-stage":a.stage,children:[(0,d.jsx)("span",{className:"answer-delivery-kind",children:g(d8[a.kind])}),(0,d.jsx)("span",{className:"answer-delivery-text",title:f,children:f}),(0,d.jsx)("span",{className:"answer-delivery-stage",children:g(d9[a.stage])}),a.removable&&c&&(0,d.jsx)("button",{type:"button",className:"answer-delivery-remove",title:b,"aria-label":`${b}: ${f}`,onClick:()=>c(a.kind,a.text),children:(0,d.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]},a.key)})})]})}let eb=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,d.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"})]}),ec=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,d.jsx)("path",{d:"m22 9-6 6m0-6 6 6"})]});function ed({soundEnabled:a,onToggle:b}){let c=a?"완료음 끄기":"완료음 켜기";return(0,d.jsx)("div",{role:"group","aria-label":"오디오",style:{display:"flex",alignItems:"center",gap:6},children:(0,d.jsx)("button",{type:"button",className:`composer-icon-button${a?" is-active":""}`,onClick:b,"aria-pressed":a,title:c,"aria-label":c,children:(0,d.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a?eb:ec})})})}let ee=RegExp("^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:(?:통화|전화)(?:를|좀|그만)*)?(?:좀|그만)*(?:끊어|끊어봐|끊을게|끊자|끊겠습니다|끊으라고)(?:줘|주세요|요)?$|^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:통화|전화)(?:를|좀|그만)*(?:종료|종료해|종료해봐|종료할게|종료하자|종료하라고)(?:줘|주세요|요)?$","u");class ef{#a;#b;#c;#d;#e;#f;constructor(a=()=>new AudioContext){this.#b=null,this.#c=0,this.#d=0,this.#e=null,this.#f=new Set,this.#a=a}unlock(){let a=this.#g();a?.state==="suspended"&&a.resume().catch(()=>{})}get speaking(){return this.#f.size>0}push(a,b){if(a<this.#c)return;a>this.#c&&this.reset(a);let c=this.#g();if(!c)return;let d=function(a){let b=atob(a),c=new Uint8Array(b.length);for(let a=0;a<b.length;a+=1)c[a]=b.charCodeAt(a);return c}(b);if(null!==this.#e){let a=new Uint8Array(d.length+1);a[0]=this.#e,a.set(d,1),d=a,this.#e=null}d.length%2==1&&(this.#e=d[d.length-1],d=d.subarray(0,d.length-1));let e=d.length/2;if(0===e)return;let f=c.createBuffer(1,e,24e3),g=f.getChannelData(0),h=new DataView(d.buffer,d.byteOffset,d.byteLength);for(let a=0;a<e;a+=1)g[a]=h.getInt16(2*a,!0)/32768;let i=c.createBufferSource();i.buffer=f,i.connect(c.destination);let j=Math.max(c.currentTime+.05,this.#d);i.onended=()=>{this.#f.delete(i)},this.#f.add(i),i.start(j),this.#d=j+f.duration}reset(a){for(let b of(this.#c=Math.max(this.#c,a),this.#d=0,this.#e=null,this.#f)){b.onended=null;try{b.stop()}catch{}}this.#f.clear()}close(){this.reset(this.#c);let a=this.#b;this.#b=null,a&&a.close().catch(()=>{})}#g(){if(this.#b&&"closed"!==this.#b.state)return this.#b;try{this.#b=this.#a()}catch{this.#b=null}return this.#b}}function eg(a){return a&&"object"==typeof a&&"mode"in a?"character"===a.mode&&"string"==typeof a.alias&&("accepted"===a.tuning||"provisional"===a.tuning)?{mode:"character",alias:a.alias,tuning:a.tuning}:"native"===a.mode&&("no-key"===a.reason||"character-unknown"===a.reason||"voice-not-ready"===a.reason)?{mode:"native",alias:"string"==typeof a.alias?a.alias:null,reason:a.reason}:null:null}let eh={idle:!0,connecting:!0,live:!0,working:!0,error:!0,closed:!0},ei={unsupported:"chat.liveUnsupported","mic-denied":"chat.liveMicDenied","mic-unavailable":"chat.liveMicUnavailable",auth:"chat.liveAuthRequired",upstream:"chat.liveUpstreamFailed",voice:"chat.liveVoiceFailed",failed:"chat.liveFailed"},ej=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,d.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),(0,d.jsx)("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),ek=(0,d.jsx)(d.Fragment,{children:(0,d.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"})});function el({sessionId:a,onEnsureSession:b,onTranscriptPersisted:c}){let{t:f}=(0,x.s)(),g=function(a,b,c){let{locale:d}=(0,x.s)(),[f,g]=(0,e.useState)("idle"),[h,i]=(0,e.useState)(null),[j,k]=(0,e.useState)(null),[l,m]=(0,e.useState)(null),[n,o]=(0,e.useState)(null),[p,q]=(0,e.useState)(null),[r,s]=(0,e.useState)(!1),t=(0,e.useRef)(null),u=(0,e.useRef)(null),v=(0,e.useRef)(null),w=(0,e.useRef)(null),y=(0,e.useRef)(null),z=(0,e.useRef)(null),A=(0,e.useRef)(null),B=(0,e.useRef)(0),C=(0,e.useCallback)(a=>{B.current+=1;let b=y.current;for(let a of(y.current=null,w.current?.close(),w.current=null,t.current?.close(),t.current=null,u.current?.getTracks()??[]))a.stop();u.current=null;let c=v.current;v.current=null,c&&(c.srcObject=null,c.remove()),z.current?.close(),z.current=null,A.current=null,b&&fetch(`/api/live/call/${encodeURIComponent(b)}`,{method:"DELETE"}).catch(()=>{}),g(a),m(null),o(null),s(!1)},[]),D=(0,e.useCallback)((a,b)=>{i(a),k(b??null),C("error")},[C]),E=(0,e.useCallback)(async()=>{let e,f=B.current+1;B.current=f,i(null),k(null),s(!0),g("connecting"),z.current?.close();let h=new ef;h.unlock(),z.current=h;let j=a;if(!j&&b){try{j=await b()}catch{j=void 0}if(B.current!==f)return}if(!j){B.current===f&&(s(!1),D("failed"));return}try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(b){let a=b instanceof DOMException?b.name:"";B.current===f&&(s(!1),D("NotAllowedError"===a||"SecurityError"===a?"mic-denied":"mic-unavailable"));return}if(B.current!==f){for(let a of e.getTracks())a.stop();return}u.current=e;try{let a,b,h=new RTCPeerConnection;for(let a of(t.current=h,e.getTracks()))h.addTrack(a,e);let i=document.createElement("audio");if(i.autoplay=!0,v.current=i,h.ontrack=a=>{let[b]=a.streams;b&&A.current?.mode!=="character"&&(i.srcObject=b)},await h.setLocalDescription(await h.createOffer()),await function(a){if("complete"===a.iceGatheringState)return Promise.resolve();let{promise:b,resolve:c}=Promise.withResolvers(),d=()=>{clearTimeout(f),a.removeEventListener("icegatheringstatechange",e),c()},e=()=>{"complete"===a.iceGatheringState&&d()},f=setTimeout(d,3e3);return a.addEventListener("icegatheringstatechange",e),b}(h),B.current!==f)return;let k=h.localDescription?.sdp;if(!k)throw Error("The browser produced no offer SDP.");let p=await fetch("/api/live/offer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:j,sdp:k,locale:d})}),q=await p.json().catch(()=>({})),r="",u="";if(q&&"object"==typeof q&&("error"in q&&(a=q.error),"message"in q&&"string"==typeof q.message&&(b=q.message),"callId"in q&&"string"==typeof q.callId&&(r=q.callId),"sdp"in q&&"string"==typeof q.sdp&&(u=q.sdp),"voice"in q&&B.current===f&&(A.current=eg(q.voice))),!p.ok||!r||!u){if(B.current===f){var l,n;s(!1),D((l=p.status,n=a,401===l||"live-auth"===n?"auth":502===l||"live-upstream"===n?"upstream":"failed"),b)}return}if(B.current!==f)return void fetch(`/api/live/call/${encodeURIComponent(r)}`,{method:"DELETE"}).catch(()=>{});if(await h.setRemoteDescription({type:"answer",sdp:u}),B.current!==f){h.close(),fetch(`/api/live/call/${encodeURIComponent(r)}`,{method:"DELETE"}).catch(()=>{});return}y.current=r,o(A.current);let x=new EventSource(`/api/live/events?callId=${encodeURIComponent(r)}`);w.current=x,x.onmessage=a=>{let b;if(B.current===f){try{b=JSON.parse(a.data)}catch{return}if(b&&"object"==typeof b&&"type"in b){if("state"===b.type&&"state"in b){var d;if("string"!=typeof b.state||(d=b.state,!0!==eh[d]))return;"closed"===b.state?C("closed"):g(b.state);return}if("transcript"===b.type&&"role"in b&&"text"in b){if(("user"===b.role||"assistant"===b.role)&&"string"==typeof b.text){let a;m({role:b.role,text:b.text}),"final"in b&&!0===b.final&&c&&Promise.resolve().then(()=>c(j)).catch(()=>{}),"final"in b&&!0===b.final&&"user"===b.role&&(a=b.text.normalize("NFC").replace(/[^\p{L}\p{N}]+/gu,"")).length>0&&ee.test(a)&&C("idle")}return}if("voice"===b.type&&"voice"in b){let a=eg(b.voice);a&&a.mode===A.current?.mode&&(A.current=a,o(a));return}if("speech"===b.type&&"epoch"in b&&"audio"in b){"number"==typeof b.epoch&&"string"==typeof b.audio&&z.current?.push(b.epoch,b.audio);return}if("speech-reset"===b.type&&"epoch"in b){"number"==typeof b.epoch&&z.current?.reset(b.epoch);return}if("speech-error"===b.type&&"message"in b&&"string"==typeof b.message)return void D("voice",b.message);"error"===b.type&&"message"in b&&"string"==typeof b.message&&D("upstream",b.message)}}},x.onerror=()=>{B.current===f&&y.current&&D("failed")},g("live")}catch(a){B.current===f&&D("failed",a instanceof Error?a.message:String(a))}finally{B.current===f&&s(!1)}},[a,b,c,d,D,C]),F=(0,e.useCallback)(()=>{if("idle"===f||"closed"===f||"error"===f){r||E();return}C("idle")},[r,f,E,C]);return{state:f,failure:h,detail:j,transcript:l,voice:n,supported:p,toggle:F}}(a,b,c),h="connecting"===g.state||"live"===g.state||"working"===g.state,i="connecting"===g.state?"chat.liveConnecting":"working"===g.state?"chat.liveWorking":"live"===g.state?"chat.liveOn":null,j=f(h?"chat.liveStop":"chat.liveStart"),k=!1===g.supported?ei.unsupported:g.failure?ei[g.failure]:null,l=!!(a||b),m=l?null:"chat.liveNeedsSession",n=h?function(a,b){if(!a)return null;if("character"===a.mode){let c=b("chat.liveVoiceCharacter",{name:a.alias});return"provisional"===a.tuning?`${c} \xb7 ${b("chat.liveVoiceProvisional")}`:c}return"voice-not-ready"===a.reason&&a.alias?b("chat.liveVoiceNativeNotReady",{name:a.alias}):"character-unknown"===a.reason?b("chat.liveVoiceNativeUnknown"):null}(g.voice,f):null;return(0,d.jsxs)("div",{role:"group","aria-label":f("chat.liveVoice"),style:{display:"flex",alignItems:"center",gap:6,flex:"0 1 auto",minWidth:0},children:[k&&(0,d.jsx)("span",{role:"status",style:{fontSize:11,color:"var(--danger)",maxWidth:220,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:g.detail??void 0,children:f(k)}),i&&(0,d.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:f(i)}),n&&(0,d.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",maxWidth:200,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:n,children:n}),(0,d.jsx)("button",{type:"button",className:`composer-icon-button${h?" is-active":""}`,onClick:g.toggle,disabled:!g.supported||!l,"aria-pressed":h,title:m?f(m):j,"aria-label":m?f(m):j,children:(0,d.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:h?ek:ej})})]})}let em={display:"inline-flex",alignItems:"center",flexShrink:0,height:32,padding:"0 10px",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",background:"var(--accent-soft)",color:"var(--accent-hover)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600,lineHeight:1.3,whiteSpace:"nowrap"};function en({sessionId:a}){let{t:b}=(0,x.s)(),[c,f]=(0,e.useState)(null);return c?(0,d.jsx)("span",{style:em,title:b("gpt6.boundBadgeHint",{handle:c}),children:b("gpt6.boundBadge",{handle:c})}):null}function eo(a){if(!a||"object"!=typeof a||"string"!=typeof a.data||"string"!=typeof a.mimeType||!a.mimeType.startsWith("image/"))return!1;let b=function(a){if(!a||a.length%4!=0)return null;let b=a.endsWith("==")?2:+!!a.endsWith("="),c=a.length-b;for(let b=0;b<c;b+=1){var d;if(!((d=a.charCodeAt(b))>=65&&d<=90||d>=97&&d<=122||d>=48&&d<=57||43===d||47===d))return null}for(let b=c;b<a.length;b+=1)if("="!==a[b])return null;return a.length/4*3-b}(a.data);return null!==b&&b<=0xa00000}let ep=new Map,eq="ompweb-drafts-for-reload-v1",er=!1,es=new Map,et=new Map,eu="\0stale",ev=new Map,ew=0,ex=new Map,ey=new Map,ez=new Map,eA=new Map,eB=new Map;function eC(){if(er||"u"<typeof sessionStorage)return;er=!0;let a=sessionStorage.getItem(eq);if(a){sessionStorage.removeItem(eq);try{let b=JSON.parse(a);if(!Array.isArray(b))return;for(let a of b){if(!Array.isArray(a)||2!==a.length||"string"!=typeof a[0])continue;let b=a[1];b&&"string"==typeof b.value&&Array.isArray(b.images)&&Array.isArray(b.documents)&&(ep.set(a[0],eD(b)),"string"==typeof b.draftId&&b.draftId&&(es.set(a[0],b.draftId),et.set(b.draftId,eu)),eM(a[0]))}}catch{}}}function eD(a){return{value:a.value,images:a.images.map(a=>({...a})),documents:a.documents.map(a=>({...a}))}}function eE(a){return!a.value&&0===a.images.length&&0===a.documents.length}function eF(a){eC();let b=ep.get(a);return b?eD(b):null}function eG(a,b){eC(),eE(b)?ep.delete(a):ep.set(a,eD(b)),eM(a)}function eH(a){ep.delete(a),eM(a)}function eI(a,b,c,d,e,f=[]){let g=[...b??[],...d].filter(eo).slice(0,10).map(({data:a,mimeType:b})=>({data:a,mimeType:b})),h=cy([...e??[],...f]);return{value:a.trim()?c.trim()?`${a}
|
|
17
17
|
|
|
18
|
-
${c}`:a:c,images:g,documents:h}}function eJ(a,b,c){if(a===b)return c?eD(c):eF(b);let d=eF(a),e=c&&!eE(c)?eD(c):d??(c?eD(c):null),f=eF(b),g=es.get(a);if(es.delete(a),g&&!es.has(b)&&es.set(b,g),eH(a),!e)return f;let h=f?eI(f.value,f.images,e.value,e.images,f.documents,e.documents):e;return eG(b,h),eD(h)}function eK(a){let b=[];for(let c of a??[])c.attachmentId&&!b.includes(c.attachmentId)&&b.push(c.attachmentId);return b}function eL(a){eC();let b=es.get(a);return b||(b=function(){let a=globalThis.crypto;if("function"==typeof a?.randomUUID)return a.randomUUID();let b=a.getRandomValues(new Uint8Array(16));b[6]=15&b[6]|64,b[8]=63&b[8]|128;let c=[...b].map(a=>a.toString(16).padStart(2,"0")).join("");return`${c.slice(0,8)}-${c.slice(8,12)}-${c.slice(12,16)}-${c.slice(16,20)}-${c.slice(20)}`}(),es.set(a,b)),b}function eM(a){let b=eK(ep.get(a)?.documents),c=b.length?eL(a):es.get(a);for(let[a,c]of ey){for(let a of b)c.delete(a);0===c.size&&ey.delete(a)}let d=`${c??""}|${b.join(",")}`;eA.get(a)!==d&&(0!==b.length||c?eA.set(a,d):eA.delete(a),eO())}async function eN(a){let b=eL(a);ex.set(b,(ex.get(b)??0)+1),await eB.get(b);let c=!1;return{draftId:b,end(a){if(c)return;c=!0;let d=(ex.get(b)??1)-1;if(d>0?ex.set(b,d):ex.delete(b),a){let c=ey.get(b)??new Set;c.add(a),ey.set(b,c)}et.set(b,eu),eO()}}}function eO(){}let eP=Math.floor(Number.MAX_SAFE_INTEGER/1048576),eQ=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function eR(a){return"number"==typeof a&&Number.isSafeInteger(a)&&a>=1&&a<=eP}async function eS(a){let b,c=await a.json().catch(()=>null);if(!a.ok||!c||!eR(c.uploadLimitMb)||"boolean"!=typeof c.autoCleanupEnabled)throw Error("string"==typeof c?.error?c.error:`HTTP ${a.status}`);return{uploadLimitMb:eR((b=c&&"object"==typeof c?c:{}).uploadLimitMb)?b.uploadLimitMb:eQ.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof b.autoCleanupEnabled?b.autoCleanupEnabled:eQ.autoCleanupEnabled,orphanGraceDays:7}}async function eT(a={}){return eS(await fetch("/api/attachment-settings",{cache:"no-store",signal:a.signal}))}async function eU(a){return eS(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}))}function eV(a){let b=/(?:^|\s)@"([^"\n]*)$/.exec(a);if(b)return{start:a.length-(b[1].length+2),query:b[1],quoted:!0};let c=/(?:^|\s)@([^\s"]*)$/.exec(a);return c?{start:a.length-(c[1].length+1),query:c[1],quoted:!1}:null}function eW(a){let b=0;for(let c=0;c<a.length;c++)"/"===a[c]&&b++;return b}function eX(a,b){if(!a)return!0;let c=0;for(let d=0;d<b.length&&c<a.length;d++)b[d]===a[c]&&c++;return c===a.length}let eY="omp-web:model-picks";function eZ(){try{let a=JSON.parse(window.localStorage.getItem(eY)??"{}");if(!a||"object"!=typeof a||Array.isArray(a))return{};let b={};for(let[c,d]of Object.entries(a))"number"==typeof d&&Number.isFinite(d)&&d>0&&(b[c]=Math.floor(d));return b}catch{return{}}}function e$(a,b,c,d,e={}){let f=e.gap??8,g=e.margin??8,h=e.prefer??"above",i=Math.min(e.minHeight??120,Math.max(0,c-2*g)),j=Math.max(0,a-f-g),k=Math.max(0,c-b-f-g),l="above"===h?j:k,m="above"===h?k:j,n=l>=d||l>=m;return{side:n?h:"above"===h?"below":"above",maxHeight:Math.max(i,Math.min(d,n?l:m))}}function e_(a,b,c){return Math.min(a*b,c)}function e0(a,b,c){let{viewportFraction:d,cap:f,gap:g,margin:h,minHeight:i,prefer:j}=c,[k,l]=(0,e.useState)({side:j??"above",maxHeight:f});return(0,e.useCallback)(()=>{let b=a.current;if(!b)return;let c=window.visualViewport?.height??window.innerHeight,e=b.getBoundingClientRect(),k=e$(e.top,e.bottom,c,e_(c,d,f),{gap:g,margin:h,minHeight:i,prefer:j});l(a=>a.side===k.side&&a.maxHeight===k.maxHeight?a:k)},[a,f,g,h,i,j,d]),k}var e1=c(29947);async function e2(a,b,c,d,e,f,g){let h=a.slice(1).split(/\s/,1)[0];try{let i=b?.length?b:await g?.()??[],j=[...fg,...i].find(a=>a.name===h||"aliases"in a&&a.aliases?.includes(h));if(f&&(!j||"builtin"===j.source))return e(`/${h} cannot run with attachments. Remove them and retry.`),!1;let k=await c?.(a);if(k?.handled){if(k.error)return!1;return k.prompt&&d(k.prompt),!0}if(j&&"builtin"!==j.source)return d(a),!0;return e(`/${h} is not available in this web session.`),!1}catch(a){return e(a instanceof Error?a.message:String(a)),!1}}function e3(a){let b=a.transcription?.state;return"planning"===b||"confirm"===b||"running"===b}let e4=["off","default","full"],e5={off:"none",default:"default",full:"full"},e6=e1.IN.join(" \xb7 "),e7=e1.C1.filter(a=>!e1.IN.includes(a)).join(" \xb7 ");function e8(a){return"above"===a?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let e9=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),fa=0,fb={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function fc(a,b){return e9.compare(a.name||a.modelId,b.name||b.modelId)||e9.compare(a.provider,b.provider)||e9.compare(a.modelId,b.modelId)}let fd=["auto","off","minimal","low","medium","high","xhigh","max"],fe=["low","medium","high","xhigh"],ff={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},fg=[{name:"compact",descriptionKey:"chat.commandCompact",source:"builtin"},{name:"reload",descriptionKey:"chat.commandReload",source:"builtin"},{name:"name",descriptionKey:"chat.commandName",source:"builtin"},{name:"session",descriptionKey:"chat.commandSession",source:"builtin"},{name:"copy",descriptionKey:"chat.commandCopy",source:"builtin"}],fh=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],fi={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},fj={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function fk(a,b,c){let d=a.name.toLowerCase(),e=fl(a,c).toLowerCase();return d===b?0:d.startsWith(b)?1:d.includes(b)?2:e.includes(b)?3:4}function fl(a,b){return"descriptionKey"in a?b(a.descriptionKey):a.description??""}function fm(a,b){return"skill"===a.source&&!!a.name.startsWith("skill:")&&!0===b[a.name.slice(6)]}function fn(a){return{data:a.data,mimeType:a.mimeType}}function fo(a){return{...a,previewUrl:`data:${a.mimeType};base64,${a.data}`}}function fp(a){return(a??[]).filter(eo).slice(0,10).map(fo)}let fq=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,fr="\n\nTranscript of the audio ";function fs(a){return cy(a).map(a=>{let b=cF(a),c="audio"===b&&a.attachmentId&&!a.text.includes(fr)?fq.exec(a.text):null;return{...a,id:++fa,status:"ready",..."audio"===b||"file"===b?{stored:b}:{},...c?{storedInfo:{path:c[1],mimeType:c[2],size:Number(c[3])}}:{}}})}function ft({name:a,mimeType:b,size:c,text:d,attachmentId:e}){return e?{name:a,mimeType:b,size:c,text:d,attachmentId:e}:{name:a,mimeType:b,size:c,text:d}}function fu(a,b){let c=new Map(b.flatMap(a=>a.attachmentId?[[a.attachmentId,a]]:[]));return[...a.map(a=>{let b=a.attachmentId?c.get(a.attachmentId):void 0;return b?(c.delete(a.attachmentId),{...a,id:b.id,sourceSize:b.sourceSize,storedInfo:b.storedInfo??a.storedInfo,transcription:b.transcription}):a}),...b.filter(a=>"ready"!==a.status)]}class fv extends Error{constructor(a,b,c,d){super(a),this.code=b,this.completedParts=c,this.parts=d}}let fw="composer:unkeyed";async function fx(a){let b=await a.json().catch(()=>null),c=b&&"object"==typeof b?{...b}:{};if(a.ok)return c;throw new fv("string"==typeof c.error?c.error:`HTTP ${a.status}`,"string"==typeof c.code?c.code:null,"number"==typeof c.completedParts?c.completedParts:null,"number"==typeof c.parts?c.parts:null)}function fy(a){a.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(a.previewUrl)}function fz({tone:a,title:b,body:c}){let e="error"===a?"danger":"warning";return(0,d.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid var(--${e}-line)`,borderRadius:"var(--radius-control)",background:`var(--${e}-soft)`,color:`var(--${e})`,fontSize:11,lineHeight:1.45},children:[(0,d.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,d.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,d.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,d.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsx)("div",{style:{fontWeight:600},children:b}),(0,d.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:c})]})]})}function fA({error:a}){return a?(0,d.jsx)(fz,{tone:"error",title:"Model error",body:a}):null}function fB({warnings:a}){return a&&0!==a.length?(0,d.jsx)(fz,{tone:"warning",title:a.length>1?"Model scope warnings":"Model scope warning",body:a.join("\n")}):null}let fC=(0,e.forwardRef)(function({onSend:a,onAbort:b,onSteer:c,onFollowUp:g,isStreaming:i,model:j,isAutoModelSelection:k,modelNames:l,modelList:m,modelError:n,modelScopeWarnings:o,onModelChange:p,onMainPresetChange:q,mainPresetActiveAlias:r,modelRoles:s,onRoleModelChange:t,modelSwitching:u,onCompact:v,onAbortCompaction:w,isCompacting:y,compactError:z,compactResult:A,toolPreset:B,onToolPresetChange:C,thinkingLevel:E,effectiveThinkingLevel:F,thinkingCeiling:G,onThinkingLevelChange:H,availableThinkingLevels:I,thinkingLevelMap:J,fastMode:K=null,fastModeBusy:L=!1,onFastModeToggle:M,retryInfo:N,deliveryRows:O=[],inputHistory:P=[],onRecallQueue:Q,onRemoveQueuedMessage:R,slashCommands:S,slashCommandsLoading:T,onLoadSlashCommands:U,onBuiltinCommand:V,soundEnabled:W,onSoundToggle:X,onAudioUnlock:Y,onPromptWithStreamingBehavior:Z,draftKey:$,cwd:_,sessionId:aa,onEnsureSession:ab,onLiveTranscriptPersisted:ac},ad){let ae,af,ag,ah,ai,aj,ak,al,am,an,{t:ao}=(0,x.s)(),{st:ap}=bT(),aq=O.some(a=>a.removable),ar=D(),[as,at]=(0,e.useState)(()=>$?eF($)?.value??"":""),[au,av]=(0,e.useState)(!1),[aw,ax]=(0,e.useState)(null),[ay,az]=(0,e.useState)(""),[aA,aB]=(0,e.useState)({});(0,e.useEffect)(()=>{au&&aB(eZ())},[au]);let[aC,aD]=(0,e.useState)(!1),[aE,aF]=(0,e.useState)(null),[aG,aH]=(0,e.useState)(!1),[aI,aJ]=(0,e.useState)(!1),[aK,aL]=(0,e.useState)(null),[aM,aN]=(0,e.useState)(!1),[aO,aP]=(0,e.useState)(()=>$?fp(eF($)?.images):[]),[aQ,aR]=(0,e.useState)(()=>$?fs(eF($)?.documents):[]),[aS,aT]=(0,e.useState)(null),aU=(0,e.useMemo)(()=>aQ.filter(a=>"ready"===a.status),[aQ]),aV=aQ.some(a=>"ready"!==a.status||e3(a)),aW=aQ.filter(a=>"audio"===a.stored&&a.attachmentId&&a.storedInfo&&(void 0!==a.transcription||!a.text.includes(fr))),aX=as.trimStart(),aY=0===aO.length&&0===aQ.length&&aX.startsWith("!"),aZ=aY&&aX.startsWith("!!"),[a$,a_]=(0,e.useState)(!1),[a0,a1]=(0,e.useState)(0),[a2,a3]=(0,e.useState)(null),[a4,a5]=(0,e.useState)(!1),[a6,a7]=(0,e.useState)(0),[a8,a9]=(0,e.useState)(!1),[ba,bb]=(0,e.useState)(0),[bc,bd]=(0,e.useState)(null),[be,bf]=(0,e.useState)(!1),[bg,bh]=(0,e.useState)(null),[bi,bj]=(0,e.useState)(null),bk=_&&bi?.cwd===_?bi.values:{},bl=(0,e.useRef)(null),bm=(0,e.useRef)(null),bn=(0,e.useRef)(null),bo=(0,e.useRef)(null),bp=(0,e.useRef)(null),bq=(0,e.useRef)(null),br=(0,e.useRef)(null),bs=(0,e.useRef)(null),bt=(0,e.useRef)(null),bu=(0,e.useRef)(null),bv=(0,e.useRef)(null),bw=(0,e.useRef)(!1),bx=(0,e.useRef)(0),by=(0,e.useRef)(!1),bA=(0,e.useRef)([]),bB=(0,e.useRef)([]),bC=(0,e.useRef)([]),bD=(0,e.useRef)(null),bE=(0,e.useRef)(null),bF=(0,e.useRef)($),bG=(0,e.useRef)(as),bH=(0,e.useRef)(aO),bI=(0,e.useRef)(0),bK=(0,e.useRef)(aQ);bG.current=as,bH.current=aO,bK.current=aQ,(0,e.useImperativeHandle)(ad,()=>({insertIfEmpty(a){let b=bl.current;(b?b.value:as).trim()||(bG.current=a,at(a),a3(null),requestAnimationFrame(()=>{b&&(b.focus(),b.style.height="auto",b.style.height=`${Math.min(b.scrollHeight,200)}px`)}))},replaceMessage(a){let b,c,d=bl.current;if(!function(a,b,c,d=0){return!a.trim()&&0===b&&0===c&&0===d}(d?d.value:as,bH.current.length,bI.current,bK.current.length))return;let e=(b="string"==typeof a.content?a.content:a.content.filter(a=>"text"===a.type).map(a=>a.text).join("\n"),cB(b)?.message??b),f=fp("string"==typeof a.content?[]:a.content.flatMap(a=>{if("image"!==a.type)return[];let b=a.source?.type==="base64"?a.source.data:a.data,c=a.source?.type==="base64"?a.source.media_type:a.mimeType;if("string"!=typeof b||"string"!=typeof c)return[];let d={data:b,mimeType:c};return eo(d)?[d]:[]})),g=fs((c="string"==typeof a.content?a.content:a.content.filter(a=>"text"===a.type).map(a=>a.text).join("\n"),cB(c)?.documents??[]));bG.current=e,bH.current=f,bK.current=g,at(e),a3(null),a9(!1),aP(a=>(a.forEach(fy),f)),aR(g),requestAnimationFrame(()=>{d&&(d.focus(),d.style.height="auto",d.style.height=`${Math.min(d.scrollHeight,200)}px`)})},rekeyDraft(a,b){if(a===b)return;if(bF.current!==a)return void eJ(a,b);let c={value:bG.current,images:bH.current.map(fn),documents:bK.current.filter(a=>"ready"===a.status).map(ft)},d=eJ(a,b,c)??{value:"",images:[],documents:[]},e=d.value===c.value&&d.images.length===c.images.length&&d.images.every((a,b)=>a.data===c.images[b]?.data&&a.mimeType===c.images[b]?.mimeType)&&d.documents.length===c.documents.length&&d.documents.every((a,b)=>a.name===c.documents[b]?.name&&a.mimeType===c.documents[b]?.mimeType&&a.size===c.documents[b]?.size&&a.text===c.documents[b]?.text&&a.attachmentId===c.documents[b]?.attachmentId);if(bF.current=b,e)return;let f=fp(d.images),g=fu(fs(d.documents),bK.current),h=d.value;bG.current=h,bH.current=f,bK.current=g,at(h),aP(a=>(a.forEach(fy),f)),aR(g),a3(null),a9(!1)},restoreSubmission(a,b,c,d){if(!a.trim()&&!b?.length&&!c?.length)return;let e=bF.current,f=d??e,g=f===e,h=!g&&f?eF(f):null,i=eI(a,b,g?bG.current:h?.value??"",g?bH.current.map(fn):h?.images??[],c,g?bK.current.filter(a=>"ready"===a.status).map(ft):h?.documents??[]);if(f&&eG(f,i),!g)return;let j=b?.length?[...fp(b).slice(0,Math.max(0,10-bH.current.length)),...bH.current].slice(0,10):bH.current,k=fu(fs(i.documents),bK.current);bG.current=i.value,bH.current=j,bK.current=k,at(i.value),a3(null),a9(!1),b?.length&&aP(a=>{let c=Math.max(0,10-a.length),d=fp(b).slice(0,c),e=d.length>0?[...d,...a]:a;return bH.current=e,e}),aR(k),requestAnimationFrame(()=>{let a=bl.current;a&&(a.focus(),a.setSelectionRange(a.value.length,a.value.length),a.style.height="auto",a.style.height=`${Math.min(a.scrollHeight,200)}px`)})},insertText(a){let b=bl.current;if(!b)return void at(b=>b+(b?" ":"")+a);let c=b.selectionStart??b.value.length,d=b.selectionEnd??b.value.length,e=b.value.slice(0,c),f=b.value.slice(d),g=e.length>0&&!e.endsWith(" ")?" ":"",h=e+g+a+f;bG.current=h,at(h),a3(null),requestAnimationFrame(()=>{if(!b)return;let d=c+g.length+a.length;b.setSelectionRange(d,d),b.focus(),b.style.height="auto",b.style.height=`${Math.min(b.scrollHeight,200)}px`})},addAttachments(a){b0(a)}}));let bL=(0,e.useCallback)(async a=>{let b=Math.max(0,10-bH.current.length-bI.current),c=a.filter(a=>a.size>0xa00000);c.length>0&&aT(ao("chat.attachImageTooLarge",{name:c.map(a=>a.name).join(", "),limit:cC(0xa00000)}));let d=a.filter(a=>a.size<=0xa00000),e=d.slice(0,b);if(e.length<d.length&&aT(ao("chat.attachImageLimit",{count:10})),e.length){bI.current+=e.length;try{let a=await Promise.all(e.map(a=>new Promise((b,c)=>{let d=new FileReader;d.onload=()=>{let c=d.result.split(",")[1];b({data:c,mimeType:a.type,previewUrl:URL.createObjectURL(a)})},d.onerror=c,d.readAsDataURL(a)})));aP(b=>{let c=a.slice(0,Math.max(0,10-b.length));a.slice(c.length).forEach(fy);let d=[...b,...c];return bH.current=d,d})}finally{bI.current-=e.length}}},[ao]),bM=(0,e.useCallback)(async a=>{for(let b of a){let a=cu(b);if(!a)continue;if(bK.current.length>=3){aT(ao("chat.attachLimit",{count:3}));continue}if(b.size>8388608){aT(ao("chat.attachTooLarge",{name:b.name,limit:cC(8388608)}));continue}if(bK.current.reduce((a,b)=>a+b.size,0)+b.size>0x1000000){aT(ao("chat.attachTotalTooLarge",{limit:cC(0x1000000)}));continue}let c={id:++fa,name:b.name,mimeType:cr[a],size:b.size,text:"",status:"extracting"},d=[...bK.current,c];bK.current=d,aR(d);try{let a=await cz(b);if(bK.current.reduce((a,b)=>a+(b.id===c.id?0:b.text.length),0)+a.text.length>24e4)throw new cq("text_too_large","Total extracted text exceeds 240000 characters");let d=bK.current.map(b=>b.id===c.id?{...a,id:b.id,status:"ready"}:b);bK.current=d,aR(d)}catch(e){let a=bK.current.some(a=>a.id===c.id),d=bK.current.filter(a=>a.id!==c.id);if(bK.current=d,aR(d),!a)continue;e instanceof cq?"text_too_large"===e.code?aT(ao("chat.attachTextTooLarge",{name:b.name,limit:12e4.toLocaleString()})):"too_many_pages"===e.code?aT(ao("chat.attachTooManyPages",{name:b.name,limit:250})):"no_extractable_text"===e.code?aT(ao("chat.attachNoPdfText",{name:b.name})):"password_protected"===e.code?aT(ao("chat.attachPasswordProtected",{name:b.name})):aT(ao("chat.attachExtractFailed",{name:b.name})):aT(ao("chat.attachExtractFailed",{name:b.name}))}}},[ao]),bN=(0,e.useCallback)((a,b)=>{if(!bK.current.some(b=>b.id===a))return!1;let c=b?bK.current.map(c=>c.id===a?b:c):bK.current.filter(b=>b.id!==a);return bK.current=c,aR(c),!0},[]),bO=(0,e.useCallback)((a,b)=>{if(!bK.current.some(b=>b.attachmentId===a))return!1;let c=bK.current.map(c=>c.attachmentId===a?b(c):c);return bK.current=c,aR(c),!0},[]),bP=(0,e.useCallback)((a,b,c)=>{if(!a||a===bF.current)return;let d=eF(a);d?.documents.some(a=>a.attachmentId===b)&&eG(a,{...d,documents:fs(d.documents).map(a=>a.attachmentId===b?c(a):a).map(ft)})},[]),bQ=(0,e.useRef)(new Map),bR=(0,e.useRef)(new Map),bS=(0,e.useRef)(new Set),bU=(0,e.useCallback)((a,b,c)=>{if(!a.storedInfo)return null;let d=Math.min(12e4,24e4-c.reduce((b,c)=>b+(c.attachmentId===a.attachmentId?0:c.text.length),0)),e=cG({...a.storedInfo,transcript:b},d);return e.length>d?null:{...a,text:e,size:new TextEncoder().encode(e).byteLength,transcription:void 0}},[]),bV=(0,e.useCallback)(a=>a instanceof fv&&"media_tool_unavailable"===a.code?ao("chat.transcribeToolMissing"):a instanceof fv&&"transcription_failed"===a.code&&null!==a.completedParts&&null!==a.parts?ao("chat.transcribePartialFailed",{done:a.completedParts,total:a.parts}):a instanceof Error?a.message:String(a),[ao]),bW=(0,e.useCallback)(async(a,b)=>{let c=bF.current,d=bK.current.find(b=>b.attachmentId===a);if(!d?.storedInfo)return;let e=d.transcription?.state==="confirm"?d.transcription.plan:null;bR.current.get(a)?.abort();let f=new AbortController;bR.current.set(a,f),bO(a,a=>({...a,transcription:{state:"running",plan:e}}));try{let d=await fx(await fetch(`/api/attachments/${encodeURIComponent(a)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b?{confirmed:!0}:{}),signal:f.signal}));if("string"!=typeof d.transcript)throw new fv("Invalid transcription result",null,null,null);let e=d.transcript;bO(a,a=>bU(a,e,bK.current)??{...a,transcription:{state:"failed",error:ao("chat.transcribeTooLong")}})||bP(c,a,a=>bU(a,e,[])??a)}catch(c){if(f.signal.aborted)return void bO(a,a=>({...a,transcription:{state:"skipped"}}));if(c instanceof fv&&"confirmation_required"===c.code)return void bX.current?.(a);let b=bV(c);bO(a,a=>({...a,transcription:{state:"failed",error:b}}))}finally{bR.current.get(a)===f&&bR.current.delete(a)}},[ao,bV,bO,bP,bU]),bX=(0,e.useRef)(null),bY=(0,e.useCallback)(async a=>{let b;bR.current.get(a)?.abort();let c=new AbortController;bR.current.set(a,c),bO(a,a=>({...a,transcription:{state:"planning"}}));try{b=function(a){if("boolean"!=typeof a.requiresConfirmation||"number"!=typeof a.estimatedCalls||"string"!=typeof a.notice||null!==a.durationSeconds&&"number"!=typeof a.durationSeconds||"direct"!==a.processing&&"compress-and-split"!==a.processing)throw new fv("Invalid transcription plan",null,null,null);return{durationSeconds:a.durationSeconds,estimatedCalls:a.estimatedCalls,requiresConfirmation:a.requiresConfirmation,processing:a.processing,notice:a.notice}}(await fx(await fetch(`/api/attachments/${encodeURIComponent(a)}/transcription`,{cache:"no-store",signal:c.signal})))}catch(b){if(c.signal.aborted)bO(a,a=>({...a,transcription:{state:"skipped"}}));else{let c=bV(b);bO(a,a=>({...a,transcription:{state:"failed",error:c}}))}return}finally{bR.current.get(a)===c&&bR.current.delete(a)}b.requiresConfirmation?bO(a,a=>({...a,transcription:{state:"confirm",plan:b}})):await bW(a,!1)},[bW,bV,bO]);bX.current=bY;let bZ=(0,e.useCallback)(a=>{let b=bR.current.get(a);b?b.abort():bO(a,a=>({...a,transcription:{state:"skipped"}}))},[bO]),b$=(0,e.useCallback)(async(a,b)=>{let c=null;for(let d of a){if(bK.current.length>=3){aT(ao("chat.attachLimit",{count:3}));continue}let a="file"===b&&d.size<=8388608,e={id:++fa,name:d.name,mimeType:"text/plain",size:a?d.size:0,text:"",status:a?"extracting":"uploading",sourceSize:d.size},f=[...bK.current,e];bK.current=f,aR(f);let g=(a,b)=>{let c=bK.current.filter(a=>a.id!==e.id);return a<=12e4&&c.reduce((a,b)=>a+b.text.length,0)+a<=24e4&&c.reduce((a,b)=>a+b.size,0)+b<=0x1000000};if(a){let a=await d.arrayBuffer().then(a=>{var b;return 255===(b=new Uint8Array(a))[0]&&254===b[1]?cx("utf-16le",b.subarray(2)):254===b[0]&&255===b[1]?cx("utf-16be",b.subarray(2)):b.includes(0)?null:cx("utf-8",b)??cx("euc-kr",b)},()=>null);if(null!==a&&g(a.length,d.size)){bN(e.id,{...e,text:a,status:"ready"});continue}}if(null===c&&(c=1048576*(await eT().catch(()=>eQ)).uploadLimitMb),d.size>c){bN(e.id,null)&&aT(ao("chat.attachStoredTooLarge",{name:d.name,limit:cC(c)}));continue}let h={...e,stored:b,status:"uploading",size:0};if(!bN(e.id,h))continue;let i=bF.current??fw,j=await eN(i),k=null,l=new AbortController;bQ.current.set(e.id,l);try{if(bS.current.has(e.id))continue;let a=await cH(d,{sessionId:aa,draftId:j.draftId,signal:l.signal}),c=bK.current.filter(a=>a.id!==e.id).reduce((a,b)=>a+b.text.length,0),f=cG({path:a.path,size:a.size,mimeType:a.mimeType},Math.min(12e4,24e4-c)),m=new TextEncoder().encode(f).byteLength;if(!g(f.length,m)){bN(e.id,null)&&aT(ao("chat.attachTotalTooLarge",{limit:cC(0x1000000)}));continue}let n={...h,attachmentId:a.id,text:f,size:m,status:"ready",storedInfo:{path:a.path,size:a.size,mimeType:a.mimeType},..."audio"===b?{transcription:{state:"planning"}}:{}};if(bN(e.id,n))k=a.id;else if(!bS.current.has(e.id)&&i!==bF.current){let b=eF(i)??{value:"",images:[],documents:[]};eG(i,{...b,documents:[...b.documents,ft(n)]}),k=a.id}}catch(a){if(l.signal.aborted)continue;bN(e.id,null)&&aT(ao("chat.attachUploadFailed",{name:d.name,error:a instanceof Error?a.message:String(a)}))}finally{bQ.current.delete(e.id),j.end(k)}k&&"audio"===b&&bK.current.some(a=>a.attachmentId===k)&&bY(k)}},[bN,bY,aa,ao]),b0=(0,e.useCallback)(async a=>{aT(null);let{images:b,documents:c,audio:d,files:e}=function(a){let b=[],c=[],d=[],e=[];for(let f of a)f.type.startsWith("image/")?b.push(f):null!==cu(f)?c.push(f):cw(f)?d.push(f):e.push(f);return{images:b,documents:c,audio:d,files:e}}(a),f=c.filter(a=>a.size>8388608);await Promise.all([bL(b),bM(c.filter(a=>a.size<=8388608)),b$(d,"audio"),b$([...e,...f],"file")])},[bM,b$,bL]),b1=(0,e.useCallback)(a=>{aP(b=>{let c=[...b],[d]=c.splice(a,1);return d&&fy(d),bH.current=c,c})},[]),b3=(0,e.useCallback)(a=>{let b=bK.current.find(b=>b.id===a);if(bS.current.add(a),bQ.current.get(a)?.abort(),b?.attachmentId){bR.current.get(b.attachmentId)?.abort();var c=b.attachmentId;for(let[a,b]of ey)b.delete(c)&&(0===b.size&&ey.delete(a),eO())}let d=bK.current.filter(b=>b.id!==a);bK.current=d,aR(d)},[]),b4=(0,e.useCallback)(()=>{bH.current=[],aP(a=>(a.forEach(fy),[]))},[]),b5=(0,e.useCallback)(()=>{bK.current=[],aR([])},[]),b6=(0,e.useCallback)(()=>{bG.current="",at(""),a3(null),a9(!1),$&&eH($),bF.current&&bF.current!==$&&eH(bF.current),b4(),b5(),aT(null),bl.current&&(bl.current.style.height="auto")},[b5,b4,$]);(0,e.useEffect)(()=>{$&&bF.current===$&&eG($,{value:as,images:aO.map(fn),documents:aU.map(ft)})},[aO,$,aU,as]),(0,e.useEffect)(()=>{let a=bF.current;if(a===$)return;a&&eG(a,{value:bG.current,images:bH.current.map(fn),documents:bK.current.filter(a=>"ready"===a.status).map(ft)});let b=$?eF($):null;bF.current=$;let c=b?.value??"",d=fp(b?.images),e=fs(b?.documents);bG.current=c,bH.current=d,bK.current=e,at(c),a3(null),a9(!1),aP(a=>(a.forEach(fy),d)),aR(e)},[$]),(0,e.useEffect)(()=>{let a=bl.current;a&&(a.style.height="auto",as&&(a.style.height=`${Math.min(a.scrollHeight,200)}px`))},[as]),(0,e.useEffect)(()=>()=>{bH.current.forEach(fy)},[]);let b7=(0,e.useCallback)((a,b)=>{let c=function(a,b){let c=eK(b);if(0===c.length)return()=>{};let d=++ew;return ev.set(d,{draftId:eL(a),ids:c}),a=>{if("accepted"!==a&&"returned"!==a)return;let b=ev.get(d);if(b){if(ev.delete(d),"accepted"===a){let a=ez.get(b.draftId)??new Set;for(let c of b.ids)a.add(c);ez.set(b.draftId,a)}eO()}}}(bF.current??fw,a);Promise.resolve(b()).then(a=>c("accepted"===a||"returned"===a?a:void 0),()=>void 0)},[]),b8=(0,e.useCallback)(async()=>{let b=as.trim(),c=aX.trim(),d=c.startsWith("/")||c.startsWith("!")?c:b;if(!d&&!aO.length&&!aU.length||i||aV)return;Y?.();let e=aO.length?aO:void 0,f=aU.length?aU:void 0;if(d.startsWith("/")){await e2(d,S,V,b=>b7(f,()=>a(b,e,f)),aT,!!(e||f),U)&&b6();return}b6(),b7(f,()=>a(d,e,f))},[as,aX,aO,aU,aV,i,V,S,U,a,b6,Y,b7]),b9=aX.startsWith("/")&&!/\s/.test(aX.slice(1))?aX.slice(1).toLowerCase():null,ca=(()=>{if(null===b9)return[];let a=[...i?[]:fg,...S??[]],b=new Set;return[...a].filter(a=>{let b=a.name.toLowerCase(),c=fl(a,ao).toLowerCase();return b.includes(b9)||c.includes(b9)}).sort((a,b)=>{let c=fk(a,b9,ao)-fk(b,b9,ao);return 0!==c?c:fj[a.source]-fj[b.source]||e9.compare(a.name,b.name)}).filter(a=>{let c=a.name.toLowerCase();return!b.has(c)&&(b.add(c),!0)})})(),{commands:cb,groups:cc}=(ae=0,{commands:(af=fh.map(a=>{let b=ca.filter(b=>b.source===a),c="skill"===a?[...b.filter(a=>!fm(a,bk)),...b.filter(a=>fm(a,bk))]:b;return{source:a,items:c.map(a=>({command:a,index:ae++}))}}).filter(a=>a.items.length>0)).flatMap(a=>a.items.map(({command:a})=>a)),groups:af}),cd=1===ca.length?ao(b9?"chat.match":"chat.command"):ao(b9?"chat.matches":"chat.commands",{count:ca.length}),ce=!!as.trim(),cf=!aV&&(ce||aO.length>0||aU.length>0),cg=(0,e.useCallback)((a,b)=>{if(!_)return void a3(null);let c=b??a.length;a3(eV(a.slice(0,c)))},[_]),ch=a2?.query??null,ci=f().useMemo(()=>null!==ch&&bc&&bc.cwd===_?function(a,b,c=20){let d=b.toLowerCase();if(!d)return a.slice(0,c);let e=[];for(let b of a){let a=function(a,b){let c=a.path.toLowerCase(),d=0;if(b.includes("/"))c===b?d=100:c.startsWith(b)?d=80:c.includes(b)?d=50:eX(b,c)&&(d=10);else{let a=c.lastIndexOf("/"),e=-1===a?c:c.slice(a+1);e===b?d=100:e.startsWith(b)?d=80:e.includes(b)?d=50:c.includes(b)?d=30:eX(b,c)&&(d=10)}return a.isDir&&d>0&&(d+=10),d}(b,d);a>0&&e.push({entry:b,score:a})}return e.sort((a,b)=>b.score-a.score||eW(a.entry.path)-eW(b.entry.path)||a.entry.path.localeCompare(b.entry.path)),e.slice(0,c).map(a=>a.entry)}(bc.entries,ch):[],[ch,bc,_]),cj=!!(ch&&bc?.truncated&&bc.cwd===_);(0,e.useEffect)(()=>{if(!cj||!_||!ch)return;let a=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(_)}&q=${encodeURIComponent(ch)}`).then(a=>{if(!a.ok)throw Error(`file search failed: ${a.status}`);return a.json()}).then(a=>bh({cwd:_,query:ch,matches:a.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(a)},[cj,ch,_]);let ck=cj&&null!==bg&&bg.cwd===_&&bg.query===ch,cl=ck?bg.matches:ci,cm=null===a2?null:`${a2.start}:${+!!a2.quoted}:${a2.query}`;(0,e.useEffect)(()=>{if(null===cm){a5(!1),a7(0);return}a5(!0),a7(0)},[cm]);let cn=null!==a2,co=e0(bu,a8,{viewportFraction:.44,cap:360}),cp=e0(bu,a$,{viewportFraction:.56,cap:460}),cs=e0(bu,a4,{viewportFraction:.48,cap:400});(0,e.useEffect)(()=>{if(!cn||!_)return;let a=bD.current;a&&a.cwd===_&&Date.now()-a.fetchedAt<1e4||bE.current===_||(bE.current=_,bf(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(_)}`).then(a=>{if(!a.ok)throw Error(`file index failed: ${a.status}`);return a.json()}).then(a=>{bd({cwd:_,entries:function(a){let b=new Set;for(let c of a){let a=c.indexOf("/");for(;-1!==a;)b.add(c.slice(0,a)),a=c.indexOf("/",a+1)}let c=[];for(let a of b)c.push({path:a,isDir:!0});for(let b of a)b&&c.push({path:b,isDir:!1});return c.sort((a,b)=>eW(a.path)-eW(b.path)||a.path.localeCompare(b.path)),c}(a.files??[]),truncated:!!a.truncated}),bD.current={cwd:_,fetchedAt:Date.now()}}).catch(()=>{bD.current=null}).finally(()=>{bE.current=null,bf(!1)}))},[cn,_]);let ct=(0,e.useCallback)(a=>{if(!a2)return;let b=bl.current,c=b?.selectionStart??as.length,d=as.slice(0,a2.start),e=as.slice(c);a2.quoted&&e.startsWith('"')&&(e=e.slice(1));let f=function(a,b,c=!1){let d=b?`${a}/`:a,e=c||d.includes(" ");if(b){let a=e?`@"${d}"`:`@${d}`;return{text:a,cursorOffset:e?a.length-1:a.length}}let f=e?`@"${d}" `:`@${d} `;return{text:f,cursorOffset:f.length}}(a.path,a.isDir,a2.quoted),g=d+f.text+e,h=d.length+f.cursorOffset;at(g),a3(eV(g.slice(0,h))),requestAnimationFrame(()=>{let a=bl.current;a&&(a.focus(),a.setSelectionRange(h,h),a.style.height="auto",a.style.height=`${Math.min(a.scrollHeight,200)}px`)})},[a2,as]);(0,e.useEffect)(()=>{a6>=cl.length&&a7(Math.max(0,cl.length-1))},[cl.length,a6]),(0,e.useEffect)(()=>{bB.current.length=cl.length},[cl.length]),(0,e.useEffect)(()=>{a4&&bB.current[a6]?.scrollIntoView({block:"nearest",inline:"nearest"})},[a6,a4]),(0,e.useEffect)(()=>{ba>=P.length&&bb(Math.max(0,P.length-1))},[P.length,ba]),(0,e.useEffect)(()=>{bC.current.length=P.length},[P.length]),(0,e.useEffect)(()=>{a8&&bC.current[ba]?.scrollIntoView({block:"nearest",inline:"nearest"})},[ba,a8]);let cv=(0,e.useCallback)(a=>{bG.current=a,at(a),a9(!1),bb(0),a3(null),requestAnimationFrame(()=>{let b=bl.current;b&&(b.focus(),b.setSelectionRange(a.length,a.length),b.style.height="auto",b.style.height=`${Math.min(b.scrollHeight,200)}px`)})},[]),cy=(0,e.useCallback)(a=>{let b=`/${a.name} `;bG.current=b,at(b),a_(!1),a1(0),requestAnimationFrame(()=>{let a=bl.current;a&&(a.focus(),a.setSelectionRange(b.length,b.length),a.style.height="auto",a.style.height=`${Math.min(a.scrollHeight,200)}px`)})},[]),cA=(0,e.useCallback)(async a=>{let b=as.trim(),d=aX.trim(),e=d.startsWith("/")||d.startsWith("!")?d:b,f=aV||!e&&0===aO.length&&0===aU.length?null:{message:e,images:aO.length?aO:void 0,documents:aU.length?aU:void 0};if(!f)return;Y?.();let h="steer"===a?"steer":"followUp";if(e.startsWith("/")){await e2(e,S,V,a=>{if(!Z)throw Error("Cannot queue this command while the session is busy.");b7(f.documents,()=>Z(a,h,f.images,f.documents))},aT,!!(f.images?.length||f.documents?.length),U)&&b6();return}b6(),"steer"===a&&c?b7(f.documents,()=>c(f.message,f.images,f.documents)):"followup"===a&&g&&b7(f.documents,()=>g(f.message,f.images,f.documents))},[as,aX,aO,aU,aV,S,U,V,Z,c,g,b6,Y,b7]),cD=(0,e.useCallback)(a=>{let b=cb.length-1;if(b<0)return 0;if("left"===a)return Math.max(0,a0-1);if("right"===a)return Math.min(b,a0+1);let c=bA.current[a0];if(!c)return"down"===a?Math.min(b,a0+1):Math.max(0,a0-1);let d=c.getBoundingClientRect(),e=d.left+d.width/2,f=d.top+d.height/2,g=-1,h=1/0;for(let c=0;c<=b;c+=1){if(c===a0)continue;let b=bA.current[c];if(!b)continue;let d=b.getBoundingClientRect(),i=d.top+d.height/2-f;if("down"===a?i<=4:i>=-4)continue;let j=1e3*Math.abs(i)+Math.abs(d.left+d.width/2-e);j<h&&(g=c,h=j)}return g>=0?g:"down"===a?Math.min(b,a0+1):Math.max(0,a0-1)},[cb.length,a0]),cE=(0,e.useCallback)(a=>{let d=a.nativeEvent,e=Date.now()-bx.current<100,f=bw.current||d.isComposing||229===d.keyCode;if("Enter"===a.key&&!a.shiftKey&&(f||e)){e&&a.preventDefault();return}if(a8&&!f){if("ArrowDown"===a.key){a.preventDefault(),bb(a=>Math.min(Math.max(0,P.length-1),a+1));return}if("ArrowUp"===a.key){a.preventDefault(),bb(a=>Math.max(0,a-1));return}if("Escape"===a.key){a.preventDefault(),a9(!1);return}if(("Tab"===a.key||"Enter"===a.key&&!a.shiftKey)&&P[ba]){a.preventDefault(),cv(P[ba]);return}}if(a$&&null!==b9){if("ArrowDown"===a.key){a.preventDefault(),a1(cD("down"));return}if("ArrowUp"===a.key){a.preventDefault(),a1(cD("up"));return}if("ArrowRight"===a.key){a.preventDefault(),a1(cD("right"));return}if("ArrowLeft"===a.key){a.preventDefault(),a1(cD("left"));return}if("Escape"===a.key){a.preventDefault(),a_(!1);return}if(("Tab"===a.key||"Enter"===a.key&&!a.shiftKey)&&cb[a0]){a.preventDefault(),cy(cb[a0]);return}}if(a4&&null!==a2&&!f){if("ArrowDown"===a.key){a.preventDefault(),a7(a=>Math.min(Math.max(0,cl.length-1),a+1));return}if("ArrowUp"===a.key){a.preventDefault(),a7(a=>Math.max(0,a-1));return}if("Escape"===a.key){a.preventDefault(),a5(!1);return}if(("Tab"===a.key||"Enter"===a.key&&!a.shiftKey)&&cl[a6]){a.preventDefault(),ct(cl[a6]);return}}if("ArrowUp"===a.key&&!f&&!i&&P.length>0&&0===as.trim().length){a.preventDefault(),a_(!1),a5(!1),bb(P.length-1),a9(!0);return}if("Escape"===a.key&&!f&&i&&b){a.preventDefault(),b();return}"Enter"!==a.key||a.shiftKey||(a.preventDefault(),i&&(c||g)?cA(c?"steer":"followup"):b8())},[i,c,g,b,a$,b9,cb,a0,cy,cA,b8,cD,a4,a2,cl,a6,ct,a8,P,ba,cv,as]),cF=(0,e.useCallback)(()=>{let a=bl.current;a&&(a.style.height="auto",a.style.height=`${Math.min(a.scrollHeight,200)}px`)},[]),cI=(0,e.useCallback)(a=>{let b=function(a){let b=Array.from(a.files??[]);if(b.length>0)return b;let c=[];for(let b of Array.from(a.items??[])){if("file"!==b.kind)continue;let a=b.getAsFile();a&&c.push(a)}return c}(a.clipboardData);b.length&&(a.preventDefault(),b0(b))},[b0]);(0,e.useEffect)(()=>{if(null===b9){a_(!1),a1(0),by.current=!1;return}a_(!0),a1(0),!by.current&&U&&(by.current=!0,Promise.resolve(U()).catch(()=>{by.current=!1}))},[b9,U]),(0,e.useEffect)(()=>{if(!a$||!_)return;let a=!1;return bj({cwd:_,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(_)}`).then(a=>{if(!a.ok)throw Error(`skills fetch failed: ${a.status}`);return a.json()}).then(b=>{if(a)return;let c={};for(let a of b.skills??[])c[a.name]=a.disableModelInvocation;bj({cwd:_,values:c})}).catch(()=>{a||bj({cwd:_,values:{}})}),()=>{a=!0}},[a$,_]),(0,e.useEffect)(()=>{a0>=cb.length&&a1(Math.max(0,cb.length-1))},[cb.length,a0]),(0,e.useEffect)(()=>{bA.current.length=cb.length},[cb.length]),(0,e.useEffect)(()=>{a$&&bA.current[a0]?.scrollIntoView({block:"nearest",inline:"nearest"})},[a0,a$]);let cJ=m&&m.length>0?m.map(a=>({provider:a.provider,modelId:a.id,name:a.name})).sort(fc):Object.entries(l??{}).map(([a,b])=>({provider:j?.provider??"unknown",modelId:a,name:b})).sort(fc),cK=r??null,cL=bJ.bo.find(a=>a.alias===cK)?.provider??null,cM=cL?cJ.filter(a=>a.provider===cL):cJ,cN=(ag=ay.trim().toLocaleLowerCase())?cM.filter(a=>`${a.name} ${a.modelId}`.toLocaleLowerCase().includes(ag)):cM,cO=cM.length>8,cP=[];for(let a of cN){let b=cP.find(b=>b.provider===a.provider);b?b.options.push(a):cP.push({provider:a.provider,options:[a]})}let cQ=cL?[]:(s??[]).filter(a=>!a.hidden&&a.resolved),cR=j?cQ.find(a=>a.resolved?.provider===j.provider&&a.resolved?.modelId===j.modelId):void 0,cS=ay.trim()?[]:cM.map((a,b)=>{var c,d;return{option:a,order:b,count:aA[c=a.provider,d=a.modelId,`${c}/${d}`]??0}}).filter(a=>a.count>=2).sort((a,b)=>b.count-a.count||a.order-b.order).slice(0,5).map(({option:a,count:b})=>({option:a,count:b})),cT=(a,b,c)=>{let e=a.modelId===j?.modelId&&a.provider===j?.provider;return(0,d.jsxs)("button",{onClick:()=>{if(av(!1),az(""),!e||k){var b,c;let d=function(a,b){let c={...a,[b]:(a[b]??0)+1},d=Object.keys(c);if(d.length<=30)return c;for(let a of(d.sort((a,b)=>c[a]-c[b]),d)){if(Object.keys(c).length<=30)break;a!==b&&delete c[a]}return c}(eZ(),(b=a.provider,c=a.modelId,`${b}/${c}`));try{window.localStorage.setItem(eY,JSON.stringify(d))}catch{}aB(d),p?.(a.provider,a.modelId)}},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:e?"var(--bg-selected)":"none",border:"none",color:e?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:e?600:400,whiteSpace:"nowrap"},onMouseEnter:a=>{e||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{e||(a.currentTarget.style.background="none")},children:[e?(0,d.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,d.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,d.jsx)("span",{style:{width:10,flexShrink:0}}),a.name,void 0!==c&&c>=2&&(0,d.jsx)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10.5},children:ao("chat.modelPickCount",{count:c})})]},`${b}:${a.provider}:${a.modelId}`)},cU=j?cJ.find(a=>a.modelId===j.modelId&&a.provider===j.provider)?.name??j.modelId:null,cV=A?Math.max(0,A.tokensBefore-A.estimatedTokensAfter):0,cW=A?`${A.reason&&"manual"!==A.reason?`${A.reason[0].toUpperCase()}${A.reason.slice(1)} `:ao("chat.compacted")} ${bz(A.tokensBefore)} -> ${bz(A.estimatedTokensAfter)} tokens (${ao("chat.tokensSaved",{saved:bz(cV)})})`:null,cX=a=>{let b=J?.[a];return null!=b&&b!==a?b:null},cY="auto"===(ah=E??"auto")?G?`auto ≤ ${cX(G)??G}`:"auto":J?J[ah]??ah:ah,cZ=(E??"auto")==="auto"&&F&&"auto"!==F?J?.[F]??F:null,c$=H&&cZ?ao("chat.currentReasoning",{level:cZ}):null,c_=a=>!I||I.includes(a),c0=[{level:"auto",ceiling:null},...fe.filter(c_).map(a=>({level:"auto",ceiling:a})),...fd.filter(a=>"auto"!==a&&c_(a)).map(a=>({level:a,ceiling:null}))],c1=Object.entries(e5).find(([,a])=>a===(B??"default"))?.[0]??"default";return(0,e.useEffect)(()=>{let a=a=>{bm.current&&!bm.current.contains(a.target)&&bn.current&&!bn.current.contains(a.target)&&(av(!1),az("")),bo.current&&!bo.current.contains(a.target)&&bp.current&&!bp.current.contains(a.target)&&aD(!1),bq.current&&!bq.current.contains(a.target)&&aH(!1),br.current&&!br.current.contains(a.target)&&aJ(!1),bs.current&&!bs.current.contains(a.target)&&aN(!1),!bt.current||bt.current.contains(a.target)||bl.current?.contains(a.target)||a9(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]),(0,e.useEffect)(()=>{ar||aN(!1)},[ar]),(0,d.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,d.jsx)("input",{ref:bv,type:"file",multiple:!0,style:{display:"none"},onChange:a=>{b0(Array.from(a.target.files??[])),a.target.value=""}}),(0,d.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:[(0,d.jsx)(fA,{error:n}),(0,d.jsx)(fB,{warnings:o}),O.length>0&&(0,d.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",padding:"5px 0"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,d.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:ap("delivery.title",{count:O.length})}),Q&&aq&&(0,d.jsxs)("button",{onClick:Q,title:ao("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:"var(--radius-control)",cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:a=>{a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:a=>{a.currentTarget.style.background="transparent",a.currentTarget.style.borderColor="var(--border)"},children:[(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,d.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),ao("chat.recall")]})]}),(0,d.jsx)(ea,{rows:O,removeLabel:ao("chat.queueRemove"),onRemove:R?(a,b)=>R("steer"===a?"steering":"followUp",b):void 0})]}),N&&(0,d.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--warning-soft)",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--warning)",display:"flex",alignItems:"center",gap:6},children:[(0,d.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,d.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,d.jsx)("path",{d:"M3 3v5h5"})]}),ao("chat.retrying",{attempt:N.attempt,max:N.maxAttempts}),N.errorMessage&&(0,d.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",N.errorMessage]})]}),cW&&(0,d.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--success-soft)",border:"1px solid var(--success-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--success)",display:"flex",alignItems:"center",gap:6},children:[(0,d.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,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}),cW]}),z&&(0,d.jsx)("div",{role:"alert",style:{marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:z}),aS&&(0,d.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontSize:12,lineHeight:1.5},children:[(0,d.jsx)("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"},children:aS}),(0,d.jsx)("button",{type:"button",onClick:()=>aT(null),"aria-label":ao("i18n.close"),title:ao("i18n.close"),style:{flexShrink:0,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"inherit",cursor:"pointer"},children:(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,d.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(aO.length>0||aQ.length>0)&&(0,d.jsxs)("div",{role:"list","aria-label":ao("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[aO.map((a,b)=>(0,d.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,d.jsx)("img",{src:a.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",display:"block"}}),(0,d.jsx)("button",{type:"button","aria-label":ao("chat.removeImage",{index:b+1}),onClick:()=>b1(b),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,d.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,d.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},`image-${b}`)),aQ.map(a=>(0,d.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==a.status||e3(a)||void 0,style:{display:"flex",alignItems:"center",gap:7,minWidth:0,maxWidth:320,height:32,padding:"0 7px 0 9px"},children:["ready"!==a.status||a.transcription?.state==="planning"||a.transcription?.state==="running"?(0,d.jsx)("span",{"aria-hidden":"true",style:{width:13,height:13,flexShrink:0,border:"1.5px solid var(--border-strong)",borderTopColor:"var(--accent)",borderRadius:"50%",animation:"spin 0.8s linear infinite"}}):b2(a.name,14),(0,d.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,d.jsx)("span",{title:a.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:a.name}),(0,d.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===a.stored?ao("chat.attachKindAudio"):"file"===a.stored?ao("chat.attachKindFile"):fb[a.mimeType]," \xb7 ",cC(a.sourceSize??a.size),"extracting"===a.status?` \xb7 ${ao("chat.attachExtracting")}`:"","uploading"===a.status?` \xb7 ${ao("chat.attachUploading")}`:"",a.transcription?.state==="planning"?` \xb7 ${ao("chat.transcribeChecking")}`:"",a.transcription?.state==="confirm"?` \xb7 ${ao("chat.attachTranscribePending")}`:"",a.transcription?.state==="running"?` \xb7 ${ao("chat.attachTranscribing")}`:"",a.transcription?.state==="failed"&&(0,d.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${ao("chat.attachTranscribeFailed")}`})]})]}),(0,d.jsx)("button",{type:"button",onClick:()=>b3(a.id),"aria-label":ao("chat.removeAttachment",{name:a.name}),title:ao("chat.removeAttachment",{name:a.name}),style:{width:24,height:24,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:(0,d.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,d.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},a.id))]}),aW.length>0&&(0,d.jsx)("div",{role:"group","aria-label":ao("chat.transcribeGroup"),"aria-live":"polite",style:{display:"flex",flexDirection:"column",gap:6,marginBottom:6},children:aW.map(a=>{let b,c,e,f,g=a.attachmentId,i=a.transcription,j=i?.state==="confirm"||i?.state==="running"?i.plan:null,k=j?ao("chat.transcribePlanSummary",{duration:null===j.durationSeconds?ao("chat.transcribeDurationUnknown"):(c=Math.floor((b=Math.round(j.durationSeconds))/3600),e=Math.floor(b%3600/60),f=String(b%60).padStart(2,"0"),c>0?`${c}:${String(e).padStart(2,"0")}:${f}`:`${e}:${f}`),calls:j.estimatedCalls}):null,l=i?.state==="confirm"?ao("chat.transcribeConfirmTitle",{name:a.name}):i?.state==="running"?ao("chat.transcribeRunning",{name:a.name}):i?.state==="planning"?`${a.name} \xb7 ${ao("chat.transcribeChecking")}`:i?.state==="failed"?ao("chat.transcribeFailedRow",{name:a.name,error:i.error}):ao("chat.transcribeSkipped",{name:a.name});return(0,d.jsxs)("div",{"data-transcription-state":i?.state??"idle",style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"7px 10px",border:`1px solid ${i?.state==="failed"?"var(--danger-line)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:i?.state==="failed"?"var(--danger-soft)":"var(--bg-panel)",fontSize:12,lineHeight:1.45},children:[(0,d.jsxs)("div",{style:{flex:"1 1 220px",minWidth:0},children:[(0,d.jsx)("div",{style:{color:i?.state==="failed"?"var(--danger)":"var(--text)",overflowWrap:"anywhere"},children:l}),k&&(0,d.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:k}),i?.state==="confirm"&&(0,d.jsxs)(d.Fragment,{children:[i.plan.notice&&(0,d.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:i.plan.notice}),(0,d.jsx)("div",{style:{color:"var(--text-dim)"},children:ao("chat.transcribeUsageNotice")})]})]}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[i?.state==="confirm"&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(h.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void bW(g,!0),children:ao("chat.transcribeStart")}),(0,d.jsx)(h.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>bZ(g),children:ao("chat.transcribeSkip")})]}),(i?.state==="planning"||i?.state==="running")&&(0,d.jsx)(h.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>bZ(g),children:ao("chat.transcribeCancel")}),(void 0===i||"skipped"===i.state||"failed"===i.state)&&(0,d.jsx)(h.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void bY(g),children:ao(i?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},a.id)})}),(0,d.jsxs)("div",{ref:bu,style:{position:"relative",minWidth:0},children:[a8&&P.length>0&&(0,d.jsxs)("div",{ref:bt,style:{position:"absolute",left:0,right:0,...e8(co.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:co.maxHeight},children:[(0,d.jsx)("div",{title:"Input history",style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,d.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,d.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,d.jsx)("path",{d:"M3 4v5h5"}),(0,d.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,d.jsx)("div",{style:{maxHeight:Math.max(0,co.maxHeight-31),overflowY:"auto",padding:4},children:P.map((a,b)=>{let c=b===ba;return(0,d.jsxs)("button",{ref:a=>{bC.current[b]=a},type:"button",onMouseDown:b=>{b.preventDefault(),cv(a)},onMouseEnter:()=>bb(b),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:"var(--radius-control)",background:c?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,d.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:b+1}),(0,d.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:a})]},`${b}:${a}`)})})]}),a$&&null!==b9&&(0,d.jsxs)("div",{style:{position:"absolute",left:0,right:0,...e8(cp.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:cp.maxHeight},children:[(0,d.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)"},children:[(0,d.jsx)("span",{children:T?ao("chat.loadingCommands"):ao("chat.slashCommands",{label:cd})}),(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ao("chat.tabEnter")})]}),(0,d.jsx)("div",{style:{maxHeight:Math.max(0,cp.maxHeight-34),overflowY:"auto",padding:10},children:T||0!==ca.length?cc.map(a=>(0,d.jsxs)("section",{style:{marginBottom:12},children:[(0,d.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,d.jsx)("span",{children:ao(fi[a.source])}),(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:a.items.length})]}),(0,d.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:a.items.map(({command:a,index:b})=>{let c=b===a0,e=fm(a,bk);return(0,d.jsxs)("button",{ref:a=>{bA.current[b]=a},type:"button",onMouseDown:b=>{b.preventDefault(),cy(a)},onMouseEnter:()=>a1(b),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${c?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:c?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:c?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,d.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:e?"var(--text-dim)":void 0},children:["/",a.name,e&&(0,d.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:ao("chat.dormant")})]}),fl(a,ao)&&(0,d.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:fl(a,ao)})]},`${a.source}:${a.name}`)})})]},a.source)):(0,d.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:ao("chat.noCommands")})})]}),a4&&null!==a2&&(ai=be&&(!bc||bc.cwd!==_),aj=1===cl.length?ao("chat.match"):ao("chat.matches",{count:cl.length}),ak=bc?.truncated&&!ck?a2.query?ao("chat.searchingAll"):ao("chat.indexTruncated"):"",(0,d.jsxs)("div",{style:{position:"absolute",left:0,right:0,...e8(cs.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:cs.maxHeight},children:[(0,d.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)"},children:[(0,d.jsx)("span",{children:ai?ao("chat.loadingFiles"):ao("chat.files",{label:aj,hint:ak})}),(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ao("chat.tabEnter")})]}),(0,d.jsx)("div",{style:{maxHeight:Math.max(0,cs.maxHeight-34),overflowY:"auto",padding:4},children:ai||0!==cl.length?cl.map((a,b)=>{let c=b===a6,e=a.path.split("/").pop()??a.path,f=a.path.slice(0,a.path.length-e.length);return(0,d.jsxs)("button",{ref:a=>{bB.current[b]=a},type:"button",onMouseDown:b=>{b.preventDefault(),ct(a)},onMouseEnter:()=>a7(b),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:"var(--radius-control)",background:c?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,d.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:a.isDir?(0,d.jsx)(b_,{size:14}):b2(e,14)}),(0,d.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[f&&(0,d.jsx)("span",{style:{color:"var(--text-dim)"},children:f}),e,a.isDir&&(0,d.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${a.isDir?"d":"f"}:${a.path}`)}):(0,d.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:cj&&!ck?ao("chat.searching"):ao("chat.noMatchingFiles")})})]})),(0,d.jsxs)("div",{className:`chat-composer-field${aY?" is-bash":""}${i?" is-streaming":""}`,style:{minWidth:0,display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:`1px solid ${aY?"var(--tool-bg)":i&&(c||g)?"var(--warning-line)":"var(--border)"}`,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",boxShadow:"var(--seed-shadow-s1)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,d.jsx)("textarea",{className:"chat-composer-textarea",ref:bl,value:as,onChange:a=>{bG.current=a.target.value,at(a.target.value),a9(!1),cg(a.target.value,a.target.selectionStart)},onSelect:a=>{let b=a.currentTarget;cg(b.value,b.selectionStart)},onKeyDown:cE,onCompositionStart:()=>{bw.current=!0},onCompositionEnd:a=>{bw.current=!1,bx.current=Date.now();let b=a.currentTarget;cg(b.value,b.selectionStart)},onInput:cF,onPaste:cI,placeholder:i&&(c||g)?ao("chat.steerPlaceholder"):i?ao("chat.agentPlaceholder"):ao("chat.messagePlaceholder"),rows:1,style:{flex:1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:14,lineHeight:1.6,fontFamily:"inherit",minHeight:24,maxHeight:200,overflow:"auto"}}),i?(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[c&&(0,d.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>cA("steer"),disabled:!cf,title:aV?ao("chat.attachExtractingWait"):ao("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:cf?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:cf?"var(--warning)":"var(--text-dim)",cursor:cf?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,d.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),ao("chat.steer")]}),g&&(0,d.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>cA("followup"),disabled:!cf,title:aV?ao("chat.attachExtractingWait"):ao("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:cf?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:cf?"var(--accent-hover)":"var(--text-dim)",cursor:cf?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,d.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,d.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),ao("chat.followUp")]})]}):(0,d.jsxs)("button",{className:"chat-composer-send",onClick:b8,disabled:!cf,"aria-busy":aV||void 0,title:aV?ao("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",gap:6,padding:"7px 14px",background:cf?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:cf?"var(--accent-hover)":"var(--text-dim)",cursor:cf?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 0.15s"},children:[(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,d.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),ao("chat.send")]})]})]}),aY&&(0,d.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:aZ?"var(--text-muted)":"var(--accent)",marginTop:4},children:[ao("chat.shell")," \xb7 ",aZ?ao("chat.outputLocal"):ao("chat.outputModel")]}),(0,d.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,d.jsxs)("div",{style:{flex:ar?"1 1 0%":"0 0 auto",minWidth:ar?"min-content":0,display:"flex",alignItems:"center",gap:2},children:[(0,d.jsx)("button",{type:"button",className:`composer-icon-button${aO.length||aQ.length?" is-active":""}`,onClick:()=>bv.current?.click(),title:ao("chat.attachFile"),"aria-label":ao("chat.attachFile"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:"var(--radius-control)",color:aO.length||aQ.length?"var(--accent)":"var(--text-muted)",cursor:"pointer",opacity:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:a=>{a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color=aO.length||aQ.length?"var(--accent)":"var(--text)"},onMouseLeave:a=>{a.currentTarget.style.background="none",a.currentTarget.style.color=aO.length||aQ.length?"var(--accent)":"var(--text-muted)"},children:(0,d.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,d.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,d.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),q&&bJ.bo.length>0&&(0,d.jsxs)("div",{ref:bo,style:{position:"relative",flexShrink:+!!ar,minWidth:0},children:[(0,d.jsxs)("button",{className:`${ar?"composer-icon-button":"composer-chip"}${aC?" is-active":""}`,onClick:a=>{let b=a.currentTarget.getBoundingClientRect();aF({top:b.top,bottom:b.bottom,left:b.left,width:b.width}),av(!1),az(""),aD(a=>!a)},disabled:i||u,"aria-haspopup":"menu","aria-expanded":aC,onKeyDown:a=>{"Escape"===a.key&&aC&&(a.stopPropagation(),aD(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:aC?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:i||u?"not-allowed":"pointer",fontSize:12,opacity:i?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:a=>{i||u||(a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color="var(--text)")},onMouseLeave:a=>{a.currentTarget.style.background=aC?"var(--bg-hover)":"none",a.currentTarget.style.color="var(--text-muted)"},title:ao("chat.mainPreset"),"aria-label":ao("chat.mainPreset"),children:[(0,d.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,d.jsx)("path",{d:"M12 3l2.2 5.1 5.6.5-4.2 3.7 1.2 5.5L12 15l-4.8 2.8 1.2-5.5L4.2 8.6l5.6-.5z"})}),ar?null:(0,d.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:ao("chat.mainPreset")})]}),aC&&aE&&(()=>{let a=window.visualViewport?.height??window.innerHeight,{side:b,maxHeight:c}=e$(aE.top,aE.bottom,a,e_(a,.6,460),{gap:6,prefer:"above"}),e="above"===b?{bottom:a-aE.top+6}:{top:aE.bottom+6},f=ar?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:aE.left,width:"max-content",minWidth:aE.width};return(0,d.jsx)("div",{ref:bp,role:"menu","aria-label":ao("chat.mainPreset"),onKeyDown:a=>{"Escape"===a.key&&(aD(!1),bo.current?.querySelector("button")?.focus())},style:{position:"fixed",...e,...f,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:c,display:"flex",flexDirection:"column"},children:(0,d.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:bJ.bo.map(a=>{let b=a.alias===cK;return(0,d.jsxs)("button",{role:"menuitemradio","aria-checked":b,onClick:()=>{aD(!1),q((0,bJ.zq)(a))},title:`${a.provider}/${a.model}`,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:b?"var(--bg-selected)":"none",border:"none",color:b?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:b?600:400,whiteSpace:"nowrap"},onMouseEnter:a=>{b||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{b||(a.currentTarget.style.background="none")},children:[b?(0,d.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,d.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,d.jsx)("span",{style:{width:10,flexShrink:0}}),(0,d.jsx)("img",{className:"account-avatar",src:(0,bJ.uk)(a.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,d.jsx)("span",{children:a.alias}),(0,d.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[a.provider,"/",a.model,void 0!==a.oauthPosition?` \xb7 OAuth ${a.oauthPosition}`:""]})]},a.alias)})})})})()]}),(cJ.length>0||cU||n)&&p&&(0,d.jsxs)("div",{ref:bm,style:{position:"relative",flex:ar?"1 1 0%":void 0,width:ar?0:void 0,minWidth:44*!!ar},children:[(0,d.jsxs)("button",{className:`composer-chip${au?" is-active":""}`,onClick:a=>{let b=a.currentTarget.getBoundingClientRect();ax({top:b.top,bottom:b.bottom,left:b.left,width:b.width}),av(a=>(a&&az(""),!a))},disabled:i||u,"aria-busy":u||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:ar?"flex-start":void 0,padding:ar?"8px 10px":"8px 12px",height:32,width:ar?"100%":void 0,maxWidth:ar?"100%":220,overflow:"hidden",background:au?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:i||u?"not-allowed":"pointer",fontSize:12,opacity:i?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:a=>{i||u||(a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color="var(--text)")},onMouseLeave:a=>{a.currentTarget.style.background=au?"var(--bg-hover)":"none",a.currentTarget.style.color="var(--text-muted)"},title:u?"Switching model":cJ.length>0?"Change model":"No available models",children:[u?(0,d.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,d.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,d.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,d.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,d.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,d.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,d.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,d.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,d.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,d.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,d.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,d.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,d.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:cU??(cJ.length>0?"Select model":"No models")})]}),au&&aw&&(()=>{let a=window.visualViewport?.height??window.innerHeight,{side:b,maxHeight:c}=e$(aw.top,aw.bottom,a,e_(a,.6,460),{gap:6,prefer:"above"}),e="above"===b?{bottom:a-aw.top+6}:{top:aw.bottom+6},f=ar?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:aw.left,width:"max-content",minWidth:aw.width};return(0,d.jsxs)("div",{ref:bn,style:{position:"fixed",...e,...f,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:c,display:"flex",flexDirection:"column"},children:[cO&&(0,d.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,d.jsx)("input",{value:ay,onChange:a=>az(a.target.value),onKeyDown:a=>{"Escape"===a.key&&(az(""),av(!1))},placeholder:ao("chat.filterModels"),"aria-label":ao("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!ar,fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,d.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[cS.length>0&&(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:ao("chat.frequentModels")}),cS.map(({option:a,count:b})=>cT(a,"frequent",b))]}),cQ.length>0&&!ay.trim()&&t&&(0,d.jsxs)("div",{style:{borderTop:cS.length>0?"1px solid var(--border)":"none"},children:[(0,d.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:ao("chat.modelRoles")}),cQ.map(a=>{let b=cR?.role===a.role,c=a.resolved?.name??a.resolved?.modelId??"";return(0,d.jsxs)("button",{onClick:()=>{av(!1),az(""),t(a.role)},title:a.selector??c,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:b?"var(--bg-selected)":"none",border:"none",color:b?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:a=>{b||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{b||(a.currentTarget.style.background="none")},children:[b?(0,d.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,d.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,d.jsx)("span",{style:{width:10,flexShrink:0}}),(0,d.jsx)("span",{style:{flexShrink:0,minWidth:58,padding:"1px 6px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-subtle)",color:b?"var(--accent)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:a.tag??a.role.toUpperCase()}),(0,d.jsx)("span",{style:{fontWeight:b?600:500},children:a.name}),(0,d.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[c,a.resolved?.thinkingLevel?` \xb7 ${a.resolved.thinkingLevel}`:""]})]},a.role)}),(0,d.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:"1px solid var(--border)"},children:ao("chat.allModels")})]}),0===cP.length?(0,d.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:ay.trim()?ao("chat.noMatchingModels"):"No available models"}):cP.map((a,b)=>(0,d.jsxs)("div",{children:[cP.length>1&&(0,d.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:b>0?"1px solid var(--border)":"none"},children:a.provider}),a.options.map(a=>cT(a,"all"))]},a.provider))]})]})})()]}),H&&(0,d.jsxs)("div",{ref:br,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,d.jsxs)("button",{type:"button",className:`${ar?"composer-icon-button":"composer-chip"}${aI?" is-active":""}`,onClick:a=>{let b=a.currentTarget.getBoundingClientRect();aL({top:b.top,bottom:b.bottom,left:b.left,width:b.width}),av(!1),az(""),aD(!1),aJ(a=>!a)},disabled:i||u,"aria-haspopup":"menu","aria-expanded":aI,onKeyDown:a=>{"Escape"===a.key&&aI&&(a.stopPropagation(),aJ(!1))},title:ao("chat.changeReasoning",{level:cY}),"aria-label":ao("chat.changeReasoning",{level:cY}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ar?0:"8px 12px",height:32,background:aI?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:i||u?"not-allowed":"pointer",fontSize:12,opacity:i?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:a=>{i||u||(a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color="var(--text)")},onMouseLeave:a=>{a.currentTarget.style.background=aI?"var(--bg-hover)":"none",a.currentTarget.style.color="var(--text-muted)"},children:[(0,d.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,d.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,d.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,d.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),ar?null:(0,d.jsx)("span",{style:{whiteSpace:"nowrap"},children:cY})]}),aI&&aK&&(()=>{let a=window.visualViewport?.height??window.innerHeight,{side:b,maxHeight:c}=e$(aK.top,aK.bottom,a,e_(a,.6,460),{gap:6,prefer:"above"}),e="above"===b?{bottom:a-aK.top+6}:{top:aK.bottom+6},f=ar?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:aK.left,width:"max-content",minWidth:Math.max(180,aK.width)};return(0,d.jsx)("div",{role:"menu","aria-label":ao("chat.changeReasoningLabel"),onKeyDown:a=>{"Escape"===a.key&&(aJ(!1),br.current?.querySelector("button")?.focus())},style:{position:"fixed",...e,...f,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:c},children:c0.map(({level:a,ceiling:b})=>{let c=(E??"auto")===a&&("auto"!==a||(G??null)===b),e=b??a,f="auto"===a&&null===b?null:cX(e),g=b?`auto ≤ ${f??b}`:f??a,h=b?ao("chat.thinkingAutoCapped",{level:f??b}):ao(ff[a]);return(0,d.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":c,onClick:()=>{aJ(!1),H(a,b)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:c?"var(--bg-selected)":"none",border:"none",color:c?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:c?600:400,whiteSpace:"nowrap"},onMouseEnter:a=>{c||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{c||(a.currentTarget.style.background="none")},children:[c?(0,d.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,d.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,d.jsx)("span",{style:{width:10,flexShrink:0}}),(0,d.jsxs)("span",{style:{flex:1},children:[g,null!==f&&(0,d.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",e,")"]})]}),(0,d.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:h})]},b?`auto-${b}`:a)})})})()]}),M&&(al=L?ao("chat.fastModeBusy"):null===K?ao("chat.fastModeUnknown"):K.active?ao("chat.fastModeActive"):K.enabled?ao("chat.fastModeInactive"):ao("chat.fastModeOff"),am=L||i||u,an=K?.enabled===!0,(0,d.jsx)("button",{type:"button",className:`composer-icon-button${K?.active?" is-active":""}`,onClick:M,disabled:am,"aria-pressed":null===K?void 0:K.enabled,"aria-busy":L||void 0,title:al,"aria-label":al,style:{flexShrink:0,opacity:i?.5:1},children:(0,d.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:K?.active?"var(--accent)":"none",stroke:an?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===K?"3 2":void 0,style:{opacity:an&&!K?.active?.6:1},"aria-hidden":"true",children:(0,d.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})),!ar&&c$&&(0,d.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:c$}),(0,d.jsx)(en,{sessionId:aa})]}),(0,d.jsxs)("div",{ref:bs,style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:ar?4:2},children:[ar?(0,d.jsx)("button",{type:"button",className:`composer-icon-button${aM?" is-active":""}`,title:ao("chat.moreControls"),"aria-label":ao("chat.moreControls"),"aria-expanded":aM,onClick:()=>{av(!1),az(""),aN(a=>!a)},children:(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,d.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,d.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,d.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,d.jsx)(h.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:aM?void 0:ao("chat.moreControls"),"aria-label":ao("chat.moreControls"),"aria-expanded":aM,onClick:()=>{av(!1),az(""),aN(a=>!a)},children:ao("chat.moreControls")}),(0,d.jsxs)("div",{role:"group","aria-label":ao("chat.moreControls"),style:{display:aM?"flex":"none",alignItems:"center",gap:1,position:"absolute",right:0,bottom:"100%",marginBottom:"var(--seed-dimension-x1)",zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"wrap",justifyContent:"flex-end",border:"1px solid var(--seed-color-stroke-neutral-muted)",borderRadius:"var(--seed-radius-r2)",background:"var(--seed-color-bg-layer-floating)",boxShadow:"var(--seed-shadow-s2)"},children:[!i&&C&&(0,d.jsxs)("div",{ref:bq,style:{position:"relative"},children:[(0,d.jsxs)("button",{className:`composer-chip${aG?" is-active":""}`,onClick:()=>!i&&aH(a=>!a),disabled:i,title:ao("chat.changeToolPreset")+`: ${c1}`,"aria-label":ao("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:aG?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:i?"not-allowed":"pointer",fontSize:12,opacity:i?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:a=>{i||(a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color="var(--text)")},onMouseLeave:a=>{a.currentTarget.style.background=aG?"var(--bg-hover)":"none",a.currentTarget.style.color="var(--text-muted)"},children:[(0,d.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.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"})}),(0,d.jsx)("span",{style:{whiteSpace:"nowrap"},children:c1})]}),aG&&(0,d.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",minWidth:120},children:e4.map(a=>{let b=e5[a],c=(B??"default")===b,e="off"===a?ao("chat.noTools"):"default"===a?ao("chat.builtInTools",{tools:e6}):ao("chat.allBuiltInTools",{tools:`${e6} + ${e7}`});return(0,d.jsxs)("button",{onClick:()=>{aH(!1),c||C(b)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:c?"var(--bg-selected)":"none",border:"none",color:c?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:c?600:400,whiteSpace:"nowrap"},onMouseEnter:a=>{c||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{c||(a.currentTarget.style.background="none")},children:[c?(0,d.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,d.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,d.jsx)("span",{style:{width:10,flexShrink:0}}),(0,d.jsx)("span",{style:{flex:1},children:a}),(0,d.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:e})]},a)})})]}),!i&&v&&(0,d.jsx)("div",{children:(0,d.jsx)("button",{className:`composer-chip${y?" is-active is-danger":""}`,onClick:y?w:v,disabled:i&&!y,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:y?"var(--danger-soft)":"none",border:"none",borderRadius:"var(--radius-control)",color:y?"var(--danger)":"var(--text-muted)",cursor:i&&!y?"not-allowed":"pointer",fontSize:12,opacity:i&&!y?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:a=>{(!i||y)&&(a.currentTarget.style.background=y?"var(--danger-soft)":"var(--bg-hover)",a.currentTarget.style.color=y?"var(--danger)":"var(--text)")},onMouseLeave:a=>{a.currentTarget.style.background=y?"var(--danger-soft)":"none",a.currentTarget.style.color=y?"var(--danger)":"var(--text-muted)"},title:y?ao("chat.stopCompaction"):ao("chat.compactContext"),"aria-label":y?ao("chat.stopCompaction"):ao("chat.compactContext"),children:y?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,d.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(0,d.jsx)("span",{style:{whiteSpace:"nowrap"},children:ao("chat.compacting")})]}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,d.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,d.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,d.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(0,d.jsx)("span",{style:{whiteSpace:"nowrap"},children:ao("chat.compact")})]})})}),aM&&(0,d.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:ao("chat.collapseControls"),"aria-label":ao("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{aH(!1),aJ(!1),aN(!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:a=>{a.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:a=>{a.currentTarget.style.background="var(--bg-hover)"},children:(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,d.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,d.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),i&&(0,d.jsxs)("button",{className:"composer-chip is-danger is-active",onClick:b,title:ao("chat.stopAgent"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:32,background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:a=>{a.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:a=>{a.currentTarget.style.background="var(--danger-soft)"},children:[(0,d.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,d.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),ao("chat.stop")]}),(0,d.jsx)(el,{sessionId:aa,onEnsureSession:ab,onTranscriptPersisted:ac}),void 0!==X&&(0,d.jsx)(ed,{soundEnabled:W??!0,onToggle:X})]})]}),ar&&c$&&(0,d.jsx)("div",{style:{marginTop:4,padding:"0 4px",fontSize:12,color:"var(--text-muted)",overflowWrap:"anywhere"},children:c$})]})]})});function fD({statuses:a}){if(0===a.length)return null;let b=[...a].sort((a,b)=>a.key.localeCompare(b.key)).map(({text:a})=>a.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()).join(" "),c=aj(b);return(0,d.jsx)("div",{role:"status","aria-label":c,title:c,style:{display:"flex",alignItems:"center",flexShrink:0,minWidth:0,height:36,padding:"0 12px",borderTop:"1px solid var(--border)",background:"transparent"},children:(0,d.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ao(b).map((a,b)=>(0,d.jsx)("span",{style:a.style,children:a.text},b))})})}function fE({phases:a}){let{t:b}=(0,x.s)(),[c,f]=(0,e.useState)(!1),[g,h]=(0,e.useState)(!1),{currentPhase:i,activeTask:j,remaining:k,completed:l,total:m,percent:n}=function(a){let b=0,c=0,d=null,e=null,f=null;for(let g of a)for(let a of g.tasks){if("completed"===a.status){b+=1;continue}"abandoned"!==a.status&&(c+=1,"in_progress"===a.status?d||(d={phase:g,task:a}):"blocked"===a.status?f||(f={phase:g,task:a}):e||(e={phase:g,task:a}))}let g=d??e??f,h=b+c;return{currentPhase:g?.phase??null,activeTask:g?.task??null,remaining:c,completed:b,total:h,percent:h>0?Math.round(b/h*100):null}}(a);if(0===m)return null;let o=0===k;return(0,d.jsxs)("div",{className:`todo-strip${o?" is-done":""}`,children:[(0,d.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":c,onClick:()=>f(a=>!a),children:[(0,d.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:o?"✓":"›"}),i&&(0,d.jsx)("span",{className:"todo-strip-phase",children:i.name}),(0,d.jsx)("span",{className:"todo-strip-task",children:o?b("todo.allDone",{count:l}):j?.content??""}),(0,d.jsx)("span",{className:"todo-strip-count",children:o?b("todo.progressDone",{percent:n??0,completed:l,total:m}):b("todo.progress",{percent:n??0,completed:l,total:m,remaining:k})})]}),c&&(0,d.jsxs)("div",{className:"todo-strip-body",children:[a.map((b,c)=>{let e=b.tasks.filter(a=>g||"completed"!==a.status);return 0===e.length?null:(0,d.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[a.length>1&&(0,d.jsx)("div",{className:"todo-checklist-phase-name",children:b.name}),e.map((a,b)=>(0,d.jsx)(bY,{task:a},`${a.content}-${b}`))]},`${b.name}-${c}`)}),l>0&&(0,d.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":g,onClick:()=>h(a=>!a),children:b(g?"todo.hideCompleted":"todo.showCompleted",{count:l})})]})]})}function fF(a=document){return"visible"!==a.visibilityState||!a.hasFocus()}function fG(a){switch(a.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==a.closed;default:return!1}}async function fH(a,b={createWindowNotification:(a,b)=>new Notification(a,b),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let c={body:a.body,...a.tag?{tag:a.tag}:{}};if(b.getServiceWorkerRegistration)try{let d=await b.getServiceWorkerRegistration();if(d)return await d.showNotification(a.title,{...c,data:{url:a.sessionUrl}}),"service-worker"}catch{}try{let d=b.createWindowNotification(a.title,c);return d.onclick=()=>{d.close(),a.onClick()},"window"}catch{return null}}var fI=c(95361);class fJ extends Error{constructor(a,b,c,d){super(a),this.status=b,this.code=c,this.accepted=d,this.name="AgentCommandError"}}async function fK(a,b){let c=await fetch(`/api/agent/${encodeURIComponent(a)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)}),d=await c.json().catch(()=>({}));if(!c.ok||d.error)throw new fJ(d.error??`HTTP ${c.status}`,c.status,d.code,d.accepted);return d.data}let fL="ompweb-update-return-v1";function fM(a){return null===a||"running"===a?null:"failed"===a?3e4:8e3}function fN(a,b){let c=new Map(a.map(a=>[a.id,a]));for(let a of b)c.set(a.id,function(a,b){return a&&(void 0!==a.parentToolCallId&&void 0!==b.parentToolCallId?a.parentToolCallId===b.parentToolCallId:void 0===a.sessionFile||void 0===b.sessionFile||a.sessionFile===b.sessionFile)?{...b,index:a.index,agent:a.agent,agentSource:a.agentSource,description:a.description??b.description,task:a.task??b.task,assignment:a.assignment??b.assignment,sessionFile:b.sessionFile??a.sessionFile,parentToolCallId:b.parentToolCallId??a.parentToolCallId}:b}(c.get(a.id),a));let d=[...c.values()];return[...d.filter(a=>"pending"===a.status||"running"===a.status).sort((a,b)=>a.index-b.index||a.id.localeCompare(b.id)),...d.filter(a=>"pending"!==a.status&&"running"!==a.status).sort((a,b)=>b.lastUpdate-a.lastUpdate||a.id.localeCompare(b.id))].slice(0,128)}function fO(a,b){switch(b.type){case"start":return{isStreaming:!0,streamingMessage:null};case"update":return{isStreaming:!0,streamingMessage:b.message};case"end":case"reset":return{isStreaming:!1,streamingMessage:null};default:return a}}function fP(a){return{steering:a?.steering??[],followUp:a?.followUp??[]}}function fQ(a){if(a&&"boolean"==typeof a.fastModeEnabled)return{enabled:a.fastModeEnabled,active:!0===a.fastModeActive}}function fR(a){return b=>{let c=a?.isCompacting?a.compaction:null;if(!c)return b;let d=Date.now()-c.elapsedMs;return{startedAt:b?Math.min(b.startedAt,d):d,reason:b?.reason??c.reason}}}function fS(a,b){if(a===b)return!0;if(a.length!==b.length)return!1;for(let c=0;c<a.length;c+=1){let d=a[c],e=b[c];if(!d||!e||d.name!==e.name||d.tasks.length!==e.tasks.length)return!1;for(let a=0;a<d.tasks.length;a+=1){let b=d.tasks[a],c=e.tasks[a];if(!b||!c||b.content!==c.content||b.status!==c.status||b.blocker!==c.blocker)return!1}}return!0}function fT(a){return"aborted"===a.stopReason?"aborted":"error"===a.stopReason||a.errorMessage?"failed":a.stopReason?"completed":"unknown"}function fU(a,b){for(let c=a.length-1;c>=0;c--){let d=b[c]??null;if(!aH(d??void 0))return{message:a[c],entryId:d}}return null}let fV=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class fW extends Error{constructor(a){super("timeout"===a?"Timed out connecting to the agent event stream. Please try again.":"Failed to connect to the agent event stream. Please try again."),this.status=a,this.name="EventStreamConnectionError"}}function fX(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function fY(a){return new Promise(b=>setTimeout(b,a))}function fZ(a){let b=a.findIndex(a=>!a.exiting);return -1===b?a:a.map((a,c)=>c===b?{...a,exiting:!0}:a)}function f$(a,b){switch(b.type){case"add":if(a.visible.some(a=>a.exiting)||a.visible.length>=5)return{visible:a.visible.some(a=>a.exiting)?a.visible:fZ(a.visible),pending:[...a.pending,b.notice]};return{...a,visible:[...a.visible,b.notice]};case"mark_oldest_exiting":return{...a,visible:fZ(a.visible)};case"remove":return function(a,b){let c=a,d=b;for(;d.length>0&&c.length<5;){let[a,...b]=d;c=[...c,a],d=b}return d.length>0&&!c.some(a=>a.exiting)&&(c=fZ(c)),{visible:c,pending:d}}(a.visible.filter(a=>a.id!==b.id),a.pending);default:return a}}function f_(a){if(!a||"object"!=typeof a||"image"!==a.type)return"";let b=a.source;return b&&"object"==typeof b?["url"===b.type?"url":"base64","string"==typeof b.media_type?b.media_type:"","string"==typeof b.data?b.data:"","string"==typeof b.url?b.url:""].join(":"):["base64","string"==typeof a.mimeType?a.mimeType:"","string"==typeof a.data?a.data:"",""].join(":")}function f0(a){let b,c=a.content;return"string"==typeof c?JSON.stringify({text:c,images:[]}):Array.isArray(c)?JSON.stringify({text:"string"==typeof(b=a.content)?b:Array.isArray(b)?b.map(a=>a&&"object"==typeof a&&"text"===a.type&&"string"==typeof a.text?a.text:"").filter(Boolean).join("\n"):"",images:c.map(f_).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function f1(a){return"user"===a.role?`user:${f0(a)}`:"bashExecution"===a.role?JSON.stringify({role:a.role,command:a.command,output:a.output,exitCode:a.exitCode,cancelled:a.cancelled,truncated:a.truncated,fullOutputPath:a.fullOutputPath,excludeFromContext:a.excludeFromContext}):JSON.stringify({role:a.role,content:a.content,model:a.model,provider:a.provider,customType:a.customType})}function f2(a,b){return a&&"object"==typeof a?"number"!=typeof a.tokensBefore||"number"!=typeof a.estimatedTokensAfter?null:{reason:b,tokensBefore:a.tokensBefore,estimatedTokensAfter:a.estimatedTokensAfter}:null}function f3(a){return a?.map(({data:a,mimeType:b})=>({data:a,mimeType:b}))}let f4={count:50,end:null};function f5(a,b){let c=Math.max(a,0),d=null===b.end?c:Math.min(Math.max(b.end,0),c),e=Math.min(Math.max(b.count,0),d),f=d-e;return{startIndex:f,endIndex:d,hasMore:f>0,hasLater:d<c}}function f6(a,b,c){let{startIndex:d,endIndex:e}=f5(a,c);if(b>=d&&b<e)return c;let f=Math.max(0,b-10),g=Math.max(b+1,f+50);return g>=a?{count:a-f,end:null}:{count:g-f,end:g}}function f7({sticker:a,text:b,tag:c,followRef:f}){let g=(0,e.useRef)(null);return a||b?(0,d.jsxs)("div",{ref:g,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[a&&(0,d.jsx)("img",{className:"cue-bubble-sticker",src:a,alt:dE[c]}),b&&(0,d.jsx)("p",{className:a?"cue-bubble":"cue-bubble cue-bubble--solo",children:b}),a&&(0,d.jsx)(dA(),{id:"ad10be785ccf4f7",children:".cue-bubble-sticker{transform-origin:center 75%;animation:cue-sticker-pop 200ms cubic-bezier(0,0,.15,1)both}@keyframes cue-sticker-pop{from{opacity:0;transform:scale(.88)}to{opacity:1;transform:scale(1)}}@media(prefers-reduced-motion:reduce){.cue-bubble-sticker{animation:none}}"})]}):null}function f8(a){if("user"!==a.role)return null;let b="string"==typeof a.content?a.content:a.content.filter(a=>"text"===a.type).map(a=>a.text).join("\n"),c=(cB(b)?.message??b).trim();return c.length>0?c:null}let f9=[],ga=(0,e.memo)(function({messages:a,entryIds:b,toolResultsMap:c,modelNames:f,messageCwd:g,onOpenFile:h,sessionBusy:i,isNew:j,isStreaming:k,handleFork:l,forkingEntryId:m,handleNavigate:n,handleEditContent:o,sessionId:p,main:q,process:r,dispatchSlots:s,compactedDispatch:t,startIndex:u,endIndex:v,sentinelRef:w,laterSentinelRef:x,flashItem:y,t:z,onProcessLogChange:A,cues:B,cueFollowRef:C}){(0,e.useEffect)(()=>{A({groups:r,messages:a,entryIds:b,toolResults:c,modelNames:f,cwd:g,sessionId:p})},[A,r,a,b,c,f,g,p]);let D=(0,e.useMemo)(()=>{let b=new Map;for(let[d,e]of function(a,b,c,d){let e=new Map;a.forEach((a,b)=>{"answer"===a.kind&&e.set(a.idx,b)});let f=new Map,g=new Map;for(let a of b){let b=g.get(a.anchorIdx);for(let h of(b||(b=new Set,g.set(a.anchorIdx,b)),a.entries)){let a=c[h.idx];if(a?.role!=="assistant")continue;let g=Math.max(0,(h.blocks?e.get(h.idx):void 0)??h.afterMainIndex??-1),i=b;!function(a,b,c){for(let d of a){if("toolCall"!==d.type||"learn"!==d.toolName&&"manage_skill"!==d.toolName)continue;let a=b?.get(d.toolCallId);if(!a||a.isError)continue;let e=d.input??{};if("manage_skill"===d.toolName){let a=aL(e.action);if(!0===aK[a]){let b={kind:"skill",action:a,name:aL(e.name)};c(JSON.stringify(b),b)}continue}let f=aL(e.memory),g=e.skill,h=g?{action:aL(g.action),name:aL(g.name)}:void 0;c(JSON.stringify({kind:"lesson",memory:f,skill:h}),{kind:"lesson",memory:f.length>160?`${f.slice(0,160)}…`:f,...h?{skill:h}:{}})}}(h.blocks??a.content??[],d,(a,b)=>{if(i.has(a))return;i.add(a);let c=f.get(g);c?c.push(b):f.set(g,[b])})}}return f}(q,r,a,c)){let a=e.map(a=>{if("skill"===a.kind)return z("chat.savedSkill",{action:a.action,name:a.name});let b=z("chat.savedLesson",{memory:a.memory});return a.skill?`${b} (${z("chat.savedSkill",a.skill)})`:b});b.set(d,{role:"custom",customType:aE,content:[z("chat.lessonsSaved"),...a.map(a=>`- ${a}`)].join("\n"),display:!0})}return b},[q,r,a,c,z]),E=(0,e.useMemo)(()=>{let b=null;if(i)for(let c of q)"message"===c.kind&&a[c.idx]?.role==="user"&&(b=c.idx);let d=new Map;for(let[e,f]of function(a,b,c){let d=new Map,e=a.filter(a=>"message"===a.kind&&b[a.idx]?.role==="user").map(a=>a.idx),f=new Map;for(let[g,h]of(a.forEach((a,b)=>{"answer"===a.kind&&f.set(a.anchorIdx,b)}),f)){if(g===c)continue;let a=e.find(a=>a>g);d.set(h,{from:g+1,to:a??b.length})}return d}(q,a,b))d.set(e,function(a,b,c){let d=[],e=[];for(let c of a){if("toolCall"!==c.type)continue;if("task"===c.toolName){e.push(c);continue}if("bash"!==c.toolName)continue;let a="string"==typeof c.input.command?c.input.command.trim():"";if(!a||!dr.test(a))continue;let f=b.get(c.toolCallId),g=f?function(a){let b=a.details;if("number"==typeof b?.exitCode)return b.exitCode;let c=a.content.map(a=>"text"===a.type?a.text:"").join("\n"),d=/Command exited with code (-?\d+)\s*$/.exec(c.trimEnd());return d?Number(d[1]):null}(f):null,h=null===g?f?.isError?"failed":"unobserved":0===g?"passed":"failed";d.push({toolCallId:c.toolCallId,command:a,state:h,exitCode:g})}return{checks:d,dispatchCalls:e,files:aR(a,b,c)}}(function(a,b,c){let d=[];for(let e=Math.max(0,b);e<Math.min(a.length,c);e++){let b=a[e];"assistant"===b.role&&d.push(...b.content??[])}return d}(a,f.from,f.to),c,g));return d},[q,a,c,g,i]),F=u>0,G=v<q.length,H=(e,q={})=>{let r=q.messageOverride??a[e],s=e-1;for(;s>=0&&aH(b[s]);)s-=1;let t="user"===r.role&&s>=0&&"assistant"===a[s].role?b[s]:void 0,u=q.keyPrefix??"message",v=!1;if("assistant"===r.role){v=!0;for(let b=e+1;b<a.length;b++){let c=a[b].role;if("user"===c)break;if("assistant"===c){v=!1;break}}v&&k&&e===a.length-1&&(v=!1)}return void 0!==q.showTimestamp&&(v=q.showTimestamp),(0,d.jsx)(cX,{message:r,toolResults:c,modelNames:f,cwd:g,onOpenFile:h,entryId:b[e],onFork:i||j||0===e&&"user"===r.role?void 0:l,forking:m===b[e],onNavigate:i?void 0:n,prevAssistantEntryId:i?void 0:t,onEditContent:o,showTimestamp:v,prevTimestamp:e>0?a[e-1].timestamp:void 0,sessionId:p,writtenFiles:q.writtenFiles,dispatchSlot:q.dispatchSlot,turnSummary:q.turnSummary},`${u}-view-${e}`)},I=(b,c)=>{let e=q[b],f="message"===e.kind&&a[e.idx]?.role==="user";return(0,d.jsx)("div",{"data-chat-item":b,"data-chat-question":f?"":void 0,className:y===b?"chat-item chat-jump-flash":"chat-item",children:c})};return(0,d.jsxs)(d.Fragment,{children:[F&&(0,d.jsx)("div",{ref:w,className:"py-3 text-center text-xs text-text-muted",children:z("chat.loadEarlier",{count:u})}),q.slice(u,v).map((f,i)=>{let j=u+i,k=t?.position===j?(0,d.jsx)(cl,{calls:t.calls}):null,l="message"===f.kind?f.anchorIdx??f.idx:f.anchorIdx,m=q[j+1],n=m?"message"===m.kind?m.anchorIdx??m.idx:m.anchorIdx:null,o=m?m.idx:1/0,r=B.filter(c=>{let d=null!==c.anchorEntryId?b.indexOf(c.anchorEntryId):Math.min(c.liveIndex??-1,a.length-1);return d>=f.idx&&d<o}).map(a=>(0,d.jsx)(f7,{sticker:a.sticker,text:a.text,tag:a.tag,followRef:C},`cue-${a.id}`)),v=n!==l,w=D.get(j),x=w?(0,d.jsx)(cX,{message:w,cwd:g,onOpenFile:h},`saved-lessons-${j}`):null,y=v?(0,d.jsx)(dQ,{turnIndex:l,turnEntryId:b[l],sessionId:p,cwd:g,onOpenFile:h}):null;if("message"===f.kind)return(0,d.jsxs)(e.Fragment,{children:[k,I(j,H(f.idx)),x,y,r]},`message-${f.idx}`);let z=aR(f.precedingBlocks,c,g);return(0,d.jsxs)(e.Fragment,{children:[k,I(j,H(f.idx,{keyPrefix:`answer-${f.runIndex}`,messageOverride:av(a[f.idx],f.blocks),writtenFiles:z,dispatchSlot:s.get(j),turnSummary:E.get(j)})),x,y,r]},`answer-${f.idx}-${f.runIndex}`)}),t?.position===q.length&&v===q.length&&(0,d.jsx)(cl,{calls:t.calls}),G&&(0,d.jsx)("div",{ref:x,className:"py-3 text-center text-xs text-text-muted",children:z("chat.loadLater",{count:q.length-v})})]})});function gb({session:a,newSessionCwd:b,initialSessionData:f,transitioning:g=!1,onAgentEnd:h,onAttentionNeeded:i,onSessionCreated:j,onSessionForked:k,modelsRefreshKey:l,chatInputRef:m,onBranchDataChange:n,onSystemPromptChange:o,onSessionStatsChange:p,onSessionStatsPanelOpen:q,onContextUsageChange:r,onSubagentsChange:s,onMainIdentityChange:t,onOpenWorkspaceView:u,onProcessLogChange:v,onOpenFile:w,transcriptReplacement:y,onComposerFocusChange:z,onSessionBusyChange:A,onWaitingChange:B,onAttentionChange:C,soundEnabled:D=!0,onSoundToggle:F,playCueSound:G=async()=>({sticker:null,text:null}),preloadCueSound:H,unlockAudio:I,jumpRequest:J=null,onJumpHandled:K}){var L;let M,O,{t:P}=(0,x.s)(),Q=(0,e.useRef)(G);Q.current=G,(0,e.useRef)(null);let R=(0,e.useRef)(H);R.current=H;let[S,T]=(0,e.useState)([]);(0,e.useRef)(S).current=S;let U=(0,e.useRef)(0),V=(0,e.useRef)([]),W=(0,e.useRef)([]),X=(0,e.useRef)(null),Y=(0,e.useRef)(0);(0,e.useRef)(-1);let Z=(0,e.useRef)(-1);(0,e.useCallback)(()=>{let a=X.current?.current;return a?{sessionId:a,turn:Y.current}:null},[]);let $=(0,e.useCallback)(a=>X.current?.current===a.sessionId&&Y.current===a.turn,[]),_=(0,e.useCallback)((a,b,c,d)=>{if(!a.sticker&&!a.text)return;U.current=Math.max(U.current+1,Date.now());let e={id:U.current,sticker:a.sticker,text:a.text,tag:b,sessionId:c.sessionId},f="entry"===d.kind?{...e,anchorEntryId:d.entryId}:{...e,anchorEntryId:null,liveIndex:d.liveIndex,intent:d.intent};T(a=>{let b=[...a,f];return null!==f.anchorEntryId&&function(a,b){let c=[];for(let d of b)d.sessionId===a&&null!==d.anchorEntryId&&c.push({id:d.id,anchorEntryId:d.anchorEntryId,sticker:d.sticker,text:d.text,tag:d.tag});try{window.localStorage.setItem(`omp-cues:${a}`,JSON.stringify(c.slice(-200)))}catch{}}(c.sessionId,b),b})},[]),aa=(0,e.useCallback)((a,b,c,d)=>{let e=()=>$(c)&&("working"!==b||Z.current!==c.turn);e()&&Q.current(a,b,e).then(a=>{null!==b&&null!==d&&e()&&_(a,b,c,d)}).catch(()=>{})},[$,_]),ab=(0,e.useCallback)(async(a,b,c)=>{let d=(await bP(a,b,c))?.alias??null;return d&&R.current?.(d),d},[]);(0,e.useCallback)((a,b,c,d)=>{let e=function(a,b){let c=a.length-1;if(c<0)return null;let d=Math.min(a.length,b.length);if(c<d)return{kind:"entry",entryId:b[c]};let e=dK(a[c]),f=0;for(let b=d;b<=c;b++)dK(a[b])===e&&(f+=1);return{kind:"pending",liveIndex:c,intent:{baseEntryId:d>0?b[d-1]:null,identity:e,occurrence:f}}}(V.current,W.current);ab(b.sessionId,c,d).then(c=>{aa(c,a,b,e)})},[aa,ab]);let[ac,ad]=(0,e.useState)(0),ae=(0,e.useRef)([]),af=(0,e.useCallback)(a=>{if(Y.current+=1,null!==function(a){switch(a){case"completed":return"done";case"failed":return"failed";case"aborted":return null;default:return"neutral"}}(a.outcome)){let b=a.sessionId;ae.current.push({completion:a,trigger:b?{sessionId:b,turn:Y.current}:null}),ad(a=>a+1)}h?.(a)},[h]),ag=(0,e.useCallback)(a=>{m?.current?.replaceMessage(a)},[m]),{loading:ah,error:ai,messages:ak,entryIds:al,streamState:am,agentRunning:an,bashRunning:ao,pendingBash:ap,modelNames:aq,modelList:ar,modelError:as,modelScopeWarnings:at,modelThinkingLevels:au,modelThinkingLevelMaps:aw,modelRoles:aA,toolPreset:aC,thinkingLevel:aE,effectiveThinkingLevel:aK,thinkingCeiling:aL,fastMode:aN,fastModeBusy:aO,handleFastModeToggle:aP,retryInfo:aQ,contextUsage:aR,forkingEntryId:aT,isCompacting:aU,compaction:aV,compactError:aW,compactResult:aX,displayModel:aY,modelSwitching:aZ,sessionStats:a$,runStateKnown:a_,compactedWork:a0,slashCommands:a1,slashCommandsLoading:a2,deliveryRows:a3,subagents:a4,todoPhases:a5,notices:a6,extensionDialog:a7,extensionResponse:a8,extensionCustomUi:a9,extensionStatuses:ba,extensionWidgets:bb,respondToExtensionUi:bc,sendExtensionCustomInput:bd,isAutoModelSelection:be,agentPhase:bf,isNew:bg,autoFollowPaused:bh,resumeAutoFollow:bi,pauseAutoFollow:bj,goalStatus:bk,sessionIdRef:bl,messagesEndRef:bm,scrollContainerRef:bn,handleSend:bo,handleAbort:bp,handleFork:bq,handleNavigate:br,handleModelChange:bs,handleRoleModelChange:bt,handleMainPresetChange:bu,newSessionAccount:bv,handleCompact:bw,handleSteer:bx,handleFollowUp:by,handlePromptWithStreamingBehavior:bz,handleAbortCompaction:bA,handleRecallQueue:bB,handleRemoveQueuedMessage:bC,handleBuiltinSlashCommand:bD,handleToolPresetChange:bE,handleThinkingLevelChange:bF,loadSlashCommands:bG,ensureNewSession:bH,refreshLiveTranscript:bK}=function(a){let{session:b,newSessionCwd:d,initialData:f,onAgentEnd:g,onAttentionNeeded:h,onSessionCreated:i,onSessionForked:j,modelsRefreshKey:k,onBranchDataChange:l,onSystemPromptChange:m,onSessionStatsPanelOpen:n}=a,o=null===b&&null!==d,p=f&&f.sessionId===b?.id?f:null,[q,r]=(0,e.useState)(p),[s,t]=(0,e.useState)(!o&&!p),[u,v]=(0,e.useState)(null),[w,x]=(0,e.useState)(p?.leafId??null),[y,z]=(0,e.useState)(p?.context.messages??[]),[A,B]=(0,e.useState)(p?.context.entryIds??[]),[C,D]=(0,e.useState)(p?.context.compactedWork??null),[E,F]=(0,e.useReducer)(fO,{isStreaming:!1,streamingMessage:null}),[G,H]=(0,e.useState)(!1),[I,J]=(0,e.useState)(!1),[K,L]=(0,e.useState)(null),[M,N]=(0,e.useState)({}),[O,P]=(0,e.useState)([]),[Q,R]=(0,e.useState)(null),[S,T]=(0,e.useState)([]),[U,V]=(0,e.useState)({}),[W,X]=(0,e.useState)({}),[Y,Z]=(0,e.useState)([]),[$,_]=(0,e.useState)(null),[aa,ab]=(0,e.useState)(null),[ac,ad]=(0,e.useState)(null),[ae,af]=(0,e.useState)("default"),[ag,ah]=(0,e.useState)(()=>{let a=p?.context.thinkingLevel;return a&&"off"!==a?a:"auto"}),[ai,ak]=(0,e.useState)(),[al,am]=(0,e.useState)(null),[an,ao]=(0,e.useState)(null),[ap,aq]=(0,e.useState)(!1),ar=(0,e.useRef)(0),as=(0,e.useRef)(0),at=(0,e.useRef)(""),[au,av]=(0,e.useState)(null),[aw,ax]=(0,e.useState)(p?.contextUsage??null),[ay,az]=(0,e.useState)(null),[aA,aB]=(0,e.useState)(null),[aC,aE]=(0,e.useState)(null),[aF,aJ]=(0,e.useState)(null),[aK,aL]=(0,e.useState)(!1),[aM,aN]=(0,e.useState)(!1),[aO,aP]=(0,e.useState)(null),[aQ,aR]=(0,e.useState)(null),[aS,aT]=(0,e.useState)(null),aU=(0,e.useRef)(null),[aV,aW]=(0,e.useState)(!1),[aX,aY]=(0,e.useState)(null),[aZ,a$]=(0,e.useState)([]),[a_,a0]=(0,e.useState)(!1),[a1,a2]=(0,e.useReducer)(f$,{visible:[],pending:[]}),[a3,a4]=(0,e.useState)(null),[a5,a6]=(0,e.useState)(null),[a7,a8]=(0,e.useState)(null),a9=(0,e.useRef)(null),[ba,bb]=(0,e.useState)(null),[bc,bd]=(0,e.useState)([]),[be,bf]=(0,e.useState)([]),[bg,bh]=(0,e.useState)({steering:[],followUp:[]}),[bi,bj]=(0,e.useState)([]),[bk,bl]=(0,e.useReducer)(d7,[]),bm=(0,e.useRef)(0),bn=(0,e.useMemo)(()=>(function(a,b){let c=new Map;for(let b of a){if(!b.inQueue)continue;let a=`${b.kind}\u0000${d5(b)}`;c.set(a,(c.get(a)??0)+1)}let d=[],e=(a,b)=>{b.forEach((b,e)=>{let f=`${a}\u0000${d4(b)}`,g=c.get(f)??0;g>0?c.set(f,g-1):d.push({key:`queue-${a}-${e}`,kind:a,text:b,images:0,stage:"accepted",removable:!0})})};for(let c of(e("steer",b?.steering??[]),e("followUp",b?.followUp??[]),a))d.push({key:`sent-${c.id}`,kind:c.kind,text:c.text,images:c.images,stage:c.stage,removable:c.inQueue});return d})(bk,bg),[bk,bg]),[bo,bp]=(0,e.useState)(null),bq=(0,e.useRef)(null),br=(0,e.useRef)(null),bs=(0,e.useRef)(null),bt=(0,e.useRef)(null),bu=(0,e.useRef)(null),bv=(0,e.useRef)(0),bw=(0,e.useRef)(!1),bx=(0,e.useRef)(b?.id??null),by=(0,e.useRef)(p?.leafId??null),bz=(0,e.useRef)(y),bA=(0,e.useRef)(A);bz.current=y,bA.current=A;let bB=(0,e.useRef)({sessionId:b?.id??null,outputs:[],seq:0}),bC=(0,e.useRef)(!1),bD=(0,e.useRef)(!1),bE=(0,e.useRef)(!1),bF=(0,e.useRef)(-1),bG=(0,e.useRef)("unknown"),bH=(0,e.useRef)(null),bI=(0,e.useRef)(null),bJ=(0,e.useRef)(0),bK=(0,e.useRef)(!1),bL=(0,e.useRef)(0),bM=(0,e.useRef)(null),bN=(0,e.useRef)(null),bO=(0,e.useRef)(null);(0,e.useRef)(!1);let bP=(0,e.useRef)(!0),[bQ,bR]=(0,e.useState)(!1),[bS,bT]=(0,e.useState)(null),bU=(0,e.useRef)(void 0),bV=(0,e.useRef)(0),bW=(0,e.useRef)(0),bX=(0,e.useRef)(()=>{}),bY=(0,e.useRef)(null),bZ=(0,e.useRef)(null),b$=(0,e.useRef)(null),b_=(0,e.useRef)(null),b0=(0,e.useRef)(!1),b1=(0,e.useRef)(null),b2=(0,e.useRef)(null),b3=(0,e.useRef)(null),b4=(0,e.useRef)(null),b5=(0,e.useRef)(0),b6=(0,e.useRef)(null),b7=(0,e.useRef)(null);(0,e.useRef)(!1).current=a.transitioning??!1,(0,e.useRef)(Date.now());let b8=(0,e.useRef)(0),b9=(0,e.useRef)(0),ca=(0,e.useRef)(null),cb=(0,e.useRef)(!1),cc=(0,e.useRef)(Promise.resolve()),cd=a.setToolPreset??af,ce=aC??q?.context.model??aF??null,cf=o?$??ac:ce,cg=(0,e.useMemo)(()=>{if(a3)return{...a3,totalActiveMs:q?.totalActiveMs};let a={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},c=0,d=0,e=0,f=0,g=0;for(let b of y){if("user"===b.role&&(d+=1),"toolResult"===b.role&&(f+=1),"assistant"!==b.role)continue;e+=1;let h=b.usage;g+=b.content.filter(a=>"toolCall"===a.type).length,h&&(a.input+=h.input??0,a.output+=h.output??0,a.cacheRead+=h.cacheRead??0,a.cacheWrite+=h.cacheWrite??0,c+=h.cost?.total??0)}return(a.total=a.input+a.output+a.cacheRead+a.cacheWrite,0===a.total&&0===y.length)?null:{sessionFile:q?.filePath||void 0,sessionId:bx.current??b?.id??"",sessionName:b?.name,userMessages:d,assistantMessages:e,toolCalls:g,toolResults:f,totalMessages:y.length,tokens:a,cost:c,totalActiveMs:q?.totalActiveMs,...aw?{contextUsage:aw}:{}}},[y,a3,aw,q?.filePath,q?.totalActiveMs,b?.id,b?.name]),ch=(0,e.useRef)(0),ci=(0,e.useCallback)((a,b)=>{a&&bx.current===a&&Array.isArray(b)&&(ch.current+=1,bp(c=>c?.sid===a&&fS(c.phases,b)?c:{sid:a,phases:b}))},[]),cj=(0,e.useCallback)((a,b,c)=>{bx.current===a&&ch.current===c&&Array.isArray(b)&&bp(c=>c?.sid===a&&fS(c.phases,b)?c:{sid:a,phases:b})},[]),ck=(0,e.useCallback)(a=>{let b="function"==typeof a?a(bz.current):a;bz.current=b,z(b)},[]),cl=(0,e.useCallback)(a=>{bA.current=a,B(a)},[]),cm=(0,e.useCallback)(async(a,b=!1,c=!1,d)=>{let e=!1;try{b&&t(!0);let f=d??null;if(!f){let c=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),d=await fetch(`/api/sessions/${encodeURIComponent(a)}?${c}`);if(404===d.status)return b&&(r(null),x(null),ck([]),D(null),v(null)),null;if(!d.ok)throw Error(`HTTP ${d.status}`);f=await d.json()}if(bx.current!==a)return null;r(f),x(f.leafId),by.current=f.leafId??null;let g=aI(f.context.messages,f.context.entryIds??[],bB.current.sessionId===a?bB.current.outputs:[]);ck(g.messages),cl(g.entryIds),D(f.context.compactedWork??null),ax(f.contextUsage??null),aE(a=>cb.current?a:null),v(null);let h=!c&&b4.current===a;if(h||(ah(f.context.configuredThinkingLevel??f.context.thinkingLevel??"off"),ak(f.context.thinkingLevel)),am(f.context.thinkingCeiling??null),e=!0,b&&t(!1),!c){if(h)try{let b=b5.current,c=await fetch(`/api/sessions/${encodeURIComponent(a)}/state`);if(c.ok&&bx.current===a){let d=await c.json();bx.current===a&&b5.current===b&&(d.state?.thinkingLevel!==void 0?(ah(d.state.configuredThinkingLevel??d.state.thinkingLevel),ak(d.state.thinkingLevel)):d.running||(b4.current=null,ah(f.context.configuredThinkingLevel??f.context.thinkingLevel??"off"),ak(f.context.thinkingLevel)))}}catch(a){console.error("Failed to refresh live thinking level:",a)}return null}try{let b=ch.current,c=await fetch(`/api/sessions/${encodeURIComponent(a)}/state`);if(!c.ok)throw Error(`HTTP ${c.status}`);let d=await c.json();if(bx.current!==a)return null;let e=d.state;return e?(void 0!==e.contextUsage&&ax(e.contextUsage??null),void 0!==e.systemPrompt&&az(e.systemPrompt??null),void 0!==e.thinkingLevel&&(b4.current=a,ah(e.configuredThinkingLevel??e.thinkingLevel),ak(e.thinkingLevel)),void 0!==e.thinkingCeiling&&am(e.thinkingCeiling??null),void 0!==e.extensionStatuses&&bd(e.extensionStatuses??[]),void 0!==e.extensionWidgets&&bf(e.extensionWidgets??[]),void 0!==e.queuedMessages&&bh(fP(e.queuedMessages)),void 0!==e.subagents&&bj(a=>fN(a,e.subagents??[])),cj(a,e.todoPhases,b)):d.running||bh({steering:[],followUp:[]}),d}catch(a){return console.error("Failed to load agent state:",a),null}}catch(a){return v(String(a)),null}finally{b&&!e&&t(!1)}},[cj,cl,ck]),cn=(0,e.useCallback)(a=>{let b=cc.current.then(async()=>{bx.current===a&&await cm(a)});return cc.current=b.catch(()=>{}),b},[cm]),co=(0,e.useCallback)(async(a,b)=>{let c=++as.current;try{let d=new URLSearchParams({deferThinking:"1",deferMedia:"1"});b&&d.set("leafId",b);let e=`/api/sessions/${encodeURIComponent(a)}/context?${d}`,f=await fetch(e);if(!f.ok)throw Error(`HTTP ${f.status}`);let g=await f.json();if(as.current!==c||bx.current!==a)return;by.current=b;let h=aI(g.context.messages,g.context.entryIds??[],bB.current.sessionId===a?bB.current.outputs:[]);ck(h.messages),cl(h.entryIds),D(g.context.compactedWork??null),ax(g.contextUsage??null)}catch(a){console.error("Failed to load context:",a)}},[cl,ck]),cp=(0,e.useCallback)(async a=>{try{let b=await fK(a,{type:"get_tools"});if(b){let{getPresetFromTools:a}=await Promise.resolve().then(c.bind(c,29947));cd(a(b))}}catch(a){console.error("Failed to load tools:",a)}},[cd]),cq=(0,e.useCallback)((a=0,b="(no messages)")=>{let c=bx.current;o&&d&&c&&!b0.current&&(b0.current=!0,i?.({id:c,path:"",cwd:d,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:a,firstMessage:b,transient:!0}))},[o,d,i]),cr=(0,e.useCallback)(async()=>{if(b$.current)return b$.current;let a=bx.current;if(a&&b7.current!==a||!a&&(!o||!d))return a;let b=(async()=>{let b=a;if(!b){let a=b1.current,c=b3.current,e=b2.current;a&&aJ(a);let f={cwd:d,type:"ensure_session",toolNames:(0,e1.xG)(ae),...a?{provider:a.provider,modelId:a.modelId}:{},...c?{thinkingLevel:c}:{},...a&&null!==e?{oauthPosition:e}:{}},g=JSON.stringify(f),h=b_.current,i=h?.body===g?h.createRequestId:fX();b_.current={body:g,createRequestId:i};let j=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...f,createRequestId:i})});if(!j.ok)throw Error(`HTTP ${j.status}`);let k=await j.json();b_.current=null,b=k.sessionId,bx.current=b,null!==b6.current&&(b7.current=b),k.model&&b1.current===a&&(aJ(k.model),a||ad(k.model)),k.thinkingLevel&&b3.current===c&&(ah(k.configuredThinkingLevel??k.thinkingLevel),ak(k.thinkingLevel))}for(;b7.current===b;){let a=b6.current;await fK(b,{type:"set_thinking_ceiling",ceiling:a}),b6.current===a&&b7.current===b&&(b7.current=null)}return b})();b$.current=b;try{return await b}finally{b$.current=null}},[o,d,ae]),cs=(0,e.useCallback)(async()=>{let a=bx.current??await cr();if(!a)return a$([]),[];a0(!0);try{let b=await fK(a,{type:"get_commands"}),c=b?.commands??[];return a$(c),c}catch(a){return console.error("Failed to load slash commands:",a),a$([]),[]}finally{a0(!1)}},[cr]),ct=(0,e.useCallback)(()=>{bv.current+=1,bw.current=!1,bu.current&&(clearTimeout(bu.current),bu.current=null)},[]),cu=(0,e.useCallback)(()=>{bq.current?.close(),bq.current=null,br.current=null,bs.current=null},[]),cv=(0,e.useCallback)(()=>{bt.current?.close(),bt.current=null},[]);(0,e.useCallback)(a=>{cv();let b=new EventSource(`/api/agent/${encodeURIComponent(a)}/events?entries=1`);bt.current=b,b.onmessage=b=>{try{let c=JSON.parse(b.data);"session_snapshot"===c.type?bM.current?.(c):"agent_start"===c.type&&bN.current?.(a)}catch{}}},[cv]);let cw=(0,e.useCallback)(a=>{cu();let b=new EventSource(`/api/agent/${encodeURIComponent(a)}/events`);bq.current=b,br.current=a;let c=new Promise(c=>{let d=!1,e=a=>{d||(d=!0,clearTimeout(f),bs.current?.source===b&&(bs.current.pending=!1),c({status:a,source:b}))},f=setTimeout(()=>e("timeout"),5e3);b.onmessage=a=>{try{let b=JSON.parse(a.data);"update_maintenance"===b.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:b})),"connected"===b.type&&e("connected"),bM.current?.(b)}catch{}},b.onerror=()=>{if(b.readyState===EventSource.CLOSED&&(e("closed"),bq.current===b&&(bC.current||bw.current))){bq.current=null,br.current=null,bs.current=null;let b=bv.current;setTimeout(()=>{b===bv.current&&!bq.current&&(bC.current||bw.current)&&cw(a)},1e3)}}});return bs.current={source:b,promise:c,pending:!0},c},[cu]),cx=(0,e.useCallback)(async a=>{let b=bq.current;if(b&&br.current===a){if(b.readyState===EventSource.OPEN)return;let a=bs.current;if(a?.source===b&&a.pending&&(await a.promise,bq.current===b&&b.readyState===EventSource.OPEN))return}let c=await cw(a);if("connected"!==c.status&&c.source.readyState!==EventSource.OPEN)throw bq.current===c.source&&(bq.current=null),br.current===a&&(br.current=null),bs.current?.source===c.source&&(bs.current=null),c.source.close(),new fW(c.status)},[cw]),cy=(0,e.useCallback)(async(a,b)=>{let c=a9.current;if(c?.id===a.id&&"sending"===c.status)return;let d=bx.current,e=a=>{a9.current=a,a8(a)};if(!d)return void e({id:a.id,status:"failed",error:"no session"});e({id:a.id,status:"sending"});try{await fK(d,{type:"extension_ui_response",id:a.id,...b})}catch(b){e({id:a.id,status:"failed",error:b instanceof Error?b.message:String(b)});return}e(null),a6(b=>b?.id===a.id?null:b)},[]),cz=(0,e.useCallback)(async(a,b)=>{let c=bx.current;if(c)try{await fK(c,{type:"extension_ui_input",id:a.id,data:b})}catch(a){console.error("Failed to send extension custom UI input:",a)}},[]),cB=(0,e.useCallback)(a=>{let b=a.message.trim();b&&a2({type:"add",notice:{id:a.id??fX(),message:b,type:a.type??"info"}})},[]),cC=(0,e.useCallback)(a=>{let b={role:"custom",customType:aD,content:aj(a).trim(),display:!0,timestamp:Date.now()},c=bB.current,d=bx.current;c.sessionId!==d&&(c.sessionId=d,c.outputs=[]);let e=bA.current.slice(0,bz.current.length),f=null;for(let a=e.length-1;a>=0;a--)if(!aH(e[a])){f=e[a];break}c.seq+=1,c.outputs.push({entryId:`${aG}${c.seq}`,baseEntryId:f,message:b}),ck(a=>[...a,b])},[ck]),cD=(0,e.useCallback)(b=>{if("custom"!==b.method&&"closed"in b&&b.closed){a6(a=>a?.id===b.id?null:a),a9.current?.id===b.id&&(a9.current=null,a8(null));return}switch(fG(b)&&h?.(b),b.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":a6(b);break;case"notify":cB({id:b.id,message:b.message,type:b.notifyType??"info"});break;case"setStatus":bd(a=>{let c=a.filter(a=>a.key!==b.statusKey);return void 0!==b.statusText?[...c,{key:b.statusKey,text:b.statusText}]:c});break;case"setWidget":bf(a=>{let c=a.filter(a=>a.key!==b.widgetKey);return b.widgetLines?[...c,{key:b.widgetKey,lines:b.widgetLines,placement:b.widgetPlacement??"aboveEditor"}]:c});break;case"setTitle":b.title&&(document.title=b.title);break;case"set_editor_text":a.chatInputRef?.current?.insertText(b.text);break;case"custom":bb(a=>b.closed?a?.id===b.id?null:a:b)}},[cB,h,a.chatInputRef]),cE=(0,e.useCallback)(()=>{let a=bC.current;return bC.current=!1,H(!1),aY(null),av(null),F({type:"end"}),a},[]),cF=(0,e.useCallback)(()=>{bG.current="unknown",bH.current=null;let a=fU(bz.current,bA.current);bI.current=a?{entryId:a.entryId,key:f1(a.message)}:null,bJ.current+=1},[]),cG=(0,e.useCallback)(()=>{let a=bG.current,b=bH.current;if("unknown"===a){let c=fU(bz.current,bA.current),d=c?.message,e=bI.current;null!==c&&(null===e||(null!==c.entryId&&null!==e.entryId?c.entryId!==e.entryId:f1(c.message)!==e.key))&&d?.role==="assistant"&&d.stopReason&&(a=fT(d),b??={provider:d.provider,...void 0!==d.credentialId?{credentialId:d.credentialId}:{}})}return{outcome:a,sessionId:bx.current,...b?{provider:b.provider,...void 0!==b.credentialId?{credentialId:b.credentialId}:{}}:{}}},[]),cH=(0,e.useCallback)(a=>{let b=cG();if("unknown"!==b.outcome||!a)return void g?.(b);let c=bJ.current;a.catch(()=>void 0).then(()=>{let a=bx.current===b.sessionId&&bJ.current===c;g?.(a?cG():b)})},[g,cG]),cI=(0,e.useCallback)((a,b)=>bF.current!==a&&(bF.current=a,cH(b),!0),[cH]),cJ=(0,e.useCallback)(a=>{ct(),bw.current=!0;let b=bv.current,c=async()=>{if(b===bv.current&&bx.current===a&&bw.current)try{let d=ch.current,e=await fetch(`/api/agent/${encodeURIComponent(a)}`);if(!e.ok)throw Error(`HTTP ${e.status}`);let f=await e.json();if(b!==bv.current||bx.current!==a||!bw.current)return;let g=f.state;if(bj(a=>fN(a,g?.subagents??[])),cj(a,g?.todoPhases,d),f.running&&g&&(g.isStreaming||g.isPromptRunning||g.isHandoffRunning)){bw.current=!1,bu.current=null,bD.current=!!g?.isStreaming,bE.current=!!g?.isPromptRunning,bC.current=!0,H(!0),aY(g?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(f.running&&g?.isCompacting){aN(!0),aT(fR(g)),bu.current=setTimeout(()=>void c(),600);return}if(f.running&&(g?.subagents?.length??0)>0){bu.current=setTimeout(()=>void c(),1e3);return}bw.current=!1,bu.current=null,cu()}catch{if(b!==bv.current||bx.current!==a||!bw.current)return;bu.current=setTimeout(()=>void c(),600)}};bu.current=setTimeout(()=>void c(),3e4)},[cj,ct,cu]),cK=(0,e.useCallback)(async(a=bx.current,b=b8.current)=>{if(b8.current===b)try{a&&await cm(a)}finally{if(b8.current!==b)return;let c=bE.current,d=bD.current;bE.current=!1,bD.current=!1,ca.current=null;let e=cE();c?cI(b):d&&e&&cH(),a&&cJ(a)}},[cm,cH,cI,cJ,cE]),cL=(0,e.useCallback)(async(a,b)=>{await fY(800);let c=Date.now();for(;bC.current&&Date.now()-c<2e4;){if(void 0!==b&&b8.current!==b)return;try{let c=await fetch(`/api/agent/${encodeURIComponent(a)}`);if(c.ok){let d=await c.json(),e=d.state;if(!d.running||!e||!e.isStreaming&&!e.isPromptRunning)return void await cK(a,b)}}catch{}await fY(600)}},[cK]);(0,e.useCallback)(async a=>{let b=bL.current+1;for(bL.current=b;bK.current&&bL.current===b&&bx.current===a;){await fY(1e3);try{let c=await fetch(`/api/agent/${encodeURIComponent(a)}`);if(!c.ok)continue;let d=await c.json();if(d.state?.isBashRunning)continue;if(await cm(a),bL.current!==b||bx.current!==a)return;bK.current=!1,J(!1),L(null);return}catch{}}},[cm]),(0,e.useCallback)(async a=>{if(!bC.current)return;let b=b8.current;try{let c=ch.current,d=await fetch(`/api/agent/${encodeURIComponent(a)}`);if(!d.ok)return;let e=await d.json();if(b8.current!==b)return;let f=e.state;if(aN(f?.isCompacting??!1),aT(fR(f)),bh(fP(f?.queuedMessages)),f?.contextUsage!==void 0&&ax(f.contextUsage??null),bj(a=>fN(a,f?.subagents??[])),cj(a,f?.todoPhases,c),e.running&&f&&(f.isStreaming||f.isPromptRunning||f.isCompacting||f.isHandoffRunning)||!bC.current)return;f&&(void 0!==f.systemPrompt&&az(f.systemPrompt??null),void 0!==f.extensionStatuses&&bd(f.extensionStatuses??[]),void 0!==f.extensionWidgets&&bf(f.extensionWidgets??[])),await cK(a,b)}catch{}},[cj,cK]);let cM=(0,e.useCallback)(async a=>{let b=await cm(a,!1,!0),c=b?.state;return!!b?.running&&!!c&&bx.current===a&&!bC.current&&!!(c.isStreaming||c.isPromptRunning||c.isHandoffRunning)&&(bD.current=!!c.isStreaming,bE.current=!!c.isPromptRunning,bC.current=!0,H(!0),aY(c.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),F({type:"start"}),cw(a),!c.isStreaming&&c.isPromptRunning&&cL(a),!0)},[cw,cm,cL]),cN=(0,e.useCallback)(async(a,b=b8.current)=>{let c=b9.current+1;b9.current=c;try{let d=await fetch(`/api/agent/${encodeURIComponent(a)}`);if(!d.ok)return;let e=await d.json();if(c!==b9.current||bx.current!==a||b8.current!==b)return;e.state?.contextUsage!==void 0&&ax(e.state.contextUsage??null)}catch{}},[]);bN.current=a=>{if(bx.current!==a||bC.current||bq.current||bO.current)return;let b=cM(a).then(async b=>{b||bx.current!==a||bC.current||await cm(a)}).catch(()=>{}).finally(()=>{bO.current===b&&(bO.current=null)});bO.current=b},bM.current=(0,e.useCallback)(a=>{switch(a.type){case"session_snapshot":{let b=function(a,b,c,d,e){if("session_snapshot"!==a.type||"string"!=typeof a.sessionId||a.sessionId!==b||"string"!=typeof a.entryId||""===a.entryId||a.entryId===c||!a.context||!Array.isArray(a.context.messages)||!Array.isArray(a.context.entryIds)||a.context.messages.length!==a.context.entryIds.length)return null;let f=a.context.messages,g=new Map;for(let a of f){let b=f1(a);g.set(b,(g.get(b)??0)+1)}let h=Math.min(d.length,e.length);for(let a of d.slice(0,h)){let b=f1(a),c=g.get(b)??0;c>0&&g.set(b,c-1)}let i=d.slice(h).filter(a=>{let b=f1(a),c=g.get(b)??0;return 0===c||(g.set(b,c-1),!1)});return{entryId:a.entryId,messages:[...f,...i],entryIds:[...a.context.entryIds],compactedWork:a.context.compactedWork??null}}(a,bx.current,by.current,bz.current,bA.current);if(!b)break;by.current=b.entryId;let c=aI(b.messages,b.entryIds,bB.current.sessionId===bx.current?bB.current.outputs:[]);ck(c.messages),cl(c.entryIds),D(b.compactedWork);break}case"agent_start":{let a=!bC.current;ct(),a&&cF(),bD.current=!0,bC.current=!0,H(!0),aY({kind:"waiting_model"}),F({type:"start"});break}case"agent_end":if(!bC.current)break;if(aY(null),av(null),F({type:"end"}),bx.current){cm(bx.current);let a=ch.current;fetch(`/api/agent/${encodeURIComponent(bx.current)}`).then(a=>a.json()).then(b=>{b.state?.contextUsage!==void 0&&ax(b.state.contextUsage??null),b.state?.systemPrompt!==void 0&&az(b.state.systemPrompt??null),b.state?.extensionStatuses!==void 0&&bd(b.state.extensionStatuses??[]),b.state?.extensionWidgets!==void 0&&bf(b.state.extensionWidgets??[]),b.state?.subagents!==void 0&&bj(a=>fN(a,b.state?.subagents??[])),bx.current&&cj(bx.current,b.state?.todoPhases,a),b.state?.goal!==void 0&&bT(b.state.goal??null),bh(fP(b.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":bT(a.status??null);break;case"agent_settled":{let a=bD.current;if(bD.current=!1,!a||bE.current)break;let b=bx.current,c=cE();aN(!1);let d=b?cm(b):void 0;b&&cJ(b),c&&cH(d);break}case"prompt_done":{let a=b8.current,b=bE.current;bE.current=!1,ca.current=null;let c=bF.current!==a;if(!b&&!c)break;let d=bx.current;cI(a,d?cm(d):void 0),!bD.current&&(cE(),d&&cJ(d))}break;case"prompt_error":bG.current="failed",cB({type:"error",message:a.errorMessage??"Command failed"});break;case"extension_error":bG.current="failed",cB({type:"error",message:a.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!bC.current)break;let b=a.message;if(b?.role!=="assistant")break;b&&F({type:"update",message:(0,fI.B)(b)}),aY(null);break}case"message_end":{if(!bC.current)break;let b=a.message;if(b?.role==="assistant"&&(bH.current={provider:b.provider,...void 0!==b.credentialId?{credentialId:b.credentialId}:{}},bG.current=fT(b)),b&&"user"===b.role){let a=(0,fI.B)(b),c=f0(a),d=ca.current;ca.current=null,ck(b=>{let e=b[b.length-1];return d&&e?.role==="user"&&f0(e)===d?d===c?b:[...b.slice(0,-1),a]:[...b,a]}),d||bl({type:"user-message",kind:"steering"in a&&!0===a.steering?"steer":"followUp",text:"user"!==a.role?"":"string"==typeof a.content?a.content:a.content.filter(a=>"text"===a.type).map(a=>a.text).join("\n"),images:"user"!==a.role||"string"==typeof a.content?0:a.content.filter(a=>"image"===a.type).length})}else b&&ck(a=>[...a,(0,fI.B)(b)]);let c=bx.current;c&&cN(c),F({type:"reset"}),aY({kind:"waiting_model"});break}case"thinking_level_changed":{let b=bx.current,c=a.thinkingLevel;b&&void 0!==c&&(b4.current=b,b5.current+=1,ah(a.configured??c),ak(c));break}case"todo_changed":ci(bx.current,a.phases);break;case"tool_execution_start":{let b=a.toolCallId,c=a.toolName,d=a.args;aY(a=>{let e=a?.kind==="running_tools"?[...a.tools]:[];return e.some(a=>a.id===b)||e.push({id:b,name:c,args:d}),{kind:"running_tools",tools:e}});break}case"tool_execution_end":{let b=a.toolCallId;aY(a=>{if(a?.kind!=="running_tools")return a;let c=a.tools.filter(a=>a.id!==b);return 0===c.length?{kind:"waiting_model"}:{kind:"running_tools",tools:c}});break}case"subagent_lifecycle":{let b=a.payload;if(!b?.id)break;if("started"!==b.status){let a="failed"===b.status?"failed":"aborted"===b.status?"aborted":"completed";bj(c=>{let d=c.find(a=>a.id===b.id);return fN(c,[{id:b.id,index:b.index??d?.index??0,agent:b.agent??d?.agent??b.id,agentSource:b.agentSource??d?.agentSource??"bundled",description:b.description??d?.description,status:a,task:d?.task,assignment:d?.assignment,sessionFile:b.sessionFile??d?.sessionFile,parentToolCallId:b.parentToolCallId??d?.parentToolCallId,lastUpdate:Date.now(),progress:d?.progress?{...d.progress,status:a}:void 0}])});break}let c={id:b.id,index:b.index??0,agent:b.agent??b.id,agentSource:b.agentSource??"bundled",description:b.description,status:"running",sessionFile:b.sessionFile,parentToolCallId:b.parentToolCallId,lastUpdate:Date.now()};bj(a=>fN(a,[c]));break}case"subagent_progress":{let b=a.payload;if(!b?.progress)break;let c=b.progress,d={id:c.id,index:b.index??c.index,agent:b.agent??c.agent,agentSource:b.agentSource??"bundled",description:c.description,status:c.status,task:b.task??c.task,assignment:b.assignment??c.assignment,sessionFile:b.sessionFile,parentToolCallId:b.parentToolCallId,lastUpdate:Date.now(),progress:c};bj(a=>fN(a,[d]));break}case"queue_update":bh({steering:[...a.steering??[]],followUp:[...a.followUp??[]]});break;case"auto_retry_start":av({attempt:a.attempt,maxAttempts:a.maxAttempts,errorMessage:a.errorMessage});break;case"auto_retry_end":av(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof a.reason){aU.current=a.reason;let b=a.reason;aT(a=>a?{...a,reason:b}:a)}aN(!0),aP(null),aR(null);break;case"auto_compaction_end":case"compaction_end":if(aN(!1),a.errorMessage)aP(a.errorMessage),aR(null);else if(!a.aborted){aR(f2(a.result,a.reason??"auto"));let b=bx.current;b&&(cm(b),cN(b))}break;case"extension_ui_request":cD(a)}},[cB,ci,cj,ct,cD,cm,cH,cI,cN,cF,cJ,cE,cl,ck]);let cO=(0,e.useCallback)(async(c,e,f)=>{let g=c.trim();if(!g&&!e?.length&&!f?.length)return"returned";if(bC.current||bK.current||cb.current)return"unknown";let h=cA(c,f??[]),i=!e?.length&&!f?.length&&g.startsWith("/");if(!e?.length&&!f?.length&&g.startsWith("!")){let a=g.startsWith("!!"),b=(a?g.slice(2):g.slice(1)).trim();return b?(await bU.current?.(b,a),"accepted"):"unknown"}cF();let j=b8.current+1;ct(),bE.current=!0;let k=e?.map(a=>({type:"image",source:{type:"base64",media_type:a.mimeType,data:a.data}})),l={role:"user",content:k?.length?[...h.trim()?[{type:"text",text:h}]:[],...k]:h,timestamp:Date.now()};ck(a=>[...a,l]),ca.current=f0(l),b8.current=j,bC.current=!0,H(!0),aY(i?{kind:"running_command"}:{kind:"waiting_model"}),F({type:"start"}),bX.current(!0);let m=e?.map(a=>({type:"image",data:a.data,mimeType:a.mimeType})),n=null,p=!1,q="unknown";try{if(o&&d){let a=bx.current??await b$.current,b=await cr();b&&(n=b,$&&(aJ($),a&&await fK(b,{type:"set_model",provider:$.provider,modelId:$.modelId})),await cx(b),p=!0,await fK(b,{type:"prompt",message:h,...m?.length?{images:m}:{}}),cq(1,c),q="accepted")}else b&&(n=b.id,await cx(b.id),p=!0,await fK(b.id,{type:"prompt",message:h,...m?.length?{images:m}:{}}),q="accepted");return i&&n&&cL(n,j),q}catch(h){console.error("Failed to send message:",h);let d=h instanceof fJ&&"update_draining"===h.code&&!1===h.accepted;if(!(!p||h instanceof fJ&&"prompt_rejected"===h.code&&!1===h.accepted||d)&&n)return cL(n,j),"unknown";bE.current=!1,bC.current=!1,cu();let g=ca.current;return g&&ck(a=>{let b=a[a.length-1];return b?.role==="user"&&f0(b)===g?a.slice(0,-1):a}),cB({type:"error",message:h instanceof Error?h.message:String(h)}),a.chatInputRef?.current?.restoreSubmission?.(c,f3(e),f,b?.id??n??void 0),ca.current=null,H(!1),aY(null),F({type:"end"}),"returned"}},[o,d,$,b,cr,cx,cq,cL,cB,ct,cu,a.chatInputRef,cF,ck]);bU.current=(0,e.useCallback)(async(c,d)=>{if(bC.current||bK.current)return;let e=`${d?"!!":"!"}${c}`;bK.current=!0,bX.current(!0),L({command:c,excludeFromContext:d}),J(!0);try{let a=bx.current??b?.id??await cr();if(!a)throw Error("Unable to create a session for the shell command");await fK(a,{type:"bash",command:c,excludeFromContext:d}),await cm(a),cq(1,e)}catch(b){console.error("Failed to execute shell command:",b),cB({type:"error",message:b instanceof Error?b.message:String(b)}),a.chatInputRef?.current?.insertIfEmpty(e)}finally{bK.current=!1,L(null),J(!1)}},[cB,cr,cm,a.chatInputRef,cq,b]);let cP=(0,e.useCallback)(async()=>{let a=bx.current;if(a){if(bK.current){try{await fK(a,{type:"abort_bash"})}catch(a){console.error("Failed to abort bash:",a)}return}try{await fK(a,{type:"abort"}),bG.current="aborted"}catch(a){console.error("Failed to abort:",a)}}},[]),cQ=(0,e.useCallback)(async a=>{if(bK.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let b=bx.current;if(!b)return{forked:!1,error:"No active session to fork"};aB(a??null);try{let{cancelled:c,newSessionId:d}=await fK(b,{type:"fork",...a?{entryId:a}:{}})??{};if(!c&&d)return j?.(d),{forked:!0};return{forked:!1,error:"Fork was cancelled"}}catch(a){return console.error("Fork failed:",a),{forked:!1,error:a instanceof Error?a.message:String(a)}}finally{aB(null)}},[j]),cR=(0,e.useCallback)(async a=>{if(bK.current)return;let b=bx.current;b&&(fK(b,{type:"navigate_tree",targetId:a}).catch(()=>{}),x(a),await co(b,a))},[co]);(0,e.useCallback)(async a=>{if(bK.current)return;x(a);let b=bx.current;b&&(await co(b,a),a&&fK(b,{type:"navigate_tree",targetId:a}).catch(()=>{}))},[co]);let cS=(0,e.useCallback)(async(a,b)=>{if(o){let c={provider:a,modelId:b},d=b1.current?.provider===a;b1.current=c,d||(b2.current=null,ab(null)),_(c),aJ(c);let e=bx.current??await b$.current;if(!e)return;try{await fK(e,{type:"set_model",provider:a,modelId:b})}catch(a){console.error("Failed to set model:",a)}return}let c=bx.current;if(c&&!cb.current){cb.current=!0,aE({provider:a,modelId:b}),aL(!0);try{await fK(c,{type:"set_model",provider:a,modelId:b}),cb.current=!1,await cm(c)}catch(a){console.error("Failed to set model:",a),cb.current=!1,aE(aC),cB({type:"error",message:`Failed to switch model: ${a instanceof Error?a.message:String(a)}`}),await cm(c)}finally{cb.current=!1,aL(!1)}}},[cB,aC,o,cm,_]),cT=(0,e.useCallback)(async a=>{let b={provider:a.provider,modelId:a.modelId},c=a.oauthPosition,d={type:"set_model",provider:a.provider,modelId:a.modelId,thinkingLevel:"auto",...void 0!==c?{oauthPosition:c}:{}},e=b=>`${a.alias} preset was not applied: ${b instanceof Error?b.message:String(b)}`;if(o){if(cb.current)return!1;cb.current=!0,aL(!0);let a=b1.current,f=b2.current,g=b3.current;try{b1.current=b,b2.current=c??null,b3.current="auto";let a=bx.current??await b$.current;return a&&await fK(a,d),_(b),ab(c??null),aJ(b),ah("auto"),ak(void 0),a&&await cm(a),!0}catch(c){console.error("Failed to apply Main preset:",c),b1.current=a,b2.current=f,b3.current=g,cB({type:"error",message:e(c)});let b=bx.current;return b&&await cm(b),!1}finally{cb.current=!1,aL(!1)}}let f=bx.current;if(!f||cb.current)return!1;cb.current=!0,aE(b),aL(!0);try{return await fK(f,d),await cm(f),!0}catch(a){return console.error("Failed to apply Main preset:",a),aE(aC),cB({type:"error",message:e(a)}),await cm(f),!1}finally{cb.current=!1,aL(!1)}},[cB,aC,ai,o,cm,_,ag]),cU=(0,e.useCallback)(async a=>{let b=Y.find(b=>b.role===a),c=b?.resolved;if(!c)return;if(o){let a={provider:c.provider,modelId:c.modelId},b=c.thinkingLevel;b3.current=b??null,ah(b??"auto"),ak(void 0),b1.current=a,b2.current=null,ab(null),_(a),aJ(a)}let d=bx.current??(o?await b$.current:null);if(d)try{await fK(d,{type:"set_role_model",role:a}),o||aE({provider:c.provider,modelId:c.modelId})}catch(a){console.error("Failed to set role model:",a)}},[o,Y,_]),cV=(0,e.useCallback)(async()=>{let a=bx.current;if(a&&!aM){aU.current="manual",aN(!0),aP(null),aR(null);try{let b=await fK(a,{type:"compact"});aR(f2(b,"manual")),await cm(a,!0)}catch(a){aP(a instanceof Error?a.message:String(a)),aR(null)}finally{aN(!1)}}},[aM,cm]),cW=(0,e.useCallback)(async a=>{let c=d??b?.cwd??"",e=c?`/api/models?cwd=${encodeURIComponent(c)}`:"/api/models",f=await fetch(e,a?{signal:a}:void 0);if(!f.ok)throw Error(`HTTP ${f.status}`);let g=await f.json();N(g.models),R(g.modelError??null),T(g.modelScopeWarnings??[]),V(g.thinkingLevels??{}),X(g.thinkingLevelMaps??{}),Z(g.roles??[]);let h=g.modelList??[];if(P(h),o&&!bx.current){let a=(g.defaultModel?h.find(a=>a.id===g.defaultModel?.modelId&&a.provider===g.defaultModel?.provider):void 0)??h[0];ad(a?{provider:a.provider,modelId:a.id}:null);let b=a&&g.thinkingLevelPins?.[`${a.provider}/${a.id}`];null===b3.current&&ah(b??"auto")}},[o,d,b?.cwd]),cX=(0,e.useCallback)(async a=>{if(!a.startsWith("/"))return{handled:!1};let b=a.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!b)return{handled:!1};let[,c,d=""]=b,e=d.trim(),f=await cr(),g=a=>(a.handled&&(a.error?cB({type:"error",message:a.error}):"openSessionStats"!==a.action&&cB({type:"success",message:a.message??"Command completed"})),a);try{switch(c){case"compact":{if(!f||aM)return g({handled:!0,error:"No active session to compact"});aU.current="manual",aN(!0),aP(null),aR(null);let a=await fK(f,{type:"compact",...e?{customInstructions:e}:{}});return aR(f2(a,"manual")),await cm(f,!0)&&cq(),g({handled:!0,message:"Compacted context"})}case"reload":if(!f)return g({handled:!0,error:"No active session to reload"});return await fK(f,{type:"reload"}),await Promise.all([cm(f,!1,!0),cp(f),cs(),cW()]),g({handled:!0,message:"Reloaded session resources"});case"name":if(!f)return g({handled:!0,error:"No active session to name"});if(!e)return g({handled:!0,error:"Usage: /name <name>"});return await fK(f,{type:"set_session_name",name:e}),await cm(f)&&cq(),g({handled:!0,message:`Session renamed to ${e}`});case"session":{if(!f)return g({handled:!0,error:"No active session"});let a=await fK(f,{type:"get_session_stats"});return a&&a4(a),n?.(),g({handled:!0,action:"openSessionStats"})}case"copy":{if(!f)return g({handled:!0,error:"No active session"});let a=await fK(f,{type:"get_last_assistant_text"}),b=a?.text??"";if(!b)return g({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(b),g({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!f)return g({handled:!0,error:"No active session to fork"});let a=await cQ();if(!a.forked)return g({handled:!0,error:a.error??"Fork failed"});return g({handled:!0,message:"Forked a new session"})}case"goal":{if(!f)return g({handled:!0,error:"No active session"});let a=await fK(f,{type:"goal",args:e});if(bT(a?.status??null),a?.error)return g({handled:!0,error:a.error});if(a?.message&&a.message.includes("\n")){if(cC(a.message),a.prompt)return{handled:!0,prompt:a.prompt};return{handled:!0}}if(a?.prompt)return a.message&&cB({type:"success",message:a.message}),{handled:!0,prompt:a.prompt};return g({handled:!0,message:a?.message??"Command completed"})}case"handoff":if(!f)return g({handled:!0,error:"No active session"});if(bC.current||bK.current)return g({handled:!0,error:"Cannot hand off while the session is busy"});bC.current=!0,H(!0),aY({kind:"running_command"});try{await cx(f);let a=await fK(f,{type:"handoff",...e?{customInstructions:e}:{}});if(!a||a.cancelled)return g({handled:!0,error:"Handoff cancelled"});return await cm(f,!0)&&cq(),g({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{bC.current=!1,H(!1),aY(null),bx.current===f&&cJ(f)}default:{if(!f)return g({handled:!0,error:"No active session"});let b=await fK(f,{type:"execute_slash_command",message:a});if(!b?.handled)return{handled:!1};let c=b.output?.filter(a=>a.trim()).join("\n\n")??"";if(c&&cC(c),b.prompt)return{handled:!0,prompt:b.prompt};if(c)return{handled:!0};return g({handled:!0,message:"Command completed"})}}}catch(a){return g({handled:!0,error:a instanceof Error?a.message:String(a)})}finally{"compact"===c&&aN(!1)}},[cB,cC,cx,cr,cQ,aM,cW,cm,cs,cp,cq,n,cJ]),cY=(0,e.useCallback)(async(b,c,d)=>{let e=bx.current;if(!e)return cB({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),a.chatInputRef?.current?.restoreSubmission?.(b,f3(c),d),"returned";let f=cA(b,d??[]),g=c?.map(a=>({type:"image",data:a.data,mimeType:a.mimeType})),h=++bm.current;bl({type:"submit",id:h,kind:"steer",text:f,images:g?.length??0});try{return await fK(e,{type:"steer",message:f,...g?.length?{images:g}:{}}),bl({type:"ack",id:h}),"accepted"}catch(f){return bl({type:"fail",id:h}),console.error("Failed to steer:",f),cB({type:"error",message:f instanceof Error?f.message:String(f)}),a.chatInputRef?.current?.restoreSubmission?.(b,f3(c),d,e),"returned"}},[cB,a.chatInputRef]),cZ=(0,e.useCallback)(async(b,c,d,e)=>{let f=bx.current;if(!f)return cB({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),a.chatInputRef?.current?.restoreSubmission?.(b,f3(d),e),"returned";let g=cA(b,e??[]),h=d?.map(a=>({type:"image",data:a.data,mimeType:a.mimeType})),i=++bm.current;bl({type:"submit",id:i,kind:c,text:g,images:h?.length??0});try{return await fK(f,{type:"prompt",message:g,streamingBehavior:c,...h?.length?{images:h}:{}}),bl({type:"ack",id:i}),"accepted"}catch(c){return bl({type:"fail",id:i}),console.error("Failed to queue prompt:",c),cB({type:"error",message:c instanceof Error?c.message:String(c)}),a.chatInputRef?.current?.restoreSubmission?.(b,f3(d),e,f),"returned"}},[cB,a.chatInputRef]),c$=(0,e.useCallback)(async(b,c,d)=>{let e=bx.current;if(!e)return cB({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),a.chatInputRef?.current?.restoreSubmission?.(b,f3(c),d),"returned";let f=cA(b,d??[]),g=c?.map(a=>({type:"image",data:a.data,mimeType:a.mimeType})),h=++bm.current;bl({type:"submit",id:h,kind:"followUp",text:f,images:g?.length??0});try{return await fK(e,{type:"follow_up",message:f,...g?.length?{images:g}:{}}),bl({type:"ack",id:h}),"accepted"}catch(f){return bl({type:"fail",id:h}),console.error("Failed to follow up:",f),cB({type:"error",message:f instanceof Error?f.message:String(f)}),a.chatInputRef?.current?.restoreSubmission?.(b,f3(c),d,e),"returned"}},[cB,a.chatInputRef]),c_=(0,e.useCallback)(async()=>{let a=bx.current;if(a)try{await fK(a,{type:"abort_compaction"})}catch(a){console.error("Failed to abort compaction:",a)}},[]),c0=(0,e.useCallback)(async()=>{let b=bx.current;if(b)try{var c;let d=await fK(b,{type:"clear_queue"});bl({type:"withdraw"}),bh({steering:[],followUp:[]});let e={text:(c=[...d?.steering??[],...d?.followUp??[]]).map(({text:a,images:b})=>b?.length&&"[Image]"===a?"":a).filter(a=>a.trim()).join("\n\n"),images:c.flatMap(({images:a})=>a??[]).map(({data:a,mimeType:b})=>({data:a,mimeType:b}))};a.chatInputRef?.current?.restoreSubmission?.(e.text,e.images.length?e.images:void 0,void 0,b)}catch(a){console.error("Failed to recall queued messages:",a),cB({type:"error",message:"Failed to recall queued messages"})}},[a.chatInputRef,cB]),c1=(0,e.useCallback)(async(a,b)=>{let c=bx.current;if(c)try{let d=await fK(c,{type:"remove_queued_message",message:b,queue:a});if(!d?.removed)return;bl({type:"withdraw",kind:"steering"===a?"steer":"followUp",text:b}),bh(c=>{let d=c[a].indexOf(b);return(d<0&&""===b.trim()&&(d=c[a].indexOf("[Image]")),d<0)?c:{...c,[a]:c[a].filter((a,b)=>b!==d)}})}catch(a){console.error("Failed to remove queued message:",a),cB({type:"error",message:"Failed to remove queued message"})}},[cB]),c2=(0,e.useCallback)(async(a,b=null)=>{let c="auto"===a?b:null,d=c!==al;ah(a),am(c),o&&(!bx.current||b7.current===bx.current)&&(b3.current=a,b6.current=c),ak(void 0);let e=bx.current??await b$.current;if(e)try{b7.current===e?await cr():d&&await fK(e,{type:"set_thinking_ceiling",ceiling:c}),await fK(e,{type:"set_thinking_level",level:a}),await cm(e)}catch(a){console.error("Failed to set thinking level:",a),cB({type:"error",message:"Failed to set thinking level"}),await cm(e)}},[o,cm,cB,al,cr]);at.current=cf?`${cf.provider}/${cf.modelId}`:"";let c3=a=>a?`${a}|${at.current}`:null,c4=c3(b?.id??bx.current),c5=an&&an.key===c4?an.value:null,c6=(0,e.useCallback)(async()=>{let a=bx.current??await cr(),b=c3(bx.current);if(!a||!b)return;let c=++ar.current,d=()=>ar.current===c&&c3(bx.current)===b,e=a=>{d()&&ao({key:b,value:a})};aq(!0);try{let c=an?.key===b?an.value?.enabled:void 0;if(void 0===c){let b=fQ(await fK(a,{type:"get_state"}));if(!b)throw Error("Could not read the session's Fast state");c=b.enabled}if(!d())return;let f=await fK(a,{type:"set_fast_mode",enabled:!c});e({enabled:f?.enabled===!0,active:f?.active===!0})}catch(b){if(!d())return;cB({type:"error",message:b instanceof Error?b.message:String(b)});try{e(fQ(await fK(a,{type:"get_state"}))??null)}catch{e(null)}}finally{aq(!1)}},[cr,an,cB]),c7=(0,e.useCallback)(async a=>{let b=(0,e1.xG)(a);cd(a);let c=bx.current??await b$.current;if(c)try{await fK(c,{type:"set_tools",toolNames:b})}catch(a){console.error("Failed to set tools:",a)}},[cd]),c8=(0,e.useCallback)(a=>{bP.current=a,bR(b=>!a===b?b:!a)},[]);bX.current=c8;let c9=(0,e.useCallback)((a="smooth")=>{bW.current=Date.now()+700,bY.current?.scrollIntoView({behavior:a})},[]),da=(0,e.useCallback)(()=>{bV.current=0,c8(!0),c9("smooth")},[c9,c8]),db=(0,e.useCallback)(()=>{bV.current=0,c8(!1)},[c8]);return(0,e.useCallback)(a=>{a instanceof KeyboardEvent&&(!fV.has(a.key)||a.target instanceof Element&&a.target.closest("input, textarea, [contenteditable='true']"))||(bV.current=Date.now()+1200)},[]),(0,e.useCallback)(()=>{if(!bC.current&&!bK.current)return;let a=bZ.current;if(!a)return;let b=Date.now()<=bV.current;!b&&Date.now()<bW.current||(a.scrollHeight-a.scrollTop-a.clientHeight<=72?c8(!0):b&&c8(!1))},[c8]),{data:q,loading:s,error:u,activeLeafId:w,messages:y,entryIds:A,streamState:E,agentRunning:G,modelNames:M,modelList:O,modelError:Q,modelScopeWarnings:S,modelThinkingLevels:U,modelThinkingLevelMaps:W,modelRoles:Y,newSessionModel:$,toolPreset:ae,thinkingLevel:ag,effectiveThinkingLevel:ai,thinkingCeiling:al,retryInfo:au,contextUsage:aw,systemPrompt:ay,forkingEntryId:aA,isCompacting:aM,compaction:aS,compactError:aO,compactResult:aQ,currentModel:ce,displayModel:cf,modelSwitching:aK,sessionStats:cg,runStateKnown:aV,slashCommands:aZ,slashCommandsLoading:a_,queuedMessages:bg,deliveryRows:bn,subagents:bi,todoPhases:bo&&bo.sid===bx.current?bo.phases:null,compactedWork:C,notices:a1.visible,extensionDialog:a5,extensionResponse:a7,extensionCustomUi:ba,extensionStatuses:bc,extensionWidgets:be,respondToExtensionUi:cy,sendExtensionCustomInput:cz,isAutoModelSelection:o&&null===$,agentPhase:aX,isNew:o,autoFollowPaused:bQ,resumeAutoFollow:da,pauseAutoFollow:db,goalStatus:bS,sessionIdRef:bx,eventSourceRef:bq,messagesEndRef:bY,scrollContainerRef:bZ,handleSend:cO,handleAbort:cP,handleFork:cQ,handleNavigate:cR,handleModelChange:cS,handleRoleModelChange:cU,handleMainPresetChange:cT,newSessionAccount:aa,handleCompact:cV,handleSteer:cY,handleFollowUp:c$,handlePromptWithStreamingBehavior:cZ,handleAbortCompaction:c_,handleRecallQueue:c0,handleRemoveQueuedMessage:c1,handleBuiltinSlashCommand:cX,handleToolPresetChange:c7,handleThinkingLevelChange:c2,fastMode:c5,fastModeBusy:ap,handleFastModeToggle:c6,loadTools:cp,loadSlashCommands:cs,ensureNewSession:cr,refreshLiveTranscript:cn,setActiveLeafId:x,setData:r,setMessages:z,dispatch:F,setAgentRunning:H,setForkingEntryId:aB,bashRunning:I,pendingBash:K,handleAgentEventRef:bM}}({session:a,newSessionCwd:b,initialData:f,transitioning:g,onAgentEnd:af,onAttentionNeeded:i,onSessionCreated:j,onSessionForked:k,modelsRefreshKey:l,chatInputRef:m,onBranchDataChange:n,onSystemPromptChange:o,onSessionStatsPanelOpen:q}),bL=bQ(a?.id,aY?.provider,void 0);bL?.alias;let bM=(0,e.useMemo)(()=>{if(!aY)return null;let a=bg?bv:bJ.bo.find(a=>a.alias===bL?.alias)?.oauthPosition;return bJ.bo.find(b=>b.provider===aY.provider&&(void 0===b.oauthPosition||b.oauthPosition===a))?.alias??null},[aY,bg,bv,bL]);aY?.provider,aY?.modelId,bL?.alias,bL?.seed,(0,e.useRef)(bL).current=bL;let bN=an||ao;a?.id,V.current=ak,W.current=al,X.current=bl;let bO=(0,e.useRef)(!0);bO.current=!bh,(0,e.useRef)(!1),(0,e.useRef)(null),an&&bf?.kind==="running_tools"&&bf.tools.length>0&&bf.tools.every(a=>"wait"===a.name);let bR=ah||g,{hideThinkingBlock:bS}=(b??a?.cwd,bI()),bT=(0,e.useMemo)(()=>({hideThinking:bS}),[bS]),{main:bU,process:bV}=(0,e.useMemo)(()=>(function(a,b,c={}){let d=[],e=[],f=-1,g=null,h=(a,b,c)=>{if(0===b.length)return;let f=(g&&g.anchorIdx===a||(g={anchorIdx:a,entries:[],messageCount:0,toolCallCount:0},e.push(g)),g),h=d.length-1;for(let a of b)f.entries.push({...a,afterMainIndex:h});f.messageCount+=b.length,f.toolCallCount+=c},i=aB(a),j=new Map,k=(a,b)=>{let c=j.get(a)??0;j.set(a,c+1),d.push({kind:"answer",anchorIdx:f,idx:a,runIndex:c,blocks:i.attach(b),precedingBlocks:[]})},l=()=>{let a=i.takeRemaining();a&&k(a.idx,a.blocks)};for(let e of b){if("answer"===e.kind){d.push(e);continue}if("process"===e.kind){h(e.anchorIdx,e.entries,e.toolCallCount);continue}let b=a[e.idx];if(!b)continue;if("user"===b.role){l(),f=e.idx,d.push(e);continue}if(aF(b)){d.push(void 0!==e.anchorIdx||f<0?e:{...e,anchorIdx:f});continue}if("assistant"!==b.role){"toolResult"!==b.role&&h(f,[{idx:e.idx}],0);continue}let g=ay(b,c),j=!1;for(let a of g){if("answer"===a.kind){k(e.idx,a.blocks),j=!0;continue}h(f,[{idx:e.idx,blocks:a.blocks}],az(a.blocks)),i.collect(e.idx,a.blocks)}!j&&ax(b,c)&&k(e.idx,[])}return l(),{main:d,process:e}})(ak,function(a,b={}){let c=-1;for(let b=a.length-1;b>=0;b--)if(aJ(a[b])){c=b;break}let d=[];for(let e=0;e<a.length;){if(!aJ(a[e])){d.push({kind:"message",idx:e}),e+=1;continue}let f=e,g=f+1;for(;g<a.length&&!aJ(a[g]);)g+=1;if((b.sessionBusy||b.isStreaming)&&g===a.length&&f===c||!function(a,b,c){for(let d=b;d<c;d++)if(a[d]?.role==="assistant")return!0;return!1}(a,f+1,g)){for(let a=f;a<g;a++)d.push({kind:"message",idx:a});e=g;continue}for(let c of(d.push({kind:"message",idx:f}),function(a,b,c,d){let e=[],f=[],g=0,h=[],i=0,j=0,k=aB(a.slice(b+1,c)),l=()=>{0!==f.length&&(e.push({kind:"process",anchorIdx:b,idx:f[0].idx,groupIndex:j++,entries:f,messageCount:f.length,toolCallCount:g,turnHasAnswer:!1}),f=[],g=0)},m=(a,c)=>{l(),e.push({kind:"answer",anchorIdx:b,idx:a,runIndex:i++,blocks:k.attach(c),precedingBlocks:h}),h=[]};for(let i=b+1;i<c;i++){let c=a[i];if("assistant"!==c.role){if(aF(c)){l(),e.push({kind:"message",idx:i,anchorIdx:b});continue}"toolResult"!==c.role&&f.push({idx:i});continue}let j=ay(c,d),n=j.reduce((a,b)=>"answer"===b.kind?a+1:a,0);for(let a of j){if("answer"===a.kind){m(i,a.blocks);continue}for(let b of(f.push(n>0?{idx:i,blocks:a.blocks}:{idx:i}),g+=az(a.blocks),k.collect(i,a.blocks),a.blocks))h.push(b)}0===n&&ax(c,d)&&m(i,[])}l();let n=k.takeRemaining();n&&e.push({kind:"answer",anchorIdx:b,idx:n.idx,runIndex:i++,blocks:n.blocks,precedingBlocks:[]});let o=e.some(a=>"answer"===a.kind);for(let a of e)"process"===a.kind&&(a.turnHasAnswer=o);return e}(a,f,g,{hideThinking:b.hideThinking})))d.push(c);e=g}return d}(ak,{sessionBusy:bN,isStreaming:am.isStreaming,hideThinking:bT.hideThinking}),bT),[ak,bN,am.isStreaming,bT]),bW=(0,e.useMemo)(()=>(function(a,b,c=[]){let d=new Map,e=a.map((a,b)=>({item:a,position:b})).filter(a=>"answer"===a.item.kind);if(0===e.length)return d;let f=-1,g=-1;b.forEach((a,b)=>{let c=ce(a);if(c.length>0){let a=e.filter(a=>a.item.anchorIdx===f||a.item.anchorIdx===g),h=a.filter(a=>a.item.idx<=b).pop(),i=h??a.find(a=>a.item.idx>b);if(i){let a=d.get(i.position);a?a.calls.push(...c):d.set(i.position,{calls:[...c],placement:h?"after":"before"})}}"user"===a.role&&(f=b),aJ(a)&&(g=b)});let{continuing:h}=cf(a,b,c);if(h){let a=d.get(h.position);a?a.calls.unshift(...h.calls):d.set(h.position,{calls:h.calls,placement:"before"})}return d})(bU,ak,a0?.messages),[bU,ak,a0]),bX=(0,e.useMemo)(()=>(function(a,b,c=[]){let{atCompaction:d}=cf(a,b,c);if(0===d.length)return null;let e=-1;b.forEach((a,b)=>{"custom"===a.role&&"compaction"===a.customType&&(e=b)});let f=a.findIndex(a=>a.idx>e),g=-1===f?a.length:f;return{position:g,jumpTo:g<a.length?g:a.length>0?a.length-1:null,calls:d}})(bU,ak,a0?.messages),[bU,ak,a0]),[bY,bZ]=(0,e.useState)(f4),{startIndex:b$,endIndex:b_,hasLater:b0}=f5(bU.length,bY),b1=null!==bY.end&&b0,b2=(0,e.useRef)(bU.length);b2.current=bU.length;let b3=(0,e.useRef)(null),b4=(0,e.useRef)(null);(0,e.useRef)(null);let[b5,ci]=(0,e.useState)(null),[cj,ck]=(0,e.useState)(null),[cl,cm]=(0,e.useState)(0),cn=(0,e.useRef)(null),co=(0,e.useCallback)((a,b=null)=>{bj(),cn.current={item:a,dispatchKey:b},ci(null),ck(null),bZ(b=>f6(b2.current,a,b)),cm(a=>a+1)},[bj]),cp=(0,e.useCallback)(()=>{(0,E.flushSync)(()=>bZ(f4));let a=bn.current;a&&(a.scrollTop=a.scrollHeight)},[bn]),cq=(0,e.useCallback)(()=>{b1&&cp(),bi()},[b1,cp,bi]);(0,e.useRef)(null);let[cr,cs]=(0,e.useState)(!1),[ct,cu]=(0,e.useState)(!1),[cv,cw]=(0,e.useState)(0),cx=(0,e.useMemo)(()=>ct?bU.map(a=>(function(a,b){if("answer"===a.kind)return aM(a.blocks);let c=b[a.idx];return c&&"content"in c?aM(c.content):""})(a,ak).toLowerCase()):f9,[ct,bU,ak]),cy=(0,e.useCallback)(a=>{bj(),bZ(b=>f6(b2.current,a,b))},[bj]),cz=(0,e.useCallback)(()=>cu(!1),[]),cB=(0,e.useMemo)(()=>{let a=[];return bU.forEach((b,c)=>{if("message"!==b.kind)return;let d=f8(ak[b.idx]);null!==d&&a.push({item:c,text:d})}),a},[bU,ak]),cC=`${b$}:${b_}`,cD=al.length>0?al[al.length-1]:null,[cE,cF]=(0,e.useState)(null);(0,e.useRef)(!1);let cG=(0,e.useCallback)(()=>{a?.id&&cE&&function(a,b){try{window.localStorage.setItem(`omp-web:interrupted-dismissed:${a}`,b)}catch{}}(a.id,cE),cF(null)},[a?.id,cE]),cH=null!==cE&&cE===cD&&!bN&&!b1;a$&&[a$.sessionId,a$.sessionFile??"",a$.sessionName??"",a$.userMessages,a$.assistantMessages,a$.toolCalls,a$.toolResults,a$.totalMessages,a$.tokens.input,a$.tokens.output,a$.tokens.cacheRead,a$.tokens.cacheWrite,a$.tokens.total,a$.cost??0,a$.totalActiveMs??0].join("|"),(0,e.useRef)(a$).current=a$,aR&&(aR.percent,aR.contextWindow,aR.tokens),(0,e.useRef)(aR).current=aR;let{isDragOver:cI,handleDragEnter:cJ,handleDragOver:cK,handleDragLeave:cL,handleDrop:cM}=function(a){let[b,c]=(0,e.useState)(!1),d=(0,e.useRef)(0),f=(0,e.useCallback)(a=>{Array.from(a.dataTransfer.items).some(a=>"file"===a.kind)&&(a.preventDefault(),d.current+=1,c(!0))},[]),g=(0,e.useCallback)(a=>{Array.from(a.dataTransfer.items).some(a=>"file"===a.kind)&&a.preventDefault()},[]);return{isDragOver:b,handleDragEnter:f,handleDragOver:g,handleDragLeave:(0,e.useCallback)(()=>{d.current-=1,d.current<=0&&(d.current=0,c(!1))},[]),handleDrop:(0,e.useCallback)(b=>{b.preventDefault(),d.current=0,c(!1),a(Array.from(b.dataTransfer.files))},[a])}}((0,e.useCallback)(a=>{bN||m?.current?.addAttachments(a)},[bN,m])),cN=(0,e.useMemo)(()=>{var a;return a=a0?.messages,a&&a.length>0?[...a,...ak]:ak},[a0,ak]),cO=(0,e.useMemo)(()=>{let a=new Map;for(let b of cN)"toolResult"===b.role&&a.set(b.toolCallId,b);return a},[cN]),cP=(0,e.useMemo)(()=>{let a,b,c,d;return a=new Map,b=new Map,c=new Map,d=(a,d,e)=>{let f=c.get(a);f&&d&&b.set(f,{status:d,order:e})},cN.forEach((b,e)=>{if("assistant"===b.role){for(let a of b.content??[]){if("toolCall"!==a.type||"task"!==a.toolName)continue;let b=cO.get(a.toolCallId);if(b)for(let d of ca(a,b)??[])c.set(d.agentId,d.key)}return}if("toolResult"===b.role){if("routing_verdict"===b.toolName){let c=function(a){let b=function(a){if(a.isError)return null;let b=a.details?.record;if("object"!=typeof b||null===b)try{let c=JSON.parse(b9(a.content));b=c?.ok===!0?c.record:void 0}catch{return null}return"object"==typeof b&&null!==b?b:null}(a);if(!b)return null;let c=b.verdict;if("accepted"!==c&&"rework"!==c&&"held"!==c)return null;let d=b7(b.assignmentId),e=d?.split("#")??[];if(e.length<3)return null;let f=e[e.length-1],g=e.slice(1,-1).join("#");return/^\d+$/.test(f)&&g?{key:`${g}#${f}`,record:{verdict:c,attempt:"number"==typeof b.attempt?b.attempt:null,reason:b7(b.reason)}}:null}(b);if(!c)return;let d=a.get(c.key)??[];d.push({...c.record,order:e}),a.set(c.key,d);return}if("wait"===b.toolName)for(let a of b6(b.details?.jobs)){if("task"!==a.type)continue;let b=b7(a.id);b&&d(b,b8(a.status),e)}return}if("custom"===b.role&&"async-result"===b.customType)for(let a of b9(b.content).matchAll(cb)){let b=Object.fromEntries([...a[1].matchAll(cc)].map(a=>[a[1],a[2]]));b.id&&d(b.id,b8(b.status),e)}}),{verdicts:a,runs:b,latestByAgent:c}},[cN,cO]),cQ=(0,e.useMemo)(()=>({ledger:cP,subagents:a4,toolResults:cO,onOpenPanel:u,focusedDispatch:cj}),[cP,a4,cO,u,cj]),cR=(0,e.useMemo)(()=>(function(a,b,c,d,e,f,g=null){let h=-1;a.forEach((a,b)=>{"user"===a.role&&(h=b)});let i=new Map;for(let[a,b]of c)for(let c of b.calls)i.set(c.toolCallId,a);if(g?.jumpTo!=null)for(let a of g.calls)i.set(a.toolCallId,g.jumpTo);let j=[];if(a.forEach((a,c)=>{if("assistant"!==a.role)return;let g=c>h;for(let c of a.content??[])if("toolCall"===c.type&&"task"===c.toolName)for(let a of ca(c,b.get(c.toolCallId))??[]){let b=cd(a,d,e),h=cg[b.run],k=null;"running"===h&&("live"===b.runSource||g&&f)?k="running":"awaiting"===h&&g&&!b.verdict&&(k="awaiting"),k&&j.push({maker:b,phase:k,position:i.get(c.toolCallId)??null})}}),0===j.length)return null;let k=0;for(let a of j)"running"===a.phase&&(k+=1);let l=j.filter(a=>null!==a.position);return{running:k,awaiting:j.length-k,target:l.length>0?l[l.length-1]:j[j.length-1]}})(cN,cO,bW,a4,cP,bN,bX),[cN,cO,bW,a4,cP,bN,bX]),cS=(0,e.useMemo)(()=>u?()=>u("subagents"):void 0,[u]),cT=(0,e.useMemo)(()=>{let a=new Set,b=[];for(let c=ak.length-1;c>=0;c-=1){let d=f8(ak[c]);if(!(!d||a.has(d))&&(a.add(d),b.push(d),b.length>=50))break}return b.reverse()},[ak]),cU=(0,e.useMemo)(()=>(function(a,b,c=null,d=null){return c||(function(a,b){for(let c=a.length-1;c>=0;c-=1){let d=a[c];if("assistant"!==d.role)continue;let e=d.content;if(Array.isArray(e))for(let a=e.length-1;a>=0;a-=1){let c=e[a];if("toolCall"!==c.type||!function(a){if(!a)return!1;let b=a.toLowerCase();return"todo"===b||b.endsWith(".todo")||b.endsWith("_todo")}(c.toolName))continue;let d=aS(c,b.get(c.toolCallId));if("unknown"!==d.kind)return d.phases}}return null}(a,b)??d)})(ak,cO,a5,a0?.todoPhases??null),[ak,cO,a5,a0]),cV=(0,e.useMemo)(()=>dV(am.streamingMessage).join("|"),[am.streamingMessage]),cW=(0,e.useMemo)(()=>JSON.stringify(dU(am.streamingMessage)),[am.streamingMessage]),cY=(0,e.useMemo)(()=>JSON.stringify(dX(am.streamingMessage)),[am.streamingMessage]),cZ=(0,e.useMemo)(()=>(function(a,b,c=[],d=[],e=[]){let f=function(a){let b=new Map;for(let c of a){if("toolResult"!==c.role||"write"!==c.toolName)continue;let a=c.details;if(!a||"object"!=typeof a||Array.isArray(a))continue;let d=a.message;if(!d||"object"!=typeof d||Array.isArray(d)||"send"!==d.op)continue;let e=Array.isArray(d.receipts)?d.receipts.filter(a=>"object"==typeof a&&null!==a&&!Array.isArray(a)).map(a=>({to:"string"==typeof a.to?a.to:void 0,outcome:"string"==typeof a.outcome?a.outcome:void 0})):void 0;b.set(c.toolCallId,{from:"string"==typeof d.from?d.from:void 0,receipts:e})}return b}(a),g=[],h=new Map,i=-1;for(let c=0;c<a.length;c+=1){let d=a[c];if("user"===d.role){i=c;continue}let e=dV(d),j=dX(d,f);if(0===e.length&&0===j.length||i<0)continue;let k=dU(d),l=h.get(i);l||(l={index:i,entryId:b[i],taskToolCallIds:[],characterSummons:[],peerSends:[]},h.set(i,l),g.push(l)),l.taskToolCallIds=[...l.taskToolCallIds,...e],l.characterSummons=[...l.characterSummons,...k],l.peerSends=[...l.peerSends,...j]}if(c.length>0||e.length>0){let f=-1;for(let b=a.length-1;b>=0;b-=1)if("user"===a[b].role){f=b;break}if(f>=0){let a=h.get(f);a||(a={index:f,entryId:b[f],taskToolCallIds:[],characterSummons:[],peerSends:[]},h.set(f,a),g.push(a));let i=new Set(a.taskToolCallIds);a.taskToolCallIds=[...a.taskToolCallIds,...c.filter(a=>!i.has(a))];let j=new Set(a.characterSummons.map(a=>`${a.toolCallId} ${a.name??""}`));a.characterSummons=[...a.characterSummons,...d.filter(a=>!j.has(`${a.toolCallId} ${a.name??""}`))];let k=new Set(a.peerSends.map(a=>a.toolCallId));a.peerSends=[...a.peerSends,...e.filter(a=>!k.has(a.toolCallId))]}}return g.sort((a,b)=>a.index-b.index)})(ak,al,cV.length>0?cV.split("|"):[],JSON.parse(cW),JSON.parse(cY)),[ak,al,cV,cW,cY]),c$=a?.id??bl.current??void 0,c_=(M=d$(L=(0,e.useMemo)(()=>({sessionId:c$,sessionProvider:aY?.provider,turns:cZ,messages:ak,subagents:a4}),[c$,aY?.provider,cZ,ak,a4])),O=d2(L),(0,e.useMemo)(()=>(function(a){let b=new Map;for(let c of a){let a=b.get(c.turnIndex);a?a.push(c):b.set(c.turnIndex,[c])}return b})(function(a){let b=[];for(let c of a){let a=b[b.length-1];if(a&&a.speakerId===c.speakerId&&a.turnIndex===c.turnIndex&&a.text===c.text){b[b.length-1]=c;continue}b.push(c)}return b}([...M,...O])),[M,O])),c0=bg&&0===ak.length&&!am.isStreaming&&!bN,c1=a?.cwd??b??void 0,c2=aY?au[`${aY.provider}:${aY.modelId}`]??null:null,c3=aY?aw[`${aY.provider}:${aY.modelId}`]??null:null,c4=(0,e.useRef)(null),c5=(0,e.useRef)(null);(0,e.useCallback)(()=>{c4.current?.querySelector("textarea")?.focus({preventScroll:!0})},[]);let c6=(0,e.useCallback)((...a)=>(null!==bY.end&&cp(),bo(...a)),[bo,bY.end,cp]),c7=(0,d.jsx)("div",{ref:c4,"data-chat-composer":"",style:{display:"contents"},children:(0,d.jsx)(fC,{ref:m,sessionId:a?.id??bl.current??void 0,onEnsureSession:bg&&b?bH:void 0,onLiveTranscriptPersisted:bK,onSend:c6,onAbort:bp,onSteer:an?bx:void 0,onFollowUp:an?by:void 0,onPromptWithStreamingBehavior:an?bz:void 0,isStreaming:bN,model:aY,isAutoModelSelection:be,modelNames:aq,modelList:ar,modelError:as,modelScopeWarnings:at,onModelChange:bs,onMainPresetChange:a||bg?bu:void 0,mainPresetActiveAlias:bM,modelRoles:aA,onRoleModelChange:bt,modelSwitching:aZ,onCompact:a||bg?bw:void 0,onAbortCompaction:bA,isCompacting:aU,compactError:aW,compactResult:aX,toolPreset:aC,onToolPresetChange:a||bg?bE:void 0,thinkingLevel:aE,effectiveThinkingLevel:aK,thinkingCeiling:aL,onThinkingLevelChange:a||bg?bF:void 0,fastMode:aN,fastModeBusy:aO,onFastModeToggle:a||bg?aP:void 0,availableThinkingLevels:c2,thinkingLevelMap:c3,retryInfo:aQ,deliveryRows:a3,inputHistory:cT,onRecallQueue:bB,onRemoveQueuedMessage:bC,slashCommands:a1,slashCommandsLoading:a2,onLoadSlashCommands:bG,onBuiltinCommand:bD,soundEnabled:D,onSoundToggle:F,onAudioUnlock:I,draftKey:a?.id??(b?`new:${b}`:void 0),cwd:a?.cwd??b})}),c8=am.streamingMessage,c9=(0,e.useMemo)(()=>c8?ay(c8,{isStreaming:!0}):[],[c8]),da=(0,e.useMemo)(()=>c9.filter(a=>"answer"===a.kind).flatMap(a=>a.blocks),[c9]);(0,e.useMemo)(()=>c9.filter(a=>"answer"!==a.kind).map(a=>a.blocks),[c9]);let db=c8?.role==="assistant"?c8:null;an&&(bf?.kind==="running_tools"||(db?.content??[]).some(a=>"text"===a.type&&/\S/.test(a.text)||"toolCall"===a.type)),db?.provider??aY?.provider,db?.credentialId;let[dc,dd]=(0,e.useState)(null),de=(0,e.useCallback)(a=>{dd(a)},[]);(0,e.useMemo)(()=>ap?{role:"bashExecution",command:ap.command,output:"",excludeFromContext:ap.excludeFromContext}:null,[ap]),(0,e.useMemo)(()=>{let a=[an&&!c8&&bf?function(a,b){if(a?.kind==="running_tools"){let c=a.tools.map(a=>a.name);return 0===c.length?b("chat.runningTool"):1===c.length?b("chat.runningNamedTool",{name:c[0]}):c.length<=3?b("chat.runningTools",{names:c.join(", ")}):b("chat.runningToolsMore",{names:c.slice(0,2).join(", "),count:c.length-2})}return a?.kind==="waiting_model"?b("chat.waitingModel"):a?.kind==="running_command"?b("chat.runningCommand"):null}(bf,P):null,ao&&!ap?P("chat.runningCommand"):null].filter(a=>!!a);return a.length>0?a.join(" \xb7 "):null},[an,c8,bf,ao,ap,P]);let df=bb.filter(a=>"belowEditor"!==a.placement),dg=bb.filter(a=>"belowEditor"===a.placement);return ai?(0,d.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ai}):(0,d.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":bR,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:cJ,onDragOver:cK,onDragLeave:cL,onDrop:cM,children:[bR?(0,d.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,d.jsx)("div",{className:"absolute right-3 top-3 border border-border bg-bg-panel px-3 py-2 text-sm text-text-muted shadow-sm",role:"status",children:P("chat.loadingSession")})}):null,cI&&!bN&&(0,d.jsx)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center",style:{background:"var(--accent-soft)",border:"2px dashed var(--accent-line)"},children:(0,d.jsx)("span",{className:"px-3 py-1 text-sm font-medium",style:{background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)"},children:P("chat.attachFile")})}),a9&&(0,d.jsx)(gh,{request:a9,onInput:bd}),c0&&!y?(0,d.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,d.jsxs)("div",{className:"my-auto w-full max-w-[820px] py-8",children:[(0,d.jsxs)("div",{className:"mb-3",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginLeft:16,marginRight:52,fontFamily:"var(--font-mono)"},children:[(0,d.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,d.jsx)(N,{})}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,d.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,d.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.10.0"]})]}),(0,d.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,d.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.8.0"]})]})]})]}),(0,d.jsx)(ge,{notices:a6,align:"right"})]})}):(0,d.jsxs)(d.Fragment,{children:[y&&(0,d.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:y}),(0,d.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!y,style:{display:y?"none":"flex"},children:[(0,d.jsx)("div",{style:{position:"absolute",top:12,left:0,right:0,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,d.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,d.jsx)(ds,{open:ct,onClose:cz,containerRef:bn,index:cx,renderedStart:b$,renderedEnd:b_,contentKey:ak,onReveal:cy,onProgrammaticScroll:bj,focusRequest:cv,t:P}),cr&&(0,d.jsx)("div",{className:"chat-jump-missing",role:"status",children:P("chat.jumpMissing")}),(0,d.jsx)(ge,{notices:a6,floating:!0,align:"right"})]})}),(0,d.jsx)("div",{ref:bn,className:"chat-session-scroll min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",children:(0,d.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,d.jsxs)("div",{className:"chat-column-cap",style:{width:"100%",minWidth:0,maxWidth:820,margin:"0 auto"},children:[(0,d.jsx)(gd,{widgets:df}),(0,d.jsx)(ch.Provider,{value:cQ,children:(0,d.jsx)(dP,{utterances:c_,children:(0,d.jsx)(ga,{messages:ak,entryIds:al,toolResultsMap:cO,modelNames:aq,messageCwd:c1,onOpenFile:w,sessionBusy:bN,isNew:bg,isStreaming:am.isStreaming,handleFork:bq,forkingEntryId:aT,handleNavigate:br,handleEditContent:ag,sessionId:a?.id??bl.current??void 0,main:bU,dispatchSlots:bW,compactedDispatch:bX,process:bV,startIndex:b$,endIndex:b_,sentinelRef:b3,laterSentinelRef:b4,flashItem:b5,t:P,cues:S,cueFollowRef:bO,onProcessLogChange:de})})}),!b1&&am.isStreaming&&am.streamingMessage&&da.length>0&&(0,d.jsx)(cX,{message:av(am.streamingMessage,da),sessionId:a?.id??bl.current??void 0,isStreaming:!0,modelNames:aq,cwd:c1,onOpenFile:w}),cH&&(0,d.jsx)(dy,{onDismiss:cG,t:P}),(0,d.jsx)("div",{ref:bm})]})})}),(0,d.jsx)(dt,{questions:cB,containerRef:bn,layoutKey:cC,onJump:co,label:P("chat.questionRail")}),(bN&&bh||b1)&&(0,d.jsxs)("button",{type:"button",onClick:cq,"aria-label":P("chat.jumpToBottom"),title:P("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:999,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",cursor:"pointer",boxShadow:"0 2px 10px rgba(0,0,0,0.28)"},children:[(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M12 5v14"}),(0,d.jsx)("path",{d:"m19 12-7 7-7-7"})]}),P("chat.jumpToBottom")]})]})]}),(0,d.jsxs)("div",{ref:c5,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[a7&&(0,d.jsx)("div",{style:{padding:"0 16px"},children:(0,d.jsx)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:(0,d.jsx)(gg,{request:a7,onRespond:bc,onActivity:a=>void bd(a,"activity"),delivery:a8})})}),(0,d.jsx)("div",{className:"min-h-0 overflow-y-auto",style:{padding:"0 16px"},children:(0,d.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:[(0,d.jsx)(dx,{compaction:aV,t:P}),(0,d.jsx)(gc,{goal:bk,t:P}),(0,d.jsx)(dq,{summary:cR,onJump:co,onOpenPanel:cS}),(0,d.jsx)(gd,{widgets:dg}),cU&&(0,d.jsx)(fE,{phases:cU})]})}),c7,(0,d.jsx)(fD,{statuses:ba})]})]})}function gc({goal:a,t:b}){if(!a)return null;let c=!a.enabled,e=void 0!==a.tokenBudget?b("chat.goalBudgetLeft",{left:bz(Math.max(0,a.tokenBudget-a.tokensUsed))}):b("chat.goalTokensUsed",{used:bz(a.tokensUsed)});return(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"5px 10px",border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",opacity:c?.7:1},children:[(0,d.jsx)("span",{style:{color:c?"var(--text-dim)":"var(--accent)",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",flexShrink:0},children:b("chat.goalLabel")}),(0,d.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:a.objective}),(0,d.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:c?b("chat.goalPaused"):a.status}),(0,d.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:e})]})}function gd({widgets:a}){return 0===a.length?null:(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:a.map(a=>(0,d.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,d.jsx)("div",{style:{padding:"5px 9px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:a.key}),(0,d.jsx)("pre",{style:{margin:0,padding:"8px 9px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)"},children:a.lines.join("\n")})]},a.key))})}function ge({notices:a,floating:b=!1,align:c="left"}){return 0===a.length?null:(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===c?"flex-end":"stretch",marginBottom:10*!b},children:a.map((c,e)=>{let f="error"===c.type?"var(--danger)":"warning"===c.type?"var(--warning)":"success"===c.type?"var(--success)":"var(--accent)";return(0,d.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:60,height:60,maxHeight:60,marginBottom:6*(e!==a.length-1),overflow:"hidden",borderRadius:"var(--seed-radius-r3)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:b?"var(--seed-shadow-s3)":"var(--seed-shadow-s2)",fontSize:18,lineHeight:1.45,transformOrigin:"top center",animation:c.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,d.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:f,flexShrink:0}}),(0,d.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.message})]},c.id)})})}function gf({focusKey:a,label:b,labelledBy:c,maxBlockSize:f="min(56dvh, 620px)",onCancel:g,delivery:h,children:i}){let{t:j}=(0,x.s)(),k=(0,e.useRef)(null),l=(0,e.useRef)({key:"",element:null});if(l.current.key!==a){let b="u"<typeof document?null:document.activeElement;l.current={key:a,element:b instanceof HTMLElement&&!k.current?.contains(b)?b:null}}return(0,d.jsxs)("div",{ref:k,role:"dialog","aria-modal":"false","aria-label":b,"aria-labelledby":c,className:"chat-response-surface",tabIndex:-1,onKeyDown:g?a=>{"Escape"===a.key&&(a.stopPropagation(),g())}:void 0,"aria-busy":h?.status==="sending"||void 0,style:{maxBlockSize:f},children:[h?(0,d.jsx)("p",{className:"chat-response-delivery",role:"failed"===h.status?"alert":"status","data-state":h.status,children:"sending"===h.status?j("chat.responseSending"):`${j("chat.responseFailed")}${h.error?` (${h.error})`:""}`}):null,i]})}function gg({request:a,onRespond:b,onActivity:c,delivery:f}){let{t:g}=(0,x.s)(),[h,i]=(0,e.useState)("editor"===a.method?a.prefill??"":""),[j,k]=(0,e.useState)({}),[l,m]=(0,e.useState)({}),[n,o]=(0,e.useState)(""),p=(0,e.useRef)(0),q=(0,e.useCallback)(()=>{if("ask"!==a.method||!a.timeout||!c)return;let b=Date.now();b-p.current<1e3||(p.current=b,c(a))},[a,c]),r=()=>{"confirm"===a.method?b(a,{confirmed:!0}):b(a,{value:h})};if("ask"===a.method){let c=a.questions.every(a=>(j[a.id]?.length??0)>0||(l[a.id]?.trim().length??0)>0),e=()=>{c&&b(a,{value:JSON.stringify({kind:"submit",results:a.questions.map(a=>{let b=l[a.id]?.trim();return{id:a.id,question:a.question,options:a.options.map(a=>a.label),multi:a.multi??!1,selectedOptions:(j[a.id]??[]).map(b=>a.options[b]?.label).filter(a=>void 0!==a),...b?{customInput:b}:{}}})})})};return(0,d.jsx)(gf,{focusKey:a.id,label:g("chat.agentQuestion"),onCancel:()=>b(a,{cancelled:!0}),delivery:f,children:(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,d.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:g("chat.agentQuestion")}),(0,d.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:g("chat.agentQuestionHint")}),a.timeout?(0,d.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:g("chat.askAutoSelectHint",{seconds:Math.round(a.timeout/1e3)})}):null]})}),(0,d.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,d.jsx)("div",{style:{display:"grid",gap:20},children:a.questions.map((b,c)=>{let f=j[b.id]??[];return(0,d.jsxs)("section",{style:{paddingTop:20*(0!==c),borderTop:0===c?"none":"1px solid var(--hairline)"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[b.header&&(0,d.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:b.header}),a.questions.length>1&&(0,d.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[c+1,"/",a.questions.length]})]}),(0,d.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:b.question}),(0,d.jsx)("div",{role:b.multi?"group":"radiogroup","aria-label":b.question,style:{display:"grid",gap:4},children:b.options.map((a,c)=>{let e=f.includes(c),h=b.recommended===c;return(0,d.jsxs)("button",{type:"button",role:b.multi?"checkbox":"radio","aria-checked":e,onClick:()=>{var a,d;return a=b.id,d=b.multi??!1,void(q(),k(b=>{let e=b[a]??[],f=d?e.includes(c)?e.filter(a=>a!==c):[...e,c]:[c];return{...b,[a]:f}}))},style:{display:"grid",gridTemplateColumns:"18px minmax(0, 1fr) auto",alignItems:"start",gap:9,width:"100%",minHeight:40,padding:"9px 10px",border:`1px solid ${e?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:e?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,d.jsx)("span",{"aria-hidden":"true",style:{display:"grid",placeItems:"center",width:16,height:16,marginTop:1,border:`1px solid ${e?"var(--text)":"var(--text-dim)"}`,borderRadius:b.multi?"var(--radius-control)":"50%",background:e?"var(--seed-color-fg-neutral)":"transparent",color:"var(--seed-color-fg-neutral-inverted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1},children:e&&(b.multi?(0,d.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("polyline",{points:"2 5.2 4.1 7.2 8 2.8"})}):(0,d.jsx)("span",{style:{width:5,height:5,borderRadius:"50%",background:"currentColor"}}))}),(0,d.jsxs)("span",{style:{minWidth:0},children:[(0,d.jsx)("span",{style:{display:"block",fontSize:"var(--seed-font-size-t4-static)",fontWeight:e?600:500},children:a.label}),a.description&&(0,d.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.45},children:a.description}),e&&a.preview&&(0,d.jsx)("span",{style:{display:"block",marginTop:8,padding:"7px 8px",borderLeft:"2px solid var(--border-strong)",background:"var(--bg-subtle)",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,whiteSpace:"pre-wrap"},children:a.preview})]}),h&&(0,d.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:g("chat.recommended")})]},`${b.id}:${c}`)})}),(0,d.jsx)("input",{value:l[b.id]??"",onChange:a=>{q(),m(c=>({...c,[b.id]:a.target.value}))},onKeyDown:a=>{(a.metaKey||a.ctrlKey)&&"Enter"===a.key&&e()},placeholder:g("chat.customAnswer"),"aria-label":g("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"}})]},b.id)})})}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,d.jsx)("button",{type:"button",onClick:()=>b(a,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:g("chat.cancel")}),(0,d.jsx)("button",{type:"button",onClick:()=>b(a,{value:JSON.stringify({kind:"chat"})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:g("chat.chatAboutThis")}),(0,d.jsx)("button",{type:"button",disabled:!c||f?.status==="sending",onClick:e,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:c&&f?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:c&&f?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:c&&f?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:f?.status==="sending"?g("chat.responseSending"):g("chat.submitAnswer")})]})]})})}return"plan_review"===a.method?(0,d.jsx)(gf,{focusKey:a.id,labelledBy:`plan-review-${a.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:f,children:(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,d.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,d.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:g("chat.planApproval")}),(0,d.jsx)("div",{id:`plan-review-${a.id}`,style:{marginTop:4,color:"var(--text)",fontSize:"var(--seed-font-size-t5-static)",fontWeight:600},children:a.title}),(0,d.jsx)("div",{style:{marginTop:5,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)",overflowWrap:"anywhere"},children:a.planFilePath})]}),(0,d.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,d.jsx)(bw,{children:a.planContent})}),(0,d.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,d.jsx)("textarea",{value:n,onChange:a=>o(a.target.value),placeholder:g("chat.planFeedback"),"aria-label":g("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",resize:"vertical",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5}}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,d.jsx)("button",{type:"button",onClick:()=>b(a,{value:JSON.stringify({action:"refine",feedback:n.trim()})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:g("chat.refinePlan")}),(0,d.jsx)("button",{type:"button",onClick:()=>b(a,{value:JSON.stringify({action:"approve"})}),style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:g("chat.approvePlan")})]})]})]})}):(0,d.jsx)(gf,{focusKey:a.id,labelledBy:`extension-request-${a.id}`,onCancel:()=>b(a,{cancelled:!0}),delivery:f,children:(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,d.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,d.jsx)("div",{id:`extension-request-${a.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:a.title}),(0,d.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:g("chat.extensionRequest")})]}),(0,d.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===a.method&&(0,d.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,whiteSpace:"pre-wrap"},children:a.message}),"select"===a.method&&(0,d.jsx)("div",{style:{display:"grid",gap:8},children:a.options.map(c=>(0,d.jsx)("button",{onClick:()=>b(a,{value:c}),style:{width:"100%",minHeight:40,padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t4-static)"},children:c},c))}),"input"===a.method&&(0,d.jsx)("input",{autoFocus:!0,value:h,placeholder:a.placeholder,onChange:a=>i(a.target.value),onKeyDown:a=>{"Enter"===a.key&&r()},style:{width:"100%",padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",fontSize:"var(--seed-font-size-t4-static)"}}),"editor"===a.method&&(0,d.jsx)("textarea",{autoFocus:!0,value:h,onChange:a=>i(a.target.value),onKeyDown:a=>{(a.metaKey||a.ctrlKey)&&"Enter"===a.key&&r()},style:{width:"100%",minHeight:220,padding:10,borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,d.jsx)("button",{onClick:()=>b(a,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:g("chat.cancel")}),"confirm"===a.method?(0,d.jsx)("button",{onClick:r,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:g("chat.confirm")}):"select"!==a.method?(0,d.jsx)("button",{onClick:r,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:g("chat.submit")}):null]})]})})}function gh({request:a,onInput:b}){let{t:c}=(0,x.s)(),f=(0,e.useRef)(null),g=(0,e.useRef)(!1),h=an(a.lines);return(0,d.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"var(--seed-color-bg-overlay-muted)"},children:(0,d.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:a=>{a.target.closest("button")||f.current?.focus()},style:{position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",outline:"none"},children:[(0,d.jsx)("textarea",{ref:f,"aria-label":c("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:c=>{if(g.current||c.nativeEvent.isComposing)return;let d=function(a){if(a.metaKey||a.ctrlKey&&!a.altKey&&"v"===a.key.toLowerCase())return null;if(a.ctrlKey&&!a.altKey){let b=function(a){if(1!==a.length)return null;let b=a.toUpperCase().charCodeAt(0);return b>=64&&b<=95?String.fromCharCode(31&b):"?"===a?"":null}(a.key);if(b)return b}if(a.altKey&&!a.ctrlKey){if("Backspace"===a.key)return"\x1b\x7f";let b=aq[a.key];if(b)return b;if(1===a.key.length)return`\x1b${a.key}`}return"Enter"===a.key?a.shiftKey?"\n":"\r":"Tab"===a.key?a.shiftKey?"\x1b[Z":" ":ap[a.key]??null}(c);d&&(c.preventDefault(),c.stopPropagation(),b(a,d))},onInput:c=>{if(g.current||c.nativeEvent.isComposing)return;let d=c.currentTarget.value;c.currentTarget.value="",d&&b(a,d)},onCompositionStart:()=>{g.current=!0},onCompositionEnd:c=>{g.current=!1;let d=c.currentTarget;queueMicrotask(()=>{let c=d.value;d.value="",c&&b(a,c)})},onPaste:c=>{c.preventDefault();let d=c.clipboardData.getData("text");d&&b(a,`\x1b[200~${d}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,d.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:c("chat.extensionPanel")}),(0,d.jsx)("button",{onClick:()=>b(a,"\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:c("chat.close")})]}),(0,d.jsx)("pre",{style:{margin:0,padding:14,maxHeight:"calc(min(760px, 100vh - 40px) - 48px)",overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(h.length?h:[""]).map((a,b,c)=>{var f;return(0,d.jsxs)(e.Fragment,{children:[(f=`line-${b}`,ao(a).map((a,b)=>Object.keys(a.style).length>0?(0,d.jsx)("span",{style:a.style,children:a.text},`${f}-${b}`):a.text)),b<c.length-1?"\n":null]},b)})})]})})}function gi({onPick:a,t:b}){let[c,f]=(0,e.useState)(""),[g,h]=(0,e.useState)({kind:"idle"}),i=(0,e.useRef)(null),j=c.trim(),k=a=>{let b=i.current?.querySelectorAll("button");b&&0!==b.length&&b[Math.max(0,Math.min(b.length-1,a))]?.focus()},l="done"===g.kind?g.data:null,m=l?.truncated?b(`palette.searchTruncated.${l.truncated}`,{scanned:l.scannedSessions,total:l.totalSessions}):null;return(0,d.jsxs)("div",{className:"palette-search",children:[(0,d.jsx)("input",{type:"search",value:c,onChange:a=>f(a.target.value),onKeyDown:b=>{if(!b.nativeEvent.isComposing){if("ArrowDown"===b.key)b.preventDefault(),k(0);else if("Enter"===b.key&&l&&l.hits.length>0){b.preventDefault();let c=l.hits[0],d=l.sessions[c.sessionId];d&&a(d,c,l.query)}}},placeholder:b("palette.searchPlaceholder"),"aria-label":b("palette.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),j.length>=2&&(0,d.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":b("palette.searchResults"),"aria-busy":"loading"===g.kind,children:[(0,d.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===g.kind&&b("palette.searching"),"error"===g.kind&&b("palette.searchFailed"),l&&(0===l.hits.length?b("palette.searchEmpty"):b("palette.searchHits",{count:l.hits.length})),m?` \xb7 ${m}`:"",l&&l.compactedHits>0?` \xb7 ${b("palette.searchCompacted",{count:l.compactedHits})}`:""]}),l&&l.hits.length>0&&(0,d.jsx)("div",{ref:i,className:"palette-search-list",children:l.hits.map((c,e)=>{let f=l.sessions[c.sessionId],g=c.matchStart+l.query.length;return(0,d.jsxs)("button",{type:"button",disabled:!f,onClick:()=>f&&a(f,c,l.query),onKeyDown:a=>{("ArrowDown"===a.key||"ArrowUp"===a.key)&&(a.preventDefault(),k(e+("ArrowDown"===a.key?1:-1)))},children:[(0,d.jsxs)("span",{className:"palette-search-title",children:[(0,d.jsx)("span",{children:f?f.name?.trim()||f.firstMessage?.trim()||f.id:""}),(0,d.jsx)("small",{children:"user"===c.role?b("palette.searchRoleUser"):b("palette.searchRoleAssistant")})]}),(0,d.jsxs)("span",{className:"palette-search-snippet",children:[c.snippet.slice(0,c.matchStart),(0,d.jsx)("mark",{children:c.snippet.slice(c.matchStart,g)}),c.snippet.slice(g)]})]},`${c.sessionId}:${c.entryId}`)})})]})]})}var gj=c(86475),gk=c(49216);let gl=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function gm(a){return function a(b,c){if(null==b)return"";if("string"==typeof b)return b;if("number"==typeof b||"boolean"==typeof b)return String(b);if(Array.isArray(b)){if(c.has(b))return"[Circular]";c.add(b);try{return b.map(b=>a(b,c)).filter(Boolean).join(", ")}finally{c.delete(b)}}if("object"==typeof b)try{return JSON.stringify(b)??Object.prototype.toString.call(b)}catch{return Object.prototype.toString.call(b)}return String(b)}(a,new WeakSet)}let gn=["tags","categories","keywords","tag","category"];function go({data:a}){var b;if(!a)return null;let c=Object.entries(a);if(0===c.length)return null;let e="string"==typeof(b=a.title)?b.trim()||null:"number"==typeof b||"boolean"==typeof b?String(b):null,f=gn.find(b=>Array.isArray(a[b])),g=f?a[f].map(gm).filter(Boolean):[],h=c.filter(([a])=>a!==f&&("title"!==a||!e));return(0,d.jsxs)("div",{className:"markdown-frontmatter",children:[e&&(0,d.jsx)("div",{className:"markdown-frontmatter-title",children:e}),g.length>0&&(0,d.jsx)("div",{className:"markdown-frontmatter-tags",children:g.map((a,b)=>(0,d.jsx)("span",{className:"markdown-frontmatter-tag",children:a},`${a}-${b}`))}),h.length>0&&(0,d.jsx)("dl",{className:"markdown-frontmatter-rows",children:h.map(([a,b])=>(0,d.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,d.jsx)("dt",{children:a}),(0,d.jsx)("dd",{children:function(a){let b=gm(a);return b?"string"==typeof a&&/^(https?:\/\/|mailto:)/i.test(a)?(0,d.jsx)("a",{href:a,target:"_blank",rel:"noopener noreferrer",children:b}):b:null}(b)})]},a))})]})}let gp={source:"Source",preview:"Preview",diff:"Diff"},gq={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},gr={width:48,minWidth:48,padding:"0 10px",textAlign:"right",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:11,fontStyle:"normal",fontVariantNumeric:"tabular-nums",lineHeight:"20.8px",userSelect:"none",flexShrink:0,verticalAlign:"top"};function gs(){return(0,d.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,d.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,d.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function gt({rows:a,stylesheet:b,useInlineStyles:c,wrapLines:e}){return a.map((a,f)=>{let g=a.children??[],h=g[0]?.properties?.className,i=Array.isArray(h)&&h.includes("react-syntax-highlighter-line-number"),j=i?g[0]:null,k=i?g.slice(1):g;return(0,d.jsxs)("span",{className:"file-source-line","data-line-number":f+1,style:{display:"flex",minWidth:"100%"},children:[j&&(0,gj.Ay)({node:j,stylesheet:b,useInlineStyles:c,key:`source-line-number-${f}`}),(0,d.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:e?"anywhere":"normal",whiteSpace:e?"pre-wrap":"pre"},children:k.map((a,d)=>(0,gj.Ay)({node:a,stylesheet:b,useInlineStyles:c,key:`source-token-${f}-${d}`}))})]},`source-line-${f}`)})}function gu(a,b,c,d={}){let e=aX(a),f=new URLSearchParams({type:b});for(let[a,b]of(c&&f.set("sessionId",c),Object.entries(d)))void 0!==b&&f.set(a,String(b));return`/api/files/${e}?${f.toString()}`}function gv({filePath:a,sourceSessionId:b}){let{t:c}=(0,x.s)();return(0,d.jsx)("a",{href:gu(a,"download",b),download:aY(a),title:c("i18n.downloadFile"),"aria-label":c("i18n.downloadFile"),className:"file-viewer-icon-button",children:(0,d.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,d.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,d.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,d.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})}function gw(a){return a<1024?`${a} B`:a<1048576?`${(a/1024).toFixed(1)} KB`:`${(a/1048576).toFixed(1)} MB`}function gx({patch:a}){let b,{t:c}=(0,x.s)(),e=(b=bW(a))?b.flatMap(a=>a.rows.flatMap(a=>{if("hunk"===a.type)return[];if("context"===a.left.type&&"context"===a.right.type)return[{type:"unchanged",text:a.right.text,oldLineNo:a.left.lineNo,newLineNo:a.right.lineNo}];let b=[];return"removed"===a.left.type&&b.push({type:"removed",text:a.left.text,oldLineNo:a.left.lineNo,newLineNo:null}),"added"===a.right.type&&b.push({type:"added",text:a.right.text,oldLineNo:null,newLineNo:a.right.lineNo}),b})):[];if(!e.some(a=>"unchanged"!==a.type))return(0,d.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:c("i18n.noChanges")});let f=new Set(e.flatMap((a,b)=>"unchanged"!==a.type?[b]:[])),g=new Set;for(let a of f)for(let b=Math.max(0,a-3);b<=Math.min(e.length-1,a+3);b++)g.add(b);let h=[],i=0;for(;i<e.length;)if(g.has(i)){let a=[];for(;i<e.length&&g.has(i);)a.push(e[i]),i++;h.push({hidden:!1,lines:a})}else{let a=0;for(;i<e.length&&!g.has(i);)a++,i++;h.push({hidden:!0,count:a})}return(0,d.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...gq},children:h.map((a,b)=>{if(a.hidden)return(0,d.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:["... ",a.count," unchanged lines ..."]},b);let c=a.lines.map((a,b)=>{let c="added"===a.type?"rgba(0,200,80,0.12)":"removed"===a.type?"rgba(240,60,60,0.14)":"transparent",e="added"===a.type?"+":"removed"===a.type?"-":" ",f="added"===a.type?"#4ade80":"removed"===a.type?"#f87171":"var(--text-dim)";return(0,d.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:c,borderLeft:"added"===a.type?"3px solid #4ade80":"removed"===a.type?"3px solid #f87171":"3px solid transparent"},children:[(0,d.jsx)("span",{style:gr,children:"removed"===a.type?a.oldLineNo:a.newLineNo}),(0,d.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:f,userSelect:"none",flexShrink:0,fontWeight:600},children:e}),(0,d.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:a.text||"\xa0"})]},b)});return(0,d.jsx)("div",{children:c},b)})})}function gy({filePath:a,cwd:b,sourceSessionId:c}){let{t:f}=(0,x.s)(),[g,h]=(0,e.useState)(!1),[i,j]=(0,e.useState)(0),[k,l]=(0,e.useState)(null),[m,n]=(0,e.useState)(null),[o,p]=(0,e.useState)(null);(0,e.useRef)(null);let q=aY(a).toLowerCase().split(".").pop()??"",r=gu(a,"read",c,i?{v:i}:void 0),s=null!=k?gw(k):null;return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,d.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,d.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:a,children:aZ(a,b)}),(0,d.jsx)("span",{style:{marginLeft:"auto"},children:q||"image"}),m&&(0,d.jsxs)("span",{children:[m.w," \xd7 ",m.h]}),s&&(0,d.jsx)("span",{children:s}),(0,d.jsxs)("span",{title:f(g?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:g?"#4ade80":"var(--text-dim)"},children:[(0,d.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:g?"#4ade80":"var(--border)",display:"inline-block",boxShadow:g?"0 0 4px #4ade80":"none"}}),g?"live":"static"]}),(0,d.jsx)(gv,{filePath:a,sourceSessionId:c})]}),(0,d.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:o?(0,d.jsx)("div",{style:{color:"#f87171",fontSize:13},children:o}):(0,d.jsx)("img",{src:r,alt:a,onLoad:a=>{let b=a.currentTarget;n({w:b.naturalWidth,h:b.naturalHeight})},onError:()=>p("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function gz({filePath:a,cwd:b,sourceSessionId:c}){let{t:f}=(0,x.s)(),[g,h]=(0,e.useState)(!1),[i,j]=(0,e.useState)(0),[k,l]=(0,e.useState)(null),[m,n]=(0,e.useState)(null),[o,p]=(0,e.useState)(null);(0,e.useRef)(null);let q=aY(a).toLowerCase().split(".").pop()??"",r=gu(a,"read",c,i?{v:i}:void 0);return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,d.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,d.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:a,children:aZ(a,b)}),(0,d.jsx)("span",{style:{marginLeft:"auto"},children:q||"audio"}),null!=m&&(0,d.jsx)("span",{children:function(a){if(!Number.isFinite(a))return"";let b=Math.round(a),c=Math.floor(b/60);return`${c}:${String(b%60).padStart(2,"0")}`}(m)}),null!=k&&(0,d.jsx)("span",{children:gw(k)}),(0,d.jsxs)("span",{title:f(g?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:g?"#4ade80":"var(--text-dim)"},children:[(0,d.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:g?"#4ade80":"var(--border)",display:"inline-block",boxShadow:g?"0 0 4px #4ade80":"none"}}),g?"live":"static"]}),(0,d.jsx)(gv,{filePath:a,sourceSessionId:c})]}),(0,d.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,d.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[o&&(0,d.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:o}),(0,d.jsx)("audio",{controls:!0,preload:"metadata",src:r,onLoadedMetadata:a=>n(a.currentTarget.duration),onError:()=>p("Failed to load audio"),style:{width:"100%"}},r)]})})]})}function gA({filePath:a,cwd:b,sourceSessionId:c}){let{t:f}=(0,x.s)(),[g,h]=(0,e.useState)(!1),[i,j]=(0,e.useState)(0),[k,l]=(0,e.useState)(null),[m,n]=(0,e.useState)(null);(0,e.useRef)(null);let o=at(a),p="pdf"===o,q=p?gu(a,"read",c,i?{v:i}:void 0):gu(a,"preview",c,i?{v:i}:void 0);return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,d.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,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:a,children:aZ(a,b)}),(0,d.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===o?"docx preview":"pdf"}),null!=k&&(0,d.jsx)("span",{children:gw(k)}),(0,d.jsx)(gv,{filePath:a,sourceSessionId:c}),(0,d.jsxs)("span",{title:f(g?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:g?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,d.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:g?"#4ade80":"var(--border)",display:"inline-block",boxShadow:g?"0 0 4px #4ade80":"none"}}),g?"live":"static"]})]}),(0,d.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:m?(0,d.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:m}):(0,d.jsx)("iframe",{src:q,sandbox:p?void 0:"allow-same-origin",title:f("i18n.previewFile",{file:aY(a)}),style:{width:"100%",height:"100%",border:"none",background:p?"var(--bg)":"#eef1f5"}},q)})]})}function gB({filePath:a,cwd:b,sourceSessionId:c,onOpenFile:e,onMentionLines:f,onAtMention:g,gitRefreshKey:h,initialDisplayMode:i}){let j;return au(a)?(0,d.jsx)(gy,{filePath:a,cwd:b,sourceSessionId:c}):null!==(as[at(a)]??null)?(0,d.jsx)(gz,{filePath:a,cwd:b,sourceSessionId:c}):null!==("pdf"===(j=at(a))||"docx"===j?j:null)?(0,d.jsx)(gA,{filePath:a,cwd:b,sourceSessionId:c}):(0,d.jsx)(gC,{filePath:a,cwd:b,sourceSessionId:c,onOpenFile:e,onMentionLines:f,onAtMention:g,gitRefreshKey:h,initialDisplayMode:i})}function gC({filePath:a,cwd:b,sourceSessionId:c,onOpenFile:f,onMentionLines:g,onAtMention:h,gitRefreshKey:i,initialDisplayMode:j}){let k,l,{isDark:m}=bq(),{t:n}=(0,x.s)(),[o,p]=(0,e.useState)(null),[q,r]=(0,e.useState)(null),[s,t]=(0,e.useState)(!1),[u,v]=(0,e.useState)(!0),[w,y]=(0,e.useState)(null),[z,A]=(0,e.useState)("source"),[B,C]=(0,e.useState)(!1),[D,E]=(0,e.useState)(!1);(0,e.useRef)(null);let F=(0,e.useRef)(0),G=(0,e.useRef)(null),[H,I]=(0,e.useState)(null);(0,e.useCallback)(a=>fetch(gu(a,"read",c)).then(a=>a.json()).then(a=>a.error?(y(a.error),null):(y(null),p(a),a)).catch(a=>(y(String(a)),null)),[c]),(0,e.useCallback)(async a=>{let c=++F.current;if(t(!0),!b){r(null),t(!1);return}try{let d=new URLSearchParams({cwd:b,path:a}),e=await fetch(`/api/git/diff?${d.toString()}`),f=await e.json();if(c!==F.current)return;r(e.ok&&f.supported&&"string"==typeof f.patch?f:null)}catch{c===F.current&&r(null)}finally{c===F.current&&t(!1)}},[b]);let J=q?.supported===!0&&"string"==typeof q.patch,K=J&&"deleted"===q.status;(0,e.useRef)(!1);let L=(0,e.useMemo)(()=>o?.language==="markdown"?a6(o.content):"",[o]),M=(0,e.useMemo)(()=>o?.language==="markdown"?function(a){let b=function(a){let b=gl.exec(a);if(!b)return null;let c=/^---[ \t]*(?:(?:\r\n|\n|\r)|$)/gm;c.lastIndex=b[0].length;let d=c.exec(a);return d?{yaml:a.slice(b[0].length,d.index).replace(/(?:\r\n|\n|\r)$/,""),rest:a.slice(d.index+d[0].length)}:null}(a);if(!b)return{data:null,rest:a};try{let a=(0,gk.Hh)(b.yaml);if(a&&"object"==typeof a&&!Array.isArray(a))return{data:a,rest:b.rest}}catch{}return{data:null,rest:b.rest}}(o.content):null,[o]),N=(0,e.useCallback)(c=>{g&&c&&g(aZ(a,b),c.startLine,c.endLine)},[b,a,g]);if(u||"diff"===j&&s&&!o)return(0,d.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:n("i18n.loading")});if(w&&!K)return(0,d.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:w});if(!o&&!K)return null;let O=o?.language??"text",P=o?.content??"",Q="html"===O,R="markdown"===O,S=(l=(k=aW(a).replace(/\/+$/,"")).lastIndexOf("/"))<0?"":0===l?"/":2===l&&/^[a-zA-Z]:\//.test(k)?k.slice(0,3):k.slice(0,l),T=P.split("\n"),U=K?"diff":z,V=K?["diff"]:["source",...Q||R?["preview"]:[],...J?["diff"]:[]],W=K?n("files.deleted"):`${O} \xb7 ${T.length} lines \xb7 ${gw(o.size)}`;return(0,d.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,d.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,d.jsx)("span",{className:"file-viewer-path",style:{fontFamily:"var(--font-mono)"},title:a,children:aZ(a,b)}),(0,d.jsx)("span",{className:"file-viewer-meta",title:W,children:W}),!K&&(0,d.jsx)("span",{title:D?n("i18n.liveSync"):n("i18n.notWatching"),"aria-label":D?n("i18n.liveSync"):n("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:D?"#4ade80":"var(--border)",boxShadow:D?"0 0 4px #4ade80":"none"}}),(0,d.jsxs)("div",{className:"file-viewer-controls",children:[V.length>1&&(0,d.jsx)("div",{className:"file-viewer-mode-switch","aria-label":n("i18n.fileViewMode"),children:V.map(a=>{let b=U===a;return(0,d.jsx)("button",{type:"button",onClick:()=>A(a),title:"diff"===a?n("i18n.compareHead"):void 0,"aria-pressed":b,className:"file-viewer-mode-button",style:{background:b?"var(--bg-selected)":"transparent",color:b?"var(--text)":"var(--text-muted)"},children:gp[a]},a)})}),(0,d.jsxs)("div",{className:"file-viewer-actions",children:[(h||g)&&(0,d.jsx)("button",{type:"button",onPointerDown:a=>a.preventDefault(),onClick:()=>{H&&g?N(H):h?.(aZ(a,b),!1)},title:H&&g?`${n("i18n.mentionSelectedLines")} (L${H.startLine}${H.startLine!==H.endLine?`-L${H.endLine}`:""})`:n("files.insertPath"),"aria-label":n("files.mention"),disabled:!h&&!g,className:"file-viewer-icon-button",children:(0,d.jsx)(gs,{})}),"source"===U&&(0,d.jsx)(d.Fragment,{children:(0,d.jsx)("button",{type:"button",onClick:()=>C(a=>!a),title:B?n("i18n.disableWrap"):n("i18n.enableWrap"),"aria-label":B?n("i18n.disableWrap"):n("i18n.enableWrap"),"aria-pressed":B,className:"file-viewer-icon-button",style:{background:B?"var(--bg-selected)":"transparent",color:B?"var(--text)":"var(--text-muted)"},children:(0,d.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,d.jsx)("path",{d:"M3 6h18"}),(0,d.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,d.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,d.jsx)("path",{d:"M3 18h7"})]})})})]}),!K&&(0,d.jsx)(gv,{filePath:a,sourceSessionId:c})]})]}),(0,d.jsx)("div",{ref:G,className:"file-viewer-content",style:{flex:1,overflow:"auto",background:"var(--bg)"},children:"diff"===U&&J?(0,d.jsx)(gx,{patch:q.patch}):Q&&"preview"===U?(0,d.jsx)("iframe",{srcDoc:P,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:n("i18n.htmlPreview")}):R&&"preview"===U?(0,d.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[M?.data&&(0,d.jsx)(go,{data:M.data}),(0,d.jsx)(aV.oz,{remarkPlugins:bb,rehypePlugins:bd,components:{code({className:a,children:b,...c}){let e=a?.replace("language-","").toLowerCase()??"",f=String(b);return a?.includes("language-")||f.includes("\n")?"mermaid"===e?(0,d.jsx)(bt,{code:f.replace(/\n$/,""),defaultPreview:!0}):(0,d.jsx)(bv,{code:f.replace(/\n$/,""),lang:e}):(0,d.jsx)("code",{className:a,...c,children:b})},pre:({children:a})=>(0,d.jsx)(d.Fragment,{children:a}),a({href:a,children:c,...e}){delete e.node;let g=f?aQ(a,S,b??S):null;return g&&f?(0,d.jsx)("a",{href:a,...e,onClick:a=>{a.defaultPrevented||0!==a.button||a.metaKey||a.ctrlKey||a.shiftKey||a.altKey||(a.preventDefault(),f(g))},children:c}):(0,d.jsx)("a",{href:a,...e,children:c})},img({src:a,alt:e,...f}){delete f.node;let g="string"==typeof a?aQ(a,S,b??S):null,h=g?gu(g,"read",c):a;return(0,d.jsx)("img",{src:h,alt:e??"",loading:"lazy",...f})},table:({children:a})=>(0,d.jsx)("div",{className:"markdown-table-wrap",children:(0,d.jsx)("table",{children:a})})},children:L})]}):(0,d.jsx)(aT.A,{className:B?"file-source-view is-wrapped":"file-source-view",language:"text"===O?"plaintext":O,style:m?aU.xJ:aU.vs,showLineNumbers:!0,lineNumberStyle:{...gr},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...gq,width:B?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",overflowWrap:B?"anywhere":"normal"}},renderer:a=>(0,d.jsx)(gt,{...a,wrapLines:B}),wrapLongLines:B,children:P})})]})}function gD({tabs:a,activeTabId:b,onSelectTab:c,onCloseTab:f}){let{t:g,locale:h}=(0,x.s)(),[i,j]=(0,e.useState)(null);return(0,d.jsx)("div",{className:"file-tab-list",role:"tablist","aria-label":"ko"===h?"열린 파일 탭":"Open file tabs",style:{display:"flex",alignItems:"flex-end",overflowX:"auto",flexShrink:0,height:36},children:a.map(a=>{let e=a.id===b;return(0,d.jsxs)("div",{className:`file-tab${e?" is-active":""}`,role:"presentation",onMouseDown:a=>{1===a.button&&a.preventDefault()},onAuxClick:b=>{1===b.button&&(b.preventDefault(),b.stopPropagation(),f(a.id))},style:{display:"flex",alignItems:"center",height:36,paddingRight:6,borderRight:"1px solid var(--border)",fontSize:12,whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,d.jsxs)("button",{type:"button",role:"tab","aria-selected":e,onClick:()=>c(a.id),title:a.filePath,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,height:"100%",padding:"0 0 0 12px",border:"none",background:"none",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,d.jsx)("span",{style:{flexShrink:0,opacity:e?1:.7,display:"flex",alignItems:"center"},children:b2(a.label,13)}),(0,d.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:e?500:400},children:a.label})]}),(0,d.jsx)("button",{className:"file-tab-close",onClick:b=>{b.stopPropagation(),f(a.id)},onMouseEnter:()=>j(a.id),onMouseLeave:()=>j(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:i===a.id?"var(--bg-hover)":"transparent",border:"none",color:i===a.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:g("i18n.close"),"aria-label":`${g("i18n.close")} ${a.label}`,children:(0,d.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,d.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,d.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},a.id)})})}let gE=["inherit","off","auto","minimal","low","medium","high","xhigh","max"],gF=new Set(gE);function gG(a){return void 0!==a&&gF.has(a)}function gH(a){if(!a)return[...gE];let b=new Set(a);return gE.filter(a=>"inherit"===a||"off"===a||"auto"===a||b.has(a))}function gI(a){if(!a)return"inherit";let b=a.lastIndexOf(":"),c=b>=0?a.slice(b+1):void 0;return gG(c)?c:"inherit"}function gJ(a,b){let c=a.lastIndexOf(":"),d=gG(c>=0?a.slice(c+1):void 0)?a.slice(0,c):a;return"inherit"===b?d:`${d}:${b}`}var gK=c(35836),gL=c.n(gK);function gM(a){return a.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase()}function gN({value:a,options:b,onChange:c,disabled:f=!1,placeholder:g="Select…",searchPlaceholder:h="Search options…",noResultsLabel:i="No matching options",ariaLabel:j,className:k,style:l}){let m=(0,e.useRef)(null),n=(0,e.useRef)(null),o=(0,e.useRef)(null),p=(0,e.useRef)([]),[q,r]=(0,e.useState)(!1),[s,t]=(0,e.useState)(""),[u,v]=(0,e.useState)(0),w=(0,e.useId)(),x=b.find(b=>b.value===a),y=(0,e.useMemo)(()=>{let a=gM(s.trim());return a?b.filter(b=>gM(`${b.label} ${b.value} ${b.searchText??""}`).includes(a)):b},[b,s]),{side:z,maxHeight:A}=e0(m,q,{viewportFraction:.6,cap:296,gap:5,prefer:"below",minHeight:160}),B=a=>{a.disabled||(c(a.value),r(!1))},C=a=>{if(!y.length)return;let b=u;for(let c=0;c<y.length;c+=1)if(b=(b+a+y.length)%y.length,!y[b].disabled)return void v(b)};return(0,d.jsxs)("div",{ref:m,className:`${gL().root}${k?` ${k}`:""}`,style:l,children:[(0,d.jsxs)("button",{ref:n,type:"button",className:gL().trigger,disabled:f,"aria-label":j,"aria-haspopup":"listbox","aria-expanded":q,"aria-controls":q?w:void 0,onClick:()=>r(a=>!a),onKeyDown:a=>{("ArrowDown"===a.key||"ArrowUp"===a.key)&&(a.preventDefault(),r(!0))},children:[(0,d.jsx)("span",{className:x?gL().value:gL().placeholder,children:x?.label??(a||g)}),(0,d.jsx)("svg",{className:gL().chevron,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m3 4.5 3 3 3-3"})})]}),q&&(0,d.jsxs)("div",{className:gL().popover,style:"above"===z?{bottom:"calc(100% + 5px)",maxHeight:A}:{top:"calc(100% + 5px)",maxHeight:A},"data-dismissible-layer":"searchable-select",onKeyDown:a=>{"Escape"===a.key&&(a.preventDefault(),a.stopPropagation(),r(!1),n.current?.focus())},children:[(0,d.jsxs)("div",{className:gL().searchWrap,children:[(0,d.jsxs)("svg",{className:gL().searchIcon,viewBox:"0 0 16 16","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"7",cy:"7",r:"4.25"}),(0,d.jsx)("path",{d:"m10.2 10.2 3.1 3.1"})]}),(0,d.jsx)("input",{ref:o,className:gL().search,value:s,placeholder:h,"aria-label":h,role:"combobox","aria-expanded":"true","aria-controls":w,"aria-activedescendant":y[u]?`${w}-${u}`:void 0,autoComplete:"off",spellCheck:!1,onChange:a=>{t(a.target.value),v(0)},onKeyDown:a=>{if("ArrowDown"===a.key)a.preventDefault(),C(1);else if("ArrowUp"===a.key)a.preventDefault(),C(-1);else if("Enter"===a.key){a.preventDefault();let b=y[u];b&&B(b)}else"Tab"===a.key&&r(!1)}})]}),(0,d.jsx)("div",{id:w,className:gL().options,role:"listbox","aria-label":j,style:{maxHeight:Math.max(0,A-46)},children:y.length?y.map((b,c)=>(0,d.jsxs)("button",{ref:a=>{p.current[c]=a},id:`${w}-${c}`,type:"button",role:"option","aria-selected":b.value===a,className:gL().option,"data-active":c===u,"data-selected":b.value===a,disabled:b.disabled,onMouseEnter:()=>v(c),onClick:()=>B(b),children:[(0,d.jsxs)("span",{className:gL().optionCopy,children:[(0,d.jsx)("span",{className:gL().optionLabel,children:b.label}),b.description&&(0,d.jsx)("span",{className:gL().optionDescription,children:b.description})]}),b.value===a&&(0,d.jsx)("svg",{className:gL().check,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m2.3 6.2 2.2 2.2 5.2-5.2"})})]},b.value)):(0,d.jsx)("div",{className:gL().empty,children:i})})]})]})}let gO=["global","project"],gP=["implSonnet","implOpus","implDeepSeek","makerHardUiOpus","makerHardCodeOpus","makerHardCodeSonnet"];function gQ(a){return`${a.provider}/${a.id}`}function gR({cwd:a,onRolesChanged:b}){let{t:c}=(0,x.s)(),[f,g]=(0,e.useState)([]),[h,i]=(0,e.useState)([]),[j,k]=(0,e.useState)({}),[l,m]=(0,e.useState)("global"),[n,o]=(0,e.useState)(!0),[p,q]=(0,e.useState)(null),[r,s]=(0,e.useState)(null);(0,e.useCallback)(async b=>{if(!a){g([]),i([]),k({}),o(!1);return}o(!0),q(null);try{let c=`?cwd=${encodeURIComponent(a)}`,[d,e]=await Promise.all([fetch(`/api/model-roles${c}`,b?{signal:b}:void 0),fetch(`/api/models${c}`,b?{signal:b}:void 0)]);if(!d.ok)throw Error(`HTTP ${d.status}`);let f=await d.json();if(f.error)throw Error(f.error);if(!e.ok)throw Error(`HTTP ${e.status}`);let h=await e.json();g(f.roles??[]),i(h.modelList??[]),k(h.thinkingLevels??{})}catch(a){if("AbortError"===a.name)return;q(a instanceof Error?a.message:String(a))}finally{o(!1)}},[a]);let t=(0,e.useCallback)(async(c,d)=>{if(a){s(c),q(null);try{let e=await fetch("/api/model-roles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:a,role:c,selector:d,scope:l})}),f=await e.json();if(!e.ok||f.error)throw Error(f.error??`HTTP ${e.status}`);g(f.roles??[]),b?.()}catch(a){q(a instanceof Error?a.message:String(a))}finally{s(null)}}},[a,l,b]),u=(0,e.useMemo)(()=>f.filter(a=>!a.hidden),[f]),v=u.some(a=>gP.includes(a.role)&&!a.selector);return a?(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{style:{fontSize:13,fontWeight:700,color:"var(--text)",marginBottom:4},children:c("roles.title")}),(0,d.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:c("roles.description")}),!n&&v&&(0,d.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",lineHeight:1.5,marginTop:4},children:c("roles.harnessNote")})]}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8},children:[(0,d.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:c("roles.scope")}),(0,d.jsx)("div",{style:{display:"flex",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,overflow:"hidden"},children:gO.map(a=>(0,d.jsx)("button",{onClick:()=>m(a),style:{padding:"4px 10px",border:"none",background:l===a?"var(--bg-selected)":"transparent",color:l===a?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:l===a?600:400},children:"global"===a?c("roles.scopeGlobal"):c("roles.scopeProject")},a))}),(0,d.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"global"===l?"~/.omp/agent/config.yml":".omp/config.yml"})]}),p&&(0,d.jsx)("div",{style:{fontSize:12,color:"var(--danger, #ff4757)"},children:p}),n?(0,d.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:c("i18n.loading")}):(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:u.map(a=>{let b=a.resolved?`${a.resolved.provider}/${a.resolved.modelId}`:gJ(a.selector??"","inherit"),e=gI(a.selector),f=gH(j[a.resolved?`${a.resolved.provider}:${a.resolved.modelId}`:""]),g=gP.includes(a.role);return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)"},children:[(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,rowGap:6},children:[(0,d.jsx)("span",{style:{flexShrink:0,minWidth:62,padding:"2px 6px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-subtle)",color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:a.tag??a.role.toUpperCase()}),(0,d.jsxs)("div",{style:{minWidth:0,flex:"0 0 auto",width:128},children:[(0,d.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontWeight:600},children:a.name}),g&&(0,d.jsx)("div",{style:{fontSize:10,color:"var(--text-muted)",lineHeight:1.35},children:c(`roles.harness.${a.role}`)}),(0,d.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)"},children:g&&!a.selector?c("roles.harnessUnset"):c(`roles.source.${a.source}`)})]}),(0,d.jsx)(gN,{value:b,disabled:r===a.role,ariaLabel:a.name,style:{flex:"1 1 160px",minWidth:0},onChange:b=>{if(!b)return void t(a.role,null);let c=h.find(a=>gQ(a)===b),d=c?j[`${c.provider}:${c.id}`]:void 0,e=gI(a.selector),f=gH(d).includes(e)?e:"inherit";t(a.role,gJ(b,f))},options:[{value:"",label:c("roles.unset")},...h.map(a=>({value:gQ(a),label:`${a.name} — ${a.provider}`,searchText:gQ(a)})),...b&&!h.some(a=>gQ(a)===b)?[{value:b,label:b}]:[]]}),a.warning&&(0,d.jsx)("span",{title:a.warning,style:{color:"var(--warning, #ffb347)",fontSize:12},children:"!"})]}),a.resolved&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",paddingLeft:72},children:[(0,d.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,whiteSpace:"nowrap"},children:c("roles.thinking")}),(0,d.jsx)("div",{role:"group","aria-label":`${a.name} ${c("roles.thinking")}`,style:{display:"flex",flex:"1 1 auto",minWidth:0,flexWrap:"wrap",gap:3},children:f.map(f=>{let g=e===f;return(0,d.jsx)("button",{type:"button","aria-pressed":g,disabled:r===a.role,title:"inherit"===f?c("roles.thinkingInherit"):f,onClick:()=>{g||t(a.role,gJ(b,f))},style:{padding:"3px 7px",border:`1px solid ${g?"var(--accent)":"var(--border)"}`,borderRadius:4,background:g?"var(--bg-selected)":"transparent",color:g?"var(--accent)":"var(--text-muted)",cursor:r===a.role?"not-allowed":"pointer",fontFamily:"var(--font-mono)",fontSize:10,fontWeight:g?700:500,lineHeight:1.2,opacity:r===a.role?.55:1},children:f},f)})})]})]},a.role)})})]}):(0,d.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:c("roles.needsProject")})}function gS(a){window.open(a,"_blank","noopener,noreferrer")}var gT=c(2950),gU=c(62208),gV=c(12146),gW=c(4923),gX=c(86793),gY=c(59233),gZ=c(56469),g$=c(14154),g_=c(53243),g0=c(81487),g1=c(4180),g2=c(95417),g3=c(81520),g4=c(53854),g5=c(32647),g6=c(92921),g7=c(3220),g8=c(1970),g9=c(59703),ha=c(4282),hb=c(50175),hc=c(49477),hd=c(85891),he=c(30399),hf=c(97459),hg=c(83457),hh=c(85950),hi=c(7657),hj=c(81223),hk=c(78038);let hl={anthropic:{Icon:gT.A,hasColor:!1},openai:{Icon:gU.A,hasColor:!1},"openai-codex":{Icon:gU.A,hasColor:!1},google:{Icon:gV.A,hasColor:!0},"google-vertex":{Icon:gV.A,hasColor:!0},"ant-ling":{Icon:hg.A,hasColor:!0},deepseek:{Icon:gW.A,hasColor:!0},groq:{Icon:gX.A,hasColor:!1},mistral:{Icon:gY.A,hasColor:!0},moonshotai:{Icon:gZ.A,hasColor:!1},"moonshotai-cn":{Icon:gZ.A,hasColor:!1},moonshot:{Icon:gZ.A,hasColor:!1},minimax:{Icon:g$.A,hasColor:!0},"minimax-cn":{Icon:g$.A,hasColor:!0},fireworks:{Icon:g_.A,hasColor:!0},huggingface:{Icon:g0.A,hasColor:!0},cerebras:{Icon:g1.A,hasColor:!0},openrouter:{Icon:g2.A,hasColor:!1},xai:{Icon:g3.A,hasColor:!1},"cloudflare-ai-gateway":{Icon:g4.A,hasColor:!0},"cloudflare-workers-ai":{Icon:g4.A,hasColor:!0},"vercel-ai-gateway":{Icon:g5.A,hasColor:!1},"github-copilot":{Icon:g6.A,hasColor:!1},"amazon-bedrock":{Icon:g7.A,hasColor:!0},"azure-openai-responses":{Icon:g8.A,hasColor:!0},"kimi-coding":{Icon:g9.A,hasColor:!0},nvidia:{Icon:hh.A,hasColor:!0},opencode:{Icon:hi.A,hasColor:!1},"opencode-go":{Icon:hi.A,hasColor:!1},qwen:{Icon:ha.A,hasColor:!0},xiaomi:{Icon:hj.A,hasColor:!1},"xiaomi-token-plan-ams":{Icon:hj.A,hasColor:!1},"xiaomi-token-plan-cn":{Icon:hj.A,hasColor:!1},"xiaomi-token-plan-sgp":{Icon:hj.A,hasColor:!1},zai:{Icon:hk.A,hasColor:!1},"zai-coding-cn":{Icon:hk.A,hasColor:!1},zhipu:{Icon:hb.A,hasColor:!0},cohere:{Icon:hc.A,hasColor:!0},perplexity:{Icon:hd.A,hasColor:!0},together:{Icon:he.A,hasColor:!0},grok:{Icon:hf.A,hasColor:!1}},hm=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function hn({label:a,children:b}){return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,d.jsx)("label",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:a}),b]})}let ho={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 hp({value:a,onChange:b,placeholder:c,mono:e}){return(0,d.jsx)("input",{value:a,onChange:a=>b(a.target.value),placeholder:c,style:{...ho,fontFamily:e?"var(--font-mono)":"inherit"}})}function hq({value:a,onChange:b,placeholder:c,mono:f,onKeyDown:g,autoComplete:h="off",spellCheck:i=!1,style:j}){let[k,l]=(0,e.useState)(!1),{t:m}=(0,x.s)();return(0,d.jsxs)("div",{style:{position:"relative",width:"100%",...j},children:[(0,d.jsx)("input",{type:k?"text":"password",value:a,onChange:a=>b(a.target.value),onKeyDown:g,placeholder:c,style:{...ho,paddingRight:34,fontFamily:f?"var(--font-mono)":"inherit"},autoComplete:h,spellCheck:i}),(0,d.jsx)("button",{type:"button",onClick:()=>l(a=>!a),"aria-label":m(k?"i18n.hideDetails":"i18n.showDetails"),title:m(k?"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:k?(0,d.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.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,d.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,d.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,d.jsx)("path",{d:"M1 1l22 22"})]}):(0,d.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,d.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function hr({value:a,onChange:b,placeholder:c}){return(0,d.jsx)("input",{type:"number",value:a,onChange:a=>b(a.target.value),placeholder:c,style:ho})}function hs({value:a,onChange:b,options:c,required:e}){let{t:f}=(0,x.s)();return(0,d.jsx)(gN,{value:a,onChange:b,options:[...e?[]:[{value:"",label:`— ${f("i18n.default")} / none —`}],...c.map(a=>({value:a,label:a}))]})}function ht({label:a,checked:b,onChange:c}){return(0,d.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,d.jsx)("input",{type:"checkbox",checked:b,onChange:a=>c(a.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),a]})}function hu({children:a}){return(0,d.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:a})}function hv({name:a,provider:b,onChange:c,onRename:f,onDelete:g,onAddModels:h}){let{t:i}=(0,x.s)(),[j,k]=(0,e.useState)(a),[l,m]=(0,e.useState)({phase:"idle"}),[n,o]=(0,e.useState)(""),[p,q]=(0,e.useState)([]),r=(0,e.useRef)(0),s=(0,e.useRef)(null),t=(a,d)=>c({...b,[a]:d}),u=(0,e.useCallback)(async()=>{if(!b.baseUrl?.trim()||"loading"===l.phase)return;let c=++r.current;m({phase:"loading"}),q([]);try{let d=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:a,provider:{...b,models:void 0}})}),e=await d.json();if(c!==r.current)return;if(!d.ok||e.error||!e.models)return void m({phase:"error",message:e.error??`HTTP ${d.status}`});m({phase:"success",models:e.models,endpoint:e.endpoint??b.baseUrl})}catch(a){if(c!==r.current)return;m({phase:"error",message:a instanceof Error?a.message:String(a)})}},[l.phase,a,b]),v=new Set((b.models??[]).map(a=>a.id)),w="success"===l.phase?l.models:[],y=n.trim().toLocaleLowerCase(),z=w.filter(a=>!y||a.id.toLocaleLowerCase().includes(y)||a.name?.toLocaleLowerCase().includes(y)),A=z.slice(0,300),B=A.filter(a=>!v.has(a.id)).map(a=>a.id),C=p.filter(a=>!v.has(a)).length,D=B.length>0&&B.every(a=>p.includes(a));return D||B.some(a=>p.includes(a)),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,d.jsx)(hu,{children:i("i18n.provider")}),(0,d.jsx)("button",{onClick:g,style:{padding:"3px 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11},children:i("i18n.delete")})]}),(0,d.jsxs)(hn,{label:i("i18n.providerName"),children:[(0,d.jsx)(hp,{value:j,onChange:k,placeholder:"provider-name",mono:!0}),j!==a&&j.trim()&&(0,d.jsx)("button",{onClick:()=>f(j.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:4,color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:i("i18n.rename")})]}),(0,d.jsx)(hn,{label:"Base URL",children:(0,d.jsx)(hp,{value:b.baseUrl??"",onChange:a=>t("baseUrl",a||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,d.jsxs)(hn,{label:"API Key",children:[(0,d.jsx)(hq,{value:b.apiKey??"",onChange:a=>t("apiKey",a||void 0),placeholder:"ENV_VAR_NAME, !shell-command, or literal key",mono:!0}),(0,d.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:["Prefix with ",(0,d.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:"!"})," to run a shell command, or use an env var name"]})]}),(0,d.jsx)(hn,{label:"API",children:(0,d.jsx)(hs,{value:b.api??"openai-completions",onChange:a=>t("api",a),options:hm,required:!0})}),(0,d.jsxs)(hn,{label:"Headers",children:[(0,d.jsx)(hA,{headers:b.headers,onChange:a=>t("headers",a)}),(0,d.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,d.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==l.phase&&(0,d.jsx)("button",{onClick:u,disabled:!b.baseUrl?.trim()||"loading"===l.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:b.baseUrl?.trim()&&"loading"!==l.phase?"var(--text-muted)":"var(--text-dim)",cursor:b.baseUrl?.trim()&&"loading"!==l.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===l.phase?i("models.discoveryFetching"):i("models.discoveryFetch")}),"error"===l.phase&&(0,d.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:l.message}),"success"===l.phase&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("input",{value:n,onChange:a=>o(a.target.value),placeholder:i("models.discoveryFilterPlaceholder",{count:l.models.length}),"aria-label":i("models.discoveryFilter"),style:{...ho,width:"100%",minWidth:0}}),(0,d.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,d.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:B.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,d.jsx)("input",{ref:s,type:"checkbox",checked:D,disabled:0===B.length,onChange:()=>{let a=new Set(B);q(b=>D?b.filter(b=>!a.has(b)):Array.from(new Set([...b,...B])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),i("models.discoverySelectShown")]}),0===A.length?(0,d.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:i("models.discoveryNoMatches")}):A.map((a,b)=>{let c=v.has(a.id),e=p.includes(a.id);return(0,d.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===b?"none":"1px solid var(--border)",cursor:c?"default":"pointer",opacity:c?.65:1},children:[(0,d.jsx)("input",{type:"checkbox",checked:e||c,disabled:c,onChange:()=>{var b;return b=a.id,void q(a=>a.includes(b)?a.filter(a=>a!==b):[...a,b])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,d.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,d.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:a.name??a.id}),a.name&&(0,d.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:a.id})]}),c&&(0,d.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:i("models.discoveryAdded")})]},a.id)})]}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,d.jsx)("span",{title:l.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:z.length>A.length?i("models.discoveryShowing",{shown:A.length,total:z.length}):i("models.discoveryFetched",{count:l.models.length})}),(0,d.jsx)("button",{onClick:()=>{if("success"!==l.phase)return;let a=new Set(p),b=l.models.filter(b=>a.has(b.id)&&!v.has(b.id));0!==b.length&&(h(b),q([]))},disabled:0===C,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:C?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",color:C?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:C?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:C?i("models.discoveryAddSelectedCount",{count:C}):i("models.discoveryAddSelected")})]})]})]})]})}let hw=["off","minimal","low","medium","high","xhigh","max"],hx={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function hy({value:a,onChange:b}){let c=a??{},e=(a,d)=>{let e={...c};"omit"===d?delete e[a]:e[a]=d,b(Object.keys(e).length?e:void 0)};return(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:hw.map(a=>{let b=c[a],f=a in c?null===b?"null":"string":"omit",g="string"==typeof b?b:"",h=hx[a],i={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)"},j={background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontWeight:600};return(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,d.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:h,flexShrink:0,opacity:"null"===f?.3:1}}),(0,d.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===f?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===f?"line-through":"none"},children:a})]}),(0,d.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,d.jsx)("button",{onClick:()=>e(a,"omit"),style:{...i,..."omit"===f?j:{}},children:"Default"}),(0,d.jsx)("button",{onClick:()=>e(a,null),style:{...i,borderLeft:"1px solid var(--border)",..."null"===f?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,d.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===f?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,d.jsx)("button",{onClick:()=>e(a,g||a),style:{...i,..."string"===f?j:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,d.jsx)("input",{value:g,onChange:b=>e(a,b.target.value),onFocus:()=>{"string"!==f&&e(a,g||a)},placeholder:a,maxLength:10,style:{width:"12ch",background:"string"===f?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===f?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},a)})})}let hz={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function hA({headers:a,onChange:b}){let[c,f]=(0,e.useState)(()=>Object.entries(a??{}).map(([a,b],c)=>({id:c,name:a,value:b}))),g=(0,e.useRef)(c.length),h=a=>{f(a),b(function(a){let b={};for(let c of a){let a=c.name.trim();a&&(b[a]=c.value)}return Object.keys(b).length?b:void 0}(a))},i=(a,b)=>{h(c.map(c=>c.id===a?{...c,...b}:c))},j={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,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[c.map(a=>(0,d.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,d.jsx)("input",{value:a.name,onChange:b=>i(a.id,{name:b.target.value}),placeholder:"Header-Name",style:{...ho,fontFamily:"var(--font-mono)",flex:1}}),(0,d.jsx)("input",{value:a.value,onChange:b=>i(a.id,{value:b.target.value}),placeholder:"value",style:{...ho,fontFamily:"var(--font-mono)",flex:1}}),(0,d.jsx)("button",{onClick:()=>{var b;return b=a.id,void h(c.filter(a=>a.id!==b))},style:j,children:"✕"})]},a.id)),(0,d.jsx)("button",{onClick:()=>f(a=>[...a,{id:g.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 hB({providerName:a,provider:b,model:c,onChange:f,onDelete:g}){let[h,i]=(0,e.useState)({phase:"idle"}),{t:j}=(0,x.s)(),[k,l]=(0,e.useState)({phase:"idle"}),m=(0,e.useRef)(0),n=(0,e.useRef)(null),o=(a,b)=>f({...c,[a]:b}),p=(()=>{if("idle"===h.phase)return null;if("testing"===h.phase)return j("i18n.testingModel");let a=[void 0!==h.latencyMs?`${h.latencyMs}ms`:null,void 0!==h.status?`HTTP ${h.status}`:null].filter(Boolean);return"success"===h.phase?[j("i18n.connected"),...a,h.responseText||null].filter(Boolean).join(" \xb7 "):[j("i18n.failed"),...a,h.message].filter(Boolean).join(" \xb7 ")})(),q=(0,e.useCallback)(async()=>{if(c.id.trim()&&"testing"!==h.phase){i({phase:"testing"});try{let d=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:a,provider:b,model:c})}),e=await d.json();if(!d.ok||!e.ok)return void i({phase:"error",message:e.error??`HTTP ${d.status}`,latencyMs:e.latencyMs,status:e.status});i({phase:"success",latencyMs:e.latencyMs,status:e.status,responseText:e.responseText})}catch(a){i({phase:"error",message:a instanceof Error?a.message:String(a)})}}},[c,b,a,h.phase]),r=(0,e.useCallback)(async()=>{let d=c.id.trim();if(!d||"loading"===k.phase)return;let e=++m.current;l({phase:"loading"});try{let g=new URLSearchParams({q:d,provider:a,limit:"50"});b.baseUrl?.trim()&&g.set("baseUrl",b.baseUrl.trim());let h=await fetch(`/api/models-config/catalog?${g}`),i=await h.json();if(e!==m.current)return;if(!h.ok||i.error||!i.recommendation)return void l({phase:"error",message:i.error??`HTTP ${h.status}`});let j=function(a,b){let c={...a},d=0;if(!a.name?.trim()&&b.name&&(c.name=b.name,d+=1),void 0===a.reasoning&&!0===b.reasoning&&(c.reasoning=!0,d+=1),!a.input?.length&&b.input?.length&&(c.input=[...b.input],d+=1),void 0===a.contextWindow&&void 0!==b.contextWindow&&(c.contextWindow=b.contextWindow,d+=1),void 0===a.maxTokens&&void 0!==b.maxTokens&&(c.maxTokens=b.maxTokens,d+=1),b.cost){let e={...a.cost??{}},f=!1;for(let a of["input","output","cacheRead","cacheWrite"])void 0===e[a]&&void 0!==b.cost[a]&&(e[a]=b.cost[a],f=!0,d+=1);f&&(c.cost=e)}return{model:c,appliedCount:d}}(c,i.recommendation.preset);j.appliedCount>0&&(n.current=c,f(j.model)),l({phase:"success",recommendation:i.recommendation,appliedCount:j.appliedCount})}catch(a){if(e!==m.current)return;l({phase:"error",message:a instanceof Error?a.message:String(a)})}},[k.phase,c,f,b.baseUrl,a]),s=(()=>{if("success"!==k.phase)return null;let{recommendation:b,appliedCount:c}=k,d=c>0?j("models.catalogFilled",{count:c}):j("models.catalogNoEmptyFields");if("unreliable"===b.price.status){let a="no-exact-match"===b.price.reason?j("models.catalogNoExactMatch"):j("models.catalogPriceUnreliable");return`${d} \xb7 ${a}`}let e="provider"===b.price.method?j("models.catalogPriceProvider",{provider:b.price.providerName??b.price.providerId??a}):"base-url"===b.price.method?j("models.catalogPriceBaseUrl",{provider:b.price.providerName??b.price.providerId??a}):j("models.catalogPriceConsensus",{support:b.price.support,total:b.price.total});return`${d} \xb7 ${e}`})(),t="error"===k.phase?k.message:s,u="error"===k.phase?"#ef4444":"success"===k.phase&&"unreliable"===k.recommendation.price.status?"#d97706":"var(--text-dim)";return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,d.jsx)(hu,{children:j("i18n.model")}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[p&&(0,d.jsx)("span",{title:p,style:{maxWidth:260,height:24,padding:"0 8px",border:`1px solid ${"error"===h.phase?"#fecaca":"success"===h.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===h.phase?"#fee2e2":"success"===h.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:p}),(0,d.jsxs)("button",{onClick:q,disabled:!c.id.trim()||"testing"===h.phase,title:j("i18n.testConnection"),style:{height:24,padding:"0 8px",background:"success"===h.phase?"#16a34a":"none",border:`1px solid ${"success"===h.phase?"#16a34a":"var(--border)"}`,borderRadius:4,color:"success"===h.phase?"#fff":c.id.trim()&&"testing"!==h.phase?"var(--text-muted)":"var(--text-dim)",cursor:c.id.trim()&&"testing"!==h.phase?"pointer":"not-allowed",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",gap:5},children:["success"===h.phase&&(0,d.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===h.phase?j("i18n.checking"):"success"===h.phase?j("common.ok"):j("i18n.test")]}),(0,d.jsx)("button",{onClick:g,style:{height:24,padding:"0 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,boxSizing:"border-box"},children:j("i18n.remove")})]})]}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,d.jsx)(hn,{label:"ID *",children:(0,d.jsx)(hp,{value:c.id,onChange:a=>o("id",a),placeholder:"model-id",mono:!0})}),(0,d.jsx)(hn,{label:"Name",children:(0,d.jsx)(hp,{value:c.name??"",onChange:a=>o("name",a||void 0),placeholder:"Display name"})})]}),(0,d.jsxs)("div",{style:{padding:"10px 0",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,d.jsx)("button",{onClick:()=>void r(),disabled:!c.id.trim()||"loading"===k.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:c.id.trim()&&"loading"!==k.phase?"var(--text-muted)":"var(--text-dim)",cursor:c.id.trim()&&"loading"!==k.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===k.phase?j("models.catalogFilling"):j("models.catalogFill")}),(0,d.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:j("models.catalogSource")})]}),(0,d.jsxs)("div",{"aria-live":"polite",style:{marginTop:6,height:20,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:u,fontSize:10},children:[(0,d.jsx)("span",{title:t??void 0,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t}),n.current&&(0,d.jsx)("button",{onClick:()=>{let a=n.current;a&&(n.current=null,f(a),l({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:j("models.catalogUndo")})]})]}),(0,d.jsx)(hn,{label:"API override",children:(0,d.jsx)(hs,{value:c.api??"",onChange:a=>o("api",a||void 0),options:hm})}),(0,d.jsxs)(hn,{label:"Headers",children:[(0,d.jsx)(hA,{headers:c.headers,onChange:a=>o("headers",a)}),(0,d.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to this model's requests; overrides the provider headers for this model."})]}),(0,d.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,d.jsx)(ht,{label:"Reasoning / thinking",checked:c.reasoning??!1,onChange:a=>o("reasoning",a||void 0)}),(0,d.jsx)(ht,{label:"Image input",checked:c.input?.includes("image")??!1,onChange:a=>o("input",a?["text","image"]:void 0)})]}),c.reasoning&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(ht,{label:"DeepSeek thinking compat",checked:c.compat?.thinkingFormat==="deepseek",onChange:a=>f(function(a,b){if(b)return{...a,compat:{...a.compat??{},...hz}};if(!a.compat)return a;let c={...a.compat};return delete c.thinkingFormat,delete c.requiresReasoningContentOnAssistantMessages,{...a,compat:Object.keys(c).length?c:void 0}}(c,a))}),(0,d.jsx)(ht,{label:"Use 'developer' role for the system prompt (disable if server rejects it)",checked:!1!==({...b.compat??{},...c.compat??{}}).supportsDeveloperRole,onChange:a=>f({...c,compat:{...c.compat??{},supportsDeveloperRole:a}})}),(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,d.jsx)(hu,{children:"Thinking level map"}),c.thinkingLevelMap&&(0,d.jsx)("button",{onClick:()=>o("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 7px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-dim)",cursor:"pointer"},children:"clear all"})]}),(0,d.jsx)(hy,{value:c.thinkingLevelMap,onChange:a=>o("thinkingLevelMap",a)})]})]}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,d.jsx)(hn,{label:"Context window (tokens)",children:(0,d.jsx)(hr,{value:void 0!==c.contextWindow?String(c.contextWindow):"",onChange:a=>o("contextWindow",a?parseInt(a):void 0),placeholder:"128000"})}),(0,d.jsx)(hn,{label:"Max output tokens",children:(0,d.jsx)(hr,{value:void 0!==c.maxTokens?String(c.maxTokens):"",onChange:a=>o("maxTokens",a?parseInt(a):void 0),placeholder:"16384"})})]}),(0,d.jsxs)("div",{children:[(0,d.jsx)(hu,{children:"Cost (per million tokens)"}),(0,d.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8},children:["input","output","cacheRead","cacheWrite"].map(a=>(0,d.jsx)(hn,{label:a,children:(0,d.jsx)(hr,{value:c.cost?.[a]!==void 0?String(c.cost[a]):"",onChange:b=>{let d;return d=parseFloat(b),void f({...c,cost:{...c.cost??{},[a]:isNaN(d)?void 0:d}})},placeholder:"0"})},a))})]})]})}let hC={checking:"relogin.checking",recovered:"relogin.recovered","still-failing":"relogin.stillFailing",unknown:"relogin.unknown"};function hD({provider:a,onRefresh:b,relogin:c}){let f=c?.onLoginSucceeded,[g,h]=(0,e.useState)({phase:"idle"}),{t:i}=(0,x.s)(),[j,k]=(0,e.useState)(""),l=(0,e.useRef)(null),m=(0,e.useRef)(!1),n=(0,e.useRef)(null),o=(0,e.useRef)(null),p=(0,e.useCallback)(()=>{l.current?.close(),m.current||(m.current=!0,k(""),h({phase:"success"}),b(),f?.())},[b,f]),q=(0,e.useCallback)(()=>{l.current?.close(),m.current=!1,h({phase:"connecting"}),k("");let b=new EventSource(`/api/auth/login/${encodeURIComponent(a.id)}`);l.current=b,b.onmessage=a=>{let c=JSON.parse(a.data);"auth"===c.type?(h({phase:"auth",url:c.url,instructions:c.instructions??null,token:c.token}),gS(c.url)):"device_code"===c.type?(h({phase:"device_code",userCode:c.userCode,verificationUri:c.verificationUri,intervalSeconds:c.intervalSeconds??null,expiresInSeconds:c.expiresInSeconds??null}),gS(c.verificationUri)):"prompt_request"===c.type?h({phase:"prompt",message:c.message,placeholder:c.placeholder??null,token:c.token}):"select_request"===c.type?h({phase:"select",message:c.message,options:c.options??[],token:c.token}):"progress"===c.type?h({phase:"progress",message:c.message}):"success"===c.type?p():"error"===c.type?(b.close(),h({phase:"error",message:c.message})):"cancelled"===c.type&&(b.close(),h({phase:"idle"}))},b.onerror=()=>{b.close(),h(a=>"success"===a.phase||"auth"===a.phase||"prompt"===a.phase||"select"===a.phase?a:{phase:"error",message:"Connection lost"})}},[a.id,p]),r=(0,e.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(a.id)}`,{method:"POST"}),h({phase:"idle"}),b()},[a.id,b]),s=(0,e.useCallback)(async(b,c,d)=>{h({phase:"progress",message:d});try{let d=await fetch(`/api/auth/login/${encodeURIComponent(a.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:b,code:c})}),e=await d.json().catch(()=>({}));if(!d.ok)return void h({phase:"error",message:e.error??`Server error ${d.status}`});if(k(""),"success"===e.state)return void p();l.current?.readyState===EventSource.CLOSED&&h({phase:"error",message:"Connection lost. Start the login again."})}catch(a){h({phase:"error",message:a instanceof Error?a.message:"Network error"})}},[a.id,p]),t=(0,e.useCallback)(async(a,b)=>{b.trim()&&await s(a,b.trim(),"Verifying…")},[s]),u=(0,e.useCallback)(async(a,b)=>{await s(a,b,"Continuing…")},[s]),v="connecting"===g.phase||"progress"===g.phase||"auth"===g.phase||"device_code"===g.phase||"prompt"===g.phase||"select"===g.phase;return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,d.jsx)(hu,{children:i("i18n.subscription")}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,d.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,d.jsx)("span",{style:{fontSize:11,color:a.loggedIn?"#4ade80":"var(--text-dim)"},children:i(a.loggedIn?"i18n.connected":"i18n.notConnected")})]})]}),c&&(0,d.jsxs)("div",{role:"note","aria-label":i("relogin.title"),style:{display:"flex",alignItems:"flex-start",gap:10,padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg-panel)"},children:[(0,d.jsx)(bU,{seed:c.target.seed,size:32,provider:c.target.provider}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0},children:[(0,d.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:i("relogin.title")}),(0,d.jsxs)("span",{style:{fontSize:13,fontWeight:600,color:"var(--text)",overflowWrap:"anywhere"},children:[c.target.alias,c.target.masked&&(0,d.jsx)("span",{style:{marginLeft:6,fontSize:11,fontWeight:400,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:c.target.masked})]}),c.target.reason&&(0,d.jsx)("span",{style:{fontSize:12,color:"var(--seed-color-fg-critical-contrast)",lineHeight:1.5,overflowWrap:"anywhere"},children:c.target.reason})]})]}),(0,d.jsxs)("div",{style:{minHeight:48},children:["idle"===g.phase&&(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:c?i("relogin.guide",{action:i(a.loggedIn?"i18n.relogin":"i18n.login")}):a.loggedIn?"Already connected. You can re-login or disconnect.":`Connect your ${a.name} account.`}),"connecting"===g.phase&&(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:i("i18n.openingBrowser")}),"select"===g.phase&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:g.message}),(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:g.options.map(a=>(0,d.jsx)("button",{onClick:()=>u(g.token,a.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:a.label},a.id))})]}),("auth"===g.phase||"prompt"===g.phase)&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"auth"===g.phase?"Complete sign-in in the browser. If the last page does not load (for example on a phone), copy its address from the address bar and paste it below.":g.message}),"auth"===g.phase&&(0,d.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:["If the browser window did not open,"," ",(0,d.jsx)("a",{href:g.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:"click here to open the login page"}),"."]}),(0,d.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,d.jsx)("input",{ref:n,value:j,onChange:a=>k(a.target.value),onKeyDown:a=>{"Enter"===a.key&&t(g.token,j)},placeholder:"auth"===g.phase?"Paste the redirect URL or code":g.placeholder??"Enter value…",style:{flex:1,padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",fontFamily:"var(--font-mono)",boxSizing:"border-box"}}),(0,d.jsx)("button",{onClick:()=>t(g.token,j),disabled:!j.trim(),style:{padding:"6px 12px",background:j.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:j.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:j.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,flexShrink:0},children:i("i18n.submit")})]})]}),"device_code"===g.phase&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,d.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:g.userCode}),(0,d.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,d.jsx)("a",{href:g.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:g.verificationUri}),g.expiresInSeconds?` Expires in ${Math.ceil(g.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===g.phase&&(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:g.message}),"success"===g.phase&&(c?(0,d.jsxs)("div",{role:"status",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:i("relogin.done")}),c.outcome&&(0,d.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"recovered"===c.outcome?"var(--seed-color-fg-positive-contrast)":"still-failing"===c.outcome?"var(--seed-color-fg-critical-contrast)":"var(--text-muted)"},children:i(hC[c.outcome],{account:c.target.alias})})]}):(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:i("i18n.connectedSuccessfully")})),"error"===g.phase&&(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:g.message})]}),(0,d.jsx)("div",{style:{display:"flex",gap:8},children:v?(0,d.jsx)("button",{onClick:()=>{l.current?.close(),h({phase:"idle"})},style:{padding:"5px 12px",background:"none",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:i("i18n.cancel")}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("button",{ref:o,onClick:q,style:{padding:"5px 14px",background:"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:5,color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontSize:12,fontWeight:600},children:i(a.loggedIn?"i18n.relogin":"i18n.login")}),a.loggedIn&&!c&&(0,d.jsx)("button",{onClick:r,style:{padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:"pointer",fontSize:12},children:i("i18n.disconnect")})]})})]})}function hE({provider:a,onRefresh:b}){let[c,f]=(0,e.useState)(""),[g,h]=(0,e.useState)(!1),[i,j]=(0,e.useState)(!1),[k,l]=(0,e.useState)(null),[m,n]=(0,e.useState)(!1),{t:o}=(0,x.s)(),p=(0,e.useCallback)(async()=>{if(c.trim()){h(!0),l(null),n(!1);try{let d=await fetch(`/api/auth/api-key/${encodeURIComponent(a.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:c.trim()})}),e=await d.json();!d.ok||e.error?l(e.error??`HTTP ${d.status}`):(f(""),n(!0),setTimeout(()=>n(!1),2e3),b())}catch(a){l(String(a))}finally{h(!1)}}},[c,a.id,b]),q=(0,e.useCallback)(async()=>{j(!0),l(null);try{let c=await fetch(`/api/auth/api-key/${encodeURIComponent(a.id)}`,{method:"DELETE"}),d=await c.json();!c.ok||d.error?l(d.error??`HTTP ${c.status}`):b()}catch(a){l(String(a))}finally{j(!1)}},[a.id,b]);return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,d.jsx)(hu,{children:"API Key"}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,d.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,d.jsx)("span",{style:{fontSize:11,color:a.configured?"#4ade80":"var(--text-dim)"},children:o(a.configured?"i18n.configured":"i18n.notConfigured")})]})]}),(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:a.configured?"API key is stored. Enter a new key below to replace it, or disconnect to remove it.":`Enter your ${a.displayName} API key to enable ${a.modelCount} model${1!==a.modelCount?"s":""}.`}),(0,d.jsx)(hn,{label:"API Key",children:(0,d.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,d.jsx)(hq,{value:c,onChange:f,onKeyDown:a=>{"Enter"===a.key&&c.trim()&&p()},placeholder:a.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,d.jsxs)("button",{onClick:p,disabled:g||!c.trim()||m,style:{padding:"6px 12px",background:m?"#16a34a":c.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:m?"#fff":c.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:g||!c.trim()||m?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[m&&(0,d.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}),o(m?"i18n.saved":g?"i18n.saving":"i18n.save")]})]})}),k&&(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:k}),a.configured&&(0,d.jsx)("button",{onClick:q,disabled:i,style:{alignSelf:"flex-start",padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:i?"not-allowed":"pointer",fontSize:12},children:o(i?"i18n.removing":"i18n.disconnect")})]})}function hF({id:a,size:b}){let c=hl[a];if(!c){let c=a.split(/[-_]/).filter(Boolean).slice(0,2).map(a=>a[0]).join("").toUpperCase()||"?";return(0,d.jsx)("span",{"aria-hidden":"true",style:{width:b,height:b,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*b)),fontWeight:700,lineHeight:1},children:c})}return c.hasColor?(0,d.jsx)(c.Icon,{size:b}):(0,d.jsx)(c.Icon,{size:b,style:{color:"var(--text-muted)"}})}function hG({oauthProviders:a,apiKeyProviders:b,onSelectOAuth:c,onSelectApiKey:f,onAddCustom:g,onClose:h}){let[i,j]=(0,e.useState)(""),{t:k}=(0,x.s)(),l=(0,e.useRef)(null),m=i.trim().toLowerCase(),n=a.filter(a=>!a.loggedIn&&(!m||a.name.toLowerCase().includes(m))),o=b.filter(a=>!a.configured&&(!m||a.displayName.toLowerCase().includes(m)||a.id.toLowerCase().includes(m))),p=!m||"custom".includes(m)||"openai-compatible".includes(m)||"anthropic-compatible".includes(m),q=n.length+o.length+ +!!p,r={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,d.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:a=>{a.target===a.currentTarget&&h()},children:(0,d.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,d.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,d.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,d.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,d.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,d.jsx)("input",{ref:l,value:i,onChange:a=>j(a.target.value),onKeyDown:a=>{"Escape"===a.key&&h()},placeholder:k("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,d.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===q?(0,d.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:k("i18n.noProviders")}):(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[p&&(0,d.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:k("i18n.custom")}),p&&(0,d.jsxs)("button",{onClick:()=>{g(),h()},style:r,onMouseEnter:a=>{a.currentTarget.style.borderColor="var(--accent)",a.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:a=>{a.currentTarget.style.borderColor="var(--border)",a.currentTarget.style.background="var(--bg-panel)"},children:[(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,d.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:k("i18n.customEndpoint")})]}),(0,d.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,d.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,d.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,d.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),n.length>0&&(0,d.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!p,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:k("i18n.subscriptions")}),n.map(a=>(0,d.jsxs)("button",{onClick:()=>{c(a.id),h()},style:r,onMouseEnter:a=>{a.currentTarget.style.borderColor="var(--accent)",a.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:a=>{a.currentTarget.style.borderColor="var(--border)",a.currentTarget.style.background="var(--bg-panel)"},children:[(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.name}),(0,d.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,d.jsx)(hF,{id:a.id,size:28})]},a.id)),o.length>0&&(0,d.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(n.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),o.map(a=>(0,d.jsxs)("button",{onClick:()=>{f(a.id),h()},style:r,onMouseEnter:a=>{a.currentTarget.style.borderColor="var(--accent)",a.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:a=>{a.currentTarget.style.borderColor="var(--border)",a.currentTarget.style.background="var(--bg-panel)"},children:[(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.displayName}),(0,d.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[a.modelCount," models"]})]}),(0,d.jsx)(hF,{id:a.id,size:28})]},a.id))]})})]})})}function hH({cwd:a,onClose:b,embedded:c=!1,onModelsChanged:f,relogin:g}){let h=D(),{t:i}=(0,x.s)(),[j,k]=(0,e.useState)({providers:{}}),[l,m]=(0,e.useState)(!0),[n,o]=(0,e.useState)(!1),[p,q]=(0,e.useState)(null),[r,s]=(0,e.useState)(!1),[t,u]=(0,e.useState)(g?{type:"oauth",providerId:g.target.provider}:{type:"roles"}),[v,w]=(0,e.useState)([]),[y,z]=(0,e.useState)([]),[A,B]=(0,e.useState)(!1),C=(0,e.useCallback)(()=>{fetch("/api/auth/providers").then(a=>a.json()).then(a=>w(a.providers)).catch(()=>{})},[]),E=(0,e.useCallback)(()=>{fetch("/api/auth/all-providers").then(a=>a.json()).then(a=>z(a.providers)).catch(()=>{})},[]),F=(0,e.useCallback)(()=>{C(),E()},[C,E]),G=(0,e.useCallback)(()=>{let a="new-provider",b=1;for(;j.providers?.[a];)a=`new-provider-${b++}`;k(b=>({...b,providers:{...b.providers??{},[a]:{api:"openai-completions"}}})),u({type:"provider",name:a})},[j.providers]),H=(0,e.useCallback)((a,b)=>{k(c=>({...c,providers:{...c.providers??{},[a]:b}}))},[]),I=(0,e.useCallback)((a,b)=>{k(c=>{let d=Object.entries(c.providers??{}),e=d.findIndex(([b])=>b===a);return -1===e?c:(d[e]=[b,d[e][1]],{...c,providers:Object.fromEntries(d)})}),u(c=>c?"provider"===c.type&&c.name===a?{type:"provider",name:b}:"model"===c.type&&c.providerName===a?{...c,providerName:b}:c:c)},[]),J=(0,e.useCallback)(a=>{k(b=>{let c={...b.providers??{}};return delete c[a],{...b,providers:c}}),k(a=>{let b=Object.keys(a.providers??{});return u(b.length>0?{type:"provider",name:b[0]}:null),a})},[]),K=(0,e.useCallback)(a=>{k(b=>{let c=b.providers?.[a]??{},d=[...c.models??[],{id:""}];return{...b,providers:{...b.providers??{},[a]:{...c,models:d}}}}),k(b=>{let c=(b.providers?.[a]?.models?.length??1)-1;return u({type:"model",providerName:a,index:c}),b})},[]),L=(0,e.useCallback)((a,b)=>{k(c=>{let d=c.providers?.[a]??{},e=[...d.models??[]],f=new Set(e.map(a=>a.id));for(let a of b)f.has(a.id)||(f.add(a.id),e.push({id:a.id,name:a.name}));return{...c,providers:{...c.providers??{},[a]:{...d,models:e}}}})},[]),M=(0,e.useCallback)((a,b,c)=>{k(d=>{let e=d.providers?.[a]??{},f=[...e.models??[]];return f[b]=c,{...d,providers:{...d.providers??{},[a]:{...e,models:f}}}})},[]),N=(0,e.useCallback)((a,b)=>{k(c=>{let d=c.providers?.[a]??{},e=[...d.models??[]];return e.splice(b,1),{...c,providers:{...c.providers??{},[a]:{...d,models:e.length?e:void 0}}}}),u({type:"provider",name:a})},[]),O=(0,e.useCallback)(async()=>{o(!0),q(null),s(!1);try{let a=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(j)}),b=await a.json();!a.ok||b.error?q(b.error??`HTTP ${a.status}`):(s(!0),f?.(),setTimeout(()=>s(!1),2e3))}catch(a){q(String(a))}finally{o(!1)}},[j,f]),P=Object.entries(j.providers??{}),Q=v.filter(a=>a.loggedIn),R=y.filter(a=>a.configured),S=(()=>{if(!t)return null;if("roles"===t.type)return(0,d.jsx)(gR,{cwd:a??null,onRolesChanged:f});if("oauth"===t.type){let a=v.find(a=>a.id===t.providerId);return a?(0,d.jsx)(hD,{provider:a,onRefresh:F,relogin:g?.target.provider===a.id?g:void 0},a.id):null}if("apikey"===t.type){let a=y.find(a=>a.id===t.providerId);return a?(0,d.jsx)(hE,{provider:a,onRefresh:F},a.id):null}if("provider"===t.type){let a=j.providers?.[t.name];return a?(0,d.jsx)(hv,{name:t.name,provider:a,onChange:a=>H(t.name,a),onRename:a=>I(t.name,a),onDelete:()=>J(t.name),onAddModels:a=>L(t.name,a)},t.name):null}let b=j.providers?.[t.providerName],c=b?.models?.[t.index];return c?(0,d.jsx)(hB,{providerName:t.providerName,provider:b,model:c,onChange:a=>M(t.providerName,t.index,a),onDelete:()=>N(t.providerName,t.index)},`${t.providerName}-${t.index}`):null})();return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:{position:c?"relative":"fixed",inset:c?void 0:0,width:"100%",height:"100%",zIndex:c?void 0:1e3,background:c?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:a=>{c||a.target!==a.currentTarget||b()},...c?{}:{role:"dialog","aria-modal":!0,"aria-label":i("common.models"),onKeyDown:a=>{"Escape"===a.key&&(a.stopPropagation(),b())}},children:(0,d.jsxs)("div",{style:{width:c?"100%":h?"calc(100vw - 16px)":860,maxWidth:c?"none":"calc(100vw - 16px)",height:c?"100%":h?"calc(100dvh - 16px)":"78vh",maxHeight:c?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:c?"none":"1px solid var(--border)",borderRadius:10*!c,display:"flex",flexDirection:"column",boxShadow:c?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,d.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:i("common.models")}),(0,d.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.omp/agent/models.yml"})]}),(0,d.jsx)("button",{onClick:b,"aria-label":i("i18n.close"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,d.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:h?"column":"row",overflow:"hidden"},children:[(0,d.jsxs)("div",{style:{width:h?"100%":210,maxHeight:h?"40vh":void 0,borderRight:h?"none":"1px solid var(--border)",borderBottom:h?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,d.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[(0,d.jsxs)("div",{onClick:()=>u({type:"roles"}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?.type==="roles"?"var(--bg-selected)":"none"},onMouseEnter:a=>{t?.type!=="roles"&&(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{t?.type!=="roles"&&(a.currentTarget.style.background="none")},children:[(0,d.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-muted)",flexShrink:0},children:[(0,d.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,d.jsx)("circle",{cx:"9",cy:"7",r:"2.2"}),(0,d.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,d.jsx)("circle",{cx:"15",cy:"17",r:"2.2"})]}),(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1},children:i("roles.title")})]}),(0,d.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),Q.map(a=>{let b=t?.type==="oauth"&&t.providerId===a.id;return(0,d.jsxs)("div",{onClick:()=>u({type:"oauth",providerId:a.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:b?"var(--bg-selected)":"none"},onMouseEnter:a=>{b||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{b||(a.currentTarget.style.background="none")},children:[(0,d.jsx)(hF,{id:a.id,size:16}),(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.name})]},a.id)}),R.map(a=>{let b=t?.type==="apikey"&&t.providerId===a.id;return(0,d.jsxs)("div",{onClick:()=>u({type:"apikey",providerId:a.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:b?"var(--bg-selected)":"none"},onMouseEnter:a=>{b||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{b||(a.currentTarget.style.background="none")},children:[(0,d.jsx)(hF,{id:a.id,size:16}),(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.displayName})]},a.id)}),(Q.length>0||R.length>0)&&P.length>0&&(0,d.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),l?(0,d.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:i("i18n.loading")}):P.map(([a,b])=>{let c=t?.type==="provider"&&t.name===a,e=b.models??[];return(0,d.jsxs)("div",{style:{marginBottom:2},children:[(0,d.jsxs)("div",{onClick:()=>u({type:"provider",name:a}),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:c?"var(--bg-selected)":"none"},onMouseEnter:a=>{c||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{c||(a.currentTarget.style.background="none")},children:[(0,d.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,d.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,d.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,d.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,d.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,d.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,d.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,d.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,d.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,d.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,d.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,d.jsx)("span",{style:{fontSize:12,fontWeight:c?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a})]}),e.map((b,c)=>{let e=t?.type==="model"&&t.providerName===a&&t.index===c;return(0,d.jsxs)("div",{onClick:()=>u({type:"model",providerName:a,index:c}),style:{display:"flex",alignItems:"center",gap:6,padding:"5px 8px 5px 26px",borderRadius:5,cursor:"pointer",background:e?"var(--bg-selected)":"none"},onMouseEnter:a=>{e||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{e||(a.currentTarget.style.background="none")},children:[(0,d.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:b.id?"var(--text-muted)":"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b.id||i("i18n.newModel")}),b.reasoning&&(0,d.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"})]},c)}),(0,d.jsx)("div",{onClick:b=>{b.stopPropagation(),K(a)},style:{display:"flex",alignItems:"center",gap:4,padding:"4px 8px 4px 26px",borderRadius:5,cursor:"pointer",color:"var(--text-dim)"},onMouseEnter:a=>{a.currentTarget.style.color="var(--accent)",a.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:a=>{a.currentTarget.style.color="var(--text-dim)",a.currentTarget.style.background="none"},children:(0,d.jsxs)("span",{style:{fontSize:11},children:["+ ",i("i18n.model")]})})]},a)})]}),(0,d.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 6px"},children:(0,d.jsxs)("button",{onClick:()=>B(!0),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:"100%",padding:"6px 0",background:"none",border:"1px dashed var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},onMouseEnter:a=>{a.currentTarget.style.borderColor="var(--accent)",a.currentTarget.style.color="var(--accent)"},onMouseLeave:a=>{a.currentTarget.style.borderColor="var(--border)",a.currentTarget.style.color="var(--text-muted)"},children:["+ ",i("i18n.addProvider")]})})]}),(0,d.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:l?null:S??(0,d.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:i("i18n.selectProviderModel")})})]}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:10,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[p&&(0,d.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:p}),(0,d.jsx)("button",{onClick:b,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:i("i18n.cancel")}),(0,d.jsxs)("button",{onClick:O,disabled:n||r,style:{position:"relative",padding:"6px 16px",minWidth:92,background:r?"#16a34a":n?"var(--bg-panel)":"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:6,color:r?"#fff":n?"var(--text-muted)":"var(--seed-color-fg-neutral-inverted)",cursor:n||r?"default":"pointer",fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,transition:"background-color 0.2s ease, color 0.2s ease",animation:r?"saved-pop 0.45s ease":void 0},children:[r&&(0,d.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:18,animation:"saved-check-draw 0.35s ease forwards",flexShrink:0},children:(0,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,d.jsx)("span",{children:r?i("i18n.saved"):n?i("i18n.saving"):i("i18n.save")})]})]})]})}),A&&(0,d.jsx)(hG,{oauthProviders:v,apiKeyProviders:y,onSelectOAuth:a=>u({type:"oauth",providerId:a}),onSelectApiKey:a=>u({type:"apikey",providerId:a}),onAddCustom:G,onClose:()=>B(!1)})]})}function hI(a){return a.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function hJ(a){let b=a.sourceInfo?.source,c=a.sourceInfo?.scope;return"user"===c||"user"===b?"global":"project"===c||"project"===b?"project":"path"}function hK(a){let b=hJ(a);return"path"===b?b:a.install?.skillsShUrl?`${b} / skills.sh`:b}function hL(a){return a.install?`${a.install.scope}\0${a.install.package}`:null}function hM(a){return a?a.slice(0,8):"unknown"}function hN({enabled:a,loading:b,onToggle:c}){let{t:e}=(0,x.s)();return(0,d.jsx)("button",{onClick:c,disabled:b,title:e(a?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),style:{flexShrink:0,width:40,height:22,borderRadius:11,border:"none",padding:0,cursor:b?"wait":"pointer",background:a?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none"},children:(0,d.jsx)("span",{style:{position:"absolute",top:3,left:a?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function hO({skill:a,cwd:b,onToggle:c,toggling:e,saveError:f,updateStatus:g,checkingUpdate:h,updating:i,updateError:j,onCheckUpdate:k,onUpdate:l}){let{t:m}=(0,x.s)(),n=hJ(a),o=!a.disableModelInvocation;return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7},children:[(0,d.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===n?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===n?"rgba(99,102,241,0.8)":"var(--text-dim)"},children:n}),(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:function(a){if("project"===n&&a.startsWith(b)){let c=a.slice(b.length).replace(/^[/\\]/,"");return`./${c}`}return hI(a)}(a.filePath)}),(0,d.jsx)(hN,{enabled:o,loading:e,onToggle:()=>c(a)})]}),(0,d.jsxs)("div",{style:{minHeight:16,display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,flexWrap:"wrap",textAlign:"right"},children:[!o&&(0,d.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:m("i18n.hiddenButInvocable")}),f&&(0,d.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:f})]})]}),a.install?.skillsShUrl&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Source"}),(0,d.jsx)("a",{href:a.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:a.install.skillsShUrl,style:{display:"flex",alignItems:"center",gap:8,width:"fit-content",maxWidth:"100%",color:"var(--accent)",textDecoration:"none"},children:(0,d.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[a.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})]}),a.install&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Version"}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text-muted)"},children:hM(g?.currentVersion??a.install.versionHash)}),a.install.canCheckForUpdates&&(0,d.jsx)("button",{onClick:k,disabled:h||i,style:{padding:"4px 9px",border:"1px solid var(--border)",borderRadius:5,background:"none",color:"var(--text-muted)",cursor:h||i?"not-allowed":"pointer",opacity:h||i?.5:1,fontSize:11},children:m("i18n.check")}),g?.state==="update-available"&&(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"#d97706"},children:hM(g.latestVersion)}),(h||g&&"update-available"!==g.state)&&(0,d.jsx)("span",{style:{fontSize:12,color:h?"var(--accent)":g?.state==="up-to-date"?"#16a34a":g?.state==="error"?"#ef4444":"var(--text-dim)"},children:h?m("i18n.checking"):g?.state==="up-to-date"?m("i18n.upToDate"):g?.state==="unsupported"?m("i18n.automaticChecksUnavailable"):g?.message||m("i18n.checkFailed")}),g?.state==="update-available"&&(0,d.jsx)("button",{onClick:l,disabled:i||h,style:{padding:"4px 10px",border:"none",borderRadius:5,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:i||h?"not-allowed":"pointer",opacity:i||h?.5:1,fontSize:11,fontWeight:600},children:m(i?"i18n.updating":"i18n.update")})]}),j&&(0,d.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:j})]}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Name"}),(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:14,color:"var(--text)"},children:a.name})]}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Description"}),(0,d.jsx)("span",{style:{fontSize:14,color:"var(--text-muted)",lineHeight:1.6},children:a.description})]})]})}function hP({cwd:a,installedPackages:b,projectResourcesLoaded:c,onInstalled:f}){let{t:g}=(0,x.s)(),[h,i]=(0,e.useState)(""),[j,k]=(0,e.useState)([]),[l,m]=(0,e.useState)(!1),[n,o]=(0,e.useState)(null),[p,q]=(0,e.useState)(null),[r,s]=(0,e.useState)(null),[t,u]=(0,e.useState)(new Set),[v,w]=(0,e.useState)("global"),y=(0,e.useRef)(null),z=(0,e.useCallback)(async a=>{if(a.trim()){m(!0),o(null),k([]);try{let b=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:a.trim()})}),c=await b.json();if(c.error)return void o(c.error);k(c.results??[]),0===(c.results??[]).length&&o("No skills found")}catch(a){o(String(a))}finally{m(!1)}}},[]),A=(0,e.useCallback)(async b=>{q(b),s(null);try{let c=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:b,scope:v,cwd:a})}),d=await c.json();if(!c.ok||d.error)return void s(d.error??`HTTP ${c.status}`);u(a=>new Set(a).add(`${v}:${b}`)),f()}catch(a){s(String(a))}finally{q(null)}},[f,v,a]),B="global"===v?"~/.claude/skills/":`${hI(a)}/.claude/skills/`;return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,d.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:g("i18n.addSkill")}),(0,d.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,d.jsx)("input",{ref:y,value:h,onChange:a=>i(a.target.value),onKeyDown:a=>{"Enter"===a.key&&z(h)},placeholder:g("i18n.skillSearchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:13,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",outline:"none"}}),(0,d.jsx)("button",{onClick:()=>z(h),disabled:l||!h.trim(),style:{padding:"7px 16px",fontSize:13,borderRadius:6,border:"none",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:l||!h.trim()?"not-allowed":"pointer",opacity:l||!h.trim()?.5:1,flexShrink:0},children:l?g("i18n.searching"):g("i18n.search")})]}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,d.jsx)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(a=>(0,d.jsx)("button",{onClick:()=>{("global"===a||c)&&w(a)},disabled:"project"===a&&!c,title:"project"!==a||c?void 0:g("trust.projectScopeUnavailable"),style:{padding:"3px 10px",border:"none",cursor:"project"!==a||c?"pointer":"not-allowed",background:v===a?"var(--bg-selected)":"none",color:v===a?"var(--text)":"var(--text-dim)",fontWeight:v===a?600:400,opacity:"project"!==a||c?1:.45,borderRight:"global"===a?"1px solid var(--border)":"none"},children:a},a))}),(0,d.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",B]})]}),n&&(0,d.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:n}),r&&(0,d.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:r})]}),j.length>0?(0,d.jsx)("div",{style:{flex:1,overflowY:"auto"},children:j.map(a=>{let c=b[v].has(a.package)||t.has(`${v}:${a.package}`),e=p===a.package,f=a.package.indexOf("@"),h=f>-1?a.package.slice(0,f):a.package,i=f>-1?a.package.slice(f+1):null;return(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:i??h}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:h}),(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:a.installs}),a.url&&(0,d.jsx)("a",{href:a.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,d.jsx)("button",{onClick:()=>!c&&!e&&A(a.package),disabled:c||e||null!==p,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:5,border:"1px solid var(--border)",cursor:c||e||null!==p?"not-allowed":"pointer",background:c?"rgba(34,197,94,0.1)":"none",color:c?"#16a34a":e?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:c?`✓ ${g("i18n.installed")}`:e?g("i18n.installing"):g("i18n.install")})]},a.package)})}):!n&&!l&&(0,d.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:["Search"," ",(0,d.jsx)("a",{href:"https://skills.sh",target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",textDecoration:"none"},children:"skills.sh"})," ","to discover and install skills for your agent."]})]})}function hQ({cwd:a,onClose:b,embedded:c=!1}){let f=D(),{t:g}=(0,x.s)(),[h,i]=(0,e.useState)([]),[j,k]=(0,e.useState)(!0),[l,m]=(0,e.useState)(null),[n,o]=(0,e.useState)(null),[p,q]=(0,e.useState)(new Set),[r,s]=(0,e.useState)(null),[t,u]=(0,e.useState)(!1),[v,w]=(0,e.useState)({}),[y,z]=(0,e.useState)(new Set),[A,B]=(0,e.useState)(!1),[C,E]=(0,e.useState)(null),[F,G]=(0,e.useState)(null),[H,I]=(0,e.useState)(!0),[J,K]=(0,e.useState)({}),L=(0,e.useCallback)(async()=>{k(!0),m(null);try{let b=await fetch(`/api/skills?cwd=${encodeURIComponent(a)}`),c=await b.json();if(!b.ok||c.error)throw Error(c.error??`HTTP ${b.status}`);let d=c.skills??[];if(i(d),I(c.projectResourcesLoaded??!0),d.length>0&&!n){let a=d.find(a=>!a.disableModelInvocation)??d[0];o(a.filePath),a.disableModelInvocation&&K(b=>({...b,[hK(a)]:!0}))}return d}catch(a){return m(String(a)),[]}finally{k(!1)}},[a,n]),M=(0,e.useCallback)(async b=>{let c=(b?[b]:h.filter(a=>!!a.install)).map(hL).filter(a=>!!a);if(0!==c.length){G(null),z(a=>new Set([...a,...c])),b||B(!0);try{let c=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:a,package:b?.install?.package,scope:b?.install?.scope})}),d=await c.json();if(!c.ok||d.error)throw Error(d.error??`HTTP ${c.status}`);w(a=>{let b={...a};for(let a of d.updates??[])b[`${a.scope}\0${a.package}`]=a;return b})}catch(a){G(a instanceof Error?a.message:String(a))}finally{z(a=>{let b=new Set(a);for(let a of c)b.delete(a);return b}),b||B(!1)}}},[a,h]),N=(0,e.useCallback)(async b=>{if(!b.install)return;let c=hL(b);E(c),G(null);try{let d=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:a,package:b.install.package,scope:b.install.scope})}),e=await d.json();if(!d.ok||e.error||!e.success)throw Error(e.error??`HTTP ${d.status}`);await L();let f=e.skill?.install?.versionHash;w(a=>({...a,[c]:{package:b.install.package,scope:b.install.scope,state:"up-to-date",currentVersion:f,latestVersion:f}}))}catch(a){G(a instanceof Error?a.message:String(a))}finally{E(null)}},[a,L]),O=(0,e.useCallback)(async a=>{let b=!a.disableModelInvocation;q(b=>new Set(b).add(a.filePath)),s(null);try{let c=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:a.filePath,disableModelInvocation:b})}),d=await c.json();if(!c.ok||d.error)return void s(d.error??`HTTP ${c.status}`);i(c=>c.map(c=>c.filePath===a.filePath?{...c,disableModelInvocation:b}:c)),b&&K(b=>({...b,[hK(a)]:!0}))}catch(a){s(String(a))}finally{q(b=>{let c=new Set(b);return c.delete(a.filePath),c})}},[]),P=h.find(a=>a.filePath===n)??null;return(0,d.jsx)("div",{style:{position:c?"relative":"fixed",inset:c?void 0:0,width:"100%",height:"100%",zIndex:c?void 0:1e3,background:c?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:a=>{c||a.target!==a.currentTarget||b()},children:(0,d.jsxs)("div",{style:{width:c?"100%":f?"calc(100vw - 16px)":860,maxWidth:c?"none":"calc(100vw - 16px)",height:c?"100%":f?"calc(100dvh - 16px)":"78vh",maxHeight:c?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:c?"none":"1px solid var(--border)",borderRadius:10*!c,display:"flex",flexDirection:"column",boxShadow:c?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,d.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:g("common.skills")}),(0,d.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:hI(a)})]}),(0,d.jsx)("button",{onClick:b,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!H&&(0,d.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:g("trust.skillsNotLoaded")}),(0,d.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:f?"column":"row",overflow:"hidden"},children:[(0,d.jsxs)("div",{style:{width:f?"100%":210,maxHeight:f?"40vh":void 0,borderRight:f?"none":"1px solid var(--border)",borderBottom:f?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,d.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:j?(0,d.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:g("i18n.loading")}):l?(0,d.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#f87171"},children:l}):0===h.length?(0,d.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:g("i18n.noSkills")}):(()=>{let a=[];for(let{label:b,matches:c}of[{label:"project / skills.sh",matches:a=>"project"===hJ(a)&&!!a.install?.skillsShUrl},{label:"project",matches:a=>"project"===hJ(a)&&!a.install?.skillsShUrl},{label:"global / skills.sh",matches:a=>"global"===hJ(a)&&!!a.install?.skillsShUrl},{label:"global",matches:a=>"global"===hJ(a)&&!a.install?.skillsShUrl},{label:"path",matches:a=>"path"===hJ(a)}]){let d=h.filter(c);d.length>0&&a.push({label:b,skills:d})}let b=a=>{let b,c,e=!t&&n===a.filePath,f=a.disableModelInvocation;return(0,d.jsxs)("div",{onClick:()=>{o(a.filePath),u(!1)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:e?"var(--bg-selected)":"none"},onMouseEnter:a=>{e||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{e||(a.currentTarget.style.background="none")},children:[(0,d.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:f?"var(--border)":"var(--accent)",boxShadow:f?"none":"0 0 4px var(--accent)",transition:"background 0.15s, box-shadow 0.15s"}}),(0,d.jsx)("span",{style:{fontSize:12,fontWeight:e?600:400,color:f?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.name}),(c=(b=hL(a))?v[b]:void 0,c?.state!=="update-available"?null:(0,d.jsx)("span",{title:g("i18n.updateAvailable"),style:{color:"#d97706",fontSize:13,lineHeight:1,flexShrink:0},children:"↑"}))]},a.filePath)};return a.map(({label:a,skills:c})=>{let e=c.filter(a=>!a.disableModelInvocation),f=c.filter(a=>a.disableModelInvocation),h=J[a]??!1;return(0,d.jsxs)("div",{style:{marginBottom:6},children:[(0,d.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em"},children:a}),e.map(b),f.length>0&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{onClick:()=>K(b=>({...b,[a]:!h})),style:{display:"flex",alignItems:"center",gap:5,padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",cursor:"pointer",userSelect:"none"},children:[(0,d.jsx)("span",{style:{fontSize:8},children:h?"▾":"▸"}),g("i18n.dormant")," (",f.length,")"]}),h&&f.map(b)]})]},a)})})()}),(0,d.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,d.jsxs)("div",{onClick:()=>u(!0),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none",color:t?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:a=>{t||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{t||(a.currentTarget.style.background="none")},children:[(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,d.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),g("i18n.addSkill")]})})]}),(0,d.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:t?(0,d.jsx)(hP,{cwd:a,projectResourcesLoaded:H,installedPackages:{global:new Set(h.filter(a=>a.install?.scope==="global").map(a=>a.install.package)),project:new Set(h.filter(a=>a.install?.scope==="project").map(a=>a.install.package))},onInstalled:()=>{L()}}):j?null:P?(0,d.jsx)(hO,{skill:P,cwd:a,onToggle:O,toggling:p.has(P.filePath),saveError:r,updateStatus:hL(P)?v[hL(P)]:void 0,checkingUpdate:!!hL(P)&&y.has(hL(P)),updating:C===hL(P),updateError:F,onCheckUpdate:()=>void M(P),onUpdate:()=>void N(P)},P.filePath):(0,d.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:g("i18n.selectSkill")})})]}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[h.some(a=>!!a.install)&&(0,d.jsx)("button",{onClick:()=>void M(),disabled:A||null!==C,style:{padding:"6px 12px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:A||null!==C?"not-allowed":"pointer",opacity:A||null!==C?.5:1,fontSize:12},children:A?g("i18n.checking"):g("i18n.checkUpdates")}),Object.values(v).filter(a=>"update-available"===a.state).length>0&&(0,d.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(v).filter(a=>"update-available"===a.state).length," ",1===Object.values(v).filter(a=>"update-available"===a.state).length?g("i18n.update"):g("i18n.updates")]})]}),(0,d.jsx)("button",{onClick:b,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:g("i18n.close")})]})]})})}let hR="global";function hS(a){return a.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function hT(a){let b=a.trim().match(/^\$?\s*omp\s+plugin\s+(?:add|install)\s+(\S+)\s*$/);return b?.[1]??a}function hU(a){return`${a.scope}\0${a.source}`}function hV(a,b){if(a.disabled)return b("i18n.disabled");let c=[a.counts.extensions?b("i18n.resourceCount",{count:a.counts.extensions,label:b("i18n.extensionShort")}):"",a.counts.skills?b("i18n.resourceCount",{count:a.counts.skills,label:b("i18n.skillShort")}):"",a.counts.prompts?b("i18n.resourceCount",{count:a.counts.prompts,label:b("i18n.promptShort")}):"",a.counts.themes?b("i18n.resourceCount",{count:a.counts.themes,label:b("i18n.themeShort")}):""].filter(Boolean);return c.length?c.join(" \xb7 "):b("i18n.noResources")}function hW(a,b){let c=[];return a.version&&c.push(b("i18n.installedVersion",{version:a.version})),a.configuredVersion&&c.push(b("i18n.configuredVersion",{version:a.configuredVersion})),c.length?c.join(" \xb7 "):b("i18n.unknown")}function hX(a){return"loaded"===a?"var(--accent)":"installed"===a?"#f59e0b":"disabled"===a?"var(--text-dim)":"#ef4444"}function hY({pkg:a}){let{t:b}=(0,x.s)(),c=[["extension",b("i18n.extensions")],["skill",b("i18n.skills")],["prompt",b("i18n.prompts")],["theme",b("i18n.themes")]].map(([b,c])=>({kind:b,label:c,resources:a.resources.filter(a=>a.kind===b)})).filter(a=>a.resources.length>0);return 0===c.length?(0,d.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:b(a.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:c.map((a,b)=>(0,d.jsxs)("div",{style:{borderTop:0===b?"none":"1px solid var(--border)",paddingTop:12*(0!==b)},children:[(0,d.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:a.label}),(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:a.resources.map(a=>(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:a.path,children:a.name}),(0,d.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:a.path,children:a.relativePath})]},`${a.kind}:${a.path}`))})]},a.kind))})}function hZ({scope:a}){return(0,d.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===a?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===a?"rgba(99,102,241,0.85)":"var(--text-dim)"},children:a})}function h$(a,b){return{padding:"6px 12px",background:b?"rgba(239,68,68,0.08)":"none",border:"1px solid var(--border)",borderRadius:6,color:b?"#ef4444":"var(--text-muted)",cursor:a?"not-allowed":"pointer",fontSize:12,opacity:a?.5:1}}function h_({enabled:a,loading:b,onToggle:c,label:e}){return(0,d.jsx)("button",{type:"button",onClick:c,disabled:b,title:e,"aria-label":e,"aria-pressed":a,style:{flexShrink:0,width:40,height:22,borderRadius:11,border:"none",padding:0,cursor:b?"wait":"pointer",background:a?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none",opacity:b?.65:1},children:(0,d.jsx)("span",{style:{position:"absolute",top:3,left:a?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function h0({installDir:a,source:b,busy:c,actionError:f,onSourceChange:g,onInstall:h}){let{t:i}=(0,x.s)(),j=(0,e.useRef)(null);return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:660,minHeight:"100%"},children:[(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,d.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:i("i18n.addPlugin")}),(0,d.jsxs)("a",{href:"https://github.com/can1357/oh-my-pi#plugins",target:"_blank",rel:"noopener noreferrer",style:{display:"inline-flex",alignItems:"center",gap:5,color:"var(--accent)",fontSize:12,textDecoration:"none",whiteSpace:"nowrap"},children:[(0,d.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",style:{flexShrink:0},children:[(0,d.jsx)("path",{fill:"#000",fillRule:"evenodd",d:"M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"}),(0,d.jsx)("path",{fill:"#000",d:"M517.36 400H634.72V634.72H517.36Z"})]}),"oh-my-pi plugins"]})]}),a&&(0,d.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:hS(a)})]}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,d.jsx)("label",{htmlFor:"plugin-source",style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Source"}),(0,d.jsx)("input",{id:"plugin-source",ref:j,value:b,onChange:a=>g(a.target.value),onPaste:a=>{let b=a.clipboardData.getData("text"),c=hT(b);c!==b&&(a.preventDefault(),g(c))},onBlur:a=>g(hT(a.currentTarget.value)),placeholder:"@scope/package or github:user/repo",style:{width:"100%",height:36,padding:"0 11px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,outline:"none"},onKeyDown:a=>{"Enter"===a.key&&b.trim()&&!c&&h()}})]}),(0,d.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:(0,d.jsx)("button",{type:"button",onClick:h,disabled:c||!b.trim(),style:{...h$(c||!b.trim()),background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",borderColor:"transparent"},children:i(c?"i18n.installing":"i18n.install")})}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,d.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Examples"}),(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:["@scope/omp-plugin","github:user/repo","pkg[feature]"].map(a=>(0,d.jsx)("button",{type:"button",onClick:()=>g(a),style:{width:"100%",minHeight:30,textAlign:"left",padding:"6px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"pointer",fontFamily:"var(--font-mono)",fontSize:11},onMouseEnter:a=>{a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color="var(--text-muted)"},onMouseLeave:a=>{a.currentTarget.style.background="var(--bg-panel)",a.currentTarget.style.color="var(--text-dim)"},children:a},a))})]}),f&&(0,d.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:f})]})}function h1({pkg:a,cwd:b,busyKey:c,actionError:e,actionMessage:f,sessionId:g,onAction:h,onReloadSession:i}){let{t:j}=(0,x.s)(),k=hU(a),l=c?.endsWith(k)??!1,m="reload"===c,n=!a.disabled;return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20,maxWidth:680},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,minWidth:0,flexWrap:"wrap"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:180,flex:1},children:[(0,d.jsx)(h_,{enabled:n,loading:l||m,onToggle:()=>h(a.disabled?"enable":"disable",a),label:j(a.disabled?"i18n.enablePackage":"i18n.disablePackage")}),(0,d.jsx)(hZ,{scope:a.scope}),a.disabled?(0,d.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:j("i18n.disabled")}):a.filtered&&(0,d.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:j("i18n.filtered")}),(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.source})]}),(0,d.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[(0,d.jsx)("button",{onClick:()=>h("update",a),disabled:l||m,style:h$(l||m),children:j(c===`update:${k}`?"i18n.updating":"i18n.update")}),(0,d.jsx)("button",{onClick:i,disabled:!g||m||l,style:h$(!g||m||l),title:j(g?"i18n.reloadSessionHint":"i18n.openSessionToReload"),children:j(m?"i18n.reloading":"i18n.reloadSession")}),(0,d.jsx)("button",{onClick:()=>h("remove",a),disabled:l||m,style:h$(l||m,!0),children:j(c===`remove:${k}`?"i18n.removing":"i18n.remove")})]})]}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,d.jsx)("div",{style:{color:"var(--text-dim)"},children:j("i18n.status")}),(0,d.jsx)("div",{style:{color:hX(a.status),textTransform:"capitalize"},children:a.status}),(0,d.jsx)("div",{style:{color:"var(--text-dim)"},children:j("i18n.version")}),(0,d.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:hW(a,j)}),(0,d.jsx)("div",{style:{color:"var(--text-dim)"},children:j("i18n.package")}),(0,d.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:a.packageName??j("i18n.unknown")}),(0,d.jsx)("div",{style:{color:"var(--text-dim)"},children:j("i18n.resources")}),(0,d.jsx)("div",{style:{color:"var(--text-muted)"},children:hV(a,j)}),(0,d.jsx)("div",{style:{color:"var(--text-dim)"},children:j("i18n.installedPath")}),(0,d.jsx)("div",{style:{color:a.installedPath?"var(--text-muted)":"#ef4444",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:a.installedPath?hS(a.installedPath):j("i18n.notFound")}),(0,d.jsx)("div",{style:{color:"var(--text-dim)"},children:j("i18n.cwd")}),(0,d.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:hS(b)})]}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,d.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)"},children:j("i18n.resolvedResources")}),(0,d.jsx)(hY,{pkg:a})]}),f&&(0,d.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:f}),e&&(0,d.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:e})]})}function h2({cwd:a,sessionId:b,onClose:c,onReloaded:f,embedded:g=!1}){let h=D(),{t:i}=(0,x.s)(),[j,k]=(0,e.useState)(null),[l,m]=(0,e.useState)(!0),[n,o]=(0,e.useState)(null),[p,q]=(0,e.useState)(null),[r,s]=(0,e.useState)(!1),[t,u]=(0,e.useState)(""),[v,w]=(0,e.useState)(null),[y,z]=(0,e.useState)(null),[A,B]=(0,e.useState)(null),C=(0,e.useMemo)(()=>j?.packages??[],[j?.packages]),E=C.find(a=>hU(a)===p)??null,F=j?.projectResourcesLoaded??!0,G=(0,e.useMemo)(()=>["project","global"].map(a=>({scope:a,packages:C.filter(b=>b.scope===a)})).filter(a=>a.packages.length>0),[C]),H=(0,e.useCallback)(async()=>{m(!0),o(null);try{let b=await fetch(`/api/plugins?cwd=${encodeURIComponent(a)}`),c=await b.json();if(!b.ok||c.error)throw Error(c.error??`HTTP ${b.status}`);k(c),s(a=>0===c.packages.length||a),q(a=>a&&c.packages.some(b=>hU(b)===a)?a:c.packages[0]?hU(c.packages[0]):null)}catch(a){o(a instanceof Error?a.message:String(a))}finally{m(!1)}},[a]),I=(0,e.useCallback)(async(b,c)=>{let d=hU(c);w(`${b}:${d}`),z(null),B(null);try{let d=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:b,source:c.source,scope:c.scope,cwd:a})}),e=await d.json();if(!d.ok||e.error)throw Error(e.error??`HTTP ${d.status}`);if(k(e),"remove"===b)q(e.packages[0]?hU(e.packages[0]):null),0===e.packages.length&&s(!0),B(i("i18n.packageRemoved"));else{let a={install:i("i18n.packageInstalled"),update:i("i18n.packageUpdated"),disable:i("i18n.packageDisabledRestartRequired"),enable:i("i18n.packageEnabled")};B(a[b])}}catch(a){z(a instanceof Error?a.message:String(a))}finally{w(null)}},[a,i]),J=(0,e.useCallback)(async()=>{let b=hT(t).trim();if(!b)return;u(b);let c=`${hR}\0${b}`;w(`install:${c}`),z(null),B(null);try{var d;let e,f,g=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:b,scope:hR,cwd:a})}),h=await g.json();if(!g.ok||h.error)throw Error(h.error??`HTTP ${g.status}`);k(h);let j=(d=h.packages,f=(e=b.trim()).startsWith("npm:")?e.slice(4):e,d.find(a=>a.scope===hR&&a.source===e)??d.find(a=>a.scope===hR&&a.source===`npm:${f}`)??d.find(a=>a.scope===hR&&a.source.endsWith(e)));q(j?hU(j):c),s(!1),u(""),B(i("i18n.packageInstalled"))}catch(a){z(a instanceof Error?a.message:String(a))}finally{w(null)}},[a,t,i]),K=(0,e.useCallback)(async()=>{if(b){w("reload"),z(null),B(null);try{await fK(b,{type:"reload"}),f?.(),await H(),B(i("i18n.sessionReloaded"))}catch(a){z(a instanceof Error?a.message:String(a))}finally{w(null)}}},[H,f,b,i]),L=v?.startsWith("install:")??!1;return(0,d.jsx)("div",{style:{position:g?"relative":"fixed",inset:g?void 0:0,width:"100%",height:"100%",zIndex:g?void 0:1e3,background:g?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:a=>{g||a.target!==a.currentTarget||c()},children:(0,d.jsxs)("div",{style:{width:g?"100%":h?"calc(100vw - 16px)":860,maxWidth:g?"none":"calc(100vw - 16px)",height:g?"100%":h?"calc(100dvh - 16px)":"76vh",maxHeight:g?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:g?"none":"1px solid var(--border)",borderRadius:8*!g,display:"flex",flexDirection:"column",boxShadow:g?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,d.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:i("common.plugins")}),(0,d.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:hS(a)})]}),(0,d.jsx)("button",{onClick:c,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!F&&(0,d.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:i("trust.pluginsNotLoaded")}),(0,d.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:h?"column":"row",overflow:"hidden"},children:[(0,d.jsxs)("div",{style:{width:h?"100%":245,maxHeight:h?"40vh":void 0,borderRight:h?"none":"1px solid var(--border)",borderBottom:h?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,d.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:l?(0,d.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:"Loading..."}):n?(0,d.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#ef4444"},children:n}):0===C.length?(0,d.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:"No plugins configured"}):G.map(a=>(0,d.jsxs)("div",{style:{marginBottom:6},children:[(0,d.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase"},children:a.scope}),a.packages.map(a=>{let b=hU(a),c=!r&&p===b;return(0,d.jsxs)("div",{onClick:()=>{q(b),s(!1),z(null),B(null)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:c?"var(--bg-selected)":"none"},onMouseEnter:a=>{c||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{c||(a.currentTarget.style.background="none")},children:[(0,d.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:hX(a.status)}}),(0,d.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,d.jsx)("div",{style:{fontSize:12,fontWeight:c?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.source}),(0,d.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:hV(a,i)}),(a.version||a.configuredVersion)&&(0,d.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:hW(a,i)})]})]},b)})]},a.scope))}),(0,d.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,d.jsxs)("button",{type:"button",onClick:()=>{s(!0),z(null),B(null)},style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,border:"none",width:"100%",cursor:"pointer",background:r?"var(--bg-selected)":"none",color:r?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:a=>{r||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{r||(a.currentTarget.style.background="none")},children:[(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,d.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),i("i18n.addPlugin")]})})]}),(0,d.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:r?(0,d.jsx)(h0,{installDir:j?.installDir,source:t,busy:L,actionError:y,onSourceChange:u,onInstall:J}):l?null:E?(0,d.jsx)(h1,{pkg:E,cwd:a,busyKey:v,actionError:y,actionMessage:A,sessionId:b,onAction:I,onReloadSession:K},hU(E)):(0,d.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:i("i18n.selectPackage")})})]}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,d.jsx)("div",{style:{minWidth:0,flex:1,fontSize:11,color:"var(--text-dim)",overflow:"hidden"},children:j?.diagnostics.length?(0,d.jsxs)("span",{title:j.diagnostics.map(a=>`${a.type}: ${a.source?`${a.source}: `:""}${a.message}`).join("\n"),style:{color:j.diagnostics.some(a=>"error"===a.type)?"#ef4444":"#d97706"},children:[j.diagnostics.length," diagnostic",1===j.diagnostics.length?"":"s"]}):(0,d.jsx)("span",{children:j?`${j.totals.extensions} ext \xb7 ${j.totals.skills} skills \xb7 ${j.totals.prompts} prompts \xb7 ${j.totals.themes} themes`:""})}),(0,d.jsx)("button",{onClick:()=>void H(),disabled:l||null!==v,style:h$(l||null!==v),children:i("i18n.refresh")}),(0,d.jsx)("button",{onClick:c,style:h$(!1),children:i("i18n.close")})]})]})})}var h3=c(84431),h4=c.n(h3);function h5(){let[a,b]=(0,e.useState)(null),[c,f]=(0,e.useState)(null),[g,h]=(0,e.useState)(null),[i,j]=(0,e.useState)(null),[k,l]=(0,e.useState)(!1),[m,n]=(0,e.useState)(""),[o,p]=(0,e.useState)("");(0,e.useCallback)(async()=>{try{let a=await fetch("/api/web-access",{cache:"no-store"}),c=await a.json();if(!a.ok||c.error)throw Error(c.error??`HTTP ${a.status}`);b(c),f(null)}catch(a){f(a instanceof Error?a.message:String(a))}},[]);let q=(0,e.useCallback)(async(a,c={})=>{l(!0),h(null),j(null);try{let d=await fetch("/api/web-access",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:a,...c})}),e=await d.json();if(!d.ok||e.error)throw Error(e.error??`HTTP ${d.status}`);return b(e),e}catch(a){return h(a instanceof Error?a.message:String(a)),null}finally{l(!1)}},[]),r=(0,e.useCallback)(async()=>{if(m!==o)return void h("The two passwords do not match.");let a=await q("set-password",{password:m});a&&(n(""),p(""),j(`Password saved and password access turned on. The browser will ask for the username "${a.username}" and this password on the next request.`))},[o,m,q]),s=(0,e.useCallback)(async()=>{if(!a)return;let b=await q(a.enabled?"disable":"enable");b&&j(b.enabled?`Password access is on. The browser will ask for the username "${b.username}" and your password on the next request.`:"Password access is off. The stored password is kept and can be switched back on here.")},[q,a]),t=(0,e.useCallback)(async()=>{await q("clear")&&j("The stored password was removed and password access is off.")},[q]);if(!a)return(0,d.jsx)("div",{className:h4().empty,children:c??"Loading password access…"});let u=a.managedByEnvironment,v=!k&&!u&&m.length>=8&&m===o;return(0,d.jsxs)("div",{className:h4().scrollContent,children:[(0,d.jsxs)("header",{className:h4().contentHeader,children:[(0,d.jsx)("h2",{className:h4().contentTitle,children:"Access"}),(0,d.jsxs)("p",{className:h4().contentDescription,children:["A password locks the web interface and every API endpoint behind HTTP Basic Auth, with the fixed username ",(0,d.jsx)("code",{children:a.username}),". It is stored as a scrypt hash in ",(0,d.jsx)("code",{children:a.file})," — CUELO never keeps the password itself, which is why forgetting it means recovering rather than reading it back."]}),u&&(0,d.jsxs)("div",{className:h4().readOnlyNotice,children:["Read-only \xb7 ",(0,d.jsx)("code",{children:"CUELO_PASSWORD"})," is set and overrides the stored credential. Unset it and restart CUELO to manage the password here."]}),i&&(0,d.jsx)("div",{className:h4().reloadNotice,children:(0,d.jsx)("span",{children:i})})]}),(0,d.jsxs)("div",{className:h4().settingsBody,children:[(0,d.jsxs)("section",{className:h4().group,children:[(0,d.jsx)("h3",{className:h4().groupTitle,children:"Password access"}),(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:h4().settingLabel,children:"Require a password"}),(0,d.jsx)("div",{className:h4().settingDescription,children:a.managedByEnvironment?"Every request needs the password from CUELO_PASSWORD.":a.unreadable?"The credential file exists but could not be read, so every request is being refused.":a.configured?a.enabled?"Every request needs the username and password.":"A password is stored but the lock is off.":"No password is set. Anyone who can reach this server can use it."}),!a.configured&&!u&&(0,d.jsx)("div",{className:h4().settingDescription,children:"Set a password below before turning this on."}),g&&(0,d.jsx)("div",{className:h4().error,children:g})]}),(0,d.jsx)("div",{className:h4().settingControl,children:(0,d.jsx)("button",{type:"button",className:h4().switch,"data-on":a.enabled,"aria-pressed":a.enabled,"aria-label":"Require a password",disabled:k||u||!a.enabled&&!a.stored,onClick:()=>void s()})})]})]}),(0,d.jsxs)("section",{className:h4().group,children:[(0,d.jsx)("h3",{className:h4().groupTitle,children:a.stored?"Replace the password":"Set a password"}),(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:h4().settingLabel,children:"New password"}),(0,d.jsxs)("div",{className:h4().settingDescription,children:["At least ",8," characters. Saving a password also turns password access on."]})]}),(0,d.jsx)("div",{className:h4().settingControl,children:(0,d.jsx)("input",{className:h4().textInput,type:"password",autoComplete:"new-password",value:m,disabled:k||u,onChange:a=>n(a.target.value)})})]}),(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:h4().settingLabel,children:"Confirm password"}),(0,d.jsx)("div",{className:h4().settingDescription,children:"Both entries have to match before it can be saved."})]}),(0,d.jsx)("div",{className:h4().settingControl,children:(0,d.jsx)("input",{className:h4().textInput,type:"password",autoComplete:"new-password",value:o,disabled:k||u,onChange:a=>p(a.target.value),onKeyDown:a=>{"Enter"===a.key&&v&&r()}})})]}),(0,d.jsxs)("div",{className:h4().editorActions,children:[(0,d.jsx)("div",{children:(0,d.jsx)("div",{className:h4().saveState,children:a.stored&&a.updatedAt?`Last changed ${new Date(a.updatedAt).toLocaleString()}`:"No password stored yet"})}),(0,d.jsxs)("div",{style:{display:"flex",gap:8},children:[a.stored&&!u&&(0,d.jsx)("button",{type:"button",className:h4().dangerButton,disabled:k,onClick:()=>void t(),children:"Remove password"}),(0,d.jsx)("button",{type:"button",className:h4().primaryButton,disabled:!v,onClick:()=>void r(),children:k?"Saving…":"Save password"})]})]})]}),(0,d.jsxs)("section",{className:h4().group,children:[(0,d.jsx)("h3",{className:h4().groupTitle,children:"If you forget it"}),(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:h4().settingLabel,children:"Recovery"}),(0,d.jsxs)("div",{className:h4().settingDescription,children:["Run ",(0,d.jsx)("code",{children:"cuelo --reset-password"})," on this machine to set a new one, or open ",(0,d.jsx)("code",{children:"/recover"})," in the browser: CUELO prints a one-time code on its own console, and entering that code sets a new password. Both paths require access to the machine running the server — nothing can hand the password back."]})]}),(0,d.jsx)("div",{className:h4().settingControl,children:(0,d.jsx)("a",{className:h4().linkButton,href:"/recover",target:"_blank",rel:"noreferrer",children:"Open /recover"})})]}),(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:h4().settingLabel,children:"Basic Auth is not encryption"}),(0,d.jsx)("div",{className:h4().settingDescription,children:"The password crosses the network in a reversible encoding. Over plain HTTP on an untrusted network it can be read in transit, so put CUELO behind HTTPS or a trusted VPN before exposing it beyond loopback."})]}),(0,d.jsx)("div",{className:h4().settingControl})]})]})]})]})}let h6="/api/live/character-voice",h7={ready:"chat.liveVoiceStateReady","not-prepared":"chat.liveVoiceStateNotPrepared",preparing:"chat.liveVoiceStatePreparing","needs-check":"chat.liveVoiceStateNeedsCheck",failed:"chat.liveVoiceStateFailed","missing-asset":"chat.liveVoiceStateMissingAsset"},h8={failed:!0,"needs-check":!0,"missing-asset":!0};async function h9(a){let b=await a.json().catch(()=>({}));if(!a.ok||!b||"object"!=typeof b||!("characters"in b))throw Error(b&&"object"==typeof b&&"message"in b&&"string"==typeof b.message?b.message:`HTTP ${a.status}`);return b}function ia(){let{t:a}=(0,x.s)(),b=(0,e.useId)(),c=(0,e.useId)(),[f,g]=(0,e.useState)(null),[h,i]=(0,e.useState)(null),[j,k]=(0,e.useState)(""),[l,m]=(0,e.useState)(!1),[n,o]=(0,e.useState)(!1);(0,e.useCallback)(async()=>{try{g(await h9(await fetch(h6,{cache:"no-store"})))}catch(b){i(b instanceof Error?b.message:a("chat.liveVoiceLoadFailed"))}},[a]);let p=f?.preparing===!0,q=(0,e.useCallback)(async a=>{o(!0),i(null);try{return g(await h9(await fetch(h6,a))),!0}catch(a){return i(a instanceof Error?a.message:String(a)),!1}finally{o(!1)}},[]),r=async()=>{let a=j.trim();a&&await q({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:a})})&&k("")};if(!f)return(0,d.jsx)("div",{className:h4().empty,children:h?`${a("chat.liveVoiceLoadFailed")}: ${h}`:"…"});let s=f.configured,t=h??f.lastError??null;return(0,d.jsxs)("div",{className:h4().scrollContent,children:[(0,d.jsxs)("header",{className:h4().contentHeader,children:[(0,d.jsx)("h2",{className:h4().contentTitle,children:a("chat.liveVoiceSettingsTitle")}),(0,d.jsx)("p",{className:h4().contentDescription,children:a("chat.liveVoiceSettingsDescription")})]}),(0,d.jsxs)("div",{className:h4().settingsBody,children:[(0,d.jsxs)("section",{className:h4().group,children:[(0,d.jsx)("h3",{className:h4().groupTitle,children:a("chat.liveVoiceKeyLabel")}),(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsx)("label",{htmlFor:b,className:h4().settingLabel,style:{display:"block"},children:a("chat.liveVoiceKeyLabel")}),(0,d.jsx)("div",{className:h4().settingDescription,children:a("chat.liveVoiceKeyHelp")}),s&&f.keyHint&&(0,d.jsx)("div",{className:h4().saveState,style:{overflowWrap:"anywhere"},children:a("chat.liveVoiceKeySaved",{hint:f.keyHint})})]}),(0,d.jsx)("div",{className:h4().settingControl,children:(0,d.jsx)("input",{id:b,className:h4().textInput,type:"password",autoComplete:"off",spellCheck:!1,value:j,disabled:n,onChange:a=>k(a.target.value),onKeyDown:a=>{"Enter"===a.key&&r()},placeholder:"sk_car_…"})})]}),(0,d.jsxs)("div",{className:h4().editorActions,children:[(0,d.jsx)("div",{}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8},children:[s&&(0,d.jsx)("button",{type:"button",className:h4().dangerButton,disabled:n||p,onClick:()=>void q({method:"DELETE"}),children:a("chat.liveVoiceKeyRemove")}),(0,d.jsx)("button",{type:"button",className:h4().primaryButton,disabled:n||!j.trim(),onClick:()=>void r(),children:a("chat.liveVoiceKeySave")})]})]})]}),(0,d.jsxs)("section",{className:h4().group,children:[(0,d.jsx)("h3",{className:h4().groupTitle,children:a("chat.liveVoicePrepare")}),(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{style:{display:"flex",gap:8,alignItems:"flex-start",minWidth:0},children:[(0,d.jsx)("input",{id:c,type:"checkbox",checked:l,onChange:a=>m(a.target.checked),style:{marginTop:3,flex:"none"}}),(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsx)("label",{htmlFor:c,className:h4().settingDescription,style:{display:"block",color:"var(--text)"},children:a("chat.liveVoiceConsent")}),(0,d.jsxs)("div",{className:h4().settingDescription,style:{marginTop:4},children:[a("chat.liveVoicePlanNote")," ",(0,d.jsx)("a",{href:"/audio/live/ACML-1.0.txt",target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)"},children:a("chat.liveVoiceLicense")})]})]})]}),(0,d.jsx)("div",{className:h4().settingControl,style:{alignItems:"center"},children:(0,d.jsx)("button",{type:"button",className:h4().primaryButton,disabled:n||p||!s||!l,onClick:()=>void q({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prepare:!0,acknowledged:!0})}),"aria-busy":p,children:p?a("chat.liveVoicePreparing"):a("chat.liveVoicePrepare")})})]}),t&&(0,d.jsx)("div",{className:h4().error,role:"alert",style:{overflowWrap:"anywhere"},children:t})]}),(0,d.jsxs)("section",{className:h4().group,children:[(0,d.jsx)("h3",{className:h4().groupTitle,children:a("chat.liveVoiceCharacters")}),(0,d.jsx)("ul",{"aria-live":"polite",style:{listStyle:"none",margin:0,padding:0},children:f.characters.map(b=>(0,d.jsxs)("li",{className:h4().settingRow,style:{minHeight:44},title:b.error,children:[(0,d.jsxs)("div",{className:h4().settingLabel,style:{marginBottom:0},children:[b.alias,"provisional"===b.tuning&&(0,d.jsxs)("span",{className:h4().settingDescription,style:{fontWeight:400},children:[" \xb7 ",a("chat.liveVoiceProvisional")]})]}),(0,d.jsx)("div",{className:h4().settingControl,style:{fontSize:12,color:h8[b.state]?"var(--danger)":"ready"===b.state?"var(--text)":"var(--text-muted)"},children:a(h7[b.state])})]},b.id))})]})]})]})}function ib(){let{t:a}=(0,x.s)(),b=(0,e.useId)(),c=(0,e.useId)(),[f,g]=(0,e.useState)(null),[h,i]=(0,e.useState)(""),[j,k]=(0,e.useState)(null),[l,m]=(0,e.useState)(!1),[n,o]=(0,e.useState)(!1),p=(0,e.useCallback)(async a=>{m(!0),k(null),o(!1);try{let b=await eU(a);g(b),i(String(b.uploadLimitMb)),o(!0)}catch(a){k(a instanceof Error?a.message:String(a))}finally{m(!1)}},[]);return f?(0,d.jsxs)("div",{className:h4().scrollContent,children:[(0,d.jsxs)("header",{className:h4().contentHeader,children:[(0,d.jsx)("h2",{className:h4().contentTitle,children:a("chat.attachmentSettingsTitle")}),(0,d.jsx)("p",{className:h4().contentDescription,children:a("chat.attachmentSettingsDescription")})]}),(0,d.jsx)("div",{className:h4().settingsBody,children:(0,d.jsxs)("section",{className:h4().group,children:[(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("label",{htmlFor:b,className:h4().settingLabel,style:{display:"block"},children:a("chat.attachmentUploadLimit")}),(0,d.jsx)("div",{className:h4().settingDescription,children:a("chat.attachmentUploadLimitHelp")})]}),(0,d.jsx)("div",{className:h4().settingControl,children:(0,d.jsx)("input",{id:b,className:h4().numberInput,type:"number",inputMode:"numeric",min:1,step:1,value:h,disabled:l,onChange:a=>i(a.target.value),onBlur:()=>{let b=h.trim();if(b===String(f.uploadLimitMb))return;let c=Number(b);if(!/^\d+$/.test(b)||!Number.isSafeInteger(c)||c<1){o(!1),k(a("chat.attachmentUploadLimitInvalid"));return}p({uploadLimitMb:c})},onKeyDown:a=>{"Enter"===a.key&&a.currentTarget.blur()}})})]}),(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{id:c,className:h4().settingLabel,children:a("chat.attachmentAutoCleanup")}),(0,d.jsx)("div",{className:h4().settingDescription,children:a("chat.attachmentAutoCleanupHelp",{days:f.orphanGraceDays})})]}),(0,d.jsx)("div",{className:h4().settingControl,children:(0,d.jsx)("button",{type:"button",className:h4().switch,"data-on":f.autoCleanupEnabled,"aria-pressed":f.autoCleanupEnabled,"aria-labelledby":c,disabled:l,onClick:()=>void p({autoCleanupEnabled:!f.autoCleanupEnabled})})})]}),j&&(0,d.jsx)("div",{className:h4().error,role:"alert",style:{overflowWrap:"anywhere"},children:j}),n&&!j&&(0,d.jsx)("div",{className:h4().saveState,role:"status",children:a("chat.attachmentSettingsSaved")})]})})]}):(0,d.jsx)("div",{className:h4().empty,children:j?`${a("chat.attachmentSettingsLoadFailed")}: ${j}`:"…"})}function ic({cwd:a}){let{t:b}=(0,x.s)(),[c,f]=(0,e.useState)(null),[g,h]=(0,e.useState)(null),[i,j]=(0,e.useState)(null),[k,l]=(0,e.useState)(null),[m,n]=(0,e.useState)({}),[o,p]=(0,e.useState)(null),[q,r]=(0,e.useState)(null),s=(0,e.useRef)(new Map),t=(0,e.useRef)(0),u=(0,e.useRef)(null),v=(0,e.useRef)(null),w=(0,e.useRef)(!1),y=(0,e.useCallback)(async()=>{if(w.current||"visible"!==document.visibilityState)return;let c=++t.current;u.current?.abort();let d=new AbortController;u.current=d;try{let e=a?`?include=${encodeURIComponent(a)}`:"",g=await fetch(`/api/project-trust${e}`,{cache:"no-store",signal:d.signal}),i=await g.json();if(c!==t.current||d.signal.aborted)return;if(!g.ok||!i.projects)throw Error(i.error??`HTTP ${g.status}`);let j=i.projects.find(a=>null===a.pending&&!a.error&&v.current?.some(b=>b.cwd===a.cwd&&("grant"===b.pending?a.trusted:"revoke"===b.pending&&!a.trusted)));v.current=i.projects,f(i.projects),h(null),j&&p({cwd:j.cwd,text:b("trust.doneApplied")})}catch(a){if(c!==t.current||d.signal.aborted)return;h(a instanceof Error?a.message:String(a))}finally{u.current===d&&(u.current=null)}},[a,b]);c?.some(a=>null!==a.pending);let z=(0,e.useCallback)(async(a,c)=>{if(!w.current){w.current=!0,++t.current,u.current?.abort(),l(a),j(null),r(a),p(null),n(b=>{let c={...b};return delete c[a],c});try{let d=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:a,action:c})}),e=await d.json();if(!d.ok)throw Error(e.error??`HTTP ${d.status}`);let g=v.current?.map(b=>b.cwd===a?{...e,cwd:a}:b)??null;v.current=g,f(g),"cancel"===c?p({cwd:a,text:b("trust.doneCancelled")}):e.error||null!==e.pending||p({cwd:a,text:b("trust.doneApplied")})}catch(b){n(c=>({...c,[a]:b instanceof Error?b.message:String(b)}))}finally{w.current=!1,l(null)}}},[b]);if(!c)return(0,d.jsxs)("div",{className:h4().empty,children:[g?b("trust.loadFailed",{error:g}):"…",g&&(0,d.jsx)("button",{type:"button",className:h4().linkButton,onClick:()=>void y(),children:b("trust.refresh")})]});let A=null!==k;return(0,d.jsxs)("div",{className:h4().scrollContent,children:[(0,d.jsxs)("header",{className:h4().contentHeader,children:[(0,d.jsx)("h2",{className:h4().contentTitle,children:b("trust.settingsNav")}),(0,d.jsx)("p",{className:h4().contentDescription,children:b("trust.settingsDescription")}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,marginTop:12},children:[(0,d.jsx)("button",{type:"button",className:h4().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:A,onClick:()=>void y(),children:b("trust.refresh")}),g&&(0,d.jsx)("div",{className:h4().error,role:"alert",children:b("trust.loadFailed",{error:g})})]})]}),(0,d.jsx)("div",{className:h4().settingsBody,children:(0,d.jsxs)("section",{className:h4().group,children:[0===c.length&&(0,d.jsx)("div",{className:h4().settingDescription,children:b("trust.settingsEmpty")}),c.map(a=>{var c;let e=k===a.cwd,f=i?.cwd===a.cwd?i:null,g=a.requiresTrust?a.trusted?b("trust.stateTrusted"):b("trust.stateRestricted"):b("trust.stateNotRequired"),h=m[a.cwd]??(a.error?b("trust.applyFailed",{error:a.error}):null);return(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsxs)("div",{className:h4().settingLabel,style:{display:"flex",alignItems:"center",gap:7},children:[(0,d.jsx)("span",{className:h4().statusDot,"data-off":!a.trusted||!a.requiresTrust,"aria-hidden":"true"}),(0,d.jsx)("span",{children:(c=a.cwd).split(/[\\/]/).filter(Boolean).pop()??c}),(0,d.jsx)("span",{className:h4().settingDescription,style:{fontWeight:600},children:g})]}),(0,d.jsx)("code",{className:h4().settingDescription,style:{display:"block",overflowWrap:"anywhere"},children:a.cwd}),(0,d.jsx)("div",{className:h4().saveState,children:b("trust.runtime",{sessions:a.runtime.sessions,running:a.runtime.running,loaded:a.requiresTrust?a.runtime.projectCodeLoaded:0})}),(0,d.jsxs)("div",{"aria-live":"polite",children:["grant"===a.pending&&(0,d.jsx)("div",{className:h4().settingDescription,children:b("trust.pendingGrant")}),"revoke"===a.pending&&(0,d.jsx)("div",{className:h4().settingDescription,children:b("trust.pendingRevoke",{count:a.runtime.projectCodeLoaded})}),f&&(0,d.jsx)("div",{className:h4().settingDescription,style:{color:"var(--text)"},children:"revoke"===f.action?b("trust.confirmRevoke"):f.again?b("trust.confirmTrustAgain"):b("trust.confirmGrant")}),o?.cwd===a.cwd&&(0,d.jsx)("div",{className:h4().saveState,children:o.text})]}),h&&(0,d.jsx)("div",{className:h4().error,role:"alert",children:h})]}),(0,d.jsx)("div",{ref:b=>{b?s.current.set(a.cwd,b):s.current.delete(a.cwd)},className:h4().settingControl,style:{flexWrap:"wrap",gap:8,alignItems:"flex-start"},children:f?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("button",{type:"button",className:h4().linkButton,style:{background:"transparent",cursor:"pointer"},autoFocus:!0,onClick:()=>{j(null),r(a.cwd)},children:b("trust.cancel")}),(0,d.jsx)("button",{type:"button",className:"revoke"===f.action?h4().dangerButton:h4().primaryButton,disabled:A,onClick:()=>void z(a.cwd,f.action),children:"revoke"===f.action?b("trust.revoke"):b("trust.confirm")})]}):e?(0,d.jsx)("button",{type:"button",className:h4().primaryButton,disabled:!0,children:b("trust.working")}):(0,d.jsxs)(d.Fragment,{children:["grant"===a.pending&&(0,d.jsx)("button",{type:"button",className:h4().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:A,onClick:()=>void z(a.cwd,"cancel"),children:b("trust.cancelSchedule")}),a.requiresTrust&&!a.trusted&&"grant"!==a.pending&&(0,d.jsx)("button",{type:"button",className:h4().primaryButton,disabled:A,onClick:()=>j({cwd:a.cwd,action:"grant",again:"revoke"===a.pending}),children:"revoke"===a.pending?b("trust.trustAgain"):b("trust.trustProject")}),a.trusted&&(0,d.jsx)("button",{type:"button",className:h4().dangerButton,disabled:A,onClick:()=>j({cwd:a.cwd,action:"revoke",again:!1}),children:b("trust.revoke")})]})})]},a.cwd)})]})})]})}let id=JSON.parse('{"tabs":{"appearance":"외관","model":"모델","interaction":"상호작용","context":"컨텍스트","memory":"메모리","files":"파일","shell":"Shell","tools":"도구","tasks":"작업","providers":"제공자"},"groups":{"Theme":"테마","Status Line":"상태 표시줄","Display":"표시","Images":"이미지","Thinking":"사고","Sampling":"샘플링","Prompt":"프롬프트","Retry & Fallback":"재시도 및 폴백","Advisor":"어드바이저","Prewalk":"Prewalk","Vision":"비전","Input":"입력","Approvals":"승인","Notifications":"알림","Speech":"음성","Collab":"협업","Magic Keywords":"매직 키워드","Startup & Updates":"시작 및 업데이트","Power (macOS)":"전원 (macOS)","Agent":"에이전트","Git":"Git","General":"일반","Compaction":"압축","Rules (TTSR)":"규칙 (TTSR)","Experimental":"실험적 기능","Auto-Learn":"자동 학습","Mnemopi":"Mnemopi","Hindsight":"Hindsight","Editing":"편집","Reading":"읽기","Read Summaries":"읽기 요약","LSP":"LSP","Bash":"Bash","Eval & Runtimes":"평가 및 런타임","Available Tools":"사용 가능한 도구","Todos":"할 일","Grep & Browser":"Grep 및 브라우저","Computer":"컴퓨터","GitHub":"GitHub","Output Limits":"출력 제한","Execution":"실행","Discovery & MCP":"탐색 및 MCP","Developer":"개발자","Modes":"모드","Subagents":"서브에이전트","Isolation":"격리","Commands & Skills":"명령 및 스킬","Services":"서비스","Fireworks":"Fireworks","Tiny Model":"Tiny Model","Protocol":"프로토콜","Timeouts":"타임아웃","Privacy":"개인정보"},"shell":{"Loading omp settings…":"omp 설정을 불러오는 중…","Settings unavailable":"설정을 사용할 수 없음","Matching canonical /settings entries across every category.":"모든 카테고리에서 표준 /settings 항목을 일치시킨다.","Canonical omp /settings values. Changes are saved immediately to the shared agent configuration.":"표준 omp /settings 값이다. 변경 사항은 공유 에이전트 설정에 즉시 저장된다.","Saved. Reload the active session to apply runtime settings.":"저장됨. 런타임 설정을 적용하려면 활성 세션을 다시 불러온다.","Reloading…":"다시 불러오는 중…","Reload session":"세션 다시 불러오기","No settings match this search.":"이 검색과 일치하는 설정이 없다.","Search /settings":"/settings 검색","Configuration":"구성","OMP settings":"OMP 설정","Close settings":"설정 닫기","Global configuration":"전역 구성","Settings":"설정","Search":"검색","Models":"모델","Themes":"테마","Skills":"스킬","Plugins":"플러그인","MCP":"MCP","Loading themes…":"테마를 불러오는 중…","Themes unavailable":"테마를 사용할 수 없음","Active on web":"웹에서 활성","Preview ":"미리보기 ","The web interface uses the same dark and light theme mappings as omp. Changes are persisted to ":"웹 인터페이스는 omp와 동일한 다크 및 라이트 테마 매핑을 사용한다. 변경 사항은 다음에 저장된다: "," and applied here immediately.":" 그리고 여기에 즉시 적용된다."," mapping":" 매핑","requires a project":"프로젝트가 필요하다"},"fields":{"theme.dark":{"label":"다크 테마","description":"터미널 배경이 어두울 때 사용하는 테마이다"},"theme.light":{"label":"라이트 테마","description":"터미널 배경이 밝을 때 사용하는 테마이다"},"symbolPreset":{"label":"심볼 프리셋","description":"아이콘과 기호에 사용하는 글리프 세트이다 (Unicode, Nerd Font, ASCII)"},"colorBlindMode":{"label":"색맹 모드","description":"diff 추가 표시에 초록색 대신 파란색을 사용한다"},"statusLine.preset":{"label":"상태 표시줄 프리셋","description":"미리 구성된 상태 표시줄 설정이다"},"statusLine.separator":{"label":"상태 표시줄 구분자","description":"세그먼트 사이 구분자의 스타일이다"},"statusLine.sessionAccent":{"label":"세션 강조색","description":"에디터 테두리와 상태 표시줄 여백에 세션 이름 색상을 사용한다"},"statusLine.transparent":{"label":"투명 상태 표시줄","description":"상태 표시줄에 테마의 `statusLineBg` 대신 터미널 기본 배경을 사용한다. Powerline 끝 캡은 주변 터미널로 이어지려면 대비되는 채움색이 필요하므로 제거된다."},"statusLine.compactThinkingLevel":{"label":"간결한 thinking 레벨","description":"thinking 레벨을 별도의 ` \xb7 <level>` 접미사 대신 모델 이름에 아이콘 하나로 표시한다."},"statusLine.showHookStatus":{"label":"hook 상태 표시","description":"상태 표시줄 아래에 hook 상태 메시지를 표시한다"},"terminal.showImages":{"label":"인라인 이미지 표시","description":"터미널에 이미지를 인라인으로 렌더링한다"},"images.autoResize":{"label":"이미지 자동 크기 조정","description":"모델 호환성을 높이기 위해 큰 이미지를 최대 2000x2000으로 축소한다"},"images.blockImages":{"label":"이미지 차단","description":"이미지가 LLM 제공자에게 전송되지 않도록 한다"},"terminal.showProgress":{"label":"네이티브 터미널 진행 표시","description":"에이전트나 컨텍스트 유지 작업이 실행되는 동안 OSC 9;4 부정형 진행 표시를 내보낸다"},"tui.textSizing":{"label":"큰 제목 (Kitty)","description":"Kitty의 OSC 66 text-sizing 프로토콜을 사용해 Markdown H1 제목을 2배 크기로 렌더링한다. Kitty 터미널에서만 적용되며 그 외에서는 무시된다. 기본값은 꺼짐이다."},"tui.renderMermaid":{"label":"Mermaid 다이어그램 렌더링","description":"Mermaid 코드 블록을 ASCII 다이어그램으로 렌더링한다"},"tui.codexResetFireworks":{"label":"Codex 리셋 불꽃놀이","description":"예정에 없던 Codex 주간 사용량 리셋과 새로 적립된 저장 리셋을 화면 상단 1/3의 불꽃놀이 오버레이로 축하하며, Escape를 누를 때까지 유지된다"},"tui.titleState":{"label":"터미널 제목 실행 상태","description":"터미널 제목의 구분자에 에이전트 실행 상태를 표시한다 — 작업 중에는 애니메이션 스피너(Windows에서는 고정된 \':\'), 사용자 차례일 때는 \'>\', 에이전트가 사용자를 기다릴 때는 \'!\'이다"},"tui.hyperlinks":{"label":"터미널 하이퍼링크","description":"터미널 자체의 클릭 열기를 위해 경로와 URL을 OSC 8 하이퍼링크로 감싼다 (auto: 지원 여부 감지, off: 사용 안 함, always: 무조건 사용)"},"tui.tight":{"label":"조밀한 레이아웃","description":"터미널 출력 좌우의 1문자 가로 여백을 제거한다"},"tui.scrollbackRebuild":{"label":"스크롤백 다시 쓰기","description":"블록의 최종 형태가 실시간 미리보기를 대체할 때 터미널 스크롤백을 지우고 다시 출력한다. 꺼짐(기본값)일 때는 오래된 미리보기 사본이 기록에 남고 최종 내용이 그 아래에 추가된다."},"display.shimmer":{"label":"셔머","description":"작업/로딩 메시지의 애니메이션 스타일이다"},"display.smoothStreaming":{"label":"부드러운 스트리밍","description":"청크가 도착하는 동안 어시스턴트 텍스트와 스트리밍되는 도구 입력을 부드럽게 표시한다"},"display.hideToolActivity":{"label":"도구 활동 숨김","description":"모델이 시작한 도구 호출과 결과를 대화 기록에서 숨긴다"},"display.showTokenUsage":{"label":"토큰 사용량 표시","description":"어시스턴트 메시지에 턴별 토큰 사용량을 표시한다"},"display.cacheMissMarker":{"label":"캐시 미스 표시","description":"요청이 프롬프트 캐시를 놓친(miss) 어시스턴트 턴 위에 구분선을 표시한다"},"display.collapseCompacted":{"label":"압축 히스토리 접기","description":"라이브 트랜스크립트에서 compaction 이전 히스토리를 요약 구분선 뒤로 접는다. 비활성화하면 각 compaction 지점에 구분선을 둔 채 전체 트랜스크립트를 인라인으로 유지한다"},"showHardwareCursor":{"label":"하드웨어 커서 표시","description":"IME 지원을 위해 터미널 커서를 표시한다"},"tui.imeSafeCursor":{"label":"IME 안전 프롬프트 레이아웃","description":"macOS IME preedit가 프롬프트 하단 테두리를 밀어내지 못하도록 테두리를 별도 행으로 옮긴다"},"task.showResolvedModelBadge":{"label":"확정 모델 배지 표시","description":"task 위젯 상태줄에 각 subagent가 실제로 사용한 모델 ID를 표시한다"},"advisor.enabled":{"label":"Advisor 활성화","description":"\'advisor\' 역할에 배정된 두 번째 모델을 함께 두어 각 턴을 수동적으로 검토하고 메모를 주입한다."},"prewalk.enabled":{"label":"Prewalk 활성화","description":"활성 모델로 시작한 뒤, plan nudge의 todo 목록이 생성된 이후 첫 edit/write 시점에 빠르고 저렴한 모델(기본값은 \'smol\' 역할)로 전환한다 — 강한 모델이 계획하고 todo를 확정하며 구현을 시작한 후 인계한다. 세션별로 --prewalk / --no-prewalk로 재정의할 수 있다."},"advisor.syncBacklog":{"label":"Advisor 동기화 백로그","description":"advisor가 이 턴 수만큼 뒤처지면 메인 에이전트를 최대 30초 동안 멈춘다. Off로 두면 따라잡기 지연을 비활성화한다."},"advisor.immuneTurns":{"label":"Advisor 면역 턴","description":"advisor의 concern 또는 blocker가 한 번 인터럽트한 뒤에는, 이 primary 턴 수 동안 이후 concern/blocker를 인터럽트 없이 전달한다."},"modelRoleStorage":{"label":"모델 역할 저장소","description":"모델 선택기의 역할 배정이 저장되는 위치이다"},"images.describeForTextModels":{"label":"텍스트 모델용 이미지 설명","description":"vision을 지원하지 않는 모델에 이미지가 첨부되면, 이미지를 버리지 않고 local:// 아래에 저장한 뒤 vision 지원 모델이 만든 설명을 주입한다"},"defaultThinkingLevel":{"label":"Thinking 레벨","description":"thinking을 지원하는 모델의 추론 깊이이다"},"hideThinkingBlock":{"label":"Thinking 블록 숨김","description":"어시스턴트 응답에서 thinking 블록을 숨긴다"},"proseOnlyThinking":{"label":"산문 전용 Thinking","description":"thinking 요약에서 코드 블록을 제외하고 생략 부호로 대체한다"},"omitThinking":{"label":"Thinking 요약 생략","description":"응답에서 thinking 요약을 완전히 생략하도록 업스트림 provider에 지시한다(지원되는 경우)"},"externalThinking":{"label":"외부 Thinking","description":"사용자에게 표시되지 않는 비공개 스크래치패드이다. 지원되는 GPT, Claude, Gemini의 reasoning을 비활성화한다"},"model.loopGuard.enabled":{"label":"Loop Guard","description":"모델 reasoning과 산문에 대한 자동 스트림 루프 감지를 활성화한다"},"model.loopGuard.checkAssistantContent":{"label":"Loop Guard 산문 검사","description":"thinking 로그 외에 어시스턴트 산문 메시지에도 loop guard를 적용한다"},"model.loopGuard.toolCallReminder":{"label":"Loop Guard 도구 호출 알림","description":"Gemini reasoning 스트림이 도구를 호출하지 않고 계획 헤더를 연속으로 다수 출력하면 중단하고 도구 호출을 요구하는 알림을 주입한다(Loop Guard 필요)"},"model.toolCallLoopGuard.enabled":{"label":"도구 호출 Loop Guard","description":"여러 턴에 걸친 동일한 연속 도구 호출을 감지하고 교정용 steer를 주입한다"},"inlineToolDescriptors":{"label":"인라인 도구 디스크립터","description":"시스템 프롬프트에 전체 도구 디스크립터를 렌더링하고 provider 도구 스키마에서 최상위/중첩 description을 제거해 디스크립터 텍스트를 한 번만 전송한다. Auto는 Gemini 모델에서 이를 활성화하고 그 외에는 비활성화한다"},"includeModelInPrompt":{"label":"프롬프트에 모델 포함","description":"에이전트가 자신이 어떤 모델인지 알 수 있도록 시스템 프롬프트에 활성 모델 식별자를 노출한다"},"includeWorkspaceTree":{"label":"워크스페이스 트리 포함","description":"시스템 프롬프트에 워크스페이스 디렉터리 트리를 렌더링한다. 경고: 파일이 수정되면 세션 간 프롬프트 캐싱이 깨질 수 있다."},"personality":{"label":"성격","description":"시스템 프롬프트의 personality 블록에 렌더링되는 의사소통 스타일이다"},"temperature":{"label":"Temperature","description":"샘플링 temperature이다(0 = 결정적, 1 = 창의적, -1 = provider 기본값)"},"topP":{"label":"Top P","description":"Nucleus 샘플링 컷오프이다(0-1, -1 = provider 기본값)"},"topK":{"label":"Top K","description":"상위 K개 토큰에서 샘플링한다(-1 = provider 기본값)"},"minP":{"label":"Min P","description":"최소 확률 임계값 (0-1, -1 = provider 기본값)"},"presencePenalty":{"label":"Presence Penalty","description":"이미 등장한 토큰을 도입하는 데 대한 페널티 (-1 = provider 기본값)"},"repetitionPenalty":{"label":"Repetition Penalty","description":"반복된 토큰에 대한 페널티 (-1 = provider 기본값)"},"textVerbosity":{"label":"텍스트 상세도","description":"OpenAI Responses 및 Codex 응답의 상세도 (low, medium, high)"},"tier.openai":{"label":"서비스 티어 — OpenAI","description":"OpenAI / OpenAI-Codex 요청 및 OpenRouter를 경유하는 OpenAI 계열 모델의 처리 티어 (none = 생략). `service_tier`로 전송한다."},"tier.anthropic":{"label":"서비스 티어 — Anthropic","description":"Claude 요청의 처리 티어. `priority`는 지원되는 직접 Anthropic 모델에서 fast 모드(`speed: \\"fast\\"`)를 활성화하며, Bedrock/Vertex Claude 및 OpenRouter 경유에서는 무시된다."},"tier.google":{"label":"서비스 티어 — Google","description":"Gemini(Google AI Studio + Vertex) 요청 및 OpenRouter를 경유하는 Google 계열 모델의 처리 티어 (none = 생략). 최상위 `serviceTier` 필드로 전송한다."},"tier.subagent":{"label":"서비스 티어 — 서브에이전트","description":"생성된 task/eval 서브에이전트의 서비스 티어. Inherit = 메인 에이전트의 실시간 계열별 티어를 따른다(/fast를 추적한다). 값을 지정하면 서브에이전트 모델이 속한 계열에 그 값을 적용한다."},"tier.advisor":{"label":"서비스 티어 — Advisor","description":"advisor 모델의 서비스 티어. None = 표준 처리, Inherit = 메인 에이전트의 실시간 계열별 티어를 따른다. 값을 지정하면 advisor 모델의 계열에 그 값을 적용한다."},"retry.maxRetries":{"label":"재시도 횟수","description":"API 오류 시 최대 재시도 횟수"},"retry.modelFallback":{"label":"재시도 모델 폴백","description":"재시도 복구 시 설정된 폴백 모델로 전환하도록 허용한다"},"retry.usageAwareFallback":{"label":"사용량 인식 폴백","description":"신뢰할 수 있는 coding-plan 할당량 보고를 활용해, 하드 사용량 한도에 도달하기 전에 동일 provider 계정을 먼저 사용하고 그다음 설정된 폴백 모델을 사용한다. 일반 설정 API 키는 제외한다."},"retry.usageReservePct":{"label":"예비 마진","description":"남은 비율이 이 값 미만이면 coding-plan 모델이 한도에 근접한 것으로 간주한다. 사용량을 알 수 없거나 매핑되지 않은 경우 주 모델을 유지한다."},"retry.usageReservePolicy":{"label":"예비 정책","description":"동일 provider의 모든 coding-plan 계정이 예비 마진 안에 들어왔을 때의 동작이다."},"retry.fallbackChains":{"label":"재시도 폴백 체인","description":"모델 역할, 모델 선택자(\\"provider/model-id\\"), 또는 provider 와일드카드(\\"provider/*\\")를 순서가 있는 폴백 선택자에 매핑하는 JSON 객체이다. 예: {\\"default\\":[\\"openai/gpt-4o-mini\\"],\\"google-antigravity/*\\":[\\"google/*\\",\\"google-vertex/*\\"]}. 모델 지향 키는 역할과 무관하게 해당 모델/provider가 활성일 때마다 적용되며, \\"provider/*\\" 항목은 실패한 모델의 id를 유지한 채 provider만 교체한다. id 접두사 와일드카드(\\"openrouter/google/*\\")는 실패한 모델의 순수 id에 접두사를 다시 붙이고(google-antigravity/gemini-x -> openrouter/google/gemini-x), 키로 사용될 때는 해당 접두사 아래의 그 provider id에만 매칭된다."},"retry.fallbackRevertPolicy":{"label":"폴백 복귀 정책","description":"폴백 이후 주 모델로 되돌아가는 시점이다"},"providers.anthropic.serverSideFallback":{"label":"Anthropic 서버 사이드 폴백 (Fable 5)","description":"Claude Fable 5 / Mythos 5 요청이 Anthropic의 안전 분류기에 의해 차단되면 서버 사이드에서 Claude Opus 4.8로 재시도한다(Anthropic `server-side-fallback-2026-06-01` 베타). 옵트인 방식이며, 끄면 모든 요청에 대해 폴백 이전 동작이 유지된다."},"providers.autoThinkingModel":{"label":"Auto Thinking 모델","description":"`auto` thinking 레벨의 난이도 분류기이다. 기본값은 온라인(/models의 TINY 역할, 없으면 smol)이며, 로컬 온디바이스 모델도 사용할 수 있다"},"providers.autoThinkingMaxEffort":{"label":"Auto Thinking 상한","description":"`auto` 분류기가 도달할 수 있는 최고 effort이다. `xhigh`는 분류기를 최상위보다 한 단계 아래로 유지해 명시적인 `ultrathink`만 `max`에 도달하게 하며, `max`는 분류기가 예외적이라고 판단한 턴이 이를 노출하는 모델에서 최상위 티어로 과금되도록 허용한다."},"autoResume":{"label":"자동 재개","description":"현재 디렉터리의 가장 최근 세션을 자동으로 재개한다"},"power.sleepPrevention":{"label":"절전 방지","description":"활성 세션 동안 macOS 절전을 방지한다. 각 레벨은 누적되며, 하위 레벨의 플래그를 모두 포함한다."},"git.enabled":{"label":"Git 통합 활성화","description":"TUI에 git 브랜치, 상태, PR 정보를 표시하고 저장소 메타데이터를 감시한다."},"steeringMode":{"label":"Steering 모드","description":"에이전트가 작업하는 동안 대기 중인 메시지를 처리하는 방식이다"},"followUpMode":{"label":"후속 메시지 모드","description":"턴이 완료된 후 후속 메시지를 처리하는 방식이다"},"interruptMode":{"label":"인터럽트 모드","description":"steering 메시지가 도구 실행을 중단하는 시점이다"},"loop.mode":{"label":"Loop 모드","description":"/loop 반복 사이에 프롬프트를 다시 제출하기 전에 일어나는 동작이다"},"doubleEscapeAction":{"label":"이중 Escape 동작","description":"편집기가 비어 있는 상태에서 Escape를 두 번 누를 때의 동작이다"},"treeFilterMode":{"label":"세션 트리 필터","description":"세션 트리를 열 때의 기본 필터 모드이다"},"autocompleteMaxVisible":{"label":"자동완성 항목 수","description":"자동완성 드롭다운에 표시되는 최대 항목 수이다 (3-20)"},"emojiAutocomplete":{"label":"이모지 자동완성","description":"`:name:` 숏코드로 이모지를 제안하고 `:D` 또는 `:-)` 같은 텍스트 이모티콘을 확장한다"},"paste.largeMenuThreshold":{"label":"대용량 붙여넣기 메뉴","description":"붙여넣기가 이 줄 수에 도달하면 코드 블록으로 감싸기, XML 태그로 감싸기, 파일로 저장하기 메뉴를 제공한다. 0은 메뉴를 비활성화한다(대용량 붙여넣기는 여전히 [Paste] 마커로 축약된다)."},"startup.quiet":{"label":"조용한 시작","description":"환영 화면과 시작 상태 메시지를 건너뛴다"},"startup.showSplash":{"label":"시작 스플래시 표시","description":"설정을 다시 실행하지 않고 일반 대화형 시작 시 전체 애니메이션 설정 스플래시를 표시한다. 조용한 시작은 여전히 이를 억제한다."},"startup.setupWizard":{"label":"설정 위저드","description":"새로 추가된 온보딩 단계를 설정 버전마다 한 번 표시한다"},"startup.checkUpdate":{"label":"업데이트 확인","description":"시작 시 omp 업데이트를 확인한다"},"marketplace.autoUpdate":{"label":"마켓플레이스 자동 업데이트","description":"시작 시 플러그인 업데이트를 확인한다"},"startup.changelogMode":{"label":"시작 변경 내역","description":"업데이트 노트를 요약으로 시작할지, 전체 상세로 시작할지, 숨긴 상태로 둘지 선택한다"},"magicKeywords.enabled":{"label":"매직 키워드","description":"단독으로 쓰인 ultrathink, orchestrate, workflowz 키워드에 대한 숨겨진 공지를 활성화한다"},"magicKeywords.ultrathink":{"label":"Ultrathink 키워드","description":"단독으로 쓰인 ultrathink가 최대 자동 사고를 요청하고 숨겨진 공지를 덧붙이도록 한다"},"magicKeywords.orchestrate":{"label":"Orchestrate 키워드","description":"단독으로 쓰인 orchestrate가 숨겨진 멀티 에이전트 오케스트레이션 공지를 덧붙이도록 한다"},"magicKeywords.workflow":{"label":"Workflow 키워드","description":"단독으로 쓰인 workflowz가 숨겨진 eval 워크플로 공지를 덧붙이도록 한다"},"completion.notify":{"label":"완료 알림","description":"에이전트가 턴을 마쳤을 때 알린다"},"error.notify":{"label":"오류 알림","description":"에이전트가 오류로 중단되었을 때 알린다"},"ask.timeout":{"label":"Ask 타임아웃","description":"이 초가 지나면 권장 ask 옵션을 자동 선택한다 (0은 비활성화)"},"ask.notify":{"label":"Ask 알림","description":"ask 도구가 입력을 기다릴 때 알린다"},"recap.enabled":{"label":"유휴 요약","description":"터미널이 유휴 상태가 된 후 현재 상황에 대한 간단한 LLM 요약을 생성한다"},"recap.idleSeconds":{"label":"유휴 요약 지연","description":"요약을 표시하기 전 유휴 상태로 대기하는 초이다"},"collab.relayUrl":{"label":"Relay URL","description":"/collab에서 사용하는 relay이다 (wss://host[:port])"},"collab.webUrl":{"label":"웹 UI URL","description":"/collab 링크에 사용되는 브라우저 UI이다. 비어 있으면 collab.relayUrl에서 파생되며, 명시적인 http://는 localhost에서만 사용된다"},"collab.displayName":{"label":"표시 이름","description":"다른 collab 참가자에게 표시되는 이름이다 (기본값: OS 사용자 이름)"},"share.serverUrl":{"label":"Share 서버","description":"/share에서 사용하는 공유 뷰어/업로드 기준 주소이다 (암호화된 blob 업로드 + 뷰어, 링크는 <base>/<id>#<key> 형식이다)"},"share.store":{"label":"Share 저장소","description":"/share가 암호화된 세션 blob을 업로드하는 위치이다"},"share.redactSecrets":{"label":"공유 시 비밀정보 삭제","description":"업로드 전에 /share 스냅샷에 대해 secret obfuscator를 실행한다(secrets.* 설정을 사용한다)"},"stt.enabled":{"label":"음성 인식","description":"마이크를 통한 speech-to-text 입력을 활성화한다"},"stt.modelName":{"label":"음성 모델","description":"로컬 온디바이스 음성 모델이다. Parakeet TDT v3(sherpa-onnx)가 SoTA 기본값이며, Whisper base/small/large-v3-turbo 등급(transformers.js)은 크기를 다국어 지원과 맞바꾼다. 첫 사용 시 다운로드된다."},"stt.submitTrigger":{"label":"음성 입력 전송 트리거","description":"음성 받아쓰기가 자동으로 전송되는 시점을 선택한다: Never, Release(2단어 이상), 완전한 문장으로 Release, 또는 When I Say Submit."},"tools.approval":{"label":"도구 승인 정책","description":"도구별 승인 정책이다. \'allow\'는 자동 승인, \'prompt\'는 확인 요구, \'deny\'는 차단으로 설정한다. 재정의는 모든 승인 모드에서 적용된다."},"tools.approvalMode":{"label":"도구 승인","description":"도구 호출의 기본 승인 동작이다. \'Always ask\'는 읽기 전용 도구만 자동 승인한다. \'Write\'는 읽기 및 workspace-write 도구를 자동 승인한다. \'Yolo\'는 모든 등급을 자동 승인하지만, 사용자 정책에 따라 확인이나 차단이 발생할 수 있다."},"features.unexpectedStopDetection":{"label":"예상치 못한 중단","description":"어시스턴트가 예상치 못하게 멈추면 자동으로 복구한다. \'기계적\'(기본값)은 표시할 답변 없이 끝난 경우를 재시도하고 도구 호출이 있었던 중단은 제외한다. \'스마트\'는 기계적 감지에 더해 작은 모델로 텍스트만 남긴 중단도 판별하며, \'사용 안 함\'은 감지를 끈다."},"contextPromotion.enabled":{"label":"컨텍스트 자동 승격","description":"컨텍스트 초과 시 compaction 대신 더 큰 컨텍스트 모델로 승격한다"},"compaction.enabled":{"label":"자동 Compact","description":"컨텍스트가 너무 커지면 자동으로 compact한다"},"compaction.midTurnEnabled":{"label":"턴 중간 Compaction","description":"다음 provider 요청 전에 안전한 턴 중간 tool-loop 경계에서 임계값을 확인한다"},"compaction.strategy":{"label":"Compaction 전략","description":"제자리 context-full 유지, auto-handoff, surgical shake(무거운 콘텐츠 제거), snapcompact(히스토리를 밀집 이미지로 보관) 중에서 선택하거나 자동 유지를 비활성화(off)한다"},"compaction.thresholdPercent":{"label":"Compaction 임계값","description":"컨텍스트 유지의 퍼센트 임계값이다. Default로 설정하면 기존 reserve 기반 동작을 사용한다"},"compaction.thresholdTokens":{"label":"Compaction 토큰 한도","description":"컨텍스트 유지의 고정 토큰 한도이다. 설정하면 퍼센트 값을 재정의한다"},"compaction.handoffSaveToDisk":{"label":"Handoff 문서 저장","description":"auto-handoff 흐름에서 생성된 handoff 문서를 markdown 파일로 저장한다"},"compaction.remoteEnabled":{"label":"원격 Compaction","description":"가능한 경우 로컬 요약 대신 원격 compaction 엔드포인트를 사용한다"},"compaction.remoteStreamingV2Enabled":{"label":"원격 Compaction V2","description":"호환되는 원격 compaction 모델에 대해 Responses 스트리밍 compaction을 사용한다"},"compaction.idleEnabled":{"label":"유휴 Compaction","description":"토큰 수가 임계값을 넘으면 유휴 상태에서 컨텍스트를 compact한다"},"compaction.idleThresholdTokens":{"label":"유휴 Compaction 임계값","description":"유휴 compaction이 트리거되는 토큰 수 기준이다"},"compaction.idleTimeoutSeconds":{"label":"유휴 Compaction 지연","description":"compact하기 전 유휴 상태로 대기하는 초이다"},"compaction.supersedeReads":{"label":"오래된 읽기 대체","description":"같은 파일을 다시 읽으면 이전 읽기 결과를 정리한다(캐시 인식, 매 턴 실행)"},"compaction.dropUseless":{"label":"무의미한 결과 제거","description":"컨텍스트상 무용하다고 표시된 도구 결과(일치 없음, 시간 초과된 대기)를 소비된 후 정리한다(캐시 인식)"},"snapcompact.systemPrompt":{"label":"Snapcompact 시스템 프롬프트","description":"실험적 기능이다: 선택한 시스템 프롬프트 텍스트를 밀집 PNG 이미지로 렌더링해 첫 사용자 메시지에 첨부한다(비전 모델 전용). 토큰을 절약하지만 이미지화된 텍스트의 prompt caching을 잃는다."},"snapcompact.toolResults":{"label":"Snapcompact 도구 결과","description":"실험적 기능이다: 큰 과거 도구 결과를 텍스트 대신 밀집 PNG 이미지로 렌더링한다(비전 모델 전용). 누적된 읽기/검색 출력의 토큰을 절약한다."},"tools.format":{"label":"도구 호출 모드","description":"도구가 모델에 노출되는 방식을 제어한다. Auto는 provider-native 도구 호출을 사용하지만, 선택된 모델이 이를 지원하지 않는다고 표시된 경우 GLM owned dialect로 대체한다. Native는 provider-native 도구를 강제하고, 나머지 값은 지정된 owned dialect를 강제한다. 세션 시작 시 적용된다."},"snapcompact.shape":{"label":"Snapcompact 형태","description":"snapcompact가 텍스트를 출력하는 프레임 형태이다(compaction 보관 및 인라인 이미지화). Auto는 현재 모델에 맞게 조정된 형태를 선택한다."},"branchSummary.enabled":{"label":"브랜치 요약","description":"브랜치를 떠날 때 요약을 요청한다"},"ttsr.enabled":{"label":"TTSR","description":"출력이 규칙 패턴과 일치하면 스트리밍 도중에 에이전트를 중단한다(Time-Traveling Stream Rules)"},"ttsr.contextMode":{"label":"TTSR 컨텍스트 모드","description":"TTSR이 발동할 때 부분 출력을 어떻게 처리할지 정한다"},"ttsr.interruptMode":{"label":"TTSR 인터럽트 모드","description":"스트리밍 도중에 중단할지, 완료 후 경고를 주입할지 정한다"},"ttsr.repeatMode":{"label":"TTSR 반복 모드","description":"규칙이 반복되는 방식을 정한다: 세션당 한 번 또는 메시지 간격 이후"},"ttsr.repeatGap":{"label":"TTSR 반복 간격","description":"규칙이 다시 발동할 수 있기까지의 메시지 수이다"},"ttsr.builtinRules":{"label":"기본 제공 규칙","description":"에이전트에 기본 포함된 규칙을 로드한다(ttsr.disabledRules로 개별 해제 가능)"},"memory.backend":{"label":"메모리 백엔드","description":"끄기, 로컬 요약 파이프라인, Mnemopi SQLite, 또는 Hindsight 원격 메모리 중에서 선택한다"},"autolearn.enabled":{"label":"자동 학습 (실험적)","description":"에이전트가 멈춘 뒤 교훈을 메모리에 기록하고 격리된 관리형 skill을 생성/보강하도록 유도한다"},"autolearn.autoContinue":{"label":"중지 시 캡처 자동 실행","description":"켜면 중지 시 비공개 캡처 턴을 한 번 자동 실행한다(추가 토큰을 사용한다). 끄면 상시 자동 학습 안내만 남는다."},"mnemopi.dbPath":{"label":"Mnemopi DB 경로","description":"선택적 SQLite DB 경로이다. 기본값은 에이전트 memories 디렉터리이다."},"mnemopi.bank":{"label":"Mnemopi 뱅크","description":"선택적 공유 뱅크 기본 이름이다. per-project 모드는 이를 기반으로 프로젝트 로컬 뱅크를 파생한다."},"mnemopi.scoping":{"label":"Mnemopi 스코핑","description":"global = 공유 뱅크 하나, per-project = cwd별 격리 뱅크, per-project-tagged = 프로젝트 로컬 쓰기에 global recall 가시성을 더한 방식이다"},"mnemopi.embeddingVariant":{"label":"임베딩 variant","description":"로컬 임베딩 모델 계열이다. en = 더 강력한 영어 모델, multilingual = 교차 언어 모델이다. 이를 변경하면 다음 시작 시 기존 메모리 임베딩을 다시 생성한다."},"mnemopi.autoRecall":{"label":"Mnemopi 자동 recall","description":"각 세션의 첫 턴에 로컬 메모리를 recall한다"},"mnemopi.autoRetain":{"label":"Mnemopi 자동 retain","description":"완료된 대화 턴을 로컬 Mnemopi 메모리에 retain한다"},"mnemopi.polyphonicRecall":{"label":"Mnemopi 폴리포닉 recall","description":"reciprocal rank fusion으로 융합한 4-voice recall(vector, graph, fact, temporal)을 활성화한다"},"mnemopi.enhancedRecall":{"label":"Mnemopi 향상된 recall","description":"반복되거나 유사한 recall 쿼리를 위한 계층형 쿼리 결과 캐시를 활성화한다"},"mnemopi.proactiveLinking":{"label":"Mnemopi 선제적 링킹","description":"새 메모리를 저장하는 즉시 episodic 그래프에 수집해 관련 엔터티 및 메모리와 연결한다"},"mnemopi.noEmbeddings":{"label":"Mnemopi 임베딩 비활성화","description":"vector 임베딩 대신 결정적인 FTS 전용 recall을 강제한다"},"mnemopi.embeddingModel":{"label":"Mnemopi 임베딩 모델","description":"고급: variant를 재정의하는 명시적 임베딩 모델 id이다. 비워 두면 mnemopi.embeddingVariant를 사용한다."},"mnemopi.embeddingApiUrl":{"label":"Mnemopi 임베딩 API URL","description":"Mnemopi에 전달하는 선택적 OpenAI 호환 임베딩 엔드포인트이다"},"mnemopi.embeddingApiKey":{"label":"Mnemopi 임베딩 API 키","description":"Mnemopi에 전달하는 선택적 임베딩 API 키이다"},"mnemopi.llmMode":{"label":"Mnemopi LLM 모드","description":"LLM 미사용, 온라인 tiny 모델(/models의 TINY 역할, 없으면 @smol), 또는 원격 OpenAI 호환 엔드포인트를 사용한다"},"mnemopi.llmBaseUrl":{"label":"Mnemopi LLM Base URL","description":"Mnemopi 원격 모드를 위한 선택적 OpenAI 호환 LLM 엔드포인트이다"},"mnemopi.llmApiKey":{"label":"Mnemopi LLM API 키","description":"Mnemopi 원격 모드를 위한 선택적 LLM API 키이다"},"mnemopi.llmModel":{"label":"Mnemopi LLM 모델","description":"Mnemopi 원격 모드를 위한 선택적 LLM 모델 이름이다"},"hindsight.apiUrl":{"label":"Hindsight API URL","description":"Hindsight 서버 URL(Cloud 또는 self-hosted)이다"},"hindsight.apiToken":{"label":"Hindsight API 토큰","description":"인증이 필요한 Hindsight 서버용 Bearer 토큰이다"},"hindsight.bankId":{"label":"Hindsight Bank ID","description":"메모리 뱅크 식별자다(기본값: 프로젝트 이름)"},"hindsight.scoping":{"label":"Hindsight 범위","description":"global = 하나의 공유 뱅크, per-project = cwd별로 격리된 뱅크, per-project-tagged = 프로젝트 태그가 붙은 공유 뱅크로 recall 시 global 메모리와 프로젝트 메모리가 병합된다"},"hindsight.autoRecall":{"label":"Hindsight 자동 recall","description":"각 세션의 첫 턴에 메모리를 recall한다"},"hindsight.autoRetain":{"label":"Hindsight 자동 retain","description":"N턴마다 그리고 세션 경계에서 대화 기록을 retain한다"},"hindsight.retainMode":{"label":"Hindsight retain 모드","description":"full-session = 세션당 문서 하나를 upsert하고, last-turn = 청크 단위로 저장한다"},"hindsight.mentalModelsEnabled":{"label":"Hindsight 멘탈 모델","description":"부팅 시 정리된 reflect 요약(멘탈 모델)을 developer instructions로 읽어들인다. 뱅크에 있는 기존 모델을 로드하며 쓰기는 하지 않는다. 내장 seed 세트를 자동 생성하려면 hindsight.mentalModelAutoSeed와 함께 사용한다."},"hindsight.mentalModelAutoSeed":{"label":"Hindsight 멘탈 모델 자동 seed","description":"세션 시작 시 뱅크에 아직 없는 내장 멘탈 모델(project-conventions, project-decisions, user-preferences)을 생성한다."},"providers.memoryModel":{"label":"메모리 모델","description":"사실 추출 및 통합에 사용하는 Mnemopi LLM이다: 기본값은 online(/models의 TINY 역할, 없으면 smol/remote)이며, 로컬 on-device 모델도 사용할 수 있다"},"edit.mode":{"label":"편집 모드","description":"edit 도구 변형을 선택한다(replace, patch, hashline, apply_patch)"},"edit.fuzzyMatch":{"label":"퍼지 매치","description":"공백 차이에 대해 신뢰도가 높은 퍼지 매치를 허용한다"},"edit.fuzzyThreshold":{"label":"퍼지 매치 임계값","description":"퍼지 매치를 허용하는 유사도 임계값(0-1)이다"},"edit.streamingAbort":{"label":"프리뷰 실패 시 중단","description":"패치 프리뷰가 실패하면 스트리밍 edit 도구 호출을 중단한다"},"edit.blockAutoGenerated":{"label":"자동 생성 파일 차단","description":"자동 생성된 것으로 보이는 파일(protoc, sqlc, swagger 등)의 편집을 막는다"},"edit.enforceSeenLines":{"label":"확인된 줄 가드 적용","description":"이전 read/search가 전체를 표시하지 않은 줄을 기준으로 하는 편집을 거부한다"},"readLineNumbers":{"label":"줄 번호","description":"기본적으로 read 도구 출력에 줄 번호를 앞에 붙인다"},"read.defaultLimit":{"label":"기본 read 제한","description":"에이전트가 limit 없이 read를 호출할 때 반환하는 기본 줄 수다"},"read.renderMarkdown":{"label":"Markdown 프리뷰","description":"Markdown read 결과를 원본 소스가 아니라 서식이 적용된 터미널 Markdown 프리뷰로 렌더링한다"},"read.summarize.enabled":{"label":"read 요약","description":"명시적 selector 없이 read가 호출되면 구조적 코드 요약을 반환한다"},"read.summarize.prose":{"label":"산문 요약","description":"Markdown 및 일반 텍스트 read에 대해 구조적 요약을 반환한다"},"read.toolResultPreview":{"label":"인라인 read 프리뷰","description":"read 도구 결과를 요약 행이 아니라 대화 기록에 인라인으로 렌더링한다"},"lsp.enabled":{"label":"LSP","description":"코드 인텔리전스(정의, 참조, 진단, 이름 변경)를 위한 lsp 도구를 활성화한다"},"lsp.lazy":{"label":"LSP 지연 시작","description":"세션 시작 시점이 아니라 처음 사용할 때(lsp 도구 호출 또는 해당 파일 타입 편집) language server를 시작한다"},"lsp.shared":{"label":"공유 language server","description":"daemon broker를 통해 프로젝트당 하나의 language server를 omp 인스턴스 간에 공유한다(사용할 수 없으면 개별 서버로 대체된다)"},"lsp.formatOnWrite":{"label":"쓰기 시 포맷","description":"파일을 쓴 후 LSP로 코드 파일을 자동 포맷한다"},"lsp.diagnosticsOnWrite":{"label":"쓰기 시 진단","description":"코드 파일을 쓴 후 LSP 진단을 반환한다"},"lsp.diagnosticsOnEdit":{"label":"편집 시 진단","description":"코드 파일을 편집한 후 LSP 진단을 반환한다"},"lsp.diagnosticsDeduplicate":{"label":"진단 중복 제거","description":"파일에 대해 이미 표시된 편집 후 LSP 진단을 억제하고, 새롭거나 변경된 것만 표시한다"},"bash.enabled":{"label":"Bash","description":"셸 명령 실행을 위한 bash 도구를 활성화한다"},"bash.autoBackground.enabled":{"label":"Bash 자동 백그라운드","description":"오래 실행되는 bash 명령을 자동으로 백그라운드로 보내고 결과를 나중에 전달한다"},"bashInterceptor.enabled":{"label":"Bash 인터셉터","description":"전용 도구가 있는 셸 명령을 차단한다"},"bash.direnv":{"label":"direnv 자동 로드","description":"저장소의 direnv/devenv `.envrc`를 bash 세션에 자동으로 로드해 수동 `direnv exec` 없이 devenv 도구와 환경 변수를 사용할 수 있게 한다. direnv의 허용 목록을 따르며, `direnv allow`하지 않은 `.envrc`는 절대 실행되지 않는다"},"shellMinimizer.enabled":{"label":"셸 출력 축소","description":"장황한 셸 출력(git, npm, cargo 등)을 에이전트에 반환하기 전에 압축한다"},"shellMinimizer.sourceOutlineLevel":{"label":"셸 축소 소스 아웃라인","description":"소스 파일의 cat/read에 대한 소스 아웃라인 모드: default 또는 aggressive"},"eval.py":{"label":"Python Eval 백엔드","description":"eval 도구가 Python 셀을 IPython 커널로 보내도록 허용한다"},"eval.js":{"label":"JavaScript Eval 백엔드","description":"eval 도구가 JavaScript 셀을 인프로세스 런타임으로 보내도록 허용한다"},"eval.rb":{"label":"Ruby Eval 백엔드","description":"eval 도구가 Ruby 셀을 상시 유지되는 Ruby 커널로 보내도록 허용한다"},"eval.jl":{"label":"Julia Eval 백엔드","description":"eval 도구가 Julia 셀을 상시 유지되는 Julia 커널로 보내도록 허용한다"},"python.kernelMode":{"label":"Python 커널 모드","description":"eval 호출 간에 IPython 커널을 유지할지 매번 새로 시작할지 정한다"},"python.interpreter":{"label":"Python 인터프리터","description":"정확한 Python 실행 파일의 선택적 경로이다. 설정하면 자동 Python 런타임 탐색을 건너뛴다."},"ruby.interpreter":{"label":"Ruby 인터프리터","description":"정확한 Ruby 실행 파일의 선택적 경로이다. 설정하면 자동 Ruby 런타임 탐색을 건너뛴다."},"julia.interpreter":{"label":"Julia 인터프리터","description":"정확한 Julia 실행 파일의 선택적 경로이다. 설정하면 자동 Julia 런타임 탐색을 건너뛴다."},"tools.artifactSpillThreshold":{"label":"아티팩트 분리 임계값(KB)","description":"이 크기를 넘는 도구 출력은 아티팩트로 저장되고, 끝부분은 인라인으로 유지된다"},"tools.artifactTailBytes":{"label":"아티팩트 끝부분 크기(KB)","description":"출력이 아티팩트로 넘어갈 때 인라인으로 유지되는 끝부분 내용의 양이다"},"tools.artifactHeadBytes":{"label":"아티팩트 앞부분 크기(KB)","description":"출력이 아티팩트로 넘어갈 때 끝부분과 함께 인라인으로 유지되는 앞부분 내용의 양이다(중간 생략). 0이면 비활성화되어 끝부분만 유지한다."},"tools.outputMaxColumns":{"label":"출력 열 제한","description":"스트리밍 도구 출력(bash, python, js eval)과 `read`에 대한 줄당 바이트 제한이다. 이보다 긴 줄은 말줄임표로 잘리고, 다음 줄바꿈까지 남은 바이트는 버려진다. 0이면 비활성화된다."},"tools.artifactTailLines":{"label":"아티팩트 끝부분 줄 수","description":"출력이 아티팩트로 넘어갈 때 인라인으로 유지되는 끝부분 내용의 최대 줄 수이다"},"todo.enabled":{"label":"할 일 목록","description":"작업 추적을 위한 todo 도구를 활성화한다"},"todo.reminders":{"label":"할 일 알림","description":"중지하기 전에 할 일을 완료하도록 에이전트에 상기시킨다"},"todo.remindersMax":{"label":"할 일 알림 제한","description":"포기하기 전까지의 최대 할 일 알림 횟수이다"},"todo.eager":{"label":"할 일 자동 생성","description":"첫 메시지 이후 자동 할 일 목록 생성을 얼마나 강하게 유도할지 정한다"},"glob.enabled":{"label":"Glob","description":"glob 기반 파일 조회를 위한 glob 도구를 활성화한다"},"grep.enabled":{"label":"Grep","description":"정규식 내용 검색을 위한 grep 도구를 활성화한다"},"grep.contextBefore":{"label":"Grep 앞 컨텍스트","description":"각 grep 일치 항목 앞에 표시할 컨텍스트 줄 수이다"},"grep.contextAfter":{"label":"Grep 뒤 컨텍스트","description":"각 grep 일치 항목 뒤에 표시할 컨텍스트 줄 수이다"},"astGrep.enabled":{"label":"AST Grep","description":"구조적 AST 검색을 위한 ast_grep 도구를 활성화한다"},"astEdit.enabled":{"label":"AST Edit","description":"구조적 AST 재작성을 위한 ast_edit 도구를 활성화한다"},"debug.enabled":{"label":"디버그","description":"DAP 기반 디버깅을 위한 debug 도구를 활성화한다"},"launch.enabled":{"label":"Launch","description":"공유되는 장기 실행 프로젝트 프로세스를 감독하는 launch 도구를 활성화한다"},"speechgen.enabled":{"label":"음성 생성","description":"온디바이스(Kokoro) 또는 xAI Grok Voice 음성 파일 합성을 위한 tts 도구를 활성화한다"},"generate_image.enabled":{"label":"이미지 생성","description":"generate_image 도구(텍스트-이미지 생성 및 편집)를 활성화한다. tools.xdev가 켜져 있으면 xd:// 장치로 노출된다."},"inspect_image.mode":{"label":"이미지 분석","description":"이미지 이해를 비전 지원 모델에 위임하는 inspect_image 도구를 제어한다. \'auto\'는 활성 모델이 네이티브 이미지 입력을 지원하지 않을 때만 노출하고, \'on\'은 항상 노출하며, \'off\'는 노출하지 않는다."},"computer.enabled":{"label":"컴퓨터","description":"스크립트 가능한 호스트 데스크톱 제어 도구(스크린샷, 입력, 접근성)를 활성화한다"},"computer.display":{"label":"컴퓨터 디스플레이","description":"모든 디스플레이를 합성하거나 네이티브 display id를 선택한다"},"inspect_image.timeoutMs":{"label":"이미지 분석 타임아웃","description":"inspect_image 비전 모델 호출의 요청당 타임아웃이며 단위는 milliseconds이다. 응답이 멈춘 제공자는 수동 중단까지 차단되지 않고 타임아웃 오류로 빠르게 실패한다. 0으로 설정하면 타임아웃을 비활성화한다."},"checkpoint.enabled":{"label":"체크포인트/되돌리기","description":"컨텍스트 체크포인팅을 위한 checkpoint 및 rewind 도구를 활성화한다"},"fetch.enabled":{"label":"URL 읽기","description":"read 도구가 URL을 가져와 처리하도록 허용한다"},"vault.enabled":{"label":"Obsidian Vault","description":"Obsidian CLI를 통해 Obsidian vault 내용을 읽고 편집하는 vault:// 내부 URL을 활성화한다. 비활성화하면 vault:// 해석이 거부되고 시스템 프롬프트에서 vault:// 항목이 생략된다."},"github.enabled":{"label":"GitHub CLI","description":"github 도구(리포지터리, 이슈, pull request, diff, 검색, checkout, push, Actions watch 워크플로에 대한 op 기반 디스패치)를 활성화한다"},"github.cache.enabled":{"label":"GitHub 뷰 캐시","description":"렌더링된 이슈/PR 뷰 출력을 ~/.omp/cache/github-cache.db에 캐시해 반복 읽기 비용을 없앤다"},"web_search.enabled":{"label":"웹 검색","description":"실시간 웹 결과를 위한 web_search 도구를 활성화한다"},"security.enabled":{"label":"보안","description":"OMP 네이티브 보안 스캔 계획과 실행, 그리고 읽기 전용 security:// 리소스 네임스페이스를 활성화한다"},"ask.enabled":{"label":"Ask","description":"대화형 사용자 질문을 위한 ask 도구를 활성화한다"},"browser.enabled":{"label":"브라우저","description":"스크립트 기반 Chromium 자동화(puppeteer)를 위한 browser 도구를 활성화한다"},"browser.cdpUrl":{"label":"브라우저 CDP URL","description":"브라우저를 실행하는 대신 연결할 기본 HTTP CDP 디스커버리 엔드포인트이다(예: http://127.0.0.1:9222). 도구 호출에 명시된 app.cdp_url 또는 app.path가 우선한다."},"browser.relay":{"label":"브라우저 릴레이","description":"omp browser relay를 통해 사용자의 Chrome 탭을 제어한다. 확장 프로그램을 한 번 설치하면(`omp browser-relay install`) browser 도구가 필요할 때 릴레이 서버가 자동으로 시작된다. Browser CDP URL보다 우선하며, PI_BROWSER_RELAY=0 또는 PI_BROWSER_RELAY=1로 재정의한다."},"browser.relayUrl":{"label":"브라우저 릴레이 URL","description":"omp browser relay 엔드포인트이다(기본값 http://127.0.0.1:9224)."},"browser.headless":{"label":"헤드리스 브라우저","description":"브라우저를 headless 모드로 실행한다(비활성화하면 브라우저 UI를 표시한다)"},"browser.cmux":{"label":"cmux 브라우저","description":"cmux 소켓을 사용할 수 있을 때 브라우저 자동화에 cmux WKWebView 서피스를 사용한다. PI_BROWSER_CMUX=0 또는 PI_BROWSER_CMUX=1로 재정의한다."},"browser.screenshotDir":{"label":"스크린샷 디렉터리","description":"스크린샷을 저장할 디렉터리이다. 설정하지 않으면 스크린샷은 임시 파일로 저장된다. ~를 지원한다. 예: ~/Downloads, ~/Desktop, /sdcard/Download (Android)"},"tools.intentTracing":{"label":"인텐트 트레이싱","description":"각 도구 호출을 실행하기 전에 그 의도를 설명하도록 에이전트에 요청한다"},"tools.abortOnFabricatedResult":{"label":"조작된 도구 결과 시 중단","description":"in-band 도구 호출에서 모델이 턴 중간에 도구 결과를 환각하기 시작하면 즉시 중단한다. 비활성화하면 모델이 생성을 끝내도록 두고 조작된 이어쓰기를 폐기한다."},"tools.maxTimeout":{"label":"최대 도구 타임아웃","description":"에이전트가 임의의 도구에 설정할 수 있는 최대 타임아웃(초, 0 = 무제한)"},"async.enabled":{"label":"비동기 실행","description":"비동기 bash 명령과 백그라운드 작업 실행을 활성화한다"},"tools.xdev":{"label":"xd:// 도구","description":"드물게 쓰이는(탐색 가능한) 도구의 스키마를 매 요청마다 보내는 대신 read/write로 구동되는 xd:// 디바이스 URL 아래에 마운트한다. write 도구가 허용되지 않은 세션은 마운트를 건너뛰고 모든 도구를 최상위로 노출한다. 비활성화하면 활성화된 모든 도구를 최상위로 노출한다."},"tools.xdevDocs":{"label":"xd:// 프롬프트 문서","description":"시스템 프롬프트에 인라인으로 포함할 마운트된 디바이스 문서와 스키마를 선택한다. Built-ins는 핵심 도구를 인라인으로 유지하고 MCP 및 확장 도구는 on-demand로 남긴다."},"mcp.selection":{"label":"MCP 연결 선택","description":"all은 시작 시 기존 설정대로 연결한다. per-request는 JEV가 요청에 필요한 서버를 선택해 연결하며, 설치\xb7인증\xb7권한은 자동 승인하지 않는다. 변경 후 새 세션에서 적용된다."},"mcp.enableProjectConfig":{"label":"MCP 프로젝트 설정","description":"프로젝트 루트에서 .mcp.json/mcp.json을 로드한다"},"mcp.renderMarkdownResults":{"label":"MCP Markdown 결과","description":"JSON이 아닌 MCP 텍스트 결과를 트랜스크립트에서 Markdown으로 렌더링한다"},"mcp.notifications":{"label":"MCP 업데이트 주입","description":"MCP 리소스 업데이트를 에이전트 대화에 주입한다"},"tasks.todoClearDelay":{"label":"Todo 자동 정리 지연","description":"완료되거나 중단된 todo가 todo 위젯에서 제거되기까지의 지연 시간이다"},"dev.autoqa":{"label":"Auto QA","description":"자동 도구 이슈 보고(xd://report_issue)이다. 기본적으로 켜져 있으며, 첫 보고 시 동의를 요청하고 거부하면 명시적으로 다시 활성화할 때까지 보고를 비활성화한다"},"dev.autoqaPush.endpoint":{"label":"Auto QA 푸시 엔드포인트","description":"Auto QA JSON 보고를 수신하는 전체 URL이다(기본값 https://qa.omp.sh/v1/grievances)"},"plan.enabled":{"label":"Plan 모드","description":"실행 전 읽기 전용 탐색과 계획 수립을 위한 plan 모드를 활성화한다"},"plan.defaultOnStartup":{"label":"Plan 모드로 시작","description":"모든 새 세션 시작 시 자동으로 plan 모드로 진입한다"},"goal.enabled":{"label":"Goal 모드","description":"세션별 goal 모드와 숨겨진 goal 도구를 활성화한다"},"goal.statusInFooter":{"label":"푸터의 Goal 상태","description":"상태 표시줄에서 goal 표시기와 함께 토큰 예산을 표시한다"},"title.refreshOnReplan":{"label":"재계획 시 제목 갱신","description":"사용자가 제목을 설정한 경우가 아니면 todo init 재계획 이후 생성된 세션 제목을 갱신한다"},"task.isolation.mode":{"label":"격리 모드","description":"서브에이전트의 격리 백엔드이다. \\"auto\\"는 네이티브 PAL이 사용 가능한 최적 백엔드를 선택하게 한다(CoW를 지원하는 파일시스템, 그다음 overlayfs/ProjFS, 그다음 git worktree / 재귀 복사 폴백)."},"task.isolation.apply":{"label":"격리 변경 적용","description":"성공한 격리 작업의 변경을 부모 체크아웃에 자동으로 적용한다. 비활성화하면 patch 또는 branch 아티팩트를 유지한다"},"task.isolation.merge":{"label":"격리 병합 전략","description":"격리 작업의 변경을 통합하는 방식이다(patch apply 또는 branch merge)"},"task.isolation.commits":{"label":"격리 커밋 스타일","description":"중첩 저장소 변경의 커밋 메시지 스타일이다(generic 또는 AI 생성)"},"worktree.base":{"label":"Worktree 기본 디렉터리","description":"에이전트가 관리하는 worktree의 기본 디렉터리로, 작업 격리 사본, `github` PR 체크아웃, `omp worktree` 정리가 모두 여기에 위치한다. 설정하지 않으면 ~/.omp/wt를 사용한다. 절대 경로 또는 ~ 기준 경로여야 하며, 상대 경로는 무시된다. OMP_WORKTREE_DIR 환경 변수가 이 값을 재정의한다."},"task.eager":{"label":"작업 위임 선호도","description":"서브에이전트에 작업을 위임하도록 얼마나 강하게 유도할지를 정한다"},"task.batch":{"label":"작업 호출 배치","description":"task 도구를 배치 형태로 전환한다: 한 번의 호출이 { context, tasks[] }를 전달하며, 항목당 서브에이전트 하나가 실행되고, 항목별 agent(기본값은 세션 spawn-policy 에이전트)와 항목별 격리를 지정할 수 있으며, 공유 context는 모든 assignment 앞에 필수로 붙는다. async.enabled=true인 경우 각 spawn은 일반적인 idle/parked 수명 주기를 갖는 독립 백그라운드 에이전트로 실행되고, 그렇지 않으면 호출은 병합된 결과를 기다리며 블로킹된다. 비활성화하면 평면적인 단일 spawn 스키마로 되돌아간다."},"task.enableEffort":{"label":"작업별 effort","description":"task spawn에서 선택적 effort 파라미터를 노출해, 호출자가 각 서브에이전트의 thinking 레벨을 재정의할 수 있게 한다"},"task.maxConcurrency":{"label":"최대 동시 작업 수","description":"동시에 실행되는 서브에이전트의 최대 개수이다"},"task.enableLsp":{"label":"서브에이전트 LSP","description":"task 도구로 생성된 서브에이전트가 lsp 도구를 사용할 수 있게 한다. 서브에이전트 비용을 낮게 유지하기 위해 기본적으로 꺼져 있으며, LSP를 활용한 위임이 추가 토큰만큼 가치가 있을 때 활성화한다."},"task.maxRecursionDepth":{"label":"최대 작업 재귀 깊이","description":"서브에이전트가 자신의 서브에이전트를 생성할 수 있는 최대 깊이이다"},"task.maxRuntimeMs":{"label":"서브에이전트 최대 실행 시간","description":"서브에이전트당 절대 실행 시간 제한(ms)이다. 0이면 비활성화된다. 추론 계층 워치독을 빠져나가는 프로바이더 측 스트림 정지에 대한 심층 방어 수단이며, \'timed out\' 사유로 일반적인 서브에이전트 중단을 발생시킨다."},"task.softRequestBudget":{"label":"서브에이전트 소프트 요청 예산","description":"서브에이전트당 소프트 요청 예산(실행당 assistant 요청 수)이다. 이를 초과하면 마무리를 유도하는 steering 알림이 주입되며(task.softRequestBudgetNotice 참고), 예산의 1.5배에 도달하면 실행이 강제 중단되고 에이전트는 부분 결과를 내놓아야 한다. 0이면 이 보호 장치가 비활성화된다. 번들된 scout/sonic 에이전트는 더 낮은 내장 예산이 상한이므로, 그 상한보다 낮은 값은 이들에게도 적용된다."},"task.softRequestBudgetNotice":{"label":"소프트 요청 예산 알림","description":"서브에이전트가 소프트 요청 예산을 초과할 때 steering 알림을 한 번 주입해, 1.5배 강제 중단 전에 마무리하도록 요청한다."},"task.maxEffort":{"label":"spawn당 최대 effort","description":"task 도구의 spawn별 effort 힌트에 허용되는 최대 추론 effort이다. 값을 낮추면 호출자가 서브에이전트를 이 상한 이상으로 올릴 수 없으며, 기본값은 모델의 전체 범위를 유지한다."},"task.prewalk":{"label":"일반 작업 prewalk","description":"번들된 일반 `task` 서브에이전트에 prewalk를 적용한다: 해석된 모델로 시작해 계획을 세우고 구현을 시작한 뒤, 첫 편집/쓰기 시점에 \'smol\' 역할로 넘긴다. 에이전트별 재정의(/agents 허브에서 설정하는 task.agentPrewalk)와 사용자 에이전트의 `prewalk` frontmatter는 이 토글과 무관하게 적용된다."},"skills.enableSkillCommands":{"label":"스킬 명령","description":"스킬을 /skill:name 명령으로 등록한다"},"commands.enableClaudeUser":{"label":"Claude 사용자 명령","description":"~/.claude/commands/에서 명령을 로드한다"},"commands.enableClaudeProject":{"label":"Claude 프로젝트 명령","description":".claude/commands/에서 명령을 로드한다"},"commands.enableOpencodeUser":{"label":"OpenCode 사용자 명령","description":"~/.config/opencode/commands/에서 명령을 로드한다"},"commands.enableOpencodeProject":{"label":"OpenCode 프로젝트 명령","description":".opencode/commands/에서 명령을 로드한다"},"providers.maxInFlightRequests":{"label":"최대 동시 요청 수","description":"프로바이더 id별(예: \\"openai\\" 또는 \\"anthropic\\") 최대 동시 LLM 요청 수로, 같은 config root를 쓰는 로컬 OMP 프로세스 간에 공유된다. 명시되지 않은 프로바이더는 제한이 없다."},"secrets.enabled":{"label":"시크릿 숨김","description":"AI 프로바이더로 전송하기 전에 설정된 시크릿을 난독화하고 자격 증명 형태의 토큰을 마스킹한다"},"providers.webSearchOrder":{"label":"웹 검색 프로바이더 순서","description":"web_search 도구에 사용할 프로바이더의 우선순위이며, 목록에 없는 프로바이더는 그 뒤에 기본 순서를 유지한다"},"providers.webSearchExclude":{"label":"제외할 웹 검색 프로바이더","description":"web_search가 폴백으로도 절대 사용하지 않을 프로바이더이다"},"providers.webSearchTimeoutSeconds":{"label":"웹 검색 타임아웃","description":"web_search가 다음 폴백으로 넘어가기 전 각 프로바이더 검색 전송에 적용되는 절대 타임아웃이며 단위는 초이다(최대 300)"},"providers.webSearchGeminiModel":{"label":"Gemini web_search 모델","description":"Gemini Google Search grounding에 사용할 모델 ID이다. 기본값은 gemini-2.5-flash이다."},"providers.antigravityEndpoint":{"label":"Antigravity 엔드포인트 모드","description":"google-antigravity 프로바이더의 엔드포인트 라우팅 전략이다(chat, search, image, discovery)"},"providers.imageOrder":{"label":"이미지 프로바이더 순서","description":"이미지 생성에 사용할 프로바이더의 우선순위이며, 목록에 없는 프로바이더는 활성 세션 프로바이더와 내장 순서를 따른다"},"providers.fireworksTier":{"label":"Fireworks 티어","description":"Fireworks 요청의 서빙 경로이다. Priority는 `service_tier: \\"priority\\"`를 전송해 트래픽이 몰릴 때 더 높은 신뢰성을 더 높은 가격에 제공하고, Standard는 이를 생략한다. Fast(`-fast`) 모델은 이 설정을 무시하며, Fast는 별도의 서빙 경로이다."},"live.voice":{"label":"Live 음성","description":"Codex 기반 realtime 음성 세션에서 사용하는 음성이다"},"providers.tts":{"label":"TTS 제공자","description":"tts 도구의 백엔드이다: 로컬 온디바이스 신경망 TTS(Kokoro-82M) 또는 xAI Grok Voice 중 하나이다"},"tts.localModel":{"label":"로컬 TTS 모델","description":"로컬 TTS 백엔드가 사용하는 온디바이스 신경망 TTS 모델(Kokoro-82M)이다"},"tts.localVoice":{"label":"로컬 TTS 음성","description":"로컬 TTS 백엔드가 사용하는 Kokoro 음성이다(미국/영국, 여성/남성)"},"speech.enabled":{"label":"음성 출력","description":"어시스턴트의 출력을 스트리밍되는 대로 스피커로 소리내어 읽는다"},"speech.mode":{"label":"음성 출력 모드","description":"읽을 대상이다: all = 어시스턴트 메시지 + 사고 과정, assistant = 메시지만, yield = 턴 종료 시 마지막 메시지만이다"},"speech.enhanced":{"label":"향상된 음성 재작성","description":"합성 전에 tiny/smol 모델로 어시스턴트 출력을 자연스러운 구어체 산문으로 재작성한다(코드는 설명으로 바꾸고 링크와 markdown은 제거한다). 실패하면 기계적 정리로 대체된다"},"speech.voice":{"label":"음성 출력 목소리","description":"어시스턴트의 출력을 소리내어 읽을 때 사용하는 Kokoro 음성이다"},"providers.tinyModel":{"label":"Tiny 모델","description":"세션 제목 생성 모델이다: 기본값은 온라인(/models의 TINY 역할, 없으면 @smol)이며, 로컬 온디바이스 모델도 가능하다"},"providers.tinyModelDevice":{"label":"Tiny 모델 디바이스","description":"로컬 tiny 모델(제목 + 메모리)에 사용하는 ONNX 실행 제공자이다. 기본값은 CPU 전용 추론을 사용한다. PI_TINY_DEVICE 환경 변수가 이 값을 덮어쓴다."},"providers.tinyModelDtype":{"label":"Tiny 모델 정밀도","description":"로컬 tiny 모델의 ONNX 양자화/정밀도이다. 기본값은 각 모델에 포함된 dtype(q4)을 사용하며, 정밀도가 낮으면 더 빠르고 높으면 원본에 더 충실하다. PI_TINY_DTYPE 환경 변수가 이 값을 덮어쓴다."},"providers.unexpectedStopModel":{"label":"예기치 않은 중단 모델","description":"예기치 않은 중단 감지용 분류기이다: 기본값은 온라인(/models의 TINY 역할, 없으면 smol)이며, 로컬 온디바이스 모델도 가능하다."},"providers.kimiApiFormat":{"label":"Kimi API 형식","description":"Kimi Code 제공자의 API 형식이다(auto는 라이브 모델 메타데이터를 따른다)"},"providers.openaiWebsockets":{"label":"OpenAI WebSockets","description":"OpenAI Codex 모델의 websocket 정책이다(auto는 모델 기본값을 사용하고, on은 강제하며, off는 비활성화한다)"},"providers.streamFirstEventTimeoutSeconds":{"label":"스트림 첫 이벤트 타임아웃","description":"모델 스트림의 첫 이벤트를 기다리는 초이다. -1은 provider/env 기본값을 사용하고, 0은 워치독을 비활성화한다"},"providers.streamIdleTimeoutSeconds":{"label":"스트림 유휴 타임아웃","description":"모델 스트림이 이벤트 사이에 무응답 상태로 있을 수 있는 초이다. -1은 provider/env 기본값을 사용하고, 0은 워치독을 비활성화한다"},"providers.openrouterVariant":{"label":"OpenRouter 라우팅","description":"OpenRouter 모델 ID에 덧붙이는 기본 라우팅 variant 접미사이다(선택기에서 이미 variant를 지정한 경우 무시된다)"},"providers.fetch":{"label":"Fetch 제공자","description":"fetch/read URL 도구의 리더 백엔드 우선순위이다"},"codexResets.autoRedeem":{"label":"Codex 리셋 자동 사용","description":"저장된 Codex rate-limit 리셋을 자동으로 사용한다: 턴이 멈추고 다른 계정이 대체할 수 없을 때 5h 또는 weekly 창을 소진해 차단된 계정을 복구하고, 곧 만료될 크레딧을 회수한다. unset은 첫 사용 전에 확인하고, yes는 확인 없이 사용하며, no는 두 검사 모두 비활성화한다."},"provider.appendOnlyContext":{"label":"추가 전용 컨텍스트","description":"시스템 프롬프트 + 도구 명세를 캐시하고 추가 전용 메시지 로그를 유지해 provider prefix 캐시(DeepSeek, Xiaomi/SGLang, Anthropic) 적중률을 최대화한다. auto는 prefix 캐시가 알려진 제공자에 대해 활성화한다."},"exa.enabled":{"label":"Exa","description":"Exa 웹 검색 제공자를 활성화한다"},"searxng.endpoint":{"label":"SearXNG 엔드포인트","description":"웹 검색에 사용하는 자체 호스팅 SearXNG 인스턴스의 기본 URL이다"}}}'),ie=[{id:"models",label:"Models",icon:"model"},{id:"themes",label:"Themes",icon:"theme"},{id:"skills",label:"Skills",icon:"skill",requiresCwd:!0},{id:"plugins",label:"Plugins",icon:"plugin",requiresCwd:!0},{id:"mcp",label:"MCP",icon:"mcp"},{id:"access",label:"Access",icon:"access"},{id:"trust",label:"Project trust",labelKey:"trust.settingsNav",icon:"trust"},{id:"live-voice",label:"Call voice",labelKey:"chat.liveVoiceSettingsNav",icon:"liveVoice"},{id:"attachments",label:"Attachments",labelKey:"chat.attachmentSettingsNav",icon:"attachments"}],ig={model:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"}),(0,d.jsx)("path",{d:"M9 9h6v6H9zM9 1v3m6-3v3M9 20v3m6-3v3M1 9h3m16 0h3M1 15h3m16 0h3"})]}),theme:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"8"}),(0,d.jsx)("path",{d:"M12 4a8 8 0 0 0 0 16z"})]}),skill:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"m12 3 8 4-8 4-8-4 8-4Z"}),(0,d.jsx)("path",{d:"m4 12 8 4 8-4M4 17l8 4 8-4"})]}),plugin:(0,d.jsx)(d.Fragment,{children:(0,d.jsx)("path",{d:"M8 3v5m8-5v5M6 8h12v5a6 6 0 0 1-12 0V8Zm6 11v3"})}),mcp:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("circle",{cx:"6",cy:"6",r:"2"}),(0,d.jsx)("circle",{cx:"18",cy:"6",r:"2"}),(0,d.jsx)("circle",{cx:"12",cy:"18",r:"2"}),(0,d.jsx)("path",{d:"M8 7.5 11 16m5-8.5L13 16M8 6h8"})]}),access:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("rect",{x:"4",y:"10",width:"16",height:"10",rx:"2"}),(0,d.jsx)("path",{d:"M8 10V7a4 4 0 0 1 8 0v3M12 14v2"})]}),trust:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,d.jsx)("path",{d:"m9 12 2 2 4-4"})]}),liveVoice:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,d.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2M12 19v3"})]}),attachments:(0,d.jsx)("path",{d:"m21 12-8.6 8.6a5 5 0 0 1-7-7l8.5-8.6a3.3 3.3 0 0 1 4.7 4.7l-8.5 8.6a1.7 1.7 0 0 1-2.4-2.4l7.9-7.9"}),appearance:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,d.jsx)("path",{d:"M12 3v18M3 12h18"})]}),interaction:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"M4 5h16v11H9l-5 4V5Z"}),(0,d.jsx)("path",{d:"M8 9h8m-8 3h5"})]}),context:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"M5 3h11l3 3v15H5z"}),(0,d.jsx)("path",{d:"M15 3v4h4M8 11h8m-8 4h8"})]}),memory:(0,d.jsx)(d.Fragment,{children:(0,d.jsx)("path",{d:"M9 4a3 3 0 0 0-3 3v1a3 3 0 0 0-1 5v1a3 3 0 0 0 3 3h1m6-13a3 3 0 0 1 3 3v1a3 3 0 0 1 1 5v1a3 3 0 0 1-3 3h-1M9 4v16m6-16v16"})}),files:(0,d.jsx)(d.Fragment,{children:(0,d.jsx)("path",{d:"M3 6h7l2 2h9v11H3z"})}),shell:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),(0,d.jsx)("path",{d:"m7 9 3 3-3 3m6 0h4"})]}),tools:(0,d.jsx)(d.Fragment,{children:(0,d.jsx)("path",{d:"m14 6 4-4 4 4-4 4M3 18l8-8m-6 4 5 5-3 3-5-5 3-3Z"})}),tasks:(0,d.jsx)(d.Fragment,{children:(0,d.jsx)("path",{d:"M9 6h11M9 12h11M9 18h11M4 6l1 1 2-2m-3 7 1 1 2-2m-3 7 1 1 2-2"})}),providers:(0,d.jsx)(d.Fragment,{children:(0,d.jsx)("path",{d:"M7 4h10v5H7zM4 15h6v5H4zm10 0h6v5h-6zM12 9v3m-5 0h10M7 12v3m10-3v3"})})};function ih({kind:a}){return(0,d.jsx)("svg",{className:h4().navIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:ig[a]??ig.tools})}function ii({field:a,busy:b,onSave:c}){let[f,g]=(0,e.useState)("secret"===a.type?"":String(a.value??"")),h="secret"===a.type?"":String(a.value??"");return(0,d.jsx)("input",{className:h4().textInput,type:"secret"===a.type?"password":"text",value:f,disabled:b,placeholder:"secret"===a.type&&a.configured?"Configured — enter to replace":void 0,onChange:a=>g(a.target.value),onBlur:()=>{f!==h&&("secret"!==a.type||f.length>0)&&c(f)},onKeyDown:a=>{"Enter"===a.key&&a.currentTarget.blur()}})}function ij({field:a,busy:b,onSave:c}){let f=JSON.stringify(a.value??{},null,2),[g,h]=(0,e.useState)(f),[i,j]=(0,e.useState)(null);return(0,d.jsxs)("div",{style:{width:"100%"},children:[(0,d.jsx)("textarea",{className:h4().jsonEditor,style:{minHeight:92},value:g,disabled:b,onChange:a=>h(a.target.value),onBlur:()=>{if(g!==f)try{c(JSON.parse(g)),j(null)}catch(a){j(a instanceof Error?a.message:String(a))}}}),i&&(0,d.jsx)("div",{className:h4().error,children:i})]})}function ik({field:a,busy:b,onSave:c}){let e=Array.isArray(a.value)?a.value:[],f=(a,b)=>{let d=a+b;if(d<0||d>=e.length)return;let f=[...e];[f[a],f[d]]=[f[d],f[a]],c(f)};return(0,d.jsx)("div",{className:h4().multiSelect,children:a.options?.map(g=>{let h=e.indexOf(g.value);return(0,d.jsxs)("span",{className:h4().choice,"data-selected":h>=0,title:g.description,children:[(0,d.jsx)("button",{type:"button",className:h4().choiceToggle,disabled:b,onClick:()=>{let a;return a=g.value,c(e.includes(a)?e.filter(b=>b!==a):[...e,a])},children:g.label}),a.ordered&&h>=0&&(0,d.jsxs)("span",{className:h4().reorder,children:[(0,d.jsx)("button",{type:"button",disabled:b||0===h,onClick:()=>f(h,-1),children:"←"}),(0,d.jsx)("button",{type:"button",disabled:b||h===e.length-1,onClick:()=>f(h,1),children:"→"})]})]},g.value)})})}function il({field:a,busy:b,onSave:c}){return"boolean"===a.type?(0,d.jsx)("button",{type:"button",className:h4().switch,"data-on":!0===a.value,disabled:b,"aria-pressed":!0===a.value,onClick:()=>c(!0!==a.value)}):"select"===a.type?(0,d.jsx)(gN,{value:String(a.value??""),disabled:b,ariaLabel:a.label,options:(a.options??[]).map(a=>({value:a.value,label:a.label,description:a.description})),onChange:b=>c("number"==typeof a.value||"number"==typeof a.defaultValue?Number(b):b)}):"multiselect"===a.type?(0,d.jsx)(ik,{field:a,busy:b,onSave:c}):"providerLimits"===a.type?(0,d.jsx)(ij,{field:a,busy:b,onSave:c}):(0,d.jsx)(ii,{field:a,busy:b,onSave:c})}function im({field:a,busy:b,error:c,onSave:e}){return(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:h4().settingLabel,children:a.label}),(0,d.jsx)("div",{className:h4().settingDescription,children:a.description}),c&&(0,d.jsx)("div",{className:h4().error,children:c})]}),(0,d.jsx)("div",{className:h4().settingControl,children:(0,d.jsx)(il,{field:a,busy:b,onSave:e})})]})}function io({mode:a,palette:b}){let c=b.variables["--omp-md-heading"];return(0,d.jsxs)("div",{className:h4().themePreview,"data-seed-color-mode":"dark"===a?"dark-only":"light-only",children:[(0,d.jsx)("div",{className:h4().themePreviewBar,style:c?{background:c}:void 0}),(0,d.jsxs)("div",{className:h4().themePreviewPanel,children:[(0,d.jsx)("div",{className:h4().themePreviewLine}),(0,d.jsx)("div",{className:h4().themePreviewLine})]})]})}let ip=new Set(["hideThinkingBlock"]);function iq({cwd:a,sessionId:b,initialSection:c="models",onClose:f,onModelsChanged:g,onReloaded:h}){let[i,j]=(0,e.useState)(c),[k,l]=(0,e.useState)(null),[m,n]=(0,e.useState)(!0),[o,p]=(0,e.useState)(null),[q,r]=(0,e.useState)(""),[s,t]=(0,e.useState)(new Set),[u,v]=(0,e.useState)({}),[w,y]=(0,e.useState)(!1),[z,A]=(0,e.useState)(!1),{theme:B,setPreference:C}=bq(),{locale:D,t:E}=(0,x.s)(),F=(0,e.useRef)(null),G=a=>"ko"===D?id.shell[a]??a:a,H=(0,e.useCallback)(async()=>{n(!0),p(null);try{let b=a?`?cwd=${encodeURIComponent(a)}`:"",c=await fetch(`/api/settings${b}`,{cache:"no-store"}),d=await c.json();if(!c.ok||d.error)throw Error(d.error??`HTTP ${c.status}`);l(d)}catch(a){p(a instanceof Error?a.message:String(a))}finally{n(!1)}},[a]),I=(0,e.useCallback)(async(b,c)=>{t(a=>new Set(a).add(b.path)),v(a=>{let c={...a};return delete c[b.path],c});try{let d=await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:b.path,value:c})}),e=await d.json();if(!d.ok||e.error)throw Error(e.error??`HTTP ${d.status}`);l(a=>a?{...a,fields:a.fields.map(a=>a.path===b.path?{...a,value:e.value??c,configured:!0}:a)}:a),"theme.dark"===b.path||"theme.light"===b.path?(await bp(a),await H()):ip.has(b.path)?await bH(a):y(!0)}catch(a){v(c=>({...c,[b.path]:a instanceof Error?a.message:String(a)}))}finally{t(a=>{let c=new Set(a);return c.delete(b.path),c})}},[a,H]),J=(0,e.useMemo)(()=>new Map(k?.fields.map(a=>[a.path,a.value])??[]),[k?.fields]),K=(0,e.useMemo)(()=>k?.fields.filter(a=>(function(a,b){switch(a.condition){case void 0:default:return!0;case"hasImageProtocol":return!1;case"advisorEnabled":return!0===b.get("advisor.enabled");case"hindsightActive":return"hindsight"===b.get("memory.backend");case"mnemopiActive":return"mnemopi"===b.get("memory.backend");case"autolearnActive":return!0===b.get("autolearn.enabled");case"autoThinkingActive":return"auto"===b.get("defaultThinkingLevel");case"usageAwareFallbackEnabled":return!0===b.get("retry.usageAwareFallback");case"planModeEnabled":return!0===b.get("plan.enabled");case"unexpectedStopDetection":return!0===b.get("features.unexpectedStopDetection")}})(a,J))??[],[k?.fields,J]),L=i.startsWith("settings:")?i.slice(9):null,M=(0,e.useMemo)(()=>{let a=q.trim().toLowerCase();return a?K.filter(b=>`${b.label} ${b.description} ${b.path} ${b.group??""}`.toLowerCase().includes(a)):L?K.filter(a=>a.tab===L&&("appearance"!==L||"Theme"!==a.group)):[]},[L,q,K]),N=(0,e.useCallback)(()=>{g?.(),f()},[f,g]),O=(0,e.useCallback)(async()=>{if(b){A(!0);try{await fK(b,{type:"reload"}),y(!1),h?.()}catch(a){p(a instanceof Error?a.message:String(a))}finally{A(!1)}}},[h,b]),P=k?.tabs.find(a=>a.id===L),Q=q.trim()?`${G("Search")} \xb7 ${M.length}`:P?.label??G("Settings"),R=(a,b)=>[...new Set([...b,...a.map(a=>a.group??"General").filter(a=>!b.includes(a))])].map(b=>{let c=a.filter(a=>(a.group??"General")===b);return c.length?(0,d.jsxs)("section",{className:h4().group,children:[(0,d.jsx)("h3",{className:h4().groupTitle,children:b}),c.map(a=>(0,d.jsx)(im,{field:a,busy:s.has(a.path),error:u[a.path],onSave:b=>void I(a,b)},a.path))]},b):null}),S=()=>m?(0,d.jsx)("div",{className:h4().empty,children:G("Loading omp settings…")}):o||!k?(0,d.jsx)("div",{className:h4().empty,children:o??G("Settings unavailable")}):(0,d.jsxs)("div",{className:h4().scrollContent,children:[(0,d.jsxs)("header",{className:h4().contentHeader,children:[(0,d.jsx)("h2",{className:h4().contentTitle,children:Q}),(0,d.jsx)("p",{className:h4().contentDescription,children:G(q.trim()?"Matching canonical /settings entries across every category.":"Canonical omp /settings values. Changes are saved immediately to the shared agent configuration.")}),w&&b&&(0,d.jsxs)("div",{className:h4().reloadNotice,children:[(0,d.jsx)("span",{children:G("Saved. Reload the active session to apply runtime settings.")}),(0,d.jsx)("button",{type:"button",onClick:()=>void O(),disabled:z,children:G(z?"Reloading…":"Reload session")})]})]}),(0,d.jsx)("div",{className:h4().settingsBody,children:M.length?R(M,P?.groups??[]):(0,d.jsx)("div",{className:h4().empty,children:G("No settings match this search.")})})]});return(0,d.jsx)("div",{className:h4().backdrop,onMouseDown:a=>{a.target===a.currentTarget&&N()},children:(0,d.jsxs)("div",{ref:F,tabIndex:-1,className:h4().window,role:"dialog","aria-modal":"true","aria-label":G("Settings"),children:[(0,d.jsxs)("aside",{className:h4().sidebar,children:[(0,d.jsxs)("div",{className:h4().brand,children:[(0,d.jsx)("div",{className:h4().eyebrow,children:"omp /settings"}),(0,d.jsx)("h1",{className:h4().title,children:G("Settings")}),(0,d.jsx)("code",{className:h4().context,title:a??G("Global configuration"),children:a??G("Global configuration")})]}),(0,d.jsxs)("div",{className:h4().searchWrap,children:[(0,d.jsxs)("svg",{className:h4().searchIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,d.jsx)("path",{d:"m20 20-4-4"})]}),(0,d.jsx)("input",{className:h4().search,value:q,"aria-label":G("Search /settings"),placeholder:G("Search /settings"),onChange:a=>r(a.target.value)})]}),(0,d.jsxs)("nav",{className:h4().nav,children:[(0,d.jsx)("div",{className:h4().navLabel,children:G("Configuration")}),ie.map(b=>{let c=b.labelKey?E(b.labelKey):G(b.label);return(0,d.jsxs)("button",{type:"button",className:h4().navButton,"data-active":!q&&i===b.id,disabled:b.requiresCwd&&!a,title:b.requiresCwd&&!a?`${c} ${G("requires a project")}`:c,onClick:()=>{r(""),j(b.id)},children:[(0,d.jsx)(ih,{kind:b.icon}),(0,d.jsx)("span",{children:c})]},b.id)}),(0,d.jsx)("div",{className:h4().navLabel,children:G("OMP settings")}),k?.tabs.map(a=>(0,d.jsxs)("button",{type:"button",className:h4().navButton,"data-active":!q&&L===a.id,onClick:()=>{r(""),j(`settings:${a.id}`)},children:[(0,d.jsx)(ih,{kind:a.id}),(0,d.jsx)("span",{children:a.label})]},a.id))]}),(0,d.jsx)("div",{className:h4().closeRail,children:(0,d.jsxs)("button",{type:"button",className:h4().closeButton,onClick:N,children:[(0,d.jsx)("span",{children:G("Close settings")}),(0,d.jsx)("span",{"aria-hidden":"true",children:"\xd7"})]})})]}),(0,d.jsx)("main",{className:h4().content,children:q.trim()?S():"models"===i?(0,d.jsx)(hH,{cwd:a,embedded:!0,onClose:N,onModelsChanged:g}):"themes"===i?k?(0,d.jsxs)("div",{className:h4().scrollContent,children:[(0,d.jsxs)("header",{className:h4().contentHeader,children:[(0,d.jsx)("h2",{className:h4().contentTitle,children:G("Themes")}),(0,d.jsxs)("p",{className:h4().contentDescription,children:[G("The web interface uses the same dark and light theme mappings as omp. Changes are persisted to "),(0,d.jsx)("code",{children:"~/.omp/agent/config.yml"}),G(" and applied here immediately.")]})]}),(0,d.jsxs)("div",{className:h4().settingsBody,children:[(0,d.jsx)("div",{className:h4().themeGrid,children:["dark","light"].map(a=>{let b=k.fields.find(b=>b.path===`theme.${a}`),c=k.theme.palettes[a];return(0,d.jsxs)("div",{className:h4().themeCard,children:[(0,d.jsx)(io,{mode:a,palette:c}),(0,d.jsxs)("div",{className:h4().themeCardBody,children:[(0,d.jsxs)("div",{className:h4().themeCardHeader,children:[(0,d.jsxs)("span",{className:h4().themeSlot,children:[a,G(" mapping")]}),B===a&&(0,d.jsx)("span",{className:h4().themeActive,children:G("Active on web")})]}),(0,d.jsx)(gN,{value:String(b.value),disabled:s.has(b.path),ariaLabel:`${a} theme`,options:(b.options??[]).map(a=>({value:a.value,label:a.label,description:a.description})),onChange:a=>void I(b,a)}),B!==a&&(0,d.jsxs)("button",{type:"button",className:h4().closeButton,style:{marginTop:8},onClick:()=>C(a),children:[G("Preview "),a]})]})]},a)})}),R(k.fields.filter(a=>"appearance"===a.tab&&"Theme"===a.group&&!a.path.startsWith("theme.")),["Theme"])]})]}):(0,d.jsx)("div",{className:h4().empty,children:m?G("Loading themes…"):o??G("Themes unavailable")}):"skills"===i&&a?(0,d.jsx)(hQ,{cwd:a,embedded:!0,onClose:N}):"plugins"===i&&a?(0,d.jsx)(h2,{cwd:a,sessionId:b,embedded:!0,onClose:N,onReloaded:h}):"mcp"===i?(0,d.jsx)(ir,{cwd:a,sessionId:b,onReloaded:h}):"access"===i?(0,d.jsx)(h5,{}):"trust"===i?(0,d.jsx)(ic,{cwd:a}):"live-voice"===i?(0,d.jsx)(ia,{}):"attachments"===i?(0,d.jsx)(ib,{}):S()})]})})}function ir({cwd:a,sessionId:b,onReloaded:c}){let[f,g]=(0,e.useState)(null),[h,i]=(0,e.useState)("user"),[j,k]=(0,e.useState)(0),[l,m]=(0,e.useState)(""),[n,o]=(0,e.useState)(""),[p,q]=(0,e.useState)(null),[r,s]=(0,e.useState)(!1),[t,u]=(0,e.useState)(null),v=(0,e.useCallback)(async()=>{try{let b=a?`?cwd=${encodeURIComponent(a)}`:"",c=await fetch(`/api/mcp${b}`,{cache:"no-store"}),d=await c.json();if(!c.ok||d.error)throw Error(d.error??`HTTP ${c.status}`);g(d),q(null)}catch(a){q(a instanceof Error?a.message:String(a))}},[a]),w=f?"user"===h?f.user:f.project:null,x=w?.servers[j]??null,y=a=>{g(b=>{if(!b)return b;let c={..."user"===h?b.user:b.project,servers:a};return"user"===h?{...b,user:c}:{...b,project:c}})},z=async()=>{if(w){s(!0),q(null);try{let b,c=(b=w?.servers??[],(x?.editable===!1?b:b.map((a,b)=>b===j?{...a,name:n,config:JSON.parse(l)}:a)).filter(a=>!1!==a.editable).map(({name:a,config:b})=>({name:a,config:b}))),d=a?`?cwd=${encodeURIComponent(a)}`:"",e=await fetch(`/api/mcp${d}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:h,servers:c})}),f=await e.json();if(!e.ok||f.error)throw Error(f.error??`HTTP ${e.status}`);await v()}catch(a){q(a instanceof Error?a.message:String(a))}finally{s(!1)}}},A=async d=>{u(`${h}:${d.name}`),q(null);try{let e=a?`?cwd=${encodeURIComponent(a)}`:"",f=await fetch(`/api/mcp${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:h,name:d.name,enabled:!d.enabled})}),g=await f.json();if(!f.ok||g.error)throw Error(g.error??`HTTP ${f.status}`);await v(),b&&(await fK(b,{type:"reload"}),c?.())}catch(a){q(a instanceof Error?a.message:String(a))}finally{u(null)}};return(0,d.jsxs)("div",{className:h4().scrollContent,children:[(0,d.jsxs)("header",{className:h4().contentHeader,children:[(0,d.jsx)("h2",{className:h4().contentTitle,children:"MCP servers"}),(0,d.jsx)("p",{className:h4().contentDescription,children:"All MCP servers discovered by OMP are listed by scope and can be enabled or disabled here. Native OMP entries are editable; configurations owned by Claude, Codex, Gemini, plugins, or other providers remain read-only at their source."})]}),(0,d.jsx)("div",{className:h4().settingsBody,children:f?(0,d.jsxs)("div",{className:h4().mcpLayout,children:[(0,d.jsxs)("aside",{className:h4().mcpList,children:[(0,d.jsxs)("div",{className:h4().scopeTabs,children:[(0,d.jsxs)("button",{type:"button",className:h4().scopeButton,"data-active":"user"===h,onClick:()=>{i("user"),k(0)},children:["User \xb7 ",f.user.servers.length]}),(0,d.jsxs)("button",{type:"button",className:h4().scopeButton,"data-active":"project"===h,disabled:!f.project,onClick:()=>{i("project"),k(0)},children:["Project \xb7 ",f.project?.servers.length??0]})]}),w?.error?(0,d.jsx)("div",{className:h4().error,style:{padding:12},children:w.error}):(0,d.jsx)("div",{className:h4().serverRows,children:w?.servers.length?w.servers.map((a,b)=>{let c=`${h}:${a.name}`;return(0,d.jsxs)("div",{className:h4().serverRow,"data-active":j===b,children:[(0,d.jsxs)("button",{type:"button",className:h4().serverSelect,title:a.source?.path,onClick:()=>k(b),children:[(0,d.jsx)("span",{className:h4().statusDot,"data-off":!a.enabled}),(0,d.jsx)("span",{className:h4().serverName,children:a.name}),!1===a.editable&&(0,d.jsx)("span",{className:h4().sourceBadge,children:a.source?.provider??"external"})]}),(0,d.jsx)("button",{type:"button",className:h4().serverToggle,"data-on":a.enabled,disabled:t===c,"aria-pressed":a.enabled,"aria-label":`${a.enabled?"Disable":"Enable"} ${a.name}`,title:`${a.enabled?"Disable":"Enable"} ${a.name}`,onClick:()=>void A(a),children:t===c?"…":a.enabled?"ON":"OFF"})]},`${a.name}-${a.source?.path??b}`)}):(0,d.jsx)("div",{className:h4().serverListEmpty,children:"No servers in this scope."})}),(0,d.jsx)("button",{type:"button",className:h4().addServer,disabled:!!w?.error,onClick:()=>{if(!w)return;let a="new-server",b=2;for(;w.servers.some(b=>b.name===a);)a=`new-server-${b++}`;let c=[...w.servers,{name:a,config:{type:"stdio",command:""},enabled:!0,editable:!0}];y(c),k(c.length-1)},children:"+ Add OMP server"})]}),(0,d.jsx)("section",{className:h4().mcpEditor,children:x?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{className:h4().editorHeader,children:[(0,d.jsx)("input",{className:h4().textInput,value:n,readOnly:!1===x.editable,onChange:a=>o(a.target.value),placeholder:"server-name"}),!1!==x.editable&&(0,d.jsx)("button",{type:"button",className:h4().dangerButton,onClick:()=>{w&&x&&!1!==x.editable&&(y(w.servers.filter((a,b)=>b!==j)),k(Math.max(0,j-1)))},children:"Delete"})]}),!1===x.editable&&(0,d.jsxs)("div",{className:h4().readOnlyNotice,children:["Configuration read-only \xb7 managed by ",x.source?.provider??"an external provider",". Status can be changed from the server list."]}),(0,d.jsx)("textarea",{className:h4().jsonEditor,value:l,readOnly:!1===x.editable,spellCheck:!1,onChange:a=>m(a.target.value)}),(0,d.jsxs)("div",{className:h4().editorActions,children:[(0,d.jsxs)("div",{children:[p&&(0,d.jsx)("div",{className:h4().error,children:p}),(0,d.jsx)("div",{className:h4().saveState,children:x.source?.path??w?.path})]}),!1!==x.editable&&(0,d.jsx)("button",{type:"button",className:h4().primaryButton,disabled:r,onClick:()=>void z(),children:r?"Saving…":"Save MCP"})]})]}):(0,d.jsx)("div",{className:h4().empty,children:"Add or select an MCP server."})})]}):(0,d.jsx)("div",{className:h4().empty,children:p??"Loading MCP configuration…"})})]})}function is({variant:a,locale:b,permission:c,dismissed:e,request:f,dismiss:g}){let h="ko"===b;return null===c||"granted"===c?null:"banner"===a?"default"!==c||e?null:(0,d.jsxs)("div",{className:"workspace-update-banner",role:"region","aria-label":h?"알림 권한 안내":"Notification permission",children:[(0,d.jsx)("span",{className:"workspace-update-banner-detail",style:{fontFamily:"inherit",fontSize:"inherit",color:"inherit"},children:h?"백그라운드 작업 완료 알림을 받으세요.":"Get notified when background work finishes."}),(0,d.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:f,children:h?"알림 켜기":"Enable notifications"}),(0,d.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:g,"aria-label":h?"알림 권한 안내 닫기":"Dismiss notification prompt",children:h?"닫기":"Dismiss"})]}):(0,d.jsx)(k.k.Item,{disabled:"denied"===c,onClick:"default"===c?f:void 0,children:(0,d.jsxs)(k.k.ItemBody,{children:[(0,d.jsx)(k.k.ItemLabel,{children:"default"===c?h?"알림 켜기":"Enable notifications":h?"알림 차단됨":"Notifications blocked"}),"denied"===c&&(0,d.jsx)(k.k.ItemDescription,{children:h?"주소창 옆 사이트 설정에서 알림을 허용하세요.":"Allow notifications in site settings beside the address bar."})]})})}function it({cwd:a,busy:b,scheduled:c,error:f,onCancel:g,onConfirm:h,onCancelSchedule:i}){let{t:j}=(0,x.s)(),k=(0,e.useRef)(null),l={height:32,padding:"0 12px",borderRadius:5,cursor:b?"not-allowed":"pointer",fontSize:12};return(0,d.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"rgba(0,0,0,0.4)"},onClick:a=>{b||a.target!==a.currentTarget||g()},children:(0,d.jsxs)("div",{role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title","aria-describedby":"project-trust-body",style:{width:440,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg-panel)",boxShadow:"0 12px 36px rgba(0,0,0,0.24)",overflow:"hidden"},children:[(0,d.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,d.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:1},children:[(0,d.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),c?(0,d.jsx)("path",{d:"M12 8v4l2 2"}):(0,d.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsx)("div",{id:"project-trust-title",style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:j(c?"trust.scheduledTitle":"trust.dialogTitle")}),(0,d.jsx)("div",{id:"project-trust-body","aria-live":"polite",style:{marginTop:7,fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:j(c?"trust.scheduledBody":"trust.dialogBody")}),(0,d.jsx)("code",{style:{display:"block",marginTop:10,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:a}),f&&(0,d.jsx)("div",{role:"alert",style:{marginTop:10,color:"#ef4444",fontSize:12,lineHeight:1.5},children:f})]})]}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[c&&(0,d.jsx)("button",{type:"button",onClick:i,disabled:b,style:{...l,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:j("trust.cancelSchedule")}),(0,d.jsx)("button",{ref:k,type:"button",onClick:g,disabled:b,style:{...l,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:j(c?"trust.close":"trust.cancel")}),!c&&(0,d.jsx)("button",{type:"button",onClick:h,disabled:b,style:{...l,border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:b?"wait":"pointer",opacity:b?.7:1,fontWeight:600},children:j(b?"trust.trusting":"trust.trustProject")})]})]})})}var iu=c(99952),iv=c(27332);let iw={kind:"loading"};function ix(a){return"failed"===a.status?"var(--danger)":"aborted"===a.status||a.progress?.retryState?"var(--warning)":(0,dY.Ch)(a.status)?"var(--accent)":"var(--success)"}function iy(a){return"live-archive"===a.identity?"실시간 + 디스크":"live"===a.identity?"실시간":"디스크 기록"}let iz={bundled:"기본 제공",user:"사용자 정의",project:"프로젝트 정의"};function iA(a){return a.lastUpdate||a.progress?.durationMs||0}function iB(){return{display:"grid",placeItems:"center",width:32,height:30,padding:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"}}function iC({sessionId:a,sessionCwd:b,record:c,client:f,visible:g,onBack:h}){let i=(0,e.useMemo)(()=>[{key:c.key,liveId:c.live?.id,status:c.live?.status,archiveName:c.archive?.name}],[c.key,c.live?.id,c.live?.status,c.archive?.name]),j=(0,e.useRef)(null),k=(0,dY._Z)(i,{sessionId:a,client:f,enabled:g}).get(c.key)?.state??iw,l="ready-live"===k.kind?k.entries:[],m=(0,e.useMemo)(()=>{let a=new Map;for(let b of l)"message"in b&&"toolResult"===b.message.role&&a.set(b.message.toolCallId,b.message);return a},[l]),n=c.live?.id||c.archive?.name||"Subagent";return(0,d.jsxs)("div",{role:"dialog","aria-label":`${n} 기록`,style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:0},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",borderBottom:"1px solid var(--border)"},children:[(0,d.jsx)("button",{type:"button",onClick:h,"aria-label":"Subagent 목록으로 돌아가기",title:"목록",style:iB(),children:(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m10.5 3-5 5 5 5"})})}),(0,d.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,d.jsx)("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11.5,fontWeight:700},children:n}),(0,d.jsx)("div",{style:{marginTop:2,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9},children:iy(c)})]}),c.live&&(0,d.jsx)("span",{style:{color:ix(c.live),fontFamily:"var(--font-mono)",fontSize:9.5},children:c.live.status})]}),(0,d.jsxs)("div",{ref:j,style:{flex:1,minHeight:0,overflowY:"auto",padding:"10px 12px 18px"},children:["loading"===k.kind&&(0,d.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"기록 불러오는 중…"}),"ready-live"===k.kind&&k.entries.flatMap((a,c)=>{if(!("message"in a))return[];let e=k.entries[c-1];return[(0,d.jsx)(cX,{message:a.message,toolResults:m,cwd:b,showTimestamp:!0,prevTimestamp:e&&"message"in e?e.message.timestamp:void 0},a.id)]}),"ready-archive"===k.kind&&(0,d.jsxs)(d.Fragment,{children:[k.note&&(0,d.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--text-muted)",fontSize:9.5,lineHeight:1.5},children:k.note}),k.truncated&&(0,d.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--warning)",fontSize:9.5},children:"최근 400개 기록만 표시합니다."}),k.entries.map((a,b)=>(0,d.jsxs)("div",{style:{margin:"0 0 7px",padding:"8px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontSize:11,lineHeight:1.55},children:[(0,d.jsxs)("div",{style:{marginBottom:5,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:8.5,letterSpacing:"0.04em"},children:[a.role," \xb7 ",a.kind]}),a.text||"(내용 없음)"]},`${a.at??0}:${b}`))]}),"empty"===k.kind&&(0,d.jsxs)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:[k.note&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{children:k.note}),(0,d.jsx)("br",{})]}),"대화 내용이 없습니다."]}),"unreachable"===k.kind&&(0,d.jsx)("div",{role:"status",style:{padding:10,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",fontSize:10.5,lineHeight:1.5},children:k.message}),"error"===k.kind&&(0,d.jsx)("div",{role:"alert",style:{padding:10,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--danger)",fontSize:10.5,lineHeight:1.5},children:k.message})]})]})}function iD({record:a,onSelect:b}){let c=a.live,e=a.archive,f=(0,b4.$V)(a),g=c?.id||e?.name||"Subagent",h=iy(a),i=(0,b4.wX)(a),j=(0,b4.A7)(a),k=j.modelShort??"모델 미확인",l=j.effort??"추론 미확인",m="known"===i.kind?i.label:"역할 미확인";return(0,d.jsxs)("button",{type:"button",role:"listitem",onClick:b,"data-identity":a.identity,title:`${g}
|
|
18
|
+
${c}`:a:c,images:g,documents:h}}function eJ(a,b,c){if(a===b)return c?eD(c):eF(b);let d=eF(a),e=c&&!eE(c)?eD(c):d??(c?eD(c):null),f=eF(b),g=es.get(a);if(es.delete(a),g&&!es.has(b)&&es.set(b,g),eH(a),!e)return f;let h=f?eI(f.value,f.images,e.value,e.images,f.documents,e.documents):e;return eG(b,h),eD(h)}function eK(a){let b=[];for(let c of a??[])c.attachmentId&&!b.includes(c.attachmentId)&&b.push(c.attachmentId);return b}function eL(a){eC();let b=es.get(a);return b||(b=function(){let a=globalThis.crypto;if("function"==typeof a?.randomUUID)return a.randomUUID();let b=a.getRandomValues(new Uint8Array(16));b[6]=15&b[6]|64,b[8]=63&b[8]|128;let c=[...b].map(a=>a.toString(16).padStart(2,"0")).join("");return`${c.slice(0,8)}-${c.slice(8,12)}-${c.slice(12,16)}-${c.slice(16,20)}-${c.slice(20)}`}(),es.set(a,b)),b}function eM(a){let b=eK(ep.get(a)?.documents),c=b.length?eL(a):es.get(a);for(let[a,c]of ey){for(let a of b)c.delete(a);0===c.size&&ey.delete(a)}let d=`${c??""}|${b.join(",")}`;eA.get(a)!==d&&(0!==b.length||c?eA.set(a,d):eA.delete(a),eO())}async function eN(a){let b=eL(a);ex.set(b,(ex.get(b)??0)+1),await eB.get(b);let c=!1;return{draftId:b,end(a){if(c)return;c=!0;let d=(ex.get(b)??1)-1;if(d>0?ex.set(b,d):ex.delete(b),a){let c=ey.get(b)??new Set;c.add(a),ey.set(b,c)}et.set(b,eu),eO()}}}function eO(){}let eP=Math.floor(Number.MAX_SAFE_INTEGER/1048576),eQ=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function eR(a){return"number"==typeof a&&Number.isSafeInteger(a)&&a>=1&&a<=eP}async function eS(a){let b,c=await a.json().catch(()=>null);if(!a.ok||!c||!eR(c.uploadLimitMb)||"boolean"!=typeof c.autoCleanupEnabled)throw Error("string"==typeof c?.error?c.error:`HTTP ${a.status}`);return{uploadLimitMb:eR((b=c&&"object"==typeof c?c:{}).uploadLimitMb)?b.uploadLimitMb:eQ.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof b.autoCleanupEnabled?b.autoCleanupEnabled:eQ.autoCleanupEnabled,orphanGraceDays:7}}async function eT(a={}){return eS(await fetch("/api/attachment-settings",{cache:"no-store",signal:a.signal}))}async function eU(a){return eS(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}))}function eV(a){let b=/(?:^|\s)@"([^"\n]*)$/.exec(a);if(b)return{start:a.length-(b[1].length+2),query:b[1],quoted:!0};let c=/(?:^|\s)@([^\s"]*)$/.exec(a);return c?{start:a.length-(c[1].length+1),query:c[1],quoted:!1}:null}function eW(a){let b=0;for(let c=0;c<a.length;c++)"/"===a[c]&&b++;return b}function eX(a,b){if(!a)return!0;let c=0;for(let d=0;d<b.length&&c<a.length;d++)b[d]===a[c]&&c++;return c===a.length}let eY="omp-web:model-picks";function eZ(){try{let a=JSON.parse(window.localStorage.getItem(eY)??"{}");if(!a||"object"!=typeof a||Array.isArray(a))return{};let b={};for(let[c,d]of Object.entries(a))"number"==typeof d&&Number.isFinite(d)&&d>0&&(b[c]=Math.floor(d));return b}catch{return{}}}function e$(a,b,c,d,e={}){let f=e.gap??8,g=e.margin??8,h=e.prefer??"above",i=Math.min(e.minHeight??120,Math.max(0,c-2*g)),j=Math.max(0,a-f-g),k=Math.max(0,c-b-f-g),l="above"===h?j:k,m="above"===h?k:j,n=l>=d||l>=m;return{side:n?h:"above"===h?"below":"above",maxHeight:Math.max(i,Math.min(d,n?l:m))}}function e_(a,b,c){return Math.min(a*b,c)}function e0(a,b,c){let{viewportFraction:d,cap:f,gap:g,margin:h,minHeight:i,prefer:j}=c,[k,l]=(0,e.useState)({side:j??"above",maxHeight:f});return(0,e.useCallback)(()=>{let b=a.current;if(!b)return;let c=window.visualViewport?.height??window.innerHeight,e=b.getBoundingClientRect(),k=e$(e.top,e.bottom,c,e_(c,d,f),{gap:g,margin:h,minHeight:i,prefer:j});l(a=>a.side===k.side&&a.maxHeight===k.maxHeight?a:k)},[a,f,g,h,i,j,d]),k}var e1=c(29947);async function e2(a,b,c,d,e,f,g){let h=a.slice(1).split(/\s/,1)[0];try{let i=b?.length?b:await g?.()??[],j=[...fg,...i].find(a=>a.name===h||"aliases"in a&&a.aliases?.includes(h));if(f&&(!j||"builtin"===j.source))return e(`/${h} cannot run with attachments. Remove them and retry.`),!1;let k=await c?.(a);if(k?.handled){if(k.error)return!1;return k.prompt&&d(k.prompt),!0}if(j&&"builtin"!==j.source)return d(a),!0;return e(`/${h} is not available in this web session.`),!1}catch(a){return e(a instanceof Error?a.message:String(a)),!1}}function e3(a){let b=a.transcription?.state;return"planning"===b||"confirm"===b||"running"===b}let e4=["off","default","full"],e5={off:"none",default:"default",full:"full"},e6=e1.IN.join(" \xb7 "),e7=e1.C1.filter(a=>!e1.IN.includes(a)).join(" \xb7 ");function e8(a){return"above"===a?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let e9=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),fa=0,fb={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function fc(a,b){return e9.compare(a.name||a.modelId,b.name||b.modelId)||e9.compare(a.provider,b.provider)||e9.compare(a.modelId,b.modelId)}let fd=["auto","off","minimal","low","medium","high","xhigh","max"],fe=["low","medium","high","xhigh"],ff={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},fg=[{name:"compact",descriptionKey:"chat.commandCompact",source:"builtin"},{name:"reload",descriptionKey:"chat.commandReload",source:"builtin"},{name:"name",descriptionKey:"chat.commandName",source:"builtin"},{name:"session",descriptionKey:"chat.commandSession",source:"builtin"},{name:"copy",descriptionKey:"chat.commandCopy",source:"builtin"}],fh=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],fi={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},fj={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function fk(a,b,c){let d=a.name.toLowerCase(),e=fl(a,c).toLowerCase();return d===b?0:d.startsWith(b)?1:d.includes(b)?2:e.includes(b)?3:4}function fl(a,b){return"descriptionKey"in a?b(a.descriptionKey):a.description??""}function fm(a,b){return"skill"===a.source&&!!a.name.startsWith("skill:")&&!0===b[a.name.slice(6)]}function fn(a){return{data:a.data,mimeType:a.mimeType}}function fo(a){return{...a,previewUrl:`data:${a.mimeType};base64,${a.data}`}}function fp(a){return(a??[]).filter(eo).slice(0,10).map(fo)}let fq=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,fr="\n\nTranscript of the audio ";function fs(a){return cy(a).map(a=>{let b=cF(a),c="audio"===b&&a.attachmentId&&!a.text.includes(fr)?fq.exec(a.text):null;return{...a,id:++fa,status:"ready",..."audio"===b||"file"===b?{stored:b}:{},...c?{storedInfo:{path:c[1],mimeType:c[2],size:Number(c[3])}}:{}}})}function ft({name:a,mimeType:b,size:c,text:d,attachmentId:e}){return e?{name:a,mimeType:b,size:c,text:d,attachmentId:e}:{name:a,mimeType:b,size:c,text:d}}function fu(a,b){let c=new Map(b.flatMap(a=>a.attachmentId?[[a.attachmentId,a]]:[]));return[...a.map(a=>{let b=a.attachmentId?c.get(a.attachmentId):void 0;return b?(c.delete(a.attachmentId),{...a,id:b.id,sourceSize:b.sourceSize,storedInfo:b.storedInfo??a.storedInfo,transcription:b.transcription}):a}),...b.filter(a=>"ready"!==a.status)]}class fv extends Error{constructor(a,b,c,d){super(a),this.code=b,this.completedParts=c,this.parts=d}}let fw="composer:unkeyed";async function fx(a){let b=await a.json().catch(()=>null),c=b&&"object"==typeof b?{...b}:{};if(a.ok)return c;throw new fv("string"==typeof c.error?c.error:`HTTP ${a.status}`,"string"==typeof c.code?c.code:null,"number"==typeof c.completedParts?c.completedParts:null,"number"==typeof c.parts?c.parts:null)}function fy(a){a.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(a.previewUrl)}function fz({tone:a,title:b,body:c}){let e="error"===a?"danger":"warning";return(0,d.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid var(--${e}-line)`,borderRadius:"var(--radius-control)",background:`var(--${e}-soft)`,color:`var(--${e})`,fontSize:11,lineHeight:1.45},children:[(0,d.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,d.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,d.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,d.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsx)("div",{style:{fontWeight:600},children:b}),(0,d.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:c})]})]})}function fA({error:a}){return a?(0,d.jsx)(fz,{tone:"error",title:"Model error",body:a}):null}function fB({warnings:a}){return a&&0!==a.length?(0,d.jsx)(fz,{tone:"warning",title:a.length>1?"Model scope warnings":"Model scope warning",body:a.join("\n")}):null}let fC=(0,e.forwardRef)(function({onSend:a,onAbort:b,onSteer:c,onFollowUp:g,isStreaming:i,model:j,isAutoModelSelection:k,modelNames:l,modelList:m,modelError:n,modelScopeWarnings:o,onModelChange:p,onMainPresetChange:q,mainPresetActiveAlias:r,modelRoles:s,onRoleModelChange:t,modelSwitching:u,onCompact:v,onAbortCompaction:w,isCompacting:y,compactError:z,compactResult:A,toolPreset:B,onToolPresetChange:C,thinkingLevel:E,effectiveThinkingLevel:F,thinkingCeiling:G,onThinkingLevelChange:H,availableThinkingLevels:I,thinkingLevelMap:J,fastMode:K=null,fastModeBusy:L=!1,onFastModeToggle:M,retryInfo:N,deliveryRows:O=[],inputHistory:P=[],onRecallQueue:Q,onRemoveQueuedMessage:R,slashCommands:S,slashCommandsLoading:T,onLoadSlashCommands:U,onBuiltinCommand:V,soundEnabled:W,onSoundToggle:X,onAudioUnlock:Y,onPromptWithStreamingBehavior:Z,draftKey:$,cwd:_,sessionId:aa,onEnsureSession:ab,onLiveTranscriptPersisted:ac},ad){let ae,af,ag,ah,ai,aj,ak,al,am,an,{t:ao}=(0,x.s)(),{st:ap}=bT(),aq=O.some(a=>a.removable),ar=D(),[as,at]=(0,e.useState)(()=>$?eF($)?.value??"":""),[au,av]=(0,e.useState)(!1),[aw,ax]=(0,e.useState)(null),[ay,az]=(0,e.useState)(""),[aA,aB]=(0,e.useState)({});(0,e.useEffect)(()=>{au&&aB(eZ())},[au]);let[aC,aD]=(0,e.useState)(!1),[aE,aF]=(0,e.useState)(null),[aG,aH]=(0,e.useState)(!1),[aI,aJ]=(0,e.useState)(!1),[aK,aL]=(0,e.useState)(null),[aM,aN]=(0,e.useState)(!1),[aO,aP]=(0,e.useState)(()=>$?fp(eF($)?.images):[]),[aQ,aR]=(0,e.useState)(()=>$?fs(eF($)?.documents):[]),[aS,aT]=(0,e.useState)(null),aU=(0,e.useMemo)(()=>aQ.filter(a=>"ready"===a.status),[aQ]),aV=aQ.some(a=>"ready"!==a.status||e3(a)),aW=aQ.filter(a=>"audio"===a.stored&&a.attachmentId&&a.storedInfo&&(void 0!==a.transcription||!a.text.includes(fr))),aX=as.trimStart(),aY=0===aO.length&&0===aQ.length&&aX.startsWith("!"),aZ=aY&&aX.startsWith("!!"),[a$,a_]=(0,e.useState)(!1),[a0,a1]=(0,e.useState)(0),[a2,a3]=(0,e.useState)(null),[a4,a5]=(0,e.useState)(!1),[a6,a7]=(0,e.useState)(0),[a8,a9]=(0,e.useState)(!1),[ba,bb]=(0,e.useState)(0),[bc,bd]=(0,e.useState)(null),[be,bf]=(0,e.useState)(!1),[bg,bh]=(0,e.useState)(null),[bi,bj]=(0,e.useState)(null),bk=_&&bi?.cwd===_?bi.values:{},bl=(0,e.useRef)(null),bm=(0,e.useRef)(null),bn=(0,e.useRef)(null),bo=(0,e.useRef)(null),bp=(0,e.useRef)(null),bq=(0,e.useRef)(null),br=(0,e.useRef)(null),bs=(0,e.useRef)(null),bt=(0,e.useRef)(null),bu=(0,e.useRef)(null),bv=(0,e.useRef)(null),bw=(0,e.useRef)(!1),bx=(0,e.useRef)(0),by=(0,e.useRef)(!1),bA=(0,e.useRef)([]),bB=(0,e.useRef)([]),bC=(0,e.useRef)([]),bD=(0,e.useRef)(null),bE=(0,e.useRef)(null),bF=(0,e.useRef)($),bG=(0,e.useRef)(as),bH=(0,e.useRef)(aO),bI=(0,e.useRef)(0),bK=(0,e.useRef)(aQ);bG.current=as,bH.current=aO,bK.current=aQ,(0,e.useImperativeHandle)(ad,()=>({insertIfEmpty(a){let b=bl.current;(b?b.value:as).trim()||(bG.current=a,at(a),a3(null),requestAnimationFrame(()=>{b&&(b.focus(),b.style.height="auto",b.style.height=`${Math.min(b.scrollHeight,200)}px`)}))},replaceMessage(a){let b,c,d=bl.current;if(!function(a,b,c,d=0){return!a.trim()&&0===b&&0===c&&0===d}(d?d.value:as,bH.current.length,bI.current,bK.current.length))return;let e=(b="string"==typeof a.content?a.content:a.content.filter(a=>"text"===a.type).map(a=>a.text).join("\n"),cB(b)?.message??b),f=fp("string"==typeof a.content?[]:a.content.flatMap(a=>{if("image"!==a.type)return[];let b=a.source?.type==="base64"?a.source.data:a.data,c=a.source?.type==="base64"?a.source.media_type:a.mimeType;if("string"!=typeof b||"string"!=typeof c)return[];let d={data:b,mimeType:c};return eo(d)?[d]:[]})),g=fs((c="string"==typeof a.content?a.content:a.content.filter(a=>"text"===a.type).map(a=>a.text).join("\n"),cB(c)?.documents??[]));bG.current=e,bH.current=f,bK.current=g,at(e),a3(null),a9(!1),aP(a=>(a.forEach(fy),f)),aR(g),requestAnimationFrame(()=>{d&&(d.focus(),d.style.height="auto",d.style.height=`${Math.min(d.scrollHeight,200)}px`)})},rekeyDraft(a,b){if(a===b)return;if(bF.current!==a)return void eJ(a,b);let c={value:bG.current,images:bH.current.map(fn),documents:bK.current.filter(a=>"ready"===a.status).map(ft)},d=eJ(a,b,c)??{value:"",images:[],documents:[]},e=d.value===c.value&&d.images.length===c.images.length&&d.images.every((a,b)=>a.data===c.images[b]?.data&&a.mimeType===c.images[b]?.mimeType)&&d.documents.length===c.documents.length&&d.documents.every((a,b)=>a.name===c.documents[b]?.name&&a.mimeType===c.documents[b]?.mimeType&&a.size===c.documents[b]?.size&&a.text===c.documents[b]?.text&&a.attachmentId===c.documents[b]?.attachmentId);if(bF.current=b,e)return;let f=fp(d.images),g=fu(fs(d.documents),bK.current),h=d.value;bG.current=h,bH.current=f,bK.current=g,at(h),aP(a=>(a.forEach(fy),f)),aR(g),a3(null),a9(!1)},restoreSubmission(a,b,c,d){if(!a.trim()&&!b?.length&&!c?.length)return;let e=bF.current,f=d??e,g=f===e,h=!g&&f?eF(f):null,i=eI(a,b,g?bG.current:h?.value??"",g?bH.current.map(fn):h?.images??[],c,g?bK.current.filter(a=>"ready"===a.status).map(ft):h?.documents??[]);if(f&&eG(f,i),!g)return;let j=b?.length?[...fp(b).slice(0,Math.max(0,10-bH.current.length)),...bH.current].slice(0,10):bH.current,k=fu(fs(i.documents),bK.current);bG.current=i.value,bH.current=j,bK.current=k,at(i.value),a3(null),a9(!1),b?.length&&aP(a=>{let c=Math.max(0,10-a.length),d=fp(b).slice(0,c),e=d.length>0?[...d,...a]:a;return bH.current=e,e}),aR(k),requestAnimationFrame(()=>{let a=bl.current;a&&(a.focus(),a.setSelectionRange(a.value.length,a.value.length),a.style.height="auto",a.style.height=`${Math.min(a.scrollHeight,200)}px`)})},insertText(a){let b=bl.current;if(!b)return void at(b=>b+(b?" ":"")+a);let c=b.selectionStart??b.value.length,d=b.selectionEnd??b.value.length,e=b.value.slice(0,c),f=b.value.slice(d),g=e.length>0&&!e.endsWith(" ")?" ":"",h=e+g+a+f;bG.current=h,at(h),a3(null),requestAnimationFrame(()=>{if(!b)return;let d=c+g.length+a.length;b.setSelectionRange(d,d),b.focus(),b.style.height="auto",b.style.height=`${Math.min(b.scrollHeight,200)}px`})},addAttachments(a){b0(a)}}));let bL=(0,e.useCallback)(async a=>{let b=Math.max(0,10-bH.current.length-bI.current),c=a.filter(a=>a.size>0xa00000);c.length>0&&aT(ao("chat.attachImageTooLarge",{name:c.map(a=>a.name).join(", "),limit:cC(0xa00000)}));let d=a.filter(a=>a.size<=0xa00000),e=d.slice(0,b);if(e.length<d.length&&aT(ao("chat.attachImageLimit",{count:10})),e.length){bI.current+=e.length;try{let a=await Promise.all(e.map(a=>new Promise((b,c)=>{let d=new FileReader;d.onload=()=>{let c=d.result.split(",")[1];b({data:c,mimeType:a.type,previewUrl:URL.createObjectURL(a)})},d.onerror=c,d.readAsDataURL(a)})));aP(b=>{let c=a.slice(0,Math.max(0,10-b.length));a.slice(c.length).forEach(fy);let d=[...b,...c];return bH.current=d,d})}finally{bI.current-=e.length}}},[ao]),bM=(0,e.useCallback)(async a=>{for(let b of a){let a=cu(b);if(!a)continue;if(bK.current.length>=3){aT(ao("chat.attachLimit",{count:3}));continue}if(b.size>8388608){aT(ao("chat.attachTooLarge",{name:b.name,limit:cC(8388608)}));continue}if(bK.current.reduce((a,b)=>a+b.size,0)+b.size>0x1000000){aT(ao("chat.attachTotalTooLarge",{limit:cC(0x1000000)}));continue}let c={id:++fa,name:b.name,mimeType:cr[a],size:b.size,text:"",status:"extracting"},d=[...bK.current,c];bK.current=d,aR(d);try{let a=await cz(b);if(bK.current.reduce((a,b)=>a+(b.id===c.id?0:b.text.length),0)+a.text.length>24e4)throw new cq("text_too_large","Total extracted text exceeds 240000 characters");let d=bK.current.map(b=>b.id===c.id?{...a,id:b.id,status:"ready"}:b);bK.current=d,aR(d)}catch(e){let a=bK.current.some(a=>a.id===c.id),d=bK.current.filter(a=>a.id!==c.id);if(bK.current=d,aR(d),!a)continue;e instanceof cq?"text_too_large"===e.code?aT(ao("chat.attachTextTooLarge",{name:b.name,limit:12e4.toLocaleString()})):"too_many_pages"===e.code?aT(ao("chat.attachTooManyPages",{name:b.name,limit:250})):"no_extractable_text"===e.code?aT(ao("chat.attachNoPdfText",{name:b.name})):"password_protected"===e.code?aT(ao("chat.attachPasswordProtected",{name:b.name})):aT(ao("chat.attachExtractFailed",{name:b.name})):aT(ao("chat.attachExtractFailed",{name:b.name}))}}},[ao]),bN=(0,e.useCallback)((a,b)=>{if(!bK.current.some(b=>b.id===a))return!1;let c=b?bK.current.map(c=>c.id===a?b:c):bK.current.filter(b=>b.id!==a);return bK.current=c,aR(c),!0},[]),bO=(0,e.useCallback)((a,b)=>{if(!bK.current.some(b=>b.attachmentId===a))return!1;let c=bK.current.map(c=>c.attachmentId===a?b(c):c);return bK.current=c,aR(c),!0},[]),bP=(0,e.useCallback)((a,b,c)=>{if(!a||a===bF.current)return;let d=eF(a);d?.documents.some(a=>a.attachmentId===b)&&eG(a,{...d,documents:fs(d.documents).map(a=>a.attachmentId===b?c(a):a).map(ft)})},[]),bQ=(0,e.useRef)(new Map),bR=(0,e.useRef)(new Map),bS=(0,e.useRef)(new Set),bU=(0,e.useCallback)((a,b,c)=>{if(!a.storedInfo)return null;let d=Math.min(12e4,24e4-c.reduce((b,c)=>b+(c.attachmentId===a.attachmentId?0:c.text.length),0)),e=cG({...a.storedInfo,transcript:b},d);return e.length>d?null:{...a,text:e,size:new TextEncoder().encode(e).byteLength,transcription:void 0}},[]),bV=(0,e.useCallback)(a=>a instanceof fv&&"media_tool_unavailable"===a.code?ao("chat.transcribeToolMissing"):a instanceof fv&&"transcription_failed"===a.code&&null!==a.completedParts&&null!==a.parts?ao("chat.transcribePartialFailed",{done:a.completedParts,total:a.parts}):a instanceof Error?a.message:String(a),[ao]),bW=(0,e.useCallback)(async(a,b)=>{let c=bF.current,d=bK.current.find(b=>b.attachmentId===a);if(!d?.storedInfo)return;let e=d.transcription?.state==="confirm"?d.transcription.plan:null;bR.current.get(a)?.abort();let f=new AbortController;bR.current.set(a,f),bO(a,a=>({...a,transcription:{state:"running",plan:e}}));try{let d=await fx(await fetch(`/api/attachments/${encodeURIComponent(a)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b?{confirmed:!0}:{}),signal:f.signal}));if("string"!=typeof d.transcript)throw new fv("Invalid transcription result",null,null,null);let e=d.transcript;bO(a,a=>bU(a,e,bK.current)??{...a,transcription:{state:"failed",error:ao("chat.transcribeTooLong")}})||bP(c,a,a=>bU(a,e,[])??a)}catch(c){if(f.signal.aborted)return void bO(a,a=>({...a,transcription:{state:"skipped"}}));if(c instanceof fv&&"confirmation_required"===c.code)return void bX.current?.(a);let b=bV(c);bO(a,a=>({...a,transcription:{state:"failed",error:b}}))}finally{bR.current.get(a)===f&&bR.current.delete(a)}},[ao,bV,bO,bP,bU]),bX=(0,e.useRef)(null),bY=(0,e.useCallback)(async a=>{let b;bR.current.get(a)?.abort();let c=new AbortController;bR.current.set(a,c),bO(a,a=>({...a,transcription:{state:"planning"}}));try{b=function(a){if("boolean"!=typeof a.requiresConfirmation||"number"!=typeof a.estimatedCalls||"string"!=typeof a.notice||null!==a.durationSeconds&&"number"!=typeof a.durationSeconds||"direct"!==a.processing&&"compress-and-split"!==a.processing)throw new fv("Invalid transcription plan",null,null,null);return{durationSeconds:a.durationSeconds,estimatedCalls:a.estimatedCalls,requiresConfirmation:a.requiresConfirmation,processing:a.processing,notice:a.notice}}(await fx(await fetch(`/api/attachments/${encodeURIComponent(a)}/transcription`,{cache:"no-store",signal:c.signal})))}catch(b){if(c.signal.aborted)bO(a,a=>({...a,transcription:{state:"skipped"}}));else{let c=bV(b);bO(a,a=>({...a,transcription:{state:"failed",error:c}}))}return}finally{bR.current.get(a)===c&&bR.current.delete(a)}b.requiresConfirmation?bO(a,a=>({...a,transcription:{state:"confirm",plan:b}})):await bW(a,!1)},[bW,bV,bO]);bX.current=bY;let bZ=(0,e.useCallback)(a=>{let b=bR.current.get(a);b?b.abort():bO(a,a=>({...a,transcription:{state:"skipped"}}))},[bO]),b$=(0,e.useCallback)(async(a,b)=>{let c=null;for(let d of a){if(bK.current.length>=3){aT(ao("chat.attachLimit",{count:3}));continue}let a="file"===b&&d.size<=8388608,e={id:++fa,name:d.name,mimeType:"text/plain",size:a?d.size:0,text:"",status:a?"extracting":"uploading",sourceSize:d.size},f=[...bK.current,e];bK.current=f,aR(f);let g=(a,b)=>{let c=bK.current.filter(a=>a.id!==e.id);return a<=12e4&&c.reduce((a,b)=>a+b.text.length,0)+a<=24e4&&c.reduce((a,b)=>a+b.size,0)+b<=0x1000000};if(a){let a=await d.arrayBuffer().then(a=>{var b;return 255===(b=new Uint8Array(a))[0]&&254===b[1]?cx("utf-16le",b.subarray(2)):254===b[0]&&255===b[1]?cx("utf-16be",b.subarray(2)):b.includes(0)?null:cx("utf-8",b)??cx("euc-kr",b)},()=>null);if(null!==a&&g(a.length,d.size)){bN(e.id,{...e,text:a,status:"ready"});continue}}if(null===c&&(c=1048576*(await eT().catch(()=>eQ)).uploadLimitMb),d.size>c){bN(e.id,null)&&aT(ao("chat.attachStoredTooLarge",{name:d.name,limit:cC(c)}));continue}let h={...e,stored:b,status:"uploading",size:0};if(!bN(e.id,h))continue;let i=bF.current??fw,j=await eN(i),k=null,l=new AbortController;bQ.current.set(e.id,l);try{if(bS.current.has(e.id))continue;let a=await cH(d,{sessionId:aa,draftId:j.draftId,signal:l.signal}),c=bK.current.filter(a=>a.id!==e.id).reduce((a,b)=>a+b.text.length,0),f=cG({path:a.path,size:a.size,mimeType:a.mimeType},Math.min(12e4,24e4-c)),m=new TextEncoder().encode(f).byteLength;if(!g(f.length,m)){bN(e.id,null)&&aT(ao("chat.attachTotalTooLarge",{limit:cC(0x1000000)}));continue}let n={...h,attachmentId:a.id,text:f,size:m,status:"ready",storedInfo:{path:a.path,size:a.size,mimeType:a.mimeType},..."audio"===b?{transcription:{state:"planning"}}:{}};if(bN(e.id,n))k=a.id;else if(!bS.current.has(e.id)&&i!==bF.current){let b=eF(i)??{value:"",images:[],documents:[]};eG(i,{...b,documents:[...b.documents,ft(n)]}),k=a.id}}catch(a){if(l.signal.aborted)continue;bN(e.id,null)&&aT(ao("chat.attachUploadFailed",{name:d.name,error:a instanceof Error?a.message:String(a)}))}finally{bQ.current.delete(e.id),j.end(k)}k&&"audio"===b&&bK.current.some(a=>a.attachmentId===k)&&bY(k)}},[bN,bY,aa,ao]),b0=(0,e.useCallback)(async a=>{aT(null);let{images:b,documents:c,audio:d,files:e}=function(a){let b=[],c=[],d=[],e=[];for(let f of a)f.type.startsWith("image/")?b.push(f):null!==cu(f)?c.push(f):cw(f)?d.push(f):e.push(f);return{images:b,documents:c,audio:d,files:e}}(a),f=c.filter(a=>a.size>8388608);await Promise.all([bL(b),bM(c.filter(a=>a.size<=8388608)),b$(d,"audio"),b$([...e,...f],"file")])},[bM,b$,bL]),b1=(0,e.useCallback)(a=>{aP(b=>{let c=[...b],[d]=c.splice(a,1);return d&&fy(d),bH.current=c,c})},[]),b3=(0,e.useCallback)(a=>{let b=bK.current.find(b=>b.id===a);if(bS.current.add(a),bQ.current.get(a)?.abort(),b?.attachmentId){bR.current.get(b.attachmentId)?.abort();var c=b.attachmentId;for(let[a,b]of ey)b.delete(c)&&(0===b.size&&ey.delete(a),eO())}let d=bK.current.filter(b=>b.id!==a);bK.current=d,aR(d)},[]),b4=(0,e.useCallback)(()=>{bH.current=[],aP(a=>(a.forEach(fy),[]))},[]),b5=(0,e.useCallback)(()=>{bK.current=[],aR([])},[]),b6=(0,e.useCallback)(()=>{bG.current="",at(""),a3(null),a9(!1),$&&eH($),bF.current&&bF.current!==$&&eH(bF.current),b4(),b5(),aT(null),bl.current&&(bl.current.style.height="auto")},[b5,b4,$]);(0,e.useEffect)(()=>{$&&bF.current===$&&eG($,{value:as,images:aO.map(fn),documents:aU.map(ft)})},[aO,$,aU,as]),(0,e.useEffect)(()=>{let a=bF.current;if(a===$)return;a&&eG(a,{value:bG.current,images:bH.current.map(fn),documents:bK.current.filter(a=>"ready"===a.status).map(ft)});let b=$?eF($):null;bF.current=$;let c=b?.value??"",d=fp(b?.images),e=fs(b?.documents);bG.current=c,bH.current=d,bK.current=e,at(c),a3(null),a9(!1),aP(a=>(a.forEach(fy),d)),aR(e)},[$]),(0,e.useEffect)(()=>{let a=bl.current;a&&(a.style.height="auto",as&&(a.style.height=`${Math.min(a.scrollHeight,200)}px`))},[as]),(0,e.useEffect)(()=>()=>{bH.current.forEach(fy)},[]);let b7=(0,e.useCallback)((a,b)=>{let c=function(a,b){let c=eK(b);if(0===c.length)return()=>{};let d=++ew;return ev.set(d,{draftId:eL(a),ids:c}),a=>{if("accepted"!==a&&"returned"!==a)return;let b=ev.get(d);if(b){if(ev.delete(d),"accepted"===a){let a=ez.get(b.draftId)??new Set;for(let c of b.ids)a.add(c);ez.set(b.draftId,a)}eO()}}}(bF.current??fw,a);Promise.resolve(b()).then(a=>c("accepted"===a||"returned"===a?a:void 0),()=>void 0)},[]),b8=(0,e.useCallback)(async()=>{let b=as.trim(),c=aX.trim(),d=c.startsWith("/")||c.startsWith("!")?c:b;if(!d&&!aO.length&&!aU.length||i||aV)return;Y?.();let e=aO.length?aO:void 0,f=aU.length?aU:void 0;if(d.startsWith("/")){await e2(d,S,V,b=>b7(f,()=>a(b,e,f)),aT,!!(e||f),U)&&b6();return}b6(),b7(f,()=>a(d,e,f))},[as,aX,aO,aU,aV,i,V,S,U,a,b6,Y,b7]),b9=aX.startsWith("/")&&!/\s/.test(aX.slice(1))?aX.slice(1).toLowerCase():null,ca=(()=>{if(null===b9)return[];let a=[...i?[]:fg,...S??[]],b=new Set;return[...a].filter(a=>{let b=a.name.toLowerCase(),c=fl(a,ao).toLowerCase();return b.includes(b9)||c.includes(b9)}).sort((a,b)=>{let c=fk(a,b9,ao)-fk(b,b9,ao);return 0!==c?c:fj[a.source]-fj[b.source]||e9.compare(a.name,b.name)}).filter(a=>{let c=a.name.toLowerCase();return!b.has(c)&&(b.add(c),!0)})})(),{commands:cb,groups:cc}=(ae=0,{commands:(af=fh.map(a=>{let b=ca.filter(b=>b.source===a),c="skill"===a?[...b.filter(a=>!fm(a,bk)),...b.filter(a=>fm(a,bk))]:b;return{source:a,items:c.map(a=>({command:a,index:ae++}))}}).filter(a=>a.items.length>0)).flatMap(a=>a.items.map(({command:a})=>a)),groups:af}),cd=1===ca.length?ao(b9?"chat.match":"chat.command"):ao(b9?"chat.matches":"chat.commands",{count:ca.length}),ce=!!as.trim(),cf=!aV&&(ce||aO.length>0||aU.length>0),cg=(0,e.useCallback)((a,b)=>{if(!_)return void a3(null);let c=b??a.length;a3(eV(a.slice(0,c)))},[_]),ch=a2?.query??null,ci=f().useMemo(()=>null!==ch&&bc&&bc.cwd===_?function(a,b,c=20){let d=b.toLowerCase();if(!d)return a.slice(0,c);let e=[];for(let b of a){let a=function(a,b){let c=a.path.toLowerCase(),d=0;if(b.includes("/"))c===b?d=100:c.startsWith(b)?d=80:c.includes(b)?d=50:eX(b,c)&&(d=10);else{let a=c.lastIndexOf("/"),e=-1===a?c:c.slice(a+1);e===b?d=100:e.startsWith(b)?d=80:e.includes(b)?d=50:c.includes(b)?d=30:eX(b,c)&&(d=10)}return a.isDir&&d>0&&(d+=10),d}(b,d);a>0&&e.push({entry:b,score:a})}return e.sort((a,b)=>b.score-a.score||eW(a.entry.path)-eW(b.entry.path)||a.entry.path.localeCompare(b.entry.path)),e.slice(0,c).map(a=>a.entry)}(bc.entries,ch):[],[ch,bc,_]),cj=!!(ch&&bc?.truncated&&bc.cwd===_);(0,e.useEffect)(()=>{if(!cj||!_||!ch)return;let a=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(_)}&q=${encodeURIComponent(ch)}`).then(a=>{if(!a.ok)throw Error(`file search failed: ${a.status}`);return a.json()}).then(a=>bh({cwd:_,query:ch,matches:a.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(a)},[cj,ch,_]);let ck=cj&&null!==bg&&bg.cwd===_&&bg.query===ch,cl=ck?bg.matches:ci,cm=null===a2?null:`${a2.start}:${+!!a2.quoted}:${a2.query}`;(0,e.useEffect)(()=>{if(null===cm){a5(!1),a7(0);return}a5(!0),a7(0)},[cm]);let cn=null!==a2,co=e0(bu,a8,{viewportFraction:.44,cap:360}),cp=e0(bu,a$,{viewportFraction:.56,cap:460}),cs=e0(bu,a4,{viewportFraction:.48,cap:400});(0,e.useEffect)(()=>{if(!cn||!_)return;let a=bD.current;a&&a.cwd===_&&Date.now()-a.fetchedAt<1e4||bE.current===_||(bE.current=_,bf(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(_)}`).then(a=>{if(!a.ok)throw Error(`file index failed: ${a.status}`);return a.json()}).then(a=>{bd({cwd:_,entries:function(a){let b=new Set;for(let c of a){let a=c.indexOf("/");for(;-1!==a;)b.add(c.slice(0,a)),a=c.indexOf("/",a+1)}let c=[];for(let a of b)c.push({path:a,isDir:!0});for(let b of a)b&&c.push({path:b,isDir:!1});return c.sort((a,b)=>eW(a.path)-eW(b.path)||a.path.localeCompare(b.path)),c}(a.files??[]),truncated:!!a.truncated}),bD.current={cwd:_,fetchedAt:Date.now()}}).catch(()=>{bD.current=null}).finally(()=>{bE.current=null,bf(!1)}))},[cn,_]);let ct=(0,e.useCallback)(a=>{if(!a2)return;let b=bl.current,c=b?.selectionStart??as.length,d=as.slice(0,a2.start),e=as.slice(c);a2.quoted&&e.startsWith('"')&&(e=e.slice(1));let f=function(a,b,c=!1){let d=b?`${a}/`:a,e=c||d.includes(" ");if(b){let a=e?`@"${d}"`:`@${d}`;return{text:a,cursorOffset:e?a.length-1:a.length}}let f=e?`@"${d}" `:`@${d} `;return{text:f,cursorOffset:f.length}}(a.path,a.isDir,a2.quoted),g=d+f.text+e,h=d.length+f.cursorOffset;at(g),a3(eV(g.slice(0,h))),requestAnimationFrame(()=>{let a=bl.current;a&&(a.focus(),a.setSelectionRange(h,h),a.style.height="auto",a.style.height=`${Math.min(a.scrollHeight,200)}px`)})},[a2,as]);(0,e.useEffect)(()=>{a6>=cl.length&&a7(Math.max(0,cl.length-1))},[cl.length,a6]),(0,e.useEffect)(()=>{bB.current.length=cl.length},[cl.length]),(0,e.useEffect)(()=>{a4&&bB.current[a6]?.scrollIntoView({block:"nearest",inline:"nearest"})},[a6,a4]),(0,e.useEffect)(()=>{ba>=P.length&&bb(Math.max(0,P.length-1))},[P.length,ba]),(0,e.useEffect)(()=>{bC.current.length=P.length},[P.length]),(0,e.useEffect)(()=>{a8&&bC.current[ba]?.scrollIntoView({block:"nearest",inline:"nearest"})},[ba,a8]);let cv=(0,e.useCallback)(a=>{bG.current=a,at(a),a9(!1),bb(0),a3(null),requestAnimationFrame(()=>{let b=bl.current;b&&(b.focus(),b.setSelectionRange(a.length,a.length),b.style.height="auto",b.style.height=`${Math.min(b.scrollHeight,200)}px`)})},[]),cy=(0,e.useCallback)(a=>{let b=`/${a.name} `;bG.current=b,at(b),a_(!1),a1(0),requestAnimationFrame(()=>{let a=bl.current;a&&(a.focus(),a.setSelectionRange(b.length,b.length),a.style.height="auto",a.style.height=`${Math.min(a.scrollHeight,200)}px`)})},[]),cA=(0,e.useCallback)(async a=>{let b=as.trim(),d=aX.trim(),e=d.startsWith("/")||d.startsWith("!")?d:b,f=aV||!e&&0===aO.length&&0===aU.length?null:{message:e,images:aO.length?aO:void 0,documents:aU.length?aU:void 0};if(!f)return;Y?.();let h="steer"===a?"steer":"followUp";if(e.startsWith("/")){await e2(e,S,V,a=>{if(!Z)throw Error("Cannot queue this command while the session is busy.");b7(f.documents,()=>Z(a,h,f.images,f.documents))},aT,!!(f.images?.length||f.documents?.length),U)&&b6();return}b6(),"steer"===a&&c?b7(f.documents,()=>c(f.message,f.images,f.documents)):"followup"===a&&g&&b7(f.documents,()=>g(f.message,f.images,f.documents))},[as,aX,aO,aU,aV,S,U,V,Z,c,g,b6,Y,b7]),cD=(0,e.useCallback)(a=>{let b=cb.length-1;if(b<0)return 0;if("left"===a)return Math.max(0,a0-1);if("right"===a)return Math.min(b,a0+1);let c=bA.current[a0];if(!c)return"down"===a?Math.min(b,a0+1):Math.max(0,a0-1);let d=c.getBoundingClientRect(),e=d.left+d.width/2,f=d.top+d.height/2,g=-1,h=1/0;for(let c=0;c<=b;c+=1){if(c===a0)continue;let b=bA.current[c];if(!b)continue;let d=b.getBoundingClientRect(),i=d.top+d.height/2-f;if("down"===a?i<=4:i>=-4)continue;let j=1e3*Math.abs(i)+Math.abs(d.left+d.width/2-e);j<h&&(g=c,h=j)}return g>=0?g:"down"===a?Math.min(b,a0+1):Math.max(0,a0-1)},[cb.length,a0]),cE=(0,e.useCallback)(a=>{let d=a.nativeEvent,e=Date.now()-bx.current<100,f=bw.current||d.isComposing||229===d.keyCode;if("Enter"===a.key&&!a.shiftKey&&(f||e)){e&&a.preventDefault();return}if(a8&&!f){if("ArrowDown"===a.key){a.preventDefault(),bb(a=>Math.min(Math.max(0,P.length-1),a+1));return}if("ArrowUp"===a.key){a.preventDefault(),bb(a=>Math.max(0,a-1));return}if("Escape"===a.key){a.preventDefault(),a9(!1);return}if(("Tab"===a.key||"Enter"===a.key&&!a.shiftKey)&&P[ba]){a.preventDefault(),cv(P[ba]);return}}if(a$&&null!==b9){if("ArrowDown"===a.key){a.preventDefault(),a1(cD("down"));return}if("ArrowUp"===a.key){a.preventDefault(),a1(cD("up"));return}if("ArrowRight"===a.key){a.preventDefault(),a1(cD("right"));return}if("ArrowLeft"===a.key){a.preventDefault(),a1(cD("left"));return}if("Escape"===a.key){a.preventDefault(),a_(!1);return}if(("Tab"===a.key||"Enter"===a.key&&!a.shiftKey)&&cb[a0]){a.preventDefault(),cy(cb[a0]);return}}if(a4&&null!==a2&&!f){if("ArrowDown"===a.key){a.preventDefault(),a7(a=>Math.min(Math.max(0,cl.length-1),a+1));return}if("ArrowUp"===a.key){a.preventDefault(),a7(a=>Math.max(0,a-1));return}if("Escape"===a.key){a.preventDefault(),a5(!1);return}if(("Tab"===a.key||"Enter"===a.key&&!a.shiftKey)&&cl[a6]){a.preventDefault(),ct(cl[a6]);return}}if("ArrowUp"===a.key&&!f&&!i&&P.length>0&&0===as.trim().length){a.preventDefault(),a_(!1),a5(!1),bb(P.length-1),a9(!0);return}if("Escape"===a.key&&!f&&i&&b){a.preventDefault(),b();return}"Enter"!==a.key||a.shiftKey||(a.preventDefault(),i&&(c||g)?cA(c?"steer":"followup"):b8())},[i,c,g,b,a$,b9,cb,a0,cy,cA,b8,cD,a4,a2,cl,a6,ct,a8,P,ba,cv,as]),cF=(0,e.useCallback)(()=>{let a=bl.current;a&&(a.style.height="auto",a.style.height=`${Math.min(a.scrollHeight,200)}px`)},[]),cI=(0,e.useCallback)(a=>{let b=function(a){let b=Array.from(a.files??[]);if(b.length>0)return b;let c=[];for(let b of Array.from(a.items??[])){if("file"!==b.kind)continue;let a=b.getAsFile();a&&c.push(a)}return c}(a.clipboardData);b.length&&(a.preventDefault(),b0(b))},[b0]);(0,e.useEffect)(()=>{if(null===b9){a_(!1),a1(0),by.current=!1;return}a_(!0),a1(0),!by.current&&U&&(by.current=!0,Promise.resolve(U()).catch(()=>{by.current=!1}))},[b9,U]),(0,e.useEffect)(()=>{if(!a$||!_)return;let a=!1;return bj({cwd:_,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(_)}`).then(a=>{if(!a.ok)throw Error(`skills fetch failed: ${a.status}`);return a.json()}).then(b=>{if(a)return;let c={};for(let a of b.skills??[])c[a.name]=a.disableModelInvocation;bj({cwd:_,values:c})}).catch(()=>{a||bj({cwd:_,values:{}})}),()=>{a=!0}},[a$,_]),(0,e.useEffect)(()=>{a0>=cb.length&&a1(Math.max(0,cb.length-1))},[cb.length,a0]),(0,e.useEffect)(()=>{bA.current.length=cb.length},[cb.length]),(0,e.useEffect)(()=>{a$&&bA.current[a0]?.scrollIntoView({block:"nearest",inline:"nearest"})},[a0,a$]);let cJ=m&&m.length>0?m.map(a=>({provider:a.provider,modelId:a.id,name:a.name})).sort(fc):Object.entries(l??{}).map(([a,b])=>({provider:j?.provider??"unknown",modelId:a,name:b})).sort(fc),cK=r??null,cL=bJ.bo.find(a=>a.alias===cK)?.provider??null,cM=cL?cJ.filter(a=>a.provider===cL):cJ,cN=(ag=ay.trim().toLocaleLowerCase())?cM.filter(a=>`${a.name} ${a.modelId}`.toLocaleLowerCase().includes(ag)):cM,cO=cM.length>8,cP=[];for(let a of cN){let b=cP.find(b=>b.provider===a.provider);b?b.options.push(a):cP.push({provider:a.provider,options:[a]})}let cQ=cL?[]:(s??[]).filter(a=>!a.hidden&&a.resolved),cR=j?cQ.find(a=>a.resolved?.provider===j.provider&&a.resolved?.modelId===j.modelId):void 0,cS=ay.trim()?[]:cM.map((a,b)=>{var c,d;return{option:a,order:b,count:aA[c=a.provider,d=a.modelId,`${c}/${d}`]??0}}).filter(a=>a.count>=2).sort((a,b)=>b.count-a.count||a.order-b.order).slice(0,5).map(({option:a,count:b})=>({option:a,count:b})),cT=(a,b,c)=>{let e=a.modelId===j?.modelId&&a.provider===j?.provider;return(0,d.jsxs)("button",{onClick:()=>{if(av(!1),az(""),!e||k){var b,c;let d=function(a,b){let c={...a,[b]:(a[b]??0)+1},d=Object.keys(c);if(d.length<=30)return c;for(let a of(d.sort((a,b)=>c[a]-c[b]),d)){if(Object.keys(c).length<=30)break;a!==b&&delete c[a]}return c}(eZ(),(b=a.provider,c=a.modelId,`${b}/${c}`));try{window.localStorage.setItem(eY,JSON.stringify(d))}catch{}aB(d),p?.(a.provider,a.modelId)}},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:e?"var(--bg-selected)":"none",border:"none",color:e?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:e?600:400,whiteSpace:"nowrap"},onMouseEnter:a=>{e||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{e||(a.currentTarget.style.background="none")},children:[e?(0,d.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,d.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,d.jsx)("span",{style:{width:10,flexShrink:0}}),a.name,void 0!==c&&c>=2&&(0,d.jsx)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10.5},children:ao("chat.modelPickCount",{count:c})})]},`${b}:${a.provider}:${a.modelId}`)},cU=j?cJ.find(a=>a.modelId===j.modelId&&a.provider===j.provider)?.name??j.modelId:null,cV=A?Math.max(0,A.tokensBefore-A.estimatedTokensAfter):0,cW=A?`${A.reason&&"manual"!==A.reason?`${A.reason[0].toUpperCase()}${A.reason.slice(1)} `:ao("chat.compacted")} ${bz(A.tokensBefore)} -> ${bz(A.estimatedTokensAfter)} tokens (${ao("chat.tokensSaved",{saved:bz(cV)})})`:null,cX=a=>{let b=J?.[a];return null!=b&&b!==a?b:null},cY="auto"===(ah=E??"auto")?G?`auto ≤ ${cX(G)??G}`:"auto":J?J[ah]??ah:ah,cZ=(E??"auto")==="auto"&&F&&"auto"!==F?J?.[F]??F:null,c$=H&&cZ?ao("chat.currentReasoning",{level:cZ}):null,c_=a=>!I||I.includes(a),c0=[{level:"auto",ceiling:null},...fe.filter(c_).map(a=>({level:"auto",ceiling:a})),...fd.filter(a=>"auto"!==a&&c_(a)).map(a=>({level:a,ceiling:null}))],c1=Object.entries(e5).find(([,a])=>a===(B??"default"))?.[0]??"default";return(0,e.useEffect)(()=>{let a=a=>{bm.current&&!bm.current.contains(a.target)&&bn.current&&!bn.current.contains(a.target)&&(av(!1),az("")),bo.current&&!bo.current.contains(a.target)&&bp.current&&!bp.current.contains(a.target)&&aD(!1),bq.current&&!bq.current.contains(a.target)&&aH(!1),br.current&&!br.current.contains(a.target)&&aJ(!1),bs.current&&!bs.current.contains(a.target)&&aN(!1),!bt.current||bt.current.contains(a.target)||bl.current?.contains(a.target)||a9(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]),(0,e.useEffect)(()=>{ar||aN(!1)},[ar]),(0,d.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,d.jsx)("input",{ref:bv,type:"file",multiple:!0,style:{display:"none"},onChange:a=>{b0(Array.from(a.target.files??[])),a.target.value=""}}),(0,d.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:[(0,d.jsx)(fA,{error:n}),(0,d.jsx)(fB,{warnings:o}),O.length>0&&(0,d.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",padding:"5px 0"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,d.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:ap("delivery.title",{count:O.length})}),Q&&aq&&(0,d.jsxs)("button",{onClick:Q,title:ao("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:"var(--radius-control)",cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:a=>{a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:a=>{a.currentTarget.style.background="transparent",a.currentTarget.style.borderColor="var(--border)"},children:[(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,d.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),ao("chat.recall")]})]}),(0,d.jsx)(ea,{rows:O,removeLabel:ao("chat.queueRemove"),onRemove:R?(a,b)=>R("steer"===a?"steering":"followUp",b):void 0})]}),N&&(0,d.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--warning-soft)",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--warning)",display:"flex",alignItems:"center",gap:6},children:[(0,d.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,d.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,d.jsx)("path",{d:"M3 3v5h5"})]}),ao("chat.retrying",{attempt:N.attempt,max:N.maxAttempts}),N.errorMessage&&(0,d.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",N.errorMessage]})]}),cW&&(0,d.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--success-soft)",border:"1px solid var(--success-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--success)",display:"flex",alignItems:"center",gap:6},children:[(0,d.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,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}),cW]}),z&&(0,d.jsx)("div",{role:"alert",style:{marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:z}),aS&&(0,d.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontSize:12,lineHeight:1.5},children:[(0,d.jsx)("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"},children:aS}),(0,d.jsx)("button",{type:"button",onClick:()=>aT(null),"aria-label":ao("i18n.close"),title:ao("i18n.close"),style:{flexShrink:0,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"inherit",cursor:"pointer"},children:(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,d.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(aO.length>0||aQ.length>0)&&(0,d.jsxs)("div",{role:"list","aria-label":ao("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[aO.map((a,b)=>(0,d.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,d.jsx)("img",{src:a.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",display:"block"}}),(0,d.jsx)("button",{type:"button","aria-label":ao("chat.removeImage",{index:b+1}),onClick:()=>b1(b),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,d.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,d.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},`image-${b}`)),aQ.map(a=>(0,d.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==a.status||e3(a)||void 0,style:{display:"flex",alignItems:"center",gap:7,minWidth:0,maxWidth:320,height:32,padding:"0 7px 0 9px"},children:["ready"!==a.status||a.transcription?.state==="planning"||a.transcription?.state==="running"?(0,d.jsx)("span",{"aria-hidden":"true",style:{width:13,height:13,flexShrink:0,border:"1.5px solid var(--border-strong)",borderTopColor:"var(--accent)",borderRadius:"50%",animation:"spin 0.8s linear infinite"}}):b2(a.name,14),(0,d.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,d.jsx)("span",{title:a.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:a.name}),(0,d.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===a.stored?ao("chat.attachKindAudio"):"file"===a.stored?ao("chat.attachKindFile"):fb[a.mimeType]," \xb7 ",cC(a.sourceSize??a.size),"extracting"===a.status?` \xb7 ${ao("chat.attachExtracting")}`:"","uploading"===a.status?` \xb7 ${ao("chat.attachUploading")}`:"",a.transcription?.state==="planning"?` \xb7 ${ao("chat.transcribeChecking")}`:"",a.transcription?.state==="confirm"?` \xb7 ${ao("chat.attachTranscribePending")}`:"",a.transcription?.state==="running"?` \xb7 ${ao("chat.attachTranscribing")}`:"",a.transcription?.state==="failed"&&(0,d.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${ao("chat.attachTranscribeFailed")}`})]})]}),(0,d.jsx)("button",{type:"button",onClick:()=>b3(a.id),"aria-label":ao("chat.removeAttachment",{name:a.name}),title:ao("chat.removeAttachment",{name:a.name}),style:{width:24,height:24,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:(0,d.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,d.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},a.id))]}),aW.length>0&&(0,d.jsx)("div",{role:"group","aria-label":ao("chat.transcribeGroup"),"aria-live":"polite",style:{display:"flex",flexDirection:"column",gap:6,marginBottom:6},children:aW.map(a=>{let b,c,e,f,g=a.attachmentId,i=a.transcription,j=i?.state==="confirm"||i?.state==="running"?i.plan:null,k=j?ao("chat.transcribePlanSummary",{duration:null===j.durationSeconds?ao("chat.transcribeDurationUnknown"):(c=Math.floor((b=Math.round(j.durationSeconds))/3600),e=Math.floor(b%3600/60),f=String(b%60).padStart(2,"0"),c>0?`${c}:${String(e).padStart(2,"0")}:${f}`:`${e}:${f}`),calls:j.estimatedCalls}):null,l=i?.state==="confirm"?ao("chat.transcribeConfirmTitle",{name:a.name}):i?.state==="running"?ao("chat.transcribeRunning",{name:a.name}):i?.state==="planning"?`${a.name} \xb7 ${ao("chat.transcribeChecking")}`:i?.state==="failed"?ao("chat.transcribeFailedRow",{name:a.name,error:i.error}):ao("chat.transcribeSkipped",{name:a.name});return(0,d.jsxs)("div",{"data-transcription-state":i?.state??"idle",style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"7px 10px",border:`1px solid ${i?.state==="failed"?"var(--danger-line)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:i?.state==="failed"?"var(--danger-soft)":"var(--bg-panel)",fontSize:12,lineHeight:1.45},children:[(0,d.jsxs)("div",{style:{flex:"1 1 220px",minWidth:0},children:[(0,d.jsx)("div",{style:{color:i?.state==="failed"?"var(--danger)":"var(--text)",overflowWrap:"anywhere"},children:l}),k&&(0,d.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:k}),i?.state==="confirm"&&(0,d.jsxs)(d.Fragment,{children:[i.plan.notice&&(0,d.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:i.plan.notice}),(0,d.jsx)("div",{style:{color:"var(--text-dim)"},children:ao("chat.transcribeUsageNotice")})]})]}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[i?.state==="confirm"&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(h.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void bW(g,!0),children:ao("chat.transcribeStart")}),(0,d.jsx)(h.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>bZ(g),children:ao("chat.transcribeSkip")})]}),(i?.state==="planning"||i?.state==="running")&&(0,d.jsx)(h.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>bZ(g),children:ao("chat.transcribeCancel")}),(void 0===i||"skipped"===i.state||"failed"===i.state)&&(0,d.jsx)(h.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void bY(g),children:ao(i?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},a.id)})}),(0,d.jsxs)("div",{ref:bu,style:{position:"relative",minWidth:0},children:[a8&&P.length>0&&(0,d.jsxs)("div",{ref:bt,style:{position:"absolute",left:0,right:0,...e8(co.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:co.maxHeight},children:[(0,d.jsx)("div",{title:"Input history",style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,d.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,d.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,d.jsx)("path",{d:"M3 4v5h5"}),(0,d.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,d.jsx)("div",{style:{maxHeight:Math.max(0,co.maxHeight-31),overflowY:"auto",padding:4},children:P.map((a,b)=>{let c=b===ba;return(0,d.jsxs)("button",{ref:a=>{bC.current[b]=a},type:"button",onMouseDown:b=>{b.preventDefault(),cv(a)},onMouseEnter:()=>bb(b),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:"var(--radius-control)",background:c?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,d.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:b+1}),(0,d.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:a})]},`${b}:${a}`)})})]}),a$&&null!==b9&&(0,d.jsxs)("div",{style:{position:"absolute",left:0,right:0,...e8(cp.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:cp.maxHeight},children:[(0,d.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)"},children:[(0,d.jsx)("span",{children:T?ao("chat.loadingCommands"):ao("chat.slashCommands",{label:cd})}),(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ao("chat.tabEnter")})]}),(0,d.jsx)("div",{style:{maxHeight:Math.max(0,cp.maxHeight-34),overflowY:"auto",padding:10},children:T||0!==ca.length?cc.map(a=>(0,d.jsxs)("section",{style:{marginBottom:12},children:[(0,d.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,d.jsx)("span",{children:ao(fi[a.source])}),(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:a.items.length})]}),(0,d.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:a.items.map(({command:a,index:b})=>{let c=b===a0,e=fm(a,bk);return(0,d.jsxs)("button",{ref:a=>{bA.current[b]=a},type:"button",onMouseDown:b=>{b.preventDefault(),cy(a)},onMouseEnter:()=>a1(b),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${c?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:c?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:c?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,d.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:e?"var(--text-dim)":void 0},children:["/",a.name,e&&(0,d.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:ao("chat.dormant")})]}),fl(a,ao)&&(0,d.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:fl(a,ao)})]},`${a.source}:${a.name}`)})})]},a.source)):(0,d.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:ao("chat.noCommands")})})]}),a4&&null!==a2&&(ai=be&&(!bc||bc.cwd!==_),aj=1===cl.length?ao("chat.match"):ao("chat.matches",{count:cl.length}),ak=bc?.truncated&&!ck?a2.query?ao("chat.searchingAll"):ao("chat.indexTruncated"):"",(0,d.jsxs)("div",{style:{position:"absolute",left:0,right:0,...e8(cs.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:cs.maxHeight},children:[(0,d.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)"},children:[(0,d.jsx)("span",{children:ai?ao("chat.loadingFiles"):ao("chat.files",{label:aj,hint:ak})}),(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ao("chat.tabEnter")})]}),(0,d.jsx)("div",{style:{maxHeight:Math.max(0,cs.maxHeight-34),overflowY:"auto",padding:4},children:ai||0!==cl.length?cl.map((a,b)=>{let c=b===a6,e=a.path.split("/").pop()??a.path,f=a.path.slice(0,a.path.length-e.length);return(0,d.jsxs)("button",{ref:a=>{bB.current[b]=a},type:"button",onMouseDown:b=>{b.preventDefault(),ct(a)},onMouseEnter:()=>a7(b),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:"var(--radius-control)",background:c?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,d.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:a.isDir?(0,d.jsx)(b_,{size:14}):b2(e,14)}),(0,d.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[f&&(0,d.jsx)("span",{style:{color:"var(--text-dim)"},children:f}),e,a.isDir&&(0,d.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${a.isDir?"d":"f"}:${a.path}`)}):(0,d.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:cj&&!ck?ao("chat.searching"):ao("chat.noMatchingFiles")})})]})),(0,d.jsxs)("div",{className:`chat-composer-field${aY?" is-bash":""}${i?" is-streaming":""}`,style:{minWidth:0,display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:`1px solid ${aY?"var(--tool-bg)":i&&(c||g)?"var(--warning-line)":"var(--border)"}`,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",boxShadow:"var(--seed-shadow-s1)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,d.jsx)("textarea",{className:"chat-composer-textarea",ref:bl,value:as,onChange:a=>{bG.current=a.target.value,at(a.target.value),a9(!1),cg(a.target.value,a.target.selectionStart)},onSelect:a=>{let b=a.currentTarget;cg(b.value,b.selectionStart)},onKeyDown:cE,onCompositionStart:()=>{bw.current=!0},onCompositionEnd:a=>{bw.current=!1,bx.current=Date.now();let b=a.currentTarget;cg(b.value,b.selectionStart)},onInput:cF,onPaste:cI,placeholder:i&&(c||g)?ao("chat.steerPlaceholder"):i?ao("chat.agentPlaceholder"):ao("chat.messagePlaceholder"),rows:1,style:{flex:1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:14,lineHeight:1.6,fontFamily:"inherit",minHeight:24,maxHeight:200,overflow:"auto"}}),i?(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[c&&(0,d.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>cA("steer"),disabled:!cf,title:aV?ao("chat.attachExtractingWait"):ao("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:cf?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:cf?"var(--warning)":"var(--text-dim)",cursor:cf?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,d.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),ao("chat.steer")]}),g&&(0,d.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>cA("followup"),disabled:!cf,title:aV?ao("chat.attachExtractingWait"):ao("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:cf?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:cf?"var(--accent-hover)":"var(--text-dim)",cursor:cf?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,d.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,d.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),ao("chat.followUp")]})]}):(0,d.jsxs)("button",{className:"chat-composer-send",onClick:b8,disabled:!cf,"aria-busy":aV||void 0,title:aV?ao("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",gap:6,padding:"7px 14px",background:cf?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:cf?"var(--accent-hover)":"var(--text-dim)",cursor:cf?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 0.15s"},children:[(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,d.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),ao("chat.send")]})]})]}),aY&&(0,d.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:aZ?"var(--text-muted)":"var(--accent)",marginTop:4},children:[ao("chat.shell")," \xb7 ",aZ?ao("chat.outputLocal"):ao("chat.outputModel")]}),(0,d.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,d.jsxs)("div",{style:{flex:ar?"1 1 0%":"0 0 auto",minWidth:ar?"min-content":0,display:"flex",alignItems:"center",gap:2},children:[(0,d.jsx)("button",{type:"button",className:`composer-icon-button${aO.length||aQ.length?" is-active":""}`,onClick:()=>bv.current?.click(),title:ao("chat.attachFile"),"aria-label":ao("chat.attachFile"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:"var(--radius-control)",color:aO.length||aQ.length?"var(--accent)":"var(--text-muted)",cursor:"pointer",opacity:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:a=>{a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color=aO.length||aQ.length?"var(--accent)":"var(--text)"},onMouseLeave:a=>{a.currentTarget.style.background="none",a.currentTarget.style.color=aO.length||aQ.length?"var(--accent)":"var(--text-muted)"},children:(0,d.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,d.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,d.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),q&&bJ.bo.length>0&&(0,d.jsxs)("div",{ref:bo,style:{position:"relative",flexShrink:+!!ar,minWidth:0},children:[(0,d.jsxs)("button",{className:`${ar?"composer-icon-button":"composer-chip"}${aC?" is-active":""}`,onClick:a=>{let b=a.currentTarget.getBoundingClientRect();aF({top:b.top,bottom:b.bottom,left:b.left,width:b.width}),av(!1),az(""),aD(a=>!a)},disabled:i||u,"aria-haspopup":"menu","aria-expanded":aC,onKeyDown:a=>{"Escape"===a.key&&aC&&(a.stopPropagation(),aD(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:aC?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:i||u?"not-allowed":"pointer",fontSize:12,opacity:i?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:a=>{i||u||(a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color="var(--text)")},onMouseLeave:a=>{a.currentTarget.style.background=aC?"var(--bg-hover)":"none",a.currentTarget.style.color="var(--text-muted)"},title:ao("chat.mainPreset"),"aria-label":ao("chat.mainPreset"),children:[(0,d.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,d.jsx)("path",{d:"M12 3l2.2 5.1 5.6.5-4.2 3.7 1.2 5.5L12 15l-4.8 2.8 1.2-5.5L4.2 8.6l5.6-.5z"})}),ar?null:(0,d.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:ao("chat.mainPreset")})]}),aC&&aE&&(()=>{let a=window.visualViewport?.height??window.innerHeight,{side:b,maxHeight:c}=e$(aE.top,aE.bottom,a,e_(a,.6,460),{gap:6,prefer:"above"}),e="above"===b?{bottom:a-aE.top+6}:{top:aE.bottom+6},f=ar?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:aE.left,width:"max-content",minWidth:aE.width};return(0,d.jsx)("div",{ref:bp,role:"menu","aria-label":ao("chat.mainPreset"),onKeyDown:a=>{"Escape"===a.key&&(aD(!1),bo.current?.querySelector("button")?.focus())},style:{position:"fixed",...e,...f,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:c,display:"flex",flexDirection:"column"},children:(0,d.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:bJ.bo.map(a=>{let b=a.alias===cK;return(0,d.jsxs)("button",{role:"menuitemradio","aria-checked":b,onClick:()=>{aD(!1),q((0,bJ.zq)(a))},title:`${a.provider}/${a.model}`,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:b?"var(--bg-selected)":"none",border:"none",color:b?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:b?600:400,whiteSpace:"nowrap"},onMouseEnter:a=>{b||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{b||(a.currentTarget.style.background="none")},children:[b?(0,d.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,d.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,d.jsx)("span",{style:{width:10,flexShrink:0}}),(0,d.jsx)("img",{className:"account-avatar",src:(0,bJ.uk)(a.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,d.jsx)("span",{children:a.alias}),(0,d.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[a.provider,"/",a.model,void 0!==a.oauthPosition?` \xb7 OAuth ${a.oauthPosition}`:""]})]},a.alias)})})})})()]}),(cJ.length>0||cU||n)&&p&&(0,d.jsxs)("div",{ref:bm,style:{position:"relative",flex:ar?"1 1 0%":void 0,width:ar?0:void 0,minWidth:44*!!ar},children:[(0,d.jsxs)("button",{className:`composer-chip${au?" is-active":""}`,onClick:a=>{let b=a.currentTarget.getBoundingClientRect();ax({top:b.top,bottom:b.bottom,left:b.left,width:b.width}),av(a=>(a&&az(""),!a))},disabled:i||u,"aria-busy":u||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:ar?"flex-start":void 0,padding:ar?"8px 10px":"8px 12px",height:32,width:ar?"100%":void 0,maxWidth:ar?"100%":220,overflow:"hidden",background:au?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:i||u?"not-allowed":"pointer",fontSize:12,opacity:i?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:a=>{i||u||(a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color="var(--text)")},onMouseLeave:a=>{a.currentTarget.style.background=au?"var(--bg-hover)":"none",a.currentTarget.style.color="var(--text-muted)"},title:u?"Switching model":cJ.length>0?"Change model":"No available models",children:[u?(0,d.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,d.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,d.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,d.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,d.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,d.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,d.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,d.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,d.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,d.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,d.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,d.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,d.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:cU??(cJ.length>0?"Select model":"No models")})]}),au&&aw&&(()=>{let a=window.visualViewport?.height??window.innerHeight,{side:b,maxHeight:c}=e$(aw.top,aw.bottom,a,e_(a,.6,460),{gap:6,prefer:"above"}),e="above"===b?{bottom:a-aw.top+6}:{top:aw.bottom+6},f=ar?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:aw.left,width:"max-content",minWidth:aw.width};return(0,d.jsxs)("div",{ref:bn,style:{position:"fixed",...e,...f,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:c,display:"flex",flexDirection:"column"},children:[cO&&(0,d.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,d.jsx)("input",{value:ay,onChange:a=>az(a.target.value),onKeyDown:a=>{"Escape"===a.key&&(az(""),av(!1))},placeholder:ao("chat.filterModels"),"aria-label":ao("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!ar,fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,d.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[cS.length>0&&(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:ao("chat.frequentModels")}),cS.map(({option:a,count:b})=>cT(a,"frequent",b))]}),cQ.length>0&&!ay.trim()&&t&&(0,d.jsxs)("div",{style:{borderTop:cS.length>0?"1px solid var(--border)":"none"},children:[(0,d.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:ao("chat.modelRoles")}),cQ.map(a=>{let b=cR?.role===a.role,c=a.resolved?.name??a.resolved?.modelId??"";return(0,d.jsxs)("button",{onClick:()=>{av(!1),az(""),t(a.role)},title:a.selector??c,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:b?"var(--bg-selected)":"none",border:"none",color:b?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:a=>{b||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{b||(a.currentTarget.style.background="none")},children:[b?(0,d.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,d.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,d.jsx)("span",{style:{width:10,flexShrink:0}}),(0,d.jsx)("span",{style:{flexShrink:0,minWidth:58,padding:"1px 6px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-subtle)",color:b?"var(--accent)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:a.tag??a.role.toUpperCase()}),(0,d.jsx)("span",{style:{fontWeight:b?600:500},children:a.name}),(0,d.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[c,a.resolved?.thinkingLevel?` \xb7 ${a.resolved.thinkingLevel}`:""]})]},a.role)}),(0,d.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:"1px solid var(--border)"},children:ao("chat.allModels")})]}),0===cP.length?(0,d.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:ay.trim()?ao("chat.noMatchingModels"):"No available models"}):cP.map((a,b)=>(0,d.jsxs)("div",{children:[cP.length>1&&(0,d.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:b>0?"1px solid var(--border)":"none"},children:a.provider}),a.options.map(a=>cT(a,"all"))]},a.provider))]})]})})()]}),H&&(0,d.jsxs)("div",{ref:br,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,d.jsxs)("button",{type:"button",className:`${ar?"composer-icon-button":"composer-chip"}${aI?" is-active":""}`,onClick:a=>{let b=a.currentTarget.getBoundingClientRect();aL({top:b.top,bottom:b.bottom,left:b.left,width:b.width}),av(!1),az(""),aD(!1),aJ(a=>!a)},disabled:i||u,"aria-haspopup":"menu","aria-expanded":aI,onKeyDown:a=>{"Escape"===a.key&&aI&&(a.stopPropagation(),aJ(!1))},title:ao("chat.changeReasoning",{level:cY}),"aria-label":ao("chat.changeReasoning",{level:cY}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ar?0:"8px 12px",height:32,background:aI?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:i||u?"not-allowed":"pointer",fontSize:12,opacity:i?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:a=>{i||u||(a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color="var(--text)")},onMouseLeave:a=>{a.currentTarget.style.background=aI?"var(--bg-hover)":"none",a.currentTarget.style.color="var(--text-muted)"},children:[(0,d.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,d.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,d.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,d.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),ar?null:(0,d.jsx)("span",{style:{whiteSpace:"nowrap"},children:cY})]}),aI&&aK&&(()=>{let a=window.visualViewport?.height??window.innerHeight,{side:b,maxHeight:c}=e$(aK.top,aK.bottom,a,e_(a,.6,460),{gap:6,prefer:"above"}),e="above"===b?{bottom:a-aK.top+6}:{top:aK.bottom+6},f=ar?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:aK.left,width:"max-content",minWidth:Math.max(180,aK.width)};return(0,d.jsx)("div",{role:"menu","aria-label":ao("chat.changeReasoningLabel"),onKeyDown:a=>{"Escape"===a.key&&(aJ(!1),br.current?.querySelector("button")?.focus())},style:{position:"fixed",...e,...f,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:c},children:c0.map(({level:a,ceiling:b})=>{let c=(E??"auto")===a&&("auto"!==a||(G??null)===b),e=b??a,f="auto"===a&&null===b?null:cX(e),g=b?`auto ≤ ${f??b}`:f??a,h=b?ao("chat.thinkingAutoCapped",{level:f??b}):ao(ff[a]);return(0,d.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":c,onClick:()=>{aJ(!1),H(a,b)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:c?"var(--bg-selected)":"none",border:"none",color:c?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:c?600:400,whiteSpace:"nowrap"},onMouseEnter:a=>{c||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{c||(a.currentTarget.style.background="none")},children:[c?(0,d.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,d.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,d.jsx)("span",{style:{width:10,flexShrink:0}}),(0,d.jsxs)("span",{style:{flex:1},children:[g,null!==f&&(0,d.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",e,")"]})]}),(0,d.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:h})]},b?`auto-${b}`:a)})})})()]}),M&&(al=L?ao("chat.fastModeBusy"):null===K?ao("chat.fastModeUnknown"):K.active?ao("chat.fastModeActive"):K.enabled?ao("chat.fastModeInactive"):ao("chat.fastModeOff"),am=L||i||u,an=K?.enabled===!0,(0,d.jsx)("button",{type:"button",className:`composer-icon-button${K?.active?" is-active":""}`,onClick:M,disabled:am,"aria-pressed":null===K?void 0:K.enabled,"aria-busy":L||void 0,title:al,"aria-label":al,style:{flexShrink:0,opacity:i?.5:1},children:(0,d.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:K?.active?"var(--accent)":"none",stroke:an?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===K?"3 2":void 0,style:{opacity:an&&!K?.active?.6:1},"aria-hidden":"true",children:(0,d.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})),!ar&&c$&&(0,d.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:c$}),(0,d.jsx)(en,{sessionId:aa})]}),(0,d.jsxs)("div",{ref:bs,style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:ar?4:2},children:[ar?(0,d.jsx)("button",{type:"button",className:`composer-icon-button${aM?" is-active":""}`,title:ao("chat.moreControls"),"aria-label":ao("chat.moreControls"),"aria-expanded":aM,onClick:()=>{av(!1),az(""),aN(a=>!a)},children:(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,d.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,d.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,d.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,d.jsx)(h.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:aM?void 0:ao("chat.moreControls"),"aria-label":ao("chat.moreControls"),"aria-expanded":aM,onClick:()=>{av(!1),az(""),aN(a=>!a)},children:ao("chat.moreControls")}),(0,d.jsxs)("div",{role:"group","aria-label":ao("chat.moreControls"),style:{display:aM?"flex":"none",alignItems:"center",gap:1,position:"absolute",right:0,bottom:"100%",marginBottom:"var(--seed-dimension-x1)",zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"wrap",justifyContent:"flex-end",border:"1px solid var(--seed-color-stroke-neutral-muted)",borderRadius:"var(--seed-radius-r2)",background:"var(--seed-color-bg-layer-floating)",boxShadow:"var(--seed-shadow-s2)"},children:[!i&&C&&(0,d.jsxs)("div",{ref:bq,style:{position:"relative"},children:[(0,d.jsxs)("button",{className:`composer-chip${aG?" is-active":""}`,onClick:()=>!i&&aH(a=>!a),disabled:i,title:ao("chat.changeToolPreset")+`: ${c1}`,"aria-label":ao("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:aG?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:i?"not-allowed":"pointer",fontSize:12,opacity:i?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:a=>{i||(a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color="var(--text)")},onMouseLeave:a=>{a.currentTarget.style.background=aG?"var(--bg-hover)":"none",a.currentTarget.style.color="var(--text-muted)"},children:[(0,d.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.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"})}),(0,d.jsx)("span",{style:{whiteSpace:"nowrap"},children:c1})]}),aG&&(0,d.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",minWidth:120},children:e4.map(a=>{let b=e5[a],c=(B??"default")===b,e="off"===a?ao("chat.noTools"):"default"===a?ao("chat.builtInTools",{tools:e6}):ao("chat.allBuiltInTools",{tools:`${e6} + ${e7}`});return(0,d.jsxs)("button",{onClick:()=>{aH(!1),c||C(b)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:c?"var(--bg-selected)":"none",border:"none",color:c?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:c?600:400,whiteSpace:"nowrap"},onMouseEnter:a=>{c||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{c||(a.currentTarget.style.background="none")},children:[c?(0,d.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,d.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,d.jsx)("span",{style:{width:10,flexShrink:0}}),(0,d.jsx)("span",{style:{flex:1},children:a}),(0,d.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:e})]},a)})})]}),!i&&v&&(0,d.jsx)("div",{children:(0,d.jsx)("button",{className:`composer-chip${y?" is-active is-danger":""}`,onClick:y?w:v,disabled:i&&!y,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:y?"var(--danger-soft)":"none",border:"none",borderRadius:"var(--radius-control)",color:y?"var(--danger)":"var(--text-muted)",cursor:i&&!y?"not-allowed":"pointer",fontSize:12,opacity:i&&!y?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:a=>{(!i||y)&&(a.currentTarget.style.background=y?"var(--danger-soft)":"var(--bg-hover)",a.currentTarget.style.color=y?"var(--danger)":"var(--text)")},onMouseLeave:a=>{a.currentTarget.style.background=y?"var(--danger-soft)":"none",a.currentTarget.style.color=y?"var(--danger)":"var(--text-muted)"},title:y?ao("chat.stopCompaction"):ao("chat.compactContext"),"aria-label":y?ao("chat.stopCompaction"):ao("chat.compactContext"),children:y?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,d.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(0,d.jsx)("span",{style:{whiteSpace:"nowrap"},children:ao("chat.compacting")})]}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,d.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,d.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,d.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(0,d.jsx)("span",{style:{whiteSpace:"nowrap"},children:ao("chat.compact")})]})})}),aM&&(0,d.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:ao("chat.collapseControls"),"aria-label":ao("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{aH(!1),aJ(!1),aN(!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:a=>{a.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:a=>{a.currentTarget.style.background="var(--bg-hover)"},children:(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,d.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,d.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),i&&(0,d.jsxs)("button",{className:"composer-chip is-danger is-active",onClick:b,title:ao("chat.stopAgent"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:32,background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:a=>{a.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:a=>{a.currentTarget.style.background="var(--danger-soft)"},children:[(0,d.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,d.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),ao("chat.stop")]}),(0,d.jsx)(el,{sessionId:aa,onEnsureSession:ab,onTranscriptPersisted:ac}),void 0!==X&&(0,d.jsx)(ed,{soundEnabled:W??!0,onToggle:X})]})]}),ar&&c$&&(0,d.jsx)("div",{style:{marginTop:4,padding:"0 4px",fontSize:12,color:"var(--text-muted)",overflowWrap:"anywhere"},children:c$})]})]})});function fD({statuses:a}){if(0===a.length)return null;let b=[...a].sort((a,b)=>a.key.localeCompare(b.key)).map(({text:a})=>a.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()).join(" "),c=aj(b);return(0,d.jsx)("div",{role:"status","aria-label":c,title:c,style:{display:"flex",alignItems:"center",flexShrink:0,minWidth:0,height:36,padding:"0 12px",borderTop:"1px solid var(--border)",background:"transparent"},children:(0,d.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ao(b).map((a,b)=>(0,d.jsx)("span",{style:a.style,children:a.text},b))})})}function fE({phases:a}){let{t:b}=(0,x.s)(),[c,f]=(0,e.useState)(!1),[g,h]=(0,e.useState)(!1),{currentPhase:i,activeTask:j,remaining:k,completed:l,total:m,percent:n}=function(a){let b=0,c=0,d=null,e=null,f=null;for(let g of a)for(let a of g.tasks){if("completed"===a.status){b+=1;continue}"abandoned"!==a.status&&(c+=1,"in_progress"===a.status?d||(d={phase:g,task:a}):"blocked"===a.status?f||(f={phase:g,task:a}):e||(e={phase:g,task:a}))}let g=d??e??f,h=b+c;return{currentPhase:g?.phase??null,activeTask:g?.task??null,remaining:c,completed:b,total:h,percent:h>0?Math.round(b/h*100):null}}(a);if(0===m)return null;let o=0===k;return(0,d.jsxs)("div",{className:`todo-strip${o?" is-done":""}`,children:[(0,d.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":c,onClick:()=>f(a=>!a),children:[(0,d.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:o?"✓":"›"}),i&&(0,d.jsx)("span",{className:"todo-strip-phase",children:i.name}),(0,d.jsx)("span",{className:"todo-strip-task",children:o?b("todo.allDone",{count:l}):j?.content??""}),(0,d.jsx)("span",{className:"todo-strip-count",children:o?b("todo.progressDone",{percent:n??0,completed:l,total:m}):b("todo.progress",{percent:n??0,completed:l,total:m,remaining:k})})]}),c&&(0,d.jsxs)("div",{className:"todo-strip-body",children:[a.map((b,c)=>{let e=b.tasks.filter(a=>g||"completed"!==a.status);return 0===e.length?null:(0,d.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[a.length>1&&(0,d.jsx)("div",{className:"todo-checklist-phase-name",children:b.name}),e.map((a,b)=>(0,d.jsx)(bY,{task:a},`${a.content}-${b}`))]},`${b.name}-${c}`)}),l>0&&(0,d.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":g,onClick:()=>h(a=>!a),children:b(g?"todo.hideCompleted":"todo.showCompleted",{count:l})})]})]})}function fF(a=document){return"visible"!==a.visibilityState||!a.hasFocus()}function fG(a){switch(a.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==a.closed;default:return!1}}async function fH(a,b={createWindowNotification:(a,b)=>new Notification(a,b),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let c={body:a.body,...a.tag?{tag:a.tag}:{}};if(b.getServiceWorkerRegistration)try{let d=await b.getServiceWorkerRegistration();if(d)return await d.showNotification(a.title,{...c,data:{url:a.sessionUrl}}),"service-worker"}catch{}try{let d=b.createWindowNotification(a.title,c);return d.onclick=()=>{d.close(),a.onClick()},"window"}catch{return null}}var fI=c(95361);class fJ extends Error{constructor(a,b,c,d){super(a),this.status=b,this.code=c,this.accepted=d,this.name="AgentCommandError"}}async function fK(a,b){let c=await fetch(`/api/agent/${encodeURIComponent(a)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)}),d=await c.json().catch(()=>({}));if(!c.ok||d.error)throw new fJ(d.error??`HTTP ${c.status}`,c.status,d.code,d.accepted);return d.data}let fL="ompweb-update-return-v1";function fM(a){return null===a||"running"===a?null:"failed"===a?3e4:8e3}function fN(a,b){let c=new Map(a.map(a=>[a.id,a]));for(let a of b)c.set(a.id,function(a,b){return a&&(void 0!==a.parentToolCallId&&void 0!==b.parentToolCallId?a.parentToolCallId===b.parentToolCallId:void 0===a.sessionFile||void 0===b.sessionFile||a.sessionFile===b.sessionFile)?{...b,index:a.index,agent:a.agent,agentSource:a.agentSource,description:a.description??b.description,task:a.task??b.task,assignment:a.assignment??b.assignment,sessionFile:b.sessionFile??a.sessionFile,parentToolCallId:b.parentToolCallId??a.parentToolCallId}:b}(c.get(a.id),a));let d=[...c.values()];return[...d.filter(a=>"pending"===a.status||"running"===a.status).sort((a,b)=>a.index-b.index||a.id.localeCompare(b.id)),...d.filter(a=>"pending"!==a.status&&"running"!==a.status).sort((a,b)=>b.lastUpdate-a.lastUpdate||a.id.localeCompare(b.id))].slice(0,128)}function fO(a,b){switch(b.type){case"start":return{isStreaming:!0,streamingMessage:null};case"update":return{isStreaming:!0,streamingMessage:b.message};case"end":case"reset":return{isStreaming:!1,streamingMessage:null};default:return a}}function fP(a){return{steering:a?.steering??[],followUp:a?.followUp??[]}}function fQ(a){if(a&&"boolean"==typeof a.fastModeEnabled)return{enabled:a.fastModeEnabled,active:!0===a.fastModeActive}}function fR(a){return b=>{let c=a?.isCompacting?a.compaction:null;if(!c)return b;let d=Date.now()-c.elapsedMs;return{startedAt:b?Math.min(b.startedAt,d):d,reason:b?.reason??c.reason}}}function fS(a,b){if(a===b)return!0;if(a.length!==b.length)return!1;for(let c=0;c<a.length;c+=1){let d=a[c],e=b[c];if(!d||!e||d.name!==e.name||d.tasks.length!==e.tasks.length)return!1;for(let a=0;a<d.tasks.length;a+=1){let b=d.tasks[a],c=e.tasks[a];if(!b||!c||b.content!==c.content||b.status!==c.status||b.blocker!==c.blocker)return!1}}return!0}function fT(a){return"aborted"===a.stopReason?"aborted":"error"===a.stopReason||a.errorMessage?"failed":a.stopReason?"completed":"unknown"}function fU(a,b){for(let c=a.length-1;c>=0;c--){let d=b[c]??null;if(!aH(d??void 0))return{message:a[c],entryId:d}}return null}let fV=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class fW extends Error{constructor(a){super("timeout"===a?"Timed out connecting to the agent event stream. Please try again.":"Failed to connect to the agent event stream. Please try again."),this.status=a,this.name="EventStreamConnectionError"}}function fX(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function fY(a){return new Promise(b=>setTimeout(b,a))}function fZ(a){let b=a.findIndex(a=>!a.exiting);return -1===b?a:a.map((a,c)=>c===b?{...a,exiting:!0}:a)}function f$(a,b){switch(b.type){case"add":if(a.visible.some(a=>a.exiting)||a.visible.length>=5)return{visible:a.visible.some(a=>a.exiting)?a.visible:fZ(a.visible),pending:[...a.pending,b.notice]};return{...a,visible:[...a.visible,b.notice]};case"mark_oldest_exiting":return{...a,visible:fZ(a.visible)};case"remove":return function(a,b){let c=a,d=b;for(;d.length>0&&c.length<5;){let[a,...b]=d;c=[...c,a],d=b}return d.length>0&&!c.some(a=>a.exiting)&&(c=fZ(c)),{visible:c,pending:d}}(a.visible.filter(a=>a.id!==b.id),a.pending);default:return a}}function f_(a){if(!a||"object"!=typeof a||"image"!==a.type)return"";let b=a.source;return b&&"object"==typeof b?["url"===b.type?"url":"base64","string"==typeof b.media_type?b.media_type:"","string"==typeof b.data?b.data:"","string"==typeof b.url?b.url:""].join(":"):["base64","string"==typeof a.mimeType?a.mimeType:"","string"==typeof a.data?a.data:"",""].join(":")}function f0(a){let b,c=a.content;return"string"==typeof c?JSON.stringify({text:c,images:[]}):Array.isArray(c)?JSON.stringify({text:"string"==typeof(b=a.content)?b:Array.isArray(b)?b.map(a=>a&&"object"==typeof a&&"text"===a.type&&"string"==typeof a.text?a.text:"").filter(Boolean).join("\n"):"",images:c.map(f_).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function f1(a){return"user"===a.role?`user:${f0(a)}`:"bashExecution"===a.role?JSON.stringify({role:a.role,command:a.command,output:a.output,exitCode:a.exitCode,cancelled:a.cancelled,truncated:a.truncated,fullOutputPath:a.fullOutputPath,excludeFromContext:a.excludeFromContext}):JSON.stringify({role:a.role,content:a.content,model:a.model,provider:a.provider,customType:a.customType})}function f2(a,b){return a&&"object"==typeof a?"number"!=typeof a.tokensBefore||"number"!=typeof a.estimatedTokensAfter?null:{reason:b,tokensBefore:a.tokensBefore,estimatedTokensAfter:a.estimatedTokensAfter}:null}function f3(a){return a?.map(({data:a,mimeType:b})=>({data:a,mimeType:b}))}let f4={count:50,end:null};function f5(a,b){let c=Math.max(a,0),d=null===b.end?c:Math.min(Math.max(b.end,0),c),e=Math.min(Math.max(b.count,0),d),f=d-e;return{startIndex:f,endIndex:d,hasMore:f>0,hasLater:d<c}}function f6(a,b,c){let{startIndex:d,endIndex:e}=f5(a,c);if(b>=d&&b<e)return c;let f=Math.max(0,b-10),g=Math.max(b+1,f+50);return g>=a?{count:a-f,end:null}:{count:g-f,end:g}}function f7({sticker:a,text:b,tag:c,followRef:f}){let g=(0,e.useRef)(null);return a||b?(0,d.jsxs)("div",{ref:g,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[a&&(0,d.jsx)("img",{className:"cue-bubble-sticker",src:a,alt:dE[c]}),b&&(0,d.jsx)("p",{className:a?"cue-bubble":"cue-bubble cue-bubble--solo",children:b}),a&&(0,d.jsx)(dA(),{id:"ad10be785ccf4f7",children:".cue-bubble-sticker{transform-origin:center 75%;animation:cue-sticker-pop 200ms cubic-bezier(0,0,.15,1)both}@keyframes cue-sticker-pop{from{opacity:0;transform:scale(.88)}to{opacity:1;transform:scale(1)}}@media(prefers-reduced-motion:reduce){.cue-bubble-sticker{animation:none}}"})]}):null}function f8(a){if("user"!==a.role)return null;let b="string"==typeof a.content?a.content:a.content.filter(a=>"text"===a.type).map(a=>a.text).join("\n"),c=(cB(b)?.message??b).trim();return c.length>0?c:null}let f9=[],ga=(0,e.memo)(function({messages:a,entryIds:b,toolResultsMap:c,modelNames:f,messageCwd:g,onOpenFile:h,sessionBusy:i,isNew:j,isStreaming:k,handleFork:l,forkingEntryId:m,handleNavigate:n,handleEditContent:o,sessionId:p,main:q,process:r,dispatchSlots:s,compactedDispatch:t,startIndex:u,endIndex:v,sentinelRef:w,laterSentinelRef:x,flashItem:y,t:z,onProcessLogChange:A,cues:B,cueFollowRef:C}){(0,e.useEffect)(()=>{A({groups:r,messages:a,entryIds:b,toolResults:c,modelNames:f,cwd:g,sessionId:p})},[A,r,a,b,c,f,g,p]);let D=(0,e.useMemo)(()=>{let b=new Map;for(let[d,e]of function(a,b,c,d){let e=new Map;a.forEach((a,b)=>{"answer"===a.kind&&e.set(a.idx,b)});let f=new Map,g=new Map;for(let a of b){let b=g.get(a.anchorIdx);for(let h of(b||(b=new Set,g.set(a.anchorIdx,b)),a.entries)){let a=c[h.idx];if(a?.role!=="assistant")continue;let g=Math.max(0,(h.blocks?e.get(h.idx):void 0)??h.afterMainIndex??-1),i=b;!function(a,b,c){for(let d of a){if("toolCall"!==d.type||"learn"!==d.toolName&&"manage_skill"!==d.toolName)continue;let a=b?.get(d.toolCallId);if(!a||a.isError)continue;let e=d.input??{};if("manage_skill"===d.toolName){let a=aL(e.action);if(!0===aK[a]){let b={kind:"skill",action:a,name:aL(e.name)};c(JSON.stringify(b),b)}continue}let f=aL(e.memory),g=e.skill,h=g?{action:aL(g.action),name:aL(g.name)}:void 0;c(JSON.stringify({kind:"lesson",memory:f,skill:h}),{kind:"lesson",memory:f.length>160?`${f.slice(0,160)}…`:f,...h?{skill:h}:{}})}}(h.blocks??a.content??[],d,(a,b)=>{if(i.has(a))return;i.add(a);let c=f.get(g);c?c.push(b):f.set(g,[b])})}}return f}(q,r,a,c)){let a=e.map(a=>{if("skill"===a.kind)return z("chat.savedSkill",{action:a.action,name:a.name});let b=z("chat.savedLesson",{memory:a.memory});return a.skill?`${b} (${z("chat.savedSkill",a.skill)})`:b});b.set(d,{role:"custom",customType:aE,content:[z("chat.lessonsSaved"),...a.map(a=>`- ${a}`)].join("\n"),display:!0})}return b},[q,r,a,c,z]),E=(0,e.useMemo)(()=>{let b=null;if(i)for(let c of q)"message"===c.kind&&a[c.idx]?.role==="user"&&(b=c.idx);let d=new Map;for(let[e,f]of function(a,b,c){let d=new Map,e=a.filter(a=>"message"===a.kind&&b[a.idx]?.role==="user").map(a=>a.idx),f=new Map;for(let[g,h]of(a.forEach((a,b)=>{"answer"===a.kind&&f.set(a.anchorIdx,b)}),f)){if(g===c)continue;let a=e.find(a=>a>g);d.set(h,{from:g+1,to:a??b.length})}return d}(q,a,b))d.set(e,function(a,b,c){let d=[],e=[];for(let c of a){if("toolCall"!==c.type)continue;if("task"===c.toolName){e.push(c);continue}if("bash"!==c.toolName)continue;let a="string"==typeof c.input.command?c.input.command.trim():"";if(!a||!dr.test(a))continue;let f=b.get(c.toolCallId),g=f?function(a){let b=a.details;if("number"==typeof b?.exitCode)return b.exitCode;let c=a.content.map(a=>"text"===a.type?a.text:"").join("\n"),d=/Command exited with code (-?\d+)\s*$/.exec(c.trimEnd());return d?Number(d[1]):null}(f):null,h=null===g?f?.isError?"failed":"unobserved":0===g?"passed":"failed";d.push({toolCallId:c.toolCallId,command:a,state:h,exitCode:g})}return{checks:d,dispatchCalls:e,files:aR(a,b,c)}}(function(a,b,c){let d=[];for(let e=Math.max(0,b);e<Math.min(a.length,c);e++){let b=a[e];"assistant"===b.role&&d.push(...b.content??[])}return d}(a,f.from,f.to),c,g));return d},[q,a,c,g,i]),F=u>0,G=v<q.length,H=(e,q={})=>{let r=q.messageOverride??a[e],s=e-1;for(;s>=0&&aH(b[s]);)s-=1;let t="user"===r.role&&s>=0&&"assistant"===a[s].role?b[s]:void 0,u=q.keyPrefix??"message",v=!1;if("assistant"===r.role){v=!0;for(let b=e+1;b<a.length;b++){let c=a[b].role;if("user"===c)break;if("assistant"===c){v=!1;break}}v&&k&&e===a.length-1&&(v=!1)}return void 0!==q.showTimestamp&&(v=q.showTimestamp),(0,d.jsx)(cX,{message:r,toolResults:c,modelNames:f,cwd:g,onOpenFile:h,entryId:b[e],onFork:i||j||0===e&&"user"===r.role?void 0:l,forking:m===b[e],onNavigate:i?void 0:n,prevAssistantEntryId:i?void 0:t,onEditContent:o,showTimestamp:v,prevTimestamp:e>0?a[e-1].timestamp:void 0,sessionId:p,writtenFiles:q.writtenFiles,dispatchSlot:q.dispatchSlot,turnSummary:q.turnSummary},`${u}-view-${e}`)},I=(b,c)=>{let e=q[b],f="message"===e.kind&&a[e.idx]?.role==="user";return(0,d.jsx)("div",{"data-chat-item":b,"data-chat-question":f?"":void 0,className:y===b?"chat-item chat-jump-flash":"chat-item",children:c})};return(0,d.jsxs)(d.Fragment,{children:[F&&(0,d.jsx)("div",{ref:w,className:"py-3 text-center text-xs text-text-muted",children:z("chat.loadEarlier",{count:u})}),q.slice(u,v).map((f,i)=>{let j=u+i,k=t?.position===j?(0,d.jsx)(cl,{calls:t.calls}):null,l="message"===f.kind?f.anchorIdx??f.idx:f.anchorIdx,m=q[j+1],n=m?"message"===m.kind?m.anchorIdx??m.idx:m.anchorIdx:null,o=m?m.idx:1/0,r=B.filter(c=>{let d=null!==c.anchorEntryId?b.indexOf(c.anchorEntryId):Math.min(c.liveIndex??-1,a.length-1);return d>=f.idx&&d<o}).map(a=>(0,d.jsx)(f7,{sticker:a.sticker,text:a.text,tag:a.tag,followRef:C},`cue-${a.id}`)),v=n!==l,w=D.get(j),x=w?(0,d.jsx)(cX,{message:w,cwd:g,onOpenFile:h},`saved-lessons-${j}`):null,y=v?(0,d.jsx)(dQ,{turnIndex:l,turnEntryId:b[l],sessionId:p,cwd:g,onOpenFile:h}):null;if("message"===f.kind)return(0,d.jsxs)(e.Fragment,{children:[k,I(j,H(f.idx)),x,y,r]},`message-${f.idx}`);let z=aR(f.precedingBlocks,c,g);return(0,d.jsxs)(e.Fragment,{children:[k,I(j,H(f.idx,{keyPrefix:`answer-${f.runIndex}`,messageOverride:av(a[f.idx],f.blocks),writtenFiles:z,dispatchSlot:s.get(j),turnSummary:E.get(j)})),x,y,r]},`answer-${f.idx}-${f.runIndex}`)}),t?.position===q.length&&v===q.length&&(0,d.jsx)(cl,{calls:t.calls}),G&&(0,d.jsx)("div",{ref:x,className:"py-3 text-center text-xs text-text-muted",children:z("chat.loadLater",{count:q.length-v})})]})});function gb({session:a,newSessionCwd:b,initialSessionData:f,transitioning:g=!1,onAgentEnd:h,onAttentionNeeded:i,onSessionCreated:j,onSessionForked:k,modelsRefreshKey:l,chatInputRef:m,onBranchDataChange:n,onSystemPromptChange:o,onSessionStatsChange:p,onSessionStatsPanelOpen:q,onContextUsageChange:r,onSubagentsChange:s,onMainIdentityChange:t,onOpenWorkspaceView:u,onProcessLogChange:v,onOpenFile:w,transcriptReplacement:y,onComposerFocusChange:z,onSessionBusyChange:A,onWaitingChange:B,onAttentionChange:C,soundEnabled:D=!0,onSoundToggle:F,playCueSound:G=async()=>({sticker:null,text:null}),preloadCueSound:H,unlockAudio:I,jumpRequest:J=null,onJumpHandled:K}){var L;let M,O,{t:P}=(0,x.s)(),Q=(0,e.useRef)(G);Q.current=G,(0,e.useRef)(null);let R=(0,e.useRef)(H);R.current=H;let[S,T]=(0,e.useState)([]);(0,e.useRef)(S).current=S;let U=(0,e.useRef)(0),V=(0,e.useRef)([]),W=(0,e.useRef)([]),X=(0,e.useRef)(null),Y=(0,e.useRef)(0);(0,e.useRef)(-1);let Z=(0,e.useRef)(-1);(0,e.useCallback)(()=>{let a=X.current?.current;return a?{sessionId:a,turn:Y.current}:null},[]);let $=(0,e.useCallback)(a=>X.current?.current===a.sessionId&&Y.current===a.turn,[]),_=(0,e.useCallback)((a,b,c,d)=>{if(!a.sticker&&!a.text)return;U.current=Math.max(U.current+1,Date.now());let e={id:U.current,sticker:a.sticker,text:a.text,tag:b,sessionId:c.sessionId},f="entry"===d.kind?{...e,anchorEntryId:d.entryId}:{...e,anchorEntryId:null,liveIndex:d.liveIndex,intent:d.intent};T(a=>{let b=[...a,f];return null!==f.anchorEntryId&&function(a,b){let c=[];for(let d of b)d.sessionId===a&&null!==d.anchorEntryId&&c.push({id:d.id,anchorEntryId:d.anchorEntryId,sticker:d.sticker,text:d.text,tag:d.tag});try{window.localStorage.setItem(`omp-cues:${a}`,JSON.stringify(c.slice(-200)))}catch{}}(c.sessionId,b),b})},[]),aa=(0,e.useCallback)((a,b,c,d)=>{let e=()=>$(c)&&("working"!==b||Z.current!==c.turn);e()&&Q.current(a,b,e).then(a=>{null!==b&&null!==d&&e()&&_(a,b,c,d)}).catch(()=>{})},[$,_]),ab=(0,e.useCallback)(async(a,b,c)=>{let d=(await bP(a,b,c))?.alias??null;return d&&R.current?.(d),d},[]);(0,e.useCallback)((a,b,c,d)=>{let e=function(a,b){let c=a.length-1;if(c<0)return null;let d=Math.min(a.length,b.length);if(c<d)return{kind:"entry",entryId:b[c]};let e=dK(a[c]),f=0;for(let b=d;b<=c;b++)dK(a[b])===e&&(f+=1);return{kind:"pending",liveIndex:c,intent:{baseEntryId:d>0?b[d-1]:null,identity:e,occurrence:f}}}(V.current,W.current);ab(b.sessionId,c,d).then(c=>{aa(c,a,b,e)})},[aa,ab]);let[ac,ad]=(0,e.useState)(0),ae=(0,e.useRef)([]),af=(0,e.useCallback)(a=>{if(Y.current+=1,null!==function(a){switch(a){case"completed":return"done";case"failed":return"failed";case"aborted":return null;default:return"neutral"}}(a.outcome)){let b=a.sessionId;ae.current.push({completion:a,trigger:b?{sessionId:b,turn:Y.current}:null}),ad(a=>a+1)}h?.(a)},[h]),ag=(0,e.useCallback)(a=>{m?.current?.replaceMessage(a)},[m]),{loading:ah,error:ai,messages:ak,entryIds:al,streamState:am,agentRunning:an,bashRunning:ao,pendingBash:ap,modelNames:aq,modelList:ar,modelError:as,modelScopeWarnings:at,modelThinkingLevels:au,modelThinkingLevelMaps:aw,modelRoles:aA,toolPreset:aC,thinkingLevel:aE,effectiveThinkingLevel:aK,thinkingCeiling:aL,fastMode:aN,fastModeBusy:aO,handleFastModeToggle:aP,retryInfo:aQ,contextUsage:aR,forkingEntryId:aT,isCompacting:aU,compaction:aV,compactError:aW,compactResult:aX,displayModel:aY,modelSwitching:aZ,sessionStats:a$,runStateKnown:a_,compactedWork:a0,slashCommands:a1,slashCommandsLoading:a2,deliveryRows:a3,subagents:a4,todoPhases:a5,notices:a6,extensionDialog:a7,extensionResponse:a8,extensionCustomUi:a9,extensionStatuses:ba,extensionWidgets:bb,respondToExtensionUi:bc,sendExtensionCustomInput:bd,isAutoModelSelection:be,agentPhase:bf,isNew:bg,autoFollowPaused:bh,resumeAutoFollow:bi,pauseAutoFollow:bj,goalStatus:bk,sessionIdRef:bl,messagesEndRef:bm,scrollContainerRef:bn,handleSend:bo,handleAbort:bp,handleFork:bq,handleNavigate:br,handleModelChange:bs,handleRoleModelChange:bt,handleMainPresetChange:bu,newSessionAccount:bv,handleCompact:bw,handleSteer:bx,handleFollowUp:by,handlePromptWithStreamingBehavior:bz,handleAbortCompaction:bA,handleRecallQueue:bB,handleRemoveQueuedMessage:bC,handleBuiltinSlashCommand:bD,handleToolPresetChange:bE,handleThinkingLevelChange:bF,loadSlashCommands:bG,ensureNewSession:bH,refreshLiveTranscript:bK}=function(a){let{session:b,newSessionCwd:d,initialData:f,onAgentEnd:g,onAttentionNeeded:h,onSessionCreated:i,onSessionForked:j,modelsRefreshKey:k,onBranchDataChange:l,onSystemPromptChange:m,onSessionStatsPanelOpen:n}=a,o=null===b&&null!==d,p=f&&f.sessionId===b?.id?f:null,[q,r]=(0,e.useState)(p),[s,t]=(0,e.useState)(!o&&!p),[u,v]=(0,e.useState)(null),[w,x]=(0,e.useState)(p?.leafId??null),[y,z]=(0,e.useState)(p?.context.messages??[]),[A,B]=(0,e.useState)(p?.context.entryIds??[]),[C,D]=(0,e.useState)(p?.context.compactedWork??null),[E,F]=(0,e.useReducer)(fO,{isStreaming:!1,streamingMessage:null}),[G,H]=(0,e.useState)(!1),[I,J]=(0,e.useState)(!1),[K,L]=(0,e.useState)(null),[M,N]=(0,e.useState)({}),[O,P]=(0,e.useState)([]),[Q,R]=(0,e.useState)(null),[S,T]=(0,e.useState)([]),[U,V]=(0,e.useState)({}),[W,X]=(0,e.useState)({}),[Y,Z]=(0,e.useState)([]),[$,_]=(0,e.useState)(null),[aa,ab]=(0,e.useState)(null),[ac,ad]=(0,e.useState)(null),[ae,af]=(0,e.useState)("default"),[ag,ah]=(0,e.useState)(()=>{let a=p?.context.thinkingLevel;return a&&"off"!==a?a:"auto"}),[ai,ak]=(0,e.useState)(),[al,am]=(0,e.useState)(null),[an,ao]=(0,e.useState)(null),[ap,aq]=(0,e.useState)(!1),ar=(0,e.useRef)(0),as=(0,e.useRef)(0),at=(0,e.useRef)(""),[au,av]=(0,e.useState)(null),[aw,ax]=(0,e.useState)(p?.contextUsage??null),[ay,az]=(0,e.useState)(null),[aA,aB]=(0,e.useState)(null),[aC,aE]=(0,e.useState)(null),[aF,aJ]=(0,e.useState)(null),[aK,aL]=(0,e.useState)(!1),[aM,aN]=(0,e.useState)(!1),[aO,aP]=(0,e.useState)(null),[aQ,aR]=(0,e.useState)(null),[aS,aT]=(0,e.useState)(null),aU=(0,e.useRef)(null),[aV,aW]=(0,e.useState)(!1),[aX,aY]=(0,e.useState)(null),[aZ,a$]=(0,e.useState)([]),[a_,a0]=(0,e.useState)(!1),[a1,a2]=(0,e.useReducer)(f$,{visible:[],pending:[]}),[a3,a4]=(0,e.useState)(null),[a5,a6]=(0,e.useState)(null),[a7,a8]=(0,e.useState)(null),a9=(0,e.useRef)(null),[ba,bb]=(0,e.useState)(null),[bc,bd]=(0,e.useState)([]),[be,bf]=(0,e.useState)([]),[bg,bh]=(0,e.useState)({steering:[],followUp:[]}),[bi,bj]=(0,e.useState)([]),[bk,bl]=(0,e.useReducer)(d7,[]),bm=(0,e.useRef)(0),bn=(0,e.useMemo)(()=>(function(a,b){let c=new Map;for(let b of a){if(!b.inQueue)continue;let a=`${b.kind}\u0000${d5(b)}`;c.set(a,(c.get(a)??0)+1)}let d=[],e=(a,b)=>{b.forEach((b,e)=>{let f=`${a}\u0000${d4(b)}`,g=c.get(f)??0;g>0?c.set(f,g-1):d.push({key:`queue-${a}-${e}`,kind:a,text:b,images:0,stage:"accepted",removable:!0})})};for(let c of(e("steer",b?.steering??[]),e("followUp",b?.followUp??[]),a))d.push({key:`sent-${c.id}`,kind:c.kind,text:c.text,images:c.images,stage:c.stage,removable:c.inQueue});return d})(bk,bg),[bk,bg]),[bo,bp]=(0,e.useState)(null),bq=(0,e.useRef)(null),br=(0,e.useRef)(null),bs=(0,e.useRef)(null),bt=(0,e.useRef)(null),bu=(0,e.useRef)(null),bv=(0,e.useRef)(0),bw=(0,e.useRef)(!1),bx=(0,e.useRef)(b?.id??null),by=(0,e.useRef)(p?.leafId??null),bz=(0,e.useRef)(y),bA=(0,e.useRef)(A);bz.current=y,bA.current=A;let bB=(0,e.useRef)({sessionId:b?.id??null,outputs:[],seq:0}),bC=(0,e.useRef)(!1),bD=(0,e.useRef)(!1),bE=(0,e.useRef)(!1),bF=(0,e.useRef)(-1),bG=(0,e.useRef)("unknown"),bH=(0,e.useRef)(null),bI=(0,e.useRef)(null),bJ=(0,e.useRef)(0),bK=(0,e.useRef)(!1),bL=(0,e.useRef)(0),bM=(0,e.useRef)(null),bN=(0,e.useRef)(null),bO=(0,e.useRef)(null);(0,e.useRef)(!1);let bP=(0,e.useRef)(!0),[bQ,bR]=(0,e.useState)(!1),[bS,bT]=(0,e.useState)(null),bU=(0,e.useRef)(void 0),bV=(0,e.useRef)(0),bW=(0,e.useRef)(0),bX=(0,e.useRef)(()=>{}),bY=(0,e.useRef)(null),bZ=(0,e.useRef)(null),b$=(0,e.useRef)(null),b_=(0,e.useRef)(null),b0=(0,e.useRef)(!1),b1=(0,e.useRef)(null),b2=(0,e.useRef)(null),b3=(0,e.useRef)(null),b4=(0,e.useRef)(null),b5=(0,e.useRef)(0),b6=(0,e.useRef)(null),b7=(0,e.useRef)(null);(0,e.useRef)(!1).current=a.transitioning??!1,(0,e.useRef)(Date.now());let b8=(0,e.useRef)(0),b9=(0,e.useRef)(0),ca=(0,e.useRef)(null),cb=(0,e.useRef)(!1),cc=(0,e.useRef)(Promise.resolve()),cd=a.setToolPreset??af,ce=aC??q?.context.model??aF??null,cf=o?$??ac:ce,cg=(0,e.useMemo)(()=>{if(a3)return{...a3,totalActiveMs:q?.totalActiveMs};let a={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},c=0,d=0,e=0,f=0,g=0;for(let b of y){if("user"===b.role&&(d+=1),"toolResult"===b.role&&(f+=1),"assistant"!==b.role)continue;e+=1;let h=b.usage;g+=b.content.filter(a=>"toolCall"===a.type).length,h&&(a.input+=h.input??0,a.output+=h.output??0,a.cacheRead+=h.cacheRead??0,a.cacheWrite+=h.cacheWrite??0,c+=h.cost?.total??0)}return(a.total=a.input+a.output+a.cacheRead+a.cacheWrite,0===a.total&&0===y.length)?null:{sessionFile:q?.filePath||void 0,sessionId:bx.current??b?.id??"",sessionName:b?.name,userMessages:d,assistantMessages:e,toolCalls:g,toolResults:f,totalMessages:y.length,tokens:a,cost:c,totalActiveMs:q?.totalActiveMs,...aw?{contextUsage:aw}:{}}},[y,a3,aw,q?.filePath,q?.totalActiveMs,b?.id,b?.name]),ch=(0,e.useRef)(0),ci=(0,e.useCallback)((a,b)=>{a&&bx.current===a&&Array.isArray(b)&&(ch.current+=1,bp(c=>c?.sid===a&&fS(c.phases,b)?c:{sid:a,phases:b}))},[]),cj=(0,e.useCallback)((a,b,c)=>{bx.current===a&&ch.current===c&&Array.isArray(b)&&bp(c=>c?.sid===a&&fS(c.phases,b)?c:{sid:a,phases:b})},[]),ck=(0,e.useCallback)(a=>{let b="function"==typeof a?a(bz.current):a;bz.current=b,z(b)},[]),cl=(0,e.useCallback)(a=>{bA.current=a,B(a)},[]),cm=(0,e.useCallback)(async(a,b=!1,c=!1,d)=>{let e=!1;try{b&&t(!0);let f=d??null;if(!f){let c=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),d=await fetch(`/api/sessions/${encodeURIComponent(a)}?${c}`);if(404===d.status)return b&&(r(null),x(null),ck([]),D(null),v(null)),null;if(!d.ok)throw Error(`HTTP ${d.status}`);f=await d.json()}if(bx.current!==a)return null;r(f),x(f.leafId),by.current=f.leafId??null;let g=aI(f.context.messages,f.context.entryIds??[],bB.current.sessionId===a?bB.current.outputs:[]);ck(g.messages),cl(g.entryIds),D(f.context.compactedWork??null),ax(f.contextUsage??null),aE(a=>cb.current?a:null),v(null);let h=!c&&b4.current===a;if(h||(ah(f.context.configuredThinkingLevel??f.context.thinkingLevel??"off"),ak(f.context.thinkingLevel)),am(f.context.thinkingCeiling??null),e=!0,b&&t(!1),!c){if(h)try{let b=b5.current,c=await fetch(`/api/sessions/${encodeURIComponent(a)}/state`);if(c.ok&&bx.current===a){let d=await c.json();bx.current===a&&b5.current===b&&(d.state?.thinkingLevel!==void 0?(ah(d.state.configuredThinkingLevel??d.state.thinkingLevel),ak(d.state.thinkingLevel)):d.running||(b4.current=null,ah(f.context.configuredThinkingLevel??f.context.thinkingLevel??"off"),ak(f.context.thinkingLevel)))}}catch(a){console.error("Failed to refresh live thinking level:",a)}return null}try{let b=ch.current,c=await fetch(`/api/sessions/${encodeURIComponent(a)}/state`);if(!c.ok)throw Error(`HTTP ${c.status}`);let d=await c.json();if(bx.current!==a)return null;let e=d.state;return e?(void 0!==e.contextUsage&&ax(e.contextUsage??null),void 0!==e.systemPrompt&&az(e.systemPrompt??null),void 0!==e.thinkingLevel&&(b4.current=a,ah(e.configuredThinkingLevel??e.thinkingLevel),ak(e.thinkingLevel)),void 0!==e.thinkingCeiling&&am(e.thinkingCeiling??null),void 0!==e.extensionStatuses&&bd(e.extensionStatuses??[]),void 0!==e.extensionWidgets&&bf(e.extensionWidgets??[]),void 0!==e.queuedMessages&&bh(fP(e.queuedMessages)),void 0!==e.subagents&&bj(a=>fN(a,e.subagents??[])),cj(a,e.todoPhases,b)):d.running||bh({steering:[],followUp:[]}),d}catch(a){return console.error("Failed to load agent state:",a),null}}catch(a){return v(String(a)),null}finally{b&&!e&&t(!1)}},[cj,cl,ck]),cn=(0,e.useCallback)(a=>{let b=cc.current.then(async()=>{bx.current===a&&await cm(a)});return cc.current=b.catch(()=>{}),b},[cm]),co=(0,e.useCallback)(async(a,b)=>{let c=++as.current;try{let d=new URLSearchParams({deferThinking:"1",deferMedia:"1"});b&&d.set("leafId",b);let e=`/api/sessions/${encodeURIComponent(a)}/context?${d}`,f=await fetch(e);if(!f.ok)throw Error(`HTTP ${f.status}`);let g=await f.json();if(as.current!==c||bx.current!==a)return;by.current=b;let h=aI(g.context.messages,g.context.entryIds??[],bB.current.sessionId===a?bB.current.outputs:[]);ck(h.messages),cl(h.entryIds),D(g.context.compactedWork??null),ax(g.contextUsage??null)}catch(a){console.error("Failed to load context:",a)}},[cl,ck]),cp=(0,e.useCallback)(async a=>{try{let b=await fK(a,{type:"get_tools"});if(b){let{getPresetFromTools:a}=await Promise.resolve().then(c.bind(c,29947));cd(a(b))}}catch(a){console.error("Failed to load tools:",a)}},[cd]),cq=(0,e.useCallback)((a=0,b="(no messages)")=>{let c=bx.current;o&&d&&c&&!b0.current&&(b0.current=!0,i?.({id:c,path:"",cwd:d,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:a,firstMessage:b,transient:!0}))},[o,d,i]),cr=(0,e.useCallback)(async()=>{if(b$.current)return b$.current;let a=bx.current;if(a&&b7.current!==a||!a&&(!o||!d))return a;let b=(async()=>{let b=a;if(!b){let a=b1.current,c=b3.current,e=b2.current;a&&aJ(a);let f={cwd:d,type:"ensure_session",toolNames:(0,e1.xG)(ae),...a?{provider:a.provider,modelId:a.modelId}:{},...c?{thinkingLevel:c}:{},...a&&null!==e?{oauthPosition:e}:{}},g=JSON.stringify(f),h=b_.current,i=h?.body===g?h.createRequestId:fX();b_.current={body:g,createRequestId:i};let j=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...f,createRequestId:i})});if(!j.ok)throw Error(`HTTP ${j.status}`);let k=await j.json();b_.current=null,b=k.sessionId,bx.current=b,null!==b6.current&&(b7.current=b),k.model&&b1.current===a&&(aJ(k.model),a||ad(k.model)),k.thinkingLevel&&b3.current===c&&(ah(k.configuredThinkingLevel??k.thinkingLevel),ak(k.thinkingLevel))}for(;b7.current===b;){let a=b6.current;await fK(b,{type:"set_thinking_ceiling",ceiling:a}),b6.current===a&&b7.current===b&&(b7.current=null)}return b})();b$.current=b;try{return await b}finally{b$.current=null}},[o,d,ae]),cs=(0,e.useCallback)(async()=>{let a=bx.current??await cr();if(!a)return a$([]),[];a0(!0);try{let b=await fK(a,{type:"get_commands"}),c=b?.commands??[];return a$(c),c}catch(a){return console.error("Failed to load slash commands:",a),a$([]),[]}finally{a0(!1)}},[cr]),ct=(0,e.useCallback)(()=>{bv.current+=1,bw.current=!1,bu.current&&(clearTimeout(bu.current),bu.current=null)},[]),cu=(0,e.useCallback)(()=>{bq.current?.close(),bq.current=null,br.current=null,bs.current=null},[]),cv=(0,e.useCallback)(()=>{bt.current?.close(),bt.current=null},[]);(0,e.useCallback)(a=>{cv();let b=new EventSource(`/api/agent/${encodeURIComponent(a)}/events?entries=1`);bt.current=b,b.onmessage=b=>{try{let c=JSON.parse(b.data);"session_snapshot"===c.type?bM.current?.(c):"agent_start"===c.type&&bN.current?.(a)}catch{}}},[cv]);let cw=(0,e.useCallback)(a=>{cu();let b=new EventSource(`/api/agent/${encodeURIComponent(a)}/events`);bq.current=b,br.current=a;let c=new Promise(c=>{let d=!1,e=a=>{d||(d=!0,clearTimeout(f),bs.current?.source===b&&(bs.current.pending=!1),c({status:a,source:b}))},f=setTimeout(()=>e("timeout"),5e3);b.onmessage=a=>{try{let b=JSON.parse(a.data);"update_maintenance"===b.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:b})),"connected"===b.type&&e("connected"),bM.current?.(b)}catch{}},b.onerror=()=>{if(b.readyState===EventSource.CLOSED&&(e("closed"),bq.current===b&&(bC.current||bw.current))){bq.current=null,br.current=null,bs.current=null;let b=bv.current;setTimeout(()=>{b===bv.current&&!bq.current&&(bC.current||bw.current)&&cw(a)},1e3)}}});return bs.current={source:b,promise:c,pending:!0},c},[cu]),cx=(0,e.useCallback)(async a=>{let b=bq.current;if(b&&br.current===a){if(b.readyState===EventSource.OPEN)return;let a=bs.current;if(a?.source===b&&a.pending&&(await a.promise,bq.current===b&&b.readyState===EventSource.OPEN))return}let c=await cw(a);if("connected"!==c.status&&c.source.readyState!==EventSource.OPEN)throw bq.current===c.source&&(bq.current=null),br.current===a&&(br.current=null),bs.current?.source===c.source&&(bs.current=null),c.source.close(),new fW(c.status)},[cw]),cy=(0,e.useCallback)(async(a,b)=>{let c=a9.current;if(c?.id===a.id&&"sending"===c.status)return;let d=bx.current,e=a=>{a9.current=a,a8(a)};if(!d)return void e({id:a.id,status:"failed",error:"no session"});e({id:a.id,status:"sending"});try{await fK(d,{type:"extension_ui_response",id:a.id,...b})}catch(b){e({id:a.id,status:"failed",error:b instanceof Error?b.message:String(b)});return}e(null),a6(b=>b?.id===a.id?null:b)},[]),cz=(0,e.useCallback)(async(a,b)=>{let c=bx.current;if(c)try{await fK(c,{type:"extension_ui_input",id:a.id,data:b})}catch(a){console.error("Failed to send extension custom UI input:",a)}},[]),cB=(0,e.useCallback)(a=>{let b=a.message.trim();b&&a2({type:"add",notice:{id:a.id??fX(),message:b,type:a.type??"info"}})},[]),cC=(0,e.useCallback)(a=>{let b={role:"custom",customType:aD,content:aj(a).trim(),display:!0,timestamp:Date.now()},c=bB.current,d=bx.current;c.sessionId!==d&&(c.sessionId=d,c.outputs=[]);let e=bA.current.slice(0,bz.current.length),f=null;for(let a=e.length-1;a>=0;a--)if(!aH(e[a])){f=e[a];break}c.seq+=1,c.outputs.push({entryId:`${aG}${c.seq}`,baseEntryId:f,message:b}),ck(a=>[...a,b])},[ck]),cD=(0,e.useCallback)(b=>{if("custom"!==b.method&&"closed"in b&&b.closed){a6(a=>a?.id===b.id?null:a),a9.current?.id===b.id&&(a9.current=null,a8(null));return}switch(fG(b)&&h?.(b),b.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":a6(b);break;case"notify":cB({id:b.id,message:b.message,type:b.notifyType??"info"});break;case"setStatus":bd(a=>{let c=a.filter(a=>a.key!==b.statusKey);return void 0!==b.statusText?[...c,{key:b.statusKey,text:b.statusText}]:c});break;case"setWidget":bf(a=>{let c=a.filter(a=>a.key!==b.widgetKey);return b.widgetLines?[...c,{key:b.widgetKey,lines:b.widgetLines,placement:b.widgetPlacement??"aboveEditor"}]:c});break;case"setTitle":b.title&&(document.title=b.title);break;case"set_editor_text":a.chatInputRef?.current?.insertText(b.text);break;case"custom":bb(a=>b.closed?a?.id===b.id?null:a:b)}},[cB,h,a.chatInputRef]),cE=(0,e.useCallback)(()=>{let a=bC.current;return bC.current=!1,H(!1),aY(null),av(null),F({type:"end"}),a},[]),cF=(0,e.useCallback)(()=>{bG.current="unknown",bH.current=null;let a=fU(bz.current,bA.current);bI.current=a?{entryId:a.entryId,key:f1(a.message)}:null,bJ.current+=1},[]),cG=(0,e.useCallback)(()=>{let a=bG.current,b=bH.current;if("unknown"===a){let c=fU(bz.current,bA.current),d=c?.message,e=bI.current;null!==c&&(null===e||(null!==c.entryId&&null!==e.entryId?c.entryId!==e.entryId:f1(c.message)!==e.key))&&d?.role==="assistant"&&d.stopReason&&(a=fT(d),b??={provider:d.provider,...void 0!==d.credentialId?{credentialId:d.credentialId}:{}})}return{outcome:a,sessionId:bx.current,...b?{provider:b.provider,...void 0!==b.credentialId?{credentialId:b.credentialId}:{}}:{}}},[]),cH=(0,e.useCallback)(a=>{let b=cG();if("unknown"!==b.outcome||!a)return void g?.(b);let c=bJ.current;a.catch(()=>void 0).then(()=>{let a=bx.current===b.sessionId&&bJ.current===c;g?.(a?cG():b)})},[g,cG]),cI=(0,e.useCallback)((a,b)=>bF.current!==a&&(bF.current=a,cH(b),!0),[cH]),cJ=(0,e.useCallback)(a=>{ct(),bw.current=!0;let b=bv.current,c=async()=>{if(b===bv.current&&bx.current===a&&bw.current)try{let d=ch.current,e=await fetch(`/api/agent/${encodeURIComponent(a)}`);if(!e.ok)throw Error(`HTTP ${e.status}`);let f=await e.json();if(b!==bv.current||bx.current!==a||!bw.current)return;let g=f.state;if(bj(a=>fN(a,g?.subagents??[])),cj(a,g?.todoPhases,d),f.running&&g&&(g.isStreaming||g.isPromptRunning||g.isHandoffRunning)){bw.current=!1,bu.current=null,bD.current=!!g?.isStreaming,bE.current=!!g?.isPromptRunning,bC.current=!0,H(!0),aY(g?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(f.running&&g?.isCompacting){aN(!0),aT(fR(g)),bu.current=setTimeout(()=>void c(),600);return}if(f.running&&(g?.subagents?.length??0)>0){bu.current=setTimeout(()=>void c(),1e3);return}bw.current=!1,bu.current=null,cu()}catch{if(b!==bv.current||bx.current!==a||!bw.current)return;bu.current=setTimeout(()=>void c(),600)}};bu.current=setTimeout(()=>void c(),3e4)},[cj,ct,cu]),cK=(0,e.useCallback)(async(a=bx.current,b=b8.current)=>{if(b8.current===b)try{a&&await cm(a)}finally{if(b8.current!==b)return;let c=bE.current,d=bD.current;bE.current=!1,bD.current=!1,ca.current=null;let e=cE();c?cI(b):d&&e&&cH(),a&&cJ(a)}},[cm,cH,cI,cJ,cE]),cL=(0,e.useCallback)(async(a,b)=>{await fY(800);let c=Date.now();for(;bC.current&&Date.now()-c<2e4;){if(void 0!==b&&b8.current!==b)return;try{let c=await fetch(`/api/agent/${encodeURIComponent(a)}`);if(c.ok){let d=await c.json(),e=d.state;if(!d.running||!e||!e.isStreaming&&!e.isPromptRunning)return void await cK(a,b)}}catch{}await fY(600)}},[cK]);(0,e.useCallback)(async a=>{let b=bL.current+1;for(bL.current=b;bK.current&&bL.current===b&&bx.current===a;){await fY(1e3);try{let c=await fetch(`/api/agent/${encodeURIComponent(a)}`);if(!c.ok)continue;let d=await c.json();if(d.state?.isBashRunning)continue;if(await cm(a),bL.current!==b||bx.current!==a)return;bK.current=!1,J(!1),L(null);return}catch{}}},[cm]),(0,e.useCallback)(async a=>{if(!bC.current)return;let b=b8.current;try{let c=ch.current,d=await fetch(`/api/agent/${encodeURIComponent(a)}`);if(!d.ok)return;let e=await d.json();if(b8.current!==b)return;let f=e.state;if(aN(f?.isCompacting??!1),aT(fR(f)),bh(fP(f?.queuedMessages)),f?.contextUsage!==void 0&&ax(f.contextUsage??null),bj(a=>fN(a,f?.subagents??[])),cj(a,f?.todoPhases,c),e.running&&f&&(f.isStreaming||f.isPromptRunning||f.isCompacting||f.isHandoffRunning)||!bC.current)return;f&&(void 0!==f.systemPrompt&&az(f.systemPrompt??null),void 0!==f.extensionStatuses&&bd(f.extensionStatuses??[]),void 0!==f.extensionWidgets&&bf(f.extensionWidgets??[])),await cK(a,b)}catch{}},[cj,cK]);let cM=(0,e.useCallback)(async a=>{let b=await cm(a,!1,!0),c=b?.state;return!!b?.running&&!!c&&bx.current===a&&!bC.current&&!!(c.isStreaming||c.isPromptRunning||c.isHandoffRunning)&&(bD.current=!!c.isStreaming,bE.current=!!c.isPromptRunning,bC.current=!0,H(!0),aY(c.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),F({type:"start"}),cw(a),!c.isStreaming&&c.isPromptRunning&&cL(a),!0)},[cw,cm,cL]),cN=(0,e.useCallback)(async(a,b=b8.current)=>{let c=b9.current+1;b9.current=c;try{let d=await fetch(`/api/agent/${encodeURIComponent(a)}`);if(!d.ok)return;let e=await d.json();if(c!==b9.current||bx.current!==a||b8.current!==b)return;e.state?.contextUsage!==void 0&&ax(e.state.contextUsage??null)}catch{}},[]);bN.current=a=>{if(bx.current!==a||bC.current||bq.current||bO.current)return;let b=cM(a).then(async b=>{b||bx.current!==a||bC.current||await cm(a)}).catch(()=>{}).finally(()=>{bO.current===b&&(bO.current=null)});bO.current=b},bM.current=(0,e.useCallback)(a=>{switch(a.type){case"session_snapshot":{let b=function(a,b,c,d,e){if("session_snapshot"!==a.type||"string"!=typeof a.sessionId||a.sessionId!==b||"string"!=typeof a.entryId||""===a.entryId||a.entryId===c||!a.context||!Array.isArray(a.context.messages)||!Array.isArray(a.context.entryIds)||a.context.messages.length!==a.context.entryIds.length)return null;let f=a.context.messages,g=new Map;for(let a of f){let b=f1(a);g.set(b,(g.get(b)??0)+1)}let h=Math.min(d.length,e.length);for(let a of d.slice(0,h)){let b=f1(a),c=g.get(b)??0;c>0&&g.set(b,c-1)}let i=d.slice(h).filter(a=>{let b=f1(a),c=g.get(b)??0;return 0===c||(g.set(b,c-1),!1)});return{entryId:a.entryId,messages:[...f,...i],entryIds:[...a.context.entryIds],compactedWork:a.context.compactedWork??null}}(a,bx.current,by.current,bz.current,bA.current);if(!b)break;by.current=b.entryId;let c=aI(b.messages,b.entryIds,bB.current.sessionId===bx.current?bB.current.outputs:[]);ck(c.messages),cl(c.entryIds),D(b.compactedWork);break}case"agent_start":{let a=!bC.current;ct(),a&&cF(),bD.current=!0,bC.current=!0,H(!0),aY({kind:"waiting_model"}),F({type:"start"});break}case"agent_end":if(!bC.current)break;if(aY(null),av(null),F({type:"end"}),bx.current){cm(bx.current);let a=ch.current;fetch(`/api/agent/${encodeURIComponent(bx.current)}`).then(a=>a.json()).then(b=>{b.state?.contextUsage!==void 0&&ax(b.state.contextUsage??null),b.state?.systemPrompt!==void 0&&az(b.state.systemPrompt??null),b.state?.extensionStatuses!==void 0&&bd(b.state.extensionStatuses??[]),b.state?.extensionWidgets!==void 0&&bf(b.state.extensionWidgets??[]),b.state?.subagents!==void 0&&bj(a=>fN(a,b.state?.subagents??[])),bx.current&&cj(bx.current,b.state?.todoPhases,a),b.state?.goal!==void 0&&bT(b.state.goal??null),bh(fP(b.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":bT(a.status??null);break;case"agent_settled":{let a=bD.current;if(bD.current=!1,!a||bE.current)break;let b=bx.current,c=cE();aN(!1);let d=b?cm(b):void 0;b&&cJ(b),c&&cH(d);break}case"prompt_done":{let a=b8.current,b=bE.current;bE.current=!1,ca.current=null;let c=bF.current!==a;if(!b&&!c)break;let d=bx.current;cI(a,d?cm(d):void 0),!bD.current&&(cE(),d&&cJ(d))}break;case"prompt_error":bG.current="failed",cB({type:"error",message:a.errorMessage??"Command failed"});break;case"extension_error":bG.current="failed",cB({type:"error",message:a.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!bC.current)break;let b=a.message;if(b?.role!=="assistant")break;b&&F({type:"update",message:(0,fI.B)(b)}),aY(null);break}case"message_end":{if(!bC.current)break;let b=a.message;if(b?.role==="assistant"&&(bH.current={provider:b.provider,...void 0!==b.credentialId?{credentialId:b.credentialId}:{}},bG.current=fT(b)),b&&"user"===b.role){let a=(0,fI.B)(b),c=f0(a),d=ca.current;ca.current=null,ck(b=>{let e=b[b.length-1];return d&&e?.role==="user"&&f0(e)===d?d===c?b:[...b.slice(0,-1),a]:[...b,a]}),d||bl({type:"user-message",kind:"steering"in a&&!0===a.steering?"steer":"followUp",text:"user"!==a.role?"":"string"==typeof a.content?a.content:a.content.filter(a=>"text"===a.type).map(a=>a.text).join("\n"),images:"user"!==a.role||"string"==typeof a.content?0:a.content.filter(a=>"image"===a.type).length})}else b&&ck(a=>[...a,(0,fI.B)(b)]);let c=bx.current;c&&cN(c),F({type:"reset"}),aY({kind:"waiting_model"});break}case"thinking_level_changed":{let b=bx.current,c=a.thinkingLevel;b&&void 0!==c&&(b4.current=b,b5.current+=1,ah(a.configured??c),ak(c));break}case"todo_changed":ci(bx.current,a.phases);break;case"tool_execution_start":{let b=a.toolCallId,c=a.toolName,d=a.args;aY(a=>{let e=a?.kind==="running_tools"?[...a.tools]:[];return e.some(a=>a.id===b)||e.push({id:b,name:c,args:d}),{kind:"running_tools",tools:e}});break}case"tool_execution_end":{let b=a.toolCallId;aY(a=>{if(a?.kind!=="running_tools")return a;let c=a.tools.filter(a=>a.id!==b);return 0===c.length?{kind:"waiting_model"}:{kind:"running_tools",tools:c}});break}case"subagent_lifecycle":{let b=a.payload;if(!b?.id)break;if("started"!==b.status){let a="failed"===b.status?"failed":"aborted"===b.status?"aborted":"completed";bj(c=>{let d=c.find(a=>a.id===b.id);return fN(c,[{id:b.id,index:b.index??d?.index??0,agent:b.agent??d?.agent??b.id,agentSource:b.agentSource??d?.agentSource??"bundled",description:b.description??d?.description,status:a,task:d?.task,assignment:d?.assignment,sessionFile:b.sessionFile??d?.sessionFile,parentToolCallId:b.parentToolCallId??d?.parentToolCallId,lastUpdate:Date.now(),progress:d?.progress?{...d.progress,status:a}:void 0}])});break}let c={id:b.id,index:b.index??0,agent:b.agent??b.id,agentSource:b.agentSource??"bundled",description:b.description,status:"running",sessionFile:b.sessionFile,parentToolCallId:b.parentToolCallId,lastUpdate:Date.now()};bj(a=>fN(a,[c]));break}case"subagent_progress":{let b=a.payload;if(!b?.progress)break;let c=b.progress,d={id:c.id,index:b.index??c.index,agent:b.agent??c.agent,agentSource:b.agentSource??"bundled",description:c.description,status:c.status,task:b.task??c.task,assignment:b.assignment??c.assignment,sessionFile:b.sessionFile,parentToolCallId:b.parentToolCallId,lastUpdate:Date.now(),progress:c};bj(a=>fN(a,[d]));break}case"queue_update":bh({steering:[...a.steering??[]],followUp:[...a.followUp??[]]});break;case"auto_retry_start":av({attempt:a.attempt,maxAttempts:a.maxAttempts,errorMessage:a.errorMessage});break;case"auto_retry_end":av(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof a.reason){aU.current=a.reason;let b=a.reason;aT(a=>a?{...a,reason:b}:a)}aN(!0),aP(null),aR(null);break;case"auto_compaction_end":case"compaction_end":if(aN(!1),a.errorMessage)aP(a.errorMessage),aR(null);else if(!a.aborted){aR(f2(a.result,a.reason??"auto"));let b=bx.current;b&&(cm(b),cN(b))}break;case"extension_ui_request":cD(a)}},[cB,ci,cj,ct,cD,cm,cH,cI,cN,cF,cJ,cE,cl,ck]);let cO=(0,e.useCallback)(async(c,e,f)=>{let g=c.trim();if(!g&&!e?.length&&!f?.length)return"returned";if(bC.current||bK.current||cb.current)return"unknown";let h=cA(c,f??[]),i=!e?.length&&!f?.length&&g.startsWith("/");if(!e?.length&&!f?.length&&g.startsWith("!")){let a=g.startsWith("!!"),b=(a?g.slice(2):g.slice(1)).trim();return b?(await bU.current?.(b,a),"accepted"):"unknown"}cF();let j=b8.current+1;ct(),bE.current=!0;let k=e?.map(a=>({type:"image",source:{type:"base64",media_type:a.mimeType,data:a.data}})),l={role:"user",content:k?.length?[...h.trim()?[{type:"text",text:h}]:[],...k]:h,timestamp:Date.now()};ck(a=>[...a,l]),ca.current=f0(l),b8.current=j,bC.current=!0,H(!0),aY(i?{kind:"running_command"}:{kind:"waiting_model"}),F({type:"start"}),bX.current(!0);let m=e?.map(a=>({type:"image",data:a.data,mimeType:a.mimeType})),n=null,p=!1,q="unknown";try{if(o&&d){let a=bx.current??await b$.current,b=await cr();b&&(n=b,$&&(aJ($),a&&await fK(b,{type:"set_model",provider:$.provider,modelId:$.modelId})),await cx(b),p=!0,await fK(b,{type:"prompt",message:h,...m?.length?{images:m}:{}}),cq(1,c),q="accepted")}else b&&(n=b.id,await cx(b.id),p=!0,await fK(b.id,{type:"prompt",message:h,...m?.length?{images:m}:{}}),q="accepted");return i&&n&&cL(n,j),q}catch(h){console.error("Failed to send message:",h);let d=h instanceof fJ&&"update_draining"===h.code&&!1===h.accepted;if(!(!p||h instanceof fJ&&"prompt_rejected"===h.code&&!1===h.accepted||d)&&n)return cL(n,j),"unknown";bE.current=!1,bC.current=!1,cu();let g=ca.current;return g&&ck(a=>{let b=a[a.length-1];return b?.role==="user"&&f0(b)===g?a.slice(0,-1):a}),cB({type:"error",message:h instanceof Error?h.message:String(h)}),a.chatInputRef?.current?.restoreSubmission?.(c,f3(e),f,b?.id??n??void 0),ca.current=null,H(!1),aY(null),F({type:"end"}),"returned"}},[o,d,$,b,cr,cx,cq,cL,cB,ct,cu,a.chatInputRef,cF,ck]);bU.current=(0,e.useCallback)(async(c,d)=>{if(bC.current||bK.current)return;let e=`${d?"!!":"!"}${c}`;bK.current=!0,bX.current(!0),L({command:c,excludeFromContext:d}),J(!0);try{let a=bx.current??b?.id??await cr();if(!a)throw Error("Unable to create a session for the shell command");await fK(a,{type:"bash",command:c,excludeFromContext:d}),await cm(a),cq(1,e)}catch(b){console.error("Failed to execute shell command:",b),cB({type:"error",message:b instanceof Error?b.message:String(b)}),a.chatInputRef?.current?.insertIfEmpty(e)}finally{bK.current=!1,L(null),J(!1)}},[cB,cr,cm,a.chatInputRef,cq,b]);let cP=(0,e.useCallback)(async()=>{let a=bx.current;if(a){if(bK.current){try{await fK(a,{type:"abort_bash"})}catch(a){console.error("Failed to abort bash:",a)}return}try{await fK(a,{type:"abort"}),bG.current="aborted"}catch(a){console.error("Failed to abort:",a)}}},[]),cQ=(0,e.useCallback)(async a=>{if(bK.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let b=bx.current;if(!b)return{forked:!1,error:"No active session to fork"};aB(a??null);try{let{cancelled:c,newSessionId:d}=await fK(b,{type:"fork",...a?{entryId:a}:{}})??{};if(!c&&d)return j?.(d),{forked:!0};return{forked:!1,error:"Fork was cancelled"}}catch(a){return console.error("Fork failed:",a),{forked:!1,error:a instanceof Error?a.message:String(a)}}finally{aB(null)}},[j]),cR=(0,e.useCallback)(async a=>{if(bK.current)return;let b=bx.current;b&&(fK(b,{type:"navigate_tree",targetId:a}).catch(()=>{}),x(a),await co(b,a))},[co]);(0,e.useCallback)(async a=>{if(bK.current)return;x(a);let b=bx.current;b&&(await co(b,a),a&&fK(b,{type:"navigate_tree",targetId:a}).catch(()=>{}))},[co]);let cS=(0,e.useCallback)(async(a,b)=>{if(o){let c={provider:a,modelId:b},d=b1.current?.provider===a;b1.current=c,d||(b2.current=null,ab(null)),_(c),aJ(c);let e=bx.current??await b$.current;if(!e)return;try{await fK(e,{type:"set_model",provider:a,modelId:b})}catch(a){console.error("Failed to set model:",a)}return}let c=bx.current;if(c&&!cb.current){cb.current=!0,aE({provider:a,modelId:b}),aL(!0);try{await fK(c,{type:"set_model",provider:a,modelId:b}),cb.current=!1,await cm(c)}catch(a){console.error("Failed to set model:",a),cb.current=!1,aE(aC),cB({type:"error",message:`Failed to switch model: ${a instanceof Error?a.message:String(a)}`}),await cm(c)}finally{cb.current=!1,aL(!1)}}},[cB,aC,o,cm,_]),cT=(0,e.useCallback)(async a=>{let b={provider:a.provider,modelId:a.modelId},c=a.oauthPosition,d={type:"set_model",provider:a.provider,modelId:a.modelId,thinkingLevel:"auto",...void 0!==c?{oauthPosition:c}:{}},e=b=>`${a.alias} preset was not applied: ${b instanceof Error?b.message:String(b)}`;if(o){if(cb.current)return!1;cb.current=!0,aL(!0);let a=b1.current,f=b2.current,g=b3.current;try{b1.current=b,b2.current=c??null,b3.current="auto";let a=bx.current??await b$.current;return a&&await fK(a,d),_(b),ab(c??null),aJ(b),ah("auto"),ak(void 0),a&&await cm(a),!0}catch(c){console.error("Failed to apply Main preset:",c),b1.current=a,b2.current=f,b3.current=g,cB({type:"error",message:e(c)});let b=bx.current;return b&&await cm(b),!1}finally{cb.current=!1,aL(!1)}}let f=bx.current;if(!f||cb.current)return!1;cb.current=!0,aE(b),aL(!0);try{return await fK(f,d),await cm(f),!0}catch(a){return console.error("Failed to apply Main preset:",a),aE(aC),cB({type:"error",message:e(a)}),await cm(f),!1}finally{cb.current=!1,aL(!1)}},[cB,aC,ai,o,cm,_,ag]),cU=(0,e.useCallback)(async a=>{let b=Y.find(b=>b.role===a),c=b?.resolved;if(!c)return;if(o){let a={provider:c.provider,modelId:c.modelId},b=c.thinkingLevel;b3.current=b??null,ah(b??"auto"),ak(void 0),b1.current=a,b2.current=null,ab(null),_(a),aJ(a)}let d=bx.current??(o?await b$.current:null);if(d)try{await fK(d,{type:"set_role_model",role:a}),o||aE({provider:c.provider,modelId:c.modelId})}catch(a){console.error("Failed to set role model:",a)}},[o,Y,_]),cV=(0,e.useCallback)(async()=>{let a=bx.current;if(a&&!aM){aU.current="manual",aN(!0),aP(null),aR(null);try{let b=await fK(a,{type:"compact"});aR(f2(b,"manual")),await cm(a,!0)}catch(a){aP(a instanceof Error?a.message:String(a)),aR(null)}finally{aN(!1)}}},[aM,cm]),cW=(0,e.useCallback)(async a=>{let c=d??b?.cwd??"",e=c?`/api/models?cwd=${encodeURIComponent(c)}`:"/api/models",f=await fetch(e,a?{signal:a}:void 0);if(!f.ok)throw Error(`HTTP ${f.status}`);let g=await f.json();N(g.models),R(g.modelError??null),T(g.modelScopeWarnings??[]),V(g.thinkingLevels??{}),X(g.thinkingLevelMaps??{}),Z(g.roles??[]);let h=g.modelList??[];if(P(h),o&&!bx.current){let a=(g.defaultModel?h.find(a=>a.id===g.defaultModel?.modelId&&a.provider===g.defaultModel?.provider):void 0)??h[0];ad(a?{provider:a.provider,modelId:a.id}:null);let b=a&&g.thinkingLevelPins?.[`${a.provider}/${a.id}`];null===b3.current&&ah(b??"auto")}},[o,d,b?.cwd]),cX=(0,e.useCallback)(async a=>{if(!a.startsWith("/"))return{handled:!1};let b=a.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!b)return{handled:!1};let[,c,d=""]=b,e=d.trim(),f=await cr(),g=a=>(a.handled&&(a.error?cB({type:"error",message:a.error}):"openSessionStats"!==a.action&&cB({type:"success",message:a.message??"Command completed"})),a);try{switch(c){case"compact":{if(!f||aM)return g({handled:!0,error:"No active session to compact"});aU.current="manual",aN(!0),aP(null),aR(null);let a=await fK(f,{type:"compact",...e?{customInstructions:e}:{}});return aR(f2(a,"manual")),await cm(f,!0)&&cq(),g({handled:!0,message:"Compacted context"})}case"reload":if(!f)return g({handled:!0,error:"No active session to reload"});return await fK(f,{type:"reload"}),await Promise.all([cm(f,!1,!0),cp(f),cs(),cW()]),g({handled:!0,message:"Reloaded session resources"});case"name":if(!f)return g({handled:!0,error:"No active session to name"});if(!e)return g({handled:!0,error:"Usage: /name <name>"});return await fK(f,{type:"set_session_name",name:e}),await cm(f)&&cq(),g({handled:!0,message:`Session renamed to ${e}`});case"session":{if(!f)return g({handled:!0,error:"No active session"});let a=await fK(f,{type:"get_session_stats"});return a&&a4(a),n?.(),g({handled:!0,action:"openSessionStats"})}case"copy":{if(!f)return g({handled:!0,error:"No active session"});let a=await fK(f,{type:"get_last_assistant_text"}),b=a?.text??"";if(!b)return g({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(b),g({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!f)return g({handled:!0,error:"No active session to fork"});let a=await cQ();if(!a.forked)return g({handled:!0,error:a.error??"Fork failed"});return g({handled:!0,message:"Forked a new session"})}case"goal":{if(!f)return g({handled:!0,error:"No active session"});let a=await fK(f,{type:"goal",args:e});if(bT(a?.status??null),a?.error)return g({handled:!0,error:a.error});if(a?.message&&a.message.includes("\n")){if(cC(a.message),a.prompt)return{handled:!0,prompt:a.prompt};return{handled:!0}}if(a?.prompt)return a.message&&cB({type:"success",message:a.message}),{handled:!0,prompt:a.prompt};return g({handled:!0,message:a?.message??"Command completed"})}case"handoff":if(!f)return g({handled:!0,error:"No active session"});if(bC.current||bK.current)return g({handled:!0,error:"Cannot hand off while the session is busy"});bC.current=!0,H(!0),aY({kind:"running_command"});try{await cx(f);let a=await fK(f,{type:"handoff",...e?{customInstructions:e}:{}});if(!a||a.cancelled)return g({handled:!0,error:"Handoff cancelled"});return await cm(f,!0)&&cq(),g({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{bC.current=!1,H(!1),aY(null),bx.current===f&&cJ(f)}default:{if(!f)return g({handled:!0,error:"No active session"});let b=await fK(f,{type:"execute_slash_command",message:a});if(!b?.handled)return{handled:!1};let c=b.output?.filter(a=>a.trim()).join("\n\n")??"";if(c&&cC(c),b.prompt)return{handled:!0,prompt:b.prompt};if(c)return{handled:!0};return g({handled:!0,message:"Command completed"})}}}catch(a){return g({handled:!0,error:a instanceof Error?a.message:String(a)})}finally{"compact"===c&&aN(!1)}},[cB,cC,cx,cr,cQ,aM,cW,cm,cs,cp,cq,n,cJ]),cY=(0,e.useCallback)(async(b,c,d)=>{let e=bx.current;if(!e)return cB({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),a.chatInputRef?.current?.restoreSubmission?.(b,f3(c),d),"returned";let f=cA(b,d??[]),g=c?.map(a=>({type:"image",data:a.data,mimeType:a.mimeType})),h=++bm.current;bl({type:"submit",id:h,kind:"steer",text:f,images:g?.length??0});try{return await fK(e,{type:"steer",message:f,...g?.length?{images:g}:{}}),bl({type:"ack",id:h}),"accepted"}catch(f){return bl({type:"fail",id:h}),console.error("Failed to steer:",f),cB({type:"error",message:f instanceof Error?f.message:String(f)}),a.chatInputRef?.current?.restoreSubmission?.(b,f3(c),d,e),"returned"}},[cB,a.chatInputRef]),cZ=(0,e.useCallback)(async(b,c,d,e)=>{let f=bx.current;if(!f)return cB({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),a.chatInputRef?.current?.restoreSubmission?.(b,f3(d),e),"returned";let g=cA(b,e??[]),h=d?.map(a=>({type:"image",data:a.data,mimeType:a.mimeType})),i=++bm.current;bl({type:"submit",id:i,kind:c,text:g,images:h?.length??0});try{return await fK(f,{type:"prompt",message:g,streamingBehavior:c,...h?.length?{images:h}:{}}),bl({type:"ack",id:i}),"accepted"}catch(c){return bl({type:"fail",id:i}),console.error("Failed to queue prompt:",c),cB({type:"error",message:c instanceof Error?c.message:String(c)}),a.chatInputRef?.current?.restoreSubmission?.(b,f3(d),e,f),"returned"}},[cB,a.chatInputRef]),c$=(0,e.useCallback)(async(b,c,d)=>{let e=bx.current;if(!e)return cB({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),a.chatInputRef?.current?.restoreSubmission?.(b,f3(c),d),"returned";let f=cA(b,d??[]),g=c?.map(a=>({type:"image",data:a.data,mimeType:a.mimeType})),h=++bm.current;bl({type:"submit",id:h,kind:"followUp",text:f,images:g?.length??0});try{return await fK(e,{type:"follow_up",message:f,...g?.length?{images:g}:{}}),bl({type:"ack",id:h}),"accepted"}catch(f){return bl({type:"fail",id:h}),console.error("Failed to follow up:",f),cB({type:"error",message:f instanceof Error?f.message:String(f)}),a.chatInputRef?.current?.restoreSubmission?.(b,f3(c),d,e),"returned"}},[cB,a.chatInputRef]),c_=(0,e.useCallback)(async()=>{let a=bx.current;if(a)try{await fK(a,{type:"abort_compaction"})}catch(a){console.error("Failed to abort compaction:",a)}},[]),c0=(0,e.useCallback)(async()=>{let b=bx.current;if(b)try{var c;let d=await fK(b,{type:"clear_queue"});bl({type:"withdraw"}),bh({steering:[],followUp:[]});let e={text:(c=[...d?.steering??[],...d?.followUp??[]]).map(({text:a,images:b})=>b?.length&&"[Image]"===a?"":a).filter(a=>a.trim()).join("\n\n"),images:c.flatMap(({images:a})=>a??[]).map(({data:a,mimeType:b})=>({data:a,mimeType:b}))};a.chatInputRef?.current?.restoreSubmission?.(e.text,e.images.length?e.images:void 0,void 0,b)}catch(a){console.error("Failed to recall queued messages:",a),cB({type:"error",message:"Failed to recall queued messages"})}},[a.chatInputRef,cB]),c1=(0,e.useCallback)(async(a,b)=>{let c=bx.current;if(c)try{let d=await fK(c,{type:"remove_queued_message",message:b,queue:a});if(!d?.removed)return;bl({type:"withdraw",kind:"steering"===a?"steer":"followUp",text:b}),bh(c=>{let d=c[a].indexOf(b);return(d<0&&""===b.trim()&&(d=c[a].indexOf("[Image]")),d<0)?c:{...c,[a]:c[a].filter((a,b)=>b!==d)}})}catch(a){console.error("Failed to remove queued message:",a),cB({type:"error",message:"Failed to remove queued message"})}},[cB]),c2=(0,e.useCallback)(async(a,b=null)=>{let c="auto"===a?b:null,d=c!==al;ah(a),am(c),o&&(!bx.current||b7.current===bx.current)&&(b3.current=a,b6.current=c),ak(void 0);let e=bx.current??await b$.current;if(e)try{b7.current===e?await cr():d&&await fK(e,{type:"set_thinking_ceiling",ceiling:c}),await fK(e,{type:"set_thinking_level",level:a}),await cm(e)}catch(a){console.error("Failed to set thinking level:",a),cB({type:"error",message:"Failed to set thinking level"}),await cm(e)}},[o,cm,cB,al,cr]);at.current=cf?`${cf.provider}/${cf.modelId}`:"";let c3=a=>a?`${a}|${at.current}`:null,c4=c3(b?.id??bx.current),c5=an&&an.key===c4?an.value:null,c6=(0,e.useCallback)(async()=>{let a=bx.current??await cr(),b=c3(bx.current);if(!a||!b)return;let c=++ar.current,d=()=>ar.current===c&&c3(bx.current)===b,e=a=>{d()&&ao({key:b,value:a})};aq(!0);try{let c=an?.key===b?an.value?.enabled:void 0;if(void 0===c){let b=fQ(await fK(a,{type:"get_state"}));if(!b)throw Error("Could not read the session's Fast state");c=b.enabled}if(!d())return;let f=await fK(a,{type:"set_fast_mode",enabled:!c});e({enabled:f?.enabled===!0,active:f?.active===!0})}catch(b){if(!d())return;cB({type:"error",message:b instanceof Error?b.message:String(b)});try{e(fQ(await fK(a,{type:"get_state"}))??null)}catch{e(null)}}finally{aq(!1)}},[cr,an,cB]),c7=(0,e.useCallback)(async a=>{let b=(0,e1.xG)(a);cd(a);let c=bx.current??await b$.current;if(c)try{await fK(c,{type:"set_tools",toolNames:b})}catch(a){console.error("Failed to set tools:",a)}},[cd]),c8=(0,e.useCallback)(a=>{bP.current=a,bR(b=>!a===b?b:!a)},[]);bX.current=c8;let c9=(0,e.useCallback)((a="smooth")=>{bW.current=Date.now()+700,bY.current?.scrollIntoView({behavior:a})},[]),da=(0,e.useCallback)(()=>{bV.current=0,c8(!0),c9("smooth")},[c9,c8]),db=(0,e.useCallback)(()=>{bV.current=0,c8(!1)},[c8]);return(0,e.useCallback)(a=>{a instanceof KeyboardEvent&&(!fV.has(a.key)||a.target instanceof Element&&a.target.closest("input, textarea, [contenteditable='true']"))||(bV.current=Date.now()+1200)},[]),(0,e.useCallback)(()=>{if(!bC.current&&!bK.current)return;let a=bZ.current;if(!a)return;let b=Date.now()<=bV.current;!b&&Date.now()<bW.current||(a.scrollHeight-a.scrollTop-a.clientHeight<=72?c8(!0):b&&c8(!1))},[c8]),{data:q,loading:s,error:u,activeLeafId:w,messages:y,entryIds:A,streamState:E,agentRunning:G,modelNames:M,modelList:O,modelError:Q,modelScopeWarnings:S,modelThinkingLevels:U,modelThinkingLevelMaps:W,modelRoles:Y,newSessionModel:$,toolPreset:ae,thinkingLevel:ag,effectiveThinkingLevel:ai,thinkingCeiling:al,retryInfo:au,contextUsage:aw,systemPrompt:ay,forkingEntryId:aA,isCompacting:aM,compaction:aS,compactError:aO,compactResult:aQ,currentModel:ce,displayModel:cf,modelSwitching:aK,sessionStats:cg,runStateKnown:aV,slashCommands:aZ,slashCommandsLoading:a_,queuedMessages:bg,deliveryRows:bn,subagents:bi,todoPhases:bo&&bo.sid===bx.current?bo.phases:null,compactedWork:C,notices:a1.visible,extensionDialog:a5,extensionResponse:a7,extensionCustomUi:ba,extensionStatuses:bc,extensionWidgets:be,respondToExtensionUi:cy,sendExtensionCustomInput:cz,isAutoModelSelection:o&&null===$,agentPhase:aX,isNew:o,autoFollowPaused:bQ,resumeAutoFollow:da,pauseAutoFollow:db,goalStatus:bS,sessionIdRef:bx,eventSourceRef:bq,messagesEndRef:bY,scrollContainerRef:bZ,handleSend:cO,handleAbort:cP,handleFork:cQ,handleNavigate:cR,handleModelChange:cS,handleRoleModelChange:cU,handleMainPresetChange:cT,newSessionAccount:aa,handleCompact:cV,handleSteer:cY,handleFollowUp:c$,handlePromptWithStreamingBehavior:cZ,handleAbortCompaction:c_,handleRecallQueue:c0,handleRemoveQueuedMessage:c1,handleBuiltinSlashCommand:cX,handleToolPresetChange:c7,handleThinkingLevelChange:c2,fastMode:c5,fastModeBusy:ap,handleFastModeToggle:c6,loadTools:cp,loadSlashCommands:cs,ensureNewSession:cr,refreshLiveTranscript:cn,setActiveLeafId:x,setData:r,setMessages:z,dispatch:F,setAgentRunning:H,setForkingEntryId:aB,bashRunning:I,pendingBash:K,handleAgentEventRef:bM}}({session:a,newSessionCwd:b,initialData:f,transitioning:g,onAgentEnd:af,onAttentionNeeded:i,onSessionCreated:j,onSessionForked:k,modelsRefreshKey:l,chatInputRef:m,onBranchDataChange:n,onSystemPromptChange:o,onSessionStatsPanelOpen:q}),bL=bQ(a?.id,aY?.provider,void 0);bL?.alias;let bM=(0,e.useMemo)(()=>{if(!aY)return null;let a=bg?bv:bJ.bo.find(a=>a.alias===bL?.alias)?.oauthPosition;return bJ.bo.find(b=>b.provider===aY.provider&&(void 0===b.oauthPosition||b.oauthPosition===a))?.alias??null},[aY,bg,bv,bL]);aY?.provider,aY?.modelId,bL?.alias,bL?.seed,(0,e.useRef)(bL).current=bL;let bN=an||ao;a?.id,V.current=ak,W.current=al,X.current=bl;let bO=(0,e.useRef)(!0);bO.current=!bh,(0,e.useRef)(!1),(0,e.useRef)(null),an&&bf?.kind==="running_tools"&&bf.tools.length>0&&bf.tools.every(a=>"wait"===a.name);let bR=ah||g,{hideThinkingBlock:bS}=(b??a?.cwd,bI()),bT=(0,e.useMemo)(()=>({hideThinking:bS}),[bS]),{main:bU,process:bV}=(0,e.useMemo)(()=>(function(a,b,c={}){let d=[],e=[],f=-1,g=null,h=(a,b,c)=>{if(0===b.length)return;let f=(g&&g.anchorIdx===a||(g={anchorIdx:a,entries:[],messageCount:0,toolCallCount:0},e.push(g)),g),h=d.length-1;for(let a of b)f.entries.push({...a,afterMainIndex:h});f.messageCount+=b.length,f.toolCallCount+=c},i=aB(a),j=new Map,k=(a,b)=>{let c=j.get(a)??0;j.set(a,c+1),d.push({kind:"answer",anchorIdx:f,idx:a,runIndex:c,blocks:i.attach(b),precedingBlocks:[]})},l=()=>{let a=i.takeRemaining();a&&k(a.idx,a.blocks)};for(let e of b){if("answer"===e.kind){d.push(e);continue}if("process"===e.kind){h(e.anchorIdx,e.entries,e.toolCallCount);continue}let b=a[e.idx];if(!b)continue;if("user"===b.role){l(),f=e.idx,d.push(e);continue}if(aF(b)){d.push(void 0!==e.anchorIdx||f<0?e:{...e,anchorIdx:f});continue}if("assistant"!==b.role){"toolResult"!==b.role&&h(f,[{idx:e.idx}],0);continue}let g=ay(b,c),j=!1;for(let a of g){if("answer"===a.kind){k(e.idx,a.blocks),j=!0;continue}h(f,[{idx:e.idx,blocks:a.blocks}],az(a.blocks)),i.collect(e.idx,a.blocks)}!j&&ax(b,c)&&k(e.idx,[])}return l(),{main:d,process:e}})(ak,function(a,b={}){let c=-1;for(let b=a.length-1;b>=0;b--)if(aJ(a[b])){c=b;break}let d=[];for(let e=0;e<a.length;){if(!aJ(a[e])){d.push({kind:"message",idx:e}),e+=1;continue}let f=e,g=f+1;for(;g<a.length&&!aJ(a[g]);)g+=1;if((b.sessionBusy||b.isStreaming)&&g===a.length&&f===c||!function(a,b,c){for(let d=b;d<c;d++)if(a[d]?.role==="assistant")return!0;return!1}(a,f+1,g)){for(let a=f;a<g;a++)d.push({kind:"message",idx:a});e=g;continue}for(let c of(d.push({kind:"message",idx:f}),function(a,b,c,d){let e=[],f=[],g=0,h=[],i=0,j=0,k=aB(a.slice(b+1,c)),l=()=>{0!==f.length&&(e.push({kind:"process",anchorIdx:b,idx:f[0].idx,groupIndex:j++,entries:f,messageCount:f.length,toolCallCount:g,turnHasAnswer:!1}),f=[],g=0)},m=(a,c)=>{l(),e.push({kind:"answer",anchorIdx:b,idx:a,runIndex:i++,blocks:k.attach(c),precedingBlocks:h}),h=[]};for(let i=b+1;i<c;i++){let c=a[i];if("assistant"!==c.role){if(aF(c)){l(),e.push({kind:"message",idx:i,anchorIdx:b});continue}"toolResult"!==c.role&&f.push({idx:i});continue}let j=ay(c,d),n=j.reduce((a,b)=>"answer"===b.kind?a+1:a,0);for(let a of j){if("answer"===a.kind){m(i,a.blocks);continue}for(let b of(f.push(n>0?{idx:i,blocks:a.blocks}:{idx:i}),g+=az(a.blocks),k.collect(i,a.blocks),a.blocks))h.push(b)}0===n&&ax(c,d)&&m(i,[])}l();let n=k.takeRemaining();n&&e.push({kind:"answer",anchorIdx:b,idx:n.idx,runIndex:i++,blocks:n.blocks,precedingBlocks:[]});let o=e.some(a=>"answer"===a.kind);for(let a of e)"process"===a.kind&&(a.turnHasAnswer=o);return e}(a,f,g,{hideThinking:b.hideThinking})))d.push(c);e=g}return d}(ak,{sessionBusy:bN,isStreaming:am.isStreaming,hideThinking:bT.hideThinking}),bT),[ak,bN,am.isStreaming,bT]),bW=(0,e.useMemo)(()=>(function(a,b,c=[]){let d=new Map,e=a.map((a,b)=>({item:a,position:b})).filter(a=>"answer"===a.item.kind);if(0===e.length)return d;let f=-1,g=-1;b.forEach((a,b)=>{let c=ce(a);if(c.length>0){let a=e.filter(a=>a.item.anchorIdx===f||a.item.anchorIdx===g),h=a.filter(a=>a.item.idx<=b).pop(),i=h??a.find(a=>a.item.idx>b);if(i){let a=d.get(i.position);a?a.calls.push(...c):d.set(i.position,{calls:[...c],placement:h?"after":"before"})}}"user"===a.role&&(f=b),aJ(a)&&(g=b)});let{continuing:h}=cf(a,b,c);if(h){let a=d.get(h.position);a?a.calls.unshift(...h.calls):d.set(h.position,{calls:h.calls,placement:"before"})}return d})(bU,ak,a0?.messages),[bU,ak,a0]),bX=(0,e.useMemo)(()=>(function(a,b,c=[]){let{atCompaction:d}=cf(a,b,c);if(0===d.length)return null;let e=-1;b.forEach((a,b)=>{"custom"===a.role&&"compaction"===a.customType&&(e=b)});let f=a.findIndex(a=>a.idx>e),g=-1===f?a.length:f;return{position:g,jumpTo:g<a.length?g:a.length>0?a.length-1:null,calls:d}})(bU,ak,a0?.messages),[bU,ak,a0]),[bY,bZ]=(0,e.useState)(f4),{startIndex:b$,endIndex:b_,hasLater:b0}=f5(bU.length,bY),b1=null!==bY.end&&b0,b2=(0,e.useRef)(bU.length);b2.current=bU.length;let b3=(0,e.useRef)(null),b4=(0,e.useRef)(null);(0,e.useRef)(null);let[b5,ci]=(0,e.useState)(null),[cj,ck]=(0,e.useState)(null),[cl,cm]=(0,e.useState)(0),cn=(0,e.useRef)(null),co=(0,e.useCallback)((a,b=null)=>{bj(),cn.current={item:a,dispatchKey:b},ci(null),ck(null),bZ(b=>f6(b2.current,a,b)),cm(a=>a+1)},[bj]),cp=(0,e.useCallback)(()=>{(0,E.flushSync)(()=>bZ(f4));let a=bn.current;a&&(a.scrollTop=a.scrollHeight)},[bn]),cq=(0,e.useCallback)(()=>{b1&&cp(),bi()},[b1,cp,bi]);(0,e.useRef)(null);let[cr,cs]=(0,e.useState)(!1),[ct,cu]=(0,e.useState)(!1),[cv,cw]=(0,e.useState)(0),cx=(0,e.useMemo)(()=>ct?bU.map(a=>(function(a,b){if("answer"===a.kind)return aM(a.blocks);let c=b[a.idx];return c&&"content"in c?aM(c.content):""})(a,ak).toLowerCase()):f9,[ct,bU,ak]),cy=(0,e.useCallback)(a=>{bj(),bZ(b=>f6(b2.current,a,b))},[bj]),cz=(0,e.useCallback)(()=>cu(!1),[]),cB=(0,e.useMemo)(()=>{let a=[];return bU.forEach((b,c)=>{if("message"!==b.kind)return;let d=f8(ak[b.idx]);null!==d&&a.push({item:c,text:d})}),a},[bU,ak]),cC=`${b$}:${b_}`,cD=al.length>0?al[al.length-1]:null,[cE,cF]=(0,e.useState)(null);(0,e.useRef)(!1);let cG=(0,e.useCallback)(()=>{a?.id&&cE&&function(a,b){try{window.localStorage.setItem(`omp-web:interrupted-dismissed:${a}`,b)}catch{}}(a.id,cE),cF(null)},[a?.id,cE]),cH=null!==cE&&cE===cD&&!bN&&!b1;a$&&[a$.sessionId,a$.sessionFile??"",a$.sessionName??"",a$.userMessages,a$.assistantMessages,a$.toolCalls,a$.toolResults,a$.totalMessages,a$.tokens.input,a$.tokens.output,a$.tokens.cacheRead,a$.tokens.cacheWrite,a$.tokens.total,a$.cost??0,a$.totalActiveMs??0].join("|"),(0,e.useRef)(a$).current=a$,aR&&(aR.percent,aR.contextWindow,aR.tokens),(0,e.useRef)(aR).current=aR;let{isDragOver:cI,handleDragEnter:cJ,handleDragOver:cK,handleDragLeave:cL,handleDrop:cM}=function(a){let[b,c]=(0,e.useState)(!1),d=(0,e.useRef)(0),f=(0,e.useCallback)(a=>{Array.from(a.dataTransfer.items).some(a=>"file"===a.kind)&&(a.preventDefault(),d.current+=1,c(!0))},[]),g=(0,e.useCallback)(a=>{Array.from(a.dataTransfer.items).some(a=>"file"===a.kind)&&a.preventDefault()},[]);return{isDragOver:b,handleDragEnter:f,handleDragOver:g,handleDragLeave:(0,e.useCallback)(()=>{d.current-=1,d.current<=0&&(d.current=0,c(!1))},[]),handleDrop:(0,e.useCallback)(b=>{b.preventDefault(),d.current=0,c(!1),a(Array.from(b.dataTransfer.files))},[a])}}((0,e.useCallback)(a=>{bN||m?.current?.addAttachments(a)},[bN,m])),cN=(0,e.useMemo)(()=>{var a;return a=a0?.messages,a&&a.length>0?[...a,...ak]:ak},[a0,ak]),cO=(0,e.useMemo)(()=>{let a=new Map;for(let b of cN)"toolResult"===b.role&&a.set(b.toolCallId,b);return a},[cN]),cP=(0,e.useMemo)(()=>{let a,b,c,d;return a=new Map,b=new Map,c=new Map,d=(a,d,e)=>{let f=c.get(a);f&&d&&b.set(f,{status:d,order:e})},cN.forEach((b,e)=>{if("assistant"===b.role){for(let a of b.content??[]){if("toolCall"!==a.type||"task"!==a.toolName)continue;let b=cO.get(a.toolCallId);if(b)for(let d of ca(a,b)??[])c.set(d.agentId,d.key)}return}if("toolResult"===b.role){if("routing_verdict"===b.toolName){let c=function(a){let b=function(a){if(a.isError)return null;let b=a.details?.record;if("object"!=typeof b||null===b)try{let c=JSON.parse(b9(a.content));b=c?.ok===!0?c.record:void 0}catch{return null}return"object"==typeof b&&null!==b?b:null}(a);if(!b)return null;let c=b.verdict;if("accepted"!==c&&"rework"!==c&&"held"!==c)return null;let d=b7(b.assignmentId),e=d?.split("#")??[];if(e.length<3)return null;let f=e[e.length-1],g=e.slice(1,-1).join("#");return/^\d+$/.test(f)&&g?{key:`${g}#${f}`,record:{verdict:c,attempt:"number"==typeof b.attempt?b.attempt:null,reason:b7(b.reason)}}:null}(b);if(!c)return;let d=a.get(c.key)??[];d.push({...c.record,order:e}),a.set(c.key,d);return}if("wait"===b.toolName)for(let a of b6(b.details?.jobs)){if("task"!==a.type)continue;let b=b7(a.id);b&&d(b,b8(a.status),e)}return}if("custom"===b.role&&"async-result"===b.customType)for(let a of b9(b.content).matchAll(cb)){let b=Object.fromEntries([...a[1].matchAll(cc)].map(a=>[a[1],a[2]]));b.id&&d(b.id,b8(b.status),e)}}),{verdicts:a,runs:b,latestByAgent:c}},[cN,cO]),cQ=(0,e.useMemo)(()=>({ledger:cP,subagents:a4,toolResults:cO,onOpenPanel:u,focusedDispatch:cj}),[cP,a4,cO,u,cj]),cR=(0,e.useMemo)(()=>(function(a,b,c,d,e,f,g=null){let h=-1;a.forEach((a,b)=>{"user"===a.role&&(h=b)});let i=new Map;for(let[a,b]of c)for(let c of b.calls)i.set(c.toolCallId,a);if(g?.jumpTo!=null)for(let a of g.calls)i.set(a.toolCallId,g.jumpTo);let j=[];if(a.forEach((a,c)=>{if("assistant"!==a.role)return;let g=c>h;for(let c of a.content??[])if("toolCall"===c.type&&"task"===c.toolName)for(let a of ca(c,b.get(c.toolCallId))??[]){let b=cd(a,d,e),h=cg[b.run],k=null;"running"===h&&("live"===b.runSource||g&&f)?k="running":"awaiting"===h&&g&&!b.verdict&&(k="awaiting"),k&&j.push({maker:b,phase:k,position:i.get(c.toolCallId)??null})}}),0===j.length)return null;let k=0;for(let a of j)"running"===a.phase&&(k+=1);let l=j.filter(a=>null!==a.position);return{running:k,awaiting:j.length-k,target:l.length>0?l[l.length-1]:j[j.length-1]}})(cN,cO,bW,a4,cP,bN,bX),[cN,cO,bW,a4,cP,bN,bX]),cS=(0,e.useMemo)(()=>u?()=>u("subagents"):void 0,[u]),cT=(0,e.useMemo)(()=>{let a=new Set,b=[];for(let c=ak.length-1;c>=0;c-=1){let d=f8(ak[c]);if(!(!d||a.has(d))&&(a.add(d),b.push(d),b.length>=50))break}return b.reverse()},[ak]),cU=(0,e.useMemo)(()=>(function(a,b,c=null,d=null){return c||(function(a,b){for(let c=a.length-1;c>=0;c-=1){let d=a[c];if("assistant"!==d.role)continue;let e=d.content;if(Array.isArray(e))for(let a=e.length-1;a>=0;a-=1){let c=e[a];if("toolCall"!==c.type||!function(a){if(!a)return!1;let b=a.toLowerCase();return"todo"===b||b.endsWith(".todo")||b.endsWith("_todo")}(c.toolName))continue;let d=aS(c,b.get(c.toolCallId));if("unknown"!==d.kind)return d.phases}}return null}(a,b)??d)})(ak,cO,a5,a0?.todoPhases??null),[ak,cO,a5,a0]),cV=(0,e.useMemo)(()=>dV(am.streamingMessage).join("|"),[am.streamingMessage]),cW=(0,e.useMemo)(()=>JSON.stringify(dU(am.streamingMessage)),[am.streamingMessage]),cY=(0,e.useMemo)(()=>JSON.stringify(dX(am.streamingMessage)),[am.streamingMessage]),cZ=(0,e.useMemo)(()=>(function(a,b,c=[],d=[],e=[]){let f=function(a){let b=new Map;for(let c of a){if("toolResult"!==c.role||"write"!==c.toolName)continue;let a=c.details;if(!a||"object"!=typeof a||Array.isArray(a))continue;let d=a.message;if(!d||"object"!=typeof d||Array.isArray(d)||"send"!==d.op)continue;let e=Array.isArray(d.receipts)?d.receipts.filter(a=>"object"==typeof a&&null!==a&&!Array.isArray(a)).map(a=>({to:"string"==typeof a.to?a.to:void 0,outcome:"string"==typeof a.outcome?a.outcome:void 0})):void 0;b.set(c.toolCallId,{from:"string"==typeof d.from?d.from:void 0,receipts:e})}return b}(a),g=[],h=new Map,i=-1;for(let c=0;c<a.length;c+=1){let d=a[c];if("user"===d.role){i=c;continue}let e=dV(d),j=dX(d,f);if(0===e.length&&0===j.length||i<0)continue;let k=dU(d),l=h.get(i);l||(l={index:i,entryId:b[i],taskToolCallIds:[],characterSummons:[],peerSends:[]},h.set(i,l),g.push(l)),l.taskToolCallIds=[...l.taskToolCallIds,...e],l.characterSummons=[...l.characterSummons,...k],l.peerSends=[...l.peerSends,...j]}if(c.length>0||e.length>0){let f=-1;for(let b=a.length-1;b>=0;b-=1)if("user"===a[b].role){f=b;break}if(f>=0){let a=h.get(f);a||(a={index:f,entryId:b[f],taskToolCallIds:[],characterSummons:[],peerSends:[]},h.set(f,a),g.push(a));let i=new Set(a.taskToolCallIds);a.taskToolCallIds=[...a.taskToolCallIds,...c.filter(a=>!i.has(a))];let j=new Set(a.characterSummons.map(a=>`${a.toolCallId} ${a.name??""}`));a.characterSummons=[...a.characterSummons,...d.filter(a=>!j.has(`${a.toolCallId} ${a.name??""}`))];let k=new Set(a.peerSends.map(a=>a.toolCallId));a.peerSends=[...a.peerSends,...e.filter(a=>!k.has(a.toolCallId))]}}return g.sort((a,b)=>a.index-b.index)})(ak,al,cV.length>0?cV.split("|"):[],JSON.parse(cW),JSON.parse(cY)),[ak,al,cV,cW,cY]),c$=a?.id??bl.current??void 0,c_=(M=d$(L=(0,e.useMemo)(()=>({sessionId:c$,sessionProvider:aY?.provider,turns:cZ,messages:ak,subagents:a4}),[c$,aY?.provider,cZ,ak,a4])),O=d2(L),(0,e.useMemo)(()=>(function(a){let b=new Map;for(let c of a){let a=b.get(c.turnIndex);a?a.push(c):b.set(c.turnIndex,[c])}return b})(function(a){let b=[];for(let c of a){let a=b[b.length-1];if(a&&a.speakerId===c.speakerId&&a.turnIndex===c.turnIndex&&a.text===c.text){b[b.length-1]=c;continue}b.push(c)}return b}([...M,...O])),[M,O])),c0=bg&&0===ak.length&&!am.isStreaming&&!bN,c1=a?.cwd??b??void 0,c2=aY?au[`${aY.provider}:${aY.modelId}`]??null:null,c3=aY?aw[`${aY.provider}:${aY.modelId}`]??null:null,c4=(0,e.useRef)(null),c5=(0,e.useRef)(null);(0,e.useCallback)(()=>{c4.current?.querySelector("textarea")?.focus({preventScroll:!0})},[]);let c6=(0,e.useCallback)((...a)=>(null!==bY.end&&cp(),bo(...a)),[bo,bY.end,cp]),c7=(0,d.jsx)("div",{ref:c4,"data-chat-composer":"",style:{display:"contents"},children:(0,d.jsx)(fC,{ref:m,sessionId:a?.id??bl.current??void 0,onEnsureSession:bg&&b?bH:void 0,onLiveTranscriptPersisted:bK,onSend:c6,onAbort:bp,onSteer:an?bx:void 0,onFollowUp:an?by:void 0,onPromptWithStreamingBehavior:an?bz:void 0,isStreaming:bN,model:aY,isAutoModelSelection:be,modelNames:aq,modelList:ar,modelError:as,modelScopeWarnings:at,onModelChange:bs,onMainPresetChange:a||bg?bu:void 0,mainPresetActiveAlias:bM,modelRoles:aA,onRoleModelChange:bt,modelSwitching:aZ,onCompact:a||bg?bw:void 0,onAbortCompaction:bA,isCompacting:aU,compactError:aW,compactResult:aX,toolPreset:aC,onToolPresetChange:a||bg?bE:void 0,thinkingLevel:aE,effectiveThinkingLevel:aK,thinkingCeiling:aL,onThinkingLevelChange:a||bg?bF:void 0,fastMode:aN,fastModeBusy:aO,onFastModeToggle:a||bg?aP:void 0,availableThinkingLevels:c2,thinkingLevelMap:c3,retryInfo:aQ,deliveryRows:a3,inputHistory:cT,onRecallQueue:bB,onRemoveQueuedMessage:bC,slashCommands:a1,slashCommandsLoading:a2,onLoadSlashCommands:bG,onBuiltinCommand:bD,soundEnabled:D,onSoundToggle:F,onAudioUnlock:I,draftKey:a?.id??(b?`new:${b}`:void 0),cwd:a?.cwd??b})}),c8=am.streamingMessage,c9=(0,e.useMemo)(()=>c8?ay(c8,{isStreaming:!0}):[],[c8]),da=(0,e.useMemo)(()=>c9.filter(a=>"answer"===a.kind).flatMap(a=>a.blocks),[c9]);(0,e.useMemo)(()=>c9.filter(a=>"answer"!==a.kind).map(a=>a.blocks),[c9]);let db=c8?.role==="assistant"?c8:null;an&&(bf?.kind==="running_tools"||(db?.content??[]).some(a=>"text"===a.type&&/\S/.test(a.text)||"toolCall"===a.type)),db?.provider??aY?.provider,db?.credentialId;let[dc,dd]=(0,e.useState)(null),de=(0,e.useCallback)(a=>{dd(a)},[]);(0,e.useMemo)(()=>ap?{role:"bashExecution",command:ap.command,output:"",excludeFromContext:ap.excludeFromContext}:null,[ap]),(0,e.useMemo)(()=>{let a=[an&&!c8&&bf?function(a,b){if(a?.kind==="running_tools"){let c=a.tools.map(a=>a.name);return 0===c.length?b("chat.runningTool"):1===c.length?b("chat.runningNamedTool",{name:c[0]}):c.length<=3?b("chat.runningTools",{names:c.join(", ")}):b("chat.runningToolsMore",{names:c.slice(0,2).join(", "),count:c.length-2})}return a?.kind==="waiting_model"?b("chat.waitingModel"):a?.kind==="running_command"?b("chat.runningCommand"):null}(bf,P):null,ao&&!ap?P("chat.runningCommand"):null].filter(a=>!!a);return a.length>0?a.join(" \xb7 "):null},[an,c8,bf,ao,ap,P]);let df=bb.filter(a=>"belowEditor"!==a.placement),dg=bb.filter(a=>"belowEditor"===a.placement);return ai?(0,d.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ai}):(0,d.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":bR,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:cJ,onDragOver:cK,onDragLeave:cL,onDrop:cM,children:[bR?(0,d.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,d.jsx)("div",{className:"absolute right-3 top-3 border border-border bg-bg-panel px-3 py-2 text-sm text-text-muted shadow-sm",role:"status",children:P("chat.loadingSession")})}):null,cI&&!bN&&(0,d.jsx)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center",style:{background:"var(--accent-soft)",border:"2px dashed var(--accent-line)"},children:(0,d.jsx)("span",{className:"px-3 py-1 text-sm font-medium",style:{background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)"},children:P("chat.attachFile")})}),a9&&(0,d.jsx)(gh,{request:a9,onInput:bd}),c0&&!y?(0,d.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,d.jsxs)("div",{className:"my-auto w-full max-w-[820px] py-8",children:[(0,d.jsxs)("div",{className:"mb-3",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginLeft:16,marginRight:52,fontFamily:"var(--font-mono)"},children:[(0,d.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,d.jsx)(N,{})}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,d.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,d.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.10.2"]})]}),(0,d.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,d.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.8.6"]})]})]})]}),(0,d.jsx)(ge,{notices:a6,align:"right"})]})}):(0,d.jsxs)(d.Fragment,{children:[y&&(0,d.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:y}),(0,d.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!y,style:{display:y?"none":"flex"},children:[(0,d.jsx)("div",{style:{position:"absolute",top:12,left:0,right:0,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,d.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,d.jsx)(ds,{open:ct,onClose:cz,containerRef:bn,index:cx,renderedStart:b$,renderedEnd:b_,contentKey:ak,onReveal:cy,onProgrammaticScroll:bj,focusRequest:cv,t:P}),cr&&(0,d.jsx)("div",{className:"chat-jump-missing",role:"status",children:P("chat.jumpMissing")}),(0,d.jsx)(ge,{notices:a6,floating:!0,align:"right"})]})}),(0,d.jsx)("div",{ref:bn,className:"chat-session-scroll min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",children:(0,d.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,d.jsxs)("div",{className:"chat-column-cap",style:{width:"100%",minWidth:0,maxWidth:820,margin:"0 auto"},children:[(0,d.jsx)(gd,{widgets:df}),(0,d.jsx)(ch.Provider,{value:cQ,children:(0,d.jsx)(dP,{utterances:c_,children:(0,d.jsx)(ga,{messages:ak,entryIds:al,toolResultsMap:cO,modelNames:aq,messageCwd:c1,onOpenFile:w,sessionBusy:bN,isNew:bg,isStreaming:am.isStreaming,handleFork:bq,forkingEntryId:aT,handleNavigate:br,handleEditContent:ag,sessionId:a?.id??bl.current??void 0,main:bU,dispatchSlots:bW,compactedDispatch:bX,process:bV,startIndex:b$,endIndex:b_,sentinelRef:b3,laterSentinelRef:b4,flashItem:b5,t:P,cues:S,cueFollowRef:bO,onProcessLogChange:de})})}),!b1&&am.isStreaming&&am.streamingMessage&&da.length>0&&(0,d.jsx)(cX,{message:av(am.streamingMessage,da),sessionId:a?.id??bl.current??void 0,isStreaming:!0,modelNames:aq,cwd:c1,onOpenFile:w}),cH&&(0,d.jsx)(dy,{onDismiss:cG,t:P}),(0,d.jsx)("div",{ref:bm})]})})}),(0,d.jsx)(dt,{questions:cB,containerRef:bn,layoutKey:cC,onJump:co,label:P("chat.questionRail")}),(bN&&bh||b1)&&(0,d.jsxs)("button",{type:"button",onClick:cq,"aria-label":P("chat.jumpToBottom"),title:P("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:999,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",cursor:"pointer",boxShadow:"0 2px 10px rgba(0,0,0,0.28)"},children:[(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M12 5v14"}),(0,d.jsx)("path",{d:"m19 12-7 7-7-7"})]}),P("chat.jumpToBottom")]})]})]}),(0,d.jsxs)("div",{ref:c5,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[a7&&(0,d.jsx)("div",{style:{padding:"0 16px"},children:(0,d.jsx)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:(0,d.jsx)(gg,{request:a7,onRespond:bc,onActivity:a=>void bd(a,"activity"),delivery:a8})})}),(0,d.jsx)("div",{className:"min-h-0 overflow-y-auto",style:{padding:"0 16px"},children:(0,d.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:[(0,d.jsx)(dx,{compaction:aV,t:P}),(0,d.jsx)(gc,{goal:bk,t:P}),(0,d.jsx)(dq,{summary:cR,onJump:co,onOpenPanel:cS}),(0,d.jsx)(gd,{widgets:dg}),cU&&(0,d.jsx)(fE,{phases:cU})]})}),c7,(0,d.jsx)(fD,{statuses:ba})]})]})}function gc({goal:a,t:b}){if(!a)return null;let c=!a.enabled,e=void 0!==a.tokenBudget?b("chat.goalBudgetLeft",{left:bz(Math.max(0,a.tokenBudget-a.tokensUsed))}):b("chat.goalTokensUsed",{used:bz(a.tokensUsed)});return(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"5px 10px",border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",opacity:c?.7:1},children:[(0,d.jsx)("span",{style:{color:c?"var(--text-dim)":"var(--accent)",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",flexShrink:0},children:b("chat.goalLabel")}),(0,d.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:a.objective}),(0,d.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:c?b("chat.goalPaused"):a.status}),(0,d.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:e})]})}function gd({widgets:a}){return 0===a.length?null:(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:a.map(a=>(0,d.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,d.jsx)("div",{style:{padding:"5px 9px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:a.key}),(0,d.jsx)("pre",{style:{margin:0,padding:"8px 9px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)"},children:a.lines.join("\n")})]},a.key))})}function ge({notices:a,floating:b=!1,align:c="left"}){return 0===a.length?null:(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===c?"flex-end":"stretch",marginBottom:10*!b},children:a.map((c,e)=>{let f="error"===c.type?"var(--danger)":"warning"===c.type?"var(--warning)":"success"===c.type?"var(--success)":"var(--accent)";return(0,d.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:60,height:60,maxHeight:60,marginBottom:6*(e!==a.length-1),overflow:"hidden",borderRadius:"var(--seed-radius-r3)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:b?"var(--seed-shadow-s3)":"var(--seed-shadow-s2)",fontSize:18,lineHeight:1.45,transformOrigin:"top center",animation:c.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,d.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:f,flexShrink:0}}),(0,d.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.message})]},c.id)})})}function gf({focusKey:a,label:b,labelledBy:c,maxBlockSize:f="min(56dvh, 620px)",onCancel:g,delivery:h,children:i}){let{t:j}=(0,x.s)(),k=(0,e.useRef)(null),l=(0,e.useRef)({key:"",element:null});if(l.current.key!==a){let b="u"<typeof document?null:document.activeElement;l.current={key:a,element:b instanceof HTMLElement&&!k.current?.contains(b)?b:null}}return(0,d.jsxs)("div",{ref:k,role:"dialog","aria-modal":"false","aria-label":b,"aria-labelledby":c,className:"chat-response-surface",tabIndex:-1,onKeyDown:g?a=>{"Escape"===a.key&&(a.stopPropagation(),g())}:void 0,"aria-busy":h?.status==="sending"||void 0,style:{maxBlockSize:f},children:[h?(0,d.jsx)("p",{className:"chat-response-delivery",role:"failed"===h.status?"alert":"status","data-state":h.status,children:"sending"===h.status?j("chat.responseSending"):`${j("chat.responseFailed")}${h.error?` (${h.error})`:""}`}):null,i]})}function gg({request:a,onRespond:b,onActivity:c,delivery:f}){let{t:g}=(0,x.s)(),[h,i]=(0,e.useState)("editor"===a.method?a.prefill??"":""),[j,k]=(0,e.useState)({}),[l,m]=(0,e.useState)({}),[n,o]=(0,e.useState)(""),p=(0,e.useRef)(0),q=(0,e.useCallback)(()=>{if("ask"!==a.method||!a.timeout||!c)return;let b=Date.now();b-p.current<1e3||(p.current=b,c(a))},[a,c]),r=()=>{"confirm"===a.method?b(a,{confirmed:!0}):b(a,{value:h})};if("ask"===a.method){let c=a.questions.every(a=>(j[a.id]?.length??0)>0||(l[a.id]?.trim().length??0)>0),e=()=>{c&&b(a,{value:JSON.stringify({kind:"submit",results:a.questions.map(a=>{let b=l[a.id]?.trim();return{id:a.id,question:a.question,options:a.options.map(a=>a.label),multi:a.multi??!1,selectedOptions:(j[a.id]??[]).map(b=>a.options[b]?.label).filter(a=>void 0!==a),...b?{customInput:b}:{}}})})})};return(0,d.jsx)(gf,{focusKey:a.id,label:g("chat.agentQuestion"),onCancel:()=>b(a,{cancelled:!0}),delivery:f,children:(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,d.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:g("chat.agentQuestion")}),(0,d.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:g("chat.agentQuestionHint")}),a.timeout?(0,d.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:g("chat.askAutoSelectHint",{seconds:Math.round(a.timeout/1e3)})}):null]})}),(0,d.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,d.jsx)("div",{style:{display:"grid",gap:20},children:a.questions.map((b,c)=>{let f=j[b.id]??[];return(0,d.jsxs)("section",{style:{paddingTop:20*(0!==c),borderTop:0===c?"none":"1px solid var(--hairline)"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[b.header&&(0,d.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:b.header}),a.questions.length>1&&(0,d.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[c+1,"/",a.questions.length]})]}),(0,d.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:b.question}),(0,d.jsx)("div",{role:b.multi?"group":"radiogroup","aria-label":b.question,style:{display:"grid",gap:4},children:b.options.map((a,c)=>{let e=f.includes(c),h=b.recommended===c;return(0,d.jsxs)("button",{type:"button",role:b.multi?"checkbox":"radio","aria-checked":e,onClick:()=>{var a,d;return a=b.id,d=b.multi??!1,void(q(),k(b=>{let e=b[a]??[],f=d?e.includes(c)?e.filter(a=>a!==c):[...e,c]:[c];return{...b,[a]:f}}))},style:{display:"grid",gridTemplateColumns:"18px minmax(0, 1fr) auto",alignItems:"start",gap:9,width:"100%",minHeight:40,padding:"9px 10px",border:`1px solid ${e?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:e?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,d.jsx)("span",{"aria-hidden":"true",style:{display:"grid",placeItems:"center",width:16,height:16,marginTop:1,border:`1px solid ${e?"var(--text)":"var(--text-dim)"}`,borderRadius:b.multi?"var(--radius-control)":"50%",background:e?"var(--seed-color-fg-neutral)":"transparent",color:"var(--seed-color-fg-neutral-inverted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1},children:e&&(b.multi?(0,d.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("polyline",{points:"2 5.2 4.1 7.2 8 2.8"})}):(0,d.jsx)("span",{style:{width:5,height:5,borderRadius:"50%",background:"currentColor"}}))}),(0,d.jsxs)("span",{style:{minWidth:0},children:[(0,d.jsx)("span",{style:{display:"block",fontSize:"var(--seed-font-size-t4-static)",fontWeight:e?600:500},children:a.label}),a.description&&(0,d.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.45},children:a.description}),e&&a.preview&&(0,d.jsx)("span",{style:{display:"block",marginTop:8,padding:"7px 8px",borderLeft:"2px solid var(--border-strong)",background:"var(--bg-subtle)",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,whiteSpace:"pre-wrap"},children:a.preview})]}),h&&(0,d.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:g("chat.recommended")})]},`${b.id}:${c}`)})}),(0,d.jsx)("input",{value:l[b.id]??"",onChange:a=>{q(),m(c=>({...c,[b.id]:a.target.value}))},onKeyDown:a=>{(a.metaKey||a.ctrlKey)&&"Enter"===a.key&&e()},placeholder:g("chat.customAnswer"),"aria-label":g("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"}})]},b.id)})})}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,d.jsx)("button",{type:"button",onClick:()=>b(a,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:g("chat.cancel")}),(0,d.jsx)("button",{type:"button",onClick:()=>b(a,{value:JSON.stringify({kind:"chat"})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:g("chat.chatAboutThis")}),(0,d.jsx)("button",{type:"button",disabled:!c||f?.status==="sending",onClick:e,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:c&&f?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:c&&f?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:c&&f?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:f?.status==="sending"?g("chat.responseSending"):g("chat.submitAnswer")})]})]})})}return"plan_review"===a.method?(0,d.jsx)(gf,{focusKey:a.id,labelledBy:`plan-review-${a.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:f,children:(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,d.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,d.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:g("chat.planApproval")}),(0,d.jsx)("div",{id:`plan-review-${a.id}`,style:{marginTop:4,color:"var(--text)",fontSize:"var(--seed-font-size-t5-static)",fontWeight:600},children:a.title}),(0,d.jsx)("div",{style:{marginTop:5,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)",overflowWrap:"anywhere"},children:a.planFilePath})]}),(0,d.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,d.jsx)(bw,{children:a.planContent})}),(0,d.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,d.jsx)("textarea",{value:n,onChange:a=>o(a.target.value),placeholder:g("chat.planFeedback"),"aria-label":g("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",resize:"vertical",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5}}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,d.jsx)("button",{type:"button",onClick:()=>b(a,{value:JSON.stringify({action:"refine",feedback:n.trim()})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:g("chat.refinePlan")}),(0,d.jsx)("button",{type:"button",onClick:()=>b(a,{value:JSON.stringify({action:"approve"})}),style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:g("chat.approvePlan")})]})]})]})}):(0,d.jsx)(gf,{focusKey:a.id,labelledBy:`extension-request-${a.id}`,onCancel:()=>b(a,{cancelled:!0}),delivery:f,children:(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,d.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,d.jsx)("div",{id:`extension-request-${a.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:a.title}),(0,d.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:g("chat.extensionRequest")})]}),(0,d.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===a.method&&(0,d.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,whiteSpace:"pre-wrap"},children:a.message}),"select"===a.method&&(0,d.jsx)("div",{style:{display:"grid",gap:8},children:a.options.map(c=>(0,d.jsx)("button",{onClick:()=>b(a,{value:c}),style:{width:"100%",minHeight:40,padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t4-static)"},children:c},c))}),"input"===a.method&&(0,d.jsx)("input",{autoFocus:!0,value:h,placeholder:a.placeholder,onChange:a=>i(a.target.value),onKeyDown:a=>{"Enter"===a.key&&r()},style:{width:"100%",padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",fontSize:"var(--seed-font-size-t4-static)"}}),"editor"===a.method&&(0,d.jsx)("textarea",{autoFocus:!0,value:h,onChange:a=>i(a.target.value),onKeyDown:a=>{(a.metaKey||a.ctrlKey)&&"Enter"===a.key&&r()},style:{width:"100%",minHeight:220,padding:10,borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,d.jsx)("button",{onClick:()=>b(a,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:g("chat.cancel")}),"confirm"===a.method?(0,d.jsx)("button",{onClick:r,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:g("chat.confirm")}):"select"!==a.method?(0,d.jsx)("button",{onClick:r,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:g("chat.submit")}):null]})]})})}function gh({request:a,onInput:b}){let{t:c}=(0,x.s)(),f=(0,e.useRef)(null),g=(0,e.useRef)(!1),h=an(a.lines);return(0,d.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"var(--seed-color-bg-overlay-muted)"},children:(0,d.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:a=>{a.target.closest("button")||f.current?.focus()},style:{position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",outline:"none"},children:[(0,d.jsx)("textarea",{ref:f,"aria-label":c("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:c=>{if(g.current||c.nativeEvent.isComposing)return;let d=function(a){if(a.metaKey||a.ctrlKey&&!a.altKey&&"v"===a.key.toLowerCase())return null;if(a.ctrlKey&&!a.altKey){let b=function(a){if(1!==a.length)return null;let b=a.toUpperCase().charCodeAt(0);return b>=64&&b<=95?String.fromCharCode(31&b):"?"===a?"":null}(a.key);if(b)return b}if(a.altKey&&!a.ctrlKey){if("Backspace"===a.key)return"\x1b\x7f";let b=aq[a.key];if(b)return b;if(1===a.key.length)return`\x1b${a.key}`}return"Enter"===a.key?a.shiftKey?"\n":"\r":"Tab"===a.key?a.shiftKey?"\x1b[Z":" ":ap[a.key]??null}(c);d&&(c.preventDefault(),c.stopPropagation(),b(a,d))},onInput:c=>{if(g.current||c.nativeEvent.isComposing)return;let d=c.currentTarget.value;c.currentTarget.value="",d&&b(a,d)},onCompositionStart:()=>{g.current=!0},onCompositionEnd:c=>{g.current=!1;let d=c.currentTarget;queueMicrotask(()=>{let c=d.value;d.value="",c&&b(a,c)})},onPaste:c=>{c.preventDefault();let d=c.clipboardData.getData("text");d&&b(a,`\x1b[200~${d}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,d.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:c("chat.extensionPanel")}),(0,d.jsx)("button",{onClick:()=>b(a,"\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:c("chat.close")})]}),(0,d.jsx)("pre",{style:{margin:0,padding:14,maxHeight:"calc(min(760px, 100vh - 40px) - 48px)",overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(h.length?h:[""]).map((a,b,c)=>{var f;return(0,d.jsxs)(e.Fragment,{children:[(f=`line-${b}`,ao(a).map((a,b)=>Object.keys(a.style).length>0?(0,d.jsx)("span",{style:a.style,children:a.text},`${f}-${b}`):a.text)),b<c.length-1?"\n":null]},b)})})]})})}function gi({onPick:a,t:b}){let[c,f]=(0,e.useState)(""),[g,h]=(0,e.useState)({kind:"idle"}),i=(0,e.useRef)(null),j=c.trim(),k=a=>{let b=i.current?.querySelectorAll("button");b&&0!==b.length&&b[Math.max(0,Math.min(b.length-1,a))]?.focus()},l="done"===g.kind?g.data:null,m=l?.truncated?b(`palette.searchTruncated.${l.truncated}`,{scanned:l.scannedSessions,total:l.totalSessions}):null;return(0,d.jsxs)("div",{className:"palette-search",children:[(0,d.jsx)("input",{type:"search",value:c,onChange:a=>f(a.target.value),onKeyDown:b=>{if(!b.nativeEvent.isComposing){if("ArrowDown"===b.key)b.preventDefault(),k(0);else if("Enter"===b.key&&l&&l.hits.length>0){b.preventDefault();let c=l.hits[0],d=l.sessions[c.sessionId];d&&a(d,c,l.query)}}},placeholder:b("palette.searchPlaceholder"),"aria-label":b("palette.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),j.length>=2&&(0,d.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":b("palette.searchResults"),"aria-busy":"loading"===g.kind,children:[(0,d.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===g.kind&&b("palette.searching"),"error"===g.kind&&b("palette.searchFailed"),l&&(0===l.hits.length?b("palette.searchEmpty"):b("palette.searchHits",{count:l.hits.length})),m?` \xb7 ${m}`:"",l&&l.compactedHits>0?` \xb7 ${b("palette.searchCompacted",{count:l.compactedHits})}`:""]}),l&&l.hits.length>0&&(0,d.jsx)("div",{ref:i,className:"palette-search-list",children:l.hits.map((c,e)=>{let f=l.sessions[c.sessionId],g=c.matchStart+l.query.length;return(0,d.jsxs)("button",{type:"button",disabled:!f,onClick:()=>f&&a(f,c,l.query),onKeyDown:a=>{("ArrowDown"===a.key||"ArrowUp"===a.key)&&(a.preventDefault(),k(e+("ArrowDown"===a.key?1:-1)))},children:[(0,d.jsxs)("span",{className:"palette-search-title",children:[(0,d.jsx)("span",{children:f?f.name?.trim()||f.firstMessage?.trim()||f.id:""}),(0,d.jsx)("small",{children:"user"===c.role?b("palette.searchRoleUser"):b("palette.searchRoleAssistant")})]}),(0,d.jsxs)("span",{className:"palette-search-snippet",children:[c.snippet.slice(0,c.matchStart),(0,d.jsx)("mark",{children:c.snippet.slice(c.matchStart,g)}),c.snippet.slice(g)]})]},`${c.sessionId}:${c.entryId}`)})})]})]})}var gj=c(86475),gk=c(49216);let gl=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function gm(a){return function a(b,c){if(null==b)return"";if("string"==typeof b)return b;if("number"==typeof b||"boolean"==typeof b)return String(b);if(Array.isArray(b)){if(c.has(b))return"[Circular]";c.add(b);try{return b.map(b=>a(b,c)).filter(Boolean).join(", ")}finally{c.delete(b)}}if("object"==typeof b)try{return JSON.stringify(b)??Object.prototype.toString.call(b)}catch{return Object.prototype.toString.call(b)}return String(b)}(a,new WeakSet)}let gn=["tags","categories","keywords","tag","category"];function go({data:a}){var b;if(!a)return null;let c=Object.entries(a);if(0===c.length)return null;let e="string"==typeof(b=a.title)?b.trim()||null:"number"==typeof b||"boolean"==typeof b?String(b):null,f=gn.find(b=>Array.isArray(a[b])),g=f?a[f].map(gm).filter(Boolean):[],h=c.filter(([a])=>a!==f&&("title"!==a||!e));return(0,d.jsxs)("div",{className:"markdown-frontmatter",children:[e&&(0,d.jsx)("div",{className:"markdown-frontmatter-title",children:e}),g.length>0&&(0,d.jsx)("div",{className:"markdown-frontmatter-tags",children:g.map((a,b)=>(0,d.jsx)("span",{className:"markdown-frontmatter-tag",children:a},`${a}-${b}`))}),h.length>0&&(0,d.jsx)("dl",{className:"markdown-frontmatter-rows",children:h.map(([a,b])=>(0,d.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,d.jsx)("dt",{children:a}),(0,d.jsx)("dd",{children:function(a){let b=gm(a);return b?"string"==typeof a&&/^(https?:\/\/|mailto:)/i.test(a)?(0,d.jsx)("a",{href:a,target:"_blank",rel:"noopener noreferrer",children:b}):b:null}(b)})]},a))})]})}let gp={source:"Source",preview:"Preview",diff:"Diff"},gq={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},gr={width:48,minWidth:48,padding:"0 10px",textAlign:"right",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:11,fontStyle:"normal",fontVariantNumeric:"tabular-nums",lineHeight:"20.8px",userSelect:"none",flexShrink:0,verticalAlign:"top"};function gs(){return(0,d.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,d.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,d.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function gt({rows:a,stylesheet:b,useInlineStyles:c,wrapLines:e}){return a.map((a,f)=>{let g=a.children??[],h=g[0]?.properties?.className,i=Array.isArray(h)&&h.includes("react-syntax-highlighter-line-number"),j=i?g[0]:null,k=i?g.slice(1):g;return(0,d.jsxs)("span",{className:"file-source-line","data-line-number":f+1,style:{display:"flex",minWidth:"100%"},children:[j&&(0,gj.Ay)({node:j,stylesheet:b,useInlineStyles:c,key:`source-line-number-${f}`}),(0,d.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:e?"anywhere":"normal",whiteSpace:e?"pre-wrap":"pre"},children:k.map((a,d)=>(0,gj.Ay)({node:a,stylesheet:b,useInlineStyles:c,key:`source-token-${f}-${d}`}))})]},`source-line-${f}`)})}function gu(a,b,c,d={}){let e=aX(a),f=new URLSearchParams({type:b});for(let[a,b]of(c&&f.set("sessionId",c),Object.entries(d)))void 0!==b&&f.set(a,String(b));return`/api/files/${e}?${f.toString()}`}function gv({filePath:a,sourceSessionId:b}){let{t:c}=(0,x.s)();return(0,d.jsx)("a",{href:gu(a,"download",b),download:aY(a),title:c("i18n.downloadFile"),"aria-label":c("i18n.downloadFile"),className:"file-viewer-icon-button",children:(0,d.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,d.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,d.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,d.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})}function gw(a){return a<1024?`${a} B`:a<1048576?`${(a/1024).toFixed(1)} KB`:`${(a/1048576).toFixed(1)} MB`}function gx({patch:a}){let b,{t:c}=(0,x.s)(),e=(b=bW(a))?b.flatMap(a=>a.rows.flatMap(a=>{if("hunk"===a.type)return[];if("context"===a.left.type&&"context"===a.right.type)return[{type:"unchanged",text:a.right.text,oldLineNo:a.left.lineNo,newLineNo:a.right.lineNo}];let b=[];return"removed"===a.left.type&&b.push({type:"removed",text:a.left.text,oldLineNo:a.left.lineNo,newLineNo:null}),"added"===a.right.type&&b.push({type:"added",text:a.right.text,oldLineNo:null,newLineNo:a.right.lineNo}),b})):[];if(!e.some(a=>"unchanged"!==a.type))return(0,d.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:c("i18n.noChanges")});let f=new Set(e.flatMap((a,b)=>"unchanged"!==a.type?[b]:[])),g=new Set;for(let a of f)for(let b=Math.max(0,a-3);b<=Math.min(e.length-1,a+3);b++)g.add(b);let h=[],i=0;for(;i<e.length;)if(g.has(i)){let a=[];for(;i<e.length&&g.has(i);)a.push(e[i]),i++;h.push({hidden:!1,lines:a})}else{let a=0;for(;i<e.length&&!g.has(i);)a++,i++;h.push({hidden:!0,count:a})}return(0,d.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...gq},children:h.map((a,b)=>{if(a.hidden)return(0,d.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:["... ",a.count," unchanged lines ..."]},b);let c=a.lines.map((a,b)=>{let c="added"===a.type?"rgba(0,200,80,0.12)":"removed"===a.type?"rgba(240,60,60,0.14)":"transparent",e="added"===a.type?"+":"removed"===a.type?"-":" ",f="added"===a.type?"#4ade80":"removed"===a.type?"#f87171":"var(--text-dim)";return(0,d.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:c,borderLeft:"added"===a.type?"3px solid #4ade80":"removed"===a.type?"3px solid #f87171":"3px solid transparent"},children:[(0,d.jsx)("span",{style:gr,children:"removed"===a.type?a.oldLineNo:a.newLineNo}),(0,d.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:f,userSelect:"none",flexShrink:0,fontWeight:600},children:e}),(0,d.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:a.text||"\xa0"})]},b)});return(0,d.jsx)("div",{children:c},b)})})}function gy({filePath:a,cwd:b,sourceSessionId:c}){let{t:f}=(0,x.s)(),[g,h]=(0,e.useState)(!1),[i,j]=(0,e.useState)(0),[k,l]=(0,e.useState)(null),[m,n]=(0,e.useState)(null),[o,p]=(0,e.useState)(null);(0,e.useRef)(null);let q=aY(a).toLowerCase().split(".").pop()??"",r=gu(a,"read",c,i?{v:i}:void 0),s=null!=k?gw(k):null;return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,d.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,d.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:a,children:aZ(a,b)}),(0,d.jsx)("span",{style:{marginLeft:"auto"},children:q||"image"}),m&&(0,d.jsxs)("span",{children:[m.w," \xd7 ",m.h]}),s&&(0,d.jsx)("span",{children:s}),(0,d.jsxs)("span",{title:f(g?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:g?"#4ade80":"var(--text-dim)"},children:[(0,d.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:g?"#4ade80":"var(--border)",display:"inline-block",boxShadow:g?"0 0 4px #4ade80":"none"}}),g?"live":"static"]}),(0,d.jsx)(gv,{filePath:a,sourceSessionId:c})]}),(0,d.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:o?(0,d.jsx)("div",{style:{color:"#f87171",fontSize:13},children:o}):(0,d.jsx)("img",{src:r,alt:a,onLoad:a=>{let b=a.currentTarget;n({w:b.naturalWidth,h:b.naturalHeight})},onError:()=>p("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function gz({filePath:a,cwd:b,sourceSessionId:c}){let{t:f}=(0,x.s)(),[g,h]=(0,e.useState)(!1),[i,j]=(0,e.useState)(0),[k,l]=(0,e.useState)(null),[m,n]=(0,e.useState)(null),[o,p]=(0,e.useState)(null);(0,e.useRef)(null);let q=aY(a).toLowerCase().split(".").pop()??"",r=gu(a,"read",c,i?{v:i}:void 0);return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,d.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,d.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:a,children:aZ(a,b)}),(0,d.jsx)("span",{style:{marginLeft:"auto"},children:q||"audio"}),null!=m&&(0,d.jsx)("span",{children:function(a){if(!Number.isFinite(a))return"";let b=Math.round(a),c=Math.floor(b/60);return`${c}:${String(b%60).padStart(2,"0")}`}(m)}),null!=k&&(0,d.jsx)("span",{children:gw(k)}),(0,d.jsxs)("span",{title:f(g?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:g?"#4ade80":"var(--text-dim)"},children:[(0,d.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:g?"#4ade80":"var(--border)",display:"inline-block",boxShadow:g?"0 0 4px #4ade80":"none"}}),g?"live":"static"]}),(0,d.jsx)(gv,{filePath:a,sourceSessionId:c})]}),(0,d.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,d.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[o&&(0,d.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:o}),(0,d.jsx)("audio",{controls:!0,preload:"metadata",src:r,onLoadedMetadata:a=>n(a.currentTarget.duration),onError:()=>p("Failed to load audio"),style:{width:"100%"}},r)]})})]})}function gA({filePath:a,cwd:b,sourceSessionId:c}){let{t:f}=(0,x.s)(),[g,h]=(0,e.useState)(!1),[i,j]=(0,e.useState)(0),[k,l]=(0,e.useState)(null),[m,n]=(0,e.useState)(null);(0,e.useRef)(null);let o=at(a),p="pdf"===o,q=p?gu(a,"read",c,i?{v:i}:void 0):gu(a,"preview",c,i?{v:i}:void 0);return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,d.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,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:a,children:aZ(a,b)}),(0,d.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===o?"docx preview":"pdf"}),null!=k&&(0,d.jsx)("span",{children:gw(k)}),(0,d.jsx)(gv,{filePath:a,sourceSessionId:c}),(0,d.jsxs)("span",{title:f(g?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:g?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,d.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:g?"#4ade80":"var(--border)",display:"inline-block",boxShadow:g?"0 0 4px #4ade80":"none"}}),g?"live":"static"]})]}),(0,d.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:m?(0,d.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:m}):(0,d.jsx)("iframe",{src:q,sandbox:p?void 0:"allow-same-origin",title:f("i18n.previewFile",{file:aY(a)}),style:{width:"100%",height:"100%",border:"none",background:p?"var(--bg)":"#eef1f5"}},q)})]})}function gB({filePath:a,cwd:b,sourceSessionId:c,onOpenFile:e,onMentionLines:f,onAtMention:g,gitRefreshKey:h,initialDisplayMode:i}){let j;return au(a)?(0,d.jsx)(gy,{filePath:a,cwd:b,sourceSessionId:c}):null!==(as[at(a)]??null)?(0,d.jsx)(gz,{filePath:a,cwd:b,sourceSessionId:c}):null!==("pdf"===(j=at(a))||"docx"===j?j:null)?(0,d.jsx)(gA,{filePath:a,cwd:b,sourceSessionId:c}):(0,d.jsx)(gC,{filePath:a,cwd:b,sourceSessionId:c,onOpenFile:e,onMentionLines:f,onAtMention:g,gitRefreshKey:h,initialDisplayMode:i})}function gC({filePath:a,cwd:b,sourceSessionId:c,onOpenFile:f,onMentionLines:g,onAtMention:h,gitRefreshKey:i,initialDisplayMode:j}){let k,l,{isDark:m}=bq(),{t:n}=(0,x.s)(),[o,p]=(0,e.useState)(null),[q,r]=(0,e.useState)(null),[s,t]=(0,e.useState)(!1),[u,v]=(0,e.useState)(!0),[w,y]=(0,e.useState)(null),[z,A]=(0,e.useState)("source"),[B,C]=(0,e.useState)(!1),[D,E]=(0,e.useState)(!1);(0,e.useRef)(null);let F=(0,e.useRef)(0),G=(0,e.useRef)(null),[H,I]=(0,e.useState)(null);(0,e.useCallback)(a=>fetch(gu(a,"read",c)).then(a=>a.json()).then(a=>a.error?(y(a.error),null):(y(null),p(a),a)).catch(a=>(y(String(a)),null)),[c]),(0,e.useCallback)(async a=>{let c=++F.current;if(t(!0),!b){r(null),t(!1);return}try{let d=new URLSearchParams({cwd:b,path:a}),e=await fetch(`/api/git/diff?${d.toString()}`),f=await e.json();if(c!==F.current)return;r(e.ok&&f.supported&&"string"==typeof f.patch?f:null)}catch{c===F.current&&r(null)}finally{c===F.current&&t(!1)}},[b]);let J=q?.supported===!0&&"string"==typeof q.patch,K=J&&"deleted"===q.status;(0,e.useRef)(!1);let L=(0,e.useMemo)(()=>o?.language==="markdown"?a6(o.content):"",[o]),M=(0,e.useMemo)(()=>o?.language==="markdown"?function(a){let b=function(a){let b=gl.exec(a);if(!b)return null;let c=/^---[ \t]*(?:(?:\r\n|\n|\r)|$)/gm;c.lastIndex=b[0].length;let d=c.exec(a);return d?{yaml:a.slice(b[0].length,d.index).replace(/(?:\r\n|\n|\r)$/,""),rest:a.slice(d.index+d[0].length)}:null}(a);if(!b)return{data:null,rest:a};try{let a=(0,gk.Hh)(b.yaml);if(a&&"object"==typeof a&&!Array.isArray(a))return{data:a,rest:b.rest}}catch{}return{data:null,rest:b.rest}}(o.content):null,[o]),N=(0,e.useCallback)(c=>{g&&c&&g(aZ(a,b),c.startLine,c.endLine)},[b,a,g]);if(u||"diff"===j&&s&&!o)return(0,d.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:n("i18n.loading")});if(w&&!K)return(0,d.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:w});if(!o&&!K)return null;let O=o?.language??"text",P=o?.content??"",Q="html"===O,R="markdown"===O,S=(l=(k=aW(a).replace(/\/+$/,"")).lastIndexOf("/"))<0?"":0===l?"/":2===l&&/^[a-zA-Z]:\//.test(k)?k.slice(0,3):k.slice(0,l),T=P.split("\n"),U=K?"diff":z,V=K?["diff"]:["source",...Q||R?["preview"]:[],...J?["diff"]:[]],W=K?n("files.deleted"):`${O} \xb7 ${T.length} lines \xb7 ${gw(o.size)}`;return(0,d.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,d.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,d.jsx)("span",{className:"file-viewer-path",style:{fontFamily:"var(--font-mono)"},title:a,children:aZ(a,b)}),(0,d.jsx)("span",{className:"file-viewer-meta",title:W,children:W}),!K&&(0,d.jsx)("span",{title:D?n("i18n.liveSync"):n("i18n.notWatching"),"aria-label":D?n("i18n.liveSync"):n("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:D?"#4ade80":"var(--border)",boxShadow:D?"0 0 4px #4ade80":"none"}}),(0,d.jsxs)("div",{className:"file-viewer-controls",children:[V.length>1&&(0,d.jsx)("div",{className:"file-viewer-mode-switch","aria-label":n("i18n.fileViewMode"),children:V.map(a=>{let b=U===a;return(0,d.jsx)("button",{type:"button",onClick:()=>A(a),title:"diff"===a?n("i18n.compareHead"):void 0,"aria-pressed":b,className:"file-viewer-mode-button",style:{background:b?"var(--bg-selected)":"transparent",color:b?"var(--text)":"var(--text-muted)"},children:gp[a]},a)})}),(0,d.jsxs)("div",{className:"file-viewer-actions",children:[(h||g)&&(0,d.jsx)("button",{type:"button",onPointerDown:a=>a.preventDefault(),onClick:()=>{H&&g?N(H):h?.(aZ(a,b),!1)},title:H&&g?`${n("i18n.mentionSelectedLines")} (L${H.startLine}${H.startLine!==H.endLine?`-L${H.endLine}`:""})`:n("files.insertPath"),"aria-label":n("files.mention"),disabled:!h&&!g,className:"file-viewer-icon-button",children:(0,d.jsx)(gs,{})}),"source"===U&&(0,d.jsx)(d.Fragment,{children:(0,d.jsx)("button",{type:"button",onClick:()=>C(a=>!a),title:B?n("i18n.disableWrap"):n("i18n.enableWrap"),"aria-label":B?n("i18n.disableWrap"):n("i18n.enableWrap"),"aria-pressed":B,className:"file-viewer-icon-button",style:{background:B?"var(--bg-selected)":"transparent",color:B?"var(--text)":"var(--text-muted)"},children:(0,d.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,d.jsx)("path",{d:"M3 6h18"}),(0,d.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,d.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,d.jsx)("path",{d:"M3 18h7"})]})})})]}),!K&&(0,d.jsx)(gv,{filePath:a,sourceSessionId:c})]})]}),(0,d.jsx)("div",{ref:G,className:"file-viewer-content",style:{flex:1,overflow:"auto",background:"var(--bg)"},children:"diff"===U&&J?(0,d.jsx)(gx,{patch:q.patch}):Q&&"preview"===U?(0,d.jsx)("iframe",{srcDoc:P,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:n("i18n.htmlPreview")}):R&&"preview"===U?(0,d.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[M?.data&&(0,d.jsx)(go,{data:M.data}),(0,d.jsx)(aV.oz,{remarkPlugins:bb,rehypePlugins:bd,components:{code({className:a,children:b,...c}){let e=a?.replace("language-","").toLowerCase()??"",f=String(b);return a?.includes("language-")||f.includes("\n")?"mermaid"===e?(0,d.jsx)(bt,{code:f.replace(/\n$/,""),defaultPreview:!0}):(0,d.jsx)(bv,{code:f.replace(/\n$/,""),lang:e}):(0,d.jsx)("code",{className:a,...c,children:b})},pre:({children:a})=>(0,d.jsx)(d.Fragment,{children:a}),a({href:a,children:c,...e}){delete e.node;let g=f?aQ(a,S,b??S):null;return g&&f?(0,d.jsx)("a",{href:a,...e,onClick:a=>{a.defaultPrevented||0!==a.button||a.metaKey||a.ctrlKey||a.shiftKey||a.altKey||(a.preventDefault(),f(g))},children:c}):(0,d.jsx)("a",{href:a,...e,children:c})},img({src:a,alt:e,...f}){delete f.node;let g="string"==typeof a?aQ(a,S,b??S):null,h=g?gu(g,"read",c):a;return(0,d.jsx)("img",{src:h,alt:e??"",loading:"lazy",...f})},table:({children:a})=>(0,d.jsx)("div",{className:"markdown-table-wrap",children:(0,d.jsx)("table",{children:a})})},children:L})]}):(0,d.jsx)(aT.A,{className:B?"file-source-view is-wrapped":"file-source-view",language:"text"===O?"plaintext":O,style:m?aU.xJ:aU.vs,showLineNumbers:!0,lineNumberStyle:{...gr},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...gq,width:B?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",overflowWrap:B?"anywhere":"normal"}},renderer:a=>(0,d.jsx)(gt,{...a,wrapLines:B}),wrapLongLines:B,children:P})})]})}function gD({tabs:a,activeTabId:b,onSelectTab:c,onCloseTab:f}){let{t:g,locale:h}=(0,x.s)(),[i,j]=(0,e.useState)(null);return(0,d.jsx)("div",{className:"file-tab-list",role:"tablist","aria-label":"ko"===h?"열린 파일 탭":"Open file tabs",style:{display:"flex",alignItems:"flex-end",overflowX:"auto",flexShrink:0,height:36},children:a.map(a=>{let e=a.id===b;return(0,d.jsxs)("div",{className:`file-tab${e?" is-active":""}`,role:"presentation",onMouseDown:a=>{1===a.button&&a.preventDefault()},onAuxClick:b=>{1===b.button&&(b.preventDefault(),b.stopPropagation(),f(a.id))},style:{display:"flex",alignItems:"center",height:36,paddingRight:6,borderRight:"1px solid var(--border)",fontSize:12,whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,d.jsxs)("button",{type:"button",role:"tab","aria-selected":e,onClick:()=>c(a.id),title:a.filePath,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,height:"100%",padding:"0 0 0 12px",border:"none",background:"none",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,d.jsx)("span",{style:{flexShrink:0,opacity:e?1:.7,display:"flex",alignItems:"center"},children:b2(a.label,13)}),(0,d.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:e?500:400},children:a.label})]}),(0,d.jsx)("button",{className:"file-tab-close",onClick:b=>{b.stopPropagation(),f(a.id)},onMouseEnter:()=>j(a.id),onMouseLeave:()=>j(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:i===a.id?"var(--bg-hover)":"transparent",border:"none",color:i===a.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:g("i18n.close"),"aria-label":`${g("i18n.close")} ${a.label}`,children:(0,d.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,d.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,d.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},a.id)})})}let gE=["inherit","off","auto","minimal","low","medium","high","xhigh","max"],gF=new Set(gE);function gG(a){return void 0!==a&&gF.has(a)}function gH(a){if(!a)return[...gE];let b=new Set(a);return gE.filter(a=>"inherit"===a||"off"===a||"auto"===a||b.has(a))}function gI(a){if(!a)return"inherit";let b=a.lastIndexOf(":"),c=b>=0?a.slice(b+1):void 0;return gG(c)?c:"inherit"}function gJ(a,b){let c=a.lastIndexOf(":"),d=gG(c>=0?a.slice(c+1):void 0)?a.slice(0,c):a;return"inherit"===b?d:`${d}:${b}`}var gK=c(35836),gL=c.n(gK);function gM(a){return a.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase()}function gN({value:a,options:b,onChange:c,disabled:f=!1,placeholder:g="Select…",searchPlaceholder:h="Search options…",noResultsLabel:i="No matching options",ariaLabel:j,className:k,style:l}){let m=(0,e.useRef)(null),n=(0,e.useRef)(null),o=(0,e.useRef)(null),p=(0,e.useRef)([]),[q,r]=(0,e.useState)(!1),[s,t]=(0,e.useState)(""),[u,v]=(0,e.useState)(0),w=(0,e.useId)(),x=b.find(b=>b.value===a),y=(0,e.useMemo)(()=>{let a=gM(s.trim());return a?b.filter(b=>gM(`${b.label} ${b.value} ${b.searchText??""}`).includes(a)):b},[b,s]),{side:z,maxHeight:A}=e0(m,q,{viewportFraction:.6,cap:296,gap:5,prefer:"below",minHeight:160}),B=a=>{a.disabled||(c(a.value),r(!1))},C=a=>{if(!y.length)return;let b=u;for(let c=0;c<y.length;c+=1)if(b=(b+a+y.length)%y.length,!y[b].disabled)return void v(b)};return(0,d.jsxs)("div",{ref:m,className:`${gL().root}${k?` ${k}`:""}`,style:l,children:[(0,d.jsxs)("button",{ref:n,type:"button",className:gL().trigger,disabled:f,"aria-label":j,"aria-haspopup":"listbox","aria-expanded":q,"aria-controls":q?w:void 0,onClick:()=>r(a=>!a),onKeyDown:a=>{("ArrowDown"===a.key||"ArrowUp"===a.key)&&(a.preventDefault(),r(!0))},children:[(0,d.jsx)("span",{className:x?gL().value:gL().placeholder,children:x?.label??(a||g)}),(0,d.jsx)("svg",{className:gL().chevron,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m3 4.5 3 3 3-3"})})]}),q&&(0,d.jsxs)("div",{className:gL().popover,style:"above"===z?{bottom:"calc(100% + 5px)",maxHeight:A}:{top:"calc(100% + 5px)",maxHeight:A},"data-dismissible-layer":"searchable-select",onKeyDown:a=>{"Escape"===a.key&&(a.preventDefault(),a.stopPropagation(),r(!1),n.current?.focus())},children:[(0,d.jsxs)("div",{className:gL().searchWrap,children:[(0,d.jsxs)("svg",{className:gL().searchIcon,viewBox:"0 0 16 16","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"7",cy:"7",r:"4.25"}),(0,d.jsx)("path",{d:"m10.2 10.2 3.1 3.1"})]}),(0,d.jsx)("input",{ref:o,className:gL().search,value:s,placeholder:h,"aria-label":h,role:"combobox","aria-expanded":"true","aria-controls":w,"aria-activedescendant":y[u]?`${w}-${u}`:void 0,autoComplete:"off",spellCheck:!1,onChange:a=>{t(a.target.value),v(0)},onKeyDown:a=>{if("ArrowDown"===a.key)a.preventDefault(),C(1);else if("ArrowUp"===a.key)a.preventDefault(),C(-1);else if("Enter"===a.key){a.preventDefault();let b=y[u];b&&B(b)}else"Tab"===a.key&&r(!1)}})]}),(0,d.jsx)("div",{id:w,className:gL().options,role:"listbox","aria-label":j,style:{maxHeight:Math.max(0,A-46)},children:y.length?y.map((b,c)=>(0,d.jsxs)("button",{ref:a=>{p.current[c]=a},id:`${w}-${c}`,type:"button",role:"option","aria-selected":b.value===a,className:gL().option,"data-active":c===u,"data-selected":b.value===a,disabled:b.disabled,onMouseEnter:()=>v(c),onClick:()=>B(b),children:[(0,d.jsxs)("span",{className:gL().optionCopy,children:[(0,d.jsx)("span",{className:gL().optionLabel,children:b.label}),b.description&&(0,d.jsx)("span",{className:gL().optionDescription,children:b.description})]}),b.value===a&&(0,d.jsx)("svg",{className:gL().check,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m2.3 6.2 2.2 2.2 5.2-5.2"})})]},b.value)):(0,d.jsx)("div",{className:gL().empty,children:i})})]})]})}let gO=["global","project"],gP=["implSonnet","implOpus","implDeepSeek","makerHardUiOpus","makerHardCodeOpus","makerHardCodeSonnet"];function gQ(a){return`${a.provider}/${a.id}`}function gR({cwd:a,onRolesChanged:b}){let{t:c}=(0,x.s)(),[f,g]=(0,e.useState)([]),[h,i]=(0,e.useState)([]),[j,k]=(0,e.useState)({}),[l,m]=(0,e.useState)("global"),[n,o]=(0,e.useState)(!0),[p,q]=(0,e.useState)(null),[r,s]=(0,e.useState)(null);(0,e.useCallback)(async b=>{if(!a){g([]),i([]),k({}),o(!1);return}o(!0),q(null);try{let c=`?cwd=${encodeURIComponent(a)}`,[d,e]=await Promise.all([fetch(`/api/model-roles${c}`,b?{signal:b}:void 0),fetch(`/api/models${c}`,b?{signal:b}:void 0)]);if(!d.ok)throw Error(`HTTP ${d.status}`);let f=await d.json();if(f.error)throw Error(f.error);if(!e.ok)throw Error(`HTTP ${e.status}`);let h=await e.json();g(f.roles??[]),i(h.modelList??[]),k(h.thinkingLevels??{})}catch(a){if("AbortError"===a.name)return;q(a instanceof Error?a.message:String(a))}finally{o(!1)}},[a]);let t=(0,e.useCallback)(async(c,d)=>{if(a){s(c),q(null);try{let e=await fetch("/api/model-roles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:a,role:c,selector:d,scope:l})}),f=await e.json();if(!e.ok||f.error)throw Error(f.error??`HTTP ${e.status}`);g(f.roles??[]),b?.()}catch(a){q(a instanceof Error?a.message:String(a))}finally{s(null)}}},[a,l,b]),u=(0,e.useMemo)(()=>f.filter(a=>!a.hidden),[f]),v=u.some(a=>gP.includes(a.role)&&!a.selector);return a?(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{style:{fontSize:13,fontWeight:700,color:"var(--text)",marginBottom:4},children:c("roles.title")}),(0,d.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:c("roles.description")}),!n&&v&&(0,d.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",lineHeight:1.5,marginTop:4},children:c("roles.harnessNote")})]}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8},children:[(0,d.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:c("roles.scope")}),(0,d.jsx)("div",{style:{display:"flex",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,overflow:"hidden"},children:gO.map(a=>(0,d.jsx)("button",{onClick:()=>m(a),style:{padding:"4px 10px",border:"none",background:l===a?"var(--bg-selected)":"transparent",color:l===a?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:l===a?600:400},children:"global"===a?c("roles.scopeGlobal"):c("roles.scopeProject")},a))}),(0,d.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"global"===l?"~/.omp/agent/config.yml":".omp/config.yml"})]}),p&&(0,d.jsx)("div",{style:{fontSize:12,color:"var(--danger, #ff4757)"},children:p}),n?(0,d.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:c("i18n.loading")}):(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:u.map(a=>{let b=a.resolved?`${a.resolved.provider}/${a.resolved.modelId}`:gJ(a.selector??"","inherit"),e=gI(a.selector),f=gH(j[a.resolved?`${a.resolved.provider}:${a.resolved.modelId}`:""]),g=gP.includes(a.role);return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)"},children:[(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,rowGap:6},children:[(0,d.jsx)("span",{style:{flexShrink:0,minWidth:62,padding:"2px 6px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-subtle)",color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:a.tag??a.role.toUpperCase()}),(0,d.jsxs)("div",{style:{minWidth:0,flex:"0 0 auto",width:128},children:[(0,d.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontWeight:600},children:a.name}),g&&(0,d.jsx)("div",{style:{fontSize:10,color:"var(--text-muted)",lineHeight:1.35},children:c(`roles.harness.${a.role}`)}),(0,d.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)"},children:g&&!a.selector?c("roles.harnessUnset"):c(`roles.source.${a.source}`)})]}),(0,d.jsx)(gN,{value:b,disabled:r===a.role,ariaLabel:a.name,style:{flex:"1 1 160px",minWidth:0},onChange:b=>{if(!b)return void t(a.role,null);let c=h.find(a=>gQ(a)===b),d=c?j[`${c.provider}:${c.id}`]:void 0,e=gI(a.selector),f=gH(d).includes(e)?e:"inherit";t(a.role,gJ(b,f))},options:[{value:"",label:c("roles.unset")},...h.map(a=>({value:gQ(a),label:`${a.name} — ${a.provider}`,searchText:gQ(a)})),...b&&!h.some(a=>gQ(a)===b)?[{value:b,label:b}]:[]]}),a.warning&&(0,d.jsx)("span",{title:a.warning,style:{color:"var(--warning, #ffb347)",fontSize:12},children:"!"})]}),a.resolved&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",paddingLeft:72},children:[(0,d.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,whiteSpace:"nowrap"},children:c("roles.thinking")}),(0,d.jsx)("div",{role:"group","aria-label":`${a.name} ${c("roles.thinking")}`,style:{display:"flex",flex:"1 1 auto",minWidth:0,flexWrap:"wrap",gap:3},children:f.map(f=>{let g=e===f;return(0,d.jsx)("button",{type:"button","aria-pressed":g,disabled:r===a.role,title:"inherit"===f?c("roles.thinkingInherit"):f,onClick:()=>{g||t(a.role,gJ(b,f))},style:{padding:"3px 7px",border:`1px solid ${g?"var(--accent)":"var(--border)"}`,borderRadius:4,background:g?"var(--bg-selected)":"transparent",color:g?"var(--accent)":"var(--text-muted)",cursor:r===a.role?"not-allowed":"pointer",fontFamily:"var(--font-mono)",fontSize:10,fontWeight:g?700:500,lineHeight:1.2,opacity:r===a.role?.55:1},children:f},f)})})]})]},a.role)})})]}):(0,d.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:c("roles.needsProject")})}function gS(a){window.open(a,"_blank","noopener,noreferrer")}var gT=c(2950),gU=c(62208),gV=c(12146),gW=c(4923),gX=c(86793),gY=c(59233),gZ=c(56469),g$=c(14154),g_=c(53243),g0=c(81487),g1=c(4180),g2=c(95417),g3=c(81520),g4=c(53854),g5=c(32647),g6=c(92921),g7=c(3220),g8=c(1970),g9=c(59703),ha=c(4282),hb=c(50175),hc=c(49477),hd=c(85891),he=c(30399),hf=c(97459),hg=c(83457),hh=c(85950),hi=c(7657),hj=c(81223),hk=c(78038);let hl={anthropic:{Icon:gT.A,hasColor:!1},openai:{Icon:gU.A,hasColor:!1},"openai-codex":{Icon:gU.A,hasColor:!1},google:{Icon:gV.A,hasColor:!0},"google-vertex":{Icon:gV.A,hasColor:!0},"ant-ling":{Icon:hg.A,hasColor:!0},deepseek:{Icon:gW.A,hasColor:!0},groq:{Icon:gX.A,hasColor:!1},mistral:{Icon:gY.A,hasColor:!0},moonshotai:{Icon:gZ.A,hasColor:!1},"moonshotai-cn":{Icon:gZ.A,hasColor:!1},moonshot:{Icon:gZ.A,hasColor:!1},minimax:{Icon:g$.A,hasColor:!0},"minimax-cn":{Icon:g$.A,hasColor:!0},fireworks:{Icon:g_.A,hasColor:!0},huggingface:{Icon:g0.A,hasColor:!0},cerebras:{Icon:g1.A,hasColor:!0},openrouter:{Icon:g2.A,hasColor:!1},xai:{Icon:g3.A,hasColor:!1},"cloudflare-ai-gateway":{Icon:g4.A,hasColor:!0},"cloudflare-workers-ai":{Icon:g4.A,hasColor:!0},"vercel-ai-gateway":{Icon:g5.A,hasColor:!1},"github-copilot":{Icon:g6.A,hasColor:!1},"amazon-bedrock":{Icon:g7.A,hasColor:!0},"azure-openai-responses":{Icon:g8.A,hasColor:!0},"kimi-coding":{Icon:g9.A,hasColor:!0},nvidia:{Icon:hh.A,hasColor:!0},opencode:{Icon:hi.A,hasColor:!1},"opencode-go":{Icon:hi.A,hasColor:!1},qwen:{Icon:ha.A,hasColor:!0},xiaomi:{Icon:hj.A,hasColor:!1},"xiaomi-token-plan-ams":{Icon:hj.A,hasColor:!1},"xiaomi-token-plan-cn":{Icon:hj.A,hasColor:!1},"xiaomi-token-plan-sgp":{Icon:hj.A,hasColor:!1},zai:{Icon:hk.A,hasColor:!1},"zai-coding-cn":{Icon:hk.A,hasColor:!1},zhipu:{Icon:hb.A,hasColor:!0},cohere:{Icon:hc.A,hasColor:!0},perplexity:{Icon:hd.A,hasColor:!0},together:{Icon:he.A,hasColor:!0},grok:{Icon:hf.A,hasColor:!1}},hm=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function hn({label:a,children:b}){return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,d.jsx)("label",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:a}),b]})}let ho={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 hp({value:a,onChange:b,placeholder:c,mono:e}){return(0,d.jsx)("input",{value:a,onChange:a=>b(a.target.value),placeholder:c,style:{...ho,fontFamily:e?"var(--font-mono)":"inherit"}})}function hq({value:a,onChange:b,placeholder:c,mono:f,onKeyDown:g,autoComplete:h="off",spellCheck:i=!1,style:j}){let[k,l]=(0,e.useState)(!1),{t:m}=(0,x.s)();return(0,d.jsxs)("div",{style:{position:"relative",width:"100%",...j},children:[(0,d.jsx)("input",{type:k?"text":"password",value:a,onChange:a=>b(a.target.value),onKeyDown:g,placeholder:c,style:{...ho,paddingRight:34,fontFamily:f?"var(--font-mono)":"inherit"},autoComplete:h,spellCheck:i}),(0,d.jsx)("button",{type:"button",onClick:()=>l(a=>!a),"aria-label":m(k?"i18n.hideDetails":"i18n.showDetails"),title:m(k?"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:k?(0,d.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.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,d.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,d.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,d.jsx)("path",{d:"M1 1l22 22"})]}):(0,d.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,d.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function hr({value:a,onChange:b,placeholder:c}){return(0,d.jsx)("input",{type:"number",value:a,onChange:a=>b(a.target.value),placeholder:c,style:ho})}function hs({value:a,onChange:b,options:c,required:e}){let{t:f}=(0,x.s)();return(0,d.jsx)(gN,{value:a,onChange:b,options:[...e?[]:[{value:"",label:`— ${f("i18n.default")} / none —`}],...c.map(a=>({value:a,label:a}))]})}function ht({label:a,checked:b,onChange:c}){return(0,d.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,d.jsx)("input",{type:"checkbox",checked:b,onChange:a=>c(a.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),a]})}function hu({children:a}){return(0,d.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:a})}function hv({name:a,provider:b,onChange:c,onRename:f,onDelete:g,onAddModels:h}){let{t:i}=(0,x.s)(),[j,k]=(0,e.useState)(a),[l,m]=(0,e.useState)({phase:"idle"}),[n,o]=(0,e.useState)(""),[p,q]=(0,e.useState)([]),r=(0,e.useRef)(0),s=(0,e.useRef)(null),t=(a,d)=>c({...b,[a]:d}),u=(0,e.useCallback)(async()=>{if(!b.baseUrl?.trim()||"loading"===l.phase)return;let c=++r.current;m({phase:"loading"}),q([]);try{let d=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:a,provider:{...b,models:void 0}})}),e=await d.json();if(c!==r.current)return;if(!d.ok||e.error||!e.models)return void m({phase:"error",message:e.error??`HTTP ${d.status}`});m({phase:"success",models:e.models,endpoint:e.endpoint??b.baseUrl})}catch(a){if(c!==r.current)return;m({phase:"error",message:a instanceof Error?a.message:String(a)})}},[l.phase,a,b]),v=new Set((b.models??[]).map(a=>a.id)),w="success"===l.phase?l.models:[],y=n.trim().toLocaleLowerCase(),z=w.filter(a=>!y||a.id.toLocaleLowerCase().includes(y)||a.name?.toLocaleLowerCase().includes(y)),A=z.slice(0,300),B=A.filter(a=>!v.has(a.id)).map(a=>a.id),C=p.filter(a=>!v.has(a)).length,D=B.length>0&&B.every(a=>p.includes(a));return D||B.some(a=>p.includes(a)),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,d.jsx)(hu,{children:i("i18n.provider")}),(0,d.jsx)("button",{onClick:g,style:{padding:"3px 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11},children:i("i18n.delete")})]}),(0,d.jsxs)(hn,{label:i("i18n.providerName"),children:[(0,d.jsx)(hp,{value:j,onChange:k,placeholder:"provider-name",mono:!0}),j!==a&&j.trim()&&(0,d.jsx)("button",{onClick:()=>f(j.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:4,color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:i("i18n.rename")})]}),(0,d.jsx)(hn,{label:"Base URL",children:(0,d.jsx)(hp,{value:b.baseUrl??"",onChange:a=>t("baseUrl",a||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,d.jsxs)(hn,{label:"API Key",children:[(0,d.jsx)(hq,{value:b.apiKey??"",onChange:a=>t("apiKey",a||void 0),placeholder:"ENV_VAR_NAME, !shell-command, or literal key",mono:!0}),(0,d.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:["Prefix with ",(0,d.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:"!"})," to run a shell command, or use an env var name"]})]}),(0,d.jsx)(hn,{label:"API",children:(0,d.jsx)(hs,{value:b.api??"openai-completions",onChange:a=>t("api",a),options:hm,required:!0})}),(0,d.jsxs)(hn,{label:"Headers",children:[(0,d.jsx)(hA,{headers:b.headers,onChange:a=>t("headers",a)}),(0,d.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,d.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==l.phase&&(0,d.jsx)("button",{onClick:u,disabled:!b.baseUrl?.trim()||"loading"===l.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:b.baseUrl?.trim()&&"loading"!==l.phase?"var(--text-muted)":"var(--text-dim)",cursor:b.baseUrl?.trim()&&"loading"!==l.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===l.phase?i("models.discoveryFetching"):i("models.discoveryFetch")}),"error"===l.phase&&(0,d.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:l.message}),"success"===l.phase&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("input",{value:n,onChange:a=>o(a.target.value),placeholder:i("models.discoveryFilterPlaceholder",{count:l.models.length}),"aria-label":i("models.discoveryFilter"),style:{...ho,width:"100%",minWidth:0}}),(0,d.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,d.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:B.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,d.jsx)("input",{ref:s,type:"checkbox",checked:D,disabled:0===B.length,onChange:()=>{let a=new Set(B);q(b=>D?b.filter(b=>!a.has(b)):Array.from(new Set([...b,...B])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),i("models.discoverySelectShown")]}),0===A.length?(0,d.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:i("models.discoveryNoMatches")}):A.map((a,b)=>{let c=v.has(a.id),e=p.includes(a.id);return(0,d.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===b?"none":"1px solid var(--border)",cursor:c?"default":"pointer",opacity:c?.65:1},children:[(0,d.jsx)("input",{type:"checkbox",checked:e||c,disabled:c,onChange:()=>{var b;return b=a.id,void q(a=>a.includes(b)?a.filter(a=>a!==b):[...a,b])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,d.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,d.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:a.name??a.id}),a.name&&(0,d.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:a.id})]}),c&&(0,d.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:i("models.discoveryAdded")})]},a.id)})]}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,d.jsx)("span",{title:l.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:z.length>A.length?i("models.discoveryShowing",{shown:A.length,total:z.length}):i("models.discoveryFetched",{count:l.models.length})}),(0,d.jsx)("button",{onClick:()=>{if("success"!==l.phase)return;let a=new Set(p),b=l.models.filter(b=>a.has(b.id)&&!v.has(b.id));0!==b.length&&(h(b),q([]))},disabled:0===C,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:C?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",color:C?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:C?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:C?i("models.discoveryAddSelectedCount",{count:C}):i("models.discoveryAddSelected")})]})]})]})]})}let hw=["off","minimal","low","medium","high","xhigh","max"],hx={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function hy({value:a,onChange:b}){let c=a??{},e=(a,d)=>{let e={...c};"omit"===d?delete e[a]:e[a]=d,b(Object.keys(e).length?e:void 0)};return(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:hw.map(a=>{let b=c[a],f=a in c?null===b?"null":"string":"omit",g="string"==typeof b?b:"",h=hx[a],i={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)"},j={background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontWeight:600};return(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,d.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:h,flexShrink:0,opacity:"null"===f?.3:1}}),(0,d.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===f?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===f?"line-through":"none"},children:a})]}),(0,d.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,d.jsx)("button",{onClick:()=>e(a,"omit"),style:{...i,..."omit"===f?j:{}},children:"Default"}),(0,d.jsx)("button",{onClick:()=>e(a,null),style:{...i,borderLeft:"1px solid var(--border)",..."null"===f?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,d.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===f?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,d.jsx)("button",{onClick:()=>e(a,g||a),style:{...i,..."string"===f?j:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,d.jsx)("input",{value:g,onChange:b=>e(a,b.target.value),onFocus:()=>{"string"!==f&&e(a,g||a)},placeholder:a,maxLength:10,style:{width:"12ch",background:"string"===f?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===f?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},a)})})}let hz={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function hA({headers:a,onChange:b}){let[c,f]=(0,e.useState)(()=>Object.entries(a??{}).map(([a,b],c)=>({id:c,name:a,value:b}))),g=(0,e.useRef)(c.length),h=a=>{f(a),b(function(a){let b={};for(let c of a){let a=c.name.trim();a&&(b[a]=c.value)}return Object.keys(b).length?b:void 0}(a))},i=(a,b)=>{h(c.map(c=>c.id===a?{...c,...b}:c))},j={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,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[c.map(a=>(0,d.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,d.jsx)("input",{value:a.name,onChange:b=>i(a.id,{name:b.target.value}),placeholder:"Header-Name",style:{...ho,fontFamily:"var(--font-mono)",flex:1}}),(0,d.jsx)("input",{value:a.value,onChange:b=>i(a.id,{value:b.target.value}),placeholder:"value",style:{...ho,fontFamily:"var(--font-mono)",flex:1}}),(0,d.jsx)("button",{onClick:()=>{var b;return b=a.id,void h(c.filter(a=>a.id!==b))},style:j,children:"✕"})]},a.id)),(0,d.jsx)("button",{onClick:()=>f(a=>[...a,{id:g.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 hB({providerName:a,provider:b,model:c,onChange:f,onDelete:g}){let[h,i]=(0,e.useState)({phase:"idle"}),{t:j}=(0,x.s)(),[k,l]=(0,e.useState)({phase:"idle"}),m=(0,e.useRef)(0),n=(0,e.useRef)(null),o=(a,b)=>f({...c,[a]:b}),p=(()=>{if("idle"===h.phase)return null;if("testing"===h.phase)return j("i18n.testingModel");let a=[void 0!==h.latencyMs?`${h.latencyMs}ms`:null,void 0!==h.status?`HTTP ${h.status}`:null].filter(Boolean);return"success"===h.phase?[j("i18n.connected"),...a,h.responseText||null].filter(Boolean).join(" \xb7 "):[j("i18n.failed"),...a,h.message].filter(Boolean).join(" \xb7 ")})(),q=(0,e.useCallback)(async()=>{if(c.id.trim()&&"testing"!==h.phase){i({phase:"testing"});try{let d=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:a,provider:b,model:c})}),e=await d.json();if(!d.ok||!e.ok)return void i({phase:"error",message:e.error??`HTTP ${d.status}`,latencyMs:e.latencyMs,status:e.status});i({phase:"success",latencyMs:e.latencyMs,status:e.status,responseText:e.responseText})}catch(a){i({phase:"error",message:a instanceof Error?a.message:String(a)})}}},[c,b,a,h.phase]),r=(0,e.useCallback)(async()=>{let d=c.id.trim();if(!d||"loading"===k.phase)return;let e=++m.current;l({phase:"loading"});try{let g=new URLSearchParams({q:d,provider:a,limit:"50"});b.baseUrl?.trim()&&g.set("baseUrl",b.baseUrl.trim());let h=await fetch(`/api/models-config/catalog?${g}`),i=await h.json();if(e!==m.current)return;if(!h.ok||i.error||!i.recommendation)return void l({phase:"error",message:i.error??`HTTP ${h.status}`});let j=function(a,b){let c={...a},d=0;if(!a.name?.trim()&&b.name&&(c.name=b.name,d+=1),void 0===a.reasoning&&!0===b.reasoning&&(c.reasoning=!0,d+=1),!a.input?.length&&b.input?.length&&(c.input=[...b.input],d+=1),void 0===a.contextWindow&&void 0!==b.contextWindow&&(c.contextWindow=b.contextWindow,d+=1),void 0===a.maxTokens&&void 0!==b.maxTokens&&(c.maxTokens=b.maxTokens,d+=1),b.cost){let e={...a.cost??{}},f=!1;for(let a of["input","output","cacheRead","cacheWrite"])void 0===e[a]&&void 0!==b.cost[a]&&(e[a]=b.cost[a],f=!0,d+=1);f&&(c.cost=e)}return{model:c,appliedCount:d}}(c,i.recommendation.preset);j.appliedCount>0&&(n.current=c,f(j.model)),l({phase:"success",recommendation:i.recommendation,appliedCount:j.appliedCount})}catch(a){if(e!==m.current)return;l({phase:"error",message:a instanceof Error?a.message:String(a)})}},[k.phase,c,f,b.baseUrl,a]),s=(()=>{if("success"!==k.phase)return null;let{recommendation:b,appliedCount:c}=k,d=c>0?j("models.catalogFilled",{count:c}):j("models.catalogNoEmptyFields");if("unreliable"===b.price.status){let a="no-exact-match"===b.price.reason?j("models.catalogNoExactMatch"):j("models.catalogPriceUnreliable");return`${d} \xb7 ${a}`}let e="provider"===b.price.method?j("models.catalogPriceProvider",{provider:b.price.providerName??b.price.providerId??a}):"base-url"===b.price.method?j("models.catalogPriceBaseUrl",{provider:b.price.providerName??b.price.providerId??a}):j("models.catalogPriceConsensus",{support:b.price.support,total:b.price.total});return`${d} \xb7 ${e}`})(),t="error"===k.phase?k.message:s,u="error"===k.phase?"#ef4444":"success"===k.phase&&"unreliable"===k.recommendation.price.status?"#d97706":"var(--text-dim)";return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,d.jsx)(hu,{children:j("i18n.model")}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[p&&(0,d.jsx)("span",{title:p,style:{maxWidth:260,height:24,padding:"0 8px",border:`1px solid ${"error"===h.phase?"#fecaca":"success"===h.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===h.phase?"#fee2e2":"success"===h.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:p}),(0,d.jsxs)("button",{onClick:q,disabled:!c.id.trim()||"testing"===h.phase,title:j("i18n.testConnection"),style:{height:24,padding:"0 8px",background:"success"===h.phase?"#16a34a":"none",border:`1px solid ${"success"===h.phase?"#16a34a":"var(--border)"}`,borderRadius:4,color:"success"===h.phase?"#fff":c.id.trim()&&"testing"!==h.phase?"var(--text-muted)":"var(--text-dim)",cursor:c.id.trim()&&"testing"!==h.phase?"pointer":"not-allowed",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",gap:5},children:["success"===h.phase&&(0,d.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===h.phase?j("i18n.checking"):"success"===h.phase?j("common.ok"):j("i18n.test")]}),(0,d.jsx)("button",{onClick:g,style:{height:24,padding:"0 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,boxSizing:"border-box"},children:j("i18n.remove")})]})]}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,d.jsx)(hn,{label:"ID *",children:(0,d.jsx)(hp,{value:c.id,onChange:a=>o("id",a),placeholder:"model-id",mono:!0})}),(0,d.jsx)(hn,{label:"Name",children:(0,d.jsx)(hp,{value:c.name??"",onChange:a=>o("name",a||void 0),placeholder:"Display name"})})]}),(0,d.jsxs)("div",{style:{padding:"10px 0",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,d.jsx)("button",{onClick:()=>void r(),disabled:!c.id.trim()||"loading"===k.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:c.id.trim()&&"loading"!==k.phase?"var(--text-muted)":"var(--text-dim)",cursor:c.id.trim()&&"loading"!==k.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===k.phase?j("models.catalogFilling"):j("models.catalogFill")}),(0,d.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:j("models.catalogSource")})]}),(0,d.jsxs)("div",{"aria-live":"polite",style:{marginTop:6,height:20,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:u,fontSize:10},children:[(0,d.jsx)("span",{title:t??void 0,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t}),n.current&&(0,d.jsx)("button",{onClick:()=>{let a=n.current;a&&(n.current=null,f(a),l({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:j("models.catalogUndo")})]})]}),(0,d.jsx)(hn,{label:"API override",children:(0,d.jsx)(hs,{value:c.api??"",onChange:a=>o("api",a||void 0),options:hm})}),(0,d.jsxs)(hn,{label:"Headers",children:[(0,d.jsx)(hA,{headers:c.headers,onChange:a=>o("headers",a)}),(0,d.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to this model's requests; overrides the provider headers for this model."})]}),(0,d.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,d.jsx)(ht,{label:"Reasoning / thinking",checked:c.reasoning??!1,onChange:a=>o("reasoning",a||void 0)}),(0,d.jsx)(ht,{label:"Image input",checked:c.input?.includes("image")??!1,onChange:a=>o("input",a?["text","image"]:void 0)})]}),c.reasoning&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(ht,{label:"DeepSeek thinking compat",checked:c.compat?.thinkingFormat==="deepseek",onChange:a=>f(function(a,b){if(b)return{...a,compat:{...a.compat??{},...hz}};if(!a.compat)return a;let c={...a.compat};return delete c.thinkingFormat,delete c.requiresReasoningContentOnAssistantMessages,{...a,compat:Object.keys(c).length?c:void 0}}(c,a))}),(0,d.jsx)(ht,{label:"Use 'developer' role for the system prompt (disable if server rejects it)",checked:!1!==({...b.compat??{},...c.compat??{}}).supportsDeveloperRole,onChange:a=>f({...c,compat:{...c.compat??{},supportsDeveloperRole:a}})}),(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,d.jsx)(hu,{children:"Thinking level map"}),c.thinkingLevelMap&&(0,d.jsx)("button",{onClick:()=>o("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 7px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-dim)",cursor:"pointer"},children:"clear all"})]}),(0,d.jsx)(hy,{value:c.thinkingLevelMap,onChange:a=>o("thinkingLevelMap",a)})]})]}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,d.jsx)(hn,{label:"Context window (tokens)",children:(0,d.jsx)(hr,{value:void 0!==c.contextWindow?String(c.contextWindow):"",onChange:a=>o("contextWindow",a?parseInt(a):void 0),placeholder:"128000"})}),(0,d.jsx)(hn,{label:"Max output tokens",children:(0,d.jsx)(hr,{value:void 0!==c.maxTokens?String(c.maxTokens):"",onChange:a=>o("maxTokens",a?parseInt(a):void 0),placeholder:"16384"})})]}),(0,d.jsxs)("div",{children:[(0,d.jsx)(hu,{children:"Cost (per million tokens)"}),(0,d.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8},children:["input","output","cacheRead","cacheWrite"].map(a=>(0,d.jsx)(hn,{label:a,children:(0,d.jsx)(hr,{value:c.cost?.[a]!==void 0?String(c.cost[a]):"",onChange:b=>{let d;return d=parseFloat(b),void f({...c,cost:{...c.cost??{},[a]:isNaN(d)?void 0:d}})},placeholder:"0"})},a))})]})]})}let hC={checking:"relogin.checking",recovered:"relogin.recovered","still-failing":"relogin.stillFailing",unknown:"relogin.unknown"};function hD({provider:a,onRefresh:b,relogin:c}){let f=c?.onLoginSucceeded,[g,h]=(0,e.useState)({phase:"idle"}),{t:i}=(0,x.s)(),[j,k]=(0,e.useState)(""),l=(0,e.useRef)(null),m=(0,e.useRef)(!1),n=(0,e.useRef)(null),o=(0,e.useRef)(null),p=(0,e.useCallback)(()=>{l.current?.close(),m.current||(m.current=!0,k(""),h({phase:"success"}),b(),f?.())},[b,f]),q=(0,e.useCallback)(()=>{l.current?.close(),m.current=!1,h({phase:"connecting"}),k("");let b=new EventSource(`/api/auth/login/${encodeURIComponent(a.id)}`);l.current=b,b.onmessage=a=>{let c=JSON.parse(a.data);"auth"===c.type?(h({phase:"auth",url:c.url,instructions:c.instructions??null,token:c.token}),gS(c.url)):"device_code"===c.type?(h({phase:"device_code",userCode:c.userCode,verificationUri:c.verificationUri,intervalSeconds:c.intervalSeconds??null,expiresInSeconds:c.expiresInSeconds??null}),gS(c.verificationUri)):"prompt_request"===c.type?h({phase:"prompt",message:c.message,placeholder:c.placeholder??null,token:c.token}):"select_request"===c.type?h({phase:"select",message:c.message,options:c.options??[],token:c.token}):"progress"===c.type?h({phase:"progress",message:c.message}):"success"===c.type?p():"error"===c.type?(b.close(),h({phase:"error",message:c.message})):"cancelled"===c.type&&(b.close(),h({phase:"idle"}))},b.onerror=()=>{b.close(),h(a=>"success"===a.phase||"auth"===a.phase||"prompt"===a.phase||"select"===a.phase?a:{phase:"error",message:"Connection lost"})}},[a.id,p]),r=(0,e.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(a.id)}`,{method:"POST"}),h({phase:"idle"}),b()},[a.id,b]),s=(0,e.useCallback)(async(b,c,d)=>{h({phase:"progress",message:d});try{let d=await fetch(`/api/auth/login/${encodeURIComponent(a.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:b,code:c})}),e=await d.json().catch(()=>({}));if(!d.ok)return void h({phase:"error",message:e.error??`Server error ${d.status}`});if(k(""),"success"===e.state)return void p();l.current?.readyState===EventSource.CLOSED&&h({phase:"error",message:"Connection lost. Start the login again."})}catch(a){h({phase:"error",message:a instanceof Error?a.message:"Network error"})}},[a.id,p]),t=(0,e.useCallback)(async(a,b)=>{b.trim()&&await s(a,b.trim(),"Verifying…")},[s]),u=(0,e.useCallback)(async(a,b)=>{await s(a,b,"Continuing…")},[s]),v="connecting"===g.phase||"progress"===g.phase||"auth"===g.phase||"device_code"===g.phase||"prompt"===g.phase||"select"===g.phase;return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,d.jsx)(hu,{children:i("i18n.subscription")}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,d.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,d.jsx)("span",{style:{fontSize:11,color:a.loggedIn?"#4ade80":"var(--text-dim)"},children:i(a.loggedIn?"i18n.connected":"i18n.notConnected")})]})]}),c&&(0,d.jsxs)("div",{role:"note","aria-label":i("relogin.title"),style:{display:"flex",alignItems:"flex-start",gap:10,padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg-panel)"},children:[(0,d.jsx)(bU,{seed:c.target.seed,size:32,provider:c.target.provider}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0},children:[(0,d.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:i("relogin.title")}),(0,d.jsxs)("span",{style:{fontSize:13,fontWeight:600,color:"var(--text)",overflowWrap:"anywhere"},children:[c.target.alias,c.target.masked&&(0,d.jsx)("span",{style:{marginLeft:6,fontSize:11,fontWeight:400,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:c.target.masked})]}),c.target.reason&&(0,d.jsx)("span",{style:{fontSize:12,color:"var(--seed-color-fg-critical-contrast)",lineHeight:1.5,overflowWrap:"anywhere"},children:c.target.reason})]})]}),(0,d.jsxs)("div",{style:{minHeight:48},children:["idle"===g.phase&&(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:c?i("relogin.guide",{action:i(a.loggedIn?"i18n.relogin":"i18n.login")}):a.loggedIn?"Already connected. You can re-login or disconnect.":`Connect your ${a.name} account.`}),"connecting"===g.phase&&(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:i("i18n.openingBrowser")}),"select"===g.phase&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:g.message}),(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:g.options.map(a=>(0,d.jsx)("button",{onClick:()=>u(g.token,a.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:a.label},a.id))})]}),("auth"===g.phase||"prompt"===g.phase)&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"auth"===g.phase?"Complete sign-in in the browser. If the last page does not load (for example on a phone), copy its address from the address bar and paste it below.":g.message}),"auth"===g.phase&&(0,d.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:["If the browser window did not open,"," ",(0,d.jsx)("a",{href:g.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:"click here to open the login page"}),"."]}),(0,d.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,d.jsx)("input",{ref:n,value:j,onChange:a=>k(a.target.value),onKeyDown:a=>{"Enter"===a.key&&t(g.token,j)},placeholder:"auth"===g.phase?"Paste the redirect URL or code":g.placeholder??"Enter value…",style:{flex:1,padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",fontFamily:"var(--font-mono)",boxSizing:"border-box"}}),(0,d.jsx)("button",{onClick:()=>t(g.token,j),disabled:!j.trim(),style:{padding:"6px 12px",background:j.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:j.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:j.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,flexShrink:0},children:i("i18n.submit")})]})]}),"device_code"===g.phase&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,d.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:g.userCode}),(0,d.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,d.jsx)("a",{href:g.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:g.verificationUri}),g.expiresInSeconds?` Expires in ${Math.ceil(g.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===g.phase&&(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:g.message}),"success"===g.phase&&(c?(0,d.jsxs)("div",{role:"status",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:i("relogin.done")}),c.outcome&&(0,d.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"recovered"===c.outcome?"var(--seed-color-fg-positive-contrast)":"still-failing"===c.outcome?"var(--seed-color-fg-critical-contrast)":"var(--text-muted)"},children:i(hC[c.outcome],{account:c.target.alias})})]}):(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:i("i18n.connectedSuccessfully")})),"error"===g.phase&&(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:g.message})]}),(0,d.jsx)("div",{style:{display:"flex",gap:8},children:v?(0,d.jsx)("button",{onClick:()=>{l.current?.close(),h({phase:"idle"})},style:{padding:"5px 12px",background:"none",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:i("i18n.cancel")}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("button",{ref:o,onClick:q,style:{padding:"5px 14px",background:"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:5,color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontSize:12,fontWeight:600},children:i(a.loggedIn?"i18n.relogin":"i18n.login")}),a.loggedIn&&!c&&(0,d.jsx)("button",{onClick:r,style:{padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:"pointer",fontSize:12},children:i("i18n.disconnect")})]})})]})}function hE({provider:a,onRefresh:b}){let[c,f]=(0,e.useState)(""),[g,h]=(0,e.useState)(!1),[i,j]=(0,e.useState)(!1),[k,l]=(0,e.useState)(null),[m,n]=(0,e.useState)(!1),{t:o}=(0,x.s)(),p=(0,e.useCallback)(async()=>{if(c.trim()){h(!0),l(null),n(!1);try{let d=await fetch(`/api/auth/api-key/${encodeURIComponent(a.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:c.trim()})}),e=await d.json();!d.ok||e.error?l(e.error??`HTTP ${d.status}`):(f(""),n(!0),setTimeout(()=>n(!1),2e3),b())}catch(a){l(String(a))}finally{h(!1)}}},[c,a.id,b]),q=(0,e.useCallback)(async()=>{j(!0),l(null);try{let c=await fetch(`/api/auth/api-key/${encodeURIComponent(a.id)}`,{method:"DELETE"}),d=await c.json();!c.ok||d.error?l(d.error??`HTTP ${c.status}`):b()}catch(a){l(String(a))}finally{j(!1)}},[a.id,b]);return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,d.jsx)(hu,{children:"API Key"}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,d.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,d.jsx)("span",{style:{fontSize:11,color:a.configured?"#4ade80":"var(--text-dim)"},children:o(a.configured?"i18n.configured":"i18n.notConfigured")})]})]}),(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:a.configured?"API key is stored. Enter a new key below to replace it, or disconnect to remove it.":`Enter your ${a.displayName} API key to enable ${a.modelCount} model${1!==a.modelCount?"s":""}.`}),(0,d.jsx)(hn,{label:"API Key",children:(0,d.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,d.jsx)(hq,{value:c,onChange:f,onKeyDown:a=>{"Enter"===a.key&&c.trim()&&p()},placeholder:a.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,d.jsxs)("button",{onClick:p,disabled:g||!c.trim()||m,style:{padding:"6px 12px",background:m?"#16a34a":c.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:m?"#fff":c.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:g||!c.trim()||m?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[m&&(0,d.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}),o(m?"i18n.saved":g?"i18n.saving":"i18n.save")]})]})}),k&&(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:k}),a.configured&&(0,d.jsx)("button",{onClick:q,disabled:i,style:{alignSelf:"flex-start",padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:i?"not-allowed":"pointer",fontSize:12},children:o(i?"i18n.removing":"i18n.disconnect")})]})}function hF({id:a,size:b}){let c=hl[a];if(!c){let c=a.split(/[-_]/).filter(Boolean).slice(0,2).map(a=>a[0]).join("").toUpperCase()||"?";return(0,d.jsx)("span",{"aria-hidden":"true",style:{width:b,height:b,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*b)),fontWeight:700,lineHeight:1},children:c})}return c.hasColor?(0,d.jsx)(c.Icon,{size:b}):(0,d.jsx)(c.Icon,{size:b,style:{color:"var(--text-muted)"}})}function hG({oauthProviders:a,apiKeyProviders:b,onSelectOAuth:c,onSelectApiKey:f,onAddCustom:g,onClose:h}){let[i,j]=(0,e.useState)(""),{t:k}=(0,x.s)(),l=(0,e.useRef)(null),m=i.trim().toLowerCase(),n=a.filter(a=>!a.loggedIn&&(!m||a.name.toLowerCase().includes(m))),o=b.filter(a=>!a.configured&&(!m||a.displayName.toLowerCase().includes(m)||a.id.toLowerCase().includes(m))),p=!m||"custom".includes(m)||"openai-compatible".includes(m)||"anthropic-compatible".includes(m),q=n.length+o.length+ +!!p,r={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,d.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:a=>{a.target===a.currentTarget&&h()},children:(0,d.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,d.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,d.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,d.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,d.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,d.jsx)("input",{ref:l,value:i,onChange:a=>j(a.target.value),onKeyDown:a=>{"Escape"===a.key&&h()},placeholder:k("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,d.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===q?(0,d.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:k("i18n.noProviders")}):(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[p&&(0,d.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:k("i18n.custom")}),p&&(0,d.jsxs)("button",{onClick:()=>{g(),h()},style:r,onMouseEnter:a=>{a.currentTarget.style.borderColor="var(--accent)",a.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:a=>{a.currentTarget.style.borderColor="var(--border)",a.currentTarget.style.background="var(--bg-panel)"},children:[(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,d.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:k("i18n.customEndpoint")})]}),(0,d.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,d.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,d.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,d.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),n.length>0&&(0,d.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!p,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:k("i18n.subscriptions")}),n.map(a=>(0,d.jsxs)("button",{onClick:()=>{c(a.id),h()},style:r,onMouseEnter:a=>{a.currentTarget.style.borderColor="var(--accent)",a.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:a=>{a.currentTarget.style.borderColor="var(--border)",a.currentTarget.style.background="var(--bg-panel)"},children:[(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.name}),(0,d.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,d.jsx)(hF,{id:a.id,size:28})]},a.id)),o.length>0&&(0,d.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(n.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),o.map(a=>(0,d.jsxs)("button",{onClick:()=>{f(a.id),h()},style:r,onMouseEnter:a=>{a.currentTarget.style.borderColor="var(--accent)",a.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:a=>{a.currentTarget.style.borderColor="var(--border)",a.currentTarget.style.background="var(--bg-panel)"},children:[(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.displayName}),(0,d.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[a.modelCount," models"]})]}),(0,d.jsx)(hF,{id:a.id,size:28})]},a.id))]})})]})})}function hH({cwd:a,onClose:b,embedded:c=!1,onModelsChanged:f,relogin:g}){let h=D(),{t:i}=(0,x.s)(),[j,k]=(0,e.useState)({providers:{}}),[l,m]=(0,e.useState)(!0),[n,o]=(0,e.useState)(!1),[p,q]=(0,e.useState)(null),[r,s]=(0,e.useState)(!1),[t,u]=(0,e.useState)(g?{type:"oauth",providerId:g.target.provider}:{type:"roles"}),[v,w]=(0,e.useState)([]),[y,z]=(0,e.useState)([]),[A,B]=(0,e.useState)(!1),C=(0,e.useCallback)(()=>{fetch("/api/auth/providers").then(a=>a.json()).then(a=>w(a.providers)).catch(()=>{})},[]),E=(0,e.useCallback)(()=>{fetch("/api/auth/all-providers").then(a=>a.json()).then(a=>z(a.providers)).catch(()=>{})},[]),F=(0,e.useCallback)(()=>{C(),E()},[C,E]),G=(0,e.useCallback)(()=>{let a="new-provider",b=1;for(;j.providers?.[a];)a=`new-provider-${b++}`;k(b=>({...b,providers:{...b.providers??{},[a]:{api:"openai-completions"}}})),u({type:"provider",name:a})},[j.providers]),H=(0,e.useCallback)((a,b)=>{k(c=>({...c,providers:{...c.providers??{},[a]:b}}))},[]),I=(0,e.useCallback)((a,b)=>{k(c=>{let d=Object.entries(c.providers??{}),e=d.findIndex(([b])=>b===a);return -1===e?c:(d[e]=[b,d[e][1]],{...c,providers:Object.fromEntries(d)})}),u(c=>c?"provider"===c.type&&c.name===a?{type:"provider",name:b}:"model"===c.type&&c.providerName===a?{...c,providerName:b}:c:c)},[]),J=(0,e.useCallback)(a=>{k(b=>{let c={...b.providers??{}};return delete c[a],{...b,providers:c}}),k(a=>{let b=Object.keys(a.providers??{});return u(b.length>0?{type:"provider",name:b[0]}:null),a})},[]),K=(0,e.useCallback)(a=>{k(b=>{let c=b.providers?.[a]??{},d=[...c.models??[],{id:""}];return{...b,providers:{...b.providers??{},[a]:{...c,models:d}}}}),k(b=>{let c=(b.providers?.[a]?.models?.length??1)-1;return u({type:"model",providerName:a,index:c}),b})},[]),L=(0,e.useCallback)((a,b)=>{k(c=>{let d=c.providers?.[a]??{},e=[...d.models??[]],f=new Set(e.map(a=>a.id));for(let a of b)f.has(a.id)||(f.add(a.id),e.push({id:a.id,name:a.name}));return{...c,providers:{...c.providers??{},[a]:{...d,models:e}}}})},[]),M=(0,e.useCallback)((a,b,c)=>{k(d=>{let e=d.providers?.[a]??{},f=[...e.models??[]];return f[b]=c,{...d,providers:{...d.providers??{},[a]:{...e,models:f}}}})},[]),N=(0,e.useCallback)((a,b)=>{k(c=>{let d=c.providers?.[a]??{},e=[...d.models??[]];return e.splice(b,1),{...c,providers:{...c.providers??{},[a]:{...d,models:e.length?e:void 0}}}}),u({type:"provider",name:a})},[]),O=(0,e.useCallback)(async()=>{o(!0),q(null),s(!1);try{let a=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(j)}),b=await a.json();!a.ok||b.error?q(b.error??`HTTP ${a.status}`):(s(!0),f?.(),setTimeout(()=>s(!1),2e3))}catch(a){q(String(a))}finally{o(!1)}},[j,f]),P=Object.entries(j.providers??{}),Q=v.filter(a=>a.loggedIn),R=y.filter(a=>a.configured),S=(()=>{if(!t)return null;if("roles"===t.type)return(0,d.jsx)(gR,{cwd:a??null,onRolesChanged:f});if("oauth"===t.type){let a=v.find(a=>a.id===t.providerId);return a?(0,d.jsx)(hD,{provider:a,onRefresh:F,relogin:g?.target.provider===a.id?g:void 0},a.id):null}if("apikey"===t.type){let a=y.find(a=>a.id===t.providerId);return a?(0,d.jsx)(hE,{provider:a,onRefresh:F},a.id):null}if("provider"===t.type){let a=j.providers?.[t.name];return a?(0,d.jsx)(hv,{name:t.name,provider:a,onChange:a=>H(t.name,a),onRename:a=>I(t.name,a),onDelete:()=>J(t.name),onAddModels:a=>L(t.name,a)},t.name):null}let b=j.providers?.[t.providerName],c=b?.models?.[t.index];return c?(0,d.jsx)(hB,{providerName:t.providerName,provider:b,model:c,onChange:a=>M(t.providerName,t.index,a),onDelete:()=>N(t.providerName,t.index)},`${t.providerName}-${t.index}`):null})();return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:{position:c?"relative":"fixed",inset:c?void 0:0,width:"100%",height:"100%",zIndex:c?void 0:1e3,background:c?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:a=>{c||a.target!==a.currentTarget||b()},...c?{}:{role:"dialog","aria-modal":!0,"aria-label":i("common.models"),onKeyDown:a=>{"Escape"===a.key&&(a.stopPropagation(),b())}},children:(0,d.jsxs)("div",{style:{width:c?"100%":h?"calc(100vw - 16px)":860,maxWidth:c?"none":"calc(100vw - 16px)",height:c?"100%":h?"calc(100dvh - 16px)":"78vh",maxHeight:c?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:c?"none":"1px solid var(--border)",borderRadius:10*!c,display:"flex",flexDirection:"column",boxShadow:c?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,d.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:i("common.models")}),(0,d.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.omp/agent/models.yml"})]}),(0,d.jsx)("button",{onClick:b,"aria-label":i("i18n.close"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,d.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:h?"column":"row",overflow:"hidden"},children:[(0,d.jsxs)("div",{style:{width:h?"100%":210,maxHeight:h?"40vh":void 0,borderRight:h?"none":"1px solid var(--border)",borderBottom:h?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,d.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[(0,d.jsxs)("div",{onClick:()=>u({type:"roles"}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?.type==="roles"?"var(--bg-selected)":"none"},onMouseEnter:a=>{t?.type!=="roles"&&(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{t?.type!=="roles"&&(a.currentTarget.style.background="none")},children:[(0,d.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-muted)",flexShrink:0},children:[(0,d.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,d.jsx)("circle",{cx:"9",cy:"7",r:"2.2"}),(0,d.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,d.jsx)("circle",{cx:"15",cy:"17",r:"2.2"})]}),(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1},children:i("roles.title")})]}),(0,d.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),Q.map(a=>{let b=t?.type==="oauth"&&t.providerId===a.id;return(0,d.jsxs)("div",{onClick:()=>u({type:"oauth",providerId:a.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:b?"var(--bg-selected)":"none"},onMouseEnter:a=>{b||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{b||(a.currentTarget.style.background="none")},children:[(0,d.jsx)(hF,{id:a.id,size:16}),(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.name})]},a.id)}),R.map(a=>{let b=t?.type==="apikey"&&t.providerId===a.id;return(0,d.jsxs)("div",{onClick:()=>u({type:"apikey",providerId:a.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:b?"var(--bg-selected)":"none"},onMouseEnter:a=>{b||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{b||(a.currentTarget.style.background="none")},children:[(0,d.jsx)(hF,{id:a.id,size:16}),(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.displayName})]},a.id)}),(Q.length>0||R.length>0)&&P.length>0&&(0,d.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),l?(0,d.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:i("i18n.loading")}):P.map(([a,b])=>{let c=t?.type==="provider"&&t.name===a,e=b.models??[];return(0,d.jsxs)("div",{style:{marginBottom:2},children:[(0,d.jsxs)("div",{onClick:()=>u({type:"provider",name:a}),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:c?"var(--bg-selected)":"none"},onMouseEnter:a=>{c||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{c||(a.currentTarget.style.background="none")},children:[(0,d.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,d.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,d.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,d.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,d.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,d.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,d.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,d.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,d.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,d.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,d.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,d.jsx)("span",{style:{fontSize:12,fontWeight:c?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a})]}),e.map((b,c)=>{let e=t?.type==="model"&&t.providerName===a&&t.index===c;return(0,d.jsxs)("div",{onClick:()=>u({type:"model",providerName:a,index:c}),style:{display:"flex",alignItems:"center",gap:6,padding:"5px 8px 5px 26px",borderRadius:5,cursor:"pointer",background:e?"var(--bg-selected)":"none"},onMouseEnter:a=>{e||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{e||(a.currentTarget.style.background="none")},children:[(0,d.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:b.id?"var(--text-muted)":"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b.id||i("i18n.newModel")}),b.reasoning&&(0,d.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"})]},c)}),(0,d.jsx)("div",{onClick:b=>{b.stopPropagation(),K(a)},style:{display:"flex",alignItems:"center",gap:4,padding:"4px 8px 4px 26px",borderRadius:5,cursor:"pointer",color:"var(--text-dim)"},onMouseEnter:a=>{a.currentTarget.style.color="var(--accent)",a.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:a=>{a.currentTarget.style.color="var(--text-dim)",a.currentTarget.style.background="none"},children:(0,d.jsxs)("span",{style:{fontSize:11},children:["+ ",i("i18n.model")]})})]},a)})]}),(0,d.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 6px"},children:(0,d.jsxs)("button",{onClick:()=>B(!0),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:"100%",padding:"6px 0",background:"none",border:"1px dashed var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},onMouseEnter:a=>{a.currentTarget.style.borderColor="var(--accent)",a.currentTarget.style.color="var(--accent)"},onMouseLeave:a=>{a.currentTarget.style.borderColor="var(--border)",a.currentTarget.style.color="var(--text-muted)"},children:["+ ",i("i18n.addProvider")]})})]}),(0,d.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:l?null:S??(0,d.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:i("i18n.selectProviderModel")})})]}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:10,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[p&&(0,d.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:p}),(0,d.jsx)("button",{onClick:b,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:i("i18n.cancel")}),(0,d.jsxs)("button",{onClick:O,disabled:n||r,style:{position:"relative",padding:"6px 16px",minWidth:92,background:r?"#16a34a":n?"var(--bg-panel)":"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:6,color:r?"#fff":n?"var(--text-muted)":"var(--seed-color-fg-neutral-inverted)",cursor:n||r?"default":"pointer",fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,transition:"background-color 0.2s ease, color 0.2s ease",animation:r?"saved-pop 0.45s ease":void 0},children:[r&&(0,d.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:18,animation:"saved-check-draw 0.35s ease forwards",flexShrink:0},children:(0,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,d.jsx)("span",{children:r?i("i18n.saved"):n?i("i18n.saving"):i("i18n.save")})]})]})]})}),A&&(0,d.jsx)(hG,{oauthProviders:v,apiKeyProviders:y,onSelectOAuth:a=>u({type:"oauth",providerId:a}),onSelectApiKey:a=>u({type:"apikey",providerId:a}),onAddCustom:G,onClose:()=>B(!1)})]})}function hI(a){return a.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function hJ(a){let b=a.sourceInfo?.source,c=a.sourceInfo?.scope;return"user"===c||"user"===b?"global":"project"===c||"project"===b?"project":"path"}function hK(a){let b=hJ(a);return"path"===b?b:a.install?.skillsShUrl?`${b} / skills.sh`:b}function hL(a){return a.install?`${a.install.scope}\0${a.install.package}`:null}function hM(a){return a?a.slice(0,8):"unknown"}function hN({enabled:a,loading:b,onToggle:c}){let{t:e}=(0,x.s)();return(0,d.jsx)("button",{onClick:c,disabled:b,title:e(a?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),style:{flexShrink:0,width:40,height:22,borderRadius:11,border:"none",padding:0,cursor:b?"wait":"pointer",background:a?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none"},children:(0,d.jsx)("span",{style:{position:"absolute",top:3,left:a?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function hO({skill:a,cwd:b,onToggle:c,toggling:e,saveError:f,updateStatus:g,checkingUpdate:h,updating:i,updateError:j,onCheckUpdate:k,onUpdate:l}){let{t:m}=(0,x.s)(),n=hJ(a),o=!a.disableModelInvocation;return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7},children:[(0,d.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===n?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===n?"rgba(99,102,241,0.8)":"var(--text-dim)"},children:n}),(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:function(a){if("project"===n&&a.startsWith(b)){let c=a.slice(b.length).replace(/^[/\\]/,"");return`./${c}`}return hI(a)}(a.filePath)}),(0,d.jsx)(hN,{enabled:o,loading:e,onToggle:()=>c(a)})]}),(0,d.jsxs)("div",{style:{minHeight:16,display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,flexWrap:"wrap",textAlign:"right"},children:[!o&&(0,d.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:m("i18n.hiddenButInvocable")}),f&&(0,d.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:f})]})]}),a.install?.skillsShUrl&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Source"}),(0,d.jsx)("a",{href:a.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:a.install.skillsShUrl,style:{display:"flex",alignItems:"center",gap:8,width:"fit-content",maxWidth:"100%",color:"var(--accent)",textDecoration:"none"},children:(0,d.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[a.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})]}),a.install&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Version"}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text-muted)"},children:hM(g?.currentVersion??a.install.versionHash)}),a.install.canCheckForUpdates&&(0,d.jsx)("button",{onClick:k,disabled:h||i,style:{padding:"4px 9px",border:"1px solid var(--border)",borderRadius:5,background:"none",color:"var(--text-muted)",cursor:h||i?"not-allowed":"pointer",opacity:h||i?.5:1,fontSize:11},children:m("i18n.check")}),g?.state==="update-available"&&(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"#d97706"},children:hM(g.latestVersion)}),(h||g&&"update-available"!==g.state)&&(0,d.jsx)("span",{style:{fontSize:12,color:h?"var(--accent)":g?.state==="up-to-date"?"#16a34a":g?.state==="error"?"#ef4444":"var(--text-dim)"},children:h?m("i18n.checking"):g?.state==="up-to-date"?m("i18n.upToDate"):g?.state==="unsupported"?m("i18n.automaticChecksUnavailable"):g?.message||m("i18n.checkFailed")}),g?.state==="update-available"&&(0,d.jsx)("button",{onClick:l,disabled:i||h,style:{padding:"4px 10px",border:"none",borderRadius:5,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:i||h?"not-allowed":"pointer",opacity:i||h?.5:1,fontSize:11,fontWeight:600},children:m(i?"i18n.updating":"i18n.update")})]}),j&&(0,d.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:j})]}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Name"}),(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:14,color:"var(--text)"},children:a.name})]}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Description"}),(0,d.jsx)("span",{style:{fontSize:14,color:"var(--text-muted)",lineHeight:1.6},children:a.description})]})]})}function hP({cwd:a,installedPackages:b,projectResourcesLoaded:c,onInstalled:f}){let{t:g}=(0,x.s)(),[h,i]=(0,e.useState)(""),[j,k]=(0,e.useState)([]),[l,m]=(0,e.useState)(!1),[n,o]=(0,e.useState)(null),[p,q]=(0,e.useState)(null),[r,s]=(0,e.useState)(null),[t,u]=(0,e.useState)(new Set),[v,w]=(0,e.useState)("global"),y=(0,e.useRef)(null),z=(0,e.useCallback)(async a=>{if(a.trim()){m(!0),o(null),k([]);try{let b=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:a.trim()})}),c=await b.json();if(c.error)return void o(c.error);k(c.results??[]),0===(c.results??[]).length&&o("No skills found")}catch(a){o(String(a))}finally{m(!1)}}},[]),A=(0,e.useCallback)(async b=>{q(b),s(null);try{let c=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:b,scope:v,cwd:a})}),d=await c.json();if(!c.ok||d.error)return void s(d.error??`HTTP ${c.status}`);u(a=>new Set(a).add(`${v}:${b}`)),f()}catch(a){s(String(a))}finally{q(null)}},[f,v,a]),B="global"===v?"~/.claude/skills/":`${hI(a)}/.claude/skills/`;return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,d.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:g("i18n.addSkill")}),(0,d.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,d.jsx)("input",{ref:y,value:h,onChange:a=>i(a.target.value),onKeyDown:a=>{"Enter"===a.key&&z(h)},placeholder:g("i18n.skillSearchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:13,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",outline:"none"}}),(0,d.jsx)("button",{onClick:()=>z(h),disabled:l||!h.trim(),style:{padding:"7px 16px",fontSize:13,borderRadius:6,border:"none",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:l||!h.trim()?"not-allowed":"pointer",opacity:l||!h.trim()?.5:1,flexShrink:0},children:l?g("i18n.searching"):g("i18n.search")})]}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,d.jsx)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(a=>(0,d.jsx)("button",{onClick:()=>{("global"===a||c)&&w(a)},disabled:"project"===a&&!c,title:"project"!==a||c?void 0:g("trust.projectScopeUnavailable"),style:{padding:"3px 10px",border:"none",cursor:"project"!==a||c?"pointer":"not-allowed",background:v===a?"var(--bg-selected)":"none",color:v===a?"var(--text)":"var(--text-dim)",fontWeight:v===a?600:400,opacity:"project"!==a||c?1:.45,borderRight:"global"===a?"1px solid var(--border)":"none"},children:a},a))}),(0,d.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",B]})]}),n&&(0,d.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:n}),r&&(0,d.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:r})]}),j.length>0?(0,d.jsx)("div",{style:{flex:1,overflowY:"auto"},children:j.map(a=>{let c=b[v].has(a.package)||t.has(`${v}:${a.package}`),e=p===a.package,f=a.package.indexOf("@"),h=f>-1?a.package.slice(0,f):a.package,i=f>-1?a.package.slice(f+1):null;return(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:i??h}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:h}),(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:a.installs}),a.url&&(0,d.jsx)("a",{href:a.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,d.jsx)("button",{onClick:()=>!c&&!e&&A(a.package),disabled:c||e||null!==p,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:5,border:"1px solid var(--border)",cursor:c||e||null!==p?"not-allowed":"pointer",background:c?"rgba(34,197,94,0.1)":"none",color:c?"#16a34a":e?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:c?`✓ ${g("i18n.installed")}`:e?g("i18n.installing"):g("i18n.install")})]},a.package)})}):!n&&!l&&(0,d.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:["Search"," ",(0,d.jsx)("a",{href:"https://skills.sh",target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",textDecoration:"none"},children:"skills.sh"})," ","to discover and install skills for your agent."]})]})}function hQ({cwd:a,onClose:b,embedded:c=!1}){let f=D(),{t:g}=(0,x.s)(),[h,i]=(0,e.useState)([]),[j,k]=(0,e.useState)(!0),[l,m]=(0,e.useState)(null),[n,o]=(0,e.useState)(null),[p,q]=(0,e.useState)(new Set),[r,s]=(0,e.useState)(null),[t,u]=(0,e.useState)(!1),[v,w]=(0,e.useState)({}),[y,z]=(0,e.useState)(new Set),[A,B]=(0,e.useState)(!1),[C,E]=(0,e.useState)(null),[F,G]=(0,e.useState)(null),[H,I]=(0,e.useState)(!0),[J,K]=(0,e.useState)({}),L=(0,e.useCallback)(async()=>{k(!0),m(null);try{let b=await fetch(`/api/skills?cwd=${encodeURIComponent(a)}`),c=await b.json();if(!b.ok||c.error)throw Error(c.error??`HTTP ${b.status}`);let d=c.skills??[];if(i(d),I(c.projectResourcesLoaded??!0),d.length>0&&!n){let a=d.find(a=>!a.disableModelInvocation)??d[0];o(a.filePath),a.disableModelInvocation&&K(b=>({...b,[hK(a)]:!0}))}return d}catch(a){return m(String(a)),[]}finally{k(!1)}},[a,n]),M=(0,e.useCallback)(async b=>{let c=(b?[b]:h.filter(a=>!!a.install)).map(hL).filter(a=>!!a);if(0!==c.length){G(null),z(a=>new Set([...a,...c])),b||B(!0);try{let c=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:a,package:b?.install?.package,scope:b?.install?.scope})}),d=await c.json();if(!c.ok||d.error)throw Error(d.error??`HTTP ${c.status}`);w(a=>{let b={...a};for(let a of d.updates??[])b[`${a.scope}\0${a.package}`]=a;return b})}catch(a){G(a instanceof Error?a.message:String(a))}finally{z(a=>{let b=new Set(a);for(let a of c)b.delete(a);return b}),b||B(!1)}}},[a,h]),N=(0,e.useCallback)(async b=>{if(!b.install)return;let c=hL(b);E(c),G(null);try{let d=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:a,package:b.install.package,scope:b.install.scope})}),e=await d.json();if(!d.ok||e.error||!e.success)throw Error(e.error??`HTTP ${d.status}`);await L();let f=e.skill?.install?.versionHash;w(a=>({...a,[c]:{package:b.install.package,scope:b.install.scope,state:"up-to-date",currentVersion:f,latestVersion:f}}))}catch(a){G(a instanceof Error?a.message:String(a))}finally{E(null)}},[a,L]),O=(0,e.useCallback)(async a=>{let b=!a.disableModelInvocation;q(b=>new Set(b).add(a.filePath)),s(null);try{let c=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:a.filePath,disableModelInvocation:b})}),d=await c.json();if(!c.ok||d.error)return void s(d.error??`HTTP ${c.status}`);i(c=>c.map(c=>c.filePath===a.filePath?{...c,disableModelInvocation:b}:c)),b&&K(b=>({...b,[hK(a)]:!0}))}catch(a){s(String(a))}finally{q(b=>{let c=new Set(b);return c.delete(a.filePath),c})}},[]),P=h.find(a=>a.filePath===n)??null;return(0,d.jsx)("div",{style:{position:c?"relative":"fixed",inset:c?void 0:0,width:"100%",height:"100%",zIndex:c?void 0:1e3,background:c?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:a=>{c||a.target!==a.currentTarget||b()},children:(0,d.jsxs)("div",{style:{width:c?"100%":f?"calc(100vw - 16px)":860,maxWidth:c?"none":"calc(100vw - 16px)",height:c?"100%":f?"calc(100dvh - 16px)":"78vh",maxHeight:c?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:c?"none":"1px solid var(--border)",borderRadius:10*!c,display:"flex",flexDirection:"column",boxShadow:c?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,d.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:g("common.skills")}),(0,d.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:hI(a)})]}),(0,d.jsx)("button",{onClick:b,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!H&&(0,d.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:g("trust.skillsNotLoaded")}),(0,d.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:f?"column":"row",overflow:"hidden"},children:[(0,d.jsxs)("div",{style:{width:f?"100%":210,maxHeight:f?"40vh":void 0,borderRight:f?"none":"1px solid var(--border)",borderBottom:f?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,d.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:j?(0,d.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:g("i18n.loading")}):l?(0,d.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#f87171"},children:l}):0===h.length?(0,d.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:g("i18n.noSkills")}):(()=>{let a=[];for(let{label:b,matches:c}of[{label:"project / skills.sh",matches:a=>"project"===hJ(a)&&!!a.install?.skillsShUrl},{label:"project",matches:a=>"project"===hJ(a)&&!a.install?.skillsShUrl},{label:"global / skills.sh",matches:a=>"global"===hJ(a)&&!!a.install?.skillsShUrl},{label:"global",matches:a=>"global"===hJ(a)&&!a.install?.skillsShUrl},{label:"path",matches:a=>"path"===hJ(a)}]){let d=h.filter(c);d.length>0&&a.push({label:b,skills:d})}let b=a=>{let b,c,e=!t&&n===a.filePath,f=a.disableModelInvocation;return(0,d.jsxs)("div",{onClick:()=>{o(a.filePath),u(!1)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:e?"var(--bg-selected)":"none"},onMouseEnter:a=>{e||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{e||(a.currentTarget.style.background="none")},children:[(0,d.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:f?"var(--border)":"var(--accent)",boxShadow:f?"none":"0 0 4px var(--accent)",transition:"background 0.15s, box-shadow 0.15s"}}),(0,d.jsx)("span",{style:{fontSize:12,fontWeight:e?600:400,color:f?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.name}),(c=(b=hL(a))?v[b]:void 0,c?.state!=="update-available"?null:(0,d.jsx)("span",{title:g("i18n.updateAvailable"),style:{color:"#d97706",fontSize:13,lineHeight:1,flexShrink:0},children:"↑"}))]},a.filePath)};return a.map(({label:a,skills:c})=>{let e=c.filter(a=>!a.disableModelInvocation),f=c.filter(a=>a.disableModelInvocation),h=J[a]??!1;return(0,d.jsxs)("div",{style:{marginBottom:6},children:[(0,d.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em"},children:a}),e.map(b),f.length>0&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{onClick:()=>K(b=>({...b,[a]:!h})),style:{display:"flex",alignItems:"center",gap:5,padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",cursor:"pointer",userSelect:"none"},children:[(0,d.jsx)("span",{style:{fontSize:8},children:h?"▾":"▸"}),g("i18n.dormant")," (",f.length,")"]}),h&&f.map(b)]})]},a)})})()}),(0,d.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,d.jsxs)("div",{onClick:()=>u(!0),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none",color:t?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:a=>{t||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{t||(a.currentTarget.style.background="none")},children:[(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,d.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),g("i18n.addSkill")]})})]}),(0,d.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:t?(0,d.jsx)(hP,{cwd:a,projectResourcesLoaded:H,installedPackages:{global:new Set(h.filter(a=>a.install?.scope==="global").map(a=>a.install.package)),project:new Set(h.filter(a=>a.install?.scope==="project").map(a=>a.install.package))},onInstalled:()=>{L()}}):j?null:P?(0,d.jsx)(hO,{skill:P,cwd:a,onToggle:O,toggling:p.has(P.filePath),saveError:r,updateStatus:hL(P)?v[hL(P)]:void 0,checkingUpdate:!!hL(P)&&y.has(hL(P)),updating:C===hL(P),updateError:F,onCheckUpdate:()=>void M(P),onUpdate:()=>void N(P)},P.filePath):(0,d.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:g("i18n.selectSkill")})})]}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[h.some(a=>!!a.install)&&(0,d.jsx)("button",{onClick:()=>void M(),disabled:A||null!==C,style:{padding:"6px 12px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:A||null!==C?"not-allowed":"pointer",opacity:A||null!==C?.5:1,fontSize:12},children:A?g("i18n.checking"):g("i18n.checkUpdates")}),Object.values(v).filter(a=>"update-available"===a.state).length>0&&(0,d.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(v).filter(a=>"update-available"===a.state).length," ",1===Object.values(v).filter(a=>"update-available"===a.state).length?g("i18n.update"):g("i18n.updates")]})]}),(0,d.jsx)("button",{onClick:b,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:g("i18n.close")})]})]})})}let hR="global";function hS(a){return a.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function hT(a){let b=a.trim().match(/^\$?\s*omp\s+plugin\s+(?:add|install)\s+(\S+)\s*$/);return b?.[1]??a}function hU(a){return`${a.scope}\0${a.source}`}function hV(a,b){if(a.disabled)return b("i18n.disabled");let c=[a.counts.extensions?b("i18n.resourceCount",{count:a.counts.extensions,label:b("i18n.extensionShort")}):"",a.counts.skills?b("i18n.resourceCount",{count:a.counts.skills,label:b("i18n.skillShort")}):"",a.counts.prompts?b("i18n.resourceCount",{count:a.counts.prompts,label:b("i18n.promptShort")}):"",a.counts.themes?b("i18n.resourceCount",{count:a.counts.themes,label:b("i18n.themeShort")}):""].filter(Boolean);return c.length?c.join(" \xb7 "):b("i18n.noResources")}function hW(a,b){let c=[];return a.version&&c.push(b("i18n.installedVersion",{version:a.version})),a.configuredVersion&&c.push(b("i18n.configuredVersion",{version:a.configuredVersion})),c.length?c.join(" \xb7 "):b("i18n.unknown")}function hX(a){return"loaded"===a?"var(--accent)":"installed"===a?"#f59e0b":"disabled"===a?"var(--text-dim)":"#ef4444"}function hY({pkg:a}){let{t:b}=(0,x.s)(),c=[["extension",b("i18n.extensions")],["skill",b("i18n.skills")],["prompt",b("i18n.prompts")],["theme",b("i18n.themes")]].map(([b,c])=>({kind:b,label:c,resources:a.resources.filter(a=>a.kind===b)})).filter(a=>a.resources.length>0);return 0===c.length?(0,d.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:b(a.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:c.map((a,b)=>(0,d.jsxs)("div",{style:{borderTop:0===b?"none":"1px solid var(--border)",paddingTop:12*(0!==b)},children:[(0,d.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:a.label}),(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:a.resources.map(a=>(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:a.path,children:a.name}),(0,d.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:a.path,children:a.relativePath})]},`${a.kind}:${a.path}`))})]},a.kind))})}function hZ({scope:a}){return(0,d.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===a?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===a?"rgba(99,102,241,0.85)":"var(--text-dim)"},children:a})}function h$(a,b){return{padding:"6px 12px",background:b?"rgba(239,68,68,0.08)":"none",border:"1px solid var(--border)",borderRadius:6,color:b?"#ef4444":"var(--text-muted)",cursor:a?"not-allowed":"pointer",fontSize:12,opacity:a?.5:1}}function h_({enabled:a,loading:b,onToggle:c,label:e}){return(0,d.jsx)("button",{type:"button",onClick:c,disabled:b,title:e,"aria-label":e,"aria-pressed":a,style:{flexShrink:0,width:40,height:22,borderRadius:11,border:"none",padding:0,cursor:b?"wait":"pointer",background:a?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none",opacity:b?.65:1},children:(0,d.jsx)("span",{style:{position:"absolute",top:3,left:a?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function h0({installDir:a,source:b,busy:c,actionError:f,onSourceChange:g,onInstall:h}){let{t:i}=(0,x.s)(),j=(0,e.useRef)(null);return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:660,minHeight:"100%"},children:[(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,d.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:i("i18n.addPlugin")}),(0,d.jsxs)("a",{href:"https://github.com/can1357/oh-my-pi#plugins",target:"_blank",rel:"noopener noreferrer",style:{display:"inline-flex",alignItems:"center",gap:5,color:"var(--accent)",fontSize:12,textDecoration:"none",whiteSpace:"nowrap"},children:[(0,d.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",style:{flexShrink:0},children:[(0,d.jsx)("path",{fill:"#000",fillRule:"evenodd",d:"M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"}),(0,d.jsx)("path",{fill:"#000",d:"M517.36 400H634.72V634.72H517.36Z"})]}),"oh-my-pi plugins"]})]}),a&&(0,d.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:hS(a)})]}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,d.jsx)("label",{htmlFor:"plugin-source",style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Source"}),(0,d.jsx)("input",{id:"plugin-source",ref:j,value:b,onChange:a=>g(a.target.value),onPaste:a=>{let b=a.clipboardData.getData("text"),c=hT(b);c!==b&&(a.preventDefault(),g(c))},onBlur:a=>g(hT(a.currentTarget.value)),placeholder:"@scope/package or github:user/repo",style:{width:"100%",height:36,padding:"0 11px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,outline:"none"},onKeyDown:a=>{"Enter"===a.key&&b.trim()&&!c&&h()}})]}),(0,d.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:(0,d.jsx)("button",{type:"button",onClick:h,disabled:c||!b.trim(),style:{...h$(c||!b.trim()),background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",borderColor:"transparent"},children:i(c?"i18n.installing":"i18n.install")})}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,d.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Examples"}),(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:["@scope/omp-plugin","github:user/repo","pkg[feature]"].map(a=>(0,d.jsx)("button",{type:"button",onClick:()=>g(a),style:{width:"100%",minHeight:30,textAlign:"left",padding:"6px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"pointer",fontFamily:"var(--font-mono)",fontSize:11},onMouseEnter:a=>{a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color="var(--text-muted)"},onMouseLeave:a=>{a.currentTarget.style.background="var(--bg-panel)",a.currentTarget.style.color="var(--text-dim)"},children:a},a))})]}),f&&(0,d.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:f})]})}function h1({pkg:a,cwd:b,busyKey:c,actionError:e,actionMessage:f,sessionId:g,onAction:h,onReloadSession:i}){let{t:j}=(0,x.s)(),k=hU(a),l=c?.endsWith(k)??!1,m="reload"===c,n=!a.disabled;return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20,maxWidth:680},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,minWidth:0,flexWrap:"wrap"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:180,flex:1},children:[(0,d.jsx)(h_,{enabled:n,loading:l||m,onToggle:()=>h(a.disabled?"enable":"disable",a),label:j(a.disabled?"i18n.enablePackage":"i18n.disablePackage")}),(0,d.jsx)(hZ,{scope:a.scope}),a.disabled?(0,d.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:j("i18n.disabled")}):a.filtered&&(0,d.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:j("i18n.filtered")}),(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.source})]}),(0,d.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[(0,d.jsx)("button",{onClick:()=>h("update",a),disabled:l||m,style:h$(l||m),children:j(c===`update:${k}`?"i18n.updating":"i18n.update")}),(0,d.jsx)("button",{onClick:i,disabled:!g||m||l,style:h$(!g||m||l),title:j(g?"i18n.reloadSessionHint":"i18n.openSessionToReload"),children:j(m?"i18n.reloading":"i18n.reloadSession")}),(0,d.jsx)("button",{onClick:()=>h("remove",a),disabled:l||m,style:h$(l||m,!0),children:j(c===`remove:${k}`?"i18n.removing":"i18n.remove")})]})]}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,d.jsx)("div",{style:{color:"var(--text-dim)"},children:j("i18n.status")}),(0,d.jsx)("div",{style:{color:hX(a.status),textTransform:"capitalize"},children:a.status}),(0,d.jsx)("div",{style:{color:"var(--text-dim)"},children:j("i18n.version")}),(0,d.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:hW(a,j)}),(0,d.jsx)("div",{style:{color:"var(--text-dim)"},children:j("i18n.package")}),(0,d.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:a.packageName??j("i18n.unknown")}),(0,d.jsx)("div",{style:{color:"var(--text-dim)"},children:j("i18n.resources")}),(0,d.jsx)("div",{style:{color:"var(--text-muted)"},children:hV(a,j)}),(0,d.jsx)("div",{style:{color:"var(--text-dim)"},children:j("i18n.installedPath")}),(0,d.jsx)("div",{style:{color:a.installedPath?"var(--text-muted)":"#ef4444",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:a.installedPath?hS(a.installedPath):j("i18n.notFound")}),(0,d.jsx)("div",{style:{color:"var(--text-dim)"},children:j("i18n.cwd")}),(0,d.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:hS(b)})]}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,d.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)"},children:j("i18n.resolvedResources")}),(0,d.jsx)(hY,{pkg:a})]}),f&&(0,d.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:f}),e&&(0,d.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:e})]})}function h2({cwd:a,sessionId:b,onClose:c,onReloaded:f,embedded:g=!1}){let h=D(),{t:i}=(0,x.s)(),[j,k]=(0,e.useState)(null),[l,m]=(0,e.useState)(!0),[n,o]=(0,e.useState)(null),[p,q]=(0,e.useState)(null),[r,s]=(0,e.useState)(!1),[t,u]=(0,e.useState)(""),[v,w]=(0,e.useState)(null),[y,z]=(0,e.useState)(null),[A,B]=(0,e.useState)(null),C=(0,e.useMemo)(()=>j?.packages??[],[j?.packages]),E=C.find(a=>hU(a)===p)??null,F=j?.projectResourcesLoaded??!0,G=(0,e.useMemo)(()=>["project","global"].map(a=>({scope:a,packages:C.filter(b=>b.scope===a)})).filter(a=>a.packages.length>0),[C]),H=(0,e.useCallback)(async()=>{m(!0),o(null);try{let b=await fetch(`/api/plugins?cwd=${encodeURIComponent(a)}`),c=await b.json();if(!b.ok||c.error)throw Error(c.error??`HTTP ${b.status}`);k(c),s(a=>0===c.packages.length||a),q(a=>a&&c.packages.some(b=>hU(b)===a)?a:c.packages[0]?hU(c.packages[0]):null)}catch(a){o(a instanceof Error?a.message:String(a))}finally{m(!1)}},[a]),I=(0,e.useCallback)(async(b,c)=>{let d=hU(c);w(`${b}:${d}`),z(null),B(null);try{let d=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:b,source:c.source,scope:c.scope,cwd:a})}),e=await d.json();if(!d.ok||e.error)throw Error(e.error??`HTTP ${d.status}`);if(k(e),"remove"===b)q(e.packages[0]?hU(e.packages[0]):null),0===e.packages.length&&s(!0),B(i("i18n.packageRemoved"));else{let a={install:i("i18n.packageInstalled"),update:i("i18n.packageUpdated"),disable:i("i18n.packageDisabledRestartRequired"),enable:i("i18n.packageEnabled")};B(a[b])}}catch(a){z(a instanceof Error?a.message:String(a))}finally{w(null)}},[a,i]),J=(0,e.useCallback)(async()=>{let b=hT(t).trim();if(!b)return;u(b);let c=`${hR}\0${b}`;w(`install:${c}`),z(null),B(null);try{var d;let e,f,g=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:b,scope:hR,cwd:a})}),h=await g.json();if(!g.ok||h.error)throw Error(h.error??`HTTP ${g.status}`);k(h);let j=(d=h.packages,f=(e=b.trim()).startsWith("npm:")?e.slice(4):e,d.find(a=>a.scope===hR&&a.source===e)??d.find(a=>a.scope===hR&&a.source===`npm:${f}`)??d.find(a=>a.scope===hR&&a.source.endsWith(e)));q(j?hU(j):c),s(!1),u(""),B(i("i18n.packageInstalled"))}catch(a){z(a instanceof Error?a.message:String(a))}finally{w(null)}},[a,t,i]),K=(0,e.useCallback)(async()=>{if(b){w("reload"),z(null),B(null);try{await fK(b,{type:"reload"}),f?.(),await H(),B(i("i18n.sessionReloaded"))}catch(a){z(a instanceof Error?a.message:String(a))}finally{w(null)}}},[H,f,b,i]),L=v?.startsWith("install:")??!1;return(0,d.jsx)("div",{style:{position:g?"relative":"fixed",inset:g?void 0:0,width:"100%",height:"100%",zIndex:g?void 0:1e3,background:g?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:a=>{g||a.target!==a.currentTarget||c()},children:(0,d.jsxs)("div",{style:{width:g?"100%":h?"calc(100vw - 16px)":860,maxWidth:g?"none":"calc(100vw - 16px)",height:g?"100%":h?"calc(100dvh - 16px)":"76vh",maxHeight:g?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:g?"none":"1px solid var(--border)",borderRadius:8*!g,display:"flex",flexDirection:"column",boxShadow:g?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,d.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:i("common.plugins")}),(0,d.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:hS(a)})]}),(0,d.jsx)("button",{onClick:c,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!F&&(0,d.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:i("trust.pluginsNotLoaded")}),(0,d.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:h?"column":"row",overflow:"hidden"},children:[(0,d.jsxs)("div",{style:{width:h?"100%":245,maxHeight:h?"40vh":void 0,borderRight:h?"none":"1px solid var(--border)",borderBottom:h?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,d.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:l?(0,d.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:"Loading..."}):n?(0,d.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#ef4444"},children:n}):0===C.length?(0,d.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:"No plugins configured"}):G.map(a=>(0,d.jsxs)("div",{style:{marginBottom:6},children:[(0,d.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase"},children:a.scope}),a.packages.map(a=>{let b=hU(a),c=!r&&p===b;return(0,d.jsxs)("div",{onClick:()=>{q(b),s(!1),z(null),B(null)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:c?"var(--bg-selected)":"none"},onMouseEnter:a=>{c||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{c||(a.currentTarget.style.background="none")},children:[(0,d.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:hX(a.status)}}),(0,d.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,d.jsx)("div",{style:{fontSize:12,fontWeight:c?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.source}),(0,d.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:hV(a,i)}),(a.version||a.configuredVersion)&&(0,d.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:hW(a,i)})]})]},b)})]},a.scope))}),(0,d.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,d.jsxs)("button",{type:"button",onClick:()=>{s(!0),z(null),B(null)},style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,border:"none",width:"100%",cursor:"pointer",background:r?"var(--bg-selected)":"none",color:r?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:a=>{r||(a.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:a=>{r||(a.currentTarget.style.background="none")},children:[(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,d.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),i("i18n.addPlugin")]})})]}),(0,d.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:r?(0,d.jsx)(h0,{installDir:j?.installDir,source:t,busy:L,actionError:y,onSourceChange:u,onInstall:J}):l?null:E?(0,d.jsx)(h1,{pkg:E,cwd:a,busyKey:v,actionError:y,actionMessage:A,sessionId:b,onAction:I,onReloadSession:K},hU(E)):(0,d.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:i("i18n.selectPackage")})})]}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,d.jsx)("div",{style:{minWidth:0,flex:1,fontSize:11,color:"var(--text-dim)",overflow:"hidden"},children:j?.diagnostics.length?(0,d.jsxs)("span",{title:j.diagnostics.map(a=>`${a.type}: ${a.source?`${a.source}: `:""}${a.message}`).join("\n"),style:{color:j.diagnostics.some(a=>"error"===a.type)?"#ef4444":"#d97706"},children:[j.diagnostics.length," diagnostic",1===j.diagnostics.length?"":"s"]}):(0,d.jsx)("span",{children:j?`${j.totals.extensions} ext \xb7 ${j.totals.skills} skills \xb7 ${j.totals.prompts} prompts \xb7 ${j.totals.themes} themes`:""})}),(0,d.jsx)("button",{onClick:()=>void H(),disabled:l||null!==v,style:h$(l||null!==v),children:i("i18n.refresh")}),(0,d.jsx)("button",{onClick:c,style:h$(!1),children:i("i18n.close")})]})]})})}var h3=c(84431),h4=c.n(h3);function h5(){let[a,b]=(0,e.useState)(null),[c,f]=(0,e.useState)(null),[g,h]=(0,e.useState)(null),[i,j]=(0,e.useState)(null),[k,l]=(0,e.useState)(!1),[m,n]=(0,e.useState)(""),[o,p]=(0,e.useState)("");(0,e.useCallback)(async()=>{try{let a=await fetch("/api/web-access",{cache:"no-store"}),c=await a.json();if(!a.ok||c.error)throw Error(c.error??`HTTP ${a.status}`);b(c),f(null)}catch(a){f(a instanceof Error?a.message:String(a))}},[]);let q=(0,e.useCallback)(async(a,c={})=>{l(!0),h(null),j(null);try{let d=await fetch("/api/web-access",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:a,...c})}),e=await d.json();if(!d.ok||e.error)throw Error(e.error??`HTTP ${d.status}`);return b(e),e}catch(a){return h(a instanceof Error?a.message:String(a)),null}finally{l(!1)}},[]),r=(0,e.useCallback)(async()=>{if(m!==o)return void h("The two passwords do not match.");let a=await q("set-password",{password:m});a&&(n(""),p(""),j(`Password saved and password access turned on. The browser will ask for the username "${a.username}" and this password on the next request.`))},[o,m,q]),s=(0,e.useCallback)(async()=>{if(!a)return;let b=await q(a.enabled?"disable":"enable");b&&j(b.enabled?`Password access is on. The browser will ask for the username "${b.username}" and your password on the next request.`:"Password access is off. The stored password is kept and can be switched back on here.")},[q,a]),t=(0,e.useCallback)(async()=>{await q("clear")&&j("The stored password was removed and password access is off.")},[q]);if(!a)return(0,d.jsx)("div",{className:h4().empty,children:c??"Loading password access…"});let u=a.managedByEnvironment,v=!k&&!u&&m.length>=8&&m===o;return(0,d.jsxs)("div",{className:h4().scrollContent,children:[(0,d.jsxs)("header",{className:h4().contentHeader,children:[(0,d.jsx)("h2",{className:h4().contentTitle,children:"Access"}),(0,d.jsxs)("p",{className:h4().contentDescription,children:["A password locks the web interface and every API endpoint behind HTTP Basic Auth, with the fixed username ",(0,d.jsx)("code",{children:a.username}),". It is stored as a scrypt hash in ",(0,d.jsx)("code",{children:a.file})," — CUELO never keeps the password itself, which is why forgetting it means recovering rather than reading it back."]}),u&&(0,d.jsxs)("div",{className:h4().readOnlyNotice,children:["Read-only \xb7 ",(0,d.jsx)("code",{children:"CUELO_PASSWORD"})," is set and overrides the stored credential. Unset it and restart CUELO to manage the password here."]}),i&&(0,d.jsx)("div",{className:h4().reloadNotice,children:(0,d.jsx)("span",{children:i})})]}),(0,d.jsxs)("div",{className:h4().settingsBody,children:[(0,d.jsxs)("section",{className:h4().group,children:[(0,d.jsx)("h3",{className:h4().groupTitle,children:"Password access"}),(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:h4().settingLabel,children:"Require a password"}),(0,d.jsx)("div",{className:h4().settingDescription,children:a.managedByEnvironment?"Every request needs the password from CUELO_PASSWORD.":a.unreadable?"The credential file exists but could not be read, so every request is being refused.":a.configured?a.enabled?"Every request needs the username and password.":"A password is stored but the lock is off.":"No password is set. Anyone who can reach this server can use it."}),!a.configured&&!u&&(0,d.jsx)("div",{className:h4().settingDescription,children:"Set a password below before turning this on."}),g&&(0,d.jsx)("div",{className:h4().error,children:g})]}),(0,d.jsx)("div",{className:h4().settingControl,children:(0,d.jsx)("button",{type:"button",className:h4().switch,"data-on":a.enabled,"aria-pressed":a.enabled,"aria-label":"Require a password",disabled:k||u||!a.enabled&&!a.stored,onClick:()=>void s()})})]})]}),(0,d.jsxs)("section",{className:h4().group,children:[(0,d.jsx)("h3",{className:h4().groupTitle,children:a.stored?"Replace the password":"Set a password"}),(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:h4().settingLabel,children:"New password"}),(0,d.jsxs)("div",{className:h4().settingDescription,children:["At least ",8," characters. Saving a password also turns password access on."]})]}),(0,d.jsx)("div",{className:h4().settingControl,children:(0,d.jsx)("input",{className:h4().textInput,type:"password",autoComplete:"new-password",value:m,disabled:k||u,onChange:a=>n(a.target.value)})})]}),(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:h4().settingLabel,children:"Confirm password"}),(0,d.jsx)("div",{className:h4().settingDescription,children:"Both entries have to match before it can be saved."})]}),(0,d.jsx)("div",{className:h4().settingControl,children:(0,d.jsx)("input",{className:h4().textInput,type:"password",autoComplete:"new-password",value:o,disabled:k||u,onChange:a=>p(a.target.value),onKeyDown:a=>{"Enter"===a.key&&v&&r()}})})]}),(0,d.jsxs)("div",{className:h4().editorActions,children:[(0,d.jsx)("div",{children:(0,d.jsx)("div",{className:h4().saveState,children:a.stored&&a.updatedAt?`Last changed ${new Date(a.updatedAt).toLocaleString()}`:"No password stored yet"})}),(0,d.jsxs)("div",{style:{display:"flex",gap:8},children:[a.stored&&!u&&(0,d.jsx)("button",{type:"button",className:h4().dangerButton,disabled:k,onClick:()=>void t(),children:"Remove password"}),(0,d.jsx)("button",{type:"button",className:h4().primaryButton,disabled:!v,onClick:()=>void r(),children:k?"Saving…":"Save password"})]})]})]}),(0,d.jsxs)("section",{className:h4().group,children:[(0,d.jsx)("h3",{className:h4().groupTitle,children:"If you forget it"}),(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:h4().settingLabel,children:"Recovery"}),(0,d.jsxs)("div",{className:h4().settingDescription,children:["Run ",(0,d.jsx)("code",{children:"cuelo --reset-password"})," on this machine to set a new one, or open ",(0,d.jsx)("code",{children:"/recover"})," in the browser: CUELO prints a one-time code on its own console, and entering that code sets a new password. Both paths require access to the machine running the server — nothing can hand the password back."]})]}),(0,d.jsx)("div",{className:h4().settingControl,children:(0,d.jsx)("a",{className:h4().linkButton,href:"/recover",target:"_blank",rel:"noreferrer",children:"Open /recover"})})]}),(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:h4().settingLabel,children:"Basic Auth is not encryption"}),(0,d.jsx)("div",{className:h4().settingDescription,children:"The password crosses the network in a reversible encoding. Over plain HTTP on an untrusted network it can be read in transit, so put CUELO behind HTTPS or a trusted VPN before exposing it beyond loopback."})]}),(0,d.jsx)("div",{className:h4().settingControl})]})]})]})]})}let h6="/api/live/character-voice",h7={ready:"chat.liveVoiceStateReady","not-prepared":"chat.liveVoiceStateNotPrepared",preparing:"chat.liveVoiceStatePreparing","needs-check":"chat.liveVoiceStateNeedsCheck",failed:"chat.liveVoiceStateFailed","missing-asset":"chat.liveVoiceStateMissingAsset"},h8={failed:!0,"needs-check":!0,"missing-asset":!0};async function h9(a){let b=await a.json().catch(()=>({}));if(!a.ok||!b||"object"!=typeof b||!("characters"in b))throw Error(b&&"object"==typeof b&&"message"in b&&"string"==typeof b.message?b.message:`HTTP ${a.status}`);return b}function ia(){let{t:a}=(0,x.s)(),b=(0,e.useId)(),c=(0,e.useId)(),[f,g]=(0,e.useState)(null),[h,i]=(0,e.useState)(null),[j,k]=(0,e.useState)(""),[l,m]=(0,e.useState)(!1),[n,o]=(0,e.useState)(!1);(0,e.useCallback)(async()=>{try{g(await h9(await fetch(h6,{cache:"no-store"})))}catch(b){i(b instanceof Error?b.message:a("chat.liveVoiceLoadFailed"))}},[a]);let p=f?.preparing===!0,q=(0,e.useCallback)(async a=>{o(!0),i(null);try{return g(await h9(await fetch(h6,a))),!0}catch(a){return i(a instanceof Error?a.message:String(a)),!1}finally{o(!1)}},[]),r=async()=>{let a=j.trim();a&&await q({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:a})})&&k("")};if(!f)return(0,d.jsx)("div",{className:h4().empty,children:h?`${a("chat.liveVoiceLoadFailed")}: ${h}`:"…"});let s=f.configured,t=h??f.lastError??null;return(0,d.jsxs)("div",{className:h4().scrollContent,children:[(0,d.jsxs)("header",{className:h4().contentHeader,children:[(0,d.jsx)("h2",{className:h4().contentTitle,children:a("chat.liveVoiceSettingsTitle")}),(0,d.jsx)("p",{className:h4().contentDescription,children:a("chat.liveVoiceSettingsDescription")})]}),(0,d.jsxs)("div",{className:h4().settingsBody,children:[(0,d.jsxs)("section",{className:h4().group,children:[(0,d.jsx)("h3",{className:h4().groupTitle,children:a("chat.liveVoiceKeyLabel")}),(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsx)("label",{htmlFor:b,className:h4().settingLabel,style:{display:"block"},children:a("chat.liveVoiceKeyLabel")}),(0,d.jsx)("div",{className:h4().settingDescription,children:a("chat.liveVoiceKeyHelp")}),s&&f.keyHint&&(0,d.jsx)("div",{className:h4().saveState,style:{overflowWrap:"anywhere"},children:a("chat.liveVoiceKeySaved",{hint:f.keyHint})})]}),(0,d.jsx)("div",{className:h4().settingControl,children:(0,d.jsx)("input",{id:b,className:h4().textInput,type:"password",autoComplete:"off",spellCheck:!1,value:j,disabled:n,onChange:a=>k(a.target.value),onKeyDown:a=>{"Enter"===a.key&&r()},placeholder:"sk_car_…"})})]}),(0,d.jsxs)("div",{className:h4().editorActions,children:[(0,d.jsx)("div",{}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8},children:[s&&(0,d.jsx)("button",{type:"button",className:h4().dangerButton,disabled:n||p,onClick:()=>void q({method:"DELETE"}),children:a("chat.liveVoiceKeyRemove")}),(0,d.jsx)("button",{type:"button",className:h4().primaryButton,disabled:n||!j.trim(),onClick:()=>void r(),children:a("chat.liveVoiceKeySave")})]})]})]}),(0,d.jsxs)("section",{className:h4().group,children:[(0,d.jsx)("h3",{className:h4().groupTitle,children:a("chat.liveVoicePrepare")}),(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{style:{display:"flex",gap:8,alignItems:"flex-start",minWidth:0},children:[(0,d.jsx)("input",{id:c,type:"checkbox",checked:l,onChange:a=>m(a.target.checked),style:{marginTop:3,flex:"none"}}),(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsx)("label",{htmlFor:c,className:h4().settingDescription,style:{display:"block",color:"var(--text)"},children:a("chat.liveVoiceConsent")}),(0,d.jsxs)("div",{className:h4().settingDescription,style:{marginTop:4},children:[a("chat.liveVoicePlanNote")," ",(0,d.jsx)("a",{href:"/audio/live/ACML-1.0.txt",target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)"},children:a("chat.liveVoiceLicense")})]})]})]}),(0,d.jsx)("div",{className:h4().settingControl,style:{alignItems:"center"},children:(0,d.jsx)("button",{type:"button",className:h4().primaryButton,disabled:n||p||!s||!l,onClick:()=>void q({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prepare:!0,acknowledged:!0})}),"aria-busy":p,children:p?a("chat.liveVoicePreparing"):a("chat.liveVoicePrepare")})})]}),t&&(0,d.jsx)("div",{className:h4().error,role:"alert",style:{overflowWrap:"anywhere"},children:t})]}),(0,d.jsxs)("section",{className:h4().group,children:[(0,d.jsx)("h3",{className:h4().groupTitle,children:a("chat.liveVoiceCharacters")}),(0,d.jsx)("ul",{"aria-live":"polite",style:{listStyle:"none",margin:0,padding:0},children:f.characters.map(b=>(0,d.jsxs)("li",{className:h4().settingRow,style:{minHeight:44},title:b.error,children:[(0,d.jsxs)("div",{className:h4().settingLabel,style:{marginBottom:0},children:[b.alias,"provisional"===b.tuning&&(0,d.jsxs)("span",{className:h4().settingDescription,style:{fontWeight:400},children:[" \xb7 ",a("chat.liveVoiceProvisional")]})]}),(0,d.jsx)("div",{className:h4().settingControl,style:{fontSize:12,color:h8[b.state]?"var(--danger)":"ready"===b.state?"var(--text)":"var(--text-muted)"},children:a(h7[b.state])})]},b.id))})]})]})]})}function ib(){let{t:a}=(0,x.s)(),b=(0,e.useId)(),c=(0,e.useId)(),[f,g]=(0,e.useState)(null),[h,i]=(0,e.useState)(""),[j,k]=(0,e.useState)(null),[l,m]=(0,e.useState)(!1),[n,o]=(0,e.useState)(!1),p=(0,e.useCallback)(async a=>{m(!0),k(null),o(!1);try{let b=await eU(a);g(b),i(String(b.uploadLimitMb)),o(!0)}catch(a){k(a instanceof Error?a.message:String(a))}finally{m(!1)}},[]);return f?(0,d.jsxs)("div",{className:h4().scrollContent,children:[(0,d.jsxs)("header",{className:h4().contentHeader,children:[(0,d.jsx)("h2",{className:h4().contentTitle,children:a("chat.attachmentSettingsTitle")}),(0,d.jsx)("p",{className:h4().contentDescription,children:a("chat.attachmentSettingsDescription")})]}),(0,d.jsx)("div",{className:h4().settingsBody,children:(0,d.jsxs)("section",{className:h4().group,children:[(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("label",{htmlFor:b,className:h4().settingLabel,style:{display:"block"},children:a("chat.attachmentUploadLimit")}),(0,d.jsx)("div",{className:h4().settingDescription,children:a("chat.attachmentUploadLimitHelp")})]}),(0,d.jsx)("div",{className:h4().settingControl,children:(0,d.jsx)("input",{id:b,className:h4().numberInput,type:"number",inputMode:"numeric",min:1,step:1,value:h,disabled:l,onChange:a=>i(a.target.value),onBlur:()=>{let b=h.trim();if(b===String(f.uploadLimitMb))return;let c=Number(b);if(!/^\d+$/.test(b)||!Number.isSafeInteger(c)||c<1){o(!1),k(a("chat.attachmentUploadLimitInvalid"));return}p({uploadLimitMb:c})},onKeyDown:a=>{"Enter"===a.key&&a.currentTarget.blur()}})})]}),(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{id:c,className:h4().settingLabel,children:a("chat.attachmentAutoCleanup")}),(0,d.jsx)("div",{className:h4().settingDescription,children:a("chat.attachmentAutoCleanupHelp",{days:f.orphanGraceDays})})]}),(0,d.jsx)("div",{className:h4().settingControl,children:(0,d.jsx)("button",{type:"button",className:h4().switch,"data-on":f.autoCleanupEnabled,"aria-pressed":f.autoCleanupEnabled,"aria-labelledby":c,disabled:l,onClick:()=>void p({autoCleanupEnabled:!f.autoCleanupEnabled})})})]}),j&&(0,d.jsx)("div",{className:h4().error,role:"alert",style:{overflowWrap:"anywhere"},children:j}),n&&!j&&(0,d.jsx)("div",{className:h4().saveState,role:"status",children:a("chat.attachmentSettingsSaved")})]})})]}):(0,d.jsx)("div",{className:h4().empty,children:j?`${a("chat.attachmentSettingsLoadFailed")}: ${j}`:"…"})}function ic({cwd:a}){let{t:b}=(0,x.s)(),[c,f]=(0,e.useState)(null),[g,h]=(0,e.useState)(null),[i,j]=(0,e.useState)(null),[k,l]=(0,e.useState)(null),[m,n]=(0,e.useState)({}),[o,p]=(0,e.useState)(null),[q,r]=(0,e.useState)(null),s=(0,e.useRef)(new Map),t=(0,e.useRef)(0),u=(0,e.useRef)(null),v=(0,e.useRef)(null),w=(0,e.useRef)(!1),y=(0,e.useCallback)(async()=>{if(w.current||"visible"!==document.visibilityState)return;let c=++t.current;u.current?.abort();let d=new AbortController;u.current=d;try{let e=a?`?include=${encodeURIComponent(a)}`:"",g=await fetch(`/api/project-trust${e}`,{cache:"no-store",signal:d.signal}),i=await g.json();if(c!==t.current||d.signal.aborted)return;if(!g.ok||!i.projects)throw Error(i.error??`HTTP ${g.status}`);let j=i.projects.find(a=>null===a.pending&&!a.error&&v.current?.some(b=>b.cwd===a.cwd&&("grant"===b.pending?a.trusted:"revoke"===b.pending&&!a.trusted)));v.current=i.projects,f(i.projects),h(null),j&&p({cwd:j.cwd,text:b("trust.doneApplied")})}catch(a){if(c!==t.current||d.signal.aborted)return;h(a instanceof Error?a.message:String(a))}finally{u.current===d&&(u.current=null)}},[a,b]);c?.some(a=>null!==a.pending);let z=(0,e.useCallback)(async(a,c)=>{if(!w.current){w.current=!0,++t.current,u.current?.abort(),l(a),j(null),r(a),p(null),n(b=>{let c={...b};return delete c[a],c});try{let d=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:a,action:c})}),e=await d.json();if(!d.ok)throw Error(e.error??`HTTP ${d.status}`);let g=v.current?.map(b=>b.cwd===a?{...e,cwd:a}:b)??null;v.current=g,f(g),"cancel"===c?p({cwd:a,text:b("trust.doneCancelled")}):e.error||null!==e.pending||p({cwd:a,text:b("trust.doneApplied")})}catch(b){n(c=>({...c,[a]:b instanceof Error?b.message:String(b)}))}finally{w.current=!1,l(null)}}},[b]);if(!c)return(0,d.jsxs)("div",{className:h4().empty,children:[g?b("trust.loadFailed",{error:g}):"…",g&&(0,d.jsx)("button",{type:"button",className:h4().linkButton,onClick:()=>void y(),children:b("trust.refresh")})]});let A=null!==k;return(0,d.jsxs)("div",{className:h4().scrollContent,children:[(0,d.jsxs)("header",{className:h4().contentHeader,children:[(0,d.jsx)("h2",{className:h4().contentTitle,children:b("trust.settingsNav")}),(0,d.jsx)("p",{className:h4().contentDescription,children:b("trust.settingsDescription")}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,marginTop:12},children:[(0,d.jsx)("button",{type:"button",className:h4().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:A,onClick:()=>void y(),children:b("trust.refresh")}),g&&(0,d.jsx)("div",{className:h4().error,role:"alert",children:b("trust.loadFailed",{error:g})})]})]}),(0,d.jsx)("div",{className:h4().settingsBody,children:(0,d.jsxs)("section",{className:h4().group,children:[0===c.length&&(0,d.jsx)("div",{className:h4().settingDescription,children:b("trust.settingsEmpty")}),c.map(a=>{var c;let e=k===a.cwd,f=i?.cwd===a.cwd?i:null,g=a.requiresTrust?a.trusted?b("trust.stateTrusted"):b("trust.stateRestricted"):b("trust.stateNotRequired"),h=m[a.cwd]??(a.error?b("trust.applyFailed",{error:a.error}):null);return(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsxs)("div",{className:h4().settingLabel,style:{display:"flex",alignItems:"center",gap:7},children:[(0,d.jsx)("span",{className:h4().statusDot,"data-off":!a.trusted||!a.requiresTrust,"aria-hidden":"true"}),(0,d.jsx)("span",{children:(c=a.cwd).split(/[\\/]/).filter(Boolean).pop()??c}),(0,d.jsx)("span",{className:h4().settingDescription,style:{fontWeight:600},children:g})]}),(0,d.jsx)("code",{className:h4().settingDescription,style:{display:"block",overflowWrap:"anywhere"},children:a.cwd}),(0,d.jsx)("div",{className:h4().saveState,children:b("trust.runtime",{sessions:a.runtime.sessions,running:a.runtime.running,loaded:a.requiresTrust?a.runtime.projectCodeLoaded:0})}),(0,d.jsxs)("div",{"aria-live":"polite",children:["grant"===a.pending&&(0,d.jsx)("div",{className:h4().settingDescription,children:b("trust.pendingGrant")}),"revoke"===a.pending&&(0,d.jsx)("div",{className:h4().settingDescription,children:b("trust.pendingRevoke",{count:a.runtime.projectCodeLoaded})}),f&&(0,d.jsx)("div",{className:h4().settingDescription,style:{color:"var(--text)"},children:"revoke"===f.action?b("trust.confirmRevoke"):f.again?b("trust.confirmTrustAgain"):b("trust.confirmGrant")}),o?.cwd===a.cwd&&(0,d.jsx)("div",{className:h4().saveState,children:o.text})]}),h&&(0,d.jsx)("div",{className:h4().error,role:"alert",children:h})]}),(0,d.jsx)("div",{ref:b=>{b?s.current.set(a.cwd,b):s.current.delete(a.cwd)},className:h4().settingControl,style:{flexWrap:"wrap",gap:8,alignItems:"flex-start"},children:f?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("button",{type:"button",className:h4().linkButton,style:{background:"transparent",cursor:"pointer"},autoFocus:!0,onClick:()=>{j(null),r(a.cwd)},children:b("trust.cancel")}),(0,d.jsx)("button",{type:"button",className:"revoke"===f.action?h4().dangerButton:h4().primaryButton,disabled:A,onClick:()=>void z(a.cwd,f.action),children:"revoke"===f.action?b("trust.revoke"):b("trust.confirm")})]}):e?(0,d.jsx)("button",{type:"button",className:h4().primaryButton,disabled:!0,children:b("trust.working")}):(0,d.jsxs)(d.Fragment,{children:["grant"===a.pending&&(0,d.jsx)("button",{type:"button",className:h4().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:A,onClick:()=>void z(a.cwd,"cancel"),children:b("trust.cancelSchedule")}),a.requiresTrust&&!a.trusted&&"grant"!==a.pending&&(0,d.jsx)("button",{type:"button",className:h4().primaryButton,disabled:A,onClick:()=>j({cwd:a.cwd,action:"grant",again:"revoke"===a.pending}),children:"revoke"===a.pending?b("trust.trustAgain"):b("trust.trustProject")}),a.trusted&&(0,d.jsx)("button",{type:"button",className:h4().dangerButton,disabled:A,onClick:()=>j({cwd:a.cwd,action:"revoke",again:!1}),children:b("trust.revoke")})]})})]},a.cwd)})]})})]})}let id=JSON.parse('{"tabs":{"appearance":"외관","model":"모델","interaction":"상호작용","context":"컨텍스트","memory":"메모리","files":"파일","shell":"Shell","tools":"도구","tasks":"작업","providers":"제공자"},"groups":{"Theme":"테마","Status Line":"상태 표시줄","Display":"표시","Images":"이미지","Thinking":"사고","Sampling":"샘플링","Prompt":"프롬프트","Retry & Fallback":"재시도 및 폴백","Advisor":"어드바이저","Prewalk":"Prewalk","Vision":"비전","Input":"입력","Approvals":"승인","Notifications":"알림","Speech":"음성","Collab":"협업","Magic Keywords":"매직 키워드","Startup & Updates":"시작 및 업데이트","Power (macOS)":"전원 (macOS)","Agent":"에이전트","Git":"Git","General":"일반","Compaction":"압축","Rules (TTSR)":"규칙 (TTSR)","Experimental":"실험적 기능","Auto-Learn":"자동 학습","Mnemopi":"Mnemopi","Hindsight":"Hindsight","Editing":"편집","Reading":"읽기","Read Summaries":"읽기 요약","LSP":"LSP","Bash":"Bash","Eval & Runtimes":"평가 및 런타임","Available Tools":"사용 가능한 도구","Todos":"할 일","Grep & Browser":"Grep 및 브라우저","Computer":"컴퓨터","GitHub":"GitHub","Output Limits":"출력 제한","Execution":"실행","Discovery & MCP":"탐색 및 MCP","Developer":"개발자","Modes":"모드","Subagents":"서브에이전트","Isolation":"격리","Commands & Skills":"명령 및 스킬","Services":"서비스","Fireworks":"Fireworks","Tiny Model":"Tiny Model","Protocol":"프로토콜","Timeouts":"타임아웃","Privacy":"개인정보"},"shell":{"Loading omp settings…":"omp 설정을 불러오는 중…","Settings unavailable":"설정을 사용할 수 없음","Matching canonical /settings entries across every category.":"모든 카테고리에서 표준 /settings 항목을 일치시킨다.","Canonical omp /settings values. Changes are saved immediately to the shared agent configuration.":"표준 omp /settings 값이다. 변경 사항은 공유 에이전트 설정에 즉시 저장된다.","Saved. Reload the active session to apply runtime settings.":"저장됨. 런타임 설정을 적용하려면 활성 세션을 다시 불러온다.","Reloading…":"다시 불러오는 중…","Reload session":"세션 다시 불러오기","No settings match this search.":"이 검색과 일치하는 설정이 없다.","Search /settings":"/settings 검색","Configuration":"구성","OMP settings":"OMP 설정","Close settings":"설정 닫기","Global configuration":"전역 구성","Settings":"설정","Search":"검색","Models":"모델","Themes":"테마","Skills":"스킬","Plugins":"플러그인","MCP":"MCP","Loading themes…":"테마를 불러오는 중…","Themes unavailable":"테마를 사용할 수 없음","Active on web":"웹에서 활성","Preview ":"미리보기 ","The web interface uses the same dark and light theme mappings as omp. Changes are persisted to ":"웹 인터페이스는 omp와 동일한 다크 및 라이트 테마 매핑을 사용한다. 변경 사항은 다음에 저장된다: "," and applied here immediately.":" 그리고 여기에 즉시 적용된다."," mapping":" 매핑","requires a project":"프로젝트가 필요하다"},"fields":{"theme.dark":{"label":"다크 테마","description":"터미널 배경이 어두울 때 사용하는 테마이다"},"theme.light":{"label":"라이트 테마","description":"터미널 배경이 밝을 때 사용하는 테마이다"},"symbolPreset":{"label":"심볼 프리셋","description":"아이콘과 기호에 사용하는 글리프 세트이다 (Unicode, Nerd Font, ASCII)"},"colorBlindMode":{"label":"색맹 모드","description":"diff 추가 표시에 초록색 대신 파란색을 사용한다"},"statusLine.preset":{"label":"상태 표시줄 프리셋","description":"미리 구성된 상태 표시줄 설정이다"},"statusLine.separator":{"label":"상태 표시줄 구분자","description":"세그먼트 사이 구분자의 스타일이다"},"statusLine.sessionAccent":{"label":"세션 강조색","description":"에디터 테두리와 상태 표시줄 여백에 세션 이름 색상을 사용한다"},"statusLine.transparent":{"label":"투명 상태 표시줄","description":"상태 표시줄에 테마의 `statusLineBg` 대신 터미널 기본 배경을 사용한다. Powerline 끝 캡은 주변 터미널로 이어지려면 대비되는 채움색이 필요하므로 제거된다."},"statusLine.compactThinkingLevel":{"label":"간결한 thinking 레벨","description":"thinking 레벨을 별도의 ` \xb7 <level>` 접미사 대신 모델 이름에 아이콘 하나로 표시한다."},"statusLine.showHookStatus":{"label":"hook 상태 표시","description":"상태 표시줄 아래에 hook 상태 메시지를 표시한다"},"terminal.showImages":{"label":"인라인 이미지 표시","description":"터미널에 이미지를 인라인으로 렌더링한다"},"images.autoResize":{"label":"이미지 자동 크기 조정","description":"모델 호환성을 높이기 위해 큰 이미지를 최대 2000x2000으로 축소한다"},"images.blockImages":{"label":"이미지 차단","description":"이미지가 LLM 제공자에게 전송되지 않도록 한다"},"terminal.showProgress":{"label":"네이티브 터미널 진행 표시","description":"에이전트나 컨텍스트 유지 작업이 실행되는 동안 OSC 9;4 부정형 진행 표시를 내보낸다"},"tui.textSizing":{"label":"큰 제목 (Kitty)","description":"Kitty의 OSC 66 text-sizing 프로토콜을 사용해 Markdown H1 제목을 2배 크기로 렌더링한다. Kitty 터미널에서만 적용되며 그 외에서는 무시된다. 기본값은 꺼짐이다."},"tui.renderMermaid":{"label":"Mermaid 다이어그램 렌더링","description":"Mermaid 코드 블록을 ASCII 다이어그램으로 렌더링한다"},"tui.codexResetFireworks":{"label":"Codex 리셋 불꽃놀이","description":"예정에 없던 Codex 주간 사용량 리셋과 새로 적립된 저장 리셋을 화면 상단 1/3의 불꽃놀이 오버레이로 축하하며, Escape를 누를 때까지 유지된다"},"tui.titleState":{"label":"터미널 제목 실행 상태","description":"터미널 제목의 구분자에 에이전트 실행 상태를 표시한다 — 작업 중에는 애니메이션 스피너(Windows에서는 고정된 \':\'), 사용자 차례일 때는 \'>\', 에이전트가 사용자를 기다릴 때는 \'!\'이다"},"tui.hyperlinks":{"label":"터미널 하이퍼링크","description":"터미널 자체의 클릭 열기를 위해 경로와 URL을 OSC 8 하이퍼링크로 감싼다 (auto: 지원 여부 감지, off: 사용 안 함, always: 무조건 사용)"},"tui.tight":{"label":"조밀한 레이아웃","description":"터미널 출력 좌우의 1문자 가로 여백을 제거한다"},"tui.scrollbackRebuild":{"label":"스크롤백 다시 쓰기","description":"블록의 최종 형태가 실시간 미리보기를 대체할 때 터미널 스크롤백을 지우고 다시 출력한다. 꺼짐(기본값)일 때는 오래된 미리보기 사본이 기록에 남고 최종 내용이 그 아래에 추가된다."},"display.shimmer":{"label":"셔머","description":"작업/로딩 메시지의 애니메이션 스타일이다"},"display.smoothStreaming":{"label":"부드러운 스트리밍","description":"청크가 도착하는 동안 어시스턴트 텍스트와 스트리밍되는 도구 입력을 부드럽게 표시한다"},"display.hideToolActivity":{"label":"도구 활동 숨김","description":"모델이 시작한 도구 호출과 결과를 대화 기록에서 숨긴다"},"display.showTokenUsage":{"label":"토큰 사용량 표시","description":"어시스턴트 메시지에 턴별 토큰 사용량을 표시한다"},"display.cacheMissMarker":{"label":"캐시 미스 표시","description":"요청이 프롬프트 캐시를 놓친(miss) 어시스턴트 턴 위에 구분선을 표시한다"},"display.collapseCompacted":{"label":"압축 히스토리 접기","description":"라이브 트랜스크립트에서 compaction 이전 히스토리를 요약 구분선 뒤로 접는다. 비활성화하면 각 compaction 지점에 구분선을 둔 채 전체 트랜스크립트를 인라인으로 유지한다"},"showHardwareCursor":{"label":"하드웨어 커서 표시","description":"IME 지원을 위해 터미널 커서를 표시한다"},"tui.imeSafeCursor":{"label":"IME 안전 프롬프트 레이아웃","description":"macOS IME preedit가 프롬프트 하단 테두리를 밀어내지 못하도록 테두리를 별도 행으로 옮긴다"},"task.showResolvedModelBadge":{"label":"확정 모델 배지 표시","description":"task 위젯 상태줄에 각 subagent가 실제로 사용한 모델 ID를 표시한다"},"advisor.enabled":{"label":"Advisor 활성화","description":"\'advisor\' 역할에 배정된 두 번째 모델을 함께 두어 각 턴을 수동적으로 검토하고 메모를 주입한다."},"prewalk.enabled":{"label":"Prewalk 활성화","description":"활성 모델로 시작한 뒤, plan nudge의 todo 목록이 생성된 이후 첫 edit/write 시점에 빠르고 저렴한 모델(기본값은 \'smol\' 역할)로 전환한다 — 강한 모델이 계획하고 todo를 확정하며 구현을 시작한 후 인계한다. 세션별로 --prewalk / --no-prewalk로 재정의할 수 있다."},"advisor.syncBacklog":{"label":"Advisor 동기화 백로그","description":"advisor가 이 턴 수만큼 뒤처지면 메인 에이전트를 최대 30초 동안 멈춘다. Off로 두면 따라잡기 지연을 비활성화한다."},"advisor.immuneTurns":{"label":"Advisor 면역 턴","description":"advisor의 concern 또는 blocker가 한 번 인터럽트한 뒤에는, 이 primary 턴 수 동안 이후 concern/blocker를 인터럽트 없이 전달한다."},"modelRoleStorage":{"label":"모델 역할 저장소","description":"모델 선택기의 역할 배정이 저장되는 위치이다"},"images.describeForTextModels":{"label":"텍스트 모델용 이미지 설명","description":"vision을 지원하지 않는 모델에 이미지가 첨부되면, 이미지를 버리지 않고 local:// 아래에 저장한 뒤 vision 지원 모델이 만든 설명을 주입한다"},"defaultThinkingLevel":{"label":"Thinking 레벨","description":"thinking을 지원하는 모델의 추론 깊이이다"},"hideThinkingBlock":{"label":"Thinking 블록 숨김","description":"어시스턴트 응답에서 thinking 블록을 숨긴다"},"proseOnlyThinking":{"label":"산문 전용 Thinking","description":"thinking 요약에서 코드 블록을 제외하고 생략 부호로 대체한다"},"omitThinking":{"label":"Thinking 요약 생략","description":"응답에서 thinking 요약을 완전히 생략하도록 업스트림 provider에 지시한다(지원되는 경우)"},"externalThinking":{"label":"외부 Thinking","description":"사용자에게 표시되지 않는 비공개 스크래치패드이다. 지원되는 GPT, Claude, Gemini의 reasoning을 비활성화한다"},"model.loopGuard.enabled":{"label":"Loop Guard","description":"모델 reasoning과 산문에 대한 자동 스트림 루프 감지를 활성화한다"},"model.loopGuard.checkAssistantContent":{"label":"Loop Guard 산문 검사","description":"thinking 로그 외에 어시스턴트 산문 메시지에도 loop guard를 적용한다"},"model.loopGuard.toolCallReminder":{"label":"Loop Guard 도구 호출 알림","description":"Gemini reasoning 스트림이 도구를 호출하지 않고 계획 헤더를 연속으로 다수 출력하면 중단하고 도구 호출을 요구하는 알림을 주입한다(Loop Guard 필요)"},"model.toolCallLoopGuard.enabled":{"label":"도구 호출 Loop Guard","description":"여러 턴에 걸친 동일한 연속 도구 호출을 감지하고 교정용 steer를 주입한다"},"inlineToolDescriptors":{"label":"인라인 도구 디스크립터","description":"시스템 프롬프트에 전체 도구 디스크립터를 렌더링하고 provider 도구 스키마에서 최상위/중첩 description을 제거해 디스크립터 텍스트를 한 번만 전송한다. Auto는 Gemini 모델에서 이를 활성화하고 그 외에는 비활성화한다"},"includeModelInPrompt":{"label":"프롬프트에 모델 포함","description":"에이전트가 자신이 어떤 모델인지 알 수 있도록 시스템 프롬프트에 활성 모델 식별자를 노출한다"},"includeWorkspaceTree":{"label":"워크스페이스 트리 포함","description":"시스템 프롬프트에 워크스페이스 디렉터리 트리를 렌더링한다. 경고: 파일이 수정되면 세션 간 프롬프트 캐싱이 깨질 수 있다."},"personality":{"label":"성격","description":"시스템 프롬프트의 personality 블록에 렌더링되는 의사소통 스타일이다"},"temperature":{"label":"Temperature","description":"샘플링 temperature이다(0 = 결정적, 1 = 창의적, -1 = provider 기본값)"},"topP":{"label":"Top P","description":"Nucleus 샘플링 컷오프이다(0-1, -1 = provider 기본값)"},"topK":{"label":"Top K","description":"상위 K개 토큰에서 샘플링한다(-1 = provider 기본값)"},"minP":{"label":"Min P","description":"최소 확률 임계값 (0-1, -1 = provider 기본값)"},"presencePenalty":{"label":"Presence Penalty","description":"이미 등장한 토큰을 도입하는 데 대한 페널티 (-1 = provider 기본값)"},"repetitionPenalty":{"label":"Repetition Penalty","description":"반복된 토큰에 대한 페널티 (-1 = provider 기본값)"},"textVerbosity":{"label":"텍스트 상세도","description":"OpenAI Responses 및 Codex 응답의 상세도 (low, medium, high)"},"tier.openai":{"label":"서비스 티어 — OpenAI","description":"OpenAI / OpenAI-Codex 요청 및 OpenRouter를 경유하는 OpenAI 계열 모델의 처리 티어 (none = 생략). `service_tier`로 전송한다."},"tier.anthropic":{"label":"서비스 티어 — Anthropic","description":"Claude 요청의 처리 티어. `priority`는 지원되는 직접 Anthropic 모델에서 fast 모드(`speed: \\"fast\\"`)를 활성화하며, Bedrock/Vertex Claude 및 OpenRouter 경유에서는 무시된다."},"tier.google":{"label":"서비스 티어 — Google","description":"Gemini(Google AI Studio + Vertex) 요청 및 OpenRouter를 경유하는 Google 계열 모델의 처리 티어 (none = 생략). 최상위 `serviceTier` 필드로 전송한다."},"tier.subagent":{"label":"서비스 티어 — 서브에이전트","description":"생성된 task/eval 서브에이전트의 서비스 티어. Inherit = 메인 에이전트의 실시간 계열별 티어를 따른다(/fast를 추적한다). 값을 지정하면 서브에이전트 모델이 속한 계열에 그 값을 적용한다."},"tier.advisor":{"label":"서비스 티어 — Advisor","description":"advisor 모델의 서비스 티어. None = 표준 처리, Inherit = 메인 에이전트의 실시간 계열별 티어를 따른다. 값을 지정하면 advisor 모델의 계열에 그 값을 적용한다."},"retry.maxRetries":{"label":"재시도 횟수","description":"API 오류 시 최대 재시도 횟수"},"retry.modelFallback":{"label":"재시도 모델 폴백","description":"재시도 복구 시 설정된 폴백 모델로 전환하도록 허용한다"},"retry.usageAwareFallback":{"label":"사용량 인식 폴백","description":"신뢰할 수 있는 coding-plan 할당량 보고를 활용해, 하드 사용량 한도에 도달하기 전에 동일 provider 계정을 먼저 사용하고 그다음 설정된 폴백 모델을 사용한다. 일반 설정 API 키는 제외한다."},"retry.usageReservePct":{"label":"예비 마진","description":"남은 비율이 이 값 미만이면 coding-plan 모델이 한도에 근접한 것으로 간주한다. 사용량을 알 수 없거나 매핑되지 않은 경우 주 모델을 유지한다."},"retry.usageReservePolicy":{"label":"예비 정책","description":"동일 provider의 모든 coding-plan 계정이 예비 마진 안에 들어왔을 때의 동작이다."},"retry.fallbackChains":{"label":"재시도 폴백 체인","description":"모델 역할, 모델 선택자(\\"provider/model-id\\"), 또는 provider 와일드카드(\\"provider/*\\")를 순서가 있는 폴백 선택자에 매핑하는 JSON 객체이다. 예: {\\"default\\":[\\"openai/gpt-4o-mini\\"],\\"google-antigravity/*\\":[\\"google/*\\",\\"google-vertex/*\\"]}. 모델 지향 키는 역할과 무관하게 해당 모델/provider가 활성일 때마다 적용되며, \\"provider/*\\" 항목은 실패한 모델의 id를 유지한 채 provider만 교체한다. id 접두사 와일드카드(\\"openrouter/google/*\\")는 실패한 모델의 순수 id에 접두사를 다시 붙이고(google-antigravity/gemini-x -> openrouter/google/gemini-x), 키로 사용될 때는 해당 접두사 아래의 그 provider id에만 매칭된다."},"retry.fallbackRevertPolicy":{"label":"폴백 복귀 정책","description":"폴백 이후 주 모델로 되돌아가는 시점이다"},"providers.anthropic.serverSideFallback":{"label":"Anthropic 서버 사이드 폴백 (Fable 5)","description":"Claude Fable 5 / Mythos 5 요청이 Anthropic의 안전 분류기에 의해 차단되면 서버 사이드에서 Claude Opus 4.8로 재시도한다(Anthropic `server-side-fallback-2026-06-01` 베타). 옵트인 방식이며, 끄면 모든 요청에 대해 폴백 이전 동작이 유지된다."},"providers.autoThinkingModel":{"label":"Auto Thinking 모델","description":"`auto` thinking 레벨의 난이도 분류기이다. 기본값은 온라인(/models의 TINY 역할, 없으면 smol)이며, 로컬 온디바이스 모델도 사용할 수 있다"},"providers.autoThinkingMaxEffort":{"label":"Auto Thinking 상한","description":"`auto` 분류기가 도달할 수 있는 최고 effort이다. `xhigh`는 분류기를 최상위보다 한 단계 아래로 유지해 명시적인 `ultrathink`만 `max`에 도달하게 하며, `max`는 분류기가 예외적이라고 판단한 턴이 이를 노출하는 모델에서 최상위 티어로 과금되도록 허용한다."},"autoResume":{"label":"자동 재개","description":"현재 디렉터리의 가장 최근 세션을 자동으로 재개한다"},"power.sleepPrevention":{"label":"절전 방지","description":"활성 세션 동안 macOS 절전을 방지한다. 각 레벨은 누적되며, 하위 레벨의 플래그를 모두 포함한다."},"git.enabled":{"label":"Git 통합 활성화","description":"TUI에 git 브랜치, 상태, PR 정보를 표시하고 저장소 메타데이터를 감시한다."},"steeringMode":{"label":"Steering 모드","description":"에이전트가 작업하는 동안 대기 중인 메시지를 처리하는 방식이다"},"followUpMode":{"label":"후속 메시지 모드","description":"턴이 완료된 후 후속 메시지를 처리하는 방식이다"},"interruptMode":{"label":"인터럽트 모드","description":"steering 메시지가 도구 실행을 중단하는 시점이다"},"loop.mode":{"label":"Loop 모드","description":"/loop 반복 사이에 프롬프트를 다시 제출하기 전에 일어나는 동작이다"},"doubleEscapeAction":{"label":"이중 Escape 동작","description":"편집기가 비어 있는 상태에서 Escape를 두 번 누를 때의 동작이다"},"treeFilterMode":{"label":"세션 트리 필터","description":"세션 트리를 열 때의 기본 필터 모드이다"},"autocompleteMaxVisible":{"label":"자동완성 항목 수","description":"자동완성 드롭다운에 표시되는 최대 항목 수이다 (3-20)"},"emojiAutocomplete":{"label":"이모지 자동완성","description":"`:name:` 숏코드로 이모지를 제안하고 `:D` 또는 `:-)` 같은 텍스트 이모티콘을 확장한다"},"paste.largeMenuThreshold":{"label":"대용량 붙여넣기 메뉴","description":"붙여넣기가 이 줄 수에 도달하면 코드 블록으로 감싸기, XML 태그로 감싸기, 파일로 저장하기 메뉴를 제공한다. 0은 메뉴를 비활성화한다(대용량 붙여넣기는 여전히 [Paste] 마커로 축약된다)."},"startup.quiet":{"label":"조용한 시작","description":"환영 화면과 시작 상태 메시지를 건너뛴다"},"startup.showSplash":{"label":"시작 스플래시 표시","description":"설정을 다시 실행하지 않고 일반 대화형 시작 시 전체 애니메이션 설정 스플래시를 표시한다. 조용한 시작은 여전히 이를 억제한다."},"startup.setupWizard":{"label":"설정 위저드","description":"새로 추가된 온보딩 단계를 설정 버전마다 한 번 표시한다"},"startup.checkUpdate":{"label":"업데이트 확인","description":"시작 시 omp 업데이트를 확인한다"},"marketplace.autoUpdate":{"label":"마켓플레이스 자동 업데이트","description":"시작 시 플러그인 업데이트를 확인한다"},"startup.changelogMode":{"label":"시작 변경 내역","description":"업데이트 노트를 요약으로 시작할지, 전체 상세로 시작할지, 숨긴 상태로 둘지 선택한다"},"magicKeywords.enabled":{"label":"매직 키워드","description":"단독으로 쓰인 ultrathink, orchestrate, workflowz 키워드에 대한 숨겨진 공지를 활성화한다"},"magicKeywords.ultrathink":{"label":"Ultrathink 키워드","description":"단독으로 쓰인 ultrathink가 최대 자동 사고를 요청하고 숨겨진 공지를 덧붙이도록 한다"},"magicKeywords.orchestrate":{"label":"Orchestrate 키워드","description":"단독으로 쓰인 orchestrate가 숨겨진 멀티 에이전트 오케스트레이션 공지를 덧붙이도록 한다"},"magicKeywords.workflow":{"label":"Workflow 키워드","description":"단독으로 쓰인 workflowz가 숨겨진 eval 워크플로 공지를 덧붙이도록 한다"},"completion.notify":{"label":"완료 알림","description":"에이전트가 턴을 마쳤을 때 알린다"},"error.notify":{"label":"오류 알림","description":"에이전트가 오류로 중단되었을 때 알린다"},"ask.timeout":{"label":"Ask 타임아웃","description":"이 초가 지나면 권장 ask 옵션을 자동 선택한다 (0은 비활성화)"},"ask.notify":{"label":"Ask 알림","description":"ask 도구가 입력을 기다릴 때 알린다"},"recap.enabled":{"label":"유휴 요약","description":"터미널이 유휴 상태가 된 후 현재 상황에 대한 간단한 LLM 요약을 생성한다"},"recap.idleSeconds":{"label":"유휴 요약 지연","description":"요약을 표시하기 전 유휴 상태로 대기하는 초이다"},"collab.relayUrl":{"label":"Relay URL","description":"/collab에서 사용하는 relay이다 (wss://host[:port])"},"collab.webUrl":{"label":"웹 UI URL","description":"/collab 링크에 사용되는 브라우저 UI이다. 비어 있으면 collab.relayUrl에서 파생되며, 명시적인 http://는 localhost에서만 사용된다"},"collab.displayName":{"label":"표시 이름","description":"다른 collab 참가자에게 표시되는 이름이다 (기본값: OS 사용자 이름)"},"share.serverUrl":{"label":"Share 서버","description":"/share에서 사용하는 공유 뷰어/업로드 기준 주소이다 (암호화된 blob 업로드 + 뷰어, 링크는 <base>/<id>#<key> 형식이다)"},"share.store":{"label":"Share 저장소","description":"/share가 암호화된 세션 blob을 업로드하는 위치이다"},"share.redactSecrets":{"label":"공유 시 비밀정보 삭제","description":"업로드 전에 /share 스냅샷에 대해 secret obfuscator를 실행한다(secrets.* 설정을 사용한다)"},"stt.enabled":{"label":"음성 인식","description":"마이크를 통한 speech-to-text 입력을 활성화한다"},"stt.modelName":{"label":"음성 모델","description":"로컬 온디바이스 음성 모델이다. Parakeet TDT v3(sherpa-onnx)가 SoTA 기본값이며, Whisper base/small/large-v3-turbo 등급(transformers.js)은 크기를 다국어 지원과 맞바꾼다. 첫 사용 시 다운로드된다."},"stt.submitTrigger":{"label":"음성 입력 전송 트리거","description":"음성 받아쓰기가 자동으로 전송되는 시점을 선택한다: Never, Release(2단어 이상), 완전한 문장으로 Release, 또는 When I Say Submit."},"tools.approval":{"label":"도구 승인 정책","description":"도구별 승인 정책이다. \'allow\'는 자동 승인, \'prompt\'는 확인 요구, \'deny\'는 차단으로 설정한다. 재정의는 모든 승인 모드에서 적용된다."},"tools.approvalMode":{"label":"도구 승인","description":"도구 호출의 기본 승인 동작이다. \'Always ask\'는 읽기 전용 도구만 자동 승인한다. \'Write\'는 읽기 및 workspace-write 도구를 자동 승인한다. \'Yolo\'는 모든 등급을 자동 승인하지만, 사용자 정책에 따라 확인이나 차단이 발생할 수 있다."},"features.unexpectedStopDetection":{"label":"예상치 못한 중단","description":"어시스턴트가 예상치 못하게 멈추면 자동으로 복구한다. \'기계적\'(기본값)은 표시할 답변 없이 끝난 경우를 재시도하고 도구 호출이 있었던 중단은 제외한다. \'스마트\'는 기계적 감지에 더해 작은 모델로 텍스트만 남긴 중단도 판별하며, \'사용 안 함\'은 감지를 끈다."},"contextPromotion.enabled":{"label":"컨텍스트 자동 승격","description":"컨텍스트 초과 시 compaction 대신 더 큰 컨텍스트 모델로 승격한다"},"compaction.enabled":{"label":"자동 Compact","description":"컨텍스트가 너무 커지면 자동으로 compact한다"},"compaction.midTurnEnabled":{"label":"턴 중간 Compaction","description":"다음 provider 요청 전에 안전한 턴 중간 tool-loop 경계에서 임계값을 확인한다"},"compaction.strategy":{"label":"Compaction 전략","description":"제자리 context-full 유지, auto-handoff, surgical shake(무거운 콘텐츠 제거), snapcompact(히스토리를 밀집 이미지로 보관) 중에서 선택하거나 자동 유지를 비활성화(off)한다"},"compaction.thresholdPercent":{"label":"Compaction 임계값","description":"컨텍스트 유지의 퍼센트 임계값이다. Default로 설정하면 기존 reserve 기반 동작을 사용한다"},"compaction.thresholdTokens":{"label":"Compaction 토큰 한도","description":"컨텍스트 유지의 고정 토큰 한도이다. 설정하면 퍼센트 값을 재정의한다"},"compaction.handoffSaveToDisk":{"label":"Handoff 문서 저장","description":"auto-handoff 흐름에서 생성된 handoff 문서를 markdown 파일로 저장한다"},"compaction.remoteEnabled":{"label":"원격 Compaction","description":"가능한 경우 로컬 요약 대신 원격 compaction 엔드포인트를 사용한다"},"compaction.remoteStreamingV2Enabled":{"label":"원격 Compaction V2","description":"호환되는 원격 compaction 모델에 대해 Responses 스트리밍 compaction을 사용한다"},"compaction.idleEnabled":{"label":"유휴 Compaction","description":"토큰 수가 임계값을 넘으면 유휴 상태에서 컨텍스트를 compact한다"},"compaction.idleThresholdTokens":{"label":"유휴 Compaction 임계값","description":"유휴 compaction이 트리거되는 토큰 수 기준이다"},"compaction.idleTimeoutSeconds":{"label":"유휴 Compaction 지연","description":"compact하기 전 유휴 상태로 대기하는 초이다"},"compaction.supersedeReads":{"label":"오래된 읽기 대체","description":"같은 파일을 다시 읽으면 이전 읽기 결과를 정리한다(캐시 인식, 매 턴 실행)"},"compaction.dropUseless":{"label":"무의미한 결과 제거","description":"컨텍스트상 무용하다고 표시된 도구 결과(일치 없음, 시간 초과된 대기)를 소비된 후 정리한다(캐시 인식)"},"snapcompact.systemPrompt":{"label":"Snapcompact 시스템 프롬프트","description":"실험적 기능이다: 선택한 시스템 프롬프트 텍스트를 밀집 PNG 이미지로 렌더링해 첫 사용자 메시지에 첨부한다(비전 모델 전용). 토큰을 절약하지만 이미지화된 텍스트의 prompt caching을 잃는다."},"snapcompact.toolResults":{"label":"Snapcompact 도구 결과","description":"실험적 기능이다: 큰 과거 도구 결과를 텍스트 대신 밀집 PNG 이미지로 렌더링한다(비전 모델 전용). 누적된 읽기/검색 출력의 토큰을 절약한다."},"tools.format":{"label":"도구 호출 모드","description":"도구가 모델에 노출되는 방식을 제어한다. Auto는 provider-native 도구 호출을 사용하지만, 선택된 모델이 이를 지원하지 않는다고 표시된 경우 GLM owned dialect로 대체한다. Native는 provider-native 도구를 강제하고, 나머지 값은 지정된 owned dialect를 강제한다. 세션 시작 시 적용된다."},"snapcompact.shape":{"label":"Snapcompact 형태","description":"snapcompact가 텍스트를 출력하는 프레임 형태이다(compaction 보관 및 인라인 이미지화). Auto는 현재 모델에 맞게 조정된 형태를 선택한다."},"branchSummary.enabled":{"label":"브랜치 요약","description":"브랜치를 떠날 때 요약을 요청한다"},"ttsr.enabled":{"label":"TTSR","description":"출력이 규칙 패턴과 일치하면 스트리밍 도중에 에이전트를 중단한다(Time-Traveling Stream Rules)"},"ttsr.contextMode":{"label":"TTSR 컨텍스트 모드","description":"TTSR이 발동할 때 부분 출력을 어떻게 처리할지 정한다"},"ttsr.interruptMode":{"label":"TTSR 인터럽트 모드","description":"스트리밍 도중에 중단할지, 완료 후 경고를 주입할지 정한다"},"ttsr.repeatMode":{"label":"TTSR 반복 모드","description":"규칙이 반복되는 방식을 정한다: 세션당 한 번 또는 메시지 간격 이후"},"ttsr.repeatGap":{"label":"TTSR 반복 간격","description":"규칙이 다시 발동할 수 있기까지의 메시지 수이다"},"ttsr.builtinRules":{"label":"기본 제공 규칙","description":"에이전트에 기본 포함된 규칙을 로드한다(ttsr.disabledRules로 개별 해제 가능)"},"memory.backend":{"label":"메모리 백엔드","description":"끄기, 로컬 요약 파이프라인, Mnemopi SQLite, 또는 Hindsight 원격 메모리 중에서 선택한다"},"autolearn.enabled":{"label":"자동 학습 (실험적)","description":"에이전트가 멈춘 뒤 교훈을 메모리에 기록하고 격리된 관리형 skill을 생성/보강하도록 유도한다"},"autolearn.autoContinue":{"label":"중지 시 캡처 자동 실행","description":"켜면 중지 시 비공개 캡처 턴을 한 번 자동 실행한다(추가 토큰을 사용한다). 끄면 상시 자동 학습 안내만 남는다."},"mnemopi.dbPath":{"label":"Mnemopi DB 경로","description":"선택적 SQLite DB 경로이다. 기본값은 에이전트 memories 디렉터리이다."},"mnemopi.bank":{"label":"Mnemopi 뱅크","description":"선택적 공유 뱅크 기본 이름이다. per-project 모드는 이를 기반으로 프로젝트 로컬 뱅크를 파생한다."},"mnemopi.scoping":{"label":"Mnemopi 스코핑","description":"global = 공유 뱅크 하나, per-project = cwd별 격리 뱅크, per-project-tagged = 프로젝트 로컬 쓰기에 global recall 가시성을 더한 방식이다"},"mnemopi.embeddingVariant":{"label":"임베딩 variant","description":"로컬 임베딩 모델 계열이다. en = 더 강력한 영어 모델, multilingual = 교차 언어 모델이다. 이를 변경하면 다음 시작 시 기존 메모리 임베딩을 다시 생성한다."},"mnemopi.autoRecall":{"label":"Mnemopi 자동 recall","description":"각 세션의 첫 턴에 로컬 메모리를 recall한다"},"mnemopi.autoRetain":{"label":"Mnemopi 자동 retain","description":"완료된 대화 턴을 로컬 Mnemopi 메모리에 retain한다"},"mnemopi.polyphonicRecall":{"label":"Mnemopi 폴리포닉 recall","description":"reciprocal rank fusion으로 융합한 4-voice recall(vector, graph, fact, temporal)을 활성화한다"},"mnemopi.enhancedRecall":{"label":"Mnemopi 향상된 recall","description":"반복되거나 유사한 recall 쿼리를 위한 계층형 쿼리 결과 캐시를 활성화한다"},"mnemopi.proactiveLinking":{"label":"Mnemopi 선제적 링킹","description":"새 메모리를 저장하는 즉시 episodic 그래프에 수집해 관련 엔터티 및 메모리와 연결한다"},"mnemopi.noEmbeddings":{"label":"Mnemopi 임베딩 비활성화","description":"vector 임베딩 대신 결정적인 FTS 전용 recall을 강제한다"},"mnemopi.embeddingModel":{"label":"Mnemopi 임베딩 모델","description":"고급: variant를 재정의하는 명시적 임베딩 모델 id이다. 비워 두면 mnemopi.embeddingVariant를 사용한다."},"mnemopi.embeddingApiUrl":{"label":"Mnemopi 임베딩 API URL","description":"Mnemopi에 전달하는 선택적 OpenAI 호환 임베딩 엔드포인트이다"},"mnemopi.embeddingApiKey":{"label":"Mnemopi 임베딩 API 키","description":"Mnemopi에 전달하는 선택적 임베딩 API 키이다"},"mnemopi.llmMode":{"label":"Mnemopi LLM 모드","description":"LLM 미사용, 온라인 tiny 모델(/models의 TINY 역할, 없으면 @smol), 또는 원격 OpenAI 호환 엔드포인트를 사용한다"},"mnemopi.llmBaseUrl":{"label":"Mnemopi LLM Base URL","description":"Mnemopi 원격 모드를 위한 선택적 OpenAI 호환 LLM 엔드포인트이다"},"mnemopi.llmApiKey":{"label":"Mnemopi LLM API 키","description":"Mnemopi 원격 모드를 위한 선택적 LLM API 키이다"},"mnemopi.llmModel":{"label":"Mnemopi LLM 모델","description":"Mnemopi 원격 모드를 위한 선택적 LLM 모델 이름이다"},"hindsight.apiUrl":{"label":"Hindsight API URL","description":"Hindsight 서버 URL(Cloud 또는 self-hosted)이다"},"hindsight.apiToken":{"label":"Hindsight API 토큰","description":"인증이 필요한 Hindsight 서버용 Bearer 토큰이다"},"hindsight.bankId":{"label":"Hindsight Bank ID","description":"메모리 뱅크 식별자다(기본값: 프로젝트 이름)"},"hindsight.scoping":{"label":"Hindsight 범위","description":"global = 하나의 공유 뱅크, per-project = cwd별로 격리된 뱅크, per-project-tagged = 프로젝트 태그가 붙은 공유 뱅크로 recall 시 global 메모리와 프로젝트 메모리가 병합된다"},"hindsight.autoRecall":{"label":"Hindsight 자동 recall","description":"각 세션의 첫 턴에 메모리를 recall한다"},"hindsight.autoRetain":{"label":"Hindsight 자동 retain","description":"N턴마다 그리고 세션 경계에서 대화 기록을 retain한다"},"hindsight.retainMode":{"label":"Hindsight retain 모드","description":"full-session = 세션당 문서 하나를 upsert하고, last-turn = 청크 단위로 저장한다"},"hindsight.mentalModelsEnabled":{"label":"Hindsight 멘탈 모델","description":"부팅 시 정리된 reflect 요약(멘탈 모델)을 developer instructions로 읽어들인다. 뱅크에 있는 기존 모델을 로드하며 쓰기는 하지 않는다. 내장 seed 세트를 자동 생성하려면 hindsight.mentalModelAutoSeed와 함께 사용한다."},"hindsight.mentalModelAutoSeed":{"label":"Hindsight 멘탈 모델 자동 seed","description":"세션 시작 시 뱅크에 아직 없는 내장 멘탈 모델(project-conventions, project-decisions, user-preferences)을 생성한다."},"providers.memoryModel":{"label":"메모리 모델","description":"사실 추출 및 통합에 사용하는 Mnemopi LLM이다: 기본값은 online(/models의 TINY 역할, 없으면 smol/remote)이며, 로컬 on-device 모델도 사용할 수 있다"},"edit.mode":{"label":"편집 모드","description":"edit 도구 변형을 선택한다(replace, patch, hashline, apply_patch)"},"edit.fuzzyMatch":{"label":"퍼지 매치","description":"공백 차이에 대해 신뢰도가 높은 퍼지 매치를 허용한다"},"edit.fuzzyThreshold":{"label":"퍼지 매치 임계값","description":"퍼지 매치를 허용하는 유사도 임계값(0-1)이다"},"edit.streamingAbort":{"label":"프리뷰 실패 시 중단","description":"패치 프리뷰가 실패하면 스트리밍 edit 도구 호출을 중단한다"},"edit.blockAutoGenerated":{"label":"자동 생성 파일 차단","description":"자동 생성된 것으로 보이는 파일(protoc, sqlc, swagger 등)의 편집을 막는다"},"edit.enforceSeenLines":{"label":"확인된 줄 가드 적용","description":"이전 read/search가 전체를 표시하지 않은 줄을 기준으로 하는 편집을 거부한다"},"readLineNumbers":{"label":"줄 번호","description":"기본적으로 read 도구 출력에 줄 번호를 앞에 붙인다"},"read.defaultLimit":{"label":"기본 read 제한","description":"에이전트가 limit 없이 read를 호출할 때 반환하는 기본 줄 수다"},"read.renderMarkdown":{"label":"Markdown 프리뷰","description":"Markdown read 결과를 원본 소스가 아니라 서식이 적용된 터미널 Markdown 프리뷰로 렌더링한다"},"read.summarize.enabled":{"label":"read 요약","description":"명시적 selector 없이 read가 호출되면 구조적 코드 요약을 반환한다"},"read.summarize.prose":{"label":"산문 요약","description":"Markdown 및 일반 텍스트 read에 대해 구조적 요약을 반환한다"},"read.toolResultPreview":{"label":"인라인 read 프리뷰","description":"read 도구 결과를 요약 행이 아니라 대화 기록에 인라인으로 렌더링한다"},"lsp.enabled":{"label":"LSP","description":"코드 인텔리전스(정의, 참조, 진단, 이름 변경)를 위한 lsp 도구를 활성화한다"},"lsp.lazy":{"label":"LSP 지연 시작","description":"세션 시작 시점이 아니라 처음 사용할 때(lsp 도구 호출 또는 해당 파일 타입 편집) language server를 시작한다"},"lsp.shared":{"label":"공유 language server","description":"daemon broker를 통해 프로젝트당 하나의 language server를 omp 인스턴스 간에 공유한다(사용할 수 없으면 개별 서버로 대체된다)"},"lsp.formatOnWrite":{"label":"쓰기 시 포맷","description":"파일을 쓴 후 LSP로 코드 파일을 자동 포맷한다"},"lsp.diagnosticsOnWrite":{"label":"쓰기 시 진단","description":"코드 파일을 쓴 후 LSP 진단을 반환한다"},"lsp.diagnosticsOnEdit":{"label":"편집 시 진단","description":"코드 파일을 편집한 후 LSP 진단을 반환한다"},"lsp.diagnosticsDeduplicate":{"label":"진단 중복 제거","description":"파일에 대해 이미 표시된 편집 후 LSP 진단을 억제하고, 새롭거나 변경된 것만 표시한다"},"bash.enabled":{"label":"Bash","description":"셸 명령 실행을 위한 bash 도구를 활성화한다"},"bash.autoBackground.enabled":{"label":"Bash 자동 백그라운드","description":"오래 실행되는 bash 명령을 자동으로 백그라운드로 보내고 결과를 나중에 전달한다"},"bashInterceptor.enabled":{"label":"Bash 인터셉터","description":"전용 도구가 있는 셸 명령을 차단한다"},"bash.direnv":{"label":"direnv 자동 로드","description":"저장소의 direnv/devenv `.envrc`를 bash 세션에 자동으로 로드해 수동 `direnv exec` 없이 devenv 도구와 환경 변수를 사용할 수 있게 한다. direnv의 허용 목록을 따르며, `direnv allow`하지 않은 `.envrc`는 절대 실행되지 않는다"},"shellMinimizer.enabled":{"label":"셸 출력 축소","description":"장황한 셸 출력(git, npm, cargo 등)을 에이전트에 반환하기 전에 압축한다"},"shellMinimizer.sourceOutlineLevel":{"label":"셸 축소 소스 아웃라인","description":"소스 파일의 cat/read에 대한 소스 아웃라인 모드: default 또는 aggressive"},"eval.py":{"label":"Python Eval 백엔드","description":"eval 도구가 Python 셀을 IPython 커널로 보내도록 허용한다"},"eval.js":{"label":"JavaScript Eval 백엔드","description":"eval 도구가 JavaScript 셀을 인프로세스 런타임으로 보내도록 허용한다"},"eval.rb":{"label":"Ruby Eval 백엔드","description":"eval 도구가 Ruby 셀을 상시 유지되는 Ruby 커널로 보내도록 허용한다"},"eval.jl":{"label":"Julia Eval 백엔드","description":"eval 도구가 Julia 셀을 상시 유지되는 Julia 커널로 보내도록 허용한다"},"python.kernelMode":{"label":"Python 커널 모드","description":"eval 호출 간에 IPython 커널을 유지할지 매번 새로 시작할지 정한다"},"python.interpreter":{"label":"Python 인터프리터","description":"정확한 Python 실행 파일의 선택적 경로이다. 설정하면 자동 Python 런타임 탐색을 건너뛴다."},"ruby.interpreter":{"label":"Ruby 인터프리터","description":"정확한 Ruby 실행 파일의 선택적 경로이다. 설정하면 자동 Ruby 런타임 탐색을 건너뛴다."},"julia.interpreter":{"label":"Julia 인터프리터","description":"정확한 Julia 실행 파일의 선택적 경로이다. 설정하면 자동 Julia 런타임 탐색을 건너뛴다."},"tools.artifactSpillThreshold":{"label":"아티팩트 분리 임계값(KB)","description":"이 크기를 넘는 도구 출력은 아티팩트로 저장되고, 끝부분은 인라인으로 유지된다"},"tools.artifactTailBytes":{"label":"아티팩트 끝부분 크기(KB)","description":"출력이 아티팩트로 넘어갈 때 인라인으로 유지되는 끝부분 내용의 양이다"},"tools.artifactHeadBytes":{"label":"아티팩트 앞부분 크기(KB)","description":"출력이 아티팩트로 넘어갈 때 끝부분과 함께 인라인으로 유지되는 앞부분 내용의 양이다(중간 생략). 0이면 비활성화되어 끝부분만 유지한다."},"tools.outputMaxColumns":{"label":"출력 열 제한","description":"스트리밍 도구 출력(bash, python, js eval)과 `read`에 대한 줄당 바이트 제한이다. 이보다 긴 줄은 말줄임표로 잘리고, 다음 줄바꿈까지 남은 바이트는 버려진다. 0이면 비활성화된다."},"tools.artifactTailLines":{"label":"아티팩트 끝부분 줄 수","description":"출력이 아티팩트로 넘어갈 때 인라인으로 유지되는 끝부분 내용의 최대 줄 수이다"},"todo.enabled":{"label":"할 일 목록","description":"작업 추적을 위한 todo 도구를 활성화한다"},"todo.reminders":{"label":"할 일 알림","description":"중지하기 전에 할 일을 완료하도록 에이전트에 상기시킨다"},"todo.remindersMax":{"label":"할 일 알림 제한","description":"포기하기 전까지의 최대 할 일 알림 횟수이다"},"todo.eager":{"label":"할 일 자동 생성","description":"첫 메시지 이후 자동 할 일 목록 생성을 얼마나 강하게 유도할지 정한다"},"glob.enabled":{"label":"Glob","description":"glob 기반 파일 조회를 위한 glob 도구를 활성화한다"},"grep.enabled":{"label":"Grep","description":"정규식 내용 검색을 위한 grep 도구를 활성화한다"},"grep.contextBefore":{"label":"Grep 앞 컨텍스트","description":"각 grep 일치 항목 앞에 표시할 컨텍스트 줄 수이다"},"grep.contextAfter":{"label":"Grep 뒤 컨텍스트","description":"각 grep 일치 항목 뒤에 표시할 컨텍스트 줄 수이다"},"astGrep.enabled":{"label":"AST Grep","description":"구조적 AST 검색을 위한 ast_grep 도구를 활성화한다"},"astEdit.enabled":{"label":"AST Edit","description":"구조적 AST 재작성을 위한 ast_edit 도구를 활성화한다"},"debug.enabled":{"label":"디버그","description":"DAP 기반 디버깅을 위한 debug 도구를 활성화한다"},"launch.enabled":{"label":"Launch","description":"공유되는 장기 실행 프로젝트 프로세스를 감독하는 launch 도구를 활성화한다"},"speechgen.enabled":{"label":"음성 생성","description":"온디바이스(Kokoro) 또는 xAI Grok Voice 음성 파일 합성을 위한 tts 도구를 활성화한다"},"generate_image.enabled":{"label":"이미지 생성","description":"generate_image 도구(텍스트-이미지 생성 및 편집)를 활성화한다. tools.xdev가 켜져 있으면 xd:// 장치로 노출된다."},"inspect_image.mode":{"label":"이미지 분석","description":"이미지 이해를 비전 지원 모델에 위임하는 inspect_image 도구를 제어한다. \'auto\'는 활성 모델이 네이티브 이미지 입력을 지원하지 않을 때만 노출하고, \'on\'은 항상 노출하며, \'off\'는 노출하지 않는다."},"computer.enabled":{"label":"컴퓨터","description":"스크립트 가능한 호스트 데스크톱 제어 도구(스크린샷, 입력, 접근성)를 활성화한다"},"computer.display":{"label":"컴퓨터 디스플레이","description":"모든 디스플레이를 합성하거나 네이티브 display id를 선택한다"},"inspect_image.timeoutMs":{"label":"이미지 분석 타임아웃","description":"inspect_image 비전 모델 호출의 요청당 타임아웃이며 단위는 milliseconds이다. 응답이 멈춘 제공자는 수동 중단까지 차단되지 않고 타임아웃 오류로 빠르게 실패한다. 0으로 설정하면 타임아웃을 비활성화한다."},"checkpoint.enabled":{"label":"체크포인트/되돌리기","description":"컨텍스트 체크포인팅을 위한 checkpoint 및 rewind 도구를 활성화한다"},"fetch.enabled":{"label":"URL 읽기","description":"read 도구가 URL을 가져와 처리하도록 허용한다"},"vault.enabled":{"label":"Obsidian Vault","description":"Obsidian CLI를 통해 Obsidian vault 내용을 읽고 편집하는 vault:// 내부 URL을 활성화한다. 비활성화하면 vault:// 해석이 거부되고 시스템 프롬프트에서 vault:// 항목이 생략된다."},"github.enabled":{"label":"GitHub CLI","description":"github 도구(리포지터리, 이슈, pull request, diff, 검색, checkout, push, Actions watch 워크플로에 대한 op 기반 디스패치)를 활성화한다"},"github.cache.enabled":{"label":"GitHub 뷰 캐시","description":"렌더링된 이슈/PR 뷰 출력을 ~/.omp/cache/github-cache.db에 캐시해 반복 읽기 비용을 없앤다"},"web_search.enabled":{"label":"웹 검색","description":"실시간 웹 결과를 위한 web_search 도구를 활성화한다"},"security.enabled":{"label":"보안","description":"OMP 네이티브 보안 스캔 계획과 실행, 그리고 읽기 전용 security:// 리소스 네임스페이스를 활성화한다"},"ask.enabled":{"label":"Ask","description":"대화형 사용자 질문을 위한 ask 도구를 활성화한다"},"browser.enabled":{"label":"브라우저","description":"스크립트 기반 Chromium 자동화(puppeteer)를 위한 browser 도구를 활성화한다"},"browser.cdpUrl":{"label":"브라우저 CDP URL","description":"브라우저를 실행하는 대신 연결할 기본 HTTP CDP 디스커버리 엔드포인트이다(예: http://127.0.0.1:9222). 도구 호출에 명시된 app.cdp_url 또는 app.path가 우선한다."},"browser.relay":{"label":"브라우저 릴레이","description":"omp browser relay를 통해 사용자의 Chrome 탭을 제어한다. 확장 프로그램을 한 번 설치하면(`omp browser-relay install`) browser 도구가 필요할 때 릴레이 서버가 자동으로 시작된다. Browser CDP URL보다 우선하며, PI_BROWSER_RELAY=0 또는 PI_BROWSER_RELAY=1로 재정의한다."},"browser.relayUrl":{"label":"브라우저 릴레이 URL","description":"omp browser relay 엔드포인트이다(기본값 http://127.0.0.1:9224)."},"browser.headless":{"label":"헤드리스 브라우저","description":"브라우저를 headless 모드로 실행한다(비활성화하면 브라우저 UI를 표시한다)"},"browser.cmux":{"label":"cmux 브라우저","description":"cmux 소켓을 사용할 수 있을 때 브라우저 자동화에 cmux WKWebView 서피스를 사용한다. PI_BROWSER_CMUX=0 또는 PI_BROWSER_CMUX=1로 재정의한다."},"browser.screenshotDir":{"label":"스크린샷 디렉터리","description":"스크린샷을 저장할 디렉터리이다. 설정하지 않으면 스크린샷은 임시 파일로 저장된다. ~를 지원한다. 예: ~/Downloads, ~/Desktop, /sdcard/Download (Android)"},"tools.intentTracing":{"label":"인텐트 트레이싱","description":"각 도구 호출을 실행하기 전에 그 의도를 설명하도록 에이전트에 요청한다"},"tools.abortOnFabricatedResult":{"label":"조작된 도구 결과 시 중단","description":"in-band 도구 호출에서 모델이 턴 중간에 도구 결과를 환각하기 시작하면 즉시 중단한다. 비활성화하면 모델이 생성을 끝내도록 두고 조작된 이어쓰기를 폐기한다."},"tools.maxTimeout":{"label":"최대 도구 타임아웃","description":"에이전트가 임의의 도구에 설정할 수 있는 최대 타임아웃(초, 0 = 무제한)"},"async.enabled":{"label":"비동기 실행","description":"비동기 bash 명령과 백그라운드 작업 실행을 활성화한다"},"tools.xdev":{"label":"xd:// 도구","description":"드물게 쓰이는(탐색 가능한) 도구의 스키마를 매 요청마다 보내는 대신 read/write로 구동되는 xd:// 디바이스 URL 아래에 마운트한다. write 도구가 허용되지 않은 세션은 마운트를 건너뛰고 모든 도구를 최상위로 노출한다. 비활성화하면 활성화된 모든 도구를 최상위로 노출한다."},"tools.xdevDocs":{"label":"xd:// 프롬프트 문서","description":"시스템 프롬프트에 인라인으로 포함할 마운트된 디바이스 문서와 스키마를 선택한다. Built-ins는 핵심 도구를 인라인으로 유지하고 MCP 및 확장 도구는 on-demand로 남긴다."},"mcp.selection":{"label":"MCP 연결 선택","description":"all은 시작 시 기존 설정대로 연결한다. per-request는 JEV가 요청에 필요한 서버를 선택해 연결하며, 설치\xb7인증\xb7권한은 자동 승인하지 않는다. 변경 후 새 세션에서 적용된다."},"mcp.enableProjectConfig":{"label":"MCP 프로젝트 설정","description":"프로젝트 루트에서 .mcp.json/mcp.json을 로드한다"},"mcp.renderMarkdownResults":{"label":"MCP Markdown 결과","description":"JSON이 아닌 MCP 텍스트 결과를 트랜스크립트에서 Markdown으로 렌더링한다"},"mcp.notifications":{"label":"MCP 업데이트 주입","description":"MCP 리소스 업데이트를 에이전트 대화에 주입한다"},"tasks.todoClearDelay":{"label":"Todo 자동 정리 지연","description":"완료되거나 중단된 todo가 todo 위젯에서 제거되기까지의 지연 시간이다"},"dev.autoqa":{"label":"Auto QA","description":"자동 도구 이슈 보고(xd://report_issue)이다. 기본적으로 켜져 있으며, 첫 보고 시 동의를 요청하고 거부하면 명시적으로 다시 활성화할 때까지 보고를 비활성화한다"},"dev.autoqaPush.endpoint":{"label":"Auto QA 푸시 엔드포인트","description":"Auto QA JSON 보고를 수신하는 전체 URL이다(기본값 https://qa.omp.sh/v1/grievances)"},"plan.enabled":{"label":"Plan 모드","description":"실행 전 읽기 전용 탐색과 계획 수립을 위한 plan 모드를 활성화한다"},"plan.defaultOnStartup":{"label":"Plan 모드로 시작","description":"모든 새 세션 시작 시 자동으로 plan 모드로 진입한다"},"goal.enabled":{"label":"Goal 모드","description":"세션별 goal 모드와 숨겨진 goal 도구를 활성화한다"},"goal.statusInFooter":{"label":"푸터의 Goal 상태","description":"상태 표시줄에서 goal 표시기와 함께 토큰 예산을 표시한다"},"title.refreshOnReplan":{"label":"재계획 시 제목 갱신","description":"사용자가 제목을 설정한 경우가 아니면 todo init 재계획 이후 생성된 세션 제목을 갱신한다"},"task.isolation.mode":{"label":"격리 모드","description":"서브에이전트의 격리 백엔드이다. \\"auto\\"는 네이티브 PAL이 사용 가능한 최적 백엔드를 선택하게 한다(CoW를 지원하는 파일시스템, 그다음 overlayfs/ProjFS, 그다음 git worktree / 재귀 복사 폴백)."},"task.isolation.apply":{"label":"격리 변경 적용","description":"성공한 격리 작업의 변경을 부모 체크아웃에 자동으로 적용한다. 비활성화하면 patch 또는 branch 아티팩트를 유지한다"},"task.isolation.merge":{"label":"격리 병합 전략","description":"격리 작업의 변경을 통합하는 방식이다(patch apply 또는 branch merge)"},"task.isolation.commits":{"label":"격리 커밋 스타일","description":"중첩 저장소 변경의 커밋 메시지 스타일이다(generic 또는 AI 생성)"},"worktree.base":{"label":"Worktree 기본 디렉터리","description":"에이전트가 관리하는 worktree의 기본 디렉터리로, 작업 격리 사본, `github` PR 체크아웃, `omp worktree` 정리가 모두 여기에 위치한다. 설정하지 않으면 ~/.omp/wt를 사용한다. 절대 경로 또는 ~ 기준 경로여야 하며, 상대 경로는 무시된다. OMP_WORKTREE_DIR 환경 변수가 이 값을 재정의한다."},"task.eager":{"label":"작업 위임 선호도","description":"서브에이전트에 작업을 위임하도록 얼마나 강하게 유도할지를 정한다"},"task.batch":{"label":"작업 호출 배치","description":"task 도구를 배치 형태로 전환한다: 한 번의 호출이 { context, tasks[] }를 전달하며, 항목당 서브에이전트 하나가 실행되고, 항목별 agent(기본값은 세션 spawn-policy 에이전트)와 항목별 격리를 지정할 수 있으며, 공유 context는 모든 assignment 앞에 필수로 붙는다. async.enabled=true인 경우 각 spawn은 일반적인 idle/parked 수명 주기를 갖는 독립 백그라운드 에이전트로 실행되고, 그렇지 않으면 호출은 병합된 결과를 기다리며 블로킹된다. 비활성화하면 평면적인 단일 spawn 스키마로 되돌아간다."},"task.enableEffort":{"label":"작업별 effort","description":"task spawn에서 선택적 effort 파라미터를 노출해, 호출자가 각 서브에이전트의 thinking 레벨을 재정의할 수 있게 한다"},"task.maxConcurrency":{"label":"최대 동시 작업 수","description":"동시에 실행되는 서브에이전트의 최대 개수이다"},"task.enableLsp":{"label":"서브에이전트 LSP","description":"task 도구로 생성된 서브에이전트가 lsp 도구를 사용할 수 있게 한다. 서브에이전트 비용을 낮게 유지하기 위해 기본적으로 꺼져 있으며, LSP를 활용한 위임이 추가 토큰만큼 가치가 있을 때 활성화한다."},"task.maxRecursionDepth":{"label":"최대 작업 재귀 깊이","description":"서브에이전트가 자신의 서브에이전트를 생성할 수 있는 최대 깊이이다"},"task.maxRuntimeMs":{"label":"서브에이전트 최대 실행 시간","description":"서브에이전트당 절대 실행 시간 제한(ms)이다. 0이면 비활성화된다. 추론 계층 워치독을 빠져나가는 프로바이더 측 스트림 정지에 대한 심층 방어 수단이며, \'timed out\' 사유로 일반적인 서브에이전트 중단을 발생시킨다."},"task.softRequestBudget":{"label":"서브에이전트 소프트 요청 예산","description":"서브에이전트당 소프트 요청 예산(실행당 assistant 요청 수)이다. 이를 초과하면 마무리를 유도하는 steering 알림이 주입되며(task.softRequestBudgetNotice 참고), 예산의 1.5배에 도달하면 실행이 강제 중단되고 에이전트는 부분 결과를 내놓아야 한다. 0이면 이 보호 장치가 비활성화된다. 번들된 scout/sonic 에이전트는 더 낮은 내장 예산이 상한이므로, 그 상한보다 낮은 값은 이들에게도 적용된다."},"task.softRequestBudgetNotice":{"label":"소프트 요청 예산 알림","description":"서브에이전트가 소프트 요청 예산을 초과할 때 steering 알림을 한 번 주입해, 1.5배 강제 중단 전에 마무리하도록 요청한다."},"task.maxEffort":{"label":"spawn당 최대 effort","description":"task 도구의 spawn별 effort 힌트에 허용되는 최대 추론 effort이다. 값을 낮추면 호출자가 서브에이전트를 이 상한 이상으로 올릴 수 없으며, 기본값은 모델의 전체 범위를 유지한다."},"task.prewalk":{"label":"일반 작업 prewalk","description":"번들된 일반 `task` 서브에이전트에 prewalk를 적용한다: 해석된 모델로 시작해 계획을 세우고 구현을 시작한 뒤, 첫 편집/쓰기 시점에 \'smol\' 역할로 넘긴다. 에이전트별 재정의(/agents 허브에서 설정하는 task.agentPrewalk)와 사용자 에이전트의 `prewalk` frontmatter는 이 토글과 무관하게 적용된다."},"skills.enableSkillCommands":{"label":"스킬 명령","description":"스킬을 /skill:name 명령으로 등록한다"},"commands.enableClaudeUser":{"label":"Claude 사용자 명령","description":"~/.claude/commands/에서 명령을 로드한다"},"commands.enableClaudeProject":{"label":"Claude 프로젝트 명령","description":".claude/commands/에서 명령을 로드한다"},"commands.enableOpencodeUser":{"label":"OpenCode 사용자 명령","description":"~/.config/opencode/commands/에서 명령을 로드한다"},"commands.enableOpencodeProject":{"label":"OpenCode 프로젝트 명령","description":".opencode/commands/에서 명령을 로드한다"},"providers.maxInFlightRequests":{"label":"최대 동시 요청 수","description":"프로바이더 id별(예: \\"openai\\" 또는 \\"anthropic\\") 최대 동시 LLM 요청 수로, 같은 config root를 쓰는 로컬 OMP 프로세스 간에 공유된다. 명시되지 않은 프로바이더는 제한이 없다."},"secrets.enabled":{"label":"시크릿 숨김","description":"AI 프로바이더로 전송하기 전에 설정된 시크릿을 난독화하고 자격 증명 형태의 토큰을 마스킹한다"},"providers.webSearchOrder":{"label":"웹 검색 프로바이더 순서","description":"web_search 도구에 사용할 프로바이더의 우선순위이며, 목록에 없는 프로바이더는 그 뒤에 기본 순서를 유지한다"},"providers.webSearchExclude":{"label":"제외할 웹 검색 프로바이더","description":"web_search가 폴백으로도 절대 사용하지 않을 프로바이더이다"},"providers.webSearchTimeoutSeconds":{"label":"웹 검색 타임아웃","description":"web_search가 다음 폴백으로 넘어가기 전 각 프로바이더 검색 전송에 적용되는 절대 타임아웃이며 단위는 초이다(최대 300)"},"providers.webSearchGeminiModel":{"label":"Gemini web_search 모델","description":"Gemini Google Search grounding에 사용할 모델 ID이다. 기본값은 gemini-2.5-flash이다."},"providers.antigravityEndpoint":{"label":"Antigravity 엔드포인트 모드","description":"google-antigravity 프로바이더의 엔드포인트 라우팅 전략이다(chat, search, image, discovery)"},"providers.imageOrder":{"label":"이미지 프로바이더 순서","description":"이미지 생성에 사용할 프로바이더의 우선순위이며, 목록에 없는 프로바이더는 활성 세션 프로바이더와 내장 순서를 따른다"},"providers.fireworksTier":{"label":"Fireworks 티어","description":"Fireworks 요청의 서빙 경로이다. Priority는 `service_tier: \\"priority\\"`를 전송해 트래픽이 몰릴 때 더 높은 신뢰성을 더 높은 가격에 제공하고, Standard는 이를 생략한다. Fast(`-fast`) 모델은 이 설정을 무시하며, Fast는 별도의 서빙 경로이다."},"live.voice":{"label":"Live 음성","description":"Codex 기반 realtime 음성 세션에서 사용하는 음성이다"},"providers.tts":{"label":"TTS 제공자","description":"tts 도구의 백엔드이다: 로컬 온디바이스 신경망 TTS(Kokoro-82M) 또는 xAI Grok Voice 중 하나이다"},"tts.localModel":{"label":"로컬 TTS 모델","description":"로컬 TTS 백엔드가 사용하는 온디바이스 신경망 TTS 모델(Kokoro-82M)이다"},"tts.localVoice":{"label":"로컬 TTS 음성","description":"로컬 TTS 백엔드가 사용하는 Kokoro 음성이다(미국/영국, 여성/남성)"},"speech.enabled":{"label":"음성 출력","description":"어시스턴트의 출력을 스트리밍되는 대로 스피커로 소리내어 읽는다"},"speech.mode":{"label":"음성 출력 모드","description":"읽을 대상이다: all = 어시스턴트 메시지 + 사고 과정, assistant = 메시지만, yield = 턴 종료 시 마지막 메시지만이다"},"speech.enhanced":{"label":"향상된 음성 재작성","description":"합성 전에 tiny/smol 모델로 어시스턴트 출력을 자연스러운 구어체 산문으로 재작성한다(코드는 설명으로 바꾸고 링크와 markdown은 제거한다). 실패하면 기계적 정리로 대체된다"},"speech.voice":{"label":"음성 출력 목소리","description":"어시스턴트의 출력을 소리내어 읽을 때 사용하는 Kokoro 음성이다"},"providers.tinyModel":{"label":"Tiny 모델","description":"세션 제목 생성 모델이다: 기본값은 온라인(/models의 TINY 역할, 없으면 @smol)이며, 로컬 온디바이스 모델도 가능하다"},"providers.tinyModelDevice":{"label":"Tiny 모델 디바이스","description":"로컬 tiny 모델(제목 + 메모리)에 사용하는 ONNX 실행 제공자이다. 기본값은 CPU 전용 추론을 사용한다. PI_TINY_DEVICE 환경 변수가 이 값을 덮어쓴다."},"providers.tinyModelDtype":{"label":"Tiny 모델 정밀도","description":"로컬 tiny 모델의 ONNX 양자화/정밀도이다. 기본값은 각 모델에 포함된 dtype(q4)을 사용하며, 정밀도가 낮으면 더 빠르고 높으면 원본에 더 충실하다. PI_TINY_DTYPE 환경 변수가 이 값을 덮어쓴다."},"providers.unexpectedStopModel":{"label":"예기치 않은 중단 모델","description":"예기치 않은 중단 감지용 분류기이다: 기본값은 온라인(/models의 TINY 역할, 없으면 smol)이며, 로컬 온디바이스 모델도 가능하다."},"providers.kimiApiFormat":{"label":"Kimi API 형식","description":"Kimi Code 제공자의 API 형식이다(auto는 라이브 모델 메타데이터를 따른다)"},"providers.openaiWebsockets":{"label":"OpenAI WebSockets","description":"OpenAI Codex 모델의 websocket 정책이다(auto는 모델 기본값을 사용하고, on은 강제하며, off는 비활성화한다)"},"providers.streamFirstEventTimeoutSeconds":{"label":"스트림 첫 이벤트 타임아웃","description":"모델 스트림의 첫 이벤트를 기다리는 초이다. -1은 provider/env 기본값을 사용하고, 0은 워치독을 비활성화한다"},"providers.streamIdleTimeoutSeconds":{"label":"스트림 유휴 타임아웃","description":"모델 스트림이 이벤트 사이에 무응답 상태로 있을 수 있는 초이다. -1은 provider/env 기본값을 사용하고, 0은 워치독을 비활성화한다"},"providers.openrouterVariant":{"label":"OpenRouter 라우팅","description":"OpenRouter 모델 ID에 덧붙이는 기본 라우팅 variant 접미사이다(선택기에서 이미 variant를 지정한 경우 무시된다)"},"providers.fetch":{"label":"Fetch 제공자","description":"fetch/read URL 도구의 리더 백엔드 우선순위이다"},"codexResets.autoRedeem":{"label":"Codex 리셋 자동 사용","description":"저장된 Codex rate-limit 리셋을 자동으로 사용한다: 턴이 멈추고 다른 계정이 대체할 수 없을 때 5h 또는 weekly 창을 소진해 차단된 계정을 복구하고, 곧 만료될 크레딧을 회수한다. unset은 첫 사용 전에 확인하고, yes는 확인 없이 사용하며, no는 두 검사 모두 비활성화한다."},"provider.appendOnlyContext":{"label":"추가 전용 컨텍스트","description":"시스템 프롬프트 + 도구 명세를 캐시하고 추가 전용 메시지 로그를 유지해 provider prefix 캐시(DeepSeek, Xiaomi/SGLang, Anthropic) 적중률을 최대화한다. auto는 prefix 캐시가 알려진 제공자에 대해 활성화한다."},"exa.enabled":{"label":"Exa","description":"Exa 웹 검색 제공자를 활성화한다"},"searxng.endpoint":{"label":"SearXNG 엔드포인트","description":"웹 검색에 사용하는 자체 호스팅 SearXNG 인스턴스의 기본 URL이다"}}}'),ie=[{id:"models",label:"Models",icon:"model"},{id:"themes",label:"Themes",icon:"theme"},{id:"skills",label:"Skills",icon:"skill",requiresCwd:!0},{id:"plugins",label:"Plugins",icon:"plugin",requiresCwd:!0},{id:"mcp",label:"MCP",icon:"mcp"},{id:"access",label:"Access",icon:"access"},{id:"trust",label:"Project trust",labelKey:"trust.settingsNav",icon:"trust"},{id:"live-voice",label:"Call voice",labelKey:"chat.liveVoiceSettingsNav",icon:"liveVoice"},{id:"attachments",label:"Attachments",labelKey:"chat.attachmentSettingsNav",icon:"attachments"}],ig={model:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"}),(0,d.jsx)("path",{d:"M9 9h6v6H9zM9 1v3m6-3v3M9 20v3m6-3v3M1 9h3m16 0h3M1 15h3m16 0h3"})]}),theme:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"8"}),(0,d.jsx)("path",{d:"M12 4a8 8 0 0 0 0 16z"})]}),skill:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"m12 3 8 4-8 4-8-4 8-4Z"}),(0,d.jsx)("path",{d:"m4 12 8 4 8-4M4 17l8 4 8-4"})]}),plugin:(0,d.jsx)(d.Fragment,{children:(0,d.jsx)("path",{d:"M8 3v5m8-5v5M6 8h12v5a6 6 0 0 1-12 0V8Zm6 11v3"})}),mcp:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("circle",{cx:"6",cy:"6",r:"2"}),(0,d.jsx)("circle",{cx:"18",cy:"6",r:"2"}),(0,d.jsx)("circle",{cx:"12",cy:"18",r:"2"}),(0,d.jsx)("path",{d:"M8 7.5 11 16m5-8.5L13 16M8 6h8"})]}),access:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("rect",{x:"4",y:"10",width:"16",height:"10",rx:"2"}),(0,d.jsx)("path",{d:"M8 10V7a4 4 0 0 1 8 0v3M12 14v2"})]}),trust:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,d.jsx)("path",{d:"m9 12 2 2 4-4"})]}),liveVoice:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,d.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2M12 19v3"})]}),attachments:(0,d.jsx)("path",{d:"m21 12-8.6 8.6a5 5 0 0 1-7-7l8.5-8.6a3.3 3.3 0 0 1 4.7 4.7l-8.5 8.6a1.7 1.7 0 0 1-2.4-2.4l7.9-7.9"}),appearance:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,d.jsx)("path",{d:"M12 3v18M3 12h18"})]}),interaction:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"M4 5h16v11H9l-5 4V5Z"}),(0,d.jsx)("path",{d:"M8 9h8m-8 3h5"})]}),context:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"M5 3h11l3 3v15H5z"}),(0,d.jsx)("path",{d:"M15 3v4h4M8 11h8m-8 4h8"})]}),memory:(0,d.jsx)(d.Fragment,{children:(0,d.jsx)("path",{d:"M9 4a3 3 0 0 0-3 3v1a3 3 0 0 0-1 5v1a3 3 0 0 0 3 3h1m6-13a3 3 0 0 1 3 3v1a3 3 0 0 1 1 5v1a3 3 0 0 1-3 3h-1M9 4v16m6-16v16"})}),files:(0,d.jsx)(d.Fragment,{children:(0,d.jsx)("path",{d:"M3 6h7l2 2h9v11H3z"})}),shell:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),(0,d.jsx)("path",{d:"m7 9 3 3-3 3m6 0h4"})]}),tools:(0,d.jsx)(d.Fragment,{children:(0,d.jsx)("path",{d:"m14 6 4-4 4 4-4 4M3 18l8-8m-6 4 5 5-3 3-5-5 3-3Z"})}),tasks:(0,d.jsx)(d.Fragment,{children:(0,d.jsx)("path",{d:"M9 6h11M9 12h11M9 18h11M4 6l1 1 2-2m-3 7 1 1 2-2m-3 7 1 1 2-2"})}),providers:(0,d.jsx)(d.Fragment,{children:(0,d.jsx)("path",{d:"M7 4h10v5H7zM4 15h6v5H4zm10 0h6v5h-6zM12 9v3m-5 0h10M7 12v3m10-3v3"})})};function ih({kind:a}){return(0,d.jsx)("svg",{className:h4().navIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:ig[a]??ig.tools})}function ii({field:a,busy:b,onSave:c}){let[f,g]=(0,e.useState)("secret"===a.type?"":String(a.value??"")),h="secret"===a.type?"":String(a.value??"");return(0,d.jsx)("input",{className:h4().textInput,type:"secret"===a.type?"password":"text",value:f,disabled:b,placeholder:"secret"===a.type&&a.configured?"Configured — enter to replace":void 0,onChange:a=>g(a.target.value),onBlur:()=>{f!==h&&("secret"!==a.type||f.length>0)&&c(f)},onKeyDown:a=>{"Enter"===a.key&&a.currentTarget.blur()}})}function ij({field:a,busy:b,onSave:c}){let f=JSON.stringify(a.value??{},null,2),[g,h]=(0,e.useState)(f),[i,j]=(0,e.useState)(null);return(0,d.jsxs)("div",{style:{width:"100%"},children:[(0,d.jsx)("textarea",{className:h4().jsonEditor,style:{minHeight:92},value:g,disabled:b,onChange:a=>h(a.target.value),onBlur:()=>{if(g!==f)try{c(JSON.parse(g)),j(null)}catch(a){j(a instanceof Error?a.message:String(a))}}}),i&&(0,d.jsx)("div",{className:h4().error,children:i})]})}function ik({field:a,busy:b,onSave:c}){let e=Array.isArray(a.value)?a.value:[],f=(a,b)=>{let d=a+b;if(d<0||d>=e.length)return;let f=[...e];[f[a],f[d]]=[f[d],f[a]],c(f)};return(0,d.jsx)("div",{className:h4().multiSelect,children:a.options?.map(g=>{let h=e.indexOf(g.value);return(0,d.jsxs)("span",{className:h4().choice,"data-selected":h>=0,title:g.description,children:[(0,d.jsx)("button",{type:"button",className:h4().choiceToggle,disabled:b,onClick:()=>{let a;return a=g.value,c(e.includes(a)?e.filter(b=>b!==a):[...e,a])},children:g.label}),a.ordered&&h>=0&&(0,d.jsxs)("span",{className:h4().reorder,children:[(0,d.jsx)("button",{type:"button",disabled:b||0===h,onClick:()=>f(h,-1),children:"←"}),(0,d.jsx)("button",{type:"button",disabled:b||h===e.length-1,onClick:()=>f(h,1),children:"→"})]})]},g.value)})})}function il({field:a,busy:b,onSave:c}){return"boolean"===a.type?(0,d.jsx)("button",{type:"button",className:h4().switch,"data-on":!0===a.value,disabled:b,"aria-pressed":!0===a.value,onClick:()=>c(!0!==a.value)}):"select"===a.type?(0,d.jsx)(gN,{value:String(a.value??""),disabled:b,ariaLabel:a.label,options:(a.options??[]).map(a=>({value:a.value,label:a.label,description:a.description})),onChange:b=>c("number"==typeof a.value||"number"==typeof a.defaultValue?Number(b):b)}):"multiselect"===a.type?(0,d.jsx)(ik,{field:a,busy:b,onSave:c}):"providerLimits"===a.type?(0,d.jsx)(ij,{field:a,busy:b,onSave:c}):(0,d.jsx)(ii,{field:a,busy:b,onSave:c})}function im({field:a,busy:b,error:c,onSave:e}){return(0,d.jsxs)("div",{className:h4().settingRow,children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:h4().settingLabel,children:a.label}),(0,d.jsx)("div",{className:h4().settingDescription,children:a.description}),c&&(0,d.jsx)("div",{className:h4().error,children:c})]}),(0,d.jsx)("div",{className:h4().settingControl,children:(0,d.jsx)(il,{field:a,busy:b,onSave:e})})]})}function io({mode:a,palette:b}){let c=b.variables["--omp-md-heading"];return(0,d.jsxs)("div",{className:h4().themePreview,"data-seed-color-mode":"dark"===a?"dark-only":"light-only",children:[(0,d.jsx)("div",{className:h4().themePreviewBar,style:c?{background:c}:void 0}),(0,d.jsxs)("div",{className:h4().themePreviewPanel,children:[(0,d.jsx)("div",{className:h4().themePreviewLine}),(0,d.jsx)("div",{className:h4().themePreviewLine})]})]})}let ip=new Set(["hideThinkingBlock"]);function iq({cwd:a,sessionId:b,initialSection:c="models",onClose:f,onModelsChanged:g,onReloaded:h}){let[i,j]=(0,e.useState)(c),[k,l]=(0,e.useState)(null),[m,n]=(0,e.useState)(!0),[o,p]=(0,e.useState)(null),[q,r]=(0,e.useState)(""),[s,t]=(0,e.useState)(new Set),[u,v]=(0,e.useState)({}),[w,y]=(0,e.useState)(!1),[z,A]=(0,e.useState)(!1),{theme:B,setPreference:C}=bq(),{locale:D,t:E}=(0,x.s)(),F=(0,e.useRef)(null),G=a=>"ko"===D?id.shell[a]??a:a,H=(0,e.useCallback)(async()=>{n(!0),p(null);try{let b=a?`?cwd=${encodeURIComponent(a)}`:"",c=await fetch(`/api/settings${b}`,{cache:"no-store"}),d=await c.json();if(!c.ok||d.error)throw Error(d.error??`HTTP ${c.status}`);l(d)}catch(a){p(a instanceof Error?a.message:String(a))}finally{n(!1)}},[a]),I=(0,e.useCallback)(async(b,c)=>{t(a=>new Set(a).add(b.path)),v(a=>{let c={...a};return delete c[b.path],c});try{let d=await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:b.path,value:c})}),e=await d.json();if(!d.ok||e.error)throw Error(e.error??`HTTP ${d.status}`);l(a=>a?{...a,fields:a.fields.map(a=>a.path===b.path?{...a,value:e.value??c,configured:!0}:a)}:a),"theme.dark"===b.path||"theme.light"===b.path?(await bp(a),await H()):ip.has(b.path)?await bH(a):y(!0)}catch(a){v(c=>({...c,[b.path]:a instanceof Error?a.message:String(a)}))}finally{t(a=>{let c=new Set(a);return c.delete(b.path),c})}},[a,H]),J=(0,e.useMemo)(()=>new Map(k?.fields.map(a=>[a.path,a.value])??[]),[k?.fields]),K=(0,e.useMemo)(()=>k?.fields.filter(a=>(function(a,b){switch(a.condition){case void 0:default:return!0;case"hasImageProtocol":return!1;case"advisorEnabled":return!0===b.get("advisor.enabled");case"hindsightActive":return"hindsight"===b.get("memory.backend");case"mnemopiActive":return"mnemopi"===b.get("memory.backend");case"autolearnActive":return!0===b.get("autolearn.enabled");case"autoThinkingActive":return"auto"===b.get("defaultThinkingLevel");case"usageAwareFallbackEnabled":return!0===b.get("retry.usageAwareFallback");case"planModeEnabled":return!0===b.get("plan.enabled");case"unexpectedStopDetection":return!0===b.get("features.unexpectedStopDetection")}})(a,J))??[],[k?.fields,J]),L=i.startsWith("settings:")?i.slice(9):null,M=(0,e.useMemo)(()=>{let a=q.trim().toLowerCase();return a?K.filter(b=>`${b.label} ${b.description} ${b.path} ${b.group??""}`.toLowerCase().includes(a)):L?K.filter(a=>a.tab===L&&("appearance"!==L||"Theme"!==a.group)):[]},[L,q,K]),N=(0,e.useCallback)(()=>{g?.(),f()},[f,g]),O=(0,e.useCallback)(async()=>{if(b){A(!0);try{await fK(b,{type:"reload"}),y(!1),h?.()}catch(a){p(a instanceof Error?a.message:String(a))}finally{A(!1)}}},[h,b]),P=k?.tabs.find(a=>a.id===L),Q=q.trim()?`${G("Search")} \xb7 ${M.length}`:P?.label??G("Settings"),R=(a,b)=>[...new Set([...b,...a.map(a=>a.group??"General").filter(a=>!b.includes(a))])].map(b=>{let c=a.filter(a=>(a.group??"General")===b);return c.length?(0,d.jsxs)("section",{className:h4().group,children:[(0,d.jsx)("h3",{className:h4().groupTitle,children:b}),c.map(a=>(0,d.jsx)(im,{field:a,busy:s.has(a.path),error:u[a.path],onSave:b=>void I(a,b)},a.path))]},b):null}),S=()=>m?(0,d.jsx)("div",{className:h4().empty,children:G("Loading omp settings…")}):o||!k?(0,d.jsx)("div",{className:h4().empty,children:o??G("Settings unavailable")}):(0,d.jsxs)("div",{className:h4().scrollContent,children:[(0,d.jsxs)("header",{className:h4().contentHeader,children:[(0,d.jsx)("h2",{className:h4().contentTitle,children:Q}),(0,d.jsx)("p",{className:h4().contentDescription,children:G(q.trim()?"Matching canonical /settings entries across every category.":"Canonical omp /settings values. Changes are saved immediately to the shared agent configuration.")}),w&&b&&(0,d.jsxs)("div",{className:h4().reloadNotice,children:[(0,d.jsx)("span",{children:G("Saved. Reload the active session to apply runtime settings.")}),(0,d.jsx)("button",{type:"button",onClick:()=>void O(),disabled:z,children:G(z?"Reloading…":"Reload session")})]})]}),(0,d.jsx)("div",{className:h4().settingsBody,children:M.length?R(M,P?.groups??[]):(0,d.jsx)("div",{className:h4().empty,children:G("No settings match this search.")})})]});return(0,d.jsx)("div",{className:h4().backdrop,onMouseDown:a=>{a.target===a.currentTarget&&N()},children:(0,d.jsxs)("div",{ref:F,tabIndex:-1,className:h4().window,role:"dialog","aria-modal":"true","aria-label":G("Settings"),children:[(0,d.jsxs)("aside",{className:h4().sidebar,children:[(0,d.jsxs)("div",{className:h4().brand,children:[(0,d.jsx)("div",{className:h4().eyebrow,children:"omp /settings"}),(0,d.jsx)("h1",{className:h4().title,children:G("Settings")}),(0,d.jsx)("code",{className:h4().context,title:a??G("Global configuration"),children:a??G("Global configuration")})]}),(0,d.jsxs)("div",{className:h4().searchWrap,children:[(0,d.jsxs)("svg",{className:h4().searchIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,d.jsx)("path",{d:"m20 20-4-4"})]}),(0,d.jsx)("input",{className:h4().search,value:q,"aria-label":G("Search /settings"),placeholder:G("Search /settings"),onChange:a=>r(a.target.value)})]}),(0,d.jsxs)("nav",{className:h4().nav,children:[(0,d.jsx)("div",{className:h4().navLabel,children:G("Configuration")}),ie.map(b=>{let c=b.labelKey?E(b.labelKey):G(b.label);return(0,d.jsxs)("button",{type:"button",className:h4().navButton,"data-active":!q&&i===b.id,disabled:b.requiresCwd&&!a,title:b.requiresCwd&&!a?`${c} ${G("requires a project")}`:c,onClick:()=>{r(""),j(b.id)},children:[(0,d.jsx)(ih,{kind:b.icon}),(0,d.jsx)("span",{children:c})]},b.id)}),(0,d.jsx)("div",{className:h4().navLabel,children:G("OMP settings")}),k?.tabs.map(a=>(0,d.jsxs)("button",{type:"button",className:h4().navButton,"data-active":!q&&L===a.id,onClick:()=>{r(""),j(`settings:${a.id}`)},children:[(0,d.jsx)(ih,{kind:a.id}),(0,d.jsx)("span",{children:a.label})]},a.id))]}),(0,d.jsx)("div",{className:h4().closeRail,children:(0,d.jsxs)("button",{type:"button",className:h4().closeButton,onClick:N,children:[(0,d.jsx)("span",{children:G("Close settings")}),(0,d.jsx)("span",{"aria-hidden":"true",children:"\xd7"})]})})]}),(0,d.jsx)("main",{className:h4().content,children:q.trim()?S():"models"===i?(0,d.jsx)(hH,{cwd:a,embedded:!0,onClose:N,onModelsChanged:g}):"themes"===i?k?(0,d.jsxs)("div",{className:h4().scrollContent,children:[(0,d.jsxs)("header",{className:h4().contentHeader,children:[(0,d.jsx)("h2",{className:h4().contentTitle,children:G("Themes")}),(0,d.jsxs)("p",{className:h4().contentDescription,children:[G("The web interface uses the same dark and light theme mappings as omp. Changes are persisted to "),(0,d.jsx)("code",{children:"~/.omp/agent/config.yml"}),G(" and applied here immediately.")]})]}),(0,d.jsxs)("div",{className:h4().settingsBody,children:[(0,d.jsx)("div",{className:h4().themeGrid,children:["dark","light"].map(a=>{let b=k.fields.find(b=>b.path===`theme.${a}`),c=k.theme.palettes[a];return(0,d.jsxs)("div",{className:h4().themeCard,children:[(0,d.jsx)(io,{mode:a,palette:c}),(0,d.jsxs)("div",{className:h4().themeCardBody,children:[(0,d.jsxs)("div",{className:h4().themeCardHeader,children:[(0,d.jsxs)("span",{className:h4().themeSlot,children:[a,G(" mapping")]}),B===a&&(0,d.jsx)("span",{className:h4().themeActive,children:G("Active on web")})]}),(0,d.jsx)(gN,{value:String(b.value),disabled:s.has(b.path),ariaLabel:`${a} theme`,options:(b.options??[]).map(a=>({value:a.value,label:a.label,description:a.description})),onChange:a=>void I(b,a)}),B!==a&&(0,d.jsxs)("button",{type:"button",className:h4().closeButton,style:{marginTop:8},onClick:()=>C(a),children:[G("Preview "),a]})]})]},a)})}),R(k.fields.filter(a=>"appearance"===a.tab&&"Theme"===a.group&&!a.path.startsWith("theme.")),["Theme"])]})]}):(0,d.jsx)("div",{className:h4().empty,children:m?G("Loading themes…"):o??G("Themes unavailable")}):"skills"===i&&a?(0,d.jsx)(hQ,{cwd:a,embedded:!0,onClose:N}):"plugins"===i&&a?(0,d.jsx)(h2,{cwd:a,sessionId:b,embedded:!0,onClose:N,onReloaded:h}):"mcp"===i?(0,d.jsx)(ir,{cwd:a,sessionId:b,onReloaded:h}):"access"===i?(0,d.jsx)(h5,{}):"trust"===i?(0,d.jsx)(ic,{cwd:a}):"live-voice"===i?(0,d.jsx)(ia,{}):"attachments"===i?(0,d.jsx)(ib,{}):S()})]})})}function ir({cwd:a,sessionId:b,onReloaded:c}){let[f,g]=(0,e.useState)(null),[h,i]=(0,e.useState)("user"),[j,k]=(0,e.useState)(0),[l,m]=(0,e.useState)(""),[n,o]=(0,e.useState)(""),[p,q]=(0,e.useState)(null),[r,s]=(0,e.useState)(!1),[t,u]=(0,e.useState)(null),v=(0,e.useCallback)(async()=>{try{let b=a?`?cwd=${encodeURIComponent(a)}`:"",c=await fetch(`/api/mcp${b}`,{cache:"no-store"}),d=await c.json();if(!c.ok||d.error)throw Error(d.error??`HTTP ${c.status}`);g(d),q(null)}catch(a){q(a instanceof Error?a.message:String(a))}},[a]),w=f?"user"===h?f.user:f.project:null,x=w?.servers[j]??null,y=a=>{g(b=>{if(!b)return b;let c={..."user"===h?b.user:b.project,servers:a};return"user"===h?{...b,user:c}:{...b,project:c}})},z=async()=>{if(w){s(!0),q(null);try{let b,c=(b=w?.servers??[],(x?.editable===!1?b:b.map((a,b)=>b===j?{...a,name:n,config:JSON.parse(l)}:a)).filter(a=>!1!==a.editable).map(({name:a,config:b})=>({name:a,config:b}))),d=a?`?cwd=${encodeURIComponent(a)}`:"",e=await fetch(`/api/mcp${d}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:h,servers:c})}),f=await e.json();if(!e.ok||f.error)throw Error(f.error??`HTTP ${e.status}`);await v()}catch(a){q(a instanceof Error?a.message:String(a))}finally{s(!1)}}},A=async d=>{u(`${h}:${d.name}`),q(null);try{let e=a?`?cwd=${encodeURIComponent(a)}`:"",f=await fetch(`/api/mcp${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:h,name:d.name,enabled:!d.enabled})}),g=await f.json();if(!f.ok||g.error)throw Error(g.error??`HTTP ${f.status}`);await v(),b&&(await fK(b,{type:"reload"}),c?.())}catch(a){q(a instanceof Error?a.message:String(a))}finally{u(null)}};return(0,d.jsxs)("div",{className:h4().scrollContent,children:[(0,d.jsxs)("header",{className:h4().contentHeader,children:[(0,d.jsx)("h2",{className:h4().contentTitle,children:"MCP servers"}),(0,d.jsx)("p",{className:h4().contentDescription,children:"All MCP servers discovered by OMP are listed by scope and can be enabled or disabled here. Native OMP entries are editable; configurations owned by Claude, Codex, Gemini, plugins, or other providers remain read-only at their source."})]}),(0,d.jsx)("div",{className:h4().settingsBody,children:f?(0,d.jsxs)("div",{className:h4().mcpLayout,children:[(0,d.jsxs)("aside",{className:h4().mcpList,children:[(0,d.jsxs)("div",{className:h4().scopeTabs,children:[(0,d.jsxs)("button",{type:"button",className:h4().scopeButton,"data-active":"user"===h,onClick:()=>{i("user"),k(0)},children:["User \xb7 ",f.user.servers.length]}),(0,d.jsxs)("button",{type:"button",className:h4().scopeButton,"data-active":"project"===h,disabled:!f.project,onClick:()=>{i("project"),k(0)},children:["Project \xb7 ",f.project?.servers.length??0]})]}),w?.error?(0,d.jsx)("div",{className:h4().error,style:{padding:12},children:w.error}):(0,d.jsx)("div",{className:h4().serverRows,children:w?.servers.length?w.servers.map((a,b)=>{let c=`${h}:${a.name}`;return(0,d.jsxs)("div",{className:h4().serverRow,"data-active":j===b,children:[(0,d.jsxs)("button",{type:"button",className:h4().serverSelect,title:a.source?.path,onClick:()=>k(b),children:[(0,d.jsx)("span",{className:h4().statusDot,"data-off":!a.enabled}),(0,d.jsx)("span",{className:h4().serverName,children:a.name}),!1===a.editable&&(0,d.jsx)("span",{className:h4().sourceBadge,children:a.source?.provider??"external"})]}),(0,d.jsx)("button",{type:"button",className:h4().serverToggle,"data-on":a.enabled,disabled:t===c,"aria-pressed":a.enabled,"aria-label":`${a.enabled?"Disable":"Enable"} ${a.name}`,title:`${a.enabled?"Disable":"Enable"} ${a.name}`,onClick:()=>void A(a),children:t===c?"…":a.enabled?"ON":"OFF"})]},`${a.name}-${a.source?.path??b}`)}):(0,d.jsx)("div",{className:h4().serverListEmpty,children:"No servers in this scope."})}),(0,d.jsx)("button",{type:"button",className:h4().addServer,disabled:!!w?.error,onClick:()=>{if(!w)return;let a="new-server",b=2;for(;w.servers.some(b=>b.name===a);)a=`new-server-${b++}`;let c=[...w.servers,{name:a,config:{type:"stdio",command:""},enabled:!0,editable:!0}];y(c),k(c.length-1)},children:"+ Add OMP server"})]}),(0,d.jsx)("section",{className:h4().mcpEditor,children:x?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{className:h4().editorHeader,children:[(0,d.jsx)("input",{className:h4().textInput,value:n,readOnly:!1===x.editable,onChange:a=>o(a.target.value),placeholder:"server-name"}),!1!==x.editable&&(0,d.jsx)("button",{type:"button",className:h4().dangerButton,onClick:()=>{w&&x&&!1!==x.editable&&(y(w.servers.filter((a,b)=>b!==j)),k(Math.max(0,j-1)))},children:"Delete"})]}),!1===x.editable&&(0,d.jsxs)("div",{className:h4().readOnlyNotice,children:["Configuration read-only \xb7 managed by ",x.source?.provider??"an external provider",". Status can be changed from the server list."]}),(0,d.jsx)("textarea",{className:h4().jsonEditor,value:l,readOnly:!1===x.editable,spellCheck:!1,onChange:a=>m(a.target.value)}),(0,d.jsxs)("div",{className:h4().editorActions,children:[(0,d.jsxs)("div",{children:[p&&(0,d.jsx)("div",{className:h4().error,children:p}),(0,d.jsx)("div",{className:h4().saveState,children:x.source?.path??w?.path})]}),!1!==x.editable&&(0,d.jsx)("button",{type:"button",className:h4().primaryButton,disabled:r,onClick:()=>void z(),children:r?"Saving…":"Save MCP"})]})]}):(0,d.jsx)("div",{className:h4().empty,children:"Add or select an MCP server."})})]}):(0,d.jsx)("div",{className:h4().empty,children:p??"Loading MCP configuration…"})})]})}function is({variant:a,locale:b,permission:c,dismissed:e,request:f,dismiss:g}){let h="ko"===b;return null===c||"granted"===c?null:"banner"===a?"default"!==c||e?null:(0,d.jsxs)("div",{className:"workspace-update-banner",role:"region","aria-label":h?"알림 권한 안내":"Notification permission",children:[(0,d.jsx)("span",{className:"workspace-update-banner-detail",style:{fontFamily:"inherit",fontSize:"inherit",color:"inherit"},children:h?"백그라운드 작업 완료 알림을 받으세요.":"Get notified when background work finishes."}),(0,d.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:f,children:h?"알림 켜기":"Enable notifications"}),(0,d.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:g,"aria-label":h?"알림 권한 안내 닫기":"Dismiss notification prompt",children:h?"닫기":"Dismiss"})]}):(0,d.jsx)(k.k.Item,{disabled:"denied"===c,onClick:"default"===c?f:void 0,children:(0,d.jsxs)(k.k.ItemBody,{children:[(0,d.jsx)(k.k.ItemLabel,{children:"default"===c?h?"알림 켜기":"Enable notifications":h?"알림 차단됨":"Notifications blocked"}),"denied"===c&&(0,d.jsx)(k.k.ItemDescription,{children:h?"주소창 옆 사이트 설정에서 알림을 허용하세요.":"Allow notifications in site settings beside the address bar."})]})})}function it({cwd:a,busy:b,scheduled:c,error:f,onCancel:g,onConfirm:h,onCancelSchedule:i}){let{t:j}=(0,x.s)(),k=(0,e.useRef)(null),l={height:32,padding:"0 12px",borderRadius:5,cursor:b?"not-allowed":"pointer",fontSize:12};return(0,d.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"rgba(0,0,0,0.4)"},onClick:a=>{b||a.target!==a.currentTarget||g()},children:(0,d.jsxs)("div",{role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title","aria-describedby":"project-trust-body",style:{width:440,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg-panel)",boxShadow:"0 12px 36px rgba(0,0,0,0.24)",overflow:"hidden"},children:[(0,d.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,d.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:1},children:[(0,d.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),c?(0,d.jsx)("path",{d:"M12 8v4l2 2"}):(0,d.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsx)("div",{id:"project-trust-title",style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:j(c?"trust.scheduledTitle":"trust.dialogTitle")}),(0,d.jsx)("div",{id:"project-trust-body","aria-live":"polite",style:{marginTop:7,fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:j(c?"trust.scheduledBody":"trust.dialogBody")}),(0,d.jsx)("code",{style:{display:"block",marginTop:10,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:a}),f&&(0,d.jsx)("div",{role:"alert",style:{marginTop:10,color:"#ef4444",fontSize:12,lineHeight:1.5},children:f})]})]}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[c&&(0,d.jsx)("button",{type:"button",onClick:i,disabled:b,style:{...l,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:j("trust.cancelSchedule")}),(0,d.jsx)("button",{ref:k,type:"button",onClick:g,disabled:b,style:{...l,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:j(c?"trust.close":"trust.cancel")}),!c&&(0,d.jsx)("button",{type:"button",onClick:h,disabled:b,style:{...l,border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:b?"wait":"pointer",opacity:b?.7:1,fontWeight:600},children:j(b?"trust.trusting":"trust.trustProject")})]})]})})}var iu=c(99952),iv=c(27332);let iw={kind:"loading"};function ix(a){return"failed"===a.status?"var(--danger)":"aborted"===a.status||a.progress?.retryState?"var(--warning)":(0,dY.Ch)(a.status)?"var(--accent)":"var(--success)"}function iy(a){return"live-archive"===a.identity?"실시간 + 디스크":"live"===a.identity?"실시간":"디스크 기록"}let iz={bundled:"기본 제공",user:"사용자 정의",project:"프로젝트 정의"};function iA(a){return a.lastUpdate||a.progress?.durationMs||0}function iB(){return{display:"grid",placeItems:"center",width:32,height:30,padding:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"}}function iC({sessionId:a,sessionCwd:b,record:c,client:f,visible:g,onBack:h}){let i=(0,e.useMemo)(()=>[{key:c.key,liveId:c.live?.id,status:c.live?.status,archiveName:c.archive?.name}],[c.key,c.live?.id,c.live?.status,c.archive?.name]),j=(0,e.useRef)(null),k=(0,dY._Z)(i,{sessionId:a,client:f,enabled:g}).get(c.key)?.state??iw,l="ready-live"===k.kind?k.entries:[],m=(0,e.useMemo)(()=>{let a=new Map;for(let b of l)"message"in b&&"toolResult"===b.message.role&&a.set(b.message.toolCallId,b.message);return a},[l]),n=c.live?.id||c.archive?.name||"Subagent";return(0,d.jsxs)("div",{role:"dialog","aria-label":`${n} 기록`,style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:0},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",borderBottom:"1px solid var(--border)"},children:[(0,d.jsx)("button",{type:"button",onClick:h,"aria-label":"Subagent 목록으로 돌아가기",title:"목록",style:iB(),children:(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m10.5 3-5 5 5 5"})})}),(0,d.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,d.jsx)("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11.5,fontWeight:700},children:n}),(0,d.jsx)("div",{style:{marginTop:2,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9},children:iy(c)})]}),c.live&&(0,d.jsx)("span",{style:{color:ix(c.live),fontFamily:"var(--font-mono)",fontSize:9.5},children:c.live.status})]}),(0,d.jsxs)("div",{ref:j,style:{flex:1,minHeight:0,overflowY:"auto",padding:"10px 12px 18px"},children:["loading"===k.kind&&(0,d.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"기록 불러오는 중…"}),"ready-live"===k.kind&&k.entries.flatMap((a,c)=>{if(!("message"in a))return[];let e=k.entries[c-1];return[(0,d.jsx)(cX,{message:a.message,toolResults:m,cwd:b,showTimestamp:!0,prevTimestamp:e&&"message"in e?e.message.timestamp:void 0},a.id)]}),"ready-archive"===k.kind&&(0,d.jsxs)(d.Fragment,{children:[k.note&&(0,d.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--text-muted)",fontSize:9.5,lineHeight:1.5},children:k.note}),k.truncated&&(0,d.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--warning)",fontSize:9.5},children:"최근 400개 기록만 표시합니다."}),k.entries.map((a,b)=>(0,d.jsxs)("div",{style:{margin:"0 0 7px",padding:"8px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontSize:11,lineHeight:1.55},children:[(0,d.jsxs)("div",{style:{marginBottom:5,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:8.5,letterSpacing:"0.04em"},children:[a.role," \xb7 ",a.kind]}),a.text||"(내용 없음)"]},`${a.at??0}:${b}`))]}),"empty"===k.kind&&(0,d.jsxs)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:[k.note&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{children:k.note}),(0,d.jsx)("br",{})]}),"대화 내용이 없습니다."]}),"unreachable"===k.kind&&(0,d.jsx)("div",{role:"status",style:{padding:10,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",fontSize:10.5,lineHeight:1.5},children:k.message}),"error"===k.kind&&(0,d.jsx)("div",{role:"alert",style:{padding:10,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--danger)",fontSize:10.5,lineHeight:1.5},children:k.message})]})]})}function iD({record:a,onSelect:b}){let c=a.live,e=a.archive,f=(0,b4.$V)(a),g=c?.id||e?.name||"Subagent",h=iy(a),i=(0,b4.wX)(a),j=(0,b4.A7)(a),k=j.modelShort??"모델 미확인",l=j.effort??"추론 미확인",m="known"===i.kind?i.label:"역할 미확인";return(0,d.jsxs)("button",{type:"button",role:"listitem",onClick:b,"data-identity":a.identity,title:`${g}
|
|
19
19
|
${j.model??"모델 미확인"} \xb7 ${l}
|
|
20
20
|
${f.title}${f.stage?`
|
|
21
21
|
현재 단계: ${f.stage}`:""}`,"aria-label":`${m} ${g}, 업무 ${f.title}${f.stage?`, 현재 단계 ${f.stage}`:""}, ${c?c.status:e?.status??"미확인"}, 모델 ${j.model??"미확인"}, 추론 ${l}`,style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",gap:"4px 8px",width:"100%",marginBottom:8,padding:12,border:"1px solid var(--seed-color-stroke-neutral-weak)",borderRadius:"var(--seed-radius-r2)",background:"var(--seed-color-bg-layer-default)",color:"var(--seed-color-fg-neutral)",cursor:"pointer",textAlign:"left"},children:[(0,d.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:["known"===i.kind?(0,d.jsxs)("span",{className:"subagent-role","data-role-kind":"known","data-role":i.agent,title:`${i.agent} \xb7 ${iz[i.source]}`,children:[(0,d.jsx)("span",{className:"sr-only",children:"역할 "}),i.label]}):(0,d.jsx)("span",{className:"subagent-role","data-role-kind":"unknown",title:"역할 정보가 없는 기록입니다.",children:"역할 미확인"}),(0,d.jsx)("span",{className:"subagent-task-line",style:{minWidth:0},children:f.title})]}),c?(0,d.jsx)("span",{style:{color:ix(c),fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:c.status}):e?(0,d.jsx)("span",{style:{color:"failed"===e.status?"var(--danger)":"aborted"===e.status?"var(--warning)":"var(--seed-color-fg-neutral-subtle)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:e.status??"미확인"}):(0,d.jsx)("span",{"aria-hidden":"true"}),f.stage&&(0,d.jsxs)("span",{className:"subagent-stage-line",title:`현재 단계: ${f.stage}`,style:{gridColumn:"1 / -1",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--seed-color-fg-neutral-subtle)",fontSize:"var(--seed-font-size-t2-static)"},children:[(0,d.jsx)("span",{style:{fontWeight:600},children:"현재 단계"})," \xb7 ",f.stage]}),(0,d.jsxs)("span",{className:"subagent-model-line","data-observed":j.model?j.effort?"both":"model":j.effort?"effort":"none","aria-hidden":"true",style:{gridColumn:"1 / -1"},children:[k,j.modelIsFallback&&(0,d.jsx)("span",{className:"subagent-effort",children:" (대체 모델)"}),(0,d.jsxs)("span",{className:"subagent-effort",children:[" \xb7 ",l]})]}),(0,d.jsxs)("span",{style:{gridColumn:"1 / -1",display:"flex",flexWrap:"wrap",gap:"4px 8px",minWidth:0,color:"var(--seed-color-fg-neutral-subtle)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t1-static)"},children:[(0,d.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g}),(0,d.jsx)("span",{children:h})]}),(0,d.jsxs)("span",{style:{gridColumn:"1 / -1",display:"flex",flexWrap:"wrap",gap:"4px 10px",color:"var(--seed-color-fg-neutral-subtle)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t1-static)",fontVariantNumeric:"tabular-nums"},children:[c?.progress&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("span",{children:["도구 ",c.progress.toolCount]}),(0,d.jsxs)("span",{children:[c.progress.tokens.toLocaleString()," Token"]}),(0,d.jsx)("span",{children:function(a=0){let b=Math.max(0,Math.floor(a/1e3));if(b<60)return`${b}초`;let c=Math.floor(b/60);return c<60?`${c}분${b%60?` ${b%60}초`:""}`:`${Math.floor(c/60)}시간 ${c%60}분`}(c.progress.durationMs)})]}),e&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{children:null===e.messages?"메시지 수 미확인":`메시지 ${e.messages}`}),(0,d.jsxs)("span",{children:[(e.bytes/1024).toFixed(+(e.bytes<10240))," KB"]}),(0,d.jsx)("span",{children:function(a=0){let b=Math.max(0,Date.now()-a);return b<1e4?"방금 전":b<6e4?`${Math.floor(b/1e3)}초 전`:b<36e5?`${Math.floor(b/6e4)}분 전`:b<864e5?`${Math.floor(b/36e5)}시간 전`:`${Math.floor(b/864e5)}일 전`}(e.modified)})]})]})]})}function iE({title:a,sessionId:b,sessionPath:c,sessionCwd:f,liveSubagents:g,client:h,visible:i=!0,onClose:j,onReturnFocus:k}){let l=(0,e.useMemo)(()=>h??(0,b4.Et)(),[h]),[m,n]=(0,e.useState)([]),[o,p]=(0,e.useState)({kind:"loading"}),[q,r]=(0,e.useState)({kind:"loading"}),[s,t]=(0,e.useState)(!1),[u,v]=(0,e.useState)(null),[w,x]=(0,e.useState)(0),y=(0,e.useMemo)(()=>(function(a,b){let c=new Map,d=[];for(let e of[...a,...b]){let a=c.get(e.id);if(!a){d.push(e.id),c.set(e.id,e);continue}let[b,f]=iA(e)>=iA(a)?[e,a]:[a,e];c.set(e.id,{...b,assignment:b.assignment??f.assignment,description:b.description??f.description})}return d.flatMap(a=>{let b=c.get(a);return b?[b]:[]})})(g,m),[g,m]),z="ready"===q.kind||"empty"===q.kind?q.data:[],A=(0,e.useMemo)(()=>(0,b4.IA)(y,z),[z,y]),B=u?A.find(a=>a.key===u)??null:null;if(B&&b)return(0,d.jsx)(iC,{sessionId:b,sessionCwd:f,record:B,client:l,visible:i,onBack:()=>v(null)});let C=0===A.length&&"loading"===o.kind&&"loading"===q.kind,D=0===A.length&&("empty"===o.kind||0===g.length)&&"empty"===q.kind;return(0,d.jsxs)("section",{"aria-label":"Subagent 기록","data-state":C?"loading":D?"empty":"ready",style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minWidth:0,minHeight:0,overflow:"hidden",background:"var(--bg-panel)",color:"var(--text)"},children:[(0,d.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",borderBottom:"1px solid var(--border)"},children:[(0,d.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,d.jsx)("div",{style:{fontSize:10,fontWeight:750,letterSpacing:"0.08em",textTransform:"uppercase"},children:a}),(0,d.jsx)("div",{title:c??void 0,style:{marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9},children:b?.slice(0,8)||"세션 없음"})]}),(0,d.jsx)("button",{type:"button",onClick:()=>x(a=>a+1),"aria-label":"Subagent 기록 새로고침",title:"새로고침",style:iB(),children:(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M13 5V2m0 0h-3m3 0-2.1 2.1A5.5 5.5 0 1 0 13.3 9"})})}),j&&(0,d.jsx)("button",{type:"button",onClick:()=>{j?.(),k?.()},"aria-label":"Subagent 기록 닫기",title:"닫기",style:iB(),children:(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})})})]}),(0,d.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"9px 10px 16px"},children:[b?C?(0,d.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"Subagent 기록 불러오는 중…"}):D?(0,d.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:"이 세션은 아직 Subagent를 실행한 적이 없습니다."}):(0,d.jsx)("div",{role:"list","aria-label":"Subagent 실시간 및 디스크 기록",children:A.map(a=>(0,d.jsx)(iD,{record:a,onSelect:()=>v(a.key)},a.key))}):(0,d.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"세션을 선택한 뒤 다시 시도하세요."}),!C&&"loading"===o.kind&&(0,d.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"실시간 상태 불러오는 중…"}),!C&&"loading"===q.kind&&(0,d.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"디스크 기록 불러오는 중…"}),"unreachable"===o.kind&&(0,d.jsx)("div",{role:"status",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",fontSize:9.5},children:o.message}),"error"===o.kind&&(0,d.jsx)("div",{role:"alert",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--danger)",fontSize:9.5},children:o.message}),"unreachable"===q.kind&&(0,d.jsx)("div",{role:"status",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",fontSize:9.5},children:q.message}),"error"===q.kind&&(0,d.jsx)("div",{role:"alert",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--danger)",fontSize:9.5},children:q.message}),s&&(0,d.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--warning)",fontSize:9.5},children:"최근 디스크 기록 60개만 표시합니다."})]})]})}let iF=["process","efficiency","subagents","files","resource","sidechat"];function iG({activeView:a,onViewChange:b,viewLabels:c,sessionId:e,sessionPath:f,sessionName:g,sessionCwd:j,liveSubagents:k,subagentClient:l,processSlot:m,fileSlot:n,sideChatSlot:o,resourceSlot:p,efficiencySlot:q,visible:r=!0,onClose:s,onReturnFocus:t}){return(0,d.jsx)("aside",{className:"auxiliary-deck","aria-label":"보조 패널","data-auxiliary-view":a,children:(0,d.jsxs)(iu.J.Root,{className:"auxiliary-deck-tabs",size:"small",contentLayout:"fill",triggerLayout:"hug",value:a,onValueChange:a=>b(a),children:[(0,d.jsxs)("div",{className:"auxiliary-deck-tabbar",children:[(0,d.jsxs)(iu.J.List,{"aria-label":"보조 패널 보기",children:[iF.map(a=>{let b="subagents"===a?k.filter(a=>"pending"===a.status||"running"===a.status).length:0;return(0,d.jsxs)(iu.J.Trigger,{value:a,"aria-label":b>0?`${c[a]} (실행 중 ${b})`:void 0,children:[(0,d.jsx)("span",{className:"auxiliary-deck-tab-label",children:c[a]}),b>0&&(0,d.jsx)(iv.E,{size:"medium",variant:"weak",tone:"informative","aria-hidden":"true",children:b})]},a)}),(0,d.jsx)(iu.J.Indicator,{})]}),s&&(0,d.jsx)(h.r,{className:"auxiliary-deck-close",variant:"ghost",size:"small",layout:"iconOnly",onClick:()=>{s?.(),t?.()},"aria-label":"보조 패널 닫기",children:(0,d.jsx)(i.In,{size:"16px",svg:(0,d.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})})})})]}),(0,d.jsx)(iu.J.Content,{value:"process",className:"auxiliary-deck-panel",children:m}),(0,d.jsx)(iu.J.Content,{value:"efficiency",className:"auxiliary-deck-panel",children:q}),(0,d.jsx)(iu.J.Content,{value:"subagents",className:"auxiliary-deck-panel",children:(0,d.jsx)(iE,{title:c.subagents,sessionId:e,sessionPath:f,sessionCwd:j,liveSubagents:k,client:l,visible:r&&"subagents"===a})}),(0,d.jsx)(iu.J.Content,{value:"files",className:"auxiliary-deck-panel",children:n}),(0,d.jsx)(iu.J.Content,{value:"sidechat",className:"auxiliary-deck-panel",children:o}),(0,d.jsx)(iu.J.Content,{value:"resource",className:"auxiliary-deck-panel",children:p})]})})}function iH({title:a,data:b,onOpenFile:c}){let{t:f}=(0,x.s)(),g=b?.groups??[],[i,j]=(0,e.useState)(()=>new Set);return(0,d.jsxs)("section",{className:"process-log","aria-label":a,children:[(0,d.jsxs)("header",{className:"process-log-header",children:[(0,d.jsx)("h2",{children:a}),(0,d.jsx)("span",{className:"process-log-count",children:g.length>0?`${g.length} ${f(1===g.length?"process.turn":"process.turns")}`:""})]}),(0,d.jsxs)("div",{className:"process-log-body",children:[b?.status?(0,d.jsxs)("p",{className:"process-log-status",role:"status",children:[(0,d.jsx)("span",{className:"process-log-status-pulse","aria-hidden":"true"}),b.status]}):null,0===g.length?(0,d.jsx)("p",{className:"process-log-empty",children:f("process.empty")}):g.map((a,e)=>{let g=i.has(a.anchorIdx),k=function(a){if(!a||"user"!==a.role)return null;let b=("string"==typeof a.content?a.content:a.content.filter(a=>"text"===a.type).map(a=>a.text).join(" ")).replace(/\s+/g," ").trim();return 0===b.length?null:b.length>72?`${b.slice(0,72)}…`:b}(b?.messages[a.anchorIdx]),l=[`${a.messageCount} ${f(1===a.messageCount?"chat.message":"chat.messages")}`];return a.toolCallCount>0&&l.push(`${a.toolCallCount} ${f(1===a.toolCallCount?"chat.toolCall":"chat.toolCalls")}`),(0,d.jsxs)("article",{className:"process-log-turn","data-process-turn":a.anchorIdx,children:[(0,d.jsxs)(h.r,{className:"process-log-turn-toggle",variant:"ghost",size:"small",layout:"withText","aria-expanded":!g,onClick:()=>j(b=>{let c=new Set(b);return c.has(a.anchorIdx)?c.delete(a.anchorIdx):c.add(a.anchorIdx),c}),title:g?f("chat.expandProcess"):f("chat.collapseProcess"),children:[(0,d.jsx)("span",{className:"process-log-turn-title",children:k??f("chat.processDetails")}),(0,d.jsx)("span",{className:"process-log-turn-meta",children:l.join(" \xb7 ")})]}),!g&&(0,d.jsx)("div",{className:"process-log-entries",children:a.entries.map((e,f)=>{let g=b?.messages[e.idx];return g?(0,d.jsx)(cX,{message:e.blocks?av(g,e.blocks,{omitUsage:!0}):g,toolResults:b?.toolResults,modelNames:b?.modelNames,cwd:b?.cwd,onOpenFile:c,entryId:b?.entryIds[e.idx],sessionId:b?.sessionId,showTimestamp:!1},`process-${a.anchorIdx}-${f}`):null})})]},`turn-${a.anchorIdx}-${e}`)})]})]})}let iI=6,iJ="omp-btw-log:",iK="omp-btw-log-index";function iL(a){return a.trim().toLowerCase()}function iM(a){return a.map(a=>({q:a.q,a:a.a,at:a.at}))}function iN(a){if(!Array.isArray(a))return[];let b=[],c=0;for(let d of a){if(!d||"object"!=typeof d||"string"!=typeof d.q||"string"!=typeof d.a)continue;let a={q:d.q,a:d.a,at:"number"==typeof d.at&&Number.isFinite(d.at)?d.at:0};b.push(a),c+=a.q.length+a.a.length}for(;b.length>40||c>12e4;){let a=b.shift();if(!a)break;c-=a.q.length+a.a.length}return b}function iO(a){return!!a&&"object"==typeof a&&("QuotaExceededError"===a.name||22===a.code||1014===a.code)}function iP(a,b={}){let c=b.now??Date.now,d=new Map,e=new Set,f=!1,g=[],h=b=>{if(a)try{a.removeItem(b)}catch{}},i=a=>{d.delete(a),e.delete(a),h(iJ+a)},j=()=>{let a=new Set,b=[];for(let c of(g.sort((a,b)=>b.updatedAt-a.updatedAt),g))!c.id||a.has(c.id)||(a.add(c.id),b.length<20?b.push(c):i(c.id));g=b},k=()=>{if(!f){if(f=!0,a)try{let b=a.getItem(iK),c=b?JSON.parse(b):[];Array.isArray(c)&&(g=c.flatMap(a=>a&&"object"==typeof a&&"string"==typeof a.id&&a.id?[{id:iL(a.id),updatedAt:"number"==typeof a.updatedAt&&Number.isFinite(a.updatedAt)?a.updatedAt:0}]:[]))}catch{g=[]}j()}},l=a=>{k();for(let b=g.length-1;b>=0;b-=1){if(g[b].id===a)continue;let[c]=g.splice(b,1);return i(c.id),!0}return!1},m=b=>{if(a){try{a.setItem(iK,JSON.stringify(g));return}catch(a){if(!iO(a)||!l(b))return}try{a.setItem(iK,JSON.stringify(g))}catch{}}},n=b=>{let c=iL(b);if(!c)return[];if(e.has(c))return iM(d.get(c)??[]);if(a)try{let b=a.getItem(iJ+c);if(b){let a=JSON.parse(b),e=iN(a?.entries);return d.set(c,e),iM(e)}}catch{}return iM(d.get(c)??[])},o=a=>{let b=iL(a);b&&(k(),g=g.filter(a=>a.id!==b),i(b),m(null))};return{read:n,append:(b,f)=>((b,f)=>{let h=iL(b);if(!h)return[];let i=iN(f),n=c();if(d.set(h,iM(i)),k(),(g=g.filter(a=>a.id!==h)).unshift({id:h,updatedAt:n}),j(),m(h),!a)return iM(i);let o=JSON.stringify({updatedAt:n,entries:i});try{return a.setItem(iJ+h,o),e.delete(h),iM(i)}catch(a){if(!iO(a)||!l(h))return e.add(h),iM(i)}m(h);try{a.setItem(iJ+h,o),e.delete(h)}catch{e.add(h)}return iM(i)})(b,[...n(b),f]),history:(a,b=iI)=>n(a).slice(-Math.max(0,b)).map(({q:a,a:b})=>({q:a,a:b})),clear:o,cleanup:(b,d)=>{if(!b.complete)return;k();let e=new Map;for(let a of b.sessions){if(!a||"string"!=typeof a.id||!a.id)continue;let b=iL(a.id),c="number"==typeof a.modified?a.modified:Date.parse(a.modified);e.set(b,Number.isFinite(c)?c:0)}let f=d?iL(d):null,i=c();for(let a of[...g])if(a.id!==f){if(!e.has(a.id)){o(a.id);continue}i-Math.max(e.get(a.id)??0,a.updatedAt)>6048e5&&o(a.id)}if(!a||"function"!=typeof a.key||"number"!=typeof a.length)return;let j=[];try{for(let b=0;b<a.length;b+=1){let c=a.key(b);if(!c?.startsWith(iJ))continue;let d=iL(c.slice(iJ.length));e.has(d)||d===f||j.push(c)}}catch{return}for(let a of j)h(a)}}}function iQ(){let a=new Map,b=new Map,c=new Map,d=a=>{c.get(a)?.forEach(a=>{a()})};return{read(b){let c=a.get(b);return c?{...c.snapshot}:null},begin(b,c){if(a.has(b))return null;let e=new AbortController;return a.set(b,{snapshot:{sessionId:b,question:c,text:"",model:null},controller:e}),d(b),{controller:e}},ingest(b,c){let e=a.get(b);e&&("d"===c.t?e.snapshot.text+=c.v:"done"===c.t?e.snapshot.text=c.v||e.snapshot.text:"m"===c.t&&(e.snapshot.model=c.v),d(b))},abort(b){let c=a.get(b);return!!c&&(c.controller.abort(),!0)},finish(c,e){a.has(c)&&(a.delete(c),b.set(c,e),d(c))},takeOutcome(a){let c=b.get(a)??null;return c&&b.delete(a),c},subscribe(a,b){let d=c.get(a);return d||(d=new Set,c.set(a,d)),d.add(b),()=>{d.delete(b),0===d.size&&c.delete(a)}}}}class iR extends Error{constructor(a,b,c){super(b),this.kind=a,this.status=c,this.name="SideChatRequestError"}}function iS(a){let b;try{b=JSON.parse(a)}catch{throw new iR("stream","사이드채팅 스트림을 해석할 수 없습니다.")}if(!b||"object"!=typeof b)throw new iR("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");let c=b;if("d"!==c.t&&"done"!==c.t&&"m"!==c.t&&"err"!==c.t||"string"!=typeof c.v)throw new iR("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");return{t:c.t,v:c.v}}class iT{push(a){this.buffer+="string"==typeof a?a:this.decoder.decode(a,{stream:!0});let b=this.buffer.split("\n");return this.buffer=b.pop()??"",b.flatMap(a=>a.trim()?[iS(a)]:[])}finish(){this.buffer+=this.decoder.decode();let a=this.buffer.trim();return this.buffer="",a?[iS(a)]:[]}constructor(){this.decoder=new TextDecoder,this.buffer=""}}async function iU(a){let b=await a.text().catch(()=>"");if(!b)return`HTTP ${a.status}`;try{let a=JSON.parse(b);if("string"==typeof a.error&&a.error)return a.error}catch{}return b}function iV(a=!1){return{minHeight:30,padding:"4px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:a?"var(--text-dim)":"var(--text-muted)",cursor:a?"default":"pointer",fontSize:"var(--seed-font-size-t2-static)",fontWeight:650}}function iW({children:a}){return(0,d.jsx)("div",{className:"side-chat-question",style:{alignSelf:"flex-end",maxWidth:"92%",padding:"8px 10px",border:"1px solid var(--border)",color:"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55},children:a})}function iX({children:a,streaming:b=!1}){return(0,d.jsxs)("div",{className:`side-chat-answer${b?" is-streaming":""}`,style:{alignSelf:"flex-start",maxWidth:"100%",padding:"8px 10px",border:"1px solid var(--border)",color:"var(--text)",overflowWrap:"anywhere",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.58},children:[a?(0,d.jsx)(bw,{isStreaming:b,children:a}):b?"응답을 기다리는 중…":null,b&&(0,d.jsx)("span",{"aria-hidden":"true",style:{marginLeft:2,color:"var(--accent)"},children:"▍"})]})}function iY({identity:a,status:b,utteranceKey:c,children:e}){let f=bQ(a?.sessionId,a?.provider,a?.credentialId),g=dM(f?.alias,b,c);return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:5},children:[f&&a?.provider&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:9,minHeight:40,marginBottom:2},children:[(0,d.jsx)(bU,{seed:f.seed,size:40,provider:a.provider}),(0,d.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:f.alias})]}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:7,minWidth:0,maxWidth:"100%"},children:[e,g&&(0,d.jsx)("img",{src:g.src,alt:g.alt,width:52,height:52,style:{flex:"0 0 auto",objectFit:"contain"}})]})]})}function iZ({title:a,sessionId:b,sessionPath:c,sessionName:f,historyStore:g,flights:h,sessionCensus:i,client:j,visible:k=!0,onClose:l,onReturnFocus:m}){let n,o,p=(0,e.useMemo)(()=>j??function(a=(a,b)=>fetch(a,b),b="/api/sidecars/sidechat/ask"){return{async ask(c){let d;try{d=await a(b,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionPath:c.sessionPath,question:c.question,history:c.history.slice(-iI)}),signal:c.signal})}catch(a){if(c.signal?.aborted)throw a;throw new iR("unreachable","사이드채팅 사이드카(30143)에 연결할 수 없습니다.")}if(!d.ok)throw new iR("http",await iU(d),d.status);if(!d.body)throw new iR("stream","사이드채팅 스트림을 열 수 없습니다.");let e=d.body.getReader(),f=new iT,g="",h=null,i=a=>{for(let b of a)if(c.onEvent?.(b),"d"===b.t)g+=b.v;else if("done"===b.t)g=b.v||g;else if("m"===b.t)h=b.v;else throw new iR("server",b.v)};try{for(;;){let a=await e.read();if(a.done)break;i(f.push(a.value))}i(f.finish())}catch(a){if(c.signal?.aborted||a instanceof iR)throw a;throw new iR("stream",a instanceof Error?a.message:"사이드채팅 스트림이 중단되었습니다.")}finally{e.releaseLock()}if(!g)throw new iR("empty","사이드채팅이 빈 응답을 반환했습니다.");return{text:g,model:h}}}}(),[j]),q=b?.toLowerCase()??null,[r,s]=(0,e.useState)([]),[t,u]=(0,e.useState)({}),v=q??"",w=t[v]??"",x=(a,b)=>{u(c=>{if((c[a]??"")===b)return c;let d={...c};return b?d[a]=b:delete d[a],d})},[y,z]=(0,e.useState)(0),[A,B]=(0,e.useState)({}),[C,D]=(0,e.useState)({}),[E,F]=(0,e.useState)({}),[G,H]=(0,e.useState)(null),[I,J]=(0,e.useState)(null),[K,L]=(0,e.useState)({}),[M,N]=(0,e.useState)({}),[O,P]=(0,e.useState)({}),Q=(0,e.useRef)((n=new Set,o=new Set,{claim:a=>!(!a||n.has(a)||o.has(a))&&(n.add(a),!0),markSent(a){n.delete(a),o.add(a)},release(a){n.delete(a)}})),R=(0,e.useRef)(!0),S=(0,e.useRef)(q),T=(0,e.useRef)(k),U=(0,e.useRef)(null),V=(0,e.useRef)(!1),W=(0,e.useRef)(0),X=(0,e.useRef)(null);S.current=q,T.current=k;let Y=async a=>{if(!q||!c){let a=q??"";D(b=>({...b,[a]:"세션 파일이 준비되지 않았습니다. 기록이 생성된 뒤 다시 시도하세요."}));return}let b=h.begin(q,a);if(!b)return;let{signal:d}=b.controller;D(a=>{let b={...a};return delete b[q],b});try{let b=await p.ask({sessionPath:c,question:a,history:g.history(q),signal:d,onEvent:a=>h.ingest(q,a)});g.append(q,{q:a,a:b.text,at:Date.now()}),h.finish(q,{kind:"done",model:b.model})}catch(c){let b=h.read(q)?.text??"";if(d.aborted){let c=!1;b&&(g.append(q,{q:a,a:b,at:Date.now()}),c=!0),h.finish(q,{kind:"aborted",saved:c})}else{let d=c instanceof iR?c.kind:"unknown",e=c instanceof Error?c.message:String(c);h.finish(q,{kind:"failed",question:a,partialAnswer:b,errorKind:d,errorMessage:e})}}finally{R.current&&T.current&&U.current?.focus()}},Z=async(a,b,c)=>{if(!q)return;let d=`${q}:${b}`;if(Q.current.claim(d)){N(a=>({...a,[d]:"sending"})),P(a=>{let b={...a};return delete b[d],b});try{var e,f;let b,g=await fetch(`/api/agent/${encodeURIComponent(q)}`,{cache:"no-store"}),h=null;try{h=await g.json()}catch{}if(!g.ok){if(h&&"object"==typeof h&&"error"in h&&"string"==typeof h.error)throw Error(h.error);throw Error(`HTTP ${g.status}`)}let i=function(a){if(!a||"object"!=typeof a||!("running"in a)||"boolean"!=typeof a.running)return null;if(!a.running)return!1;if(!("state"in a)||!a.state||"object"!=typeof a.state)return null;let b=a.state;return"isStreaming"in b&&"boolean"==typeof b.isStreaming&&"isPromptRunning"in b&&"boolean"==typeof b.isPromptRunning&&"isBashRunning"in b&&"boolean"==typeof b.isBashRunning&&"isCompacting"in b&&"boolean"==typeof b.isCompacting&&"isHandoffRunning"in b&&"boolean"==typeof b.isHandoffRunning?b.isStreaming||b.isPromptRunning||b.isBashRunning||b.isCompacting||b.isHandoffRunning:null}(h);if(null===i)throw Error("메인 세션 실행 상태를 확인할 수 없습니다.");let j=(e=a.q,f=a.a,b=c.trim(),["사이드채팅 문답을 메인 대화에서 이어서 처리해 주세요.","","[사이드채팅 질문]",e,"","[사이드채팅 답변]",f,...b?["","[추가 지시]",b]:[]].join("\n"));await fK(q,{type:i?"steer":"prompt",message:j}),Q.current.markSent(d),N(a=>({...a,[d]:"sent"}))}catch(a){Q.current.release(d),N(a=>{let b={...a};return delete b[d],b}),P(b=>({...b,[d]:a instanceof Error?a.message:String(a)}))}}},$=()=>{if(q&&null!==h.read(q))return void h.abort(q);let a=w.trim();a&&(x(v,""),Y(a))},_=A[q??""]??[],aa=C[q??""],ab=q?h.read(q):null,ac=r.length>0||_.length>0||null!==ab,ad=ab?.model??E[q??""],ae=!q||!c,af=null!==ab,ag=!af&&!ae&&w.trim().length>0,ah=!q||af,ai=G?.sessionId===q?G:null;return(0,d.jsxs)("section",{className:"side-chat-panel","aria-label":"사이드채팅","aria-busy":null!==ab,"data-state":q&&c?ab?"streaming":"ready":"unavailable",style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minWidth:0,minHeight:0,overflow:"hidden",background:"var(--bg-panel)",color:"var(--text)"},children:[(0,d.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,d.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,d.jsx)("div",{style:{fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:a}),(0,d.jsxs)("div",{title:c??void 0,style:{marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)"},children:[f||q?.slice(0,8)||"세션 없음",ad?` \xb7 ${ad}`:""]})]}),(0,d.jsx)("button",{type:"button",onClick:()=>{q&&null===h.read(q)&&(g.clear(q),s([]),B(a=>{let b={...a};return delete b[q],b}),D(a=>({...a,[q]:"현재 세션의 사이드채팅 기록을 비웠습니다."})))},disabled:ah,style:iV(ah),children:"Clear"}),l&&(0,d.jsx)("button",{type:"button",onClick:()=>{l?.(),m?.()},"aria-label":"사이드채팅 닫기",title:"닫기",style:{...iV(),width:32,padding:0},children:(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})})})]}),(0,d.jsxs)("div",{ref:X,"aria-live":"polite",style:{display:"flex",flex:1,minHeight:0,flexDirection:"column",gap:7,overflowY:"auto",padding:"11px 12px 18px"},children:[q&&c?(0,d.jsxs)(d.Fragment,{children:[r.map((a,b)=>{let c=`${a.at}:${b}`,e=`${q}:${c}`,f=M[e],g=I===e;return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,d.jsx)(iW,{children:a.q}),(0,d.jsx)(iY,{identity:ai,status:"settled",utteranceKey:c,children:(0,d.jsx)(iX,{children:a.a})}),"sent"===f?(0,d.jsx)("span",{role:"status",style:{color:"var(--text-muted)",fontSize:10.5},children:"보냄"}):(0,d.jsxs)(d.Fragment,{children:[!g&&(0,d.jsx)("button",{type:"button","aria-expanded":"false",onClick:()=>J(e),style:{...iV(),alignSelf:"flex-start"},children:"메인에 보내기"}),g&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:6},children:[(0,d.jsx)("label",{htmlFor:`side-chat-forward-${b}`,style:{color:"var(--text-muted)",fontSize:10.5},children:"메인에 덧붙일 지시 (선택)"}),(0,d.jsx)("textarea",{id:`side-chat-forward-${b}`,rows:2,value:K[e]??"",onChange:a=>L(b=>({...b,[e]:a.target.value})),style:{width:"100%",minWidth:0,boxSizing:"border-box",resize:"vertical",padding:"7px 8px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5}}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,d.jsx)("button",{type:"button",onClick:()=>void Z(a,c,K[e]??""),disabled:"sending"===f,style:iV("sending"===f),children:"sending"===f?"보내는 중…":"메인으로 전송"}),"sending"!==f&&(0,d.jsx)("button",{type:"button",onClick:()=>J(null),style:iV(),children:"취소"})]})]}),O[e]&&(0,d.jsx)("div",{role:"alert",style:{color:"var(--danger)",fontSize:10.5,lineHeight:1.5,overflowWrap:"anywhere"},children:O[e]})]})]},c)}),_.map((a,b)=>(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,d.jsx)(iW,{children:a.question}),(0,d.jsxs)(iY,{identity:ai,status:"failed",utteranceKey:`failed:${a.question}:${b}`,children:[a.partialAnswer&&(0,d.jsx)(iX,{children:a.partialAnswer}),(0,d.jsx)("div",{role:"alert","data-error-kind":a.kind,style:{padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--danger)",fontSize:10.5,lineHeight:1.5,overflowWrap:"anywhere"},children:a.message})]})]},`${a.question}:${b}`)),ab&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,d.jsx)(iW,{children:ab.question}),(0,d.jsx)(iY,{identity:ai,status:"streaming",utteranceKey:`stream:${ab.question}`,children:(0,d.jsx)(iX,{streaming:!0,children:ab.text})})]}),!ac&&(0,d.jsxs)("div",{style:{margin:"auto 0",padding:16,color:"var(--text-muted)",textAlign:"center",fontSize:11,lineHeight:1.65},children:["현재 세션의 전체 맥락을 보고 답합니다.",(0,d.jsx)("br",{}),"사이드채팅 기록은 부모 세션별로 보관됩니다."]})]}):(0,d.jsxs)("div",{role:"status",style:{margin:"auto 0",padding:16,color:"var(--text-muted)",textAlign:"center",fontSize:11,lineHeight:1.6},children:["세션 기록을 준비하는 중입니다.",(0,d.jsx)("br",{}),"세션 파일이 생성되면 사이드채팅을 사용할 수 있습니다."]}),aa&&(0,d.jsx)("div",{role:"status",style:{padding:"7px 9px",color:"var(--text-muted)",fontSize:10.5,lineHeight:1.5},children:aa})]}),(0,d.jsxs)("form",{onSubmit:a=>{a.preventDefault(),$()},style:{display:"flex",flexDirection:"column",gap:6,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,d.jsx)("label",{htmlFor:"side-chat-question",style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:"사이드채팅 질문"}),(0,d.jsx)("textarea",{ref:U,id:"side-chat-question",rows:4,value:w,onChange:a=>x(v,a.target.value),onCompositionStart:()=>{V.current=!0},onCompositionEnd:()=>{V.current=!1,W.current=Date.now()},onKeyDown:a=>{if("Enter"!==a.key||a.shiftKey)return;let b=a.nativeEvent,c=Date.now()-W.current<100;if(V.current||b.isComposing||229===b.keyCode||c){c&&a.preventDefault();return}af||(a.preventDefault(),$())},disabled:af||ae,placeholder:"질문 입력 — Enter 전송, Shift+Enter 줄바꿈",style:{width:"100%",minWidth:0,minHeight:88,maxHeight:240,boxSizing:"border-box",resize:"vertical",padding:"8px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5}}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,d.jsx)("span",{"aria-live":"polite",style:{flex:1,minWidth:0,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.4,overflowWrap:"anywhere"},children:ae?"세션 파일이 준비되면 질문할 수 있습니다.":af?"응답을 받는 중입니다.":"Enter 전송 \xb7 Shift+Enter 줄바꿈"}),(0,d.jsx)("button",{type:"submit",disabled:!af&&!ag,style:iV(!af&&!ag),children:af?"중단":"전송"})]})]})]})}function i$(a){let[b,c]=(0,e.useState)(()=>Date.now());return b}let i_="min-h-9 border border-border bg-bg px-3 text-xs font-medium text-text transition-colors hover:bg-bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-not-allowed disabled:opacity-50";function i0(...a){return a.filter(Boolean).join(" ")}function i1(a,b){let c=Math.floor((a-b)/6e4);if(c<=0)return"리셋됨";let d=Math.floor(c/1440),e=Math.floor(c%1440/60),f=c%60;return d>0?`${d}d ${e}h 후 리셋`:e>0?`${e}h ${f}m 후 리셋`:`${f}m 후 리셋`}function i2(a,b){if(!a)return null;let c=Date.parse(a);if(!Number.isFinite(c))return null;let d=Math.floor((c-b)/6e4);if(d<=0)return"만료됨";let e=Math.floor(d/1440),f=Math.floor(d%1440/60),g=d%60;return e>0?`${e}d ${f}h 후 만료`:f>0?`${f}h ${g}m 후 만료`:`${g}m 후 만료`}function i3(a){return"number"==typeof a&&Number.isFinite(a)?0===a?"$0":a>=100?`$${a.toFixed(0)}`:a>=1?`$${a.toFixed(2)}`:a>=.01?`$${a.toFixed(3)}`:`$${a.toFixed(4)}`:"—"}function i4(a){return"number"==typeof a&&Number.isFinite(a)?Math.round(a).toLocaleString("en-US"):"—"}function i5(a){return"number"==typeof a&&Number.isFinite(a)?a>=1e9?`${(a/1e9).toFixed(1)}B`:a>=1e6?`${(a/1e6).toFixed(1)}M`:a>=1e3?`${Math.round(a/1e3)}K`:String(Math.round(a)):"—"}function i6(a,b=0){return"number"==typeof a&&Number.isFinite(a)?`${(100*a).toFixed(b)}%`:"—"}function i7(a){return"number"==typeof a&&Number.isFinite(a)?`${(a/1e3).toFixed(1)}s`:"—"}function i8(a){let b=new Date(a);return`${b.getMonth()+1}/${b.getDate()}`}function i9({label:a,value:b}){return(0,d.jsxs)("div",{className:"flex min-w-0 items-baseline justify-between gap-3 border-b border-border py-1.5 last:border-b-0",children:[(0,d.jsx)("dt",{className:"text-xs text-text-muted",children:a}),(0,d.jsx)("dd",{className:"m-0 font-mono text-xs tabular-nums text-text",children:b})]})}function ja({state:a,loading:b,subject:c}){return b&&"idle"===a.status?(0,d.jsxs)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:[c," 불러오는 중…"]}):"error"===a.status?(0,d.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,d.jsxs)("div",{className:"font-medium",children:[c,"을 불러오지 못했습니다."]}),(0,d.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:a.error.message}),(0,d.jsx)("div",{className:"mt-2 text-xs text-text-dim",children:"사이드카(127.0.0.1:30142)가 실행 중인지 확인하세요."})]}):"stale"===a.status?(0,d.jsxs)("div",{className:"border-b border-border bg-bg px-4 py-2 text-xs text-text-muted",role:"status",children:["마지막 데이터를 표시합니다. 새로고침 실패: ",a.error.message]}):null}function jb(a){let b=new Date(a),c=String(b.getHours()).padStart(2,"0"),d=String(b.getMinutes()).padStart(2,"0");return`${b.getMonth()+1}/${b.getDate()} ${c}:${d}`}function jc({limit:a,now:b,detailed:c}){let e="number"==typeof a.amount?.usedFraction?a.amount.usedFraction:0,f=Math.max(0,Math.min(100,100*e)),g=Math.round(100*e),h=function(a,b){let c=a.window,d=a.amount?.usedFraction;if(!c?.resetsAt||"number"!=typeof d)return null;let e=Math.max(0,c.resetsAt-b),f=100*d,g=Math.max(0,100-f);if(!c.durationMs){let a=e/864e5;return{burnOnly:!0,unit:"하루",partial:a<1,burn:a>=1?g/a:g}}let h=Math.min(c.durationMs,Math.max(0,c.durationMs-e)),i=c.durationMs>432e5,j=i?864e5:36e5,k=c.durationMs/j,l=e/j,m=h/c.durationMs*100;return{burnOnly:!1,unit:i?"하루":"시간",partial:l<1,burn:l>=1?g/l:g,pacePct:m,deltaPct:f-m,nominal:100/k}}(a,b),i=a.daySlot,j=i?.usedPct==null||null==i.baselinePct?null:Math.max(0,Math.min(i.baselinePct,100)),k=null==j?null:Math.max(j,Math.min(100*e,100)),l=h?.pacePct==null?null:Math.min(h.pacePct,99.6),m=g>=90,n=h?.deltaPct!=null&&h.deltaPct>=.5?h.deltaPct:null,o=i?"unknown"===i.quality||null==i.usedPct?"구간 사용 — 기록 부족":"approx"===i.quality?`구간 사용 ≈${i.usedPct.toFixed(0)}% \xb7 추정`:`구간 사용 ${i.usedPct.toFixed(1)}%`:null;return(0,d.jsxs)("div",{className:"usage-limit py-2",children:[(0,d.jsxs)("div",{className:"flex items-baseline justify-between gap-2",children:[(0,d.jsx)("span",{className:"min-w-0 flex-1 truncate text-[13px] text-text-muted",children:a.label||a.id}),e>=1?(0,d.jsx)("span",{className:"usage-chip","data-tone":"danger",children:e>1?"한도 초과":"한도 도달"}):null,null!=n?(0,d.jsx)("span",{className:"usage-chip","data-tone":"warning",children:`과속 +${n.toFixed(1)}%`}):null,(0,d.jsxs)("span",{className:i0("shrink-0 font-mono text-sm font-semibold tabular-nums",m?"text-danger":"text-text"),children:[g,"%"]})]}),(0,d.jsxs)("div",{className:"relative mt-1 h-3.5 overflow-hidden border border-border-strong bg-metric-track",role:"progressbar","aria-label":`${a.label||a.id} 사용량`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":g,children:[(0,d.jsx)("div",{className:i0("absolute inset-y-0 left-0",m?"bg-danger":"bg-metric"),style:{width:`${f}%`}}),null!=j&&null!=k&&k>j?(0,d.jsx)("div",{className:"absolute inset-y-0 bg-metric-recent",style:{left:`${j}%`,width:`${k-j}%`,boxShadow:"inset 1px 0 var(--bg-panel)"}}):null,null!=l?(0,d.jsx)("div",{className:"absolute inset-y-0 w-0.5 bg-text",style:{left:`${l}%`,boxShadow:"0 0 0 1px color-mix(in srgb, var(--bg-panel) 80%, transparent)"},"aria-hidden":"true"}):null,e>1?(0,d.jsx)("div",{className:"absolute inset-y-0 right-0 w-1 bg-danger","aria-hidden":"true"}):null]}),o||a.window?.resetsAt?(0,d.jsxs)("div",{className:"mt-1 flex items-baseline justify-between gap-3 font-mono text-[11px] tabular-nums text-text-muted",children:[(0,d.jsx)("span",{className:"min-w-0 truncate",children:o??""}),a.window?.resetsAt?(0,d.jsx)("span",{className:"shrink-0",children:i1(a.window.resetsAt,b)}):null]}):null,c?(0,d.jsxs)("dl",{className:"m-0 mt-1.5 border-s-2 border-border ps-2.5",children:[h?.pacePct!=null?(0,d.jsx)(i9,{label:"페이스",value:`${h.pacePct.toFixed(1)}%`}):null,h?(0,d.jsx)(i9,{label:h.partial?"남은 한도":`앞으로 ${h.unit}`,value:`${h.burn.toFixed(1)}%`}):null,h?.nominal!=null?(0,d.jsx)(i9,{label:"균등 배분 기준",value:`${h.nominal.toFixed(1)}%/${"하루"===h.unit?"일":"시간"} \xb7 계산값`}):null,i?(0,d.jsx)(i9,{label:"구간",value:`${jb(i.slotStart)} ~ ${jb(i.slotEnd)} \xb7 ${i.slotIndex+1}/${i.slotCount}`}):null,i?(0,d.jsx)(i9,{label:"기록 품질",value:function(a){let b;if("unknown"===a.quality)return"기록 부족 \xb7 구간 시작 전 표본이 없습니다";let c=null==a.gapMs||0===a.gapMs?null:(b=Math.round(a.gapMs/6e4))<60?`${b}분`:`${Math.floor(b/60)}시간 ${b%60}분`;return"exact"===a.quality?c?`실측 \xb7 경계 ${c} 전 표본`:"실측 \xb7 구간 시작이 창의 시작":`추정 \xb7 경계 ${c??"?"} 전 표본`}(i)}):null]}):null]})}let jd={"anthropic:5h":"5시간","anthropic:7d":"주간","anthropic:7d:opus":"주간","anthropic:7d:sonnet":"주간"};function je({confirmId:a,pending:b,primaryRef:c,summary:e,onConfirm:f,onCancel:g}){return(0,d.jsxs)("div",{className:"resource-reset resource-reset-confirm-group","data-reset-state":b?"pending":"confirming","data-dismissible-layer":!0,role:"group","aria-label":"리셋 사용 확인",onKeyDown:a=>{"Escape"===a.key&&(a.preventDefault(),a.stopPropagation(),g())},children:[(0,d.jsxs)("p",{className:"m-0 text-xs leading-5 text-text-muted",children:["저장된 리셋 ",e]}),(0,d.jsx)("p",{id:a,className:"m-0 text-xs leading-5 text-text",children:"리셋 1개를 지금 사용합니다. 되돌릴 수 없습니다."}),(0,d.jsx)("p",{className:"m-0 mt-1 text-xs leading-5 text-text-muted",children:"이 계정의 차단 기록도 함께 지워집니다."}),(0,d.jsxs)("div",{className:"mt-2 flex flex-wrap justify-end gap-2",children:[(0,d.jsx)("button",{ref:c,type:"button",className:i0(i_,"resource-reset-confirm"),"aria-describedby":a,disabled:b,onClick:f,children:b?"사용 중…":"리셋 사용"}),(0,d.jsx)("button",{type:"button",className:i_,disabled:b,onClick:g,children:"취소"})]})]})}function jf({report:a,brokerOk:b,now:c,active:f,identity:g,recommendation:h,pendingAction:i,feedback:j,onToggle:k,onReset:l}){let m=a.metadata??{},n=g??(0,bJ.k)([a])[0],o=a.credentialId,p=Number.isSafeInteger(o)&&o>0,q=a.accountRole,r="usage-only"===q?"사용량":"control-only"===q?"계정 제어":m.planType,s=!0!==a.disabled&&"number"==typeof a.autoBlockedUntilMs&&a.autoBlockedUntilMs>c,t=f?"active":a.disabled?"off":s?"auto-blocked":"idle",u="toggle"===i?"전환 중…":"reset"===i?"리셋 사용 중…":p?f?"현재 사용 \xb7 이 세션":a.disabled?"꺼둠":s?`자동 차단 \xb7 ${i1(a.autoBlockedUntilMs,c)}`:"control-only"===q?"로그인 계정 \xb7 ON/OFF 제어":"대기":"usage-only"===q?"할당량 정보 \xb7 계정 연결 없음":"제어 불가 \xb7 credential id 없음",v=(0,e.useId)(),w=(0,e.useId)(),[x,y]=(0,e.useState)(!1),[z,A]=(0,e.useState)(!1),[B,C]=(0,e.useState)(null),D=(0,e.useRef)(null),E=(0,e.useRef)(null),F=(0,e.useRef)(!1),G=(0,e.useRef)(!1),H="openai-codex"===a.provider||"anthropic"===a.provider?a.savedReset:void 0,I=function(a){let b=a.savedReset?.credits??[],c=null;for(let a of b){if(!a.id)continue;let b=a.expiresAt?Date.parse(a.expiresAt):NaN,d=Number.isFinite(b)?b:null;(!c||null!=d&&(null==c.timestamp||d<c.timestamp))&&(c={id:a.id,expiresAt:a.expiresAt,timestamp:d})}return c?{id:c.id,expiresAt:c.expiresAt}:null}(a),J=I?.id??null,K=i2(I?.expiresAt??null,c),L=H?.availableCount,M=H&&"unavailable"!==H.state?"empty"===H.state||0===L?"없음":`${L??H.credits.length}개${K?` \xb7 ${K}`:""}`:"확인 불가",N=function(a){if("anthropic"!==a.provider)return null;let b=a.savedReset,c=b?.credits.find(a=>a.id===b.nextCreditId)??b?.credits[0],d=[...new Set((c?.clears??[]).map(a=>jd[a]).filter(a=>void 0!==a))];return d.length?`${d.join("\xb7")} 한도만`:null}(a),O=function(a,b){if(!a)return null;if("blocked-account"===a.reason){if(a.scope)return`권고 — ${a.scope}가 소진됐습니다. 저장된 리셋권 사용을 검토하세요.`;let c="number"==typeof a.naturalResetAt?i1(a.naturalResetAt,b).replace(/ 후 리셋$/,""):null;return c?`권고 — 지금 쓸 수 있는 다른 계정이 없고 자연 리셋까지 ${c} 남았습니다.`:"권고 — 지금 쓸 수 있는 다른 계정이 없어 저장된 리셋 사용을 검토하세요."}let c=i2(a.expiresAt??null,b),d="number"==typeof a.usedFraction?` 현재 ${Math.round(100*a.usedFraction)}% 소모한 ${"weekly"===a.window?"주간":"5시간"} 한도를 초기화할 수 있습니다.`:"";return`권고 — 리셋 1개가 ${c&&"만료됨"!==c?c:"곧 만료"}됩니다.${d}`}(h,c),P=("openai-codex"===a.provider||"anthropic"===a.provider)&&b&&!0!==a.disabled&&H?.state==="available"&&0!==L&&null!=J,Q=async()=>{if(B&&!G.current){G.current=!0;try{await l(a,B.creditId)}finally{G.current=!1,F.current=!0,C(null)}}},R=(a.limits??[]).reduce((a,b)=>{let d=b.window?.resetsAt;return"number"!=typeof d||d<=c?a:null==a||d<a?d:a},null),S=i?"pending":f?"active":a.disabled?"off":s?"blocked":"idle";return(0,d.jsxs)("section",{className:"resource-account border-b border-border-strong px-4 py-3 last:border-b-0","data-account-state":t,"aria-current":f?"true":void 0,children:[(0,d.jsxs)("div",{className:"resource-account-head flex min-w-0 items-start gap-2.5",children:[(0,d.jsx)(bU,{seed:n.seed,size:48,provider:a.provider}),(0,d.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,d.jsxs)("h3",{className:"m-0 flex min-w-0 flex-wrap items-baseline gap-x-1.5 text-sm font-semibold text-text",children:[(0,d.jsx)("span",{children:n.alias}),(0,d.jsx)("span",{className:"min-w-0 truncate text-xs font-normal text-text-muted",children:`${(0,bJ.bN)(a.provider)}${r?` \xb7 ${r}`:""}`})]}),(0,d.jsxs)("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[(0,d.jsx)("span",{className:"resource-account-state resource-account-badge","data-tone":S,role:i?"status":void 0,children:u}),null!=R&&R-c<=72e5?(0,d.jsx)("span",{className:"usage-chip",children:`곧 리셋 \xb7 ${i1(R,c).replace(/ 후 리셋$/,"")}`}):null]})]}),p?(0,d.jsxs)("span",{className:"resource-account-toggle",children:[(0,d.jsx)("span",{className:"resource-account-toggle-label",children:"사용 설정"}),(0,d.jsx)("button",{type:"button",role:"switch",className:i0(i_,"resource-account-switch min-w-[3.25rem]"),disabled:null!=i||!b,"aria-label":`${n.alias} 계정 사용 설정`,"aria-checked":!a.disabled,"aria-busy":null!=i||void 0,title:b?void 0:"제어 서버에 연결할 수 없습니다.",onClick:()=>{F.current=!1,C(null),k(a)},children:a.disabled?"OFF":"ON"})]}):null]}),a.disabled?(0,d.jsx)("div",{className:"mt-2 text-xs text-text-muted",children:"다른 계정이 있으면 이 계정을 사용하지 않습니다."}):s?(0,d.jsx)("div",{className:"mt-2 text-xs text-text-muted",children:(a.limits??[]).some(bJ.xL)?"한도를 다 써서 코어가 자동으로 차단했습니다.":"한도는 남아 있지만 토큰 갱신 실패나 일시 오류로 코어가 잠시 막았습니다. 해제 시각이 지나면 다시 씁니다."}):null,j?(0,d.jsx)("div",{className:"mt-2 text-xs text-text",role:"error"===j.tone?"alert":"status",children:j.message}):null,(0,d.jsxs)("div",{id:w,className:"resource-account-limits divide-y divide-border",children:[x?(0,d.jsxs)("div",{className:"flex items-baseline justify-between gap-3 py-2",children:[(0,d.jsx)("span",{className:"text-xs text-text-muted",children:"계정"}),(0,d.jsxs)("span",{className:"flex min-w-0 items-baseline gap-2",children:[(0,d.jsx)("span",{className:"min-w-0 truncate font-mono text-xs text-text",children:z?n.raw:n.masked||"—"}),n.raw?(0,d.jsx)("button",{type:"button",className:"resource-account-reveal","aria-pressed":z,onClick:()=>A(!z),children:z?"가리기":"이메일 보기"}):null]})]}):null,(a.limits??[]).map(a=>(0,d.jsx)(jc,{limit:a,now:c,detailed:x},a.id))]}),(a.limits??[]).length>0||n.raw?(0,d.jsx)("button",{type:"button",className:"resource-account-more","aria-expanded":x,"aria-controls":w,onClick:()=>{let a=!x;y(a),a||A(!1)},children:x?"간단히":"자세히"}):null,"openai-codex"===a.provider||"anthropic"===a.provider?B?(0,d.jsx)(je,{confirmId:v,pending:"reset"===i,primaryRef:E,summary:B.summary,onConfirm:()=>{Q()},onCancel:()=>{F.current=!0,C(null)}}):(0,d.jsxs)("div",{className:"resource-reset mt-3 border-t border-border pt-2.5","data-reset-state":b?H&&"unavailable"!==H.state?"empty"===H.state||0===L?"empty":"reset"===i?"pending":"ready":"unavailable":"offline",children:[(0,d.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1.5",children:[(0,d.jsxs)("div",{className:"flex min-w-[10.5rem] flex-1 items-baseline justify-between gap-x-3",children:[(0,d.jsx)("span",{className:"text-xs text-text-muted",children:"저장된 리셋"}),(0,d.jsx)("span",{className:i0("font-mono text-xs tabular-nums text-text",h?.reason==="expiring-credit"&&"text-warning"),children:M})]}),N?(0,d.jsx)("span",{className:"text-xs text-text-muted",children:N}):null,P?(0,d.jsx)("button",{ref:D,type:"button",className:i0(i_,"ml-auto flex-none"),disabled:null!=i,onClick:()=>{J&&C({creditId:J,summary:M})},children:"리셋 사용"}):b&&a.disabled&&H?.state==="available"?(0,d.jsx)("span",{className:"ml-auto text-xs text-text-muted",children:"켠 뒤 사용 가능"}):null]}),O?(0,d.jsx)("p",{className:"m-0 mt-1.5 text-xs leading-5 text-text-muted",children:O}):null]}):null]})}function jg({state:a,loading:b,accountState:c,pendingActions:e,feedbackByCredential:f,onToggle:g,onReset:h}){let i=i$(1e4),j=a.data,k=c?.state==="resolved"&&"session-pin"===c.source&&Number.isSafeInteger(c.credentialId)&&c.credentialId>0?c.credentialId:null,l=(0,bJ.k)(j?.reports??[]),m=null==k?-1:j?.reports.findIndex(a=>a.credentialId===k)??-1;return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(ja,{state:a,loading:b,subject:"사용량"}),j?.brokerOk===!1?(0,d.jsx)("div",{className:"border-b border-border bg-bg px-4 py-2 text-xs text-text-muted",role:"status",children:"제어 서버에 연결할 수 없어 계정 전환과 리셋 사용을 잠시 쓸 수 없습니다. 사용량 표시는 계속 갱신됩니다."}):null,(0,d.jsxs)("div",{className:"flex min-h-7 items-center gap-4 border-b border-border bg-bg-raised px-4 text-[11px] font-semibold tracking-[0.08em] text-text-muted uppercase","aria-label":"사용량 그래프 범례",children:[(0,d.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,d.jsx)("span",{className:"size-2 bg-metric","aria-hidden":"true"}),"누적"]}),(0,d.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,d.jsx)("span",{className:"size-2 bg-metric-recent","aria-hidden":"true"}),"이번 구간"]}),(0,d.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,d.jsx)("span",{className:"h-3 w-0.5 bg-text","aria-hidden":"true"}),"페이스"]})]}),j&&0===j.reports.length?(0,d.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"인증된 계정의 사용량 정보가 없습니다. `omp usage`로 확인하세요."}):null,j?.reports.map((a,b)=>{let k=a.credentialId;return(0,d.jsx)(jf,{report:a,brokerOk:!0===j.brokerOk,now:i,active:b===m,identity:l[b],recommendation:null==k?void 0:c?.resetRecommendations.find(a=>a.credentialId===k),pendingAction:null==k?null:e.get(k)??null,feedback:null==k?void 0:f.get(k),onToggle:g,onReset:h},`${a.provider}:${k??a.metadata?.accountId??a.metadata?.email??b}`)})]})}function jh({model:a}){let b=Math.max(1,Math.min(100,100*a.costShare));return(0,d.jsxs)("section",{className:"border-b border-border px-4 py-3 last:border-b-0",children:[(0,d.jsxs)("div",{className:"flex items-baseline gap-2",children:[(0,d.jsx)("h3",{className:"m-0 min-w-0 flex-1 truncate text-sm font-semibold text-text",title:a.model,children:a.model}),(0,d.jsx)("span",{className:"text-xs text-text-muted",children:a.provider}),(0,d.jsxs)("span",{className:"font-mono text-xs tabular-nums text-text",children:[i3(a.cost)," \xb7 ",i6(a.costShare)]})]}),(0,d.jsx)("div",{className:"my-2 h-1 overflow-hidden border border-border-strong bg-metric-track","aria-hidden":"true",children:(0,d.jsx)("div",{className:"h-full bg-metric",style:{width:`${b}%`}})}),(0,d.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,d.jsx)(i9,{label:"요청",value:i4(a.requests)}),(0,d.jsx)(i9,{label:"요청당",value:i3(a.costPerRequest)}),(0,d.jsx)(i9,{label:"토큰/요청",value:i5(a.tokensPerRequest)}),(0,d.jsx)(i9,{label:"출력/요청",value:i5(a.outputPerRequest)}),(0,d.jsx)(i9,{label:"캐시율",value:i6(a.cacheRate,1)}),(0,d.jsx)(i9,{label:"TTFT",value:i7(a.avgTtft)})]})]})}function ji({agent:a}){let b={main:"메인",subagent:"SubAgent",advisor:"advisor"}[a.agentType]??a.agentType,c=Math.max(1,Math.min(100,100*a.costShare));return(0,d.jsxs)("section",{className:"border-b border-border px-4 py-3 last:border-b-0",children:[(0,d.jsxs)("div",{className:"flex items-baseline justify-between gap-3",children:[(0,d.jsx)("h3",{className:"m-0 text-sm font-semibold text-text",children:b}),(0,d.jsxs)("span",{className:"font-mono text-xs tabular-nums text-text",children:[i3(a.cost)," \xb7 ",i6(a.costShare)]})]}),(0,d.jsx)("div",{className:"my-2 h-1 overflow-hidden border border-border-strong bg-metric-track","aria-hidden":"true",children:(0,d.jsx)("div",{className:"h-full bg-metric",style:{width:`${c}%`}})}),(0,d.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,d.jsx)(i9,{label:"요청",value:i4(a.requests)}),(0,d.jsx)(i9,{label:"요청당",value:i3(a.costPerRequest)}),(0,d.jsx)(i9,{label:"토큰/요청",value:i5(a.tokensPerRequest)})]})]})}function jj({day:a}){let b=a.models.slice(0,3).map(a=>a.model).join(", ");return(0,d.jsxs)("div",{className:"grid grid-cols-[auto_minmax(0,1fr)_auto] items-baseline gap-3 border-b border-border px-4 py-2 last:border-b-0",children:[(0,d.jsx)("span",{className:"font-mono text-xs tabular-nums text-text-muted",children:i8(a.timestamp)}),(0,d.jsx)("span",{className:"truncate text-xs text-text-muted",title:b,children:b}),(0,d.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:i3(a.cost)})]})}function jk({state:a,loading:b}){let c=a.data;return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(ja,{state:a,loading:b,subject:"모델 집계"}),c?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("section",{"aria-labelledby":"resource-overall-heading",children:[(0,d.jsx)("h2",{id:"resource-overall-heading",className:"m-0 border-b border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"전체"}),(0,d.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4 px-4 py-3",children:[(0,d.jsx)(i9,{label:"요청",value:i4(c.overall.requests)}),(0,d.jsx)(i9,{label:"비용",value:i3(c.overall.cost)}),(0,d.jsx)(i9,{label:"토큰",value:i5(c.overall.tokens)}),(0,d.jsx)(i9,{label:"캐시율",value:i6(c.overall.cacheRate,1)}),(0,d.jsx)(i9,{label:"캐시 절감",value:i6(c.overall.cacheSavings,1)}),(0,d.jsx)(i9,{label:"평균 TTFT",value:i7(c.overall.avgTtft)})]})]}),(0,d.jsxs)("section",{"aria-labelledby":"resource-models-heading",children:[(0,d.jsx)("h2",{id:"resource-models-heading",className:"m-0 border-y border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"모델별"}),c.models.length?c.models.map(a=>(0,d.jsx)(jh,{model:a},`${a.provider}:${a.model}`)):(0,d.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"모델 기록이 없습니다."})]}),(0,d.jsxs)("section",{"aria-labelledby":"resource-agents-heading",children:[(0,d.jsx)("h2",{id:"resource-agents-heading",className:"m-0 border-y border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"에이전트 종류별"}),c.agents.length?c.agents.map(a=>(0,d.jsx)(ji,{agent:a},a.agentType)):(0,d.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"기록이 없습니다."})]}),c.daily.length?(0,d.jsxs)("section",{"aria-labelledby":"resource-daily-heading",children:[(0,d.jsx)("h2",{id:"resource-daily-heading",className:"m-0 border-y border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"일별 비용"}),c.daily.map(a=>(0,d.jsx)(jj,{day:a},a.timestamp))]}):null,(0,d.jsx)("p",{className:"m-0 border-t border-border px-4 py-3 text-xs leading-5 text-text-dim",children:"`omp stats` 기준 누적값입니다. 구독 한도 %는 계정 한도 탭에서 확인하세요."})]}):null]})}function jl({reports:a,providerConnections:b}){return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("section",{className:"character-roster-intro","aria-labelledby":"character-roster-heading",children:[(0,d.jsx)("h2",{id:"character-roster-heading",children:"호출 가능한 캐릭터"}),(0,d.jsxs)("p",{children:[(0,d.jsx)("strong",{children:"호출\xb7불러\xb7소환"}),"은 캐릭터를 SubAgent로 이 대화에 부릅니다.",(0,d.jsx)("strong",{children:" 교체"}),"는 이 대화의 Main을 바꿉니다."]})]}),(0,d.jsx)("div",{className:"character-roster",role:"list","aria-label":"호출 가능한 캐릭터 목록",children:bJ.o.map(c=>{let e=`character-roster-${c.seed}`,f=`character-roster-${c.seed}-status`,g=`${c.provider}/${c.model}`,h=!1,i=!1;if(a){for(let b of a)if(b.provider===c.provider&&(h=!0,!0!==b.disabled)){i=!0;break}}let j="web6"!==c.provider&&(b?.get(c.provider)===!1||h&&!i);return(0,d.jsxs)("article",{className:i0("character-roster-item",j&&"is-unavailable"),role:"listitem","aria-labelledby":e,"aria-describedby":j?f:void 0,children:[(0,d.jsxs)("div",{className:"character-roster-identity",children:[(0,d.jsx)(bU,{seed:c.seed,size:48,provider:c.provider}),(0,d.jsxs)("div",{children:[(0,d.jsx)("h3",{id:e,children:c.alias}),j?(0,d.jsx)("span",{id:f,className:"character-roster-availability",children:"연결 안 됨"}):null,(0,d.jsx)("p",{children:c.voice})]})]}),(0,d.jsxs)("dl",{className:"character-roster-model",children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("dt",{children:"모델"}),(0,d.jsx)("dd",{title:g,children:g})]}),void 0!==c.oauthPosition?(0,d.jsxs)("div",{children:[(0,d.jsx)("dt",{children:"계정"}),(0,d.jsxs)("dd",{children:["OAuth ",c.oauthPosition]})]}):null]}),(0,d.jsxs)("dl",{className:"character-roster-examples",children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("dt",{children:"호출"}),(0,d.jsxs)("dd",{children:[(0,d.jsx)("code",{children:c.summonExample}),(0,d.jsx)("span",{children:c.summonNote??"SubAgent로 이 대화에 부릅니다."})]})]}),(0,d.jsxs)("div",{children:[(0,d.jsx)("dt",{children:"Main 교체"}),(0,d.jsxs)("dd",{children:[c.switchExample?(0,d.jsx)("code",{children:c.switchExample}):(0,d.jsx)("strong",{children:"교체 불가"}),(0,d.jsx)("span",{children:c.switchNote??"이 대화의 Main을 바꿉니다."})]})]})]})]},c.alias)})})]})}function jm({open:a,sessionId:b,activeTab:c,onTabChange:f,usage:g,className:i}){let j=(0,e.useId)(),k=g.state,l=g.loading,[m,n]=(0,e.useState)({status:"idle",data:null,error:null}),[o,p]=(0,e.useState)(null),[q,r]=(0,e.useState)(!1),[s,t]=(0,e.useState)(null),[u,v]=(0,e.useState)(()=>new Map),[w,x]=(0,e.useState)(()=>new Map),y=(0,e.useRef)(m);(0,e.useRef)(null);let z=(0,e.useRef)(null),A=(0,e.useRef)(new Set),B=(0,e.useRef)(new Set);y.current=m;let C=(0,e.useCallback)(async a=>{z.current?.abort();let b=new AbortController;z.current=b,r(!0);let c=await (0,bJ.t6)({refresh:a,previous:y.current.data,signal:b.signal});z.current!==b||b.signal.aborted||(n(c),r(!1))},[]),D=(0,e.useCallback)(()=>{"models"===c?C(!0):g.refresh()},[c,C,g]),E=(0,e.useCallback)(()=>g.refresh(),[g]),F=(0,e.useCallback)(async a=>{if(!Number.isSafeInteger(a.credentialId)||a.credentialId<=0)return;let b=a.credentialId,c=(0,bJ.U3)(B.current,b);if(!c)return;let d=new AbortController;A.current.add(d),g.setPaused(!0),v(a=>new Map(a).set(b,"toggle")),x(a=>{let c=new Map(a);return c.delete(b),c});try{await (0,bJ.vy)(b,!0===a.disabled,{signal:d.signal});let c=await E();d.signal.aborted||x(d=>new Map(d).set(b,{tone:"status",message:"fresh"===c.status?`계정을 ${a.disabled?"켰습니다":"껐습니다"}.`:"계정 설정 저장됨 \xb7 표시 상태 새로고침 실패."}))}catch(a){if(!d.signal.aborted){let c=a instanceof bJ.OO&&("timeout"===a.kind||a.outcomeUnknown);x(d=>new Map(d).set(b,c?{tone:"error",message:"적용 여부 확인 필요 — 새로고침으로 계정 상태를 확인하세요."}:{tone:"error",message:`계정 전환 실패: ${a instanceof Error?a.message:String(a)}`}))}}finally{A.current.delete(d),c(),g.setPaused(B.current.size>0),v(a=>{let c=new Map(a);return c.delete(b),c})}},[E,g]),G=(0,e.useCallback)(async(a,b)=>{if(!Number.isSafeInteger(a.credentialId)||a.credentialId<=0)return;let c=a.credentialId,d=(0,bJ.U3)(B.current,c);if(!d)return;let e=new AbortController;A.current.add(e),g.setPaused(!0),v(a=>new Map(a).set(c,"reset")),x(a=>{let b=new Map(a);return b.delete(c),b});try{let a=await (0,bJ.tR)(c,b,{signal:e.signal}),d=function(a){switch(a.code){case"reset":return{tone:"status",message:"리셋 사용함"};case"no_credit":return{tone:"status",message:"사용할 수 있는 리셋이 없습니다."};case"already_redeemed":return{tone:"status",message:"이미 사용된 리셋입니다."};case"nothing_to_reset":return{tone:"status",message:"지금은 초기화할 한도가 없습니다."};case"ineligible":return{tone:"status",message:"지금은 이 리셋을 쓸 수 없습니다(한도 미도달 또는 자격 없음)."};case"cooldown":return{tone:"status",message:"리셋 재사용 대기 중입니다. 잠시 뒤 다시 시도하세요."};case"offer_changed":return{tone:"status",message:"리셋 목록이 바뀌었습니다. 새로고침 후 다시 시도하세요."};case"rate_limited":return{tone:"error",message:"리셋 사용 실패: 요청이 많아 잠시 막혔습니다."};case"reset_unconfirmed":return{tone:"error",message:"이전 리셋 요청 결과를 아직 확인하지 못했습니다. 잠시 뒤 확인하세요."};case"no_account":return{tone:"error",message:"리셋 사용 실패: 계정을 찾을 수 없습니다."};case"account_unavailable":return{tone:"error",message:"리셋 사용 실패: 계정에 연결할 수 없습니다."};case"credit_list_failed":return{tone:"error",message:"리셋 사용 실패: 저장된 리셋 목록을 확인하지 못했습니다."};default:return a.code.startsWith("http_")?{tone:"error",message:`리셋 사용 실패: 서비스 응답 오류 (${a.code})`}:{tone:"error",message:`리셋 사용 실패: ${a.code}`}}}(a),f=await E();if(a.ok){let a="fresh"===f.status?f.data.reports.find(a=>a.credentialId===c):void 0,b=a?.savedReset?.availableCount;d.message="number"==typeof b?`리셋 사용함 \xb7 남은 리셋 ${b}개`:"리셋 사용함 \xb7 남은 개수를 확인하지 못했습니다."}e.signal.aborted||x(a=>new Map(a).set(c,d))}catch(a){a instanceof bJ.OO&&(a.outcomeUnknown||"timeout"===a.kind)&&!e.signal.aborted&&await E(),e.signal.aborted||x(b=>new Map(b).set(c,function(a){if(a instanceof bJ.OO){if(a.outcomeUnknown||"timeout"===a.kind)return{tone:"error",message:"적용 여부 확인 필요 — 자동으로 다시 시도하지 않았습니다. 새로고침으로 남은 개수를 확인하세요."};switch(a.code){case"account_disabled":return{tone:"error",message:"리셋 사용 실패: 꺼둔 계정에서는 사용할 수 없습니다."};case"no_account":return{tone:"error",message:"리셋 사용 실패: 계정을 찾을 수 없습니다."};case"account_unavailable":return{tone:"error",message:"리셋 사용 실패: 계정에 연결할 수 없습니다."};case"credit_list_failed":return{tone:"error",message:"리셋 사용 실패: 저장된 리셋 목록을 확인하지 못했습니다."};default:return{tone:"error",message:`리셋 사용 실패: ${a.message}`}}}return{tone:"error",message:`리셋 사용 실패: ${a instanceof Error?a.message:String(a)}`}}(a)))}finally{A.current.delete(e),d(),g.setPaused(B.current.size>0),v(a=>{let b=new Map(a);return b.delete(c),b})}},[E,g]);if(!a)return null;let H="models"===c?m.data?.generatedAt:k.data?.generatedAt,I="models"===c?m.data?.range:void 0,J=I?.from&&I.to?`${i8(I.from)}~${i8(I.to)}`:H?new Date(H).toLocaleTimeString():"",K="models"===c?q:"usage"===c&&l,L=K?"models"===c?"집계 중…":"불러오는 중…":"새로고침";return(0,d.jsxs)("section",{className:i0("resource-panel flex min-h-0 w-full flex-col overflow-hidden bg-bg-panel text-text",i),"aria-labelledby":j,"aria-busy":K,children:[(0,d.jsx)("h1",{id:j,className:"sr-only",children:"캐릭터"}),(0,d.jsxs)(iu.J.Root,{className:"resource-view-tabs",size:"small",contentLayout:"fill",triggerLayout:"fill",value:c,onValueChange:a=>f(a),children:[(0,d.jsxs)(iu.J.List,{"aria-label":"캐릭터와 사용량 보기",children:[(0,d.jsx)(iu.J.Trigger,{value:"characters",children:"캐릭터"}),(0,d.jsx)(iu.J.Trigger,{value:"usage",children:"계정 한도"}),(0,d.jsx)(iu.J.Trigger,{value:"models",children:"모델 통계"}),(0,d.jsx)(iu.J.Indicator,{})]}),(0,d.jsx)(iu.J.Content,{value:"characters",className:"resource-view-content",children:(0,d.jsx)(jl,{reports:k.data?.reports,providerConnections:s})}),(0,d.jsxs)(iu.J.Content,{value:"usage",className:"resource-view-content",children:[(0,d.jsxs)("div",{className:"resource-usage-toolbar",children:[(0,d.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] tabular-nums text-text-dim",children:J}),(0,d.jsx)(h.r,{variant:"neutralWeak",size:"xsmall",onClick:D,disabled:K,children:L})]}),(0,d.jsx)("h2",{className:"resource-group-heading",children:"계정 한도"}),(0,d.jsx)(jg,{state:k,loading:l,accountState:o?.sessionId===b?o:null,pendingActions:u,feedbackByCredential:w,onToggle:a=>{F(a)},onReset:G})]}),(0,d.jsxs)(iu.J.Content,{value:"models",className:"resource-view-content",children:[(0,d.jsxs)("div",{className:"resource-usage-toolbar",children:[(0,d.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] tabular-nums text-text-dim",children:J}),(0,d.jsx)(h.r,{variant:"neutralWeak",size:"xsmall",onClick:D,disabled:K,children:L})]}),(0,d.jsx)(jk,{state:m,loading:q})]})]})]})}let jn="/api/runs";class jo extends Error{constructor(a,b,c=null){super(b),this.name="EfficiencyClientError",this.kind=a,this.status=c}}let jp=["completed","error","aborted","interrupted","running"],jq=["main","maker","checker","advisor","unattributed"],jr=["primary","rework","review"],js=["wait-attribution","unpriced-cost","effort-unrecorded","role-unattributed","busy-unrecorded"],jt=["all","attributed"];function ju(a){return"object"==typeof a&&null!==a}function jv(a){return Array.isArray(a)&&a.every(a=>"string"==typeof a)}function jw(a){return!!ju(a)&&"string"==typeof a.runId&&"string"==typeof a.sessionId&&"string"==typeof a.entryId&&"number"==typeof a.index&&Number.isFinite(a.index)&&(null===a.title||"string"==typeof a.title)&&"number"==typeof a.startedAt&&Number.isFinite(a.startedAt)&&(null===a.endedAt||"number"==typeof a.endedAt&&Number.isFinite(a.endedAt))&&"number"==typeof a.wallClockMs&&Number.isFinite(a.wallClockMs)&&"string"==typeof a.outcome&&jp.includes(a.outcome)&&"number"==typeof a.busyMs&&Number.isFinite(a.busyMs)&&"number"==typeof a.childCount&&Number.isFinite(a.childCount)&&"number"==typeof a.totalTokens&&Number.isFinite(a.totalTokens)&&"number"==typeof a.estimatedCostUsd&&Number.isFinite(a.estimatedCostUsd)&&"number"==typeof a.unpricedRequests&&Number.isFinite(a.unpricedRequests)&&"string"==typeof a.configSignature}function jx(a){return!!ju(a)&&"string"==typeof a.id&&"string"==typeof a.kind&&jq.includes(a.kind)&&(null===a.purpose||"string"==typeof a.purpose&&jr.includes(a.purpose))&&jv(a.models)&&jv(a.efforts)&&"number"==typeof a.requestCount&&Number.isFinite(a.requestCount)&&"number"==typeof a.busyMs&&Number.isFinite(a.busyMs)&&"number"==typeof a.spanMs&&Number.isFinite(a.spanMs)&&"number"==typeof a.startedAt&&Number.isFinite(a.startedAt)&&"number"==typeof a.endedAt&&Number.isFinite(a.endedAt)&&"number"==typeof a.inputTokens&&Number.isFinite(a.inputTokens)&&"number"==typeof a.outputTokens&&Number.isFinite(a.outputTokens)&&"number"==typeof a.cacheReadTokens&&Number.isFinite(a.cacheReadTokens)&&"number"==typeof a.cacheWriteTokens&&Number.isFinite(a.cacheWriteTokens)&&"number"==typeof a.totalTokens&&Number.isFinite(a.totalTokens)&&"number"==typeof a.estimatedCostUsd&&Number.isFinite(a.estimatedCostUsd)&&"number"==typeof a.unpricedRequests&&Number.isFinite(a.unpricedRequests)&&"number"==typeof a.untimedRequests&&Number.isFinite(a.untimedRequests)&&"number"==typeof a.errorCount&&Number.isFinite(a.errorCount)&&"number"==typeof a.abortedCount&&Number.isFinite(a.abortedCount)&&"number"==typeof a.toolCalls&&Number.isFinite(a.toolCalls)}function jy(a){return!!ju(a)&&("role-busy"===a.kind||"unmeasured-gap"===a.kind)&&"string"==typeof a.id&&"number"==typeof a.ms&&Number.isFinite(a.ms)&&"number"==typeof a.relative&&Number.isFinite(a.relative)}function jz(a){return!!ju(a)&&"string"==typeof a.toolName&&"number"==typeof a.calls&&Number.isFinite(a.calls)&&"number"==typeof a.errors&&Number.isFinite(a.errors)}function jA(a){return!!ju(a)&&"string"==typeof a.kind&&jq.includes(a.kind)&&"string"==typeof a.model&&(null===a.effort||"string"==typeof a.effort)&&"number"==typeof a.count&&Number.isFinite(a.count)}function jB(a){return!!ju(a)&&"string"==typeof a.signature&&Array.isArray(a.roles)&&a.roles.every(jA)&&"number"==typeof a.runCount&&Number.isFinite(a.runCount)&&"number"==typeof a.medianWallClockMs&&Number.isFinite(a.medianWallClockMs)&&"number"==typeof a.medianBusyMs&&Number.isFinite(a.medianBusyMs)&&"number"==typeof a.medianTotalTokens&&Number.isFinite(a.medianTotalTokens)&&"number"==typeof a.medianEstimatedCostUsd&&Number.isFinite(a.medianEstimatedCostUsd)&&"number"==typeof a.totalEstimatedCostUsd&&Number.isFinite(a.totalEstimatedCostUsd)&&"number"==typeof a.unpricedRuns&&Number.isFinite(a.unpricedRuns)&&"number"==typeof a.untimedRuns&&Number.isFinite(a.untimedRuns)&&"number"==typeof a.reworkRuns&&Number.isFinite(a.reworkRuns)&&"number"==typeof a.errorRuns&&Number.isFinite(a.errorRuns)&&"number"==typeof a.childRunsAvg&&Number.isFinite(a.childRunsAvg)&&"number"==typeof a.firstSeenAt&&Number.isFinite(a.firstSeenAt)&&"number"==typeof a.lastSeenAt&&Number.isFinite(a.lastSeenAt)}function jC(a){return Array.isArray(a)&&a.every(a=>"string"==typeof a&&js.includes(a))}async function jD(a){try{return await a.json()}catch{throw new jo("invalid-response","효율 응답 JSON을 해석할 수 없습니다.",a.status)}}function jE(a,b){return a instanceof jo||a instanceof Error?a.message:b}let jF={completed:"positive",error:"critical",aborted:"warning",interrupted:"warning",running:"informative"},jG={main:"informative",maker:"neutral",checker:"neutral",advisor:"neutral",unattributed:"warning"};function jH(...a){return a.filter(Boolean).join(" ")}function jI(a){return"number"==typeof a&&Number.isFinite(a)?0===a?"$0":a>=100?`$${a.toFixed(0)}`:a>=1?`$${a.toFixed(2)}`:a>=.01?`$${a.toFixed(3)}`:`$${a.toFixed(4)}`:"—"}function jJ(a){return"number"==typeof a&&Number.isFinite(a)?Math.round(a).toLocaleString("en-US"):"—"}function jK(a){return"number"==typeof a&&Number.isFinite(a)?a>=1e9?`${(a/1e9).toFixed(1)}B`:a>=1e6?`${(a/1e6).toFixed(1)}M`:a>=1e3?`${Math.round(a/1e3)}K`:String(Math.round(a)):"—"}function jL(a){if("number"!=typeof a||!Number.isFinite(a))return"—";let b=Math.max(0,a);if(b<1e3)return`${Math.round(b)}ms`;let c=Math.round(b/1e3);if(c<60)return`${(b/1e3).toFixed(1)}s`;let d=Math.floor(c/60),e=c-60*d;return d<60?0===e?`${d}m`:`${d}m ${e}s`:`${Math.floor(d/60)}h ${d%60}m`}function jM(a,b=0){return"number"==typeof a&&Number.isFinite(a)?`${(100*a).toFixed(b)}%`:"—"}function jN({label:a,value:b}){return(0,d.jsxs)("div",{className:"flex min-w-0 items-baseline justify-between gap-3 border-b border-border py-1.5 last:border-b-0",children:[(0,d.jsx)("dt",{className:"min-w-0 flex-1 truncate text-xs text-text-muted",children:a}),(0,d.jsx)("dd",{className:"m-0 flex-none font-mono text-xs tabular-nums text-text",children:b})]})}function jO({share:a,label:b}){let c=Number.isFinite(a)?Math.max(1,Math.min(100,100*a)):1;return(0,d.jsxs)("div",{className:"efficiency-bar","aria-hidden":"true",children:[(0,d.jsx)("div",{className:"efficiency-bar-fill",style:{width:`${c}%`}}),(0,d.jsx)("span",{className:"efficiency-bar-value",children:b})]})}function jP({costUsd:a,unpriced:b,t:c}){return(0,d.jsxs)("span",{className:"font-mono tabular-nums",children:[c("efficiency.estimatedCostValue").replace("{value}",jI(a)),b>0?` \xb7 ${c("efficiency.unpricedLowerBound")}`:""]})}function jQ({outcome:a,t:b}){return(0,d.jsx)(iv.E,{tone:jF[a],variant:"weak",size:"medium",children:b({completed:"efficiency.outcomeCompleted",error:"efficiency.outcomeError",aborted:"efficiency.outcomeAborted",interrupted:"efficiency.outcomeInterrupted",running:"efficiency.outcomeRunning"}[a])})}function jR({purpose:a,t:b}){return null===a?(0,d.jsx)("span",{className:"efficiency-dim",children:b("efficiency.unmeasuredShort")}):(0,d.jsx)(iv.E,{tone:"rework"===a?"warning":"neutral",variant:"weak",size:"medium",children:b({primary:"efficiency.purposePrimary",rework:"efficiency.purposeRework",review:"efficiency.purposeReview"}[a]??"efficiency.unmeasuredShort")})}function jS({run:a,selected:b,onSelect:c,t:e}){let f=a.title&&a.title.trim().length>0?a.title:e("efficiency.noTitle");return(0,d.jsx)("li",{children:(0,d.jsxs)("button",{type:"button",onClick:c,"aria-current":b?"true":void 0,className:jH("efficiency-run-item",b&&"is-selected"),children:[(0,d.jsxs)("span",{className:"efficiency-run-top",children:[(0,d.jsxs)("span",{className:"efficiency-run-index",children:["#",a.index]}),(0,d.jsx)("span",{className:"efficiency-run-title",title:f,children:f}),(0,d.jsx)(jQ,{outcome:a.outcome,t:e})]}),(0,d.jsxs)("span",{className:"efficiency-run-meta",children:[(0,d.jsx)("span",{className:"font-mono tabular-nums",children:e("efficiency.elapsedValue").replace("{value}",jL(a.wallClockMs))}),(0,d.jsx)(jP,{costUsd:a.estimatedCostUsd,unpriced:a.unpricedRequests,t:e})]})]})})}function jT({role:a,t:b}){let c=a.models.length>0?a.models.join(", "):b("efficiency.unmeasuredShort"),e=a.efforts.length>0?a.efforts.join(", "):b("efficiency.unmeasuredShort"),f=a.outputTokens-a.helpers.reduce((a,b)=>a+b.outputTokens,0);return(0,d.jsxs)("section",{className:"efficiency-card",children:[(0,d.jsxs)("div",{className:"efficiency-card-top",children:[(0,d.jsx)("h4",{className:"efficiency-card-title",title:a.id,children:a.id}),(0,d.jsx)(iv.E,{tone:jG[a.kind]??"neutral",variant:"weak",size:"medium",children:b(`efficiency.role${"main"===a.kind?"Main":"maker"===a.kind?"Maker":"checker"===a.kind?"Checker":"advisor"===a.kind?"Advisor":"Unattributed"}`)}),(0,d.jsx)(jR,{purpose:a.purpose,t:b})]}),(0,d.jsx)("p",{className:"efficiency-model-line",title:c,children:c}),(0,d.jsxs)("p",{className:"efficiency-dim",children:[b("efficiency.effortLabel").replace("{value}",e),` \xb7 ${b("efficiency.requestsValue").replace("{value}",String(a.requestCount))}`,` \xb7 ${b("efficiency.toolCallsValue").replace("{value}",String(a.toolCalls))}`]}),(0,d.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,d.jsx)(jN,{label:b("efficiency.busyTime"),value:jL(a.busyMs)}),(0,d.jsx)(jN,{label:b("efficiency.estimatedCost"),value:jI(a.estimatedCostUsd)}),(0,d.jsx)(jN,{label:b("efficiency.tokens"),value:jK(a.totalTokens)}),(0,d.jsx)(jN,{label:b("efficiency.unpricedRequests"),value:jJ(a.unpricedRequests)}),(0,d.jsx)(jN,{label:b("efficiency.firstTokenAvg"),value:null!==a.ttftMs&&a.ttftRequests>0?jL(a.ttftMs/a.ttftRequests):b("efficiency.unmeasuredShort")}),(0,d.jsx)(jN,{label:b("efficiency.outputTokens"),value:jK(f)})]}),a.ttftRequests>0&&a.ttftRequests<a.requestCount?(0,d.jsx)("p",{className:"efficiency-note",children:b("efficiency.firstTokenPartial",{recorded:a.ttftRequests,total:a.requestCount})}):null,a.untimedRequests>0?(0,d.jsx)("p",{className:"efficiency-note",children:b("efficiency.untimedLowerBound").replace("{value}",jJ(a.untimedRequests))}):null,a.unpricedRequests>0?(0,d.jsx)("p",{className:"efficiency-note",children:b("efficiency.unpricedLowerBound")}):null,a.helpers.length>0?(0,d.jsxs)("section",{"aria-label":b("efficiency.helpersTitle"),children:[(0,d.jsx)("p",{className:"efficiency-dim",children:b("efficiency.helpersTitle")}),(0,d.jsx)("dl",{className:"m-0",children:a.helpers.map(a=>(0,d.jsx)(jN,{label:`${a.purpose} \xb7 ${a.model}`,value:b("efficiency.helperCallsValue",{count:a.requestCount,output:jK(a.outputTokens),tokens:jK(a.totalTokens),cost:jI(a.estimatedCostUsd)})},`${a.purpose}:${a.role??""}:${a.model}`))}),(0,d.jsx)("p",{className:"efficiency-note",children:b("efficiency.helpersIncludedNote")})]}):null]})}function jU({item:a,t:b}){let c="unmeasured-gap"===a.kind?b("efficiency.unmeasuredGap"):a.id;return(0,d.jsxs)("li",{className:"efficiency-bottleneck",children:[(0,d.jsxs)("div",{className:"efficiency-bottleneck-top",children:[(0,d.jsx)("span",{className:"efficiency-bottleneck-label",title:c,children:c}),(0,d.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:jL(a.ms)})]}),(0,d.jsx)(jO,{share:a.relative,label:jL(a.ms)})]})}function jV({detail:a,t:b}){return(0,d.jsxs)("div",{className:"efficiency-detail",children:[(0,d.jsxs)("section",{"aria-label":b("efficiency.summarySection"),children:[(0,d.jsx)("h3",{className:"efficiency-section-title",children:b("efficiency.summarySection")}),(0,d.jsxs)("div",{className:"efficiency-dual",children:[(0,d.jsxs)("div",{className:"efficiency-dual-cell",children:[(0,d.jsx)("span",{className:"efficiency-dual-label",children:b("efficiency.elapsed")}),(0,d.jsx)("span",{className:"efficiency-dual-value",children:jL(a.wallClockMs)})]}),(0,d.jsxs)("div",{className:"efficiency-dual-cell",children:[(0,d.jsx)("span",{className:"efficiency-dual-label",children:b("efficiency.busyTotal")}),(0,d.jsx)("span",{className:"efficiency-dual-value",children:jL(a.busyMs)})]})]}),(0,d.jsx)("p",{className:"efficiency-note",children:b("efficiency.noSumNote")}),(0,d.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,d.jsx)(jN,{label:b("efficiency.estimatedCost"),value:jI(a.estimatedCostUsd)}),(0,d.jsx)(jN,{label:b("efficiency.tokens"),value:jK(a.totalTokens)})]}),a.unpricedRequests>0?(0,d.jsx)("p",{className:"efficiency-note",children:b("efficiency.unpricedLowerBound")}):null]}),(0,d.jsxs)("section",{"aria-label":b("efficiency.rolesSection"),children:[(0,d.jsx)("h3",{className:"efficiency-section-title",children:b("efficiency.rolesSection")}),a.roles.length>0?(0,d.jsx)("div",{className:"efficiency-stack",children:a.roles.map(a=>(0,d.jsx)(jT,{role:a,t:b},a.id))}):(0,d.jsx)("p",{className:"efficiency-empty",children:b("efficiency.rolesEmpty")})]}),(0,d.jsxs)("section",{"aria-label":b("efficiency.bottlenecksSection"),children:[(0,d.jsx)("h3",{className:"efficiency-section-title",children:b("efficiency.bottlenecksSection")}),(0,d.jsx)("p",{className:"efficiency-note",children:b("efficiency.bottleneckOrderNote")}),a.bottlenecks.length>0?(0,d.jsx)("ul",{className:"efficiency-stack",children:a.bottlenecks.map(a=>(0,d.jsx)(jU,{item:a,t:b},`${a.kind}:${a.id}`))}):(0,d.jsx)("p",{className:"efficiency-empty",children:b("efficiency.bottlenecksEmpty")}),a.unmeasuredMs>0?(0,d.jsx)("p",{className:"efficiency-note",children:b("efficiency.unmeasuredGapValue").replace("{value}",jL(a.unmeasuredMs))}):null]}),a.toolTotals.length>0?(0,d.jsxs)("section",{"aria-label":b("efficiency.toolsSection"),children:[(0,d.jsx)("h3",{className:"efficiency-section-title",children:b("efficiency.toolsSection")}),(0,d.jsx)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:a.toolTotals.map(a=>(0,d.jsx)(jN,{label:`${a.toolName} \xb7 ${b("efficiency.toolErrorsValue").replace("{value}",String(a.errors))}`,value:jJ(a.calls)},a.toolName))})]}):null]})}function jW(a){return a.map(a=>{let b=a.effort??"–",c=a.count>1?` x${a.count}`:"";return`${a.kind} ${a.model}:${b}${c}`}).join(" \xb7 ")}function jX({response:a,t:b}){return(0,d.jsx)("section",{className:"efficiency-card",children:(0,d.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,d.jsx)(jN,{label:b("efficiency.scopeSessions"),value:jJ(a.sessionCount)}),(0,d.jsx)(jN,{label:b("efficiency.scopeRuns"),value:jJ(a.runCount)}),(0,d.jsx)(jN,{label:b("efficiency.scopeExcludedRuns"),value:jJ(a.excludedRunCount)})]})})}function jY({config:a,baselineRuns:b,t:c}){let e=b>0?a.runCount/b:0,f=a.runCount>0?a.reworkRuns/a.runCount:0,g=a.runCount>0?a.errorRuns/a.runCount:0;return(0,d.jsxs)("section",{className:"efficiency-card",children:[(0,d.jsx)("p",{className:"efficiency-model-line",title:jW(a.roles),children:jW(a.roles)}),(0,d.jsxs)("div",{className:"efficiency-bottleneck-top",children:[(0,d.jsx)("span",{className:"efficiency-dim",children:c("efficiency.runsValue").replace("{value}",String(a.runCount))}),(0,d.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:jM(e)})]}),(0,d.jsx)(jO,{share:e,label:jM(e)}),(0,d.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,d.jsx)(jN,{label:c("efficiency.medianElapsed"),value:jL(a.medianWallClockMs)}),(0,d.jsx)(jN,{label:c("efficiency.medianBusy"),value:jL(a.medianBusyMs)}),(0,d.jsx)(jN,{label:c("efficiency.medianTokens"),value:jK(a.medianTotalTokens)}),(0,d.jsx)(jN,{label:c("efficiency.medianEstimatedCost"),value:jI(a.medianEstimatedCostUsd)}),(0,d.jsx)(jN,{label:c("efficiency.totalEstimatedCost"),value:jI(a.totalEstimatedCostUsd)}),(0,d.jsx)(jN,{label:c("efficiency.reworkRate"),value:jM(f,1)}),(0,d.jsx)(jN,{label:c("efficiency.errorRate"),value:jM(g,1)}),(0,d.jsx)(jN,{label:c("efficiency.unpricedRuns"),value:jJ(a.unpricedRuns)}),(0,d.jsx)(jN,{label:c("efficiency.untimedRuns"),value:jJ(a.untimedRuns)})]}),a.untimedRuns>0?(0,d.jsx)("p",{className:"efficiency-note",children:c("efficiency.untimedMedianLowerBound").replace("{value}",jJ(a.untimedRuns))}):null,a.unpricedRuns>0?(0,d.jsx)("p",{className:"efficiency-note",children:c("efficiency.unpricedLowerBound")}):null]})}function jZ({open:a,sessionId:b,activeTab:c,onTabChange:f,client:g,className:i}){let k=(0,e.useId)(),l=(0,e.useId)(),{t:m}=(0,x.s)(),n=function({sessionId:a,visible:b,activeTab:c,client:d}){let[f]=(0,e.useState)(()=>d??function(a=(a,b)=>fetch(a,b)){let b=async(b,c)=>{let d;try{d=await a(b,c)}catch(a){if(c.signal?.aborted)throw a;throw new jo("unreachable","효율 기록에 연결할 수 없습니다.")}let e=await jD(d);if(!d.ok){var f;throw new jo("http",(f=`HTTP ${d.status}`,null!==e&&"object"==typeof e&&"error"in e&&"string"==typeof e.error&&e.error?e.error:f),d.status)}return{response:d,body:e}};return{async listRuns(a,c,d){let{response:e,body:f}=await b(`${jn}?sessionId=${encodeURIComponent(a)}&limit=${encodeURIComponent(String(c))}`,{method:"GET",signal:d});return function(a,b,c=null){try{if(!ju(a)||!("string"==typeof a.sessionId&&Array.isArray(a.runs)&&a.runs.every(jw)&&jC(a.unmeasured)))throw new jo("invalid-response","실행 목록 응답이 올바르지 않습니다.");return a}catch{throw new jo("invalid-response",b,c)}}(f,"실행 목록 응답이 올바르지 않습니다.",e.status)},async getRun(a,c){let{response:d,body:e}=await b(`${jn}/${encodeURIComponent(a)}`,{method:"GET",signal:c});return function(a,b,c=null){try{if(!jw(a)||!(Array.isArray(a.roles)&&a.roles.every(jx)&&Array.isArray(a.bottlenecks)&&a.bottlenecks.every(jy)&&"number"==typeof a.unmeasuredMs&&Number.isFinite(a.unmeasuredMs)&&Array.isArray(a.toolTotals)&&a.toolTotals.every(jz)&&jC(a.unmeasured)))throw new jo("invalid-response","실행 상세 응답이 올바르지 않습니다.");return a}catch{throw new jo("invalid-response",b,c)}}(e,"실행 상세 응답이 올바르지 않습니다.",d.status)},async listExperiments(a,c,d,e){let f=new URLSearchParams;null!==a&&""!==a&&f.set("folder",a),f.set("sessions",String(c)),f.set("scope",d);let{response:g,body:h}=await b(`/api/experiments?${f.toString()}`,{method:"GET",signal:e});return function(a,b,c=null){try{if(!ju(a)||!((null===a.folder||"string"==typeof a.folder)&&jv(a.folders)&&"string"==typeof a.scope&&jt.includes(a.scope)&&Array.isArray(a.configs)&&a.configs.every(jB)&&"number"==typeof a.runCount&&Number.isFinite(a.runCount)&&"number"==typeof a.sessionCount&&Number.isFinite(a.sessionCount)&&"number"==typeof a.excludedRunCount&&Number.isFinite(a.excludedRunCount)&&jC(a.unmeasured)))throw new jo("invalid-response","구성 비교 응답이 올바르지 않습니다.");return a}catch{throw new jo("invalid-response",b,c)}}(h,"구성 비교 응답이 올바르지 않습니다.",g.status)}}}()),[g,h]=(0,e.useState)({status:"idle",runs:[],error:null}),[i,j]=(0,e.useState)({status:"idle",runId:null,detail:null,error:null}),[k,l]=(0,e.useState)({status:"idle",response:null,error:null}),[m,n]=(0,e.useState)(null),[o,p]=(0,e.useState)(null),q=(0,e.useRef)(null),r=(0,e.useRef)(null),s=(0,e.useRef)(null),t=(0,e.useRef)(null),u=(0,e.useCallback)(()=>{if(!b||"governor"!==c||!a)return;q.current?.abort();let d=new AbortController;q.current=d,h(a=>({status:"loading",runs:"ready"===a.status||"empty"===a.status?a.runs:[],error:null})),f.listRuns(a,20,d.signal).then(a=>{if(!d.signal.aborted&&q.current===d){if(0===a.runs.length)return void h({status:"empty",runs:[],error:null});h({status:"ready",runs:a.runs,error:null})}}).catch(a=>{d.signal.aborted||q.current!==d||h({status:"error",runs:[],error:jE(a,"실행 목록을 불러오지 못했습니다.")})})},[c,f,a,b]);(0,e.useCallback)(a=>{if(!b)return;r.current?.abort();let c=new AbortController;r.current=c,j({status:"loading",runId:a,detail:null,error:null}),f.getRun(a,c.signal).then(b=>{c.signal.aborted||r.current!==c||j({status:"ready",runId:a,detail:b,error:null})}).catch(b=>{c.signal.aborted||r.current!==c||j({status:"error",runId:a,detail:null,error:jE(b,"실행 상세를 불러오지 못했습니다.")})})},[f,b]);let v=(0,e.useCallback)((a,d="all")=>{if(!b||"lab"!==c)return;s.current?.abort();let e=new AbortController;s.current=e,l(a=>({status:"loading",response:"ready"===a.status||"empty"===a.status?a.response:null,error:null})),f.listExperiments(a,30,d,e.signal).then(a=>{if(!e.signal.aborted&&s.current===e){if(0===a.configs.length)return void l({status:"empty",response:a,error:null});l({status:"ready",response:a,error:null})}}).catch(a=>{e.signal.aborted||s.current!==e||l({status:"error",response:null,error:jE(a,"구성 비교를 불러오지 못했습니다.")})})},[c,f,b]),w=(0,e.useCallback)(a=>{r.current?.abort(),r.current=null,n(a),null===a&&j({status:"idle",runId:null,detail:null,error:null})},[]);return{list:g,detail:i,experiments:k,selectedRunId:m,selectRun:w,refreshRuns:(0,e.useCallback)(()=>{u()},[u]),refreshExperiments:(0,e.useCallback)((a,b="all")=>{let c=void 0===a?t.current:a;void 0!==a&&(t.current=a,p(a)),v(c,b)},[v]),experimentFolder:o}}({sessionId:b,visible:a,activeTab:c,client:g}),[o,p]=(0,e.useState)(""),q=(0,e.useMemo)(()=>n.experiments.response?.folders??[],[n.experiments.response]),r=(0,e.useMemo)(()=>n.experiments.response?.configs.reduce((a,b)=>Math.max(a,b.runCount),0)??0,[n.experiments.response]),s=n.experimentFolder,t=n.experiments.response?.scope??"all";if(!a)return null;let u="governor"===c&&"loading"===n.list.status||"lab"===c&&"loading"===n.experiments.status,v=u?m("efficiency.refreshing"):m("efficiency.refresh"),w="governor"===c?n.list.runs.length>0?m("efficiency.runsValue").replace("{value}",String(n.list.runs.length)):"":n.experiments.response?m("efficiency.runsValue").replace("{value}",String(n.experiments.response.runCount)):"";return(0,d.jsxs)("section",{className:jH("efficiency-panel flex min-h-0 w-full flex-col overflow-hidden bg-bg-panel text-text",i),"aria-labelledby":k,"aria-busy":u,children:[(0,d.jsxs)("header",{className:"flex min-h-12 items-center gap-3 border-b border-border bg-bg px-3",children:[(0,d.jsx)("h1",{id:k,className:"m-0 text-sm font-semibold text-text",children:m("efficiency.title")}),(0,d.jsx)("span",{className:"min-w-0 flex-1 truncate text-right font-mono text-[11px] tabular-nums text-text-dim",children:w}),(0,d.jsx)(h.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>{"governor"===c?n.refreshRuns():n.refreshExperiments(void 0,t)},disabled:u,children:v})]}),(0,d.jsx)("div",{className:"grid grid-cols-2 border-b border-border bg-bg",role:"tablist","aria-label":m("efficiency.title"),children:["governor","lab"].map(a=>(0,d.jsx)("button",{type:"button",role:"tab","aria-selected":c===a,id:`${l}-${a}-tab`,"aria-controls":l,className:jH("min-h-10 border-0 border-r border-border bg-bg px-4 text-sm text-text-muted last:border-r-0 hover:bg-bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent",c===a&&"bg-bg-selected font-semibold text-text"),onClick:()=>f(a),children:"governor"===a?m("efficiency.governor"):m("efficiency.lab")},a))}),"lab"===c?(0,d.jsxs)("div",{className:"efficiency-folderbar",children:[(0,d.jsx)("label",{className:"efficiency-folder-label",htmlFor:`${l}-folder`,children:m("efficiency.folder")}),(0,d.jsxs)("select",{id:`${l}-folder`,className:"efficiency-folder-select",value:s??"",onChange:a=>{let b=""===a.target.value?null:a.target.value;p(b??""),n.refreshExperiments(b,t)},children:[(0,d.jsx)("option",{value:"",children:m("efficiency.folderAll")}),q.map(a=>(0,d.jsx)("option",{value:a,children:a},a)),s&&!q.includes(s)?(0,d.jsx)("option",{value:s,children:s}):null]}),(0,d.jsx)("input",{className:"efficiency-folder-input",value:o,placeholder:m("efficiency.folderPlaceholder"),"aria-label":m("efficiency.folder"),onChange:a=>p(a.target.value),onKeyDown:a=>{if("Enter"===a.key){let a=""===o.trim()?null:o.trim();n.refreshExperiments(a,t)}}}),(0,d.jsxs)("div",{className:"col-span-full flex flex-col items-start gap-2",children:[(0,d.jsx)(j.f,{variant:"neutralWeak",size:"xsmall",pressed:"attributed"===t,onPressedChange:a=>n.refreshExperiments(void 0,a?"attributed":"all"),children:m("efficiency.scopeAttributed")}),(0,d.jsx)(iv.E,{tone:"attributed"===t?"informative":"neutral",variant:"weak",size:"medium",children:m("attributed"===t?"efficiency.scopeAttributed":"efficiency.scopeAll")})]})]}):null,(0,d.jsx)("div",{id:l,className:"min-h-0 flex-1 overflow-y-auto overscroll-contain",role:"tabpanel","aria-labelledby":`${l}-${c}-tab`,children:"governor"===c?b?"idle"===n.list.status||"loading"===n.list.status?(0,d.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:m("efficiency.loadingRuns")}):"error"===n.list.status?(0,d.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,d.jsx)("div",{className:"font-medium",children:m("efficiency.runsError")}),(0,d.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:n.list.error})]}):"empty"===n.list.status?(0,d.jsx)("p",{className:"efficiency-empty",children:m("efficiency.runsEmpty")}):(0,d.jsxs)("div",{className:"efficiency-governor",children:[(0,d.jsx)("ul",{className:"efficiency-run-list",children:n.list.runs.map(a=>(0,d.jsx)(jS,{run:a,selected:n.selectedRunId===a.runId,onSelect:()=>n.selectRun(n.selectedRunId===a.runId?null:a.runId),t:m},a.runId))}),(0,d.jsx)("div",{className:"efficiency-detail-pane",children:null===n.selectedRunId||"idle"===n.detail.status?(0,d.jsx)("p",{className:"efficiency-empty",children:m("efficiency.selectRun")}):"loading"===n.detail.status?(0,d.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:m("efficiency.loadingDetail")}):"error"===n.detail.status?(0,d.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,d.jsx)("div",{className:"font-medium",children:m("efficiency.detailError")}),(0,d.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:n.detail.error})]}):n.detail.detail?(0,d.jsx)(jV,{detail:n.detail.detail,t:m}):null})]}):(0,d.jsx)("p",{className:"efficiency-empty",children:m("efficiency.noSession")}):(()=>{if("idle"===n.experiments.status||"loading"===n.experiments.status)return(0,d.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:m("efficiency.loadingExperiments")});if("error"===n.experiments.status)return(0,d.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,d.jsx)("div",{className:"font-medium",children:m("efficiency.experimentsError")}),(0,d.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:n.experiments.error})]});let a=n.experiments.response;return"empty"!==n.experiments.status&&a?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("p",{className:"efficiency-note",children:m("efficiency.difficultyNote")}),(0,d.jsxs)("div",{className:"efficiency-stack",children:[(0,d.jsx)(jX,{response:a,t:m}),a.configs.map(a=>(0,d.jsx)(jY,{config:a,baselineRuns:r,t:m},a.signature))]})]}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("p",{className:"efficiency-empty",children:m("efficiency.experimentsEmpty")}),a?(0,d.jsx)("div",{className:"efficiency-stack",children:(0,d.jsx)(jX,{response:a,t:m})}):null,(0,d.jsx)("p",{className:"efficiency-note",children:m("efficiency.difficultyNote")})]})})()})]})}function j$(a){return"message"===a.type&&"message"in a}function j_(a){let b=a,c=b.branchPreview,d=j$(b.entry)?b.entry:null,e=b.compressedEntryIds?.length??0;for(;1===b.children.length;)b=b.children[0],c??=b.branchPreview,!d&&j$(b.entry)&&(d=b.entry),e+=1+(b.compressedEntryIds?.length??0);return{node:b,skipped:e,branchPreview:c,labelEntry:d??b.entry}}function j0({node:a,activePathIds:b,depth:c,isLast:e,parentLines:f,onSelect:g}){let{node:h,skipped:i,branchPreview:j,labelEntry:k}=j_(a),l=b.has(h.entry.id),m=b.has(a.entry.id)||b.has(h.entry.id),n=j?.text??function(a){if("message"===a.type&&"message"in a){let b=a.message,c=b.content,d="";if("string"==typeof c?d=c:Array.isArray(c)&&(d=c.filter(a=>"text"===a.type).map(a=>a.text).join(" ")),d.length>40&&(d=d.slice(0,40)+"…"),d)return d;if("assistant"===b.role)return"[assistant]"}return a.type}(k),o=j?j.role??null:j$(k)?k.message.role:null;return(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:"pointer"},onClick:()=>g(h.entry.id),children:[f.map((a,b)=>(0,d.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:a&&(0,d.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},b)),(0,d.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,d.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:e?"50%":0,width:1,background:"var(--border)"}}),(0,d.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,d.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:l?"var(--accent)":m?"var(--text-muted)":"var(--border)",border:l?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),o&&(0,d.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===o?"var(--accent)":"var(--text-dim)",background:"user"===o?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===o?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===o?"U":"A"}),i>0&&(0,d.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",i]}),(0,d.jsx)("span",{style:{fontSize:11,color:l?"var(--text)":m?"var(--text-muted)":"var(--text-dim)",fontWeight:l?500:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:n})]}),h.children.map((a,i)=>(0,d.jsx)(j0,{node:a,activePathIds:b,depth:c+1,isLast:i===h.children.length-1,parentLines:[...f,!e],onSelect:g},a.entry.id))]})}function j1({tree:a,activeLeafId:b,onLeafChange:c,hasSession:f}){let{t:g}=(0,x.s)(),h=(0,e.useMemo)(()=>b?new Set(function a(c,d){for(let e of c){let c=[...d,e.entry.id];if(e.entry.id===b||e.compressedEntryIds?.includes(b))return c;let f=a(e.children,c);if(f)return f}return null}(a,[])??[]):new Set,[a,b]),i=(0,e.useCallback)(a=>{c(a)},[c]),j=f?!function a(b){if(b.length>1)return!0;for(let c of b)if(c.children.length>1||a(c.children))return!0;return!1}(a)?g("i18n.noBranches"):null:g("i18n.noActiveSession"),k=function(a){if(a.length>1)return a;if(0===a.length)return[];let b=j_(a[0]).node;return b.children.length>1?b.children:[]}(a);return!j&&k.length>0?(0,d.jsx)("div",{className:"branch-navigator-tree",children:k.map((a,b)=>(0,d.jsx)(j0,{node:a,activePathIds:h,depth:0,isLast:b===k.length-1,parentLines:[],onSelect:i},a.entry.id))}):(0,d.jsx)("p",{className:"branch-navigator-empty",children:j??g("i18n.noBranches")})}function j2(a){return a>=1e6?`${(a/1e6).toFixed(1)}M`:a>=1e3?`${(a/1e3).toFixed(0)}k`:String(a)}function j3(a){let b=a.currentTime;[523.25,659.25].forEach((c,d)=>{let e=a.createOscillator(),f=a.createGain();e.connect(f),f.connect(a.destination),e.type="sine",e.frequency.value=c;let g=b+.18*d;f.gain.setValueAtTime(0,g),f.gain.linearRampToValueAtTime(.18,g+.02),f.gain.exponentialRampToValueAtTime(.001,g+.45),e.start(g),e.stop(g+.45)})}async function j4(a){let b=await fetch(a);if(!b.ok)throw Error(`HTTP ${b.status}`);return b.arrayBuffer()}function j5(a){let b,c=a.window?.durationMs;if("number"==typeof c&&Number.isFinite(c)&&c>0)return c>=5184e5?"weekly":c<=432e5?"short":"other";let d=(b=a.scope?.windowId,`${"string"==typeof b?b:""} ${a.id} ${a.label??""}`.toLowerCase());return/(^|[^0-9])7d\b|week|7 day|주간/.test(d)?"weekly":/(^|[^0-9])(5h|1h)\b|hour|시간/.test(d)?"short":"other"}function j6(a){let b=a.amount?.usedFraction;return"number"==typeof b&&Number.isFinite(b)?Math.round(100*b):null}function j7(a){let b=j6(a);return(0,bJ.xL)(a)||"warning"===a.status||null!==b&&b>=90}function j8(a){let b=a.amount?.usedFraction;return"number"==typeof b&&Number.isFinite(b)?b:null}function j9(a){let b=new Date(a);return`${b.getMonth()+1}/${b.getDate()}`}function ka({direction:a}){return(0,d.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",children:(0,d.jsx)("polyline",{points:"up"===a?"2.5 7.5 6 4 9.5 7.5":"2.5 4.5 6 8 9.5 4.5"})})}function kb({usage:a,onOpen:b,onRelogin:c}){var f,g;let h,i,j,k,{t:l}=(0,x.s)(),m=D(),[n,o]=(0,e.useState)(!1),[p,q]=(0,e.useState)(!1),[r,s]=(0,e.useState)([]),[t,u]=(0,e.useState)(""),[v,w]=(0,e.useState)(null),y=(0,e.useRef)(null),[z,A]=(0,e.useState)(!0),B=a.bai,C=a.state.data?.reports??[],E=i$(1e4),F=(h=(0,bJ.k)(C),i=[],j=[],C.forEach((a,b)=>{let c=a.authError;if(!0===a.disabled&&!c)return;let d=h[b],e="number"==typeof a.autoBlockedUntilMs&&a.autoBlockedUntilMs>E,f=!0===a.disabled?[]:a.limits??[],g=f.some(a=>a.scope?.shared===!0&&(0,bJ.xL)(a)),k=f.some(a=>null!==j8(a)&&"short"!==j5(a)),l=[];for(let a of f){let b=j8(a);null!==b&&(!k||"short"!==j5(a)||j7(a))&&l.push({key:a.id,label:a.label||a.id,percent:Math.round(100*b),state:e?"blocked":g?"account-spent":(0,bJ.xL)(a)?"spent":"usable"})}if(0===l.length&&!c)return;let m=c?"auth":e?"blocked":g?"account-spent":"ok",n={orderKey:"string"==typeof a.accountKey&&a.accountKey.length>0?`${a.provider}:${a.accountKey}`:void 0!==a.credentialId?`${a.provider}:#${a.credentialId}`:`${a.provider}:@${b}`,provider:a.provider,alias:d.alias,seed:d.seed,masked:d.masked,..."string"==typeof a.accountKey?{accountKey:a.accountKey}:{},rows:l,state:m,...c?{authError:c}:{},usable:"ok"===m&&l.some(a=>"usable"===a.state)};(n.usable?i:j).push(n)}),f=[...i,...j],k=new Map(r.map((a,b)=>[a,b])),[...f.filter(a=>k.has(a.orderKey)).sort((a,b)=>k.get(a.orderKey)-k.get(b.orderKey)),...f.filter(a=>!k.has(a.orderKey))]),G=(a,b)=>{let c,d,e,f="up"===b?a-1:a+1;if(f<0||f>=F.length)return;let g=F.map(a=>a.orderKey);[g[a],g[f]]=[g[f],g[a]];let h=(c=new Set(g),d=[...r,...g.filter(a=>!r.includes(a))],e=0,d.map(a=>c.has(a)?g[e++]:a));s(h);try{window.localStorage.setItem("omp-sidebar-usage-order",JSON.stringify(h))}catch{}u(l("usage.moved",{account:F[a].alias,position:f+1})),w({orderKey:F[a].orderKey,direction:b})},H=a=>Math.max(1,a.rows.length),I=0,J=n||p?F:F.filter(a=>!(I>=2)&&(I+=H(a),!0)),K=F.slice(J.length).reduce((a,b)=>a+H(b),0),L=F.filter(a=>"auth"===a.state).length,M="measured"===B.status?(g=B.tokens)>=1e9?`${(g/1e9).toFixed(1)}B`:g>=1e6?`${(g/1e6).toFixed(1)}M`:g>=1e3?`${Math.round(g/1e3)}K`:String(Math.round(g)):l("empty"===B.status?"usage.baiEmpty":"usage.baiUnmeasured"),N="measured"===B.status&&null!==B.from&&null!==B.to?l("usage.baiRange",{from:j9(B.from),to:j9(B.to)}):null,O=a=>"auth"===a.state?l(a.authError?.reloginRequired?"usage.authExpired":"usage.authUnavailable"):"blocked"===a.state?l("usage.accountBlocked"):"account-spent"===a.state?l("usage.accountSpent"):null,P=a=>"spent"===a.state?l("usage.limitSpent"):null,Q=l("usage.open",{rows:[...J.flatMap(a=>{let b=O(a);return 0===a.rows.length?[`${a.alias} (${b??""}${a.authError?`: ${a.authError.message}`:""})`]:a.rows.map(c=>{let d=P(c)??b;return`${a.alias} ${c.label} ${c.percent}%${null===d?"":` (${d})`}`})}),`${l("usage.bai")} ${M}${null===N?"":` \xb7 ${N}`}`].join(", ")})+(K>0?l("usage.openMore",{count:K}):""),R=F[0],S=void 0===R?{label:l("usage.bai"),value:M,danger:!1}:0===R.rows.length?{label:R.alias,value:O(R)??"",danger:!0}:{label:R.rows[0].label,value:`${R.rows[0].percent}%`,danger:R.rows[0].percent>=90},T=L>0?l("usage.authIssues",{count:L}):null,U=(0,d.jsxs)("div",{className:"navigator-usage",role:"group","aria-label":l("usage.title"),"data-editing":p?"":void 0,onClick:a=>{p||a.target instanceof Element&&a.target.closest("button, a")||b()},children:[(0,d.jsxs)("span",{className:"navigator-usage-header",children:[(0,d.jsx)("button",{type:"button",className:"navigator-usage-open","aria-label":Q,onClick:b,children:l("usage.title")}),null===T?null:(0,d.jsx)("span",{className:"navigator-usage-alert",children:T}),F.length>1&&(0,d.jsx)("button",{type:"button",className:"navigator-usage-edit","data-active":p?"":void 0,onClick:()=>q(a=>!a),children:p?l("usage.reorderDone"):l("usage.reorder")})]}),(0,d.jsx)("div",{ref:y,role:p?"list":void 0,"aria-label":p?l("usage.reorderGroup"):void 0,className:"navigator-usage-groups",children:0===F.length?(0,d.jsx)("span",{className:"navigator-usage-empty",children:l("usage.none")}):J.map((a,b)=>{let e=O(a);return(0,d.jsxs)("div",{className:"navigator-usage-group","data-order-key":a.orderKey,role:p?"listitem":void 0,children:[(0,d.jsxs)("span",{className:"navigator-usage-account",children:[(0,d.jsx)(bU,{seed:a.seed,size:24,provider:a.provider}),(0,d.jsx)("span",{className:"navigator-usage-alias",children:a.alias}),null===e?null:(0,d.jsx)("span",{className:"navigator-usage-state","data-tone":"auth"===a.state?"danger":void 0,children:e}),p&&(0,d.jsxs)("span",{className:"navigator-usage-moves",children:[(0,d.jsx)("button",{type:"button",className:"navigator-usage-move","data-direction":"up","aria-label":l("usage.moveUp",{account:a.alias}),disabled:0===b,onClick:()=>G(b,"up"),children:(0,d.jsx)(ka,{direction:"up"})}),(0,d.jsx)("button",{type:"button",className:"navigator-usage-move","data-direction":"down","aria-label":l("usage.moveDown",{account:a.alias}),disabled:b===F.length-1,onClick:()=>G(b,"down"),children:(0,d.jsx)(ka,{direction:"down"})})]})]}),a.authError&&(0,d.jsxs)("span",{className:"navigator-usage-auth",children:[(0,d.jsx)("span",{className:"navigator-usage-reason",children:a.authError.message}),a.authError.reloginRequired&&c&&!p&&(0,d.jsx)("button",{type:"button",className:"navigator-usage-relogin","aria-label":l("usage.reloginFor",{account:a.alias}),onClick:()=>c({provider:a.provider,alias:a.alias,seed:a.seed,masked:a.masked,...a.accountKey?{accountKey:a.accountKey}:{},reason:a.authError?.message??""}),children:l("usage.relogin")})]}),a.rows.map(a=>{let b=P(a);return(0,d.jsxs)("span",{className:"navigator-usage-row",children:[(0,d.jsxs)("span",{className:"navigator-usage-head",children:[(0,d.jsx)("span",{className:"navigator-usage-label",children:a.label}),null===b?null:(0,d.jsx)("span",{className:"navigator-usage-state",children:b}),(0,d.jsxs)("span",{className:"navigator-usage-value",style:a.percent>=90?{color:"var(--danger)"}:void 0,children:[a.percent,"%"]})]}),(0,d.jsx)("span",{"aria-hidden":"true",className:"navigator-usage-track",children:(0,d.jsx)("span",{className:"navigator-usage-fill",style:{width:`${Math.max(0,Math.min(100,a.percent))}%`,background:a.percent>=90?"var(--danger)":"var(--metric)"}})})]},a.key)})]},a.orderKey)})}),!p&&(K>0||n)&&(0,d.jsx)("button",{type:"button",className:"navigator-usage-more","aria-expanded":n,onClick:()=>o(a=>!a),children:n?l("usage.showLess"):l("usage.showMore",{count:K})}),(0,d.jsxs)("span",{className:"navigator-usage-row",children:[(0,d.jsxs)("span",{className:"navigator-usage-head",children:[(0,d.jsx)("span",{className:"navigator-usage-label",children:l("usage.bai")}),(0,d.jsx)("span",{className:"navigator-usage-value",style:"measured"===B.status?void 0:{color:"var(--text-muted)"},children:M})]}),null===N?null:(0,d.jsx)("span",{className:"navigator-usage-account",children:N})]}),(0,d.jsx)("span",{className:"navigator-usage-live","aria-live":"polite",children:t})]});return m?(0,d.jsxs)("div",{className:"navigator-usage-shell",children:[(0,d.jsxs)("button",{type:"button",className:"navigator-usage-toggle","aria-expanded":!z,"aria-label":z?`${Q}${null===T?"":`, ${T}`}`:l("usage.showLess"),onClick:()=>{let a=!z;A(a);try{window.localStorage.setItem("omp-sidebar-usage-collapsed",a?"1":"0")}catch{}},children:[(0,d.jsx)("span",{className:"navigator-usage-label",children:z?S.label:l("usage.showLess")}),z&&(0,d.jsx)("span",{className:"navigator-usage-value",style:S.danger?{color:"var(--danger)"}:void 0,children:S.value}),z&&null!==T&&(0,d.jsx)("span",{className:"navigator-usage-alert",children:T}),(0,d.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,transform:z?"rotate(0deg)":"rotate(180deg)"},children:(0,d.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})]}),z?null:U]}):U}let kc={snapshot:null,revision:0,streaming:new Map};function kd(a,b,c){if(0===a.size)return a;let d=new Set(c.map(a=>a.id)),e=new Map(a);for(let[c,f]of a)(f.generation<b||d.has(c))&&e.delete(c);return e.size===a.size?a:e}function ke(a,b){switch(b.type){case"snapshot":{let c=b.data;if(c.revision<a.revision)return a;let d="sse"===b.source?new Map:kd(a.streaming,c.run.generation,c.messages);return{snapshot:c,revision:c.revision,streaming:d}}case"state":{let c=b.data;if(!a.snapshot||c.revision<a.revision)return a;let d={...a.snapshot,revision:c.revision,room:c.room,members:c.members,run:c.run,loadError:c.loadError};return{snapshot:d,revision:c.revision,streaming:kd(a.streaming,c.run.generation,d.messages)}}case"message":{let c=b.data;if(!a.snapshot||c.revision<a.revision)return a;let d=function(a,b){let c=a.findIndex(a=>a.id===b.id);if(c>=0){let d=a.slice();return d[c]=b,d}let d=[...a,b];return a.length>0&&a[a.length-1].createdAt>b.createdAt&&d.sort((a,b)=>a.createdAt-b.createdAt),d}(a.snapshot.messages,c.message),e=a.streaming;if(e.has(c.message.id)){let a=new Map(e);a.delete(c.message.id),e=a}return{snapshot:{...a.snapshot,revision:c.revision,messages:d},revision:c.revision,streaming:e}}case"delta":{let c=b.data;if(!a.snapshot||c.generation<a.snapshot.run.generation||a.snapshot.messages.some(a=>a.id===c.messageId))return a;let d=a.streaming.get(c.messageId);if(d&&d.text===c.text&&d.generation===c.generation)return a;let e=new Map(a.streaming);return e.set(c.messageId,{messageId:c.messageId,memberId:c.memberId,text:c.text,generation:c.generation}),{...a,streaming:e}}}}async function kf(a){try{let b=await a.json();if("string"==typeof b?.error&&b.error)return b.error}catch{}return`HTTP ${a.status}`}var kg=c(48090);let kh=["slow","normal","active"],ki=[5,10,20,30,60,120].filter(a=>a>=1&&a<=120);function kj({row:a,lt:b,locale:c,now:e,compact:f}){let g="weekly"!==a.kind?a.label:a.tier?b("lounge.usage.weeklyTier",{tier:a.tier}):b("lounge.usage.weekly"),h="blocked"===a.state?b("lounge.usage.blocked"):"spent"===a.state?b("lounge.usage.spent"):null,i=!f&&null!==a.resetsAt&&a.resetsAt>e?b("lounge.usage.resets",{when:(0,bR.fw)(new Date(a.resetsAt),c,new Date(e))}):null,j="usable"!==a.state;return(0,d.jsxs)("span",{className:"lounge-usage","data-compact":f?"true":void 0,"data-state":a.state,children:[(0,d.jsxs)("span",{className:"lounge-usage-head",children:[(0,d.jsx)("span",{className:"lounge-usage-label",children:g}),i?(0,d.jsx)("span",{className:"lounge-usage-reset",children:i}):null,h?(0,d.jsx)("span",{className:"lounge-usage-state",children:h}):null,(0,d.jsxs)("span",{className:"lounge-usage-value",children:[a.percent,"%"]})]}),f?null:(0,d.jsx)("span",{"aria-hidden":"true",className:"lounge-usage-track",children:(0,d.jsx)("span",{className:"lounge-usage-fill",style:{width:`${Math.max(0,Math.min(100,a.percent))}%`,background:j?"var(--danger)":"var(--metric)"}})})]})}function kk({member:a,lounge:b,usage:c,now:f,disabled:g}){let{lt:h,locale:i}=(0,O.H)(),j=(0,O.a)(a.alias,i),k=function(a,b,c){let d=b.account,e=[],f=[];if(d&&(d.selectionRequired||void 0===d.credentialId))return{selectionRequired:!0,primary:e,warnings:f};let g=(0,bJ.k)(a);return a.forEach((a,h)=>{if(a.provider!==b.provider||(d?a.credentialId!==d.credentialId:g[h].alias!==b.alias)||!0===a.disabled)return;let i="number"==typeof a.autoBlockedUntilMs&&a.autoBlockedUntilMs>c,j=(a.limits??[]).flatMap(b=>{let c=j6(b);if(null===c)return[];let d=i?"blocked":(0,bJ.xL)(b)?"spent":"warning"===b.status||c>=90?"warning":"usable",e=b.window?.resetsAt,f=b.scope?.tier??b.scope?.modelId;return[{row:{key:`${a.provider}:${a.credentialId??h}:${b.id}`,label:b.label||b.id,kind:j5(b),tier:"string"==typeof f&&f?f:null,percent:c,resetsAt:"number"==typeof e&&Number.isFinite(e)?e:null,state:d},alert:j7(b)}]}),k=j.filter(({row:a})=>"short"!==a.kind);k.length>0?(e.push(...k.map(({row:a})=>a)),f.push(...j.filter(({row:a,alert:b})=>"short"===a.kind&&b).map(({row:a})=>a))):e.push(...j.map(({row:a})=>a))}),{selectionRequired:!1,primary:e,warnings:f}}(c.state.data?.reports??[],a,f),l=a.weeklyUsage?[{key:`${a.id}:weekly`,label:h("lounge.usage.weekly"),kind:"weekly",tier:null,percent:Math.round(100*a.weeklyUsage.usedFraction),resetsAt:a.weeklyUsage.resetsAt??null,state:a.weeklyUsage.usedFraction>=1?"spent":"usable"}]:k.primary,m=null===c.state.data&&c.loading,n=h(`lounge.state.${a.state}`),o=`lounge-member-${a.id}-status`,p=b.snapshot?.room.participants??[],q=a.account,r=q?.credentialId,s=void 0!==r&&!q?.choices.some(a=>a.credentialId===r),t=void 0!==q&&(q.selectionRequired||void 0===r||s),u=void 0!==q&&q.choices.length>1,[v,w]=(0,e.useState)(!1),x=void 0!==q&&(t||u&&v),y=`lounge-member-${a.id}-account`,z=l.filter(a=>null===a.tier),A=[...l.filter(a=>null!==a.tier),...k.warnings];return(0,d.jsxs)("li",{className:"lounge-member","data-state":a.state,"data-enabled":a.enabled?"true":"false",children:[(0,d.jsxs)("span",{className:"lounge-member-face",children:[(0,d.jsx)(bU,{seed:a.seed,size:40,provider:a.provider}),(0,d.jsx)("span",{className:"lounge-member-dot","aria-hidden":"true"})]}),(0,d.jsxs)("span",{className:"lounge-member-body",children:[(0,d.jsxs)("span",{className:"lounge-member-head",children:[(0,d.jsxs)("span",{className:"lounge-member-title",children:[(0,d.jsx)("span",{className:"lounge-member-name",children:j}),(0,d.jsx)("span",{id:o,className:"lounge-member-state",children:n})]}),(0,d.jsxs)(kg.h.Root,{size:"16",tone:"neutral",className:"lounge-switch",checked:a.enabled,disabled:g,onCheckedChange:c=>{let d=c?[...p.filter(b=>b!==a.id),a.id]:p.filter(b=>b!==a.id);b.updateSettings({participants:d})},children:[(0,d.jsx)(kg.h.HiddenInput,{"aria-label":h("lounge.participate",{name:j}),"aria-describedby":o}),(0,d.jsx)(kg.h.Control,{children:(0,d.jsx)(kg.h.Thumb,{})})]})]}),a.reason?(0,d.jsx)("span",{className:"lounge-member-reason",children:a.reason}):null,z.length+A.length>0?(0,d.jsxs)("span",{className:"lounge-member-usage",children:[z.map(a=>(0,d.jsx)(kj,{row:a,lt:h,locale:i,now:f},a.key)),A.map(a=>(0,d.jsx)(kj,{row:a,lt:h,locale:i,now:f,compact:!0},a.key))]}):(0,d.jsx)("span",{className:"lounge-member-usage-empty",children:m?h("lounge.usage.loading"):k.selectionRequired?h("lounge.account.required"):h("lounge.usage.none")}),(0,d.jsxs)("span",{className:"lounge-member-meta",children:[(0,d.jsxs)("span",{className:"lounge-member-model",children:[(0,bJ.bN)(a.provider)," \xb7 ",a.model]}),u&&!t?(0,d.jsx)("button",{type:"button",className:"lounge-member-account-toggle","aria-expanded":v,"aria-controls":y,onClick:()=>w(a=>!a),children:h("lounge.account.change")}):null]}),x&&q?(0,d.jsxs)("span",{className:"lounge-member-account",children:[(0,d.jsx)("label",{className:"sr-only",htmlFor:y,children:h("lounge.account.for",{name:j})}),(0,d.jsxs)("select",{id:y,className:"lounge-select",value:void 0===r?"":String(r),disabled:g||0===q.choices.length,"aria-describedby":"lounge-account-hint",onChange:c=>{let d=Number(c.target.value);Number.isInteger(d)&&(b.updateSettings({accountBindings:{[a.id]:d}}),w(!1))},children:[void 0===r?(0,d.jsx)("option",{value:"",disabled:!0,children:h("lounge.account.choose")}):null,s?(0,d.jsx)("option",{value:String(r),disabled:!0,children:h("lounge.account.missing",{id:r})}):null,q.choices.map(a=>(0,d.jsx)("option",{value:String(a.credentialId),children:a.label},a.credentialId))]})]}):null]})]})}function kl({lounge:a,usage:b,onOpenLounge:c,loungeOpen:e=!1}){var f;let g,{lt:h,locale:i}=(0,O.H)(),j=i$(1e4),k=a.snapshot,l=k?.room??null,m=k?.members??[],n=k?.loadError??null,o=a.pending.has("settings"),p=null===k||null!==n,q=m.filter(a=>a.enabled).length,r=new Intl.DateTimeFormat(i,{hour:"2-digit",minute:"2-digit"}),s=l&&!ki.includes(l.sleepAfterMinutes)?[...ki,l.sleepAfterMinutes].sort((a,b)=>a-b):ki,t=k?.run??null;return(0,d.jsxs)("div",{id:"navigator-lounge-panel",className:"lounge-panel",children:[(0,d.jsxs)("div",{className:"lounge-panel-room",children:[(0,d.jsxs)("div",{className:"lounge-panel-room-head",children:[(0,d.jsx)("span",{className:"lounge-panel-title",children:h("lounge.title")}),(0,d.jsxs)(kg.h.Root,{size:"24",tone:"neutral",className:"lounge-switch lounge-room-switch",checked:l?.enabled??!1,disabled:p||o,onCheckedChange:b=>{a.updateSettings({enabled:b})},children:[(0,d.jsx)(kg.h.Label,{className:"lounge-room-switch-label",children:l?.enabled?h("lounge.roomOn"):h("lounge.roomOff")}),(0,d.jsx)(kg.h.HiddenInput,{"aria-label":h("lounge.roomSwitch")}),(0,d.jsx)(kg.h.Control,{children:(0,d.jsx)(kg.h.Thumb,{})})]})]}),null===k?(0,d.jsx)("p",{className:"lounge-panel-note",role:a.loadError?"alert":"status",children:a.loadError?h("lounge.loadFailed",{error:a.loadError}):h("lounge.connecting")}):n?(0,d.jsx)("p",{className:"lounge-panel-note","data-tone":"danger",role:"alert",children:h("lounge.loadFailed",{error:n})}):l&&!l.enabled?(0,d.jsx)("p",{className:"lounge-panel-note",children:h("lounge.roomOffHint")}):l?.asleep?(0,d.jsx)("p",{className:"lounge-panel-note",children:h("lounge.asleep")}):null,"reconnecting"===a.connection&&null!==k?(0,d.jsx)("p",{className:"lounge-panel-note",role:"status",children:h("lounge.reconnecting")}):null,a.actionError?(0,d.jsx)("p",{className:"lounge-panel-note","data-tone":"danger",role:"alert",children:h("lounge.actionFailed",{error:a.actionError})}):null,c?(0,d.jsx)("button",{type:"button",className:"lounge-panel-open","aria-pressed":e,onClick:c,children:h("lounge.open")}):null]}),(0,d.jsxs)("div",{className:"lounge-panel-members",children:[(0,d.jsxs)("div",{className:"lounge-panel-section-head",children:[(0,d.jsx)("span",{children:h("lounge.members")}),m.length>0?(0,d.jsx)("span",{className:"lounge-panel-count",children:h("lounge.membersCount",{active:q,total:m.length})}):null]}),(0,d.jsx)("ul",{className:"lounge-member-list","aria-label":h("lounge.members"),children:m.map(c=>(0,d.jsx)(kk,{member:c,lounge:a,usage:b,now:j,disabled:p||o},c.id))}),m.some(a=>a.account)?(0,d.jsx)("p",{id:"lounge-account-hint",className:"lounge-panel-hint",children:h("lounge.account.hint")}):null]}),l?(0,d.jsxs)("div",{className:"lounge-panel-settings",role:"group","aria-label":h("lounge.settings"),children:[(0,d.jsx)("div",{className:"lounge-panel-section-head",children:(0,d.jsx)("span",{children:h("lounge.settings")})}),(0,d.jsxs)("div",{className:"lounge-setting",children:[(0,d.jsx)("span",{className:"lounge-setting-label",id:"lounge-pace-label",children:h("lounge.pace")}),(0,d.jsx)("div",{className:"lounge-segmented",role:"radiogroup","aria-labelledby":"lounge-pace-label",children:kh.map(b=>(0,d.jsx)("button",{type:"button",role:"radio","aria-checked":l.pace===b,disabled:p||o,onClick:()=>{l.pace!==b&&a.updateSettings({pace:b})},children:h(`lounge.pace.${b}`)},b))})]}),(0,d.jsxs)("label",{className:"lounge-setting lounge-setting-inline",children:[(0,d.jsx)("span",{className:"lounge-setting-label",children:h("lounge.sleep")}),(0,d.jsx)("select",{className:"lounge-select",value:l.sleepAfterMinutes,disabled:p||o,onChange:b=>{a.updateSettings({sleepAfterMinutes:Number(b.target.value)})},children:s.map(a=>(0,d.jsx)("option",{value:a,children:h("lounge.sleepMinutes",{minutes:a})},a))})]}),(0,d.jsxs)("div",{className:"lounge-setting",children:[(0,d.jsxs)(kg.h.Root,{size:"16",tone:"neutral",className:"lounge-switch lounge-setting-switch",checked:l.autoTalk,disabled:p||o,onCheckedChange:b=>{a.updateSettings({autoTalk:b})},children:[(0,d.jsx)(kg.h.Label,{className:"lounge-setting-label",children:h("lounge.autoTalk")}),(0,d.jsx)(kg.h.HiddenInput,{"aria-describedby":"lounge-autotalk-hint"}),(0,d.jsx)(kg.h.Control,{children:(0,d.jsx)(kg.h.Thumb,{})})]}),(0,d.jsx)("span",{id:"lounge-autotalk-hint",className:"lounge-setting-hint",children:h("lounge.autoTalkHint")}),l.autoTalk&&l.autoTalkPausedReason?(0,d.jsx)("span",{className:"lounge-setting-hint","data-tone":"warning",role:"status",children:l.autoTalkPausedReason}):null]}),(0,d.jsxs)("div",{className:"lounge-panel-limits",children:[t?(0,d.jsx)("span",{children:h("lounge.calls",{window:(f=t.calls.windowMs,(g=Math.round(f/36e5))>=1?new Intl.NumberFormat(i,{style:"unit",unit:"hour",unitDisplay:"long"}).format(g):h("lounge.sleepMinutes",{minutes:Math.max(1,Math.round(f/6e4))})),used:t.calls.used,limit:t.calls.limit})}):null,t?(0,d.jsx)("span",{children:h("lounge.perTurn",{limit:t.perTurnLimit})}):null,l.enabled&&!l.asleep&&null!==l.sleepAt&&l.sleepAt>j?(0,d.jsx)("span",{children:h("lounge.sleepAt",{time:r.format(new Date(l.sleepAt))})}):null]})]}):null]})}let km="cuelo-lounge-draft",kn=["\uD83D\uDC4D","❤️","\uD83D\uDE02","\uD83D\uDE2E","\uD83D\uDE4F","\uD83D\uDC40"],ko=Math.floor(1600),kp=[],kq=[];function kr(a,b){if(0===b.length)return a;let c=b.map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),e=RegExp(`(@(?:${c.join("|")}))`,"giu");return a.split(e).map((a,b)=>b%2==1?(0,d.jsx)("span",{className:"lounge-mention",children:a},b):a)}function ks({lounge:a,visible:b=!0,onBack:c}){let{lt:f,locale:g}=(0,O.H)(),i=a.snapshot,j=i?.room??null,k=i?.run??null,l=i?.members??kp,m=i?.messages??kq,n=i?.loadError??null,o=(0,e.useMemo)(()=>new Map(l.map(a=>[a.id,a])),[l]),p=(0,e.useMemo)(()=>new Map(m.map(a=>[a.id,a])),[m]),q=(0,e.useCallback)(a=>{if("user"===a)return f("lounge.you");let b=o.get(a);return b?(0,O.a)(b.alias,g):a},[g,f,o]),r=(0,e.useMemo)(()=>l.flatMap(a=>[(0,O.a)(a.alias,"ko"),(0,O.a)(a.alias,"en")]),[l]),s=(0,e.useMemo)(()=>new Intl.DateTimeFormat(g,{hour:"2-digit",minute:"2-digit"}),[g]),[t,u]=(0,e.useState)(""),[v,w]=(0,e.useState)(null),[x,y]=(0,e.useState)(null),[z,A]=(0,e.useState)(null),B=(0,e.useRef)(null),C=(0,e.useRef)(null),D=(0,e.useRef)(!0),E=(0,e.useId)(),F=(0,e.useCallback)(a=>{u(a);try{a?window.sessionStorage.setItem(km,a):window.sessionStorage.removeItem(km)}catch{}},[]);a.streaming.map(a=>`${a.messageId}:${a.text.length}`).join("|");let G=(0,e.useMemo)(()=>{if(!x)return[];let a=x.query.toLowerCase();return l.filter(b=>!a||(0,O.a)(b.alias,"ko").toLowerCase().startsWith(a)||(0,O.a)(b.alias,"en").toLowerCase().startsWith(a)||b.id.startsWith(a))},[l,x]),H=j?.enabled===!0&&null===n&&null!==i,I=a.pending.has("send"),J=t.trim(),K=v?p.get(v)??null:null,L=a=>{if(!x)return;let b=(0,O.a)(a.alias,g),c=B.current,d=c?.selectionStart??t.length;F(`${t.slice(0,x.start)}@${b} ${t.slice(d)}`),y(null);let e=x.start+b.length+2;window.requestAnimationFrame(()=>{c?.focus(),c?.setSelectionRange(e,e)})},M=async()=>{!H||I||!J||J.length>2e3||await a.send(J,K?.id)&&(F(""),w(null),D.current=!0)},N=k?.active?k.currentMemberId:null,P=a.streaming.some(a=>a.memberId===N),Q=k?.active?k.queuedMemberIds.map(q):[],R=(b,c,e,g)=>{let h="user"===c,i=o.get(c),j=g.message,k=j?.replyToId?p.get(j.replyToId)??null:null;return(0,d.jsxs)("div",{id:j?`lounge-message-${j.id}`:void 0,className:"lounge-bubble-row","data-mine":h?"true":void 0,"data-grouped":g.grouped?"true":void 0,"data-streaming":g.streaming?"true":void 0,children:[h?null:(0,d.jsx)("span",{className:"lounge-bubble-face",children:g.grouped||!i?null:(0,d.jsx)(bU,{seed:i.seed,size:32,provider:i.provider})}),(0,d.jsxs)("div",{className:"lounge-bubble-stack",children:[h||g.grouped?null:(0,d.jsx)("span",{className:"lounge-bubble-name",children:q(c)}),(0,d.jsxs)("div",{className:"lounge-bubble-line",children:[(0,d.jsxs)("div",{className:"lounge-bubble",children:[j?.replyToId?(0,d.jsxs)("button",{type:"button",className:"lounge-bubble-quote",onClick:()=>{document.getElementById(`lounge-message-${j.replyToId}`)?.scrollIntoView({block:"center",behavior:"smooth"})},children:[(0,d.jsx)("span",{className:"lounge-bubble-quote-name",children:k?q(k.memberId):f("lounge.missingMessage")}),(0,d.jsx)("span",{className:"lounge-bubble-quote-text",children:k?k.text:""})]}):null,(0,d.jsx)("div",{className:"lounge-bubble-text",children:e})]}),void 0!==g.createdAt?(0,d.jsx)("time",{className:"lounge-bubble-time",dateTime:new Date(g.createdAt).toISOString(),children:s.format(new Date(g.createdAt))}):null]}),j?(0,d.jsxs)("div",{className:"lounge-bubble-foot",children:[j.reactions.filter(a=>a.by.length>0).map(b=>(0,d.jsxs)("button",{type:"button",className:"lounge-reaction","aria-pressed":b.by.includes("user"),"aria-label":f("lounge.reaction",{emoji:b.emoji,count:b.by.length}),title:b.by.map(q).join(", "),disabled:!H,onClick:()=>{a.react(j.id,b.emoji)},children:[(0,d.jsx)("span",{"aria-hidden":"true",children:b.emoji}),(0,d.jsx)("span",{className:"lounge-reaction-count",children:b.by.length})]},b.emoji)),(0,d.jsxs)("span",{className:"lounge-bubble-actions",children:[(0,d.jsx)("button",{type:"button",className:"lounge-bubble-action",disabled:!H,onClick:()=>{w(j.id),B.current?.focus()},children:f("lounge.reply")}),(0,d.jsx)("button",{type:"button",className:"lounge-bubble-action","aria-expanded":z===j.id,disabled:!H,onClick:()=>A(a=>a===j.id?null:j.id),children:f("lounge.react")})]}),z===j.id?(0,d.jsx)("span",{className:"lounge-reaction-picker",role:"group","aria-label":f("lounge.react"),children:kn.map(b=>(0,d.jsx)("button",{type:"button",onClick:()=>{A(null),a.react(j.id,b)},children:b},b))}):null]}):null]})]},b)},S=N?f("lounge.speaking",{name:q(N)}):null;return(0,d.jsxs)("section",{className:"lounge-view","aria-label":f("lounge.title"),hidden:!b,children:[(0,d.jsxs)("header",{className:"lounge-view-header",children:[c?(0,d.jsx)(h.r,{variant:"ghost",size:"small",className:"lounge-view-back",onClick:c,children:f("lounge.back")}):null,(0,d.jsxs)("div",{className:"lounge-view-heading",children:[(0,d.jsx)("h2",{className:"lounge-view-title",children:f("lounge.title")}),(0,d.jsx)("span",{className:"lounge-view-room","data-on":j?.enabled?"true":"false",children:j?.enabled?f("lounge.roomOn"):f("lounge.roomOff")})]}),(0,d.jsx)("ul",{className:"lounge-view-faces","aria-label":f("lounge.members"),children:l.filter(a=>a.enabled).map(a=>(0,d.jsxs)("li",{className:"lounge-view-face","data-state":a.state,children:[(0,d.jsx)(bU,{seed:a.seed,size:24,provider:a.provider}),(0,d.jsx)("span",{className:"lounge-member-dot","aria-hidden":"true"}),(0,d.jsx)("span",{className:"sr-only",children:`${q(a.id)} ${f(`lounge.state.${a.state}`)}`})]},a.id))})]}),a.loadError&&!i?(0,d.jsx)("p",{className:"lounge-banner","data-tone":"danger",role:"alert",children:f("lounge.loadFailed",{error:a.loadError})}):null,n?(0,d.jsx)("p",{className:"lounge-banner","data-tone":"danger",role:"alert",children:f("lounge.loadFailed",{error:n})}):null,"reconnecting"===a.connection&&i?(0,d.jsx)("p",{className:"lounge-banner",role:"status",children:f("lounge.reconnecting")}):null,a.actionError?(0,d.jsxs)("p",{className:"lounge-banner","data-tone":"danger",role:"alert",children:[(0,d.jsx)("span",{children:f("lounge.actionFailed",{error:a.actionError})}),(0,d.jsx)("button",{type:"button",className:"lounge-banner-action",onClick:a.dismissActionError,"aria-label":"✕",children:"✕"})]}):null,!j||j.enabled||n?j?.asleep?(0,d.jsx)("p",{className:"lounge-banner",children:f("lounge.asleep")}):j?.autoTalk&&j.autoTalkPausedReason?(0,d.jsx)("p",{className:"lounge-banner",role:"status",children:j.autoTalkPausedReason}):null:(0,d.jsxs)("p",{className:"lounge-banner",children:[(0,d.jsx)("span",{children:f("lounge.roomOffBanner")}),(0,d.jsx)("button",{type:"button",className:"lounge-banner-action",disabled:a.pending.has("settings"),onClick:()=>{a.updateSettings({enabled:!0})},children:f("lounge.turnOn")})]}),(0,d.jsxs)("div",{ref:C,className:"lounge-log",role:"log","aria-label":f("lounge.messages"),onScroll:a=>{let b=a.currentTarget;D.current=b.scrollHeight-b.scrollTop-b.clientHeight<80},children:[i&&0===m.length&&0===a.streaming.length?(0,d.jsx)("p",{className:"lounge-empty",children:f("lounge.empty")}):null,i||a.loadError?null:(0,d.jsx)("p",{className:"lounge-empty",children:f("lounge.connecting")}),m.map((a,b)=>{let c=b>0?m[b-1]:null,d=null!==c&&c.memberId===a.memberId&&a.createdAt-c.createdAt<3e5&&!a.replyToId;return R(a.id,a.memberId,kr(a.text,r),{message:a,createdAt:a.createdAt,grouped:d})}),a.streaming.map(a=>R(`stream-${a.messageId}`,a.memberId,(0,d.jsxs)(d.Fragment,{children:[kr(a.text,r),(0,d.jsx)("span",{className:"lounge-caret","aria-hidden":"true"})]}),{grouped:!1,streaming:!0})),N&&!P?R(`typing-${N}`,N,(0,d.jsxs)("span",{className:"lounge-typing","aria-hidden":"true",children:[(0,d.jsx)("span",{}),(0,d.jsx)("span",{}),(0,d.jsx)("span",{})]}),{grouped:!1,streaming:!0}):null]}),(0,d.jsxs)("div",{className:"lounge-composer",children:[(0,d.jsxs)("div",{className:"lounge-composer-status",role:"status","aria-live":"polite",children:[S?(0,d.jsx)("span",{children:S}):null,Q.length>0?(0,d.jsx)("span",{children:f("lounge.queued",{names:Q.join(", ")})}):null]}),K?(0,d.jsxs)("div",{className:"lounge-reply-chip",children:[(0,d.jsxs)("span",{className:"lounge-reply-chip-text",children:[(0,d.jsx)("strong",{children:f("lounge.replyTo",{name:q(K.memberId)})}),(0,d.jsx)("span",{children:K.text})]}),(0,d.jsx)("button",{type:"button",className:"lounge-banner-action",onClick:()=>w(null),children:f("lounge.cancelReply")})]}):null,(0,d.jsxs)("div",{className:"lounge-composer-row",children:[x&&G.length>0?(0,d.jsx)("ul",{id:E,className:"lounge-mention-list",role:"listbox","aria-label":f("lounge.mentionList"),children:G.map((a,b)=>(0,d.jsxs)("li",{id:`${E}-${a.id}`,role:"option","aria-selected":b===x.index,onMouseDown:b=>{b.preventDefault(),L(a)},children:[(0,d.jsx)(bU,{seed:a.seed,size:20,provider:a.provider}),(0,d.jsx)("span",{children:(0,O.a)(a.alias,g)}),(0,d.jsx)("span",{className:"lounge-mention-state",children:f(`lounge.state.${a.state}`)})]},a.id))}):null,(0,d.jsx)("textarea",{ref:B,className:"lounge-composer-input",rows:1,value:t,maxLength:2e3,disabled:!H,placeholder:H?f("lounge.placeholder"):f("lounge.placeholderOff"),"aria-label":f("lounge.composer"),role:"combobox","aria-expanded":null!==x&&G.length>0,"aria-controls":E,"aria-autocomplete":"list","aria-activedescendant":x&&G[x.index]?`${E}-${G[x.index].id}`:void 0,onChange:a=>{var b;let c,d,e=a.target.value;F(e);let f=(b=a.target.selectionStart??e.length,c=e.slice(0,b),(d=/(^|\s)@([^\s@]*)$/u.exec(c))?{start:b-d[2].length-1,query:d[2]}:null);y(f?{...f,index:0}:null)},onBlur:()=>y(null),onKeyDown:a=>{if(!a.nativeEvent.isComposing){if(x&&G.length>0){if("ArrowDown"===a.key||"ArrowUp"===a.key){a.preventDefault();let b="ArrowDown"===a.key?1:-1;y({...x,index:(x.index+b+G.length)%G.length});return}if("Enter"===a.key||"Tab"===a.key){a.preventDefault(),L(G[Math.min(x.index,G.length-1)]);return}if("Escape"===a.key){a.preventDefault(),y(null);return}}if("Escape"===a.key&&v){a.preventDefault(),w(null);return}"Enter"!==a.key||a.shiftKey||(a.preventDefault(),M())}}}),k?.active?(0,d.jsxs)(h.r,{variant:"neutralOutline",size:"small",className:"lounge-composer-button lounge-stop-button",loading:a.pending.has("stop"),onClick:()=>{a.stop()},children:[(0,d.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10","aria-hidden":"true",children:(0,d.jsx)("rect",{width:"10",height:"10",rx:"2",fill:"currentColor"})}),f("lounge.stop")]}):null,(0,d.jsx)(h.r,{variant:"neutralSolid",size:"small",className:"lounge-composer-button",disabled:!H||!J||J.length>2e3,loading:I,onClick:()=>{M()},children:f("lounge.send")})]}),t.length>=ko?(0,d.jsx)("span",{className:"lounge-composer-counter",children:f("lounge.textLimit",{count:t.length,max:2e3})}):null]})]})}var kt=c(60918),ku=c(73174),kv=c(78690),kw=c(54027),kx=c.n(kw);let ky=[],kz={kind:"loading"};function kA({participant:a,sessionId:b,cwd:c,recipient:f,onBackToMain:g,onOpenFile:h,client:i}){let{ot:j}=(0,kv.v)(),k=(0,kt.Jg)(),l=k(a),m=(0,e.useMemo)(()=>i??(0,b4.Et)(),[i]),{snapshot:n}=a,o=(0,e.useMemo)(()=>[{key:a.key,liveId:n.id,status:n.status}],[a.key,n.id,n.status]),p=(0,dY._Z)(o,{sessionId:b??"",client:m,enabled:!!b}).get(a.key),q=p?.state??kz,r="ready-archive"===q.kind,s=p?.entries??ky,t=(0,e.useMemo)(()=>"ready-live"===q.kind?q.entries:"ready-archive"===q.kind?(0,dY.RO)(q.entries):s,[s,q]),u=(0,e.useMemo)(()=>t.flatMap(a=>"message"in a?[a.message]:[]),[t]),v=(0,e.useMemo)(()=>{let a=new Map;for(let b of u)"toolResult"===b.role&&a.set(b.toolCallId,b);return a},[u]),w=(0,e.useMemo)(()=>{let a=new Set,b=[];for(let d of u)if("assistant"===d.role)for(let e of aR(d.content,v,c))a.has(e.filePath)||(a.add(e.filePath),b.push(e));return b},[c,u,v]),[x,y]=(0,e.useState)("transcript"),z=(0,e.useId)(),A=(0,e.useRef)(null),B=["transcript","files"],C=a=>{if("ArrowRight"!==a.key&&"ArrowLeft"!==a.key)return;a.preventDefault();let b=B[(B.indexOf(x)+1)%B.length];y(b),document.getElementById(`${z}-${b}-tab`)?.focus()},D=(0,dY.Ch)(a.status)&&n.progress?.lastIntent?.trim()||null,E=a.agent?`${j("office.maker")} \xb7 ${a.agent}`:j("office.maker");return(0,d.jsxs)("section",{className:kx().maker,"aria-label":j("office.makerRecord",{name:a.name}),children:[(0,d.jsxs)("header",{className:kx().makerHeader,children:[(0,d.jsx)(kt.AT,{seat:a.seat,size:32}),(0,d.jsxs)("div",{className:kx().makerIdentity,children:[(0,d.jsx)("h2",{className:kx().makerName,children:a.name}),(0,d.jsxs)("p",{className:kx().makerMeta,children:[(0,d.jsx)("span",{className:kx().viewOnly,children:j("office.viewOnly")}),(0,d.jsx)("span",{children:E}),(0,d.jsx)("span",{className:kx().mono,children:a.model??j("office.modelUnknown")})]})]}),(0,d.jsxs)("span",{className:kx().status,"data-tone":l.tone,children:[(0,d.jsx)("span",{className:kx().dot,"aria-hidden":"true"}),l.status]})]}),(D||"completed"===a.status)&&(0,d.jsx)("p",{className:kx().makerNote,children:D?`${j("office.currentStep")} \xb7 ${D}`:j("office.notAccepted")}),(0,d.jsx)("div",{className:kx().tabs,role:"tablist","aria-label":a.name,children:B.map(a=>(0,d.jsx)("button",{id:`${z}-${a}-tab`,type:"button",role:"tab",className:kx().tab,"aria-selected":x===a,"aria-controls":`${z}-${a}-panel`,tabIndex:x===a?0:-1,onClick:()=>y(a),onKeyDown:C,children:"transcript"===a?j("office.tabTranscript"):j("office.tabFiles",{count:r?"?":w.length})},a))}),(0,d.jsx)("div",{ref:A,id:`${z}-${x}-panel`,role:"tabpanel","aria-labelledby":`${z}-${x}-tab`,className:kx().makerBody,children:"transcript"===x?(0,d.jsxs)(d.Fragment,{children:["loading"===q.kind&&(0,d.jsx)("p",{role:"status",className:kx().bodyNote,children:j("office.loading")}),"unreachable"===q.kind&&(0,d.jsx)("p",{role:"status",className:kx().bodyNote,children:q.message}),"error"===q.kind&&(0,d.jsx)("p",{role:"alert",className:kx().bodyNote,"data-tone":"failed",children:q.message}),"empty"===q.kind&&(0,d.jsx)("p",{role:"status",className:kx().bodyNote,children:q.note??j("office.transcriptEmpty")}),r&&(0,d.jsx)("p",{role:"status",className:kx().bodyNote,children:q.note??j("office.archiveNote")}),"ready-live"===q.kind&&u.map((a,b)=>(0,d.jsx)(cX,{message:a,toolResults:v,cwd:c,onOpenFile:h,showTimestamp:!0,prevTimestamp:u[b-1]?.timestamp},`${b}:${a.timestamp??0}`)),r&&q.entries.map((a,b)=>(0,d.jsxs)("div",{className:kx().archiveEntry,children:[(0,d.jsxs)("span",{className:kx().archiveRole,children:[a.role," \xb7 ",a.kind]}),a.text||j("office.transcriptEmpty")]},`${a.at??0}:${b}`))]}):r?(0,d.jsx)("p",{className:kx().bodyNote,children:j("office.filesArchive")}):0===w.length?(0,d.jsx)("p",{className:kx().bodyNote,children:j("office.filesEmpty")}):(0,d.jsx)("ul",{className:kx().files,children:w.map(a=>(0,d.jsx)("li",{children:(0,d.jsxs)("button",{type:"button",className:kx().file,onClick:()=>h(a.filePath),title:a.filePath,children:[(0,d.jsx)("span",{className:kx().fileName,children:aY(a.filePath)}),(0,d.jsx)("span",{className:kx().filePath,children:a.filePath})]})},a.filePath))})}),(0,d.jsxs)("footer",{className:kx().makerFooter,children:[(0,d.jsx)("p",{className:kx().composerNote,children:j("office.composerNote",{name:k(f).name})}),(0,d.jsx)("button",{type:"button",className:kx().backButton,onClick:g,children:j("office.backToMain")})]})]})}var kB=c(69387),kC=c(64567);let kD="git pull && bun install && bun run build && node Tools/CUELO_Setup/files/native-runtime-patch.js --target .";function kE(a){return"unknown"===a?a:`v${a}`}function kF(){let{locale:a,t:b}=(0,x.s)(),c=D(),[f,g]=(0,e.useState)(null),[h,i]=(0,e.useState)("idle"),[j,k]=(0,e.useState)(!1),[l,m]=(0,e.useState)(null),[n,o]=(0,e.useState)(null),p=(0,e.useRef)(null),q=(0,e.useRef)(null),r=(0,e.useRef)(null),s=(0,e.useRef)(null),[t,u]=(0,e.useState)(null);if((0,e.useCallback)(()=>{let a=q.current?.getBoundingClientRect();if(!a)return;let b=window.visualViewport?.height??window.innerHeight,{side:c,maxHeight:d}=e$(a.top,a.bottom,b,e_(b,.72,620),{margin:12,minHeight:0}),e=Math.min(430,window.innerWidth-24),f=Math.max(12,window.innerWidth-e-12);u({left:Math.min(a.right+8,f),width:e,maxHeight:d,..."above"===c?{bottom:b-a.top+8}:{top:a.bottom+8}})},[]),(0,e.useCallback)(async a=>{i("loading");try{let b=await fetch("/api/updates",{cache:"no-store",signal:a});if(!b.ok)return;let c=await b.json();g(c),i("ready")}catch{a?.aborted||i("ready")}},[]),"ready"!==h||!f?.updateAvailable||!f.latestRelease)return null;let v=f.latestRelease,w=v.publishedAt?new Intl.DateTimeFormat(a,{dateStyle:"medium"}).format(new Date(v.publishedAt)):null,y=v.body.trim()||v.name,z=async a=>{try{await br(a),clearTimeout(p.current??void 0),o(a),p.current=setTimeout(()=>o(null),1600)}catch{m(b("updates.copyFailed"))}};return(0,d.jsxs)("div",{ref:q,"data-dismissible-layer":j?"":void 0,style:{position:"relative",width:"100%"},children:[(0,d.jsxs)("button",{ref:s,type:"button","aria-expanded":j,"aria-haspopup":"dialog",onClick:()=>{k(a=>!a),m(null)},title:b("updates.availableTitle",{version:kE(v.version)}),style:{width:"100%",minHeight:c?44:34,display:"flex",alignItems:"center",justifyContent:"center",gap:8,padding:"7px 10px",border:"1px solid color-mix(in srgb, var(--warning) 54%, var(--border))",borderRadius:9,background:"color-mix(in srgb, var(--warning) 8%, transparent)",color:"var(--warning)",cursor:"pointer",fontSize:11,fontFamily:"var(--font-mono)",transition:"background 0.12s, border-color 0.12s, color 0.12s"},onMouseEnter:a=>{a.currentTarget.style.background="color-mix(in srgb, var(--warning) 14%, var(--bg-hover))",a.currentTarget.style.borderColor="var(--warning)"},onMouseLeave:a=>{a.currentTarget.style.background="color-mix(in srgb, var(--warning) 8%, transparent)",a.currentTarget.style.borderColor="color-mix(in srgb, var(--warning) 54%, var(--border))"},children:[(0,d.jsx)("span",{"aria-hidden":"true",style:{width:6,height:6,borderRadius:"50%",background:"var(--warning)",boxShadow:"0 0 0 3px color-mix(in srgb, var(--warning) 14%, transparent)"}}),(0,d.jsx)("span",{children:b("updates.available")}),(0,d.jsx)("span",{style:{color:"var(--text)",fontVariantNumeric:"tabular-nums"},children:kE(v.version)})]}),j&&t&&(0,E.createPortal)((0,d.jsxs)("div",{ref:r,"data-dismissible-layer":"",role:"dialog","aria-label":b("updates.dialogTitle"),style:{position:"fixed",left:t.left,top:t.top,bottom:t.bottom,zIndex:700,width:t.width,maxHeight:t.maxHeight,display:"flex",flexDirection:"column",overflow:"hidden",border:"1px solid var(--border)",borderRadius:10,background:"var(--bg-panel)",boxShadow:"0 18px 46px rgba(0,0,0,0.28)"},children:[(0,d.jsxs)("div",{style:{padding:"13px 14px 11px",borderBottom:"1px solid var(--border)",background:"linear-gradient(135deg, color-mix(in srgb, var(--warning) 10%, var(--bg-panel)), var(--bg-panel) 65%)"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{style:{color:"var(--text-dim)",fontSize:10,letterSpacing:"0.08em",textTransform:"uppercase"},children:b("updates.dialogEyebrow")}),(0,d.jsx)("div",{style:{marginTop:3,color:"var(--text)",fontSize:15,fontWeight:650},children:b("updates.dialogTitle")})]}),(0,d.jsx)("div",{style:{color:"var(--warning)",fontFamily:"var(--font-mono)",fontSize:12,fontVariantNumeric:"tabular-nums"},children:kE(v.version)})]}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 14px",marginTop:9,color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,d.jsx)("span",{children:b("updates.current",{version:kE(f.currentAppVersion)})}),w&&(0,d.jsx)("span",{children:w})]})]}),(0,d.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"11px 14px 14px"},children:[(0,d.jsx)("div",{style:{marginBottom:7,color:"var(--text-dim)",fontSize:10,letterSpacing:"0.08em",textTransform:"uppercase"},children:b("updates.changelog")}),(0,d.jsx)("div",{className:"update-changelog",style:{color:"var(--text-muted)",fontSize:11,lineHeight:1.5},children:(0,d.jsx)(bw,{children:y})})]}),(0,d.jsxs)("div",{style:{flexShrink:0,padding:"10px 14px 12px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,d.jsx)("div",{style:{display:"flex",alignItems:"center",gap:9,marginBottom:10},children:(0,d.jsx)("a",{href:v.htmlUrl,target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",fontSize:11,textDecoration:"underline",textUnderlineOffset:3},children:b("updates.viewRelease")})}),(0,d.jsxs)("div",{style:{color:"var(--text-muted)",fontSize:11,lineHeight:1.45},children:[(0,d.jsx)("div",{style:{marginBottom:7,color:"var(--text-dim)"},children:b("updates.manual")}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,minWidth:0,marginTop:6,padding:"6px 7px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",fontFamily:"var(--font-mono)"},children:[(0,d.jsx)("code",{style:{flex:1,minWidth:0,overflowWrap:"anywhere",color:"var(--text)"},children:kD}),(0,d.jsx)("button",{type:"button",onClick:()=>void z(kD),title:n===kD?b("updates.commandCopied"):b("updates.copyCommand"),"aria-label":n===kD?b("updates.commandCopied"):b("updates.copyCommand"),style:{flex:"0 0 auto",width:c?44:24,height:c?44:24,padding:0,border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:n===kD?"var(--accent)":"var(--text-dim)",cursor:"pointer"},children:n===kD?(0,d.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,d.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]})]}),l&&(0,d.jsx)("div",{role:"alert",style:{marginTop:9,color:"var(--danger)",fontSize:11,lineHeight:1.45},children:l})]})]}),document.body)]})}let kG="pi-web:last-open-by-workspace";function kH(a){let b=a.getItem(kG);if(!b)return{};try{let a=JSON.parse(b);return null===a||"object"!=typeof a||Array.isArray(a)?{}:a}catch{return{}}}function kI(a,b=null){if(b)try{let c=kH(b);if(!(a in c))return;delete c[a],0===Object.keys(c).length?b.removeItem(kG):b.setItem(kG,JSON.stringify(c))}catch{}}function kJ(){try{return iP(null)}catch{return iP(null)}}function kK({auxiliaryDeck:a,resourcePanel:b,variant:c="chat"}={}){var f,p,q;let s,t,u,v,w,y,z,A,D,E,F,G,H,I,J,K,L,M="office"===c,N=M?"/office":"/",O=(0,g.useRouter)(),P=(0,g.useSearchParams)(),[Q]=(0,e.useState)(()=>{let a;return{requestedCwd:a=P.get("cwd")?.trim()||null,sessionId:a?null:P.get("session")}}),{preference:R,toggleTheme:S}=bq(),{locale:T,setLocale:U,t:W,supportedLocales:X}=(0,x.s)(),Y=function(){let[a,b]=(0,e.useState)(null),[c,d]=(0,e.useState)(!1),f=(0,e.useCallback)(()=>{b("Notification"in window?Notification.permission:null)},[]);return{permission:a,dismissed:c,request:(0,e.useCallback)(()=>{"Notification"in window&&"default"===Notification.permission&&Notification.requestPermission().then(b,f)},[f]),dismiss:(0,e.useCallback)(()=>{d(!0);try{window.localStorage.setItem("cuelo-notification-prompt-dismissed","1")}catch{}},[])}}(),Z=(0,e.useSyncExternalStore)(B.subscribe,B.getSnapshot,C),{soundEnabled:$,onSoundToggle:_,playCueSound:aa,preloadCueSound:ab,unlockAudio:ac,soundEnabledRef:ad}=function(){let[a,b]=(0,e.useState)(()=>!0),c=(0,e.useRef)(a),d=(0,e.useRef)(null),f=(0,e.useRef)(null),g=(0,e.useRef)(0),h=(0,e.useRef)(new Map),i=(0,e.useRef)(new Map),j=(0,e.useRef)(new Map),k=(0,e.useRef)(null),l=(0,e.useRef)(new Map),m=(0,e.useRef)(new Map);(0,e.useRef)(new Map);let n=(0,e.useCallback)(a=>{let b=m.current.get(a);return b||(b=j4(a).catch(b=>{throw m.current.delete(a),b}),m.current.set(a,b)),b},[]),o=(0,e.useCallback)(()=>{if(d.current&&"closed"!==d.current.state)return d.current;try{d.current=new AudioContext}catch{return null}return d.current},[]),p=(0,e.useCallback)(()=>(k.current??=dI(),k.current),[]),q=(0,e.useCallback)(async a=>{},[p,n]),r=(0,e.useCallback)(()=>{g.current+=1;let a=f.current;if(f.current=null,a)try{a.stop()}catch{}},[]),s=(0,e.useCallback)((a=!1)=>{if(!a&&!c.current)return;let b=o();b&&"suspended"===b.state&&b.resume().catch(()=>{})},[o]),t=(0,e.useCallback)(()=>{let a=!c.current;a?s(!0):r(),c.current=a,localStorage.setItem("omp-sound-enabled",String(a)),b(a)},[r,s]),u=(0,e.useCallback)(a=>{if(!c.current)return;let b=o();if(!b)return;r();let d=g.current,e=()=>{if(d===g.current&&c.current&&(!a||a()))try{j3(b)}catch{}};"suspended"===b.state?b.resume().then(e).catch(()=>{}):e()},[o,r]);return{soundEnabled:a,onSoundToggle:t,playCueSound:(0,e.useCallback)(async(a,b="done",d)=>{let e,k=await p(),m=null===b?null:(e=a&&Object.hasOwn(dC,a)?dC[a]:null)?k.get(e)?.get(b)??null:null,q=`${a??""}\u0000${b??""}`,s=m?dJ(m.stickers,i.current.get(q)??null):null;null!==s&&i.current.set(q,s);let t=m?dJ(m.voices,h.current.get(q)??null):null,v=t?m?.lines.get(t)??null:null;!t&&m&&null!==(v=dJ(m.captions,j.current.get(q)??null))&&j.current.set(q,v);let w={sticker:s,text:v};if(!c.current||d&&!d())return w;let x=o();if(!x)return w;if(!t)return null!==b&&dF[b]||u(d),w;r();let y=g.current,z=()=>y!==g.current||!c.current||void 0!==d&&!d();return(async()=>{if(!("suspended"===x.state&&(await x.resume().catch(()=>{}),z())))try{let a=l.current.get(t);a||(a=n(t).then(a=>x.decodeAudioData(a.slice(0))).catch(a=>{throw l.current.delete(t),a}),l.current.set(t,a));let b=await a;if(z())return;let c=x.createBufferSource(),d=x.createGain();c.buffer=b,c.connect(d),d.connect(x.destination),d.gain.setValueAtTime(.82,x.currentTime),c.onended=()=>{f.current===c&&(f.current=null)},f.current=c,c.start(),h.current.set(q,t)}catch{if(z()||null!==b&&dF[b])return;try{j3(x)}catch{}}})(),w},[o,u,r,p,n]),preloadCueSound:q,unlockAudio:s,soundEnabledRef:c}}(),ae=function(){let[a,b]=(0,e.useState)({status:"idle",data:null,error:null}),[c,d]=(0,e.useState)(!0),[f,g]=(0,e.useState)(null),h=(0,e.useRef)(null),i=(0,e.useRef)(null),j=(0,e.useCallback)(()=>{i.current?.abort();let a=new AbortController;i.current=a,(0,bJ.t6)({signal:a.signal}).then(b=>{a.signal.aborted||g(b)})},[]),k=(0,e.useCallback)(async()=>{let a=h.current;if(!a)return{status:"error",data:null,error:new bJ.OO("사용량 폴링이 시작되지 않았습니다.","aborted")};d(!0),j();let b=await a.refresh();return d(!1),b},[j]);return{state:a,loading:c,refresh:k,setPaused:(0,e.useCallback)(a=>{h.current?.setPaused(a)},[]),bai:(0,e.useMemo)(()=>(function(a){let b=a?.data;if(!b)return{status:"unmeasured"};let c=b.models.filter(a=>"b-ai"===a.provider);return 0===c.length?{status:"empty"}:{status:"measured",tokens:c.reduce((a,b)=>a+b.tokens,0),from:"number"==typeof b.range?.from?b.range.from:null,to:"number"==typeof b.range?.to?b.range.to:null}})(f),[f])}}();ae.state.data?.reports;let[af,ag]=(0,e.useState)(!1),[ah,ai]=(0,e.useState)(!1),aj=function(a=!0){let[b,c]=(0,e.useReducer)(ke,kc),[d,f]=(0,e.useState)("connecting"),[g,h]=(0,e.useState)(null),[i,j]=(0,e.useState)(null),[k,l]=(0,e.useState)(()=>new Set);(0,e.useRef)(!1).current=null!==b.snapshot;let m=(0,e.useCallback)(async a=>{let b={...a,requestId:"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,roomId:"main"};l(b=>new Set(b).add(a.action));try{let a=await fetch("/api/lounge",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)});if(!a.ok)return j(await kf(a)),!1;let d=await a.json();return d?.snapshot&&c({type:"snapshot",source:"post",data:d.snapshot}),j(null),!0}catch(a){return j(a instanceof Error?a.message:String(a)),!1}finally{l(b=>{let c=new Set(b);return c.delete(a.action),c})}},[]),n=(0,e.useCallback)(a=>m({action:"settings",...a}),[m]),o=(0,e.useCallback)((a,b)=>m(b?{action:"send",text:a,replyToId:b}:{action:"send",text:a}),[m]),p=(0,e.useCallback)(()=>m({action:"stop"}),[m]),q=(0,e.useCallback)((a,b)=>m({action:"reaction",messageId:a,emoji:b}),[m]),r=(0,e.useCallback)(()=>j(null),[]),s=(0,e.useMemo)(()=>[...b.streaming.values()],[b.streaming]);return{snapshot:b.snapshot,streaming:s,connection:d,loadError:g,actionError:i,pending:k,updateSettings:n,send:o,stop:p,react:q,dismissActionError:r}}(ah),ak=(0,e.useRef)(new Set),al=(0,e.useCallback)(()=>{ad.current&&aa(null,"done")},[aa,ad]),[am,an]=(0,e.useState)(null),[ao,ap]=(0,e.useState)(null),[aq,ar]=(0,e.useState)(null),as=(0,e.useRef)(0),at=(0,e.useRef)(null),[au,av]=(0,e.useState)(null),aw=(0,e.useRef)(0),ax=(0,e.useCallback)(a=>{av(b=>b?.id===a?null:b)},[]),[ay,az]=(0,e.useState)(!1),aA=(0,e.useCallback)(()=>{az(a=>{let b=!a;try{window.localStorage.setItem("omp-web:wide-chat",b?"1":"0")}catch{}return b})},[]),[aB,aC]=(0,e.useState)(null),[aD,aE]=(0,e.useState)(()=>Q.requestedCwd?"validating":"idle"),[aF,aG]=(0,e.useState)(null),[aH,aI]=(0,e.useState)(0),[aJ,aK]=(0,e.useState)(0),[aL,aM]=(0,e.useState)(0),[aN,aO]=(0,e.useState)(0),[aP,aQ]=(0,e.useState)(!1),[aR,aS]=(0,e.useState)(null),[aT,aU]=(0,e.useState)(null),[aV]=(0,e.useState)(()=>{let a;return a=0,{reset(){a+=1,aU(null)},check(b,c){let d=++a;aU("checking"),b().then(b=>{d===a&&aU("fresh"===b.status?function(a,b){if(!b.accountKey)return"unknown";let c=a.filter(a=>a.provider===b.provider&&a.accountKey===b.accountKey);return c.some(a=>!0!==a.disabled&&!a.authError)?"recovered":c.length>0?"still-failing":"unknown"}(b.data.reports,c):"unknown")},()=>{d===a&&aU("unknown")})}}}),[aW,aX]=(0,e.useState)(null),[aZ,a$]=(0,e.useState)(0),a_=(0,e.useRef)(null);(0,e.useRef)(null);let[a0,a1]=(0,e.useState)(!1),[a2,a3]=(0,e.useState)(!1),[a4,a5]=(0,e.useState)(null),[a6,a7]=(0,e.useReducer)(r,o),[a8,a9]=(0,e.useState)("characters"),[ba,bb]=(0,e.useState)("governor"),[bc,bd]=(0,e.useState)(()=>{let a;return Number.isFinite(0),{availableWidth:a=0,navigator:a>=n.navigator?"pinned":"drawer",deck:a>=n.deck?"pinned":"view-stack"}}),[be]=(0,e.useState)(kJ),[bf]=(0,e.useState)(iQ),[bg,bh]=(0,e.useState)([]),[bi,bj]=(0,e.useState)({sessions:[],complete:!1}),[bk,bl]=(0,e.useState)(!1),[bm,bn]=(0,e.useState)(!1),[bo,bp]=(0,e.useState)(0),bs=(0,e.useRef)(null),bt=(0,e.useRef)(null),bu=(0,e.useRef)(null),bv=(0,e.useCallback)(()=>{bp(a=>a+1)},[]),bw=(0,e.useCallback)(a=>{a&&ai(!0),ag(a),a||bv()},[bv]),bx=(0,e.useCallback)(a=>{bt.current=a},[]);(0,e.useRef)(!1);let[by,bz]=(0,e.useState)(!1);(0,e.useRef)(!1),(0,e.useRef)(!1),(0,e.useRef)(0);let[bA,bB]=(0,e.useState)(!1),[bC,bD]=(0,e.useState)(!1);(0,e.useRef)(null);let[bE,bF]=(0,e.useState)(null),[bG,bH]=(0,e.useState)(null),bI=(0,e.useRef)(null);(0,e.useRef)(!1),bI.current=bE,bE?.requestId,bE?.dismissed,bG?.requestId,bG?.deploymentCompleted,bG?.cleanup?.status;let bK=(0,e.useCallback)(a=>{if("Tab"!==a.key)return;let b=bu.current;if(!b)return;let c=Array.from(b.querySelectorAll("button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])"));if(0===c.length)return;let d=a.shiftKey?c[0]:c[c.length-1],e=document.activeElement;e!==d&&b.contains(e)||(a.preventDefault(),(a.shiftKey?c[c.length-1]:c[0]).focus())},[]),[bL,bM]=(0,e.useState)(!M),[bN,bP]=(0,e.useState)(!1),[bQ,bR]=(0,e.useState)(!1),bS=(0,e.useRef)(bL),bT=(0,e.useRef)(!1),bU=(0,e.useRef)(!M);(0,e.useRef)(null),bS.current=bL;let bV=(s=(f={clientPainted:bN,compactWorkspace:Z,requestedOpen:bL}).requestedOpen&&f.clientPainted,{laidOut:f.requestedOpen&&(!f.compactWorkspace||f.clientPainted),presented:s,drawer:s&&f.compactWorkspace}),bW=(0,e.useCallback)(a=>{bT.current=a,bM(a),a7(a?{type:"open-layer",layer:"navigator-drawer"}:{type:"close-layer"})},[]),bX=(0,e.useRef)(null);(0,e.useRef)(!1);let bY=(0,e.useRef)(260),bZ=(0,e.useCallback)(()=>480,[]),b$=function(a){let{ariaLabel:b,cssVariable:c,defaultWidth:d,getDefaultWidth:f,getMaxWidth:g,growthDirection:h,maxWidth:i,minWidth:j,storageKey:k,widthRef:l}=a,m=(0,e.useRef)(null),n=(0,e.useRef)(null);(0,e.useRef)(!1);let[o,p]=(0,e.useState)(d),[q,r]=(0,e.useState)(!1),s=(0,e.useCallback)(()=>Math.min(i,Math.max(j,g())),[g,i,j]),t=(0,e.useCallback)(a=>{var b;let c,d;return b=s(),c=Number.isFinite(a)?a:j,d=Math.max(j,b),Math.round(Math.max(j,Math.min(d,c)))},[s,j]),u=(0,e.useCallback)(a=>{l.current=a,m.current?.style.setProperty(c,`${a}px`)},[c,l]),v=(0,e.useCallback)((a,b={})=>{let{forcePersist:c=!1,persist:d=!0}=b,e=t(a),f=e!==l.current;return u(e),p(e),d&&(f||c)&&function(a,b){try{window.localStorage.setItem(a,String(b))}catch{}}(k,e),e},[u,t,k,l]),w=(0,e.useCallback)(a=>{document.body.style.cursor=a.previousCursor,document.body.style.userSelect=a.previousUserSelect},[]),x=(0,e.useCallback)(a=>{let b=n.current;if(b&&b.pointerId===a){n.current=null,w(b),r(!1),v(l.current,{forcePersist:!0});try{b.target.hasPointerCapture(a)&&b.target.releasePointerCapture(a)}catch{}}},[v,w,l]),y=(0,e.useCallback)(a=>{if("mouse"===a.pointerType&&0!==a.button)return;a.preventDefault(),a.stopPropagation();let b=n.current;b&&x(b.pointerId);let c=a.currentTarget;c.focus({preventScroll:!0}),c.setPointerCapture(a.pointerId),n.current={pointerId:a.pointerId,startX:a.clientX,startWidth:l.current,target:c,previousCursor:document.body.style.cursor,previousUserSelect:document.body.style.userSelect},document.body.style.cursor="col-resize",document.body.style.userSelect="none",r(!0)},[x,l]),z=(0,e.useCallback)(a=>{let b=n.current;if(!b||b.pointerId!==a.pointerId)return;if("mouse"===a.pointerType&&0===a.buttons)return void x(a.pointerId);a.preventDefault();let c="right"===h?1:-1,d=t(b.startWidth+(a.clientX-b.startX)*c);u(d),a.currentTarget.setAttribute("aria-valuenow",String(d)),a.currentTarget.setAttribute("aria-valuetext",`${d} px`)},[u,t,x,h]),A=(0,e.useCallback)(a=>{x(a.pointerId)},[x]),B=(0,e.useCallback)(a=>{x(a.pointerId)},[x]),C=(0,e.useCallback)(a=>{x(a.pointerId)},[x]),D=(0,e.useCallback)(()=>{v(f?.()??d,{forcePersist:!0})},[v,d,f]),E=(0,e.useCallback)(()=>{v(l.current)},[v,l]),F=(0,e.useCallback)(a=>{let b=a.shiftKey?32:12,c="right"===h?"ArrowRight":"ArrowLeft",d="right"===h?"ArrowLeft":"ArrowRight";a.key===c?(a.preventDefault(),v(l.current+b,{forcePersist:!0})):a.key===d?(a.preventDefault(),v(l.current-b,{forcePersist:!0})):"Home"===a.key?(a.preventDefault(),v(j,{forcePersist:!0})):"End"===a.key?(a.preventDefault(),v(s(),{forcePersist:!0})):"Enter"===a.key&&(a.preventDefault(),D())},[v,s,h,j,D,l]);return{isResizing:q,panelRef:m,reclampWidth:E,resetWidth:D,separatorProps:{"aria-label":b,"aria-orientation":"vertical","aria-valuemax":s(),"aria-valuemin":j,"aria-valuenow":o,"aria-valuetext":`${o} px`,onDoubleClick:D,onKeyDown:F,onLostPointerCapture:C,onPointerCancel:B,onPointerDown:y,onPointerMove:z,onPointerUp:A,role:"separator",tabIndex:0},width:o}}({ariaLabel:W("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:bZ,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"omp-sidebar-width",widthRef:bY});b$.reclampWidth;let b_=(0,e.useRef)(null),b0=(0,e.useRef)(null),[b1,b2]=(0,e.useState)({sessionId:null,tree:[],leafId:null,navigation:0}),b3=(0,e.useRef)(null),b5=(0,e.useCallback)((a,b,c)=>{b3.current=c,b2(c=>{let d=cp.current;return c.sessionId!==d?{sessionId:d,tree:a,leafId:b,navigation:0}:{...c,tree:a,leafId:b}})},[]),b6=(0,e.useCallback)(a=>{b2(b=>b.leafId===a?b:{...b,navigation:b.navigation+1}),b3.current?.(a)},[]),[b7,b8]=(0,e.useState)(null),b9=(0,e.useCallback)(a=>{b8(a)},[]),[ca,cb]=(0,e.useState)(null),[cc,cd]=(0,e.useState)([]),[ce,cf]=(0,e.useState)(null),cg=function(a,{subagents:b,enabled:c}){let[d,f]=(0,e.useState)(kB.h7),[g,h]=(0,e.useState)("floor"),[i,j]=(0,e.useState)(kC.Jq),k=(0,e.useCallback)(a=>{f(a),h("target")},[]),l=(0,e.useMemo)(()=>(0,b4.Et)(),[]),m=(0,e.useMemo)(()=>a?b.map(b=>({key:`${a}\u0000${b.id}`,liveId:b.id,status:b.status})):[],[a,b]),n=(0,dY._Z)(m,{sessionId:a??"",client:l,enabled:c&&m.length>0});return{selected:d,select:k,pane:g,setPane:h,accounts:(0,e.useMemo)(()=>(function(a,b,c){let d=new Map;if(!a)return d;for(let e of b){let b=c.get(`${a}\u0000${e.id}`);if(!b)continue;let f=function(a){let{state:b}=a;return("ready-live"===b.kind?b.entries:"ready-archive"===b.kind?(0,dY.RO)(b.entries):a.entries).flatMap(a=>"message"in a?[a.message]:[])}(b);f.some(a=>"assistant"===a.role)&&d.set(e.id,(0,kB.O2)(e,f))}return d})(a,b,n),[n,a,b]),view:i,setView:j}}(am?.id??null,{subagents:cc,enabled:M}),{ot:ch}=(0,kv.v)(),[ci,cj]=(0,e.useState)(null),[ck,cl]=(0,e.useState)(!1),[cm,cn]=(0,e.useState)({kind:"idle"}),co=(0,e.useRef)(null),cp=(0,e.useRef)(am?.id??null);cp.current=am?.id??null;let cq=(0,e.useCallback)(a=>{cb(a)},[]),[cr,cs]=(0,e.useState)(null),ct=(0,e.useRef)(null),cu=(0,e.useCallback)((a,b)=>{br(b).then(()=>{ct.current&&clearTimeout(ct.current),cs(a),ct.current=setTimeout(()=>cs(null),1400)})},[]),[cv,cw]=(0,e.useState)(null),cx=(0,e.useCallback)(a=>{cw(a)},[]),[cy,cz]=(0,e.useState)(null),[cA,cB]=(0,e.useState)(null),[cC,cD]=(0,e.useState)(null),[cE,cF]=(0,e.useState)(!1),[cG,cH]=(0,e.useState)("subagents"),cI=(0,e.useCallback)((a,b=!1)=>{a7({type:"select-view",view:a}),cB(null),Z&&bW(!1),(b||"chat"===a)&&bv()},[Z,bv,bW]),cJ=(0,e.useCallback)(a=>{let b=a6.transientLayer===a;cB(null),Z&&"navigator-drawer"===a6.transientLayer&&bW(!1),a7({type:"toggle-layer",layer:a}),b&&bv()},[Z,bv,bW,a6.transientLayer]),cK=(0,e.useCallback)(()=>{if("chat"!==a6.activeView){cH(a6.activeView),cI("chat",!0);return}cI(cG,!0)},[cG,cI,a6.activeView]),cL=(0,e.useCallback)(a=>{cB(null),a7({type:"close-layer"}),Z&&bW(!1),aV.reset(),aS(a)},[Z,aV,bW]),cM=(0,e.useCallback)(()=>{aV.reset(),aS(null),bv()},[aV,bv]),cN=ae.refresh,cO=(0,e.useCallback)(()=>{null!==aR&&aV.check(cN,aR)},[cN,aV,aR]),cP=(0,e.useCallback)(()=>a0?(a2||(a1(!1),bv()),!0):null!==aR?(cM(),!0):aP?(aQ(!1),bv(),!0):cE?(cF(!1),bv(),!0):cA?(cB(null),bv(),!0):a6.transientLayer?("navigator-drawer"===a6.transientLayer&&bW(!1),a7({type:"close-layer"}),bv(),!0):"chat"!==a6.activeView&&(a7({type:"select-view",view:"chat"}),bv(),!0),[cM,cE,aR,cA,a2,a0,bv,bW,aP,a6.activeView,a6.transientLayer]),cQ=(0,e.useCallback)(a=>{a7({type:"close-layer"}),Z&&bW(!1),cB(b=>b===a?null:a)},[Z,bW]),cR=(0,e.useCallback)(()=>{a7({type:"close-layer"}),Z&&bW(!1),cB("session")},[Z,bW]),cS=(0,e.useCallback)(()=>{if(cB(null),Z){let a="navigator-drawer"!==a6.transientLayer;bW(a),a||bv();return}a7({type:"close-layer"}),bM(a=>{let b=!a;return bU.current=b,b})},[Z,bv,bW,a6.transientLayer]),[cT,cU]=(0,e.useState)([]),[cV,cW]=(0,e.useState)(null),cX=(0,e.useCallback)(()=>{("view-stack"===bc.deck||M)&&a7({type:"select-view",view:"chat"}),Z&&bW(!1),bv()},[Z,M,bc.deck,bv,bW]),cY=(0,e.useCallback)((a,b)=>{let c;b_.current?.insertText((c=b?`${a}/`:a).includes(" ")?`@"${c}" `:`@${c} `),cX()},[cX]),cZ=(0,e.useCallback)((a,b,c)=>{let d,e,f,g;b_.current?.insertText((d=Math.max(1,Math.min(b,c)),e=Math.max(1,Math.max(b,c)),f=a.includes(" ")?`@"${a}"`:`@${a}`,g=d===e?`:${d}`:`:${d}-${e}`,`${f}${g} `)),cX()},[cX]),c$=Q.sessionId,[c_,c0]=(0,e.useState)(null);bq({cwd:am?.cwd??aB??c_,syncWithOmp:!0});let c1=(0,e.useRef)(null),[c2,c3]=(0,e.useState)(()=>!c$),c4=(0,e.useRef)(!1),c5=(0,e.useRef)(0),c6=(0,e.useCallback)(()=>{c5.current+=1},[]),c7=(0,e.useCallback)(a=>{let b=++c5.current,c=function(a,b=null){if(!b)return null;try{let c=kH(b)[a];return"string"==typeof c&&c.length>0?c:null}catch{return null}}(a);c&&fetch("/api/sessions").then(a=>a.ok?a.json():null).then(d=>{if(b!==c5.current)return;let e=d?.sessions.find(a=>a.id===c);if(!e){d&&kI(a);return}(e.projectRoot??e.cwd)!==a?kI(a):(an(e),aK(a=>a+1),new URLSearchParams(window.location.search).get("session")!==e.id&&O.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1}))}).catch(()=>{})},[O]),c8=(0,e.useCallback)((a,b)=>{if(c6(),c0(a),!a)return;let c=b??a,d=c1.current??(am?am.projectRoot??am.cwd:null);if(c1.current=c,c4.current){c4.current=!1;return}d!==c&&(as.current+=1,at.current?.abort(),at.current=null,ap(null),ar(null),an(null),aC(b=>b&&b!==a?null:b),aK(a=>a+1),b2({sessionId:null,tree:[],leafId:null,navigation:0}),b8(null),cB(null),cU([]),cW(null),a7({type:"select-view",view:"chat"}),c7(c),O.replace(N,{scroll:!1}))},[N,O,am,c6,c7]),c9=(0,e.useCallback)((a,b,c)=>{aC(null),ar(c),an(a),b2({sessionId:a.id,tree:[],leafId:null,navigation:0}),aK(a=>a+1),b8(null),c3(!0),Z&&!b&&(bW(!1),a7({type:"select-view",view:"chat"})),b&&(c4.current=!0),b||O.replace(`?session=${encodeURIComponent(a.id)}`,{scroll:!1})},[Z,O,bW]),da=(0,e.useCallback)((a,b=!1)=>{if(c1.current=a.projectRoot??a.cwd,c6(),!b&&am){let b=(am.projectRoot??am.cwd)===(a.projectRoot??a.cwd);if(am.id===a.id&&b){as.current+=1,at.current?.abort(),at.current=null,ap(null),Z&&bW(!1);return}}if(!b&&ao?.id===a.id)return;as.current+=1;let c=as.current;if(at.current?.abort(),b||!am){at.current=null,ap(null),c9(a,b,null);return}let d=new AbortController;at.current=d,ap(a);let e=new URLSearchParams({deferThinking:"1",deferMedia:"1"});fetch(`/api/sessions/${encodeURIComponent(a.id)}?${e}`,{cache:"no-store",signal:d.signal}).then(async b=>{if(!b.ok)throw Error(`HTTP ${b.status}`);let d=await b.json();if(d.sessionId!==a.id)throw Error("Session preload returned the wrong session");as.current===c&&c9(a,!1,d)}).catch(b=>{d.signal.aborted||as.current!==c||(console.error("Failed to preload session before switching:",b),c9(a,!1,null))}).finally(()=>{as.current===c&&(at.current=null,ap(null))})},[c9,c6,Z,ao?.id,am,bW]),db=(0,e.useCallback)((a,b)=>{as.current+=1,at.current?.abort(),at.current=null,ap(null),ar(null),c6(),an(null),aC(b),aK(a=>a+1),b2({sessionId:null,tree:[],leafId:null,navigation:0}),b8(null),cB(null),a7({type:"select-view",view:"chat"}),Z&&bW(!1),O.replace(N,{scroll:!1})},[N,c6,Z,O,bW]),dc=(0,e.useCallback)(a=>{let b=am?.projectRoot??c1.current??am?.cwd??c_;if(!b||!am)return;let c=bg.filter(a=>(a.projectRoot??a.cwd)===b),d=c.findIndex(a=>a.id===am.id);if(d<0)return;let e=c[d+a];e&&(cB(null),a7({type:"close-layer"}),da(e),bv())},[c_,bg,da,bv,am]);p={onNewSession:a=>db(`kb-${Date.now()}`,a),onToggleCommandPalette:()=>cJ("command-palette"),onToggleNavigator:cS,onToggleResources:()=>cI("resource"===a6.activeView?"chat":"resource",!0),onSelectView:a=>cI(a,!0),onCycleView:(0,e.useCallback)(a=>{let b=(l.indexOf(a6.activeView)+a+l.length)%l.length;cI(l[b],!0)},[cI,a6.activeView]),onNavigateSession:dc,onEscape:cP,enabled:!aP&&!a0&&null===aR,activeCwd:c_},(0,e.useRef)(p).current=p;let dd=(0,e.useCallback)(a=>{fetch("/api/sessions",{cache:"no-store"}).then(a=>a.ok?a.json():null).then(b=>{let c=b?.sessions.find(b=>b.id===a);c&&an(b=>b?.id===a?{...b,...c,transient:c.transient??!1}:b)}).catch(()=>{})},[]),de=(0,e.useCallback)(a=>{c6(),aC(null),an(a),aI(a=>a+1),dd(a.id),O.replace(`?session=${encodeURIComponent(a.id)}`,{scroll:!1})},[c6,O,dd]),df=(0,e.useCallback)(({targetSession:a,title:b,body:c,tag:d})=>{"Notification"in window&&"granted"===Notification.permission&&fH({title:b,body:c,sessionUrl:a?`/?session=${encodeURIComponent(a.id)}`:"/",tag:d,onClick:()=>{window.focus(),a&&da(a)}})},[da]),dg=(0,e.useCallback)(a=>{aI(a=>a+1),a_.current?.pending&&a$(a=>a+1),aM(a=>a+1),am&&dd(am.id),"completed"===a.outcome&&fF()&&df({targetSession:am,title:am?.name??W("i18n.sessionComplete"),body:W("i18n.taskFinished")})},[df,dd,am,W]),dh=(0,e.useCallback)(a=>{var b;fF()&&(b=ak.current,!(!fG(a)||b.has(a.id))&&(b.add(a.id),1)&&df({targetSession:am,title:W("i18n.attentionNeeded"),body:"custom"===a.method?W("i18n.extensionInputNeeded"):a.title,tag:`pi-extension-ui:${a.id}`}))},[df,am,W]),di=(0,e.useCallback)(async()=>{let a=am?.id;if(a&&"naming"!==cm.kind){co.current&&clearTimeout(co.current),cB(null),cn({kind:"naming"});try{let b=await fetch(`/api/sessions/${encodeURIComponent(a)}/auto-name`,{method:"POST"}),c=await b.json().catch(()=>({}));if(!b.ok||!c.title)throw Error(c.error||`HTTP ${b.status}`);let d=c.title.trim();if(aI(a=>a+1),cp.current!==a)return;an(b=>b?.id===a?{...b,name:d}:b),cb(b=>b?.sessionId===a?{...b,sessionName:d}:b),cn({kind:"success"}),co.current=setTimeout(()=>cn({kind:"idle"}),1800)}catch(b){if(cp.current!==a)return;cn({kind:"error",message:b instanceof Error?b.message:String(b)}),co.current=setTimeout(()=>cn({kind:"idle"}),5e3)}}},[cm.kind,am?.id]),dj=(0,e.useCallback)(a=>{c6(),aI(a=>a+1),aK(a=>a+1),aC(null),an(b=>({...b??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:a,transient:!1})),dd(a),O.replace(`?session=${encodeURIComponent(a)}`,{scroll:!1})},[c6,O,dd]),dk=(0,e.useCallback)(()=>{c3(!0)},[]),dl=(0,e.useCallback)(a=>{if(c6(),aI(a=>a+1),am?.id===a){let a=am.cwd;an(null),aC(a??null),aK(a=>a+1),b2({sessionId:null,tree:[],leafId:null,navigation:0}),b8(null),cB(null),a7({type:"select-view",view:"chat"}),bv(),O.replace(N,{scroll:!1})}},[N,c6,bv,am,O]),dm=(0,e.useCallback)((a,b,c)=>{let d=c?.sourceSessionId,e=c?.modeHint,f=`file:${a}`;cU(c=>{let g=c.find(a=>a.id===f);if(!g)return[...c,{id:f,label:b,filePath:a,sourceSessionId:d,initialDisplayMode:e}];let h=!d||g.sourceSessionId===d,i=!e||g.initialDisplayMode===e;return h&&i?c:c.map(a=>{if(a.id!==f)return a;let b={...a};return d&&(b.sourceSessionId=d),e&&(b.initialDisplayMode=e),b})}),cW(f),a7({type:"select-view",view:"files"}),cB(null),Z&&bW(!1)},[Z,bW]),dn=(0,e.useCallback)(a=>{dm(a,aY(a),{sourceSessionId:am?.id??null})},[dm,am?.id]),dp=(0,e.useCallback)(a=>{let b=cT.filter(b=>b.id!==a);cU(b),cW(c=>c!==a?c:b.length>0?b[b.length-1].id:null),0===b.length&&"files"===a6.activeView&&cI("chat",!0)},[cT,cI,a6.activeView]),dq=(0,e.useCallback)(()=>{am&&window.open(`/api/sessions/${encodeURIComponent(am.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[am]),dr=aB??(null===am&&c_?c_:null),ds=null!==am||null!==dr,dt="chat"!==a6.activeView,du=am?.cwd??dr,dv=c2&&!ds,dw=(0,e.useCallback)((a,b)=>{a_.current=a,aX(a),a5(a.error?W("trust.applyFailed",{error:a.error}):null),null!==b&&null===a.pending&&(b.trusted!==a.trusted||"revoke"===b.pending)&&(a.trusted&&a1(!1),aO(a=>a+1),aK(a=>a+1))},[W]),dx=(0,e.useCallback)(async a=>{if(du&&!a2){a3(!0),a5(null);try{let b=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:du,action:a})}),c=await b.json();if(!b.ok)throw Error(c.error??`HTTP ${b.status}`);let d=a_.current;dw(c,d),(c.trusted||"cancel"===a)&&(a1(!1),bv())}catch(a){a5(a instanceof Error?a.message:String(a))}finally{a3(!1)}}},[dw,a2,du,bv]),dy=cT.find(a=>a.id===cV)??null,dz=c_?aY(c_)||c_:null,dA=(am?.name?.trim()||am?.firstMessage?.trim()||(dr?W("i18n.newSession"):dz)||"CUELO").replace(/\s+/g," ").trim(),dB=dA.length>96?`${dA.slice(0,93)}…`:dA;M&&ch("office.toOffice");let dD=dz?`${dA} — ${dz}`:dA,dE=am?.transient?`${dD} \xb7 ${W("session.inMemory")}`:dD,dG=cc.filter(a=>"pending"===a.status||"running"===a.status).length,dH=ck?W("workspace.mainAttention"):bm?W("workspace.mainWaiting"):bk?W("workspace.mainWorking"):W("workspace.mainIdle"),dK=`${ck?"⚠":bm?"○":bk?"●":"○"} Main ${dH} \xb7 Sub ${dG}${ci?`/${ci}`:""}`,dL=(0,e.useCallback)(a=>cI(a,!0),[cI]),dM=M?(0,kB.GM)({main:{provider:ce?.provider??null,modelId:ce?.modelId??null,face:ce?.face??null,state:ck?"attention":bm?"waiting":bk?"working":"idle"},subagents:cc,accounts:cg.accounts,resolveFace:(a,b)=>bO(void 0,a,b)}):null,dN=dM?(0,kB.nk)(dM,cg.selected):cg.selected,dO=dM?.participants.find(a=>"main"===a.kind),dP=dM?.participants.find(a=>"maker"===a.kind&&a.key===dN),dQ=M?af?"target":cg.pane:null,dR="floor"===dQ,dS=dt&&(M||"view-stack"===bc.deck),dT=am?`?session=${encodeURIComponent(am.id)}`:dr?`?cwd=${encodeURIComponent(dr)}`:"",dU="ko"===T?{chat:"대화",process:"작업 과정",efficiency:"효율",subagents:"서브에이전트",files:"파일",resource:"캐릭터",sidechat:"사이드챗"}:{chat:"Chat",process:"Process",efficiency:"Efficiency",subagents:"Subagents",files:"Files",resource:"캐릭터",sidechat:"Side Chat"},dV="chat"!==a6.activeView,dW=dV?dU[a6.activeView]:dU[cG],dX=(t=cv&&Number.isFinite(cv.contextWindow)&&cv.contextWindow>0?cv.contextWindow:null,u=cv&&"number"==typeof cv.tokens&&Number.isFinite(cv.tokens)?Math.max(0,cv.tokens):null,w=null===(v=cv&&"number"==typeof cv.percent&&Number.isFinite(cv.percent)?cv.percent:null!==u&&null!==t?u/t*100:null)?"normal":v>90?"critical":v>70?"warning":"normal",y=null===u?"?":j2(u),z=null===t?"?":j2(t),A=null===v?"?":`${v.toFixed(0)}%`,{level:w,percent:v,fillPercent:null===v?0:Math.min(100,Math.max(0,v)),readout:null===t?null:`${A} \xb7 ${y}/${z}`,usedLabel:y,limitLabel:z,percentLabel:A}),dZ=dX.readout,d$=dZ?W("chat.contextUsageTitle",{used:dX.usedLabel,limit:dX.limitLabel,percent:dX.percentLabel}):null,d_="critical"===dX.level?W("chat.contextUsageCritical"):"warning"===dX.level?W("chat.contextUsageWarning"):null,d0=(q=ca?.userMessages,!am||am.transient?"unsaved":("number"==typeof q?q:0)>0||am.messageCount>0?null:"no-messages"),d1="unsaved"===d0?W("title.unsaved"):"no-messages"===d0?W("title.noMessages"):null,d2=d1??("error"===cm.kind?cm.message:null),d3="naming"===cm.kind?W("title.generating"):"success"===cm.kind?W("title.updated"):"error"===cm.kind?W("title.failed"):W("title.generate"),d4=(0,d.jsxs)("div",{id:"workspace-file-view",className:"workspace-file-view",children:[(0,d.jsx)("div",{className:"workspace-file-tabs",children:(0,d.jsx)(gD,{tabs:cT,activeTabId:cV??"",onSelectTab:cW,onCloseTab:dp})}),(0,d.jsx)("div",{className:"workspace-file-content",children:dy?.filePath?(0,d.jsx)(gB,{filePath:dy.filePath,cwd:c_??void 0,sourceSessionId:dy.sourceSessionId,gitRefreshKey:aL,initialDisplayMode:dy.initialDisplayMode,onMentionLines:cZ,onAtMention:cY,onOpenFile:a=>dm(a,aY(a),{sourceSessionId:dy.sourceSessionId})}):(0,d.jsx)("div",{className:"workspace-file-empty",children:W("files.noneOpen")})})]}),d5=(0,d.jsx)(jm,{open:"resource"===a6.activeView,sessionId:am?.id??null,activeTab:a8,onTabChange:a9,usage:ae}),d6=(0,d.jsx)(jZ,{open:"efficiency"===a6.activeView,sessionId:am?.id??null,activeTab:ba,onTabChange:bb}),d7=(0,d.jsx)(iH,{title:dU.process,data:cy,onOpenFile:dn}),d8=am?am.path?am.path:ca?.sessionId===am.id&&ca.sessionFile?ca.sessionFile:null:null,d9=(0,d.jsx)(iZ,{title:dU.sidechat,sessionId:am?.id??null,sessionPath:d8,sessionName:am?.name,historyStore:be,flights:bf,sessionCensus:bi,visible:"sidechat"===a6.activeView}),ea=dt?(0,d.jsx)(iG,{activeView:a6.activeView,onViewChange:a=>cI(a),viewLabels:dU,sessionId:am?.id??null,sessionPath:d8,sessionName:am?.name,sessionCwd:am?.cwd??dr??void 0,liveSubagents:cc,processSlot:d7,fileSlot:d4,sideChatSlot:d9,resourceSlot:b??d5,efficiencySlot:d6,visible:!0,onClose:()=>a7({type:"select-view",view:"chat"}),onReturnFocus:bv}):null,eb=a??ea,ec=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(V,{selectedSessionId:ao?.id??am?.id??null,optimisticSession:ao??am,onSelectSession:da,onNewSession:db,initialSessionId:c$,skipInitialProjectSelection:null!==Q.requestedCwd,onInitialRestoreDone:dk,refreshKey:aH,onSessionDeleted:dl,selectedCwd:am?.cwd??aB??null,onCwdChange:c8,onBackgroundTaskDone:al,loungePanel:(0,d.jsx)(kl,{lounge:aj,usage:ae,loungeOpen:af,onOpenLounge:Z?()=>bW(!1):void 0}),loungeActive:af,onLoungeActiveChange:bw}),(0,d.jsxs)("div",{className:"navigator-footer",style:{padding:"8px",flexShrink:0},children:[af?null:(0,d.jsx)(kb,{usage:ae,onOpen:()=>{a9("usage"),cI("resource",!1)},onRelogin:cL}),(0,d.jsx)(kF,{}),(0,d.jsxs)("button",{className:"navigator-settings-action",onClick:()=>{cB(null),a7({type:"close-layer"}),Z&&bW(!1),aQ(!0)},title:W("common.settings"),style:{width:"100%",height:34,display:"flex",alignItems:"center",justifyContent:"center",gap:8,background:"none",border:"1px solid var(--border)",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontFamily:"var(--font-mono)",transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:a=>{a.currentTarget.style.background="var(--bg-hover)",a.currentTarget.style.color="var(--text)",a.currentTarget.style.borderColor="var(--text-dim)"},onMouseLeave:a=>{a.currentTarget.style.background="none",a.currentTarget.style.color="var(--text-muted)",a.currentTarget.style.borderColor="var(--border)"},children:[(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,d.jsx)("path",{d:"M19.4 15a1.7 1.7 0 0 0 .34 1.88l.06.06-2.83 2.83-.06-.06A1.7 1.7 0 0 0 15 19.4a1.7 1.7 0 0 0-1 .6 1.7 1.7 0 0 0-.4 1.1V21h-4v-.09A1.7 1.7 0 0 0 8.5 19.4a1.7 1.7 0 0 0-1.88.34l-.06.06-2.83-2.83.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-.6-1 1.7 1.7 0 0 0-1.1-.4H3v-4h.09A1.7 1.7 0 0 0 4.6 8.5a1.7 1.7 0 0 0-.34-1.88l-.06-.06 2.83-2.83.06.06A1.7 1.7 0 0 0 9 4.6a1.7 1.7 0 0 0 1-.6 1.7 1.7 0 0 0 .4-1.1V3h4v.09A1.7 1.7 0 0 0 15.5 4.6a1.7 1.7 0 0 0 1.88-.34l.06-.06 2.83 2.83-.06.06A1.7 1.7 0 0 0 19.4 9c.12.39.33.74.6 1 .3.28.69.42 1.1.4h.09v4h-.09A1.7 1.7 0 0 0 19.4 15Z"})]}),W("common.settings")]})]})]}),ed=bE&&bG&&bG.requestId===bE.requestId&&bG.deploymentCompleted?bG:null,ee=ed?.cleanup??null,ef=ed&&!bE?.dismissed?function(a){if(!a)return{tone:"neutral",title:"업데이트 완료",detail:"임시 산출물 정리 상태를 확인하고 있습니다.",dismissible:!0,autoHideMs:null};let b=`${a.completedCount}/${a.totalCount} 완료`,c=`${Math.round(a.elapsedSeconds)}초 경과`;return"running"===a.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 중",detail:`${b} \xb7 ${c} \xb7 현재 ${a.currentTarget??"대상 선택 중"}`,dismissible:!1,autoHideMs:null}:"failed"===a.status?{tone:"warning",title:"업데이트 완료 \xb7 산출물 정리 실패",detail:`${b} \xb7 ${c} \xb7 보존 ${a.keptCount}건 \xb7 실패 ${a.failureCount}건. 업데이트 자체는 성공했고 실패 증거는 보존했습니다.`,dismissible:!0,autoHideMs:fM(a.status)}:"pending-approval"===a.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 승인 대기",detail:`${b} \xb7 ${c} \xb7 보존 ${a.keptCount}건. 삭제는 승인 후 실행합니다.`,dismissible:!0,autoHideMs:fM(a.status)}:"skipped"===a.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 건너뜀",detail:`${b} \xb7 ${c}`,dismissible:!0,autoHideMs:fM(a.status)}:{tone:"positive",title:"업데이트 완료 \xb7 산출물 정리 완료",detail:`${b} \xb7 ${c}`,dismissible:!0,autoHideMs:fM(a.status)}}(ee):null;return(0,d.jsxs)(d.Fragment,{children:[by?(0,d.jsx)("div",{className:"server-restart-overlay",role:"status","aria-live":"polite",children:(0,d.jsxs)("div",{className:"server-restart-card",children:[(0,d.jsx)("div",{className:"server-restart-spinner","aria-hidden":"true"}),(0,d.jsx)("strong",{children:W("restart.title")}),(0,d.jsx)("span",{children:W(bA?"restart.slow":"restart.body")})]})}):null,(0,d.jsxs)("div",{ref:bs,className:"workspace-shell","data-active-view":a6.activeView,"data-deck-mode":bc.deck,"data-deck-visible":dt,"data-chat-wide":ay?"true":void 0,children:[(0,d.jsx)("div",{"aria-hidden":"true",className:`sidebar-overlay-backdrop${bV.drawer?" is-open":""}${bN?"":" sidebar-mobile-pending"}${bQ?" sidebar-mode-shift":""}`,onClick:()=>{bW(!1),bv()}}),(0,d.jsx)("div",{ref:b$.panelRef,id:"session-sidebar",className:`sidebar-container${bV.laidOut?" sidebar-open":" sidebar-closed"}${bN?"":" sidebar-mobile-pending"}${bQ?" sidebar-mode-shift":""}${b$.isResizing?" sidebar-resizing":""}`,"aria-hidden":Z&&!bV.presented,inert:Z&&!bV.presented,style:{"--sidebar-width":`${b$.width}px`},children:ec}),bV.laidOut&&(0,d.jsx)("div",{...b$.separatorProps,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${b$.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${W("layout.resizeSidebar")}: ${W("layout.resizeHint")}`}),(0,d.jsxs)("div",{className:"workspace-session-region","data-active-view":a6.activeView,"aria-hidden":bV.drawer,inert:bV.drawer,children:[(0,d.jsxs)("div",{ref:b0,className:"workspace-header-stack",children:[ef&&bE&&(0,d.jsxs)("div",{className:"workspace-update-banner","data-tone":ef.tone,role:"status","aria-live":"polite",children:[(0,d.jsx)("span",{className:"workspace-update-banner-title",children:ef.title}),(0,d.jsx)("span",{className:"workspace-update-banner-detail",children:ef.detail}),ef.dismissible&&(0,d.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>bF(function(a){let b=function(){let a=sessionStorage.getItem(fL);if(!a)return null;try{let b=JSON.parse(a);if(1!==b.schemaVersion||"string"!=typeof b.requestId||!/^[0-9a-f]{32}$/.test(b.requestId)||"string"!=typeof b.stageHash||!/^[0-9a-f]{64}$/.test(b.stageHash)||"boolean"!=typeof b.dismissed)return null;return b}catch{return null}}();if(!b||b.requestId!==a)return b;let c={...b,dismissed:!0};try{sessionStorage.setItem(fL,JSON.stringify(c))}catch{}return c}(bE.requestId)),"aria-label":"업데이트 상태 알림 닫기",children:"닫기"})]}),bC&&!(ef&&bE)&&(0,d.jsxs)("div",{className:"workspace-update-banner","data-tone":"positive",role:"status","aria-live":"polite",children:[(0,d.jsx)("span",{className:"workspace-update-banner-title",children:W("restart.returnedTitle")}),(0,d.jsx)("span",{className:"workspace-update-banner-detail",children:W("restart.returnedBody")}),(0,d.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>bD(!1),"aria-label":W("restart.returnedDismiss"),children:W("i18n.close")})]}),(0,d.jsx)(is,{variant:"banner",locale:T,...Y}),(0,d.jsxs)("header",{className:"workspace-header-seam",children:[(0,d.jsx)(h.r,{ref:bX,className:"workspace-header-nav-toggle",variant:"ghost",size:"small",layout:"iconOnly",type:"button",onClick:cS,"aria-controls":"session-sidebar","aria-expanded":bV.presented,title:bV.presented?W("sidebar.hide"):W("sidebar.show"),"aria-label":bV.presented?W("sidebar.hide"):W("sidebar.show"),children:bV.presented?(0,d.jsx)(i.In,{size:"16px",svg:(0,d.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,d.jsx)("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}):(0,d.jsx)(i.In,{size:"18px",svg:(0,d.jsxs)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),(0,d.jsx)("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),(0,d.jsx)("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})})}),(0,d.jsxs)("div",{className:"workspace-session-identity",title:dE,children:[(0,d.jsx)("strong",{children:dB}),(0,d.jsx)("span",{"aria-live":"polite",children:dK})]}),(0,d.jsx)("span",{className:"sr-only",role:"status",children:"error"===cm.kind?cm.message:""}),ds&&aW?.requiresTrust&&!aW.trusted&&(0,d.jsxs)(h.r,{className:"workspace-header-action",variant:"ghost",size:"small",color:"fg.warning",type:"button",onClick:()=>{a5(aW.error?W("trust.applyFailed",{error:aW.error}):null),cB(null),a7({type:"close-layer"}),a1(!0),aW.pending&&a$(a=>a+1)},title:W("grant"===aW.pending?"trust.pendingBadge":"trust.resourcesNotLoaded"),"aria-label":W("grant"===aW.pending?"trust.pendingBadge":"trust.resourcesNotLoaded"),children:[(0,d.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,d.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,d.jsx)("path",{d:"M12 8v4"}),(0,d.jsx)("path",{d:"M12 16h.01"})]}),!Z&&(0,d.jsx)("span",{children:W("trust.resourcesNotLoaded")})]}),ds&&dZ&&(0,d.jsxs)(h.r,{className:"workspace-context-usage",variant:"ghost",size:"small",type:"button",onClick:cR,"aria-expanded":"session"===cA,title:d$??W("session.title"),"aria-label":d_?`${d$}. ${d_}`:d$??void 0,children:[(0,d.jsx)("span",{className:"workspace-context-meter","aria-hidden":"true",children:(0,d.jsx)("span",{className:"workspace-context-meter-fill","data-level":dX.level,style:{inlineSize:`${dX.fillPercent}%`}})}),(0,d.jsx)("span",{className:"workspace-context-readout","data-level":dX.level,children:dZ})]}),M?(0,d.jsx)(h.r,{asChild:!0,className:"workspace-header-action",variant:"ghost",size:"small",children:(0,d.jsx)("a",{href:`/${dT}`,"data-office-link":"chat",title:ch("office.toChatTitle"),children:ch("office.toChat")})}):(0,d.jsx)(h.r,{asChild:!0,className:"workspace-header-action",variant:"ghost",size:"small",children:(0,d.jsxs)("a",{href:`/office${dT}`,target:"_blank",rel:"noopener","data-office-link":"office",title:ch("office.toOfficeTitle"),"aria-label":`${ch("office.toOffice")} (${ch("office.newTab")})`,children:[ch("office.toOffice"),(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M14 4h6v6"}),(0,d.jsx)("path",{d:"M20 4 11 13"}),(0,d.jsx)("path",{d:"M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"})]})]})}),ds&&!M&&(0,d.jsx)(j.f,{className:"workspace-panel-toggle",variant:"neutralWeak",size:"small",pressed:dV,onPressedChange:cK,"aria-controls":"workspace-auxiliary-panel",title:"ko"===T?"보조 패널":"Auxiliary panel",children:dW}),(0,d.jsxs)(k.k.Root,{open:cE,onOpenChange:a=>cF(a),placement:"bottom-end",strategy:"fixed",children:[(0,d.jsx)(k.k.Trigger,{asChild:!0,children:(0,d.jsx)(h.r,{className:"workspace-header-more",variant:"ghost",size:"small",layout:"iconOnly",type:"button",title:"ko"===T?"더 보기":"More","aria-label":"ko"===T?"더 보기":"More",children:(0,d.jsx)(i.In,{size:"16px",svg:(0,d.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"12",cy:"5",r:"1"}),(0,d.jsx)("circle",{cx:"12",cy:"12",r:"1"}),(0,d.jsx)("circle",{cx:"12",cy:"19",r:"1"})]})})})}),(0,d.jsx)(k.k.Positioner,{children:(0,d.jsx)(k.k.Content,{"aria-label":"ko"===T?"세션 및 환경 메뉴":"Session and environment menu",children:(0,d.jsxs)(k.k.ScrollArea,{children:[(0,d.jsxs)(k.k.Group,{children:[(0,d.jsx)(k.k.GroupLabel,{children:"ko"===T?"세션":"Session"}),(0,d.jsx)(k.k.Item,{onClick:cR,children:(0,d.jsx)(k.k.ItemBody,{children:(0,d.jsx)(k.k.ItemLabel,{children:W("session.title")})})}),(0,d.jsx)(k.k.Item,{onClick:dq,disabled:!am,children:(0,d.jsxs)(k.k.ItemBody,{children:[(0,d.jsx)(k.k.ItemLabel,{children:W("history.label")}),!am&&(0,d.jsx)(k.k.ItemDescription,{children:W("history.unsaved")})]})}),(0,d.jsx)(k.k.Item,{onClick:()=>void di(),disabled:null!==d1||"naming"===cm.kind,children:(0,d.jsxs)(k.k.ItemBody,{children:[(0,d.jsx)(k.k.ItemLabel,{children:d3}),d2&&(0,d.jsx)(k.k.ItemDescription,{children:d2})]})}),(0,d.jsx)(k.k.Item,{onClick:()=>cQ("branches"),children:(0,d.jsx)(k.k.ItemBody,{children:(0,d.jsx)(k.k.ItemLabel,{children:W("i18n.branches")})})}),(0,d.jsx)(k.k.Item,{onClick:()=>cQ("system"),children:(0,d.jsx)(k.k.ItemBody,{children:(0,d.jsx)(k.k.ItemLabel,{children:W("system.label")})})})]}),(0,d.jsxs)(k.k.Group,{children:[(0,d.jsx)(k.k.GroupLabel,{children:"ko"===T?"환경":"Environment"}),(0,d.jsx)(is,{variant:"menu",locale:T,...Y}),(0,d.jsx)(k.k.Item,{onClick:a=>{let b=a.currentTarget.getBoundingClientRect();S({x:b.left+b.width/2,y:b.top+b.height/2})},children:(0,d.jsx)(k.k.ItemBody,{children:(0,d.jsx)(k.k.ItemLabel,{children:W("light"===R?"theme.light":"dark"===R?"theme.dark":"theme.auto")})})}),X.map(a=>(0,d.jsx)(k.k.Item,{role:"menuitemradio","aria-checked":T===a.id,onClick:()=>U(a.id),children:(0,d.jsx)(k.k.ItemBody,{children:(0,d.jsx)(k.k.ItemLabel,{children:a.label})})},a.id)),(0,d.jsx)(k.k.Item,{onClick:()=>{cB(null),a7({type:"close-layer"}),Z&&bW(!1),aQ(!0)},children:(0,d.jsx)(k.k.ItemBody,{children:(0,d.jsx)(k.k.ItemLabel,{children:W("common.settings")})})})]})]})})})]})]}),cA&&cC&&(0,d.jsxs)("div",{style:{position:"fixed",top:cC.top,left:cC.left,width:cC.width,maxHeight:`calc(100dvh - ${cC.top}px - var(--omp-dock-h, 204px) - 8px)`,overflowY:"auto",zIndex:500},children:["branches"===cA&&(0,d.jsx)("div",{className:"workspace-top-panel","aria-label":W("i18n.branches"),children:(0,d.jsx)(j1,{tree:b1.sessionId===(am?.id??null)?b1.tree:[],activeLeafId:b1.sessionId===(am?.id??null)?b1.leafId:null,onLeafChange:b6,hasSession:!!am})}),"system"===cA&&(0,d.jsx)("div",{style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:b7?(0,d.jsx)("div",{style:{maxHeight:"min(600px, 75vh)",overflowY:"auto",padding:"12px 16px",color:"var(--text-muted)",fontSize:12,lineHeight:1.6,whiteSpace:"pre-wrap",fontFamily:"var(--font-mono)"},children:b7}):""===b7?(0,d.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:W("system.empty")}):(0,d.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:W("system.load")})}),"session"===cA&&(0,d.jsx)("div",{className:"session-info-popover",style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",padding:"12px 16px"},children:ca?(D=ca.totalActiveMs??0,E=[...ca.sessionName?[{label:W("session.name"),value:ca.sessionName,copyField:null}]:[],{label:W("session.file"),value:ca.sessionFile??W("session.inMemory"),copyField:"file"},{label:W("session.id"),value:ca.sessionId,copyField:"id"},...D>0?[{label:W("session.totalActive"),value:(a=>{if(a<=0)return"0s";let b=Math.floor(a/1e3),c=Math.floor(b/3600),d=Math.floor(b%3600/60),e=b%60;return c>0?`${c}h ${d}m`:d>0?`${d}m ${e}s`:`${e}s`})(D),copyField:null}]:[]],F=[[W("session.user"),ca.userMessages.toLocaleString(T)],[W("session.assistant"),ca.assistantMessages.toLocaleString(T)],[W("session.toolCalls"),ca.toolCalls.toLocaleString(T)],[W("session.toolResults"),ca.toolResults.toLocaleString(T)],[W("session.total"),ca.totalMessages.toLocaleString(T)]],G=[[W("session.input"),ca.tokens.input.toLocaleString(T)],[W("session.output"),ca.tokens.output.toLocaleString(T)],...ca.tokens.cacheRead>0?[[W("session.cacheRead"),ca.tokens.cacheRead.toLocaleString(T)]]:[],...ca.tokens.cacheWrite>0?[[W("session.cacheWrite"),ca.tokens.cacheWrite.toLocaleString(T)]]:[],[W("session.total"),ca.tokens.total.toLocaleString(T)]],H=cv??ca.contextUsage,I=a=>a>=1e6?`${(a/1e6).toFixed(1)}M`:a>=1e3?`${(a/1e3).toFixed(0)}k`:String(a),J=[...ca.cost>0?[[W("session.cost"),`$${ca.cost.toFixed(4)}`]]:[],...H?.contextWindow?[[W("session.context"),`${null!==H.tokens?I(H.tokens):"?"} / ${I(H.contextWindow)}${null!==H.percent?` \xb7 ${H.percent.toFixed(1)}%`:""}`]]:[],...ca.tokens.cacheRead+ca.tokens.cacheWrite>0&&ca.tokens.cacheRead+ca.tokens.cacheWrite+ca.tokens.input>0?[[W("session.cacheHitRate"),`${(ca.tokens.cacheRead/(ca.tokens.cacheRead+ca.tokens.cacheWrite+ca.tokens.input)*100).toFixed(1)}%`]]:[]],K=(a,b,c="left",e=!1)=>(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:a}),(0,d.jsx)("div",{style:{display:"grid",gridTemplateColumns:e?"max-content max-content":"auto minmax(0, 1fr)",columnGap:e?14:12,rowGap:4,justifyContent:e?"start":void 0},children:b.map(([b,f])=>(0,d.jsxs)("div",{style:{display:"contents"},children:[(0,d.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:b}),(0,d.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:e?"normal":"anywhere",textAlign:c,whiteSpace:"right"===c?"nowrap":"normal"},children:f})]},`${a}:${b}`))})]}),L=(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:W("session.infoSection")}),(0,d.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:E.map(a=>{var b,c;let e;return(0,d.jsxs)("div",{style:{display:"contents"},children:[(0,d.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:a.label}),(0,d.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:a.value}),(0,d.jsx)("div",{children:a.copyField?(b=a.copyField,c=a.value,e=cr===b,(0,d.jsx)("button",{type:"button",title:e?W("session.copied"):W("file"===b?"session.copyFile":"session.copyId"),onClick:()=>cu(b,c),style:{alignSelf:"start",display:"inline-flex",alignItems:"center",justifyContent:"center",width:22,height:22,marginTop:-2,color:e?"var(--accent)":"var(--text-dim)",background:"transparent",border:"1px solid var(--border)",borderRadius:4,cursor:"pointer",flex:"0 0 auto",transition:"color 0.12s, border-color 0.12s, background 0.12s"},onMouseEnter:a=>{a.currentTarget.style.color="var(--accent)",a.currentTarget.style.borderColor="var(--accent)",a.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:a=>{a.currentTarget.style.color=e?"var(--accent)":"var(--text-dim)",a.currentTarget.style.borderColor="var(--border)",a.currentTarget.style.background="transparent"},children:e?(0,d.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,d.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})):null})]},`session-info:${a.label}`)})})]}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:Z?"1fr":"minmax(360px, 1.7fr) minmax(140px, 0.55fr) minmax(190px, 0.75fr)",gap:Z?16:24,fontSize:12,lineHeight:1.5,fontFamily:"var(--font-mono)"},children:[L,K(W("session.messages"),F),K(W("session.tokens"),[...G,...J],"right",!0)]})):(0,d.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:W("session.load")})})]})]}),(0,d.jsxs)("div",{className:`chat-content-layout${M?` ${kx().page}`:""}`,"data-office-pane":M?dQ:void 0,children:[dM&&"floor"===dQ?(0,d.jsx)(ku.t,{roster:dM,selected:dN,onSelect:cg.select,view:cg.view,onViewChange:cg.setView}):null,(0,d.jsxs)("div",{id:"workspace-transcript",className:"chat-session-column","data-lounge-open":af?"true":void 0,inert:dR||void 0,children:[ds?(0,d.jsx)(gb,{session:am,newSessionCwd:dr,initialSessionData:aq,transitioning:null!==ao,onAgentEnd:dg,onAttentionNeeded:dh,onSessionCreated:de,onSessionForked:dj,modelsRefreshKey:aN,chatInputRef:b_,onBranchDataChange:b5,onSystemPromptChange:b9,onSessionStatsChange:cq,onSessionStatsPanelOpen:cR,onContextUsageChange:cx,onSubagentsChange:cd,onMainIdentityChange:cf,onOpenWorkspaceView:dL,onProcessLogChange:cz,onOpenFile:dn,transcriptReplacement:dS?(0,d.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:eb}):dP&&dO?(0,d.jsx)(kA,{participant:dP,recipient:dO,sessionId:am?.id??null,cwd:am?.cwd??dr??void 0,onBackToMain:()=>cg.select(kB.h7),onOpenFile:dn},dP.key):null,onComposerFocusChange:bx,onSessionBusyChange:bl,onWaitingChange:bn,onAttentionChange:cl,soundEnabled:$,onSoundToggle:_,playCueSound:aa,preloadCueSound:ab,unlockAudio:ac,jumpRequest:au,onJumpHandled:ax},aJ):dS?(0,d.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:eb}):"validating"===aD?(0,d.jsxs)("div",{role:"status",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,d.jsx)("div",{style:{fontSize:14,color:"var(--text)"},children:W("workspace.opening")}),(0,d.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:Q.requestedCwd})]}):"error"===aD?(0,d.jsxs)("div",{role:"alert",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,d.jsx)("div",{style:{fontSize:14,color:"var(--danger)"},children:W("workspace.unable")}),(0,d.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:Q.requestedCwd}),(0,d.jsx)("div",{style:{maxWidth:720,fontSize:12},children:aF})]}):dv?c_?(0,d.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:W("workspace.selectSession")}):(0,d.jsxs)("div",{style:{position:"absolute",top:12,left:12,display:"flex",alignItems:"flex-start",gap:8,userSelect:"none",pointerEvents:"none"},children:[(0,d.jsxs)("svg",{width:"44",height:"44",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",style:{opacity:.7,flexShrink:0},children:[(0,d.jsx)("line",{x1:"20",y1:"12",x2:"4",y2:"12"}),(0,d.jsx)("polyline",{points:"10 6 4 12 10 18"})]}),(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{style:{fontSize:18,fontWeight:600,color:"var(--text)",marginBottom:8},children:W("workspace.getStarted")}),(0,d.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.8},children:[(0,d.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"1."}),W("workspace.selectProject"),(0,d.jsx)("br",{}),(0,d.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),W("workspace.addModels")]})]})]}):null,ah?(0,d.jsx)(ks,{lounge:aj,visible:af,onBack:()=>bw(!1)}):null]}),"pinned"===bc.deck&&dt&&!M&&(0,d.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-pinned","data-workspace-region":"deck",children:eb})]}),dM&&dQ?(0,d.jsx)(kt.FC,{roster:dM,selected:dN,onSelect:a=>{af&&bw(!1),cg.select(a)},pane:dQ,onShowFloor:()=>{af&&bw(!1),cg.setPane("floor")},selectionGone:cg.selected!==dN}):null]}),"command-palette"===a6.transientLayer&&(0,d.jsx)("div",{className:"workspace-command-layer",onMouseDown:a=>{a.target===a.currentTarget&&(a7({type:"close-layer"}),bv())},children:(0,d.jsxs)("div",{ref:bu,className:"workspace-command-palette",role:"dialog","aria-modal":"true",onKeyDown:bK,"aria-label":"ko"===T?"명령 팔레트":"Command palette",children:[(0,d.jsxs)("header",{children:[(0,d.jsx)("strong",{children:"ko"===T?"명령 팔레트":"Command palette"}),(0,d.jsx)("kbd",{children:"Ctrl K"})]}),(0,d.jsx)(gi,{t:W,onPick:(a,b)=>{a7({type:"close-layer"}),cI("chat",!1),aw.current+=1,av({id:aw.current,sessionId:a.id,entryId:b.entryId}),da(a)}}),(0,d.jsxs)("div",{className:"workspace-command-list",children:[l.map(a=>(0,d.jsxs)("button",{type:"button",onClick:()=>cI(a,!0),children:[(0,d.jsx)("span",{children:dU[a]}),(0,d.jsx)("small",{children:a6.activeView===a?"ko"===T?"현재 보기":"Current view":""})]},a)),m.map(a=>(0,d.jsxs)("button",{type:"button",onClick:()=>{a9(a),cI("resource",!1)},children:[(0,d.jsx)("span",{children:"characters"===a?"캐릭터":"usage"===a?"계정 한도":"모델 통계"}),(0,d.jsx)("small",{children:dU.resource})]},a)),(0,d.jsxs)("button",{type:"button",onClick:cS,children:[(0,d.jsx)("span",{children:bV.presented?W("sidebar.hide"):W("sidebar.show")}),(0,d.jsx)("small",{children:"Ctrl B"})]}),(0,d.jsx)("button",{type:"button",onClick:aA,children:(0,d.jsx)("span",{children:W(ay?"palette.wideChatOff":"palette.wideChatOn")})}),(0,d.jsx)("button",{type:"button",onClick:()=>{a7({type:"close-layer"}),aQ(!0)},children:(0,d.jsx)("span",{children:W("common.settings")})})]})]})})]}),aP&&(0,d.jsx)(iq,{cwd:du,sessionId:am?.id??null,onClose:()=>{aQ(!1),a$(a=>a+1),bv()},onModelsChanged:()=>aO(a=>a+1),onReloaded:()=>aK(a=>a+1)}),null!==aR&&(0,d.jsx)(hH,{cwd:du,onClose:cM,onModelsChanged:()=>aO(a=>a+1),relogin:{target:aR,outcome:aT,onLoginSucceeded:cO}}),a0&&du&&(0,d.jsx)(it,{cwd:du,busy:a2,scheduled:aW?.pending==="grant",error:a4,onCancel:()=>{a2||(a1(!1),bv())},onConfirm:()=>void dx("grant"),onCancelSchedule:()=>void dx("cancel")})]})}},84431:a=>{a.exports={backdrop:"SettingsConfig_backdrop__i6KYG",window:"SettingsConfig_window__m7dcs",sidebar:"SettingsConfig_sidebar__vEMEr",brand:"SettingsConfig_brand__DlYlu",eyebrow:"SettingsConfig_eyebrow__uTa5R",title:"SettingsConfig_title__DWTnA",context:"SettingsConfig_context__N0fl0",searchWrap:"SettingsConfig_searchWrap___PWrc",searchIcon:"SettingsConfig_searchIcon__8_YYE",search:"SettingsConfig_search__DUhSs",nav:"SettingsConfig_nav__V8P9S",navLabel:"SettingsConfig_navLabel__M1wMP",navButton:"SettingsConfig_navButton__CUOqu",navIcon:"SettingsConfig_navIcon__Wagpr",closeRail:"SettingsConfig_closeRail__PW3pT",closeButton:"SettingsConfig_closeButton__5y_6F",content:"SettingsConfig_content__n_a5Z",scrollContent:"SettingsConfig_scrollContent__03BsO",contentHeader:"SettingsConfig_contentHeader__tNmzv",contentTitle:"SettingsConfig_contentTitle__oiHOO",contentDescription:"SettingsConfig_contentDescription___l2QU",reloadNotice:"SettingsConfig_reloadNotice__enzeE",settingsBody:"SettingsConfig_settingsBody__QRFVu",group:"SettingsConfig_group__JQ_dy",groupTitle:"SettingsConfig_groupTitle__0SrM9",settingRow:"SettingsConfig_settingRow__Jy73r",settingLabel:"SettingsConfig_settingLabel__n8vtU",settingDescription:"SettingsConfig_settingDescription__TGWfP",settingControl:"SettingsConfig_settingControl__oz5Gn",select:"SettingsConfig_select__A5aGy",textInput:"SettingsConfig_textInput___NjZ2",jsonEditor:"SettingsConfig_jsonEditor__yTYDb",numberInput:"SettingsConfig_numberInput__TVVeJ",switch:"SettingsConfig_switch__5UYqz",multiSelect:"SettingsConfig_multiSelect__PTjyr",choice:"SettingsConfig_choice__Os8WR",choiceToggle:"SettingsConfig_choiceToggle__lyl75",reorder:"SettingsConfig_reorder__JR6tX",error:"SettingsConfig_error__j6wEj",saveState:"SettingsConfig_saveState__1tIL4",themeGrid:"SettingsConfig_themeGrid__7Lw8A",themeCard:"SettingsConfig_themeCard__DQFsT",themePreview:"SettingsConfig_themePreview__QzqXK",themePreviewBar:"SettingsConfig_themePreviewBar__ZbchX",themePreviewPanel:"SettingsConfig_themePreviewPanel__YN9ty",themePreviewLine:"SettingsConfig_themePreviewLine__jP0qg",themeCardBody:"SettingsConfig_themeCardBody__xiOe6",themeCardHeader:"SettingsConfig_themeCardHeader__YPRN2",themeSlot:"SettingsConfig_themeSlot__vGn9a",themeActive:"SettingsConfig_themeActive__PNmdk",mcpLayout:"SettingsConfig_mcpLayout__ek_Fi",mcpList:"SettingsConfig_mcpList__gZ9_o",scopeTabs:"SettingsConfig_scopeTabs__9bybS",scopeButton:"SettingsConfig_scopeButton__d4XPe",serverRows:"SettingsConfig_serverRows__JSJy0",serverRow:"SettingsConfig_serverRow__6gJdE",serverSelect:"SettingsConfig_serverSelect__cuYFx",serverToggle:"SettingsConfig_serverToggle__X5N_o",serverName:"SettingsConfig_serverName__lbfcK",sourceBadge:"SettingsConfig_sourceBadge__XDE2u",serverListEmpty:"SettingsConfig_serverListEmpty___icit",statusDot:"SettingsConfig_statusDot__dVcD4",addServer:"SettingsConfig_addServer__g0ivB",mcpEditor:"SettingsConfig_mcpEditor__XGcLp",editorHeader:"SettingsConfig_editorHeader__qDvAk",readOnlyNotice:"SettingsConfig_readOnlyNotice__KNzML",editorActions:"SettingsConfig_editorActions__h9p7Y",linkButton:"SettingsConfig_linkButton__0DH3I",primaryButton:"SettingsConfig_primaryButton__Eocwv",dangerButton:"SettingsConfig_dangerButton__XF_f_",empty:"SettingsConfig_empty__erg3A"}}};
|