cuelo 0.10.21 → 0.10.22
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 +4 -4
- package/.next/build-manifest.json +2 -2
- package/.next/prerender-manifest.json +3 -3
- package/.next/required-server-files.js +1 -1
- package/.next/required-server-files.json +1 -1
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_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 +4 -4
- package/.next/server/chunks/5489.js +2 -2
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/chunks/{9575-032510d25828764f.js → 9575-9b108bc443510ebc.js} +2 -2
- package/.next/static/chunks/app/{layout-a7fca69a4fa9b2c2.js → layout-cdb057e5a5cc0f50.js} +1 -1
- package/.next/trace +108 -108
- package/.next/trace-build +1 -1
- package/Tools/CUELO_Setup/files/native-runtime-patch.js +1 -1
- package/Tools/OMP_Global_Config/agent/extensions/docmap-route.ts +124 -26
- package/Tools/OMP_Global_Config/agent/extensions/lib/docmap-search.ts +38 -2
- package/Tools/OMP_Global_Config/agent/extensions/lib/native-judge.ts +82 -0
- package/Tools/OMP_Global_Config/agent/extensions/mcp-selection.ts +11 -78
- package/Tools/OMP_Global_Config/agent/rules/docs-handoff.md +1 -1
- package/Tools/OMP_Global_Config/patches/apply-core-patch.mjs +117 -198
- package/package.json +1 -1
- /package/.next/static/{IKi2VjUzAnD5AUcDn7QNi → WFIfYmiOdtHjqFYh2crxO}/_buildManifest.js +0 -0
- /package/.next/static/{IKi2VjUzAnD5AUcDn7QNi → WFIfYmiOdtHjqFYh2crxO}/_ssgManifest.js +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[9575],{13004:e=>{e.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"}},14755:(e,t,r)=>{"use strict";r.d(t,{C1:()=>a,IN:()=>i,getPresetFromTools:()=>l,xG:()=>o});let n=[],i=["read","bash","edit","write"],a=["read","bash","edit","write","grep","glob"],s=Object.fromEntries(a.map(e=>[e,!0]));function l(e){let t=e.filter(e=>e.active);if(0===t.length)return"none";let r=t.map(e=>e.name).filter(e=>!0===s[e]).sort().join(",");return r===[...i].sort().join(",")?"default":r===[...a].sort().join(",")?"full":"default"}function o(e){return"none"===e?[...n]:"full"===e?[...a]:[...i]}},21340:()=>{},21443:e=>{e.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"}},30381:(e,t,r)=>{"use strict";r.d(t,{AppShell:()=>pn});var n=r(95155),i=r(12115),a=r(73321),s=r(16871),l=r(81886),o=r(68890),d=r(6057);let c=["chat","process","subagents","files","resource","sidechat","efficiency"],u=["characters","usage","models"];Object.freeze({transcript:550,composer:384,navigator:240,deck:384});let p=Object.freeze({navigator:791,deck:1176}),h=Object.freeze({activeView:"chat",transientLayer:null}),f=Object.fromEntries(c.map(e=>[e,!0]));function m(e){return"string"==typeof e&&!0===f[e]?e:h.activeView}function g(e,t){switch(t.type){case"select-view":return{activeView:m(t.view),transientLayer:null};case"open-layer":return{activeView:m(e.activeView),transientLayer:t.layer};case"toggle-layer":return{activeView:m(e.activeView),transientLayer:e.transientLayer===t.layer?null:t.layer};case"close-layer":return{activeView:m(e.activeView),transientLayer:null}}}function x(e){let t=Number.isFinite(e)?Math.max(0,e):0;return{availableWidth:t,navigator:t>=p.navigator?"pinned":"drawer",deck:t>=p.deck?"pinned":"view-stack"}}let v=null,b=!1,y=-1/0;function w(e,t=Date.now()){b=e,e||(y=t)}let k=["projects","priority"],j="omp-web:navigator-mode",S="omp-prio-on",C=["omp-relay-session-","omp-cwd-","ompscope_"];function N(e){let t=e.trim().replace(/\\/g,"/");return"/"===(t=t.startsWith("//")?`//${t.slice(2).replace(/\/{2,}/g,"/")}`:t.replace(/\/{2,}/g,"/"))||/^[a-zA-Z]:\/$/.test(t)||(t=t.replace(/\/+$/,"")),/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}function I(e){let t=new Map;for(let r of e){let e=r.projectRoot??r.cwd;if(!e)continue;let n=N(e),i=t.get(n);(!i||r.modified>i.modified)&&t.set(n,{project:e,modified:r.modified})}return[...t.values()].sort((e,t)=>t.modified.localeCompare(e.modified)).map(e=>e.project)}function T(e,t){let r=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&r.set(N(e.key),e.order);let n=[...e],i=new Set(e.map(N));for(let e of t){let t=N(e.key);!t||i.has(t)||(n.push(e.path??e.key),i.add(t))}return n.map((e,t)=>({project:e,defaultIndex:t,order:r.get(N(e))})).sort((e,t)=>{let r=void 0!==e.order,n=void 0!==t.order;return r!==n?r?-1:1:r&&n&&e.order!==t.order?e.order-t.order:e.defaultIndex-t.defaultIndex}).map(({project:e})=>e)}let M=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function $(e){let t=e.match(M);if(!t)return null;let[,r,,,n]=t;return n?`/skill:${r} ${n}`:`/skill:${r}`}var R=r(92176);let E=`(max-width: ${p.navigator-1}px)`;function L(e){return{subscribe(t){if(!window.matchMedia)return()=>{};let r=window.matchMedia(e);return r.addEventListener("change",t),()=>r.removeEventListener("change",t)},getSnapshot:()=>!!window.matchMedia&&window.matchMedia(e).matches}}let z=L("(max-width: 640px)"),A=L(E);function P(){return!1}function W(){return(0,i.useSyncExternalStore)(z.subscribe,z.getSnapshot,P)}var F=r(47650);async function _(e){let t=e?`?path=${encodeURIComponent(e)}`:"",r=await fetch(`/api/cwd/browse${t}`),n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);return n}function D(){return(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function H(){return(0,n.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,n.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,n.jsx)("path",{d:"M2 9h12"}),(0,n.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function O({onCancel:e,onSelect:t,busy:r=!1,error:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(""),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(""),[x,v]=(0,i.useState)([]),[b,y]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!0),C=(0,i.useCallback)(async e=>{S(!0),k(null);try{let t=await _(e),r=t.path??e??"/";c(r),p(t.parentPath??null),f(!0===t.upToDrives),g(r),v(t.directories??[]),y(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{o(document.body),C()},[C]);let N=m.trim()!==d,I=!!d&&!N&&!r,T=!!u||h||/^[a-zA-Z]:[\\/]?$/.test(d);return l?(0,F.createPortal)((0,n.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":s("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||r||e()},onKeyDown:t=>{"Escape"!==t.key||r||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,n.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,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{minWidth:0,flex:1},children:(0,n.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:s("directoryPicker.selectDirectory")})}),(0,n.jsx)("button",{type:"button",onClick:e,disabled:r,title:s("i18n.close"),"aria-label":s("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:r?"default":"pointer",opacity:r?.5:1},children:"\xd7"})]}),(0,n.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=m.trim();t&&C(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void C(u??void 0),disabled:j||!T,title:s("directoryPicker.goToParent"),"aria-label":s("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:T?"pointer":"default",opacity:T?1:.45},children:(0,n.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,n.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,n.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:s("directoryPicker.directoryPath")}),(0,n.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:m,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),k(null)},style:{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,n.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:j||!m.trim(),title:s("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:j||!m.trim()?"default":"pointer",opacity:j||!m.trim()?.6:1},children:s("directoryPicker.go")})]}),(0,n.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[j?(0,n.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.loadingDirectories")}):null!==b?(0,n.jsx)(n.Fragment,{children:b.length>0?b.map(e=>(0,n.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,n.jsx)(H,{}),(0,n.jsx)("span",{children:e.name})]},e.path)):(0,n.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,n.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,n.jsx)(D,{}),(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,n.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noSubdirectories")}),(w||a)&&(0,n.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??a})]}),(0,n.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,n.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:r,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text-muted)",cursor:r?"default":"pointer",fontSize:13},children:s("i18n.cancel")}),(0,n.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(d),disabled:!I,title:s(N?"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:I?1:.6,cursor:I?"pointer":"default"},children:s(r?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),l):null}var B=r(21443),U=r.n(B);async function q(e,t){let r=await fetch(e,t?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}:void 0),n=await r.json();if(!r.ok)throw Error(n.error||`HTTP ${r.status}`);return n}function K({onCancel:e,onSelect:t,busy:r=!1,error:a}){let{t:s}=(0,R.s)(),l=(0,i.useRef)(null),[o,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)([]),[g,x]=(0,i.useState)(""),[v,b]=(0,i.useState)(""),[y,w]=(0,i.useState)(!0),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),[N,I]=(0,i.useState)(null),[T,M]=(0,i.useState)(!1),[$,E]=(0,i.useState)(50),L=p?.device?.state==="pending",z=r||S,A=(0,i.useCallback)(async()=>{w(!0),I(null);try{let e=await q("/api/github/projects");h(e),e.connected&&m((await q("/api/github/projects?view=repositories")).repositories)}catch(e){I(e instanceof Error?e.message:String(e))}finally{w(!1)}},[]);async function P(){j(!0),I(null);try{let{device:e}=await q("/api/github/projects",{action:"login"});h({connected:!1,login:null,device:e})}catch(e){I(e instanceof Error?e.message:String(e))}finally{j(!1)}}async function W(e){if(e.preventDefault(),v.trim()&&!z){C(!0),I(null);try{let{cwd:e}=await q("/api/github/projects",{action:"open",repository:v});t(e)}catch(e){I(e instanceof Error?e.message:String(e))}finally{C(!1)}}}if((0,i.useEffect)(()=>{d(!0),A()},[A]),(0,i.useEffect)(()=>{if(!o||c)return;let e=l.current;return e?.showModal(),()=>e?.close()},[o,c]),(0,i.useEffect)(()=>{let e;if(!L||c)return;let t=!1,r=async()=>{try{let e=await q("/api/github/projects");if(t)return;if(h(e),e.connected)return void await A();if(e.device?.state!=="pending")return}catch(e){t||I(e instanceof Error?e.message:String(e));return}t||(e=window.setTimeout(r,3e3))};return e=window.setTimeout(r,1500),()=>{t=!0,clearTimeout(e)}},[L,c,A]),!o)return null;if(c)return(0,n.jsx)(O,{onCancel:()=>u(!1),onSelect:t,busy:r,error:a});let _=f.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(g.toLowerCase())),D=N??a??p?.device?.error;return(0,F.createPortal)((0,n.jsx)("dialog",{ref:l,className:U().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),z||e()},children:(0,n.jsxs)("form",{onSubmit:W,className:U().form,children:[(0,n.jsxs)("header",{className:U().header,children:[(0,n.jsx)("h2",{id:"cloud-project-title",children:s("cloudProjects.title")}),(0,n.jsx)("p",{children:s("cloudProjects.description")})]}),(0,n.jsxs)("div",{className:U().sources,children:[(0,n.jsx)("span",{className:U().activeSource,children:s("cloudProjects.github")}),(0,n.jsx)("button",{type:"button",onClick:()=>u(!0),disabled:z,children:s("cloudProjects.serverFolder")})]}),(0,n.jsxs)("div",{className:U().body,children:[(0,n.jsxs)("section",{className:U().account,"aria-label":s("cloudProjects.account"),children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("strong",{children:p?.connected?p.login:s("cloudProjects.connectTitle")}),(0,n.jsx)("p",{children:p?.connected?s("cloudProjects.connected"):s("cloudProjects.connectHelp")})]}),p?.connected?(0,n.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void A(),disabled:y||z,children:s("cloudProjects.refresh")}):(0,n.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void P(),disabled:y||k||L||z,children:k||L?s("cloudProjects.waiting"):s("cloudProjects.connect")})]}),L&&(0,n.jsxs)("div",{className:U().login,role:"status",children:[(0,n.jsx)("p",{children:s("cloudProjects.deviceHelp")}),p.device?.code?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:U().codeRow,children:[(0,n.jsx)("code",{children:p.device.code}),(0,n.jsx)("button",{type:"button",className:U().secondary,onClick:()=>{navigator.clipboard.writeText(p.device.code).then(()=>M(!0)).catch(()=>I(s("cloudProjects.copyFailure")))},children:T?s("cloudProjects.copied"):s("cloudProjects.copyCode")})]}),(0,n.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:U().loginLink,children:s("cloudProjects.openLogin")}),(0,n.jsx)("small",{children:s("cloudProjects.permissionHelp")})]}):(0,n.jsx)("p",{children:s("cloudProjects.preparingCode")})]}),p?.connected&&(0,n.jsxs)("section",{className:U().repositories,"aria-label":s("cloudProjects.repositories"),children:[(0,n.jsx)("label",{htmlFor:"cloud-repo-search",children:s("cloudProjects.search")}),(0,n.jsx)("input",{id:"cloud-repo-search",value:g,onChange:e=>{x(e.target.value),E(50)},placeholder:s("cloudProjects.searchPlaceholder"),type:"search",disabled:z}),y?(0,n.jsx)("p",{role:"status",children:s("cloudProjects.loading")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("ul",{className:U().list,children:_.slice(0,$).map(e=>(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button",className:U().repo,"aria-pressed":v===e.fullName,disabled:z,onClick:()=>b(e.fullName),children:[(0,n.jsxs)("span",{className:U().repoHeading,children:[(0,n.jsx)("strong",{children:e.fullName}),(0,n.jsx)("small",{children:e.private?s("cloudProjects.private"):s("cloudProjects.public")})]}),e.description&&(0,n.jsx)("span",{className:U().repoDescription,children:e.description})]})},e.fullName))}),!_.length&&(0,n.jsx)("p",{children:s("cloudProjects.empty")}),_.length>$&&(0,n.jsx)("button",{type:"button",className:U().secondary,onClick:()=>E(e=>e+50),children:s("cloudProjects.more")})]})]}),(0,n.jsxs)("div",{className:U().repositoryInput,children:[(0,n.jsx)("label",{htmlFor:"cloud-repository",children:s("cloudProjects.urlLabel")}),(0,n.jsx)("input",{id:"cloud-repository",value:v,onChange:e=>b(e.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:z,"aria-describedby":"cloud-repo-help"}),(0,n.jsx)("small",{id:"cloud-repo-help",children:s("cloudProjects.publicHelp")})]}),D&&(0,n.jsxs)("div",{className:U().error,role:"alert",children:[(0,n.jsx)("strong",{children:s("cloudProjects.error")}),(0,n.jsx)("p",{children:D}),(0,n.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void A(),disabled:z,children:s("cloudProjects.refresh")})]}),S&&(0,n.jsx)("p",{role:"status",className:U().progress,children:s("cloudProjects.openingHelp")})]}),(0,n.jsxs)("footer",{className:U().footer,children:[(0,n.jsx)("button",{type:"button",className:U().secondary,onClick:e,disabled:z,children:s("i18n.cancel")}),(0,n.jsx)("button",{type:"submit",className:U().primary,disabled:z||!v.trim(),children:z?s("cloudProjects.opening"):s("cloudProjects.open")})]})]})}),document.body)}function V({label:e="CUELO",markSize:t=22,gap:r=10,style:i,labelStyle:a}){return(0,n.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:r,minWidth:0,color:"var(--text)",...i},children:[(0,n.jsxs)("svg",{viewBox:"0 0 100 100",width:t,height:t,"aria-hidden":"true",style:{flexShrink:0},children:[(0,n.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,n.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:"var(--font-heading)",fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...a},children:e})]})}var J=r(2730);let G={ko:{"translator.tab":"통역","translator.title":"통역","translator.back":"대화로","translator.panelHint":"통역을 시작하면 ChatGPT 계정의 Codex 라이브 통화로 두 사람의 말을 서로의 언어로 바로 소리 내어 옮깁니다. 작업 세션과 하네스 규칙을 거치지 않고, 기록은 저장하지 않습니다.","translator.open":"통역 화면 열기","translator.me":"나","translator.them":"상대","translator.myLanguage":"내 언어","translator.theirLanguage":"상대 언어","translator.swap":"두 언어 바꾸기","translator.clear":"지우기","translator.start":"통역 시작","translator.stop":"통역 끝내기","translator.empty":"통역 시작을 누르고 폰을 두 사람 사이에 두세요. 누가 말하든 상대 언어로 바로 옮겨 말합니다.","translator.connecting":"연결 중…","translator.live":"듣는 중 \xb7 그냥 말하세요","translator.unsupported":"이 브라우저는 실시간 통화(WebRTC\xb7마이크)를 지원하지 않습니다. 폰에서는 Chrome이나 Safari로 여세요.","translator.insecure":"마이크는 HTTPS 주소에서만 켜집니다.","translator.micDenied":"마이크 권한이 막혀 있습니다. 브라우저 설정에서 이 주소의 마이크를 허용하세요.","translator.micUnavailable":"마이크를 켜지 못했습니다. 다른 앱이 쓰고 있지 않은지 확인하세요.","translator.auth":"Codex 로그인이 없거나 만료됐습니다. 모델 설정에서 ChatGPT 계정으로 다시 로그인하세요.","translator.upstream":"Codex 라이브 연결이 끊겼습니다: {error}","translator.failed":"통역을 시작하지 못했습니다: {error}","translator.original":"원문","translator.translationPending":"통역 중…","translator.conversation":"통역 기록"},en:{"translator.tab":"Interpret","translator.title":"Interpreter","translator.back":"Back to chat","translator.panelHint":"Start interpreting and a Codex live call on your ChatGPT account speaks each person's words in the other's language right away. It bypasses work sessions and harness rules, and nothing is saved.","translator.open":"Open interpreter","translator.me":"Me","translator.them":"Them","translator.myLanguage":"My language","translator.theirLanguage":"Their language","translator.swap":"Swap languages","translator.clear":"Clear","translator.start":"Start interpreting","translator.stop":"Stop interpreting","translator.empty":"Press Start interpreting and put the phone between you. Whoever speaks is interpreted into the other language right away.","translator.connecting":"Connecting…","translator.live":"Listening \xb7 just talk","translator.unsupported":"This browser cannot make live calls (WebRTC and microphone). On a phone, open this page in Chrome or Safari.","translator.insecure":"The microphone only works on an HTTPS address.","translator.micDenied":"Microphone access is blocked. Allow the microphone for this address in the browser settings.","translator.micUnavailable":"The microphone could not be opened. Check that no other app is using it.","translator.auth":"The Codex sign-in is missing or expired. Sign in again with your ChatGPT account in model settings.","translator.upstream":"The Codex live connection dropped: {error}","translator.failed":"Interpreting could not start: {error}","translator.original":"Original","translator.translationPending":"Interpreting…","translator.conversation":"Interpretation log"},"zh-CN":{"translator.tab":"口译","translator.title":"口译","translator.back":"返回对话","translator.panelHint":"开始口译后,通过 ChatGPT 账号的 Codex 实时通话,把双方的话立即用对方的语言说出来。不经过工作会话和规则,也不保存记录。","translator.open":"打开口译","translator.me":"我","translator.them":"对方","translator.myLanguage":"我的语言","translator.theirLanguage":"对方语言","translator.swap":"交换语言","translator.clear":"清除","translator.start":"开始口译","translator.stop":"结束口译","translator.empty":"按开始口译,把手机放在两人之间。无论谁说话,都会立即译成对方的语言说出来。","translator.connecting":"连接中…","translator.live":"正在听 \xb7 直接说话","translator.unsupported":"此浏览器不支持实时通话(WebRTC 和麦克风)。手机请用 Chrome 或 Safari 打开。","translator.insecure":"麦克风只能在 HTTPS 地址上使用。","translator.micDenied":"麦克风权限被阻止。请在浏览器设置中允许此地址使用麦克风。","translator.micUnavailable":"无法打开麦克风。请确认没有其他应用正在使用。","translator.auth":"Codex 登录不存在或已过期。请在模型设置中用 ChatGPT 账号重新登录。","translator.upstream":"Codex 实时连接已断开:{error}","translator.failed":"无法开始口译:{error}","translator.original":"原文","translator.translationPending":"口译中…","translator.conversation":"口译记录"}};function Y(){let{locale:e}=(0,R.s)();return{tt:(0,i.useCallback)((t,r)=>(0,J.u0)(e,t,G,r),[e]),locale:e}}let Z="omp-web:unread-session-ids",X="omp-web:pinned-session-ids",Q="omp-web:removed-projects";function ee(e,t){return{minHeight:t?36:30,padding:"3px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:e?"var(--text-dim)":"var(--text-muted)",cursor:e?"default":"pointer",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.3,textAlign:"left",whiteSpace:"normal",overflowWrap:"anywhere"}}function et(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function er({text:e,style:t}){return(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...t},children:(0,n.jsx)("span",{style:{unicodeBidi:"plaintext"},children:e})})}function en({open:e,children:t,style:r}){let[a,s]=(0,i.useState)(e),[l,o]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,r;return e?(s(!0),o(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>o(!0))})):(o(!1),r=setTimeout(()=>s(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),r&&clearTimeout(r)}},[e]),a)?(0,n.jsx)("div",{style:{...r,opacity:+!!l,transform:l?"translateY(0) scale(1)":"translateY(-8px) scale(0.96)",transformOrigin:"top center",transition:"opacity 140ms ease, transform 140ms ease",pointerEvents:e?"auto":"none"},children:t}):null}let ei="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function ea(){let[e,t]=(0,i.useState)(!1),[r,a]=(0,i.useState)(!1),s=(0,i.useRef)(null),l=function(e,t){let[r,n]=(0,i.useState)(e),a=(0,i.useRef)(null),s=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void n(e);s.current=0;let r=4*e.length,i=()=>{s.current+=1;let t=Math.floor(s.current/r*e.length);n(e.split("").map((e,r)=>" "===e?" ":r<t?e:ei[Math.floor(Math.random()*ei.length)]).join("")),s.current<r?a.current=requestAnimationFrame(i):n(e)};return a.current=requestAnimationFrame(i),()=>{a.current&&cancelAnimationFrame(a.current)}},[e,t]),r}(e?"0.10.21/18.11.3":"CUELO",r),o=(0,i.useCallback)(e=>{t(e),a(!0),setTimeout(()=>a(!1),(e?6:8)*4*(1e3/60)+100)},[]),d=(0,i.useCallback)(()=>{s.current&&clearTimeout(s.current);let t=!e;o(t),t&&(s.current=setTimeout(()=>o(!1),3e3))},[e,o]);return(0,i.useEffect)(()=>()=>{s.current&&clearTimeout(s.current)},[]),(0,n.jsx)("button",{className:"navigator-brand",onClick:d,style:{display:"flex",alignItems:"center",background:"none",border:"none",padding:0,cursor:"default",color:e?"var(--accent)":"var(--text)",flex:"0 1 auto",minWidth:0,overflow:"hidden"},children:(0,n.jsx)(V,{label:l,labelStyle:e?{fontFamily:"var(--font-mono)",fontSize:12,letterSpacing:"-0.02em",textOverflow:"ellipsis"}:void 0})})}async function es(e){let t=await fetch("/api/projects",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:e})});if(!t.ok)throw Error(`HTTP ${t.status}`)}function el({selectedSessionId:e,optimisticSession:t,onSelectSession:r,onNewSession:a,initialSessionId:s,skipInitialProjectSelection:l,onInitialRestoreDone:o,refreshKey:d,onSessionDeleted:c,selectedCwd:u,onCwdChange:p,onBackgroundTaskDone:h,translatorPanel:f,translatorActive:m=!1,onTranslatorActiveChange:g}){let x,{tt:v}=Y(),{t:b,locale:y}=(0,R.s)(),w=W(),[M,$]=(0,i.useState)([]),E=t&&!M.some(e=>e.id===t.id)?[t,...M]:M,[L,z]=(0,i.useState)(!0),[A,P]=(0,i.useState)(null),[F,_]=(0,i.useState)(null),[D,H]=(0,i.useState)(""),[B,U]=(0,i.useState)(!1),[q,V]=(0,i.useState)(""),[J,G]=(0,i.useState)("projects"),[ei,ed]=(0,i.useState)(()=>new Set),[eh,ef]=(0,i.useState)(()=>new Set),[eg,ex]=(0,i.useState)(null),[ev,eb]=(0,i.useState)(null),[ey,ew]=(0,i.useState)({version:1,projects:[]}),[ek,ej]=(0,i.useState)(!1),[eS,eC]=(0,i.useState)(!1),[eN,eI]=(0,i.useState)(!1),[eT,eM]=(0,i.useState)(null),[e$,eR]=(0,i.useState)(""),[eE,eL]=(0,i.useState)(!1),[ez,eA]=(0,i.useState)(null),[eP,eW]=(0,i.useState)(""),[eF,e_]=(0,i.useState)(!1),[eD,eH]=(0,i.useState)(null),[eO,eB]=(0,i.useState)(!1),[eU,eq]=(0,i.useState)(null),[eK,eV]=(0,i.useState)(!1),[eJ,eG]=(0,i.useState)(!1),[eY,eZ]=(0,i.useState)(""),[eX,eQ]=(0,i.useState)(null),[e0,e1]=(0,i.useState)(!1),[e2,e4]=(0,i.useState)(null),e5=(0,i.useRef)(null),e8=(0,i.useRef)(null),e6=(0,i.useRef)(null),e3=(0,i.useRef)(!1),e7=(0,i.useRef)(!1),[e9,te]=(0,i.useState)(!1),[tt,tr]=(0,i.useState)(()=>new Set),[tn,ti]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(Z);if(!e)return new Set;let t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(e=>"string"==typeof e));return new Set}catch{return new Set}})()),[ta,ts]=(0,i.useState)(()=>new Set),tl=(0,i.useRef)(new Set),to=(0,i.useRef)(!1),td=(0,i.useRef)(null);(0,i.useEffect)(()=>{ts(function(){try{let e=window.localStorage.getItem(X);if(!e)return new Set;let t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(e=>"string"==typeof e)):new Set}catch{return new Set}}())},[]);let tc=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/projects",{cache:"no-store",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw Error(`HTTP ${e.status}`);ew(await e.json())}catch{ew({version:1,projects:[]})}finally{ej(!0)}},[]);(0,i.useEffect)(()=>{tc()},[tc,d]),(0,i.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(Q)}catch{return}if(!e)return;let t=[];try{let r=JSON.parse(e);Array.isArray(r)&&(t=r.filter(e=>"string"==typeof e))}catch{t=[]}(async()=>{try{for(let e=0;e<t.length;e+=500){let r=t.slice(e,e+500);await es(r.map(e=>({key:N(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(Q)}catch{}await tc()})()},[tc]);let tu=(0,i.useCallback)(async e=>{if(e7.current)throw Error("Project update in progress");e7.current=!0,eL(!0);try{await es(e),await tc()}finally{e7.current=!1,eL(!1)}},[tc]);(0,i.useEffect)(()=>{eT&&e6.current?.select()},[eT]);let tp=(0,i.useCallback)(async(e=!1,t=!1)=>{try{e&&z(!0);let r=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!r.ok)throw Error(`HTTP ${r.status}`);let n=await r.json();$(n.sessions),to.current||tr(new Set(n.runningSessionIds??[])),P(null),e||(te(!0),td.current&&clearTimeout(td.current),td.current=setTimeout(()=>te(!1),2e3))}catch(e){P(String(e))}finally{e&&z(!1)}},[]),th=(0,i.useCallback)(e=>{ti(t=>{if(!t.has(e))return t;let r=new Set(t);return r.delete(e),r}),ts(t=>{if(!t.has(e))return t;let r=new Set(t);return r.delete(e),r}),c?.(e),tp()},[tp,c]),[tf,tm]=(0,i.useState)(null),[tg,tx]=(0,i.useState)(!1),[tv,tb]=(0,i.useState)(null),ty=(0,i.useCallback)(()=>{tg||(tm(null),tb(null))},[tg]),tw=(0,i.useCallback)(async e=>{tx(!0),tb(null);let t=[],r=[],n=[];for(let i of e)if(!i.transient)try{let e=await fetch(`/api/sessions/${encodeURIComponent(i.id)}?skipRunning=1`,{method:"DELETE"});if(409===e.status){r.push(i.id);continue}if(!e.ok)throw Error(`HTTP ${e.status}`);t.push(i.id)}catch{n.push(i.name?.trim()||i.id.slice(0,8))}if(r.length>0&&(to.current=!0,tr(e=>{if(r.every(t=>e.has(t)))return e;let t=new Set(e);for(let e of r)t.add(e);return t})),t.length>0){let e=new Set(t),r=r=>t.some(e=>r.has(e))?new Set([...r].filter(t=>!e.has(t))):r;for(let e of(ti(r),ts(r),t))c?.(e)}(await tp(),tx(!1),n.length>0)?tb(b("sidebar.clearSessionsFailed",{count:n.length,names:n.join(", ")})):r.length>0||tm(null)},[tp,c,b]),[tk,tj]=(0,i.useState)(0),tS=(0,i.useCallback)(()=>{tj(e=>e+1),tp()},[tp]),tC=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!tC.current;tC.current=!0,tp(e,!e)},[tp,d]),(0,i.useEffect)(()=>{try{G(function(e,t){return"gpt6"===e?"projects":"string"==typeof e&&k.includes(e)?e:"1"===t?"priority":"projects"}(window.localStorage.getItem(j),window.localStorage.getItem(S)))}catch{}},[]);let tN=(0,i.useCallback)(e=>{G(e);try{window.localStorage.setItem(j,e),window.localStorage.setItem(S,"priority"===e?"1":"0")}catch{}},[]);(0,i.useEffect)(()=>{if("priority"!==J)return;let e=()=>{"visible"===document.visibilityState&&tp(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[tp,J]),(0,i.useEffect)(()=>{try{0===tn.size?window.localStorage.removeItem(Z):window.localStorage.setItem(Z,JSON.stringify([...tn]))}catch{}},[tn]),(0,i.useEffect)(()=>{try{0===ta.size?window.localStorage.removeItem(X):window.localStorage.setItem(X,JSON.stringify([...ta]))}catch{}},[ta]);let tI=(0,i.useCallback)(e=>{ts(t=>{let r=new Set(t);return r.has(e)?r.delete(e):r.add(e),r})},[]);(0,i.useEffect)(()=>{let e=!1,t=null,r=null,n=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let a=new AbortController;r?.abort(),r=a;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:a.signal});if(!t.ok)return;let n=await t.json();if(e||r!==a)return;to.current=!0,tr(new Set(n.runningSessionIds??[]))}catch{}finally{r===a&&(r=null),n(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},a=()=>{"visible"===document.visibilityState?i():(n(),r?.abort(),r=null)};return i(),document.addEventListener("visibilitychange",a),()=>{e=!0,n(),r?.abort(),document.removeEventListener("visibilitychange",a)}},[]),(0,i.useEffect)(()=>{let t=tl.current,r=[...t].filter(t=>!tt.has(t)&&t!==e),n=[...tt].filter(e=>!t.has(e));(r.length>0||n.length>0)&&ti(e=>{let t=new Set(e);return tt.forEach(e=>t.delete(e)),r.forEach(e=>t.add(e)),t});let i=n.some(e=>!M.some(t=>t.id===e));(r.length>0||i)&&tp(!1,!0),r.length>0&&h?.(),tl.current=tt},[tt,e,M,tp,h]),(0,i.useEffect)(()=>{e&&ti(t=>{if(!t.has(e))return t;let r=new Set(t);return r.delete(e),r})},[e]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&H(e.home),U(!0===e.cloudProjects)}).catch(()=>{})},[]);let tT=(0,i.useRef)(!1),tM=(0,i.useCallback)(e=>{if(!e)return null;if(eU&&eU.forCwd===e||eU?.worktrees.some(t=>t.path===e))return eU.projectRoot;let t=E.find(t=>t.cwd===e);return t?.projectRoot??e},[eU,E]),t$=(0,i.useRef)(null);(0,i.useEffect)(()=>{t$.current!==F&&(t$.current=F,p?.(F,tM(F)))},[F,p,tM]);let tR=(0,i.useRef)(null);(0,i.useEffect)(()=>{u&&u!==tR.current&&(tR.current=u,_(u))},[u]);let[tE,tL]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!F)return void eq(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(F)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void eq(null);eq({forCwd:F,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||eq(null)}),()=>{e=!0}},[F,tE,d]),(0,i.useEffect)(()=>{if(0!==M.length&&!l&&null===F){if(s&&!tT.current){tT.current=!0;let e=M.find(e=>e.id===s);if(e){_(e.cwd),r(e,!0);return}o?.()}if(!ek)return;let e=new Map(ey.projects.map(e=>[e.key,e])),t=T(M.length>0?I(M):[],ey.projects).filter(t=>!e.get(N(t))?.hidden);t.length>0&&_(t[0])}},[M,F,s,l,r,o,ey,ek]);let tz=(0,i.useCallback)(async e=>{let t=e.trim();if(t&&!eO){eB(!0),eH(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),r=await e.json().catch(()=>({}));if(!e.ok||r.error)return void eH(r.error??b("workspace.unable"));let n=r.cwd??t,i=N(n),a=ey.projects.find(e=>e.key===i);if(a?.hidden===!0)try{await tu([{key:i,path:n,hidden:!1}])}catch{}_(n),e_(!1)}catch{eH(b("workspace.unable"))}finally{eB(!1)}}},[tu,eO,ey.projects,b]),tA=(0,i.useCallback)(()=>{e_(!0),eH(null)},[]),tP=(0,i.useCallback)(async()=>{let e=eY.trim();if(e&&!e0&&eU){e1(!0),eQ(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eU.projectRoot,branch:e})}),r=await t.json().catch(()=>({}));if(!t.ok||r.error||!r.path)return void eQ(r.error??`HTTP ${t.status}`);eG(!1),eZ(""),eV(!1),eq(t=>t?{...t,forCwd:r.path,worktrees:[...t.worktrees,{path:r.path,branch:e,isMain:!1}]}:t),_(r.path),tL(e=>e+1)}catch(e){eQ(e instanceof Error?e.message:String(e))}finally{e1(!1)}}},[eY,e0,eU]),tW=(0,i.useCallback)(async(e,t)=>{if(eU&&!e0){e1(!0),eQ(null);try{let r=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eU.projectRoot,path:e,force:t})}),n=await r.json().catch(()=>({}));if(!r.ok){if(n.dirty&&!t)return void e4(e);eQ(n.error??`HTTP ${r.status}`);return}e4(null),F===e&&_(eU.projectRoot),tL(e=>e+1)}catch(e){eQ(e instanceof Error?e.message:String(e))}finally{e1(!1)}}},[eU,e0,F]);(0,i.useEffect)(()=>{let e=e=>{e5.current&&!e5.current.contains(e.target)&&(eb(null),eV(!1),eG(!1),eZ(""),eQ(null),e4(null),eW(""),ex(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tF=(0,i.useCallback)(e=>{e.cwd&&_(e.cwd),r(e)},[r]),t_=(0,i.useCallback)((e=F)=>{if(!e)return;let t="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;_(e),a?.(t,e)},[F,a]),[tD,tH]=(0,i.useState)(!1),[tO,tB]=(0,i.useState)(null),tU=(0,i.useCallback)(async()=>{tH(!0),tB(null);try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json().catch(()=>({}));if(!e.ok||!t.cwd)throw Error(t.error??`HTTP ${e.status}`);t_(t.cwd)}catch(e){tB(b("sidebar.newScratchSessionFailed",{error:e instanceof Error?e.message:String(e)}))}finally{tH(!1)}},[t_,b]),tq=(0,i.useCallback)(e=>{ef(t=>{let r=new Set(t);return r.has(e)?r.delete(e):r.add(e),r})},[]),tK=tM(F),tV=null===tK?null:N(tK),tJ=(0,i.useMemo)(()=>new Map(ey.projects.map(e=>[e.key,e])),[ey.projects]),tG=I(E);if(null!==tK){let e=N(tK);tG.some(t=>N(t)===e)||tG.unshift(tK)}let tY=T(tG,ey.projects),tZ=tY.filter(e=>eS||!tJ.get(N(e))?.hidden),tX=tY.some(e=>tJ.get(N(e))?.hidden),tQ=()=>{eb(null),eV(!1),eG(!1),eZ(""),eQ(null),e4(null),eW("")},t0=async(e,t)=>{tQ();try{await tu([{key:N(e),path:e,hidden:t}]),t&&tV&&tV===N(e)&&_(null),t||tY.some(t=>N(t)!==N(e)&&tJ.get(N(t))?.hidden)||eC(!1)}catch{}},t1=async e=>{if(e3.current){e3.current=!1,eM(null);return}let t=e$.trim();if(t===(tJ.get(N(e))?.alias??""))return void eM(null);eA(null);try{await tu([{key:N(e),path:e,alias:t||null}]),eM(null)}catch{eA(b("sidebar.projectUpdateFailed"))}},t2=async(e,t)=>{if(q)return;let r=tZ.indexOf(e),n=r+t;if(r<0||n<0||n>=tZ.length)return;let i=new Set(tZ),a=tY.map((e,t)=>i.has(e)?t:-1).filter(e=>e>=0),s=[...tY],l=a[r],o=a[n];[s[l],s[o]]=[s[o],s[l]],tQ();try{await tu(s.map((e,t)=>({key:N(e),path:e,order:t})))}catch{}},t4=new Map;for(let e of E){let t=e.projectRoot??e.cwd;if(!t)continue;let r=N(t),n=t4.get(r);n?n.push(e):t4.set(r,[e])}let t5=(0,i.useMemo)(()=>{let e=new Map;for(let t of E){let r=t.projectRoot??t.cwd;if(!r)continue;let n=N(r),i=e.get(n);i||(i={running:0,unread:0},e.set(n,i)),tt.has(t.id)&&i.running++,tn.has(t.id)&&i.unread++}return e},[E,tt,tn]),t8=q.trim().toLowerCase(),t6=q.length>0,t3=tZ.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,r=N(e),n=tJ.get(r),i=n?.alias??t,a=(t4.get(r)??[]).slice().sort((e,t)=>{let r=Number(ta.has(t.id))-Number(ta.has(e.id));return 0!==r?r:t.modified.localeCompare(e.modified)});if(!t8)return[{project:e,key:r,name:i,sessions:a,hidden:n?.hidden===!0}];let s=i.toLowerCase().includes(t8)||t.toLowerCase().includes(t8),l=a.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(t8));return s||0!==l.length?[{project:e,key:r,name:i,sessions:s?a:l,hidden:n?.hidden===!0}]:[]}),t7=[],t9=[];for(let e of t3){let t=e.key===tV||(t5.get(e.key)?.running??0)>0;(function(e){let t=e.trim().replace(/\\/g,"/").toLowerCase();return!!(/^[a-z]:\/?$/.test(t)||"/"===t||/(^|\/)appdata\/local\/temp(\/|$)/.test(t)||/^\/(?:var\/|private\/)?tmp(?:\/|$)/.test(t)||/^[a-z]:\/(?:tmp|temp)(?:\/|$)/.test(t)||/(^|\/)(?:users|home)\/[^/]+\/\.omp(\/|$)/.test(t))||t.split("/").some(e=>C.some(t=>e.startsWith(t)))})(e.project)&&!t?t9.push(e):t7.push(e)}let re={running:0,unread:0};for(let e of t9){let t=t5.get(e.key);t&&(re.running+=t.running,re.unread+=t.unread)}let rt=t6||eN,rr=[...t7.map(e=>({kind:"project",group:e})),...t9.length>0?[{kind:"temporary"}]:[],...rt?t9.map(e=>({kind:"project",group:e})):[]],rn=function(e){let t=new Map;for(let r of e){let e=r.toLowerCase();t.set(e,(t.get(e)??0)+1)}return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}(rr.flatMap(e=>"project"===e.kind?[e.group.name]:[])),ri=(0,i.useMemo)(()=>(function(e,t,r,n,i="Priority",a=new Set,s="Pinned"){let l=e.filter(e=>!e.transient).slice().sort((e,t)=>{let r=Date.parse(e.modified),n=Date.parse(t.modified);return(Number.isFinite(n)?n:0)-(Number.isFinite(r)?r:0)}),o=l.filter(e=>a.has(e.id)),d=[],c=new Map,u=0;for(let e of l){if(a.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let r=new Date(e.modified);if(u>=10)continue;u+=1;let n=[r.getFullYear(),String(r.getMonth()+1).padStart(2,"0"),String(r.getDate()).padStart(2,"0")].join("-"),i=c.get(n);i?i.push(e):c.set(n,[e])}let p=[];for(let e of(o.length>0&&p.push({key:"pinned",label:s,running:!1,sessions:o}),d.length>0&&p.push({key:"priority",label:i,running:!0,sessions:d}),[...c.keys()].sort().reverse()))p.push({key:e,label:function(e,t,r){let[n,i,a]=e.split("-").map(Number),s=new Date(n,i-1,a),l=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(s.getFullYear(),s.getMonth(),s.getDate()))/864e5);return 0===l||1===l?new Intl.RelativeTimeFormat(r,{numeric:"auto"}).format(-l,"day"):l>=0&&l<7?new Intl.DateTimeFormat(r,{weekday:"long"}).format(s):new Intl.DateTimeFormat(r,{month:"short",day:"numeric"}).format(s)}(e,r,n),running:!1,sessions:c.get(e)??[]});return p})(E,tt,new Date,y,b("navigator.priority"),ta,b("sidebar.pinned")),[y,ta,tt,E,b]),ra=!!(eU?.isGit&&eU.isTopLevel&&F&&tK===eU.projectRoot),rs=eU?.worktrees.find(e=>e.path===F)??eU?.worktrees.find(e=>e.isMain),rl=(eU?.worktrees.length??0)>=8,ro=rl&&eP.trim()?(eU?.worktrees??[]).filter(e=>(e.branch??et(e.path,D)).toLowerCase().includes(eP.trim().toLowerCase())):eU?.worktrees??[],rd=(()=>{if(!tf)return[];let e="project"===tf.kind?t4.get(N(tf.project))??[]:ri.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),rc=rd.filter(e=>!tt.has(e.id)),ru=e=>{let t=new Set;for(let r of e)r.transient||tt.has(r.id)||t.has(r.id)||t.add(r.id);return t.size},rp=void 0!==f&&m;return(0,n.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[eF&&(0,n.jsx)(B?K:O,{busy:eO,error:eD,onCancel:()=>{e_(!1),eH(null)},onSelect:e=>void tz(e)}),tf&&(0,n.jsx)(eo,{scope:tf,eligible:rc.length,runningExcluded:rd.length-rc.length,busy:tg,error:tv,onCancel:ty,onConfirm:()=>void tw(rc)}),(0,n.jsx)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,n.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,n.jsx)(ea,{}),(0,n.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,n.jsx)("button",{className:"navigator-icon-action",onClick:()=>t_(),disabled:!F,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:"1px solid var(--border)",color:F?"var(--text-muted)":"var(--text-dim)",cursor:F?"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:F?b("sidebar.newSessionTitle",{path:F}):b("sidebar.selectProject"),"aria-label":F?b("sidebar.newSessionTitle",{path:F}):b("sidebar.selectProject"),onMouseEnter:e=>{F&&(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=F?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)"},children:(0,n.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,n.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,n.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]})}),(0,n.jsx)("button",{className:`navigator-icon-action${e9?" is-success":""}`,onClick:()=>tp(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:e9?"rgba(74,222,128,0.18)":"var(--bg-hover)",border:`1px solid ${e9?"rgba(74,222,128,0.4)":"var(--border)"}`,color:e9?"#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:e=>{e9||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{e9||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)")},title:b("sidebar.refresh"),children:e9?(0,n.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,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,n.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,n.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,n.jsx)("path",{d:"M3 3v5h5"})]})})]})]})}),B&&!rp&&(0,n.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:tA,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:b("cloudProjects.launch")}),(0,n.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,n.jsxs)("div",{className:"navigator-mode-switcher",role:"toolbar","aria-label":b("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:[k.map(e=>{let t="projects"===e?b("sidebar.projects"):b("navigator.priority"),r=!rp&&J===e;return(0,n.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:t}),"aria-pressed":r,"aria-controls":`navigator-${e}-panel`,"data-navigator-mode":e,onClick:()=>{tN(e),rp&&g?.(!1)},style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:r?"var(--bg-selected)":"transparent",color:r?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:r?600:500,whiteSpace:"nowrap"},children:t},e)}),void 0!==f&&(0,n.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:v("translator.tab")}),"aria-pressed":rp,"aria-controls":"navigator-translator-panel","data-navigator-mode":"translator",onClick:()=>g?.(!rp),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:rp?"var(--bg-selected)":"transparent",color:rp?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:rp?600:500,whiteSpace:"nowrap"},children:v("translator.tab")})]}),!rp&&"projects"===J&&(0,n.jsx)("button",{type:"button",onClick:()=>eC(e=>!e),disabled:!tX,title:b("sidebar.projectShowHidden"),"aria-label":b("sidebar.projectShowHidden"),"aria-pressed":eS,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:5,background:eS?"var(--bg-selected)":"transparent",color:eS?"var(--accent)":"var(--text-dim)",cursor:tX?"pointer":"default",opacity:tX?1:.45,flexShrink:0},children:(0,n.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,n.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,n.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!eS&&(0,n.jsx)("path",{d:"m4 4 16 16"})]})}),!rp&&"projects"===J&&(0,n.jsx)("button",{className:"navigator-add-project",type:"button",onClick:tA,title:b("sidebar.addProject"),"aria-label":b("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:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},children:(0,n.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,n.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,n.jsx)("path",{d:"M15.5 10.5v5M13 13h5"})]})})]}),rp&&f,!rp&&"projects"===J&&(0,n.jsxs)("label",{className:"navigator-search",style:{position:"relative",display:"block",margin:"0 8px 8px"},children:[(0,n.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,n.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,n.jsx)("path",{d:"m20 20-3.5-3.5"})]}),(0,n.jsx)("input",{className:"navigator-search-input",type:"search",value:q,onChange:e=>V(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),V(""),e.currentTarget.blur())},placeholder:b("sidebar.searchProjectsAndSessions"),"aria-label":b("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}})]}),!rp&&"projects"===J&&(0,n.jsxs)("div",{id:"navigator-projects-panel",className:"navigator-session-list",style:{flex:"1 1 auto",overflowY:"auto",minHeight:80,padding:"0 6px 10px"},children:[(L||!ek)&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),A&&(0,n.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:A}),ez&&(0,n.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:ez}),!L&&ek&&!A&&0===t3.length&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:t8?b("sidebar.noMatchingProjects"):b("sidebar.noSessions")}),!L&&ek&&!A&&rr.map(t=>{let r,i,a;if("temporary"===t.kind)return(0,n.jsx)("div",{className:"navigator-project-group",children:(0,n.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":rt,title:b("sidebar.temporaryProjects"),onClick:()=>eI(e=>!e),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,n.jsx)("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,flexShrink:0,color:"var(--text-dim)"},children:(0,n.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:rt?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.12s"},children:(0,n.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.temporaryProjects")}),(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10,flexShrink:0},children:t9.length}),em(re,b)]})},"navigator-temporary-projects");let{project:s,key:l,name:o,sessions:d,hidden:c}=t.group,u=l===tV,p=rn.has(o.toLowerCase())&&et((i=Math.max((r=s.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),r.lastIndexOf("/")))<=0?"":r.slice(0,i),D)||null,h=!eh.has(s)&&!t8,f=ei.has(s),m=eT===s,g=tZ.indexOf(s),x=eE||t6||g<=0,v=eE||t6||g>=tZ.length-1,y=function(e){let t=new Map;for(let r of e)t.set(r.id,{session:r,children:[]});let r=new Map;for(let t of e)t.parentSessionId&&r.set(t.id,t.parentSessionId);let n=[];for(let e of t.values()){let i=function(e){let n=r.get(e),i=new Set;for(;n&&!i.has(n);){if(i.add(n),t.has(n))return n;n=r.get(n)}return null}(e.session.id);i?t.get(i).children.push(e):n.push(e)}let i=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>i(e.children))};return i(n),n}(f?d:d.slice(0,5)),k=d.length>5;return(0,n.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:h?3:9},children:[(0,n.jsxs)("div",{className:`navigator-project-row${u?" is-selected":""}`,ref:ev===s?e5:void 0,onMouseEnter:()=>ex(s),onMouseLeave:()=>ex(e=>e===s&&ev!==s?null:e),style:{display:"flex",alignItems:"center",minHeight:34,position:"relative",borderRadius:6,background:u?"var(--bg-hover)":"transparent",opacity:c?.55:1},children:[(0,n.jsx)("button",{type:"button",onClick:()=>tq(s),title:h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-label":h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-expanded":!h,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,n.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:h?"rotate(-90deg)":"rotate(0deg)",transition:"transform 0.12s"},children:(0,n.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),m?(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px"},children:[(0,n.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,n.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,n.jsx)("input",{ref:e6,value:e$,onChange:e=>eR(e.target.value),onBlur:()=>void t1(s),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),e3.current=!0,eM(null))},"aria-label":b("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,n.jsxs)("button",{className:"navigator-project-name",type:"button",onClick:()=>_(s),title:s,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:u?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:u?600:500},children:[(0,n.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:u?"var(--accent)":"var(--text-dim)"},children:(0,n.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,n.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o}),null===p?null:(0,n.jsx)("span",{style:{flexShrink:2,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:p}),em(t5.get(l),b)]}),(0,n.jsx)("button",{type:"button",onClick:()=>t_(s),title:b("sidebar.newSessionTitle",{path:s}),"aria-label":b("sidebar.newSessionTitle",{path:s}),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:w||eg===s?1:0,pointerEvents:w||eg===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>ex(s),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,n.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,n.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,n.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,n.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,n.jsx)("button",{type:"button",onClick:()=>{eb(ev===s?null:s),eV(!1),eG(!1),eQ(null),u||_(s)},title:b("sidebar.projectActions"),"aria-label":b("sidebar.projectActions"),"aria-expanded":ev===s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:5,background:ev===s?"var(--bg-selected)":"transparent",color:u&&rs&&!rs.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:w||eg===s||ev===s?1:0,pointerEvents:w||eg===s||ev===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>ex(s),children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,n.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,n.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,n.jsxs)(en,{open:ev===s,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:[ra&&eU&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{type:"button",onClick:()=>eV(e=>!e),title:rs?b("sidebar.switchWorktreeTitle",{path:rs.path}):b("sidebar.switchWorktree"),"aria-label":b("sidebar.worktrees"),"aria-expanded":eK,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderBottom:eK?"1px solid var(--border)":"none",background:eK?"var(--bg-selected)":"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,n.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,n.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,n.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,n.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,n.jsx)("span",{style:{flex:1},children:b("sidebar.worktrees")}),(0,n.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,n.jsx)("polyline",{points:"4 2.5 8 6 4 9.5"})})]}),(0,n.jsxs)(en,{open:eK,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:[rl&&(0,n.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,n.jsx)("input",{value:eP,onChange:e=>eW(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eW(""),eV(!1))},placeholder:b("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,n.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[ro.map(e=>{let t=e.path===F||e.isMain&&!eU.worktrees.some(e=>e.path===F);return e2===e.path?(0,n.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,n.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.forceRemoveCheckout")}),(0,n.jsx)("button",{onClick:()=>void tW(e.path,!0),disabled:e0,style:{padding:"3px 9px",background:"var(--danger)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:b("sidebar.force")}),(0,n.jsx)("button",{onClick:()=>e4(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:b("sidebar.cancel")})]},e.path):(0,n.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,n.jsxs)("button",{onClick:()=>{_(e.path),eV(!1),eQ(null),eW("")},title:e.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[t?(0,n.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,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)(er,{text:e.branch??et(e.path,D),style:{flex:1}}),e.isMain&&(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:b("sidebar.main")})]}),!e.isMain&&(0,n.jsx)("button",{onClick:()=>void tW(e.path,!1),disabled:e0,title:b("sidebar.removeWorktreeTitle",{path:e.path}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:34,height:28,padding:0,marginRight:4,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",borderRadius:5,flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="#ef4444",e.currentTarget.style.background="rgba(239,68,68,0.08)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,n.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,n.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,n.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.path)}),rl&&0===ro.length&&eP.trim()&&(0,n.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:b("sidebar.noMatchingWorktrees")})]}),eJ?(0,n.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,n.jsx)("input",{ref:e8,value:eY,onChange:e=>{eZ(e.target.value),eQ(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),tP()),"Escape"===e.key&&(eG(!1),eZ(""),eQ(null))},placeholder:b("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,n.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,n.jsx)("button",{onClick:()=>void tP(),disabled:e0||!eY.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:e0||!eY.trim()?"not-allowed":"pointer",opacity:e0||!eY.trim()?.65:1},children:e0?b("sidebar.creating"):b("sidebar.create")}),(0,n.jsx)("button",{onClick:()=>{eG(!1),eZ(""),eQ(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:b("sidebar.cancel")})]})]}):(0,n.jsxs)("button",{onClick:e=>{e.stopPropagation(),eG(!0),eQ(null),setTimeout(()=>e8.current?.focus(),0)},title:b("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,n.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,n.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,n.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,n.jsx)("span",{children:b("sidebar.newWorktree")})]}),eX&&(0,n.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:eX})]})]}),(0,n.jsxs)("button",{type:"button",disabled:eE,onClick:()=>{let e;return e=tJ.get(N(s))?.alias??"",void(e3.current=!1,eA(null),eR(e),eM(s),tQ())},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:eE?"default":"pointer",textAlign:"left",fontSize:11,opacity:eE?.55:1},children:[(0,n.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,n.jsx)("path",{d:"m4 20 4.5-1 10-10a2.1 2.1 0 0 0-3-3l-10 10L4 20Z"}),(0,n.jsx)("path",{d:"m13.5 8 3 3"})]}),b(tJ.get(N(s))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,n.jsxs)("button",{type:"button",disabled:x,title:t6?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void t2(s,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:x?"default":"pointer",textAlign:"left",fontSize:11,opacity:x?.55:1},children:[(0,n.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,n.jsx)("path",{d:"m6 15 6-6 6 6"})}),b("sidebar.projectMoveUp")]}),(0,n.jsxs)("button",{type:"button",disabled:v,title:t6?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void t2(s,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:v?"default":"pointer",textAlign:"left",fontSize:11,opacity:v?.55:1},children:[(0,n.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,n.jsx)("path",{d:"m6 9 6 6 6-6"})}),b("sidebar.projectMoveDown")]}),(0,n.jsxs)("button",{type:"button",disabled:eE,onClick:()=>void t0(s,!c),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:eE?"default":"pointer",textAlign:"left",fontSize:11,opacity:eE?.55:1},children:[(0,n.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,n.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,n.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!c&&(0,n.jsx)("path",{d:"m4 4 16 16"})]}),b(c?"sidebar.projectUnhide":"sidebar.projectHide")]}),(a=0===ru(t4.get(l)??[])||tg,(0,n.jsxs)("button",{type:"button",disabled:a,onClick:()=>{tQ(),tb(null),tm({kind:"project",project:s,label:o})},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:a?"default":"pointer",textAlign:"left",fontSize:11,opacity:a?.55:1},children:[(0,n.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,n.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),b("sidebar.clearProjectSessions")]}))]})]})]}),!h&&0===d.length&&u&&(0,n.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:b("sidebar.noSessions")}),!h&&y.length>0&&(0,n.jsx)("div",{style:{paddingLeft:12},children:y.map(t=>(0,n.jsx)(ep,{node:t,selectedSessionId:e,runningSessionIds:tt,unreadSessionIds:tn,pinnedSessionIds:ta,onSelectSession:tF,onTogglePinnedSession:tI,onRenamed:tp,onSessionDeleted:th,onSessionArchived:tS,depth:0},t.session.id))}),!h&&k&&(0,n.jsx)("button",{type:"button",onClick:()=>{ed(e=>{let t=new Set(e);return t.has(s)?t.delete(s):t.add(s),t})},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:f?b("sidebar.showLess"):b("sidebar.showMore")})]},s)})]}),!rp&&(0,n.jsx)(eu,{refreshKey:tk,selectedSessionId:e,onSelectSession:tF,onRestored:tS}),!rp&&"priority"===J&&(0,n.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[L&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),A&&(0,n.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:A}),!L&&!A&&(x=ru(ri.flatMap(e=>e.sessions)),(0,n.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"8px 2px 2px"},children:[(0,n.jsx)("button",{type:"button",disabled:tD,onClick:()=>void tU(),title:b("sidebar.newScratchSessionTitle"),style:ee(tD,w),children:b("sidebar.newScratchSession")}),ri.length>0&&(0,n.jsx)("button",{type:"button",disabled:0===x||tg,onClick:()=>{tb(null),tm({kind:"priority"})},style:ee(0===x||tg,w),children:b("sidebar.clearPriorityList")})]})),tO&&(0,n.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:tO}),!L&&!A&&0===ri.length&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.noSessions")}),!L&&!A&&ri.map((t,r)=>(0,n.jsxs)("section",{"aria-labelledby":`priority-group-${t.key}`,children:[(0,n.jsx)("h2",{id:`priority-group-${t.key}`,style:{margin:0,padding:0===r?"2px 8px 4px":"14px 8px 4px",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.label}),t.sessions.map(t=>(0,n.jsx)(ec,{session:t,selected:t.id===e,running:tt.has(t.id),unread:tn.has(t.id),pinned:ta.has(t.id),onSelect:tF,onTogglePin:tI},t.id))]},t.key))]})]})}function eo({scope:e,eligible:t,runningExcluded:r,busy:a,error:s,onCancel:l,onConfirm:o}){let{t:d}=(0,R.s)(),c=a||0===t,u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(a);h.current=a;let f=(0,i.useRef)(l);return f.current=l,(0,i.useEffect)(()=>{let e=u.current;if(!e)return;let t=document.activeElement,r=t instanceof HTMLElement&&t!==document.body&&t!==document.documentElement&&!e.contains(t)?t:null;(p.current??e).focus();let n=t=>{if("Escape"===t.key){if(h.current)return;t.preventDefault(),f.current();return}if("Tab"!==t.key)return;let r=Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0),n=document.activeElement;if(0===r.length){t.preventDefault(),e.focus();return}let i=r[0],a=r[r.length-1];t.shiftKey&&(n===i||!e.contains(n))?(t.preventDefault(),a.focus()):t.shiftKey||n!==a&&e.contains(n)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",n),()=>{e.removeEventListener("keydown",n);let t=r?.isConnected?r:e.closest(".session-navigator");t?.focus()}},[]),(0,n.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:e=>{a||e.target!==e.currentTarget||l()},children:(0,n.jsxs)("div",{ref:u,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,n.jsxs)("div",{style:{padding:"18px 18px 14px"},children:[(0,n.jsx)("div",{id:"bulk-clear-title",style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:d("sidebar.clearSessionsTitle")}),(0,n.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"===e.kind?d("sidebar.clearSessionsProjectBody",{project:e.label,count:t}):d("sidebar.clearSessionsPriorityBody",{count:t}),r>0&&(0,n.jsx)("div",{style:{marginTop:6},children:d("sidebar.clearSessionsRunningExcluded",{count:r})}),0===t&&(0,n.jsx)("div",{style:{marginTop:6},children:d("sidebar.clearSessionsNone")})]}),s&&(0,n.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:s})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("button",{ref:p,type:"button",onClick:l,disabled:a,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:d("sidebar.clearSessionsCancel")}),(0,n.jsx)("button",{type:"button",onClick:o,disabled:c,"aria-busy":a,style:{minHeight:36,padding:"0 14px",border:"1px solid var(--danger)",borderRadius:"var(--radius-control)",background:"transparent",color:c?"var(--text-dim)":"var(--danger)",cursor:c?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:d(a?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function ed({filled:e=!1}){return(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:e?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M12 17v5"}),(0,n.jsx)("path",{d:"M5 17h14"}),(0,n.jsx)("path",{d:"M6 3h12l-1 8 2 3H5l2-3-1-8z"})]})}function ec({session:e,selected:t,running:r,unread:i,pinned:a,onSelect:s,onTogglePin:l}){let{t:o}=(0,R.s)(),d=(e.name||e.firstMessage||e.id.slice(0,8)).replace(/\s+/g," ").trim(),c=e.cwd.split(/[\\/]/).filter(Boolean).at(-1)??"";return(0,n.jsxs)("div",{className:`priority-session-row${t?" is-selected":""}${r?" is-running":""}${i?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:5,background:t?"var(--bg-selected)":"transparent"},children:[(0,n.jsxs)("button",{type:"button","aria-current":t?"page":void 0,onClick:()=>s(e),title:`${d}
|
|
1
|
+
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[9575],{13004:e=>{e.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"}},14755:(e,t,r)=>{"use strict";r.d(t,{C1:()=>a,IN:()=>i,getPresetFromTools:()=>l,xG:()=>o});let n=[],i=["read","bash","edit","write"],a=["read","bash","edit","write","grep","glob"],s=Object.fromEntries(a.map(e=>[e,!0]));function l(e){let t=e.filter(e=>e.active);if(0===t.length)return"none";let r=t.map(e=>e.name).filter(e=>!0===s[e]).sort().join(",");return r===[...i].sort().join(",")?"default":r===[...a].sort().join(",")?"full":"default"}function o(e){return"none"===e?[...n]:"full"===e?[...a]:[...i]}},21340:()=>{},21443:e=>{e.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"}},30381:(e,t,r)=>{"use strict";r.d(t,{AppShell:()=>pn});var n=r(95155),i=r(12115),a=r(73321),s=r(16871),l=r(81886),o=r(68890),d=r(6057);let c=["chat","process","subagents","files","resource","sidechat","efficiency"],u=["characters","usage","models"];Object.freeze({transcript:550,composer:384,navigator:240,deck:384});let p=Object.freeze({navigator:791,deck:1176}),h=Object.freeze({activeView:"chat",transientLayer:null}),f=Object.fromEntries(c.map(e=>[e,!0]));function m(e){return"string"==typeof e&&!0===f[e]?e:h.activeView}function g(e,t){switch(t.type){case"select-view":return{activeView:m(t.view),transientLayer:null};case"open-layer":return{activeView:m(e.activeView),transientLayer:t.layer};case"toggle-layer":return{activeView:m(e.activeView),transientLayer:e.transientLayer===t.layer?null:t.layer};case"close-layer":return{activeView:m(e.activeView),transientLayer:null}}}function x(e){let t=Number.isFinite(e)?Math.max(0,e):0;return{availableWidth:t,navigator:t>=p.navigator?"pinned":"drawer",deck:t>=p.deck?"pinned":"view-stack"}}let v=null,b=!1,y=-1/0;function w(e,t=Date.now()){b=e,e||(y=t)}let k=["projects","priority"],j="omp-web:navigator-mode",S="omp-prio-on",C=["omp-relay-session-","omp-cwd-","ompscope_"];function N(e){let t=e.trim().replace(/\\/g,"/");return"/"===(t=t.startsWith("//")?`//${t.slice(2).replace(/\/{2,}/g,"/")}`:t.replace(/\/{2,}/g,"/"))||/^[a-zA-Z]:\/$/.test(t)||(t=t.replace(/\/+$/,"")),/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}function I(e){let t=new Map;for(let r of e){let e=r.projectRoot??r.cwd;if(!e)continue;let n=N(e),i=t.get(n);(!i||r.modified>i.modified)&&t.set(n,{project:e,modified:r.modified})}return[...t.values()].sort((e,t)=>t.modified.localeCompare(e.modified)).map(e=>e.project)}function T(e,t){let r=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&r.set(N(e.key),e.order);let n=[...e],i=new Set(e.map(N));for(let e of t){let t=N(e.key);!t||i.has(t)||(n.push(e.path??e.key),i.add(t))}return n.map((e,t)=>({project:e,defaultIndex:t,order:r.get(N(e))})).sort((e,t)=>{let r=void 0!==e.order,n=void 0!==t.order;return r!==n?r?-1:1:r&&n&&e.order!==t.order?e.order-t.order:e.defaultIndex-t.defaultIndex}).map(({project:e})=>e)}let M=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function $(e){let t=e.match(M);if(!t)return null;let[,r,,,n]=t;return n?`/skill:${r} ${n}`:`/skill:${r}`}var R=r(92176);let E=`(max-width: ${p.navigator-1}px)`;function L(e){return{subscribe(t){if(!window.matchMedia)return()=>{};let r=window.matchMedia(e);return r.addEventListener("change",t),()=>r.removeEventListener("change",t)},getSnapshot:()=>!!window.matchMedia&&window.matchMedia(e).matches}}let z=L("(max-width: 640px)"),A=L(E);function P(){return!1}function W(){return(0,i.useSyncExternalStore)(z.subscribe,z.getSnapshot,P)}var F=r(47650);async function _(e){let t=e?`?path=${encodeURIComponent(e)}`:"",r=await fetch(`/api/cwd/browse${t}`),n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);return n}function D(){return(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function H(){return(0,n.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,n.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,n.jsx)("path",{d:"M2 9h12"}),(0,n.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function O({onCancel:e,onSelect:t,busy:r=!1,error:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(""),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(""),[x,v]=(0,i.useState)([]),[b,y]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!0),C=(0,i.useCallback)(async e=>{S(!0),k(null);try{let t=await _(e),r=t.path??e??"/";c(r),p(t.parentPath??null),f(!0===t.upToDrives),g(r),v(t.directories??[]),y(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{o(document.body),C()},[C]);let N=m.trim()!==d,I=!!d&&!N&&!r,T=!!u||h||/^[a-zA-Z]:[\\/]?$/.test(d);return l?(0,F.createPortal)((0,n.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":s("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||r||e()},onKeyDown:t=>{"Escape"!==t.key||r||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,n.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,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{minWidth:0,flex:1},children:(0,n.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:s("directoryPicker.selectDirectory")})}),(0,n.jsx)("button",{type:"button",onClick:e,disabled:r,title:s("i18n.close"),"aria-label":s("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:r?"default":"pointer",opacity:r?.5:1},children:"\xd7"})]}),(0,n.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=m.trim();t&&C(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void C(u??void 0),disabled:j||!T,title:s("directoryPicker.goToParent"),"aria-label":s("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:T?"pointer":"default",opacity:T?1:.45},children:(0,n.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,n.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,n.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:s("directoryPicker.directoryPath")}),(0,n.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:m,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),k(null)},style:{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,n.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:j||!m.trim(),title:s("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:j||!m.trim()?"default":"pointer",opacity:j||!m.trim()?.6:1},children:s("directoryPicker.go")})]}),(0,n.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[j?(0,n.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.loadingDirectories")}):null!==b?(0,n.jsx)(n.Fragment,{children:b.length>0?b.map(e=>(0,n.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,n.jsx)(H,{}),(0,n.jsx)("span",{children:e.name})]},e.path)):(0,n.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,n.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,n.jsx)(D,{}),(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,n.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noSubdirectories")}),(w||a)&&(0,n.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??a})]}),(0,n.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,n.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:r,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text-muted)",cursor:r?"default":"pointer",fontSize:13},children:s("i18n.cancel")}),(0,n.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(d),disabled:!I,title:s(N?"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:I?1:.6,cursor:I?"pointer":"default"},children:s(r?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),l):null}var B=r(21443),U=r.n(B);async function q(e,t){let r=await fetch(e,t?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}:void 0),n=await r.json();if(!r.ok)throw Error(n.error||`HTTP ${r.status}`);return n}function K({onCancel:e,onSelect:t,busy:r=!1,error:a}){let{t:s}=(0,R.s)(),l=(0,i.useRef)(null),[o,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)([]),[g,x]=(0,i.useState)(""),[v,b]=(0,i.useState)(""),[y,w]=(0,i.useState)(!0),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),[N,I]=(0,i.useState)(null),[T,M]=(0,i.useState)(!1),[$,E]=(0,i.useState)(50),L=p?.device?.state==="pending",z=r||S,A=(0,i.useCallback)(async()=>{w(!0),I(null);try{let e=await q("/api/github/projects");h(e),e.connected&&m((await q("/api/github/projects?view=repositories")).repositories)}catch(e){I(e instanceof Error?e.message:String(e))}finally{w(!1)}},[]);async function P(){j(!0),I(null);try{let{device:e}=await q("/api/github/projects",{action:"login"});h({connected:!1,login:null,device:e})}catch(e){I(e instanceof Error?e.message:String(e))}finally{j(!1)}}async function W(e){if(e.preventDefault(),v.trim()&&!z){C(!0),I(null);try{let{cwd:e}=await q("/api/github/projects",{action:"open",repository:v});t(e)}catch(e){I(e instanceof Error?e.message:String(e))}finally{C(!1)}}}if((0,i.useEffect)(()=>{d(!0),A()},[A]),(0,i.useEffect)(()=>{if(!o||c)return;let e=l.current;return e?.showModal(),()=>e?.close()},[o,c]),(0,i.useEffect)(()=>{let e;if(!L||c)return;let t=!1,r=async()=>{try{let e=await q("/api/github/projects");if(t)return;if(h(e),e.connected)return void await A();if(e.device?.state!=="pending")return}catch(e){t||I(e instanceof Error?e.message:String(e));return}t||(e=window.setTimeout(r,3e3))};return e=window.setTimeout(r,1500),()=>{t=!0,clearTimeout(e)}},[L,c,A]),!o)return null;if(c)return(0,n.jsx)(O,{onCancel:()=>u(!1),onSelect:t,busy:r,error:a});let _=f.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(g.toLowerCase())),D=N??a??p?.device?.error;return(0,F.createPortal)((0,n.jsx)("dialog",{ref:l,className:U().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),z||e()},children:(0,n.jsxs)("form",{onSubmit:W,className:U().form,children:[(0,n.jsxs)("header",{className:U().header,children:[(0,n.jsx)("h2",{id:"cloud-project-title",children:s("cloudProjects.title")}),(0,n.jsx)("p",{children:s("cloudProjects.description")})]}),(0,n.jsxs)("div",{className:U().sources,children:[(0,n.jsx)("span",{className:U().activeSource,children:s("cloudProjects.github")}),(0,n.jsx)("button",{type:"button",onClick:()=>u(!0),disabled:z,children:s("cloudProjects.serverFolder")})]}),(0,n.jsxs)("div",{className:U().body,children:[(0,n.jsxs)("section",{className:U().account,"aria-label":s("cloudProjects.account"),children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("strong",{children:p?.connected?p.login:s("cloudProjects.connectTitle")}),(0,n.jsx)("p",{children:p?.connected?s("cloudProjects.connected"):s("cloudProjects.connectHelp")})]}),p?.connected?(0,n.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void A(),disabled:y||z,children:s("cloudProjects.refresh")}):(0,n.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void P(),disabled:y||k||L||z,children:k||L?s("cloudProjects.waiting"):s("cloudProjects.connect")})]}),L&&(0,n.jsxs)("div",{className:U().login,role:"status",children:[(0,n.jsx)("p",{children:s("cloudProjects.deviceHelp")}),p.device?.code?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:U().codeRow,children:[(0,n.jsx)("code",{children:p.device.code}),(0,n.jsx)("button",{type:"button",className:U().secondary,onClick:()=>{navigator.clipboard.writeText(p.device.code).then(()=>M(!0)).catch(()=>I(s("cloudProjects.copyFailure")))},children:T?s("cloudProjects.copied"):s("cloudProjects.copyCode")})]}),(0,n.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:U().loginLink,children:s("cloudProjects.openLogin")}),(0,n.jsx)("small",{children:s("cloudProjects.permissionHelp")})]}):(0,n.jsx)("p",{children:s("cloudProjects.preparingCode")})]}),p?.connected&&(0,n.jsxs)("section",{className:U().repositories,"aria-label":s("cloudProjects.repositories"),children:[(0,n.jsx)("label",{htmlFor:"cloud-repo-search",children:s("cloudProjects.search")}),(0,n.jsx)("input",{id:"cloud-repo-search",value:g,onChange:e=>{x(e.target.value),E(50)},placeholder:s("cloudProjects.searchPlaceholder"),type:"search",disabled:z}),y?(0,n.jsx)("p",{role:"status",children:s("cloudProjects.loading")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("ul",{className:U().list,children:_.slice(0,$).map(e=>(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button",className:U().repo,"aria-pressed":v===e.fullName,disabled:z,onClick:()=>b(e.fullName),children:[(0,n.jsxs)("span",{className:U().repoHeading,children:[(0,n.jsx)("strong",{children:e.fullName}),(0,n.jsx)("small",{children:e.private?s("cloudProjects.private"):s("cloudProjects.public")})]}),e.description&&(0,n.jsx)("span",{className:U().repoDescription,children:e.description})]})},e.fullName))}),!_.length&&(0,n.jsx)("p",{children:s("cloudProjects.empty")}),_.length>$&&(0,n.jsx)("button",{type:"button",className:U().secondary,onClick:()=>E(e=>e+50),children:s("cloudProjects.more")})]})]}),(0,n.jsxs)("div",{className:U().repositoryInput,children:[(0,n.jsx)("label",{htmlFor:"cloud-repository",children:s("cloudProjects.urlLabel")}),(0,n.jsx)("input",{id:"cloud-repository",value:v,onChange:e=>b(e.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:z,"aria-describedby":"cloud-repo-help"}),(0,n.jsx)("small",{id:"cloud-repo-help",children:s("cloudProjects.publicHelp")})]}),D&&(0,n.jsxs)("div",{className:U().error,role:"alert",children:[(0,n.jsx)("strong",{children:s("cloudProjects.error")}),(0,n.jsx)("p",{children:D}),(0,n.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void A(),disabled:z,children:s("cloudProjects.refresh")})]}),S&&(0,n.jsx)("p",{role:"status",className:U().progress,children:s("cloudProjects.openingHelp")})]}),(0,n.jsxs)("footer",{className:U().footer,children:[(0,n.jsx)("button",{type:"button",className:U().secondary,onClick:e,disabled:z,children:s("i18n.cancel")}),(0,n.jsx)("button",{type:"submit",className:U().primary,disabled:z||!v.trim(),children:z?s("cloudProjects.opening"):s("cloudProjects.open")})]})]})}),document.body)}function V({label:e="CUELO",markSize:t=22,gap:r=10,style:i,labelStyle:a}){return(0,n.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:r,minWidth:0,color:"var(--text)",...i},children:[(0,n.jsxs)("svg",{viewBox:"0 0 100 100",width:t,height:t,"aria-hidden":"true",style:{flexShrink:0},children:[(0,n.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,n.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:"var(--font-heading)",fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...a},children:e})]})}var J=r(2730);let G={ko:{"translator.tab":"통역","translator.title":"통역","translator.back":"대화로","translator.panelHint":"통역을 시작하면 ChatGPT 계정의 Codex 라이브 통화로 두 사람의 말을 서로의 언어로 바로 소리 내어 옮깁니다. 작업 세션과 하네스 규칙을 거치지 않고, 기록은 저장하지 않습니다.","translator.open":"통역 화면 열기","translator.me":"나","translator.them":"상대","translator.myLanguage":"내 언어","translator.theirLanguage":"상대 언어","translator.swap":"두 언어 바꾸기","translator.clear":"지우기","translator.start":"통역 시작","translator.stop":"통역 끝내기","translator.empty":"통역 시작을 누르고 폰을 두 사람 사이에 두세요. 누가 말하든 상대 언어로 바로 옮겨 말합니다.","translator.connecting":"연결 중…","translator.live":"듣는 중 \xb7 그냥 말하세요","translator.unsupported":"이 브라우저는 실시간 통화(WebRTC\xb7마이크)를 지원하지 않습니다. 폰에서는 Chrome이나 Safari로 여세요.","translator.insecure":"마이크는 HTTPS 주소에서만 켜집니다.","translator.micDenied":"마이크 권한이 막혀 있습니다. 브라우저 설정에서 이 주소의 마이크를 허용하세요.","translator.micUnavailable":"마이크를 켜지 못했습니다. 다른 앱이 쓰고 있지 않은지 확인하세요.","translator.auth":"Codex 로그인이 없거나 만료됐습니다. 모델 설정에서 ChatGPT 계정으로 다시 로그인하세요.","translator.upstream":"Codex 라이브 연결이 끊겼습니다: {error}","translator.failed":"통역을 시작하지 못했습니다: {error}","translator.original":"원문","translator.translationPending":"통역 중…","translator.conversation":"통역 기록"},en:{"translator.tab":"Interpret","translator.title":"Interpreter","translator.back":"Back to chat","translator.panelHint":"Start interpreting and a Codex live call on your ChatGPT account speaks each person's words in the other's language right away. It bypasses work sessions and harness rules, and nothing is saved.","translator.open":"Open interpreter","translator.me":"Me","translator.them":"Them","translator.myLanguage":"My language","translator.theirLanguage":"Their language","translator.swap":"Swap languages","translator.clear":"Clear","translator.start":"Start interpreting","translator.stop":"Stop interpreting","translator.empty":"Press Start interpreting and put the phone between you. Whoever speaks is interpreted into the other language right away.","translator.connecting":"Connecting…","translator.live":"Listening \xb7 just talk","translator.unsupported":"This browser cannot make live calls (WebRTC and microphone). On a phone, open this page in Chrome or Safari.","translator.insecure":"The microphone only works on an HTTPS address.","translator.micDenied":"Microphone access is blocked. Allow the microphone for this address in the browser settings.","translator.micUnavailable":"The microphone could not be opened. Check that no other app is using it.","translator.auth":"The Codex sign-in is missing or expired. Sign in again with your ChatGPT account in model settings.","translator.upstream":"The Codex live connection dropped: {error}","translator.failed":"Interpreting could not start: {error}","translator.original":"Original","translator.translationPending":"Interpreting…","translator.conversation":"Interpretation log"},"zh-CN":{"translator.tab":"口译","translator.title":"口译","translator.back":"返回对话","translator.panelHint":"开始口译后,通过 ChatGPT 账号的 Codex 实时通话,把双方的话立即用对方的语言说出来。不经过工作会话和规则,也不保存记录。","translator.open":"打开口译","translator.me":"我","translator.them":"对方","translator.myLanguage":"我的语言","translator.theirLanguage":"对方语言","translator.swap":"交换语言","translator.clear":"清除","translator.start":"开始口译","translator.stop":"结束口译","translator.empty":"按开始口译,把手机放在两人之间。无论谁说话,都会立即译成对方的语言说出来。","translator.connecting":"连接中…","translator.live":"正在听 \xb7 直接说话","translator.unsupported":"此浏览器不支持实时通话(WebRTC 和麦克风)。手机请用 Chrome 或 Safari 打开。","translator.insecure":"麦克风只能在 HTTPS 地址上使用。","translator.micDenied":"麦克风权限被阻止。请在浏览器设置中允许此地址使用麦克风。","translator.micUnavailable":"无法打开麦克风。请确认没有其他应用正在使用。","translator.auth":"Codex 登录不存在或已过期。请在模型设置中用 ChatGPT 账号重新登录。","translator.upstream":"Codex 实时连接已断开:{error}","translator.failed":"无法开始口译:{error}","translator.original":"原文","translator.translationPending":"口译中…","translator.conversation":"口译记录"}};function Y(){let{locale:e}=(0,R.s)();return{tt:(0,i.useCallback)((t,r)=>(0,J.u0)(e,t,G,r),[e]),locale:e}}let Z="omp-web:unread-session-ids",X="omp-web:pinned-session-ids",Q="omp-web:removed-projects";function ee(e,t){return{minHeight:t?36:30,padding:"3px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:e?"var(--text-dim)":"var(--text-muted)",cursor:e?"default":"pointer",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.3,textAlign:"left",whiteSpace:"normal",overflowWrap:"anywhere"}}function et(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function er({text:e,style:t}){return(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...t},children:(0,n.jsx)("span",{style:{unicodeBidi:"plaintext"},children:e})})}function en({open:e,children:t,style:r}){let[a,s]=(0,i.useState)(e),[l,o]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,r;return e?(s(!0),o(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>o(!0))})):(o(!1),r=setTimeout(()=>s(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),r&&clearTimeout(r)}},[e]),a)?(0,n.jsx)("div",{style:{...r,opacity:+!!l,transform:l?"translateY(0) scale(1)":"translateY(-8px) scale(0.96)",transformOrigin:"top center",transition:"opacity 140ms ease, transform 140ms ease",pointerEvents:e?"auto":"none"},children:t}):null}let ei="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function ea(){let[e,t]=(0,i.useState)(!1),[r,a]=(0,i.useState)(!1),s=(0,i.useRef)(null),l=function(e,t){let[r,n]=(0,i.useState)(e),a=(0,i.useRef)(null),s=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void n(e);s.current=0;let r=4*e.length,i=()=>{s.current+=1;let t=Math.floor(s.current/r*e.length);n(e.split("").map((e,r)=>" "===e?" ":r<t?e:ei[Math.floor(Math.random()*ei.length)]).join("")),s.current<r?a.current=requestAnimationFrame(i):n(e)};return a.current=requestAnimationFrame(i),()=>{a.current&&cancelAnimationFrame(a.current)}},[e,t]),r}(e?"0.10.22/18.11.3":"CUELO",r),o=(0,i.useCallback)(e=>{t(e),a(!0),setTimeout(()=>a(!1),(e?6:8)*4*(1e3/60)+100)},[]),d=(0,i.useCallback)(()=>{s.current&&clearTimeout(s.current);let t=!e;o(t),t&&(s.current=setTimeout(()=>o(!1),3e3))},[e,o]);return(0,i.useEffect)(()=>()=>{s.current&&clearTimeout(s.current)},[]),(0,n.jsx)("button",{className:"navigator-brand",onClick:d,style:{display:"flex",alignItems:"center",background:"none",border:"none",padding:0,cursor:"default",color:e?"var(--accent)":"var(--text)",flex:"0 1 auto",minWidth:0,overflow:"hidden"},children:(0,n.jsx)(V,{label:l,labelStyle:e?{fontFamily:"var(--font-mono)",fontSize:12,letterSpacing:"-0.02em",textOverflow:"ellipsis"}:void 0})})}async function es(e){let t=await fetch("/api/projects",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:e})});if(!t.ok)throw Error(`HTTP ${t.status}`)}function el({selectedSessionId:e,optimisticSession:t,onSelectSession:r,onNewSession:a,initialSessionId:s,skipInitialProjectSelection:l,onInitialRestoreDone:o,refreshKey:d,onSessionDeleted:c,selectedCwd:u,onCwdChange:p,onBackgroundTaskDone:h,translatorPanel:f,translatorActive:m=!1,onTranslatorActiveChange:g}){let x,{tt:v}=Y(),{t:b,locale:y}=(0,R.s)(),w=W(),[M,$]=(0,i.useState)([]),E=t&&!M.some(e=>e.id===t.id)?[t,...M]:M,[L,z]=(0,i.useState)(!0),[A,P]=(0,i.useState)(null),[F,_]=(0,i.useState)(null),[D,H]=(0,i.useState)(""),[B,U]=(0,i.useState)(!1),[q,V]=(0,i.useState)(""),[J,G]=(0,i.useState)("projects"),[ei,ed]=(0,i.useState)(()=>new Set),[eh,ef]=(0,i.useState)(()=>new Set),[eg,ex]=(0,i.useState)(null),[ev,eb]=(0,i.useState)(null),[ey,ew]=(0,i.useState)({version:1,projects:[]}),[ek,ej]=(0,i.useState)(!1),[eS,eC]=(0,i.useState)(!1),[eN,eI]=(0,i.useState)(!1),[eT,eM]=(0,i.useState)(null),[e$,eR]=(0,i.useState)(""),[eE,eL]=(0,i.useState)(!1),[ez,eA]=(0,i.useState)(null),[eP,eW]=(0,i.useState)(""),[eF,e_]=(0,i.useState)(!1),[eD,eH]=(0,i.useState)(null),[eO,eB]=(0,i.useState)(!1),[eU,eq]=(0,i.useState)(null),[eK,eV]=(0,i.useState)(!1),[eJ,eG]=(0,i.useState)(!1),[eY,eZ]=(0,i.useState)(""),[eX,eQ]=(0,i.useState)(null),[e0,e1]=(0,i.useState)(!1),[e2,e4]=(0,i.useState)(null),e5=(0,i.useRef)(null),e8=(0,i.useRef)(null),e6=(0,i.useRef)(null),e3=(0,i.useRef)(!1),e7=(0,i.useRef)(!1),[e9,te]=(0,i.useState)(!1),[tt,tr]=(0,i.useState)(()=>new Set),[tn,ti]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(Z);if(!e)return new Set;let t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(e=>"string"==typeof e));return new Set}catch{return new Set}})()),[ta,ts]=(0,i.useState)(()=>new Set),tl=(0,i.useRef)(new Set),to=(0,i.useRef)(!1),td=(0,i.useRef)(null);(0,i.useEffect)(()=>{ts(function(){try{let e=window.localStorage.getItem(X);if(!e)return new Set;let t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(e=>"string"==typeof e)):new Set}catch{return new Set}}())},[]);let tc=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/projects",{cache:"no-store",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw Error(`HTTP ${e.status}`);ew(await e.json())}catch{ew({version:1,projects:[]})}finally{ej(!0)}},[]);(0,i.useEffect)(()=>{tc()},[tc,d]),(0,i.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(Q)}catch{return}if(!e)return;let t=[];try{let r=JSON.parse(e);Array.isArray(r)&&(t=r.filter(e=>"string"==typeof e))}catch{t=[]}(async()=>{try{for(let e=0;e<t.length;e+=500){let r=t.slice(e,e+500);await es(r.map(e=>({key:N(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(Q)}catch{}await tc()})()},[tc]);let tu=(0,i.useCallback)(async e=>{if(e7.current)throw Error("Project update in progress");e7.current=!0,eL(!0);try{await es(e),await tc()}finally{e7.current=!1,eL(!1)}},[tc]);(0,i.useEffect)(()=>{eT&&e6.current?.select()},[eT]);let tp=(0,i.useCallback)(async(e=!1,t=!1)=>{try{e&&z(!0);let r=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!r.ok)throw Error(`HTTP ${r.status}`);let n=await r.json();$(n.sessions),to.current||tr(new Set(n.runningSessionIds??[])),P(null),e||(te(!0),td.current&&clearTimeout(td.current),td.current=setTimeout(()=>te(!1),2e3))}catch(e){P(String(e))}finally{e&&z(!1)}},[]),th=(0,i.useCallback)(e=>{ti(t=>{if(!t.has(e))return t;let r=new Set(t);return r.delete(e),r}),ts(t=>{if(!t.has(e))return t;let r=new Set(t);return r.delete(e),r}),c?.(e),tp()},[tp,c]),[tf,tm]=(0,i.useState)(null),[tg,tx]=(0,i.useState)(!1),[tv,tb]=(0,i.useState)(null),ty=(0,i.useCallback)(()=>{tg||(tm(null),tb(null))},[tg]),tw=(0,i.useCallback)(async e=>{tx(!0),tb(null);let t=[],r=[],n=[];for(let i of e)if(!i.transient)try{let e=await fetch(`/api/sessions/${encodeURIComponent(i.id)}?skipRunning=1`,{method:"DELETE"});if(409===e.status){r.push(i.id);continue}if(!e.ok)throw Error(`HTTP ${e.status}`);t.push(i.id)}catch{n.push(i.name?.trim()||i.id.slice(0,8))}if(r.length>0&&(to.current=!0,tr(e=>{if(r.every(t=>e.has(t)))return e;let t=new Set(e);for(let e of r)t.add(e);return t})),t.length>0){let e=new Set(t),r=r=>t.some(e=>r.has(e))?new Set([...r].filter(t=>!e.has(t))):r;for(let e of(ti(r),ts(r),t))c?.(e)}(await tp(),tx(!1),n.length>0)?tb(b("sidebar.clearSessionsFailed",{count:n.length,names:n.join(", ")})):r.length>0||tm(null)},[tp,c,b]),[tk,tj]=(0,i.useState)(0),tS=(0,i.useCallback)(()=>{tj(e=>e+1),tp()},[tp]),tC=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!tC.current;tC.current=!0,tp(e,!e)},[tp,d]),(0,i.useEffect)(()=>{try{G(function(e,t){return"gpt6"===e?"projects":"string"==typeof e&&k.includes(e)?e:"1"===t?"priority":"projects"}(window.localStorage.getItem(j),window.localStorage.getItem(S)))}catch{}},[]);let tN=(0,i.useCallback)(e=>{G(e);try{window.localStorage.setItem(j,e),window.localStorage.setItem(S,"priority"===e?"1":"0")}catch{}},[]);(0,i.useEffect)(()=>{if("priority"!==J)return;let e=()=>{"visible"===document.visibilityState&&tp(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[tp,J]),(0,i.useEffect)(()=>{try{0===tn.size?window.localStorage.removeItem(Z):window.localStorage.setItem(Z,JSON.stringify([...tn]))}catch{}},[tn]),(0,i.useEffect)(()=>{try{0===ta.size?window.localStorage.removeItem(X):window.localStorage.setItem(X,JSON.stringify([...ta]))}catch{}},[ta]);let tI=(0,i.useCallback)(e=>{ts(t=>{let r=new Set(t);return r.has(e)?r.delete(e):r.add(e),r})},[]);(0,i.useEffect)(()=>{let e=!1,t=null,r=null,n=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let a=new AbortController;r?.abort(),r=a;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:a.signal});if(!t.ok)return;let n=await t.json();if(e||r!==a)return;to.current=!0,tr(new Set(n.runningSessionIds??[]))}catch{}finally{r===a&&(r=null),n(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},a=()=>{"visible"===document.visibilityState?i():(n(),r?.abort(),r=null)};return i(),document.addEventListener("visibilitychange",a),()=>{e=!0,n(),r?.abort(),document.removeEventListener("visibilitychange",a)}},[]),(0,i.useEffect)(()=>{let t=tl.current,r=[...t].filter(t=>!tt.has(t)&&t!==e),n=[...tt].filter(e=>!t.has(e));(r.length>0||n.length>0)&&ti(e=>{let t=new Set(e);return tt.forEach(e=>t.delete(e)),r.forEach(e=>t.add(e)),t});let i=n.some(e=>!M.some(t=>t.id===e));(r.length>0||i)&&tp(!1,!0),r.length>0&&h?.(),tl.current=tt},[tt,e,M,tp,h]),(0,i.useEffect)(()=>{e&&ti(t=>{if(!t.has(e))return t;let r=new Set(t);return r.delete(e),r})},[e]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&H(e.home),U(!0===e.cloudProjects)}).catch(()=>{})},[]);let tT=(0,i.useRef)(!1),tM=(0,i.useCallback)(e=>{if(!e)return null;if(eU&&eU.forCwd===e||eU?.worktrees.some(t=>t.path===e))return eU.projectRoot;let t=E.find(t=>t.cwd===e);return t?.projectRoot??e},[eU,E]),t$=(0,i.useRef)(null);(0,i.useEffect)(()=>{t$.current!==F&&(t$.current=F,p?.(F,tM(F)))},[F,p,tM]);let tR=(0,i.useRef)(null);(0,i.useEffect)(()=>{u&&u!==tR.current&&(tR.current=u,_(u))},[u]);let[tE,tL]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!F)return void eq(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(F)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void eq(null);eq({forCwd:F,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||eq(null)}),()=>{e=!0}},[F,tE,d]),(0,i.useEffect)(()=>{if(0!==M.length&&!l&&null===F){if(s&&!tT.current){tT.current=!0;let e=M.find(e=>e.id===s);if(e){_(e.cwd),r(e,!0);return}o?.()}if(!ek)return;let e=new Map(ey.projects.map(e=>[e.key,e])),t=T(M.length>0?I(M):[],ey.projects).filter(t=>!e.get(N(t))?.hidden);t.length>0&&_(t[0])}},[M,F,s,l,r,o,ey,ek]);let tz=(0,i.useCallback)(async e=>{let t=e.trim();if(t&&!eO){eB(!0),eH(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),r=await e.json().catch(()=>({}));if(!e.ok||r.error)return void eH(r.error??b("workspace.unable"));let n=r.cwd??t,i=N(n),a=ey.projects.find(e=>e.key===i);if(a?.hidden===!0)try{await tu([{key:i,path:n,hidden:!1}])}catch{}_(n),e_(!1)}catch{eH(b("workspace.unable"))}finally{eB(!1)}}},[tu,eO,ey.projects,b]),tA=(0,i.useCallback)(()=>{e_(!0),eH(null)},[]),tP=(0,i.useCallback)(async()=>{let e=eY.trim();if(e&&!e0&&eU){e1(!0),eQ(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eU.projectRoot,branch:e})}),r=await t.json().catch(()=>({}));if(!t.ok||r.error||!r.path)return void eQ(r.error??`HTTP ${t.status}`);eG(!1),eZ(""),eV(!1),eq(t=>t?{...t,forCwd:r.path,worktrees:[...t.worktrees,{path:r.path,branch:e,isMain:!1}]}:t),_(r.path),tL(e=>e+1)}catch(e){eQ(e instanceof Error?e.message:String(e))}finally{e1(!1)}}},[eY,e0,eU]),tW=(0,i.useCallback)(async(e,t)=>{if(eU&&!e0){e1(!0),eQ(null);try{let r=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eU.projectRoot,path:e,force:t})}),n=await r.json().catch(()=>({}));if(!r.ok){if(n.dirty&&!t)return void e4(e);eQ(n.error??`HTTP ${r.status}`);return}e4(null),F===e&&_(eU.projectRoot),tL(e=>e+1)}catch(e){eQ(e instanceof Error?e.message:String(e))}finally{e1(!1)}}},[eU,e0,F]);(0,i.useEffect)(()=>{let e=e=>{e5.current&&!e5.current.contains(e.target)&&(eb(null),eV(!1),eG(!1),eZ(""),eQ(null),e4(null),eW(""),ex(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tF=(0,i.useCallback)(e=>{e.cwd&&_(e.cwd),r(e)},[r]),t_=(0,i.useCallback)((e=F)=>{if(!e)return;let t="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;_(e),a?.(t,e)},[F,a]),[tD,tH]=(0,i.useState)(!1),[tO,tB]=(0,i.useState)(null),tU=(0,i.useCallback)(async()=>{tH(!0),tB(null);try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json().catch(()=>({}));if(!e.ok||!t.cwd)throw Error(t.error??`HTTP ${e.status}`);t_(t.cwd)}catch(e){tB(b("sidebar.newScratchSessionFailed",{error:e instanceof Error?e.message:String(e)}))}finally{tH(!1)}},[t_,b]),tq=(0,i.useCallback)(e=>{ef(t=>{let r=new Set(t);return r.has(e)?r.delete(e):r.add(e),r})},[]),tK=tM(F),tV=null===tK?null:N(tK),tJ=(0,i.useMemo)(()=>new Map(ey.projects.map(e=>[e.key,e])),[ey.projects]),tG=I(E);if(null!==tK){let e=N(tK);tG.some(t=>N(t)===e)||tG.unshift(tK)}let tY=T(tG,ey.projects),tZ=tY.filter(e=>eS||!tJ.get(N(e))?.hidden),tX=tY.some(e=>tJ.get(N(e))?.hidden),tQ=()=>{eb(null),eV(!1),eG(!1),eZ(""),eQ(null),e4(null),eW("")},t0=async(e,t)=>{tQ();try{await tu([{key:N(e),path:e,hidden:t}]),t&&tV&&tV===N(e)&&_(null),t||tY.some(t=>N(t)!==N(e)&&tJ.get(N(t))?.hidden)||eC(!1)}catch{}},t1=async e=>{if(e3.current){e3.current=!1,eM(null);return}let t=e$.trim();if(t===(tJ.get(N(e))?.alias??""))return void eM(null);eA(null);try{await tu([{key:N(e),path:e,alias:t||null}]),eM(null)}catch{eA(b("sidebar.projectUpdateFailed"))}},t2=async(e,t)=>{if(q)return;let r=tZ.indexOf(e),n=r+t;if(r<0||n<0||n>=tZ.length)return;let i=new Set(tZ),a=tY.map((e,t)=>i.has(e)?t:-1).filter(e=>e>=0),s=[...tY],l=a[r],o=a[n];[s[l],s[o]]=[s[o],s[l]],tQ();try{await tu(s.map((e,t)=>({key:N(e),path:e,order:t})))}catch{}},t4=new Map;for(let e of E){let t=e.projectRoot??e.cwd;if(!t)continue;let r=N(t),n=t4.get(r);n?n.push(e):t4.set(r,[e])}let t5=(0,i.useMemo)(()=>{let e=new Map;for(let t of E){let r=t.projectRoot??t.cwd;if(!r)continue;let n=N(r),i=e.get(n);i||(i={running:0,unread:0},e.set(n,i)),tt.has(t.id)&&i.running++,tn.has(t.id)&&i.unread++}return e},[E,tt,tn]),t8=q.trim().toLowerCase(),t6=q.length>0,t3=tZ.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,r=N(e),n=tJ.get(r),i=n?.alias??t,a=(t4.get(r)??[]).slice().sort((e,t)=>{let r=Number(ta.has(t.id))-Number(ta.has(e.id));return 0!==r?r:t.modified.localeCompare(e.modified)});if(!t8)return[{project:e,key:r,name:i,sessions:a,hidden:n?.hidden===!0}];let s=i.toLowerCase().includes(t8)||t.toLowerCase().includes(t8),l=a.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(t8));return s||0!==l.length?[{project:e,key:r,name:i,sessions:s?a:l,hidden:n?.hidden===!0}]:[]}),t7=[],t9=[];for(let e of t3){let t=e.key===tV||(t5.get(e.key)?.running??0)>0;(function(e){let t=e.trim().replace(/\\/g,"/").toLowerCase();return!!(/^[a-z]:\/?$/.test(t)||"/"===t||/(^|\/)appdata\/local\/temp(\/|$)/.test(t)||/^\/(?:var\/|private\/)?tmp(?:\/|$)/.test(t)||/^[a-z]:\/(?:tmp|temp)(?:\/|$)/.test(t)||/(^|\/)(?:users|home)\/[^/]+\/\.omp(\/|$)/.test(t))||t.split("/").some(e=>C.some(t=>e.startsWith(t)))})(e.project)&&!t?t9.push(e):t7.push(e)}let re={running:0,unread:0};for(let e of t9){let t=t5.get(e.key);t&&(re.running+=t.running,re.unread+=t.unread)}let rt=t6||eN,rr=[...t7.map(e=>({kind:"project",group:e})),...t9.length>0?[{kind:"temporary"}]:[],...rt?t9.map(e=>({kind:"project",group:e})):[]],rn=function(e){let t=new Map;for(let r of e){let e=r.toLowerCase();t.set(e,(t.get(e)??0)+1)}return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}(rr.flatMap(e=>"project"===e.kind?[e.group.name]:[])),ri=(0,i.useMemo)(()=>(function(e,t,r,n,i="Priority",a=new Set,s="Pinned"){let l=e.filter(e=>!e.transient).slice().sort((e,t)=>{let r=Date.parse(e.modified),n=Date.parse(t.modified);return(Number.isFinite(n)?n:0)-(Number.isFinite(r)?r:0)}),o=l.filter(e=>a.has(e.id)),d=[],c=new Map,u=0;for(let e of l){if(a.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let r=new Date(e.modified);if(u>=10)continue;u+=1;let n=[r.getFullYear(),String(r.getMonth()+1).padStart(2,"0"),String(r.getDate()).padStart(2,"0")].join("-"),i=c.get(n);i?i.push(e):c.set(n,[e])}let p=[];for(let e of(o.length>0&&p.push({key:"pinned",label:s,running:!1,sessions:o}),d.length>0&&p.push({key:"priority",label:i,running:!0,sessions:d}),[...c.keys()].sort().reverse()))p.push({key:e,label:function(e,t,r){let[n,i,a]=e.split("-").map(Number),s=new Date(n,i-1,a),l=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(s.getFullYear(),s.getMonth(),s.getDate()))/864e5);return 0===l||1===l?new Intl.RelativeTimeFormat(r,{numeric:"auto"}).format(-l,"day"):l>=0&&l<7?new Intl.DateTimeFormat(r,{weekday:"long"}).format(s):new Intl.DateTimeFormat(r,{month:"short",day:"numeric"}).format(s)}(e,r,n),running:!1,sessions:c.get(e)??[]});return p})(E,tt,new Date,y,b("navigator.priority"),ta,b("sidebar.pinned")),[y,ta,tt,E,b]),ra=!!(eU?.isGit&&eU.isTopLevel&&F&&tK===eU.projectRoot),rs=eU?.worktrees.find(e=>e.path===F)??eU?.worktrees.find(e=>e.isMain),rl=(eU?.worktrees.length??0)>=8,ro=rl&&eP.trim()?(eU?.worktrees??[]).filter(e=>(e.branch??et(e.path,D)).toLowerCase().includes(eP.trim().toLowerCase())):eU?.worktrees??[],rd=(()=>{if(!tf)return[];let e="project"===tf.kind?t4.get(N(tf.project))??[]:ri.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),rc=rd.filter(e=>!tt.has(e.id)),ru=e=>{let t=new Set;for(let r of e)r.transient||tt.has(r.id)||t.has(r.id)||t.add(r.id);return t.size},rp=void 0!==f&&m;return(0,n.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[eF&&(0,n.jsx)(B?K:O,{busy:eO,error:eD,onCancel:()=>{e_(!1),eH(null)},onSelect:e=>void tz(e)}),tf&&(0,n.jsx)(eo,{scope:tf,eligible:rc.length,runningExcluded:rd.length-rc.length,busy:tg,error:tv,onCancel:ty,onConfirm:()=>void tw(rc)}),(0,n.jsx)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,n.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,n.jsx)(ea,{}),(0,n.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,n.jsx)("button",{className:"navigator-icon-action",onClick:()=>t_(),disabled:!F,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:"1px solid var(--border)",color:F?"var(--text-muted)":"var(--text-dim)",cursor:F?"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:F?b("sidebar.newSessionTitle",{path:F}):b("sidebar.selectProject"),"aria-label":F?b("sidebar.newSessionTitle",{path:F}):b("sidebar.selectProject"),onMouseEnter:e=>{F&&(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=F?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)"},children:(0,n.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,n.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,n.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]})}),(0,n.jsx)("button",{className:`navigator-icon-action${e9?" is-success":""}`,onClick:()=>tp(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:e9?"rgba(74,222,128,0.18)":"var(--bg-hover)",border:`1px solid ${e9?"rgba(74,222,128,0.4)":"var(--border)"}`,color:e9?"#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:e=>{e9||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{e9||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)")},title:b("sidebar.refresh"),children:e9?(0,n.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,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,n.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,n.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,n.jsx)("path",{d:"M3 3v5h5"})]})})]})]})}),B&&!rp&&(0,n.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:tA,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:b("cloudProjects.launch")}),(0,n.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,n.jsxs)("div",{className:"navigator-mode-switcher",role:"toolbar","aria-label":b("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:[k.map(e=>{let t="projects"===e?b("sidebar.projects"):b("navigator.priority"),r=!rp&&J===e;return(0,n.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:t}),"aria-pressed":r,"aria-controls":`navigator-${e}-panel`,"data-navigator-mode":e,onClick:()=>{tN(e),rp&&g?.(!1)},style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:r?"var(--bg-selected)":"transparent",color:r?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:r?600:500,whiteSpace:"nowrap"},children:t},e)}),void 0!==f&&(0,n.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:v("translator.tab")}),"aria-pressed":rp,"aria-controls":"navigator-translator-panel","data-navigator-mode":"translator",onClick:()=>g?.(!rp),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:rp?"var(--bg-selected)":"transparent",color:rp?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:rp?600:500,whiteSpace:"nowrap"},children:v("translator.tab")})]}),!rp&&"projects"===J&&(0,n.jsx)("button",{type:"button",onClick:()=>eC(e=>!e),disabled:!tX,title:b("sidebar.projectShowHidden"),"aria-label":b("sidebar.projectShowHidden"),"aria-pressed":eS,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:5,background:eS?"var(--bg-selected)":"transparent",color:eS?"var(--accent)":"var(--text-dim)",cursor:tX?"pointer":"default",opacity:tX?1:.45,flexShrink:0},children:(0,n.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,n.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,n.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!eS&&(0,n.jsx)("path",{d:"m4 4 16 16"})]})}),!rp&&"projects"===J&&(0,n.jsx)("button",{className:"navigator-add-project",type:"button",onClick:tA,title:b("sidebar.addProject"),"aria-label":b("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:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},children:(0,n.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,n.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,n.jsx)("path",{d:"M15.5 10.5v5M13 13h5"})]})})]}),rp&&f,!rp&&"projects"===J&&(0,n.jsxs)("label",{className:"navigator-search",style:{position:"relative",display:"block",margin:"0 8px 8px"},children:[(0,n.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,n.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,n.jsx)("path",{d:"m20 20-3.5-3.5"})]}),(0,n.jsx)("input",{className:"navigator-search-input",type:"search",value:q,onChange:e=>V(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),V(""),e.currentTarget.blur())},placeholder:b("sidebar.searchProjectsAndSessions"),"aria-label":b("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}})]}),!rp&&"projects"===J&&(0,n.jsxs)("div",{id:"navigator-projects-panel",className:"navigator-session-list",style:{flex:"1 1 auto",overflowY:"auto",minHeight:80,padding:"0 6px 10px"},children:[(L||!ek)&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),A&&(0,n.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:A}),ez&&(0,n.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:ez}),!L&&ek&&!A&&0===t3.length&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:t8?b("sidebar.noMatchingProjects"):b("sidebar.noSessions")}),!L&&ek&&!A&&rr.map(t=>{let r,i,a;if("temporary"===t.kind)return(0,n.jsx)("div",{className:"navigator-project-group",children:(0,n.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":rt,title:b("sidebar.temporaryProjects"),onClick:()=>eI(e=>!e),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,n.jsx)("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,flexShrink:0,color:"var(--text-dim)"},children:(0,n.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:rt?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.12s"},children:(0,n.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.temporaryProjects")}),(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10,flexShrink:0},children:t9.length}),em(re,b)]})},"navigator-temporary-projects");let{project:s,key:l,name:o,sessions:d,hidden:c}=t.group,u=l===tV,p=rn.has(o.toLowerCase())&&et((i=Math.max((r=s.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),r.lastIndexOf("/")))<=0?"":r.slice(0,i),D)||null,h=!eh.has(s)&&!t8,f=ei.has(s),m=eT===s,g=tZ.indexOf(s),x=eE||t6||g<=0,v=eE||t6||g>=tZ.length-1,y=function(e){let t=new Map;for(let r of e)t.set(r.id,{session:r,children:[]});let r=new Map;for(let t of e)t.parentSessionId&&r.set(t.id,t.parentSessionId);let n=[];for(let e of t.values()){let i=function(e){let n=r.get(e),i=new Set;for(;n&&!i.has(n);){if(i.add(n),t.has(n))return n;n=r.get(n)}return null}(e.session.id);i?t.get(i).children.push(e):n.push(e)}let i=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>i(e.children))};return i(n),n}(f?d:d.slice(0,5)),k=d.length>5;return(0,n.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:h?3:9},children:[(0,n.jsxs)("div",{className:`navigator-project-row${u?" is-selected":""}`,ref:ev===s?e5:void 0,onMouseEnter:()=>ex(s),onMouseLeave:()=>ex(e=>e===s&&ev!==s?null:e),style:{display:"flex",alignItems:"center",minHeight:34,position:"relative",borderRadius:6,background:u?"var(--bg-hover)":"transparent",opacity:c?.55:1},children:[(0,n.jsx)("button",{type:"button",onClick:()=>tq(s),title:h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-label":h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-expanded":!h,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,n.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:h?"rotate(-90deg)":"rotate(0deg)",transition:"transform 0.12s"},children:(0,n.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),m?(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px"},children:[(0,n.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,n.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,n.jsx)("input",{ref:e6,value:e$,onChange:e=>eR(e.target.value),onBlur:()=>void t1(s),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),e3.current=!0,eM(null))},"aria-label":b("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,n.jsxs)("button",{className:"navigator-project-name",type:"button",onClick:()=>_(s),title:s,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:u?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:u?600:500},children:[(0,n.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:u?"var(--accent)":"var(--text-dim)"},children:(0,n.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,n.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o}),null===p?null:(0,n.jsx)("span",{style:{flexShrink:2,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:p}),em(t5.get(l),b)]}),(0,n.jsx)("button",{type:"button",onClick:()=>t_(s),title:b("sidebar.newSessionTitle",{path:s}),"aria-label":b("sidebar.newSessionTitle",{path:s}),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:w||eg===s?1:0,pointerEvents:w||eg===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>ex(s),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,n.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,n.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,n.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,n.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,n.jsx)("button",{type:"button",onClick:()=>{eb(ev===s?null:s),eV(!1),eG(!1),eQ(null),u||_(s)},title:b("sidebar.projectActions"),"aria-label":b("sidebar.projectActions"),"aria-expanded":ev===s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:5,background:ev===s?"var(--bg-selected)":"transparent",color:u&&rs&&!rs.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:w||eg===s||ev===s?1:0,pointerEvents:w||eg===s||ev===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>ex(s),children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,n.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,n.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,n.jsxs)(en,{open:ev===s,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:[ra&&eU&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{type:"button",onClick:()=>eV(e=>!e),title:rs?b("sidebar.switchWorktreeTitle",{path:rs.path}):b("sidebar.switchWorktree"),"aria-label":b("sidebar.worktrees"),"aria-expanded":eK,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderBottom:eK?"1px solid var(--border)":"none",background:eK?"var(--bg-selected)":"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,n.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,n.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,n.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,n.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,n.jsx)("span",{style:{flex:1},children:b("sidebar.worktrees")}),(0,n.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,n.jsx)("polyline",{points:"4 2.5 8 6 4 9.5"})})]}),(0,n.jsxs)(en,{open:eK,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:[rl&&(0,n.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,n.jsx)("input",{value:eP,onChange:e=>eW(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eW(""),eV(!1))},placeholder:b("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,n.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[ro.map(e=>{let t=e.path===F||e.isMain&&!eU.worktrees.some(e=>e.path===F);return e2===e.path?(0,n.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,n.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.forceRemoveCheckout")}),(0,n.jsx)("button",{onClick:()=>void tW(e.path,!0),disabled:e0,style:{padding:"3px 9px",background:"var(--danger)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:b("sidebar.force")}),(0,n.jsx)("button",{onClick:()=>e4(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:b("sidebar.cancel")})]},e.path):(0,n.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,n.jsxs)("button",{onClick:()=>{_(e.path),eV(!1),eQ(null),eW("")},title:e.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[t?(0,n.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,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)(er,{text:e.branch??et(e.path,D),style:{flex:1}}),e.isMain&&(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:b("sidebar.main")})]}),!e.isMain&&(0,n.jsx)("button",{onClick:()=>void tW(e.path,!1),disabled:e0,title:b("sidebar.removeWorktreeTitle",{path:e.path}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:34,height:28,padding:0,marginRight:4,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",borderRadius:5,flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="#ef4444",e.currentTarget.style.background="rgba(239,68,68,0.08)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,n.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,n.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,n.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.path)}),rl&&0===ro.length&&eP.trim()&&(0,n.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:b("sidebar.noMatchingWorktrees")})]}),eJ?(0,n.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,n.jsx)("input",{ref:e8,value:eY,onChange:e=>{eZ(e.target.value),eQ(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),tP()),"Escape"===e.key&&(eG(!1),eZ(""),eQ(null))},placeholder:b("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,n.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,n.jsx)("button",{onClick:()=>void tP(),disabled:e0||!eY.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:e0||!eY.trim()?"not-allowed":"pointer",opacity:e0||!eY.trim()?.65:1},children:e0?b("sidebar.creating"):b("sidebar.create")}),(0,n.jsx)("button",{onClick:()=>{eG(!1),eZ(""),eQ(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:b("sidebar.cancel")})]})]}):(0,n.jsxs)("button",{onClick:e=>{e.stopPropagation(),eG(!0),eQ(null),setTimeout(()=>e8.current?.focus(),0)},title:b("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,n.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,n.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,n.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,n.jsx)("span",{children:b("sidebar.newWorktree")})]}),eX&&(0,n.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:eX})]})]}),(0,n.jsxs)("button",{type:"button",disabled:eE,onClick:()=>{let e;return e=tJ.get(N(s))?.alias??"",void(e3.current=!1,eA(null),eR(e),eM(s),tQ())},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:eE?"default":"pointer",textAlign:"left",fontSize:11,opacity:eE?.55:1},children:[(0,n.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,n.jsx)("path",{d:"m4 20 4.5-1 10-10a2.1 2.1 0 0 0-3-3l-10 10L4 20Z"}),(0,n.jsx)("path",{d:"m13.5 8 3 3"})]}),b(tJ.get(N(s))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,n.jsxs)("button",{type:"button",disabled:x,title:t6?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void t2(s,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:x?"default":"pointer",textAlign:"left",fontSize:11,opacity:x?.55:1},children:[(0,n.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,n.jsx)("path",{d:"m6 15 6-6 6 6"})}),b("sidebar.projectMoveUp")]}),(0,n.jsxs)("button",{type:"button",disabled:v,title:t6?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void t2(s,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:v?"default":"pointer",textAlign:"left",fontSize:11,opacity:v?.55:1},children:[(0,n.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,n.jsx)("path",{d:"m6 9 6 6 6-6"})}),b("sidebar.projectMoveDown")]}),(0,n.jsxs)("button",{type:"button",disabled:eE,onClick:()=>void t0(s,!c),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:eE?"default":"pointer",textAlign:"left",fontSize:11,opacity:eE?.55:1},children:[(0,n.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,n.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,n.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!c&&(0,n.jsx)("path",{d:"m4 4 16 16"})]}),b(c?"sidebar.projectUnhide":"sidebar.projectHide")]}),(a=0===ru(t4.get(l)??[])||tg,(0,n.jsxs)("button",{type:"button",disabled:a,onClick:()=>{tQ(),tb(null),tm({kind:"project",project:s,label:o})},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:a?"default":"pointer",textAlign:"left",fontSize:11,opacity:a?.55:1},children:[(0,n.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,n.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),b("sidebar.clearProjectSessions")]}))]})]})]}),!h&&0===d.length&&u&&(0,n.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:b("sidebar.noSessions")}),!h&&y.length>0&&(0,n.jsx)("div",{style:{paddingLeft:12},children:y.map(t=>(0,n.jsx)(ep,{node:t,selectedSessionId:e,runningSessionIds:tt,unreadSessionIds:tn,pinnedSessionIds:ta,onSelectSession:tF,onTogglePinnedSession:tI,onRenamed:tp,onSessionDeleted:th,onSessionArchived:tS,depth:0},t.session.id))}),!h&&k&&(0,n.jsx)("button",{type:"button",onClick:()=>{ed(e=>{let t=new Set(e);return t.has(s)?t.delete(s):t.add(s),t})},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:f?b("sidebar.showLess"):b("sidebar.showMore")})]},s)})]}),!rp&&(0,n.jsx)(eu,{refreshKey:tk,selectedSessionId:e,onSelectSession:tF,onRestored:tS}),!rp&&"priority"===J&&(0,n.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[L&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),A&&(0,n.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:A}),!L&&!A&&(x=ru(ri.flatMap(e=>e.sessions)),(0,n.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"8px 2px 2px"},children:[(0,n.jsx)("button",{type:"button",disabled:tD,onClick:()=>void tU(),title:b("sidebar.newScratchSessionTitle"),style:ee(tD,w),children:b("sidebar.newScratchSession")}),ri.length>0&&(0,n.jsx)("button",{type:"button",disabled:0===x||tg,onClick:()=>{tb(null),tm({kind:"priority"})},style:ee(0===x||tg,w),children:b("sidebar.clearPriorityList")})]})),tO&&(0,n.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:tO}),!L&&!A&&0===ri.length&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.noSessions")}),!L&&!A&&ri.map((t,r)=>(0,n.jsxs)("section",{"aria-labelledby":`priority-group-${t.key}`,children:[(0,n.jsx)("h2",{id:`priority-group-${t.key}`,style:{margin:0,padding:0===r?"2px 8px 4px":"14px 8px 4px",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.label}),t.sessions.map(t=>(0,n.jsx)(ec,{session:t,selected:t.id===e,running:tt.has(t.id),unread:tn.has(t.id),pinned:ta.has(t.id),onSelect:tF,onTogglePin:tI},t.id))]},t.key))]})]})}function eo({scope:e,eligible:t,runningExcluded:r,busy:a,error:s,onCancel:l,onConfirm:o}){let{t:d}=(0,R.s)(),c=a||0===t,u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(a);h.current=a;let f=(0,i.useRef)(l);return f.current=l,(0,i.useEffect)(()=>{let e=u.current;if(!e)return;let t=document.activeElement,r=t instanceof HTMLElement&&t!==document.body&&t!==document.documentElement&&!e.contains(t)?t:null;(p.current??e).focus();let n=t=>{if("Escape"===t.key){if(h.current)return;t.preventDefault(),f.current();return}if("Tab"!==t.key)return;let r=Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0),n=document.activeElement;if(0===r.length){t.preventDefault(),e.focus();return}let i=r[0],a=r[r.length-1];t.shiftKey&&(n===i||!e.contains(n))?(t.preventDefault(),a.focus()):t.shiftKey||n!==a&&e.contains(n)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",n),()=>{e.removeEventListener("keydown",n);let t=r?.isConnected?r:e.closest(".session-navigator");t?.focus()}},[]),(0,n.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:e=>{a||e.target!==e.currentTarget||l()},children:(0,n.jsxs)("div",{ref:u,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,n.jsxs)("div",{style:{padding:"18px 18px 14px"},children:[(0,n.jsx)("div",{id:"bulk-clear-title",style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:d("sidebar.clearSessionsTitle")}),(0,n.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"===e.kind?d("sidebar.clearSessionsProjectBody",{project:e.label,count:t}):d("sidebar.clearSessionsPriorityBody",{count:t}),r>0&&(0,n.jsx)("div",{style:{marginTop:6},children:d("sidebar.clearSessionsRunningExcluded",{count:r})}),0===t&&(0,n.jsx)("div",{style:{marginTop:6},children:d("sidebar.clearSessionsNone")})]}),s&&(0,n.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:s})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("button",{ref:p,type:"button",onClick:l,disabled:a,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:d("sidebar.clearSessionsCancel")}),(0,n.jsx)("button",{type:"button",onClick:o,disabled:c,"aria-busy":a,style:{minHeight:36,padding:"0 14px",border:"1px solid var(--danger)",borderRadius:"var(--radius-control)",background:"transparent",color:c?"var(--text-dim)":"var(--danger)",cursor:c?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:d(a?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function ed({filled:e=!1}){return(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:e?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M12 17v5"}),(0,n.jsx)("path",{d:"M5 17h14"}),(0,n.jsx)("path",{d:"M6 3h12l-1 8 2 3H5l2-3-1-8z"})]})}function ec({session:e,selected:t,running:r,unread:i,pinned:a,onSelect:s,onTogglePin:l}){let{t:o}=(0,R.s)(),d=(e.name||e.firstMessage||e.id.slice(0,8)).replace(/\s+/g," ").trim(),c=e.cwd.split(/[\\/]/).filter(Boolean).at(-1)??"";return(0,n.jsxs)("div",{className:`priority-session-row${t?" is-selected":""}${r?" is-running":""}${i?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:5,background:t?"var(--bg-selected)":"transparent"},children:[(0,n.jsxs)("button",{type:"button","aria-current":t?"page":void 0,onClick:()=>s(e),title:`${d}
|
|
2
2
|
${e.cwd}
|
|
3
3
|
${new Date(e.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,n.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[(0,n.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:d}),r&&(0,n.jsx)(eh,{}),!r&&i&&(0,n.jsx)(ef,{})]}),(0,n.jsx)("span",{style:{display:"block",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:c})]}),(0,n.jsx)("button",{type:"button","aria-pressed":a,"aria-label":o(a?"sidebar.unpin":"sidebar.pin"),title:o(a?"sidebar.unpin":"sidebar.pin"),onClick:()=>l(e.id),style:{width:30,border:"none",background:"transparent",color:a?"var(--accent)":"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,n.jsx)(ed,{filled:a})})]})}function eu({refreshKey:e,selectedSessionId:t,onSelectSession:r,onRestored:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)(!1),[d,c]=(0,i.useState)([]);(0,i.useEffect)(()=>{let e=!1;return(async()=>{try{let t=await fetch("/api/sessions?archived=1",{cache:"no-store"});if(!t.ok)throw Error(`HTTP ${t.status}`);let r=await t.json();e||c(r.sessions)}catch{}})(),()=>{e=!0}},[e]);let u=(0,i.useCallback)(async(e,t)=>{e.stopPropagation();try{await fetch(`/api/sessions/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:!1})}),a(t)}catch{}},[a]);return 0!==d.length||l?(0,n.jsxs)("section",{style:{borderTop:"1px solid var(--border)",marginTop:4},children:[(0,n.jsxs)("button",{type:"button",onClick:()=>o(e=>!e),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,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:l?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.1s"},children:(0,n.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})}),s("sidebar.archived")," (",d.length,")"]}),l&&(0,n.jsxs)("div",{style:{paddingLeft:12},children:[0===d.length&&(0,n.jsx)("div",{style:{padding:"4px 12px 8px 20px",color:"var(--text-dim)",fontSize:11},children:s("sidebar.noArchivedSessions")}),d.map(e=>{let i=$(e.firstMessage)??e.firstMessage,a=e.name||i.slice(0,50)||e.id.slice(0,12);return(0,n.jsxs)("div",{onClick:()=>r(e),style:{height:40,display:"flex",alignItems:"center",paddingLeft:20,paddingRight:4,gap:4,cursor:"pointer",overflow:"hidden",borderLeft:e.id===t?"2px solid var(--accent)":"2px solid transparent",background:e.id===t?"var(--bg-selected)":"transparent"},children:[(0,n.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a}),(0,n.jsx)("button",{onClick:t=>u(t,e.id),title:s("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:s("sidebar.restore")})]},e.id)})]})]}):null}function ep({node:e,selectedSessionId:t,runningSessionIds:r,unreadSessionIds:a,pinnedSessionIds:s,onSelectSession:l,onRenamed:o,onSessionDeleted:d,onTogglePinnedSession:c,onSessionArchived:u,depth:p}){let[h,f]=(0,i.useState)(!1),m=e.children.length>0;return(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{style:{position:"relative"},children:[p>0&&(0,n.jsx)("div",{style:{position:"absolute",left:10*p+6,top:0,bottom:0,width:1,background:"var(--border)",pointerEvents:"none"}}),(0,n.jsx)(eg,{session:e.session,isSelected:e.session.id===t,isRunning:r.has(e.session.id),isUnread:a.has(e.session.id),isPinned:s.has(e.session.id),onClick:()=>l(e.session),onTogglePin:()=>c(e.session.id),onRenamed:o,onDeleted:e=>d?.(e),onArchived:e=>u?.(e),depth:p,hasChildren:m,collapsed:h,onToggleCollapse:()=>f(e=>!e)})]}),m&&!h&&(0,n.jsx)("div",{children:e.children.map(e=>(0,n.jsx)(ep,{node:e,selectedSessionId:t,runningSessionIds:r,unreadSessionIds:a,pinnedSessionIds:s,onSelectSession:l,onTogglePinnedSession:c,onRenamed:o,onSessionDeleted:d,onSessionArchived:u,depth:p+1},e.session.id))})]})}function eh(){let{t:e}=(0,R.s)();return(0,n.jsx)("span",{title:e("sidebar.agentRunning"),"aria-label":e("sidebar.agentRunning"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,n.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,n.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})})})}function ef(){let{t:e}=(0,R.s)();return(0,n.jsx)("span",{title:e("sidebar.newActivity"),"aria-label":e("sidebar.newSessionActivity"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",style:{display:"block"},children:[(0,n.jsx)("circle",{cx:"7",cy:"7",r:"2.5",fill:"currentColor"}),(0,n.jsx)("circle",{className:"session-unread-ring",cx:"7",cy:"7",r:"3",stroke:"currentColor",strokeWidth:"1.4"})]})})}function em(e,t){return e&&(0!==e.running||0!==e.unread)?(0,n.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,flexShrink:0,marginLeft:6},children:[e.running>0&&(0,n.jsxs)("span",{title:t("sidebar.agentRunning"),"aria-label":`${t("sidebar.agentRunning")} (${e.running})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,n.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,n.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})}),e.running]}),e.unread>0&&(0,n.jsxs)("span",{title:t("sidebar.newSessionActivity"),"aria-label":`${t("sidebar.newSessionActivity")} (${e.unread})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,n.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"currentColor",display:"inline-block"}}),e.unread]})]}):null}function eg({session:e,isSelected:t,isRunning:r,isUnread:a,isPinned:s,onClick:l,onTogglePin:o,onRenamed:d,onDeleted:c,onArchived:u,depth:p=0,hasChildren:h=!1,collapsed:f=!1,onToggleCollapse:m}){let{t:g}=(0,R.s)(),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(!1),[w,k]=(0,i.useState)(""),[j,S]=(0,i.useState)(!1),[C,N]=(0,i.useState)(!1),I=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(b){let e=requestAnimationFrame(()=>I.current?.select());return()=>cancelAnimationFrame(e)}},[b]);let T=$(e.firstMessage)??e.firstMessage,M=e.name||T.slice(0,50)||e.id.slice(0,12),E=(0,i.useCallback)(t=>{t.stopPropagation(),e.transient||(k(e.name||T.slice(0,50)||e.id.slice(0,12)),y(!0))},[e.name,e.transient,T,e.id]),L=(0,i.useCallback)(async()=>{let t=w.trim();if(y(!1),w!==M&&t!==(e.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})}),d?.()}catch{}},[w,e.id,e.name,d,M]),z=(0,i.useCallback)(async()=>{if(!e.transient){S(!1),N(!0);try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"}),c?.(e.id)}catch{N(!1)}}},[e.id,e.transient,c]),A=(0,i.useCallback)(async t=>{if(t.stopPropagation(),!e.transient)try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:!0})}),u?.(e.id)}catch{}},[e.id,e.transient,u]),P=(0,i.useCallback)(e=>{e.stopPropagation(),e.shiftKey?z():S(!0)},[z]),W=(0,i.useCallback)(e=>{e.stopPropagation(),z()},[z]),F=(0,i.useCallback)(e=>{e.stopPropagation(),S(!1)},[]),_=(0,i.useCallback)(t=>{(function(e,t=window){let r=new CustomEvent("pi-web:session-row-contextmenu",{cancelable:!0,detail:e});return!t.dispatchEvent(r)})({id:e.id,path:e.path,cwd:e.cwd,name:e.name,clientX:t.clientX,clientY:t.clientY,refresh:()=>{d?.()}})&&(t.preventDefault(),t.stopPropagation())},[d,e.cwd,e.id,e.name,e.path]);return(0,n.jsx)("div",{className:`navigator-session-row${t?" is-selected":""}${r?" is-running":""}${a?" is-unread":""}${j?" is-confirming":""}`,onClick:j||b?void 0:l,onContextMenu:j||b?void 0:_,onMouseEnter:()=>v(!0),onMouseLeave:()=>{v(!1)},style:{height:40,display:"flex",alignItems:"center",paddingLeft:p>0?10*p+8:8,paddingRight:4,cursor:j||b?"default":"pointer",background:t?"var(--bg-selected)":x?"var(--bg-hover)":"transparent",borderLeft:"2px solid transparent",transition:"background 0.1s",opacity:C?.5:1,gap:4,overflow:"hidden"},children:j?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g("sidebar.deleteSession",{title:M.slice(0,22)+(M.length>22?"…":"")})}),(0,n.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,n.jsxs)("button",{onClick:W,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,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,n.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,n.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,n.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),g("sidebar.delete")]}),(0,n.jsx)("button",{onClick:F,style:{display:"flex",alignItems:"center",justifyContent:"center",height:30,padding:"0 11px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:500,whiteSpace:"nowrap"},children:g("sidebar.cancel")})]})]}):b?(0,n.jsx)("input",{ref:I,value:w,onChange:e=>k(e.target.value),onBlur:L,onKeyDown:e=>{"Enter"===e.key&&L(),"Escape"===e.key&&y(!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,n.jsxs)(n.Fragment,{children:[p>0&&(0,n.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,n.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,n.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,n.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,n.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),l()},"aria-current":t?"page":void 0,title:M,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,color:"var(--text)",fontSize:12.5,fontWeight:t?500:400,lineHeight:1.35,padding:0,border:"none",background:"transparent",fontFamily:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,n.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M}),r&&(0,n.jsx)(eh,{}),!r&&a&&(0,n.jsx)(ef,{}),e.worktreeBranch&&(0,n.jsx)("span",{title:g("sidebar.worktreePath",{path:e.cwd}),style:{display:"flex",color:"var(--accent)",flexShrink:0},children:(0,n.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,n.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,n.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,n.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})})]}),h&&(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),m?.()},title:g(f?"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:f?"rotate(-90deg)":"none",transition:"transform 0.15s"},children:(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),!e.transient&&(0,n.jsxs)("div",{style:{display:"flex",gap:4,flexShrink:0},children:[(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),o?.()},title:g(s?"sidebar.unpin":"sidebar.pin"),"aria-label":g(s?"sidebar.unpin":"sidebar.pin"),"aria-pressed":s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:s?"var(--bg-selected)":"transparent",border:"none",borderRadius:5,color:s?"var(--accent)":"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:x||s?1:0,pointerEvents:x||s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>v(!0),children:(0,n.jsx)(ed,{filled:s})}),(0,n.jsx)("button",{onClick:E,title:g("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:+!!x,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>v(!0),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="transparent"},children:(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),(0,n.jsx)("button",{onClick:A,title:g("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:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"3",y:"4",width:"18",height:"4",rx:"1"}),(0,n.jsx)("path",{d:"M5 8v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"}),(0,n.jsx)("path",{d:"M10 12h4"})]})}),(0,n.jsx)("button",{onClick:P,title:g("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:+!!x,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>v(!0),onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)",e.currentTarget.style.color="#ef4444",e.currentTarget.style.borderColor="rgba(239,68,68,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="transparent"},children:(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,n.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,n.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,n.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]})]})})}let ex=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,ev=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,eb=/\x1B\[([0-9;]*)m/g,ey=/\x1B_pi:c\x07/g,ew=["#1f2937","#dc2626","#16a34a","#d97706","#2563eb","#9333ea","#0891b2","#6b7280"],ek=["#9ca3af","#ef4444","#22c55e","#f59e0b","#3b82f6","#a855f7","#06b6d4","#e5e7eb"];function ej(e){return e.replace(ey,"").replace(ex,"")}function eS(e){let t=[],r=0;for(;r<e.length;){if(27===e.charCodeAt(r)){let t=e.slice(r).match(ev);if(t){r+=t[0].length;continue}}let n=e.codePointAt(r);if(void 0===n)break;let i=String.fromCodePoint(n);t.push({start:r,end:r+i.length,char:i}),r+=i.length}return t}function eC(e,t){let r=eS(e)[t];return r?e.slice(0,r.start)+e.slice(r.end):e}function eN(e){return eS(e)[0]?.char}function eI(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,r=[];for(let n of e){let e=n.replace(ey,""),i=ej(e).trimEnd();if(t.test(i))continue;let a=e,s=eN(a);("│"===s||"┃"===s)&&" "===eN(a=eC(a,0))&&(a=eC(a,0));let l=function(e){let t=eS(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(a),o=l>=0?eS(a)[l]?.char:void 0;("│"===o||"┃"===o)&&(a=eC(a,l)),r.push(function(e){let t=e;for(;;){let e=eS(t),r=e[e.length-1];if(!r||""!==r.char.trim())return t;t=t.slice(0,r.start)+t.slice(r.end)}}(a))}for(;r.length>0&&""===ej(r[0]).trim();)r.shift();for(;r.length>0&&""===ej(r[r.length-1]).trim();)r.pop();return r.length?r:e}function eT(e){let t,r=[],n={},i=0;for(eb.lastIndex=0;null!==(t=eb.exec(e));)t.index>i&&r.push({text:e.slice(i,t.index),style:n}),n=function(e,t){let r={...e};for(let e=0;e<t.length;e++){let n=t[e];if(0===n)for(let e of Object.keys(r))delete r[e];else if(1===n)r.fontWeight=700;else if(2===n)r.opacity=.65;else if(3===n)r.fontStyle="italic";else if(4===n)r.textDecoration="underline";else if(22===n)delete r.fontWeight,delete r.opacity;else if(23===n)delete r.fontStyle;else if(24===n)delete r.textDecoration;else if(39===n)delete r.color;else if(49===n)delete r.backgroundColor;else if(n>=30&&n<=37)r.color=ew[n-30];else if(n>=90&&n<=97)r.color=ek[n-90];else if(n>=40&&n<=47)r.backgroundColor=ew[n-40];else if(n>=100&&n<=107)r.backgroundColor=ek[n-100];else if((38===n||48===n)&&2===t[e+1]){let[i,a,s]=[t[e+2],t[e+3],t[e+4]];[i,a,s].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===n?r.color=`rgb(${i}, ${a}, ${s})`:r.backgroundColor=`rgb(${i}, ${a}, ${s})`),e+=4}else if((38===n||48===n)&&5===t[e+1]){let i=function(e){if(e>=0&&e<8)return ew[e];if(e>=8&&e<16)return ek[e-8];if(e>=16&&e<=231){let t=e-16,r=Math.floor(t/36),n=Math.floor(t%36/6),i=e=>0===e?0:55+40*e;return`rgb(${i(r)}, ${i(n)}, ${i(t%6)})`}if(e>=232&&e<=255){let t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}}(t[e+2]);i&&(38===n?r.color=i:r.backgroundColor=i),e+=2}}return r}(n,t[1]?t[1].split(";").map(e=>Number(e||"0")):[0]),i=t.index+t[0].length;return i<e.length&&r.push({text:e.slice(i),style:n}),r}let eM={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:""},e$={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"},eR={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"},eE={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 eL(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function ez(e){return null!==(eR[eL(e)]??null)}function eA(e,t,r={}){let n={...e,content:t};return r.omitUsage&&(n.usage=void 0),n}function eP(e,t={}){return!!t.hideThinking&&"thinking"===e.type||function(e,t={}){return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===e.thinking.trim()}(e,t)}function eW(e,t={}){return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function eF(e,t={}){let r=[];for(let n of function(e,t={}){return(e.content??[]).filter(e=>!eP(e,t))}(e,t)){let e="image"===n.type||"text"===n.type&&n.text.trim().length>0?"answer":"process",t=r[r.length-1];t?.kind===e?t.blocks.push(n):r.push({kind:e,blocks:[n]})}return r}function e_(e){return e.filter(e=>"toolCall"===e.type).length}function eD(e,t,r){let n=new URLSearchParams({sessionId:e,toolCallId:t});return void 0!==r&&n.set("index",String(r)),`/api/tool-image?${n}`}function eH(e){let t=new Map;for(let r of e)"toolResult"===r.role&&t.set(r.toolCallId,r);let r=[],n=-1;return{collect(e,i){for(let a of i)"toolCall"===a.type&&function(e,t){if(!t||t.isError)return!1;if(t.content?.some(e=>"image"===e.type))return!0;let r=e.input??{};return"generate_image"===e.toolName||("write"===e.toolName?"xd://generate_image"===r.path:"read"===e.toolName&&"string"==typeof r.path&&ez(r.path))}(a,t.get(a.toolCallId))&&(r.push({type:"image",source:{type:"url",url:""},toolImage:{toolCallId:a.toolCallId}}),n=e)},attach(e){if(0===r.length)return e;let t=[...r,...e];return r=[],t},takeRemaining(){if(0===r.length)return null;let e={idx:n,blocks:r};return r=[],e}}}let eO=new Map,eB=new Map,eU="command",eq="autolearn-saved";function eK(e){return"custom"===e.role&&(e.customType===eU||e.customType===eq&&!1!==e.display)}let eV="local-command:";function eJ(e){return e?.startsWith(eV)===!0}function eG(e,t,r){let n=new Set(r.map(e=>e.message)),i=[],a=[];for(let r=0;r<e.length;r++){let s=r<t.length;!(n.has(e[r])||s&&eJ(t[r]))&&(i.push(e[r]),s&&a.push(t[r]))}for(let e of r){let t=0;if(null!==e.baseEntryId){let r=a.indexOf(e.baseEntryId);if(-1===r)continue;t=r+1}let r=e.message.timestamp??0;for(;t<i.length;){let e=i[t];if(!n.has(e)&&"number"==typeof e.timestamp&&e.timestamp>r)break;t+=1}i.splice(t,0,e.message),t<=a.length&&a.splice(t,0,e.entryId)}return{messages:i,entryIds:a}}function eY(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}let eZ={create:!0,update:!0};function eX(e){return"string"==typeof e?e.replace(/\s+/g," ").trim():""}function eQ(e){if("string"==typeof e)return e;if(!Array.isArray(e))return"";let t=[];for(let r of e)r&&"object"==typeof r&&"type"in r&&"text"===r.type&&"text"in r&&"string"==typeof r.text&&t.push(r.text);return t.join("\n")}function e0(e,t){if(0===e.length)return -1;if(!t)return 0;let r=-1;for(let n=0;n<e.length;n++){let i=e[n];if(i.item===t.item){if(i.k===t.k)return n;r=n}}return -1===r?0:r}function e1(e){try{return decodeURIComponent(e)}catch{return e}}function e2(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function e4(e){let t=e2(e),r=/^[a-zA-Z]:\//.test(t),n=t.startsWith("//"),i=t.startsWith("/")&&!r&&!n,a=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){a.length>0&&".."!==a[a.length-1]?a.pop():i||r||n||a.push(e);continue}a.push(e)}let s=a.join("/");return r?s:n?`//${s}`:i?`/${s}`:s}function e5(e,t,r=t){let n,i,a,s,l;if(!e)return null;let o=e.split("#",1)[0].split("?",1)[0].trim();if(!o)return null;let d=null,c=null,u=e1(o),p=u.startsWith("\\\\"),h=e2(u),f=h.toLowerCase();if(f.startsWith("/api/")||f.startsWith("/_next/")||!p&&h.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(h)&&!f.startsWith("file:")&&!/^[a-zA-Z]:\//.test(h))return null;if(f.startsWith("file:")?c=(d=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let r=e1(t.pathname);if(t.hostname)return`//${t.hostname}${r.startsWith("/")?r:`/${r}`}`;if(/^\/[a-zA-Z]:\//.test(r))return r.slice(1);return r}catch{return null}}(h))?"absolute":null:/^[a-zA-Z]:\//.test(h)||h.startsWith("/")?(d=h,c="absolute"):t&&!(h.startsWith("#")||h.startsWith("?"))&&(h.startsWith("./")||h.startsWith("../")||h.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(h))&&(d=`${e2(t).replace(/\/+$/,"")}/${h}`,c="relative"),!d)return null;let m=e4(d).replace(/:\d+(?::\d+)?$/,"");return"relative"===c&&r&&(n=e4(m).replace(/\/+$/,""),i=e4(r).replace(/\/+$/,""),s=(a=/^[a-zA-Z]:\//.test(n)||/^[a-zA-Z]:\//.test(i))?n.toLowerCase():n,!(s===(l=a?i.toLowerCase():i)||s.startsWith(`${l}/`)))?null:m}function e8(e,t,r){let n=new Set,i=[];for(let a of e){if("toolCall"!==a.type||!function(e){let t,r;return"write"===(t=e.toLowerCase())||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")||"edit"===(r=e.toLowerCase())||r.startsWith("edit_")||r.endsWith(".edit")||r.endsWith("_edit")||r.includes("str_replace")||r.includes("replace_editor")}(a.toolName))continue;let e=t?.get(a.toolCallId);if(!e||e.isError)continue;let s=function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(a.input);if(!s||!/^[a-zA-Z]:[\\/]/.test(s)&&/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(s))continue;let l=function(e,t){let r;if(!e)return null;let n=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),i=e=>n?e.replace(/\\/g,"/"):e,a=i(e),s=t?i(t).replace(/\/+$/,""):void 0,l=/^[a-zA-Z]:\//.test(a),o=a.startsWith("//");if(l||o)r=a;else if(a.startsWith("/")){let e=s?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??s?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];r=e?`${e}${a}`:a}else{if(!s)return null;r=`${s}/${a}`}return e4(r)}(s,r);l&&(n.has(l)||(n.add(l),i.push({filePath:l})))}return i}function e6(e,t){var r;let n;if(t){let e=t.details,r=e&&"object"==typeof e&&"phases"in e?e.phases:void 0;if(!Array.isArray(r))return{kind:"unknown"};let{phases:n,malformed:i}=function(e){let t=[];for(let r of e){if(!r||"object"!=typeof r||!("name"in r)||!("tasks"in r))return{phases:t,malformed:!0};let{name:e,tasks:n}=r;if("string"!=typeof e||!Array.isArray(n))return{phases:t,malformed:!0};let i=Array.isArray(n)?n.flatMap(e=>{if(!e||"object"!=typeof e||!("content"in e)||!("status"in e))return[];let{content:t,status:r}=e;return"string"!=typeof t||"pending"!==r&&"in_progress"!==r&&"completed"!==r&&"abandoned"!==r&&"blocked"!==r?[]:[{content:t,status:r,blocker:"blocker"in e&&"string"==typeof e.blocker?e.blocker:void 0}]}):[];if(i.length!==n.length)return{phases:t,malformed:!0};i.length>0&&t.push({name:e,tasks:i})}return{phases:t,malformed:!1}}(r);return i?{kind:"unknown"}:{kind:"authoritative",phases:n}}let i=Array.isArray(n=(r=e.input)&&"object"==typeof r&&"list"in r?r.list:void 0)?n.flatMap(e=>{if(!e||"object"!=typeof e||!("phase"in e)||!("items"in e))return[];let{phase:t,items:r}=e;if("string"!=typeof t||!Array.isArray(r))return[];let n=r.filter(e=>"string"==typeof e).map(e=>({content:e,status:"pending"}));return n.length>0?[{name:t,tasks:n}]:[]}):[];return i.length>0?{kind:"preview",phases:i}:{kind:"unknown"}}function e3(e,t,r=null,n=null){return r||(function(e,t){for(let r=e.length-1;r>=0;r-=1){let n=e[r];if("assistant"!==n.role)continue;let i=n.content;if(Array.isArray(i))for(let e=i.length-1;e>=0;e-=1){let r=i[e];if("toolCall"!==r.type||!function(e){if(!e)return!1;let t=e.toLowerCase();return"todo"===t||t.endsWith(".todo")||t.endsWith("_todo")}(r.toolName))continue;let n=e6(r,t.get(r.toolCallId));if("unknown"!==n.kind)return n.phases}}return null}(e,t)??n)}function e7(e){let t=0,r=0,n=null,i=null,a=null;for(let s of e)for(let e of s.tasks){if("completed"===e.status){t+=1;continue}"abandoned"!==e.status&&(r+=1,"in_progress"===e.status?n||(n={phase:s,task:e}):"blocked"===e.status?a||(a={phase:s,task:e}):i||(i={phase:s,task:e}))}let s=n??i??a,l=t+r;return{currentPhase:s?.phase??null,activeTask:s?.task??null,remaining:r,completed:t,total:l,percent:l>0?Math.round(t/l*100):null}}var e9=r(65063),te=r(7644),tt=r(32316);function tr(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function tn(e){return tr(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function ti(e){let t=tr(e).replace(/\/+$/,"");return t.split("/").pop()??t}function ta(e,t){if(!t)return e;let r=tr(e),n=tr(t).replace(/\/$/,"");return r.startsWith(n+"/")?r.slice(n.length+1):e}var ts=r(88374),tl=r(63280),to=r(94764),td=r(63835),tc=r(54152),tu=r(84678),tp=r(98164);let th={...to.j,attributes:{...to.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},strip:[...to.j.strip||[],"iframe","object","style","form"]};function tf(e){let t=e.includes("\r\n")?"\r\n":"\n",r=e.split(/\r?\n/),n=[],i=null,a=0,s=null,l=new Map;for(let e=0;e<r.length;e++){var o;let t=r[e];if(s){n.push(t),RegExp(`</${s}\\s*>`,"i").test(t)&&(s=null);continue}let d=t.match(/^ {0,3}(`{3,}|~{3,})/);if(d){let e=d[1][0],r=d[1].length;i?e===i.marker&&r>=i.size&&(i=null):i={marker:e,size:r},a=0,n.push(t);continue}if(i){n.push(t);continue}let c=t.match(/<(code|pre|script|style)\b/i);if(c){let e=c[1].toLowerCase(),r=t.slice((c.index??0)+c[0].length);RegExp(`</${e}\\s*>`,"i").test(r)||(s=e),a=0,n.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){a=0,n.push(t);continue}if(a||t.includes("`")){a=function(e,t){let r=t;for(let t=0;t<e.length;){if("`"!==e[t]){t++;continue}let n=t+1;for(;"`"===e[n];)n++;let i=n-t;0===r?r=i:i===r&&(r=0),t=n}return r}(t,a),n.push(t);continue}let u=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(u){let e=u[2].trim();if(e){n.push(`${u[1]}$$`,`${u[1]}${e}`,`${u[1]}$$`);continue}}let p=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(p){let t=function(e,t){for(let r=t;r<e.length;r++){let t=e[r];if(/^ {0,3}\\\][ \t]*$/.test(t))return r;if(/^ {0,3}(`{3,}|~{3,})/.test(t)||/^ {0,3}\\\[[ \t]*$/.test(t)||/<(code|pre|script|style)\b/i.test(t))break}return -1}(r,e+1);if(-1!==t){n.push(`${p[1]}$$`,...r.slice(e+1,t).map(e=>tg(e,p[1])),`${p[1]}$$`),e=t;continue}}let h=t.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \t]*$/);if(h){let e=h[2].trim();if(e){n.push(`${h[1]}$$`,`${h[1]}${e}`,`${h[1]}$$`);continue}}let f=t.match(/^([ \t]{0,3})\$\$(.+)$/);if(f){let t=f[1],i=f[2].trimEnd();if(i&&!i.includes("$$")){let a=tm(r,e+1,t,l);if(a){n.push(`${t}$$`,`${t}${i}`);for(let i=e+1;i<a.index;i++)n.push(tg(r[i],t));a.content&&n.push(`${t}${a.content}`),n.push(`${t}$$`),e=a.index;continue}}}let m=t.match(/^([ \t]{0,3})\$\$\s*$/);if(m){let t=m[1],i=tm(r,e+1,t,l);if(i&&(i.glued||""!==t)){n.push(`${t}$$`);for(let a=e+1;a<i.index;a++)n.push(tg(r[a],t));i.content&&n.push(`${t}${i.content}`),n.push(`${t}$$`),e=i.index;continue}}n.push((o=t,/^\s{0,3}\[[^\]]+\]:/.test(o)||/]\s*\(/.test(o)||/<(?:!--|\/?[A-Za-z][^>]*>)/.test(o)||/\b(?:https?|file|mailto):/i.test(o)||/\b[A-Za-z]:\\/.test(o)?o:o.replace(/(?<!\\)\\\(([^`\r\n$]+?)(?<!\\)\\\)/g,(e,t)=>t.trim()?`$${t}$`:e)))}return n.join(t)}function tm(e,t,r,n){let i=n.get(r);if(void 0!==i&&t<i)return null;for(let i=t;i<e.length;i++){var a,s,l,o;let t=e[i];if(a=t,""===(s=r)?/^ {0,3}\$\$\s*$/.test(a):a.startsWith(s)&&/^\$\$\s*$/.test(a.slice(s.length)))return{index:i,content:"",glued:!1};if(l=t,/^ {0,3}(`{3,}|~{3,})/.test(l)||/^[ \t]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/.test(l)||/^ {0,3}#{1,6}(?:[ \t]+|$)/.test(l)||/^ {0,3}>/.test(l)||/<(code|pre|script|style)\b/i.test(l)||(o=t,/^ {0,3}\$\$(?:\S|[ \t]+\S)/.test(o)))return n.set(r,i),null;let d=function(e,t){if(!e.startsWith(t))return null;let r=e.slice(t.length).match(/^(.+?)\$\$\s*$/);if(!r)return null;let n=r[1].trimEnd();return n&&!n.includes("$$")?n:null}(t,r);if(null!==d)return{index:i,content:d,glued:!0}}return n.set(r,e.length),null}function tg(e,t){if(!t||!e||e.startsWith(" "))return e;let r=e.match(/^ */)?.[0].length??0;return r>=t.length?e:`${t.slice(r)}${e}`}let tx={singleTilde:!1},tv=[[tc.A,["yaml"]],[tu.A,tx],tp.A],tb=[[tc.A,["yaml"]],[tu.A,tx],tp.A],ty=[tl.A,[td.A,th],[ts.A,{throwOnError:!1,strict:!1}]],tw=[tl.A,[td.A,th],[ts.A,{throwOnError:!1,strict:!1}]],tk="pi-theme",tj=["light","dark","auto"],tS={preference:"auto",theme:"light"},tC="omp-theme",tN=null,tI=0,tT=new Set,tM=null,t$=!1;function tR(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function tE(e){return"auto"===e?tR():e}let tL="--omp-md-";function tz(e){let t=document.documentElement,r=tN?.palettes[e];t.dataset.ompThemeMode=e,t.setAttribute("data-seed-color-mode","dark"===e?"dark-only":"light-only"),t.classList.toggle("dark","dark"===e);for(let e=t.style.length-1;e>=0;e-=1){let r=t.style.item(e);r.startsWith("--")&&!r.startsWith(tL)&&t.style.removeProperty(r)}if(r){for(let[e,n]of Object.entries(r.variables))e.startsWith(tL)&&t.style.setProperty(e,n);t.dataset.ompThemeName=r.name}try{localStorage.setItem(tC,e)}catch{}}function tA(){if(tM)return tM;let e=function(){try{let e=localStorage.getItem(tk);if("light"===e||"dark"===e||"auto"===e)return e;let t=localStorage.getItem(tC);if("light"===t||"dark"===t)return t}catch{}return"auto"}(),t=tE(e);return tz(t),tM={preference:e,theme:t}}function tP(e,t,r){if(tz(t),r)try{localStorage.setItem(tk,e)}catch{}tM={preference:e,theme:t},tT.forEach(e=>e())}function tW(){let e=tA();if("auto"!==e.preference)return;let t=tR();t!==e.theme&&tP("auto",t,!1)}function tF(e){return tT.add(e),tA(),t$||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",tW),window.addEventListener("focus",tW),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&tW()}),t$=!0),tW(),()=>{tT.delete(e)}}function t_(){return tA()}function tD(){return tS}async function tH(e){let t=++tI,r=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/theme${r}`,{cache:"no-store"});if(!n.ok)throw Error(`Theme request failed (${n.status})`);let i=await n.json();if(t===tI){tN=i;try{localStorage.setItem("omp-theme-config",JSON.stringify(tN))}catch{}tz(tA().theme)}}function tO(e){let t=(0,i.useSyncExternalStore)(tF,t_,tD);(0,i.useEffect)(()=>{e?.syncWithOmp&&tH(e.cwd).catch(()=>{})},[e?.cwd,e?.syncWithOmp]);let r=(0,i.useCallback)((e,t)=>{let r=tE(e),n=()=>{tP(e,r,!0)},i=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||i)return void n();let a=t?.x??window.innerWidth/2,s=t?.y??window.innerHeight/2,l=Math.hypot(Math.max(a,window.innerWidth-a),Math.max(s,window.innerHeight-s));document.startViewTransition(n).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${a}px ${s}px)`,`circle(${l}px at ${a}px ${s}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]),n=(0,i.useCallback)(e=>{var t;let n;r((t=tA().preference,n=tj.indexOf(t),tj[(n+1)%tj.length]),e)},[r]),a=(0,i.useCallback)((e,t)=>{r(e,t)},[r]);return{theme:t.theme,preference:t.preference,toggleTheme:n,setPreference:a,isDark:"dark"===t.theme}}function tB(e){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);try{let t=document.createElement("textarea");return t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),Promise.resolve()}catch{return Promise.reject()}}let tU={...te.vs,...Object.fromEntries(["url","symbol","number","boolean","variable","constant","inserted"].map(e=>[e,{...te.vs[e],color:"var(--seed-color-palette-green-800)"}]))};function tq({code:e,isStreaming:t,defaultPreview:a=!1}){let{isDark:s}=tO(),{t:l}=(0,R.s)(),[o,d]=(0,i.useState)(a),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),f=`${s?"dark":"light"}
|
|
4
4
|
${e}`,m=o&&!t;(0,i.useEffect)(()=>{if(!m)return;let t=!1;return u({key:f,status:"loading"}),(async()=>{let{default:n}=await Promise.all([r.e(866),r.e(8367),r.e(3308)]).then(r.bind(r,43328)),i=getComputedStyle(document.body).fontFamily;if(await document.fonts.load(`16px ${i}`,e),await document.fonts.ready,t)return;if(n.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:s?"dark":"default",fontFamily:i}),!await n.parse(e,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let a="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,l=await n.render(a,e);t||u({key:f,status:"ready",svg:l.svg})})().catch(()=>{t||u({key:f,status:"error"})}),()=>{t=!0}},[e,f,s,m]);let g=(0,i.useMemo)(()=>(0,n.jsx)("button",{type:"button",onClick:()=>d(e=>!e),disabled:t,title:t?l("i18n.previewAfterStreaming"):m?l("i18n.showMermaidSource"):l("i18n.previewMermaid"),className:["markdown-code-action",m?"is-active":""].filter(Boolean).join(" "),children:m?l("i18n.source"):l("i18n.preview")}),[t,m,l]);if(!m)return(0,n.jsx)(tV,{code:e,lang:"mermaid",headerAction:g,isStreaming:t});let x=c?.key===f&&"error"===c.status?(0,n.jsx)("div",{className:"mermaid-block mermaid-block-error",children:l("i18n.invalidMermaid")}):c?.key!==f||"ready"!==c.status?(0,n.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":l("i18n.renderingMermaid")}):(0,n.jsxs)(n.Fragment,{children:[!p&&(0,n.jsx)("button",{type:"button",className:"mermaid-block mermaid-preview-button",title:l("i18n.openMermaidViewer"),"aria-label":l("i18n.openMermaidViewer"),onClick:()=>h(!0),dangerouslySetInnerHTML:{__html:c.svg}}),p&&(0,n.jsx)(tK,{svg:c.svg,onClose:()=>h(!1)})]});return(0,n.jsxs)("div",{className:"markdown-code-block",children:[(0,n.jsxs)("div",{className:"markdown-code-header",children:[(0,n.jsx)("span",{className:"markdown-code-lang",children:"mermaid"}),g]}),x]})}function tK({svg:e,onClose:t}){let{t:r}=(0,R.s)(),a=(0,i.useRef)(null),[s,l]=(0,i.useState)(1);return(0,i.useEffect)(()=>{let e=a.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,n.jsx)("dialog",{ref:a,className:"mermaid-zoom-dialog","aria-label":r("i18n.mermaidViewer"),onCancel:e=>{e.preventDefault(),t()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),t())},children:(0,n.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,n.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,n.jsx)("span",{className:"mermaid-zoom-title",children:r("i18n.mermaidDiagram")}),(0,n.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,n.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,n.jsx)("button",{type:"button",onClick:()=>l(e=>Math.max(.5,e-.25)),disabled:s<=.5,title:r("i18n.zoomOut"),"aria-label":r("i18n.zoomOut"),children:(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M5 12h14"})})}),(0,n.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*s),"%"]}),(0,n.jsx)("button",{type:"button",onClick:()=>l(e=>Math.min(3,e+.25)),disabled:s>=3,title:r("i18n.zoomIn"),"aria-label":r("i18n.zoomIn"),children:(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,n.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>l(1),title:r("i18n.fitToWidth"),"aria-label":r("i18n.fitToWidth"),children:(0,n.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,n.jsx)("path",{d:"M8 3H3v5M16 3h5v5M8 21H3v-5M16 21h5v-5"})})}),(0,n.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:t,title:r("i18n.close"),"aria-label":r("i18n.close"),children:(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]}),(0,n.jsx)("div",{className:"mermaid-zoom-viewport",onClick:e=>{e.target===e.currentTarget&&t()},children:(0,n.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*s}%`},dangerouslySetInnerHTML:{__html:e}})})]})})}let tV=(0,i.memo)(function({code:e,lang:t,headerAction:r,isStreaming:a}){let{isDark:s}=tO(),{t:l}=(0,R.s)(),[o,d]=(0,i.useState)(!1);return(0,n.jsxs)("div",{className:"markdown-code-block",children:[(0,n.jsxs)("div",{className:"markdown-code-header",children:[(0,n.jsx)("span",{className:"markdown-code-lang",children:t||"text"}),(0,n.jsxs)("div",{className:"markdown-code-actions",children:[r,(0,n.jsx)("button",{onClick:()=>{tB(e).then(()=>{d(!0),setTimeout(()=>d(!1),1500)})},className:"markdown-code-action",children:l(o?"i18n.copied":"i18n.copy")})]})]}),a?(0,n.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,n.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:e})}):(0,n.jsx)(e9.A,{language:t||"text",style:s?te.xJ:tU,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:e})]})});function tJ({children:e,className:t,isStreaming:r,cwd:a,onOpenFile:s}){let l=(0,i.useMemo)(()=>tf(e),[e]),o=(0,i.useMemo)(()=>({code({className:e,children:t,...i}){let a=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===a?(0,n.jsx)(tq,{code:s.replace(/\n$/,""),isStreaming:r}):(0,n.jsx)(tV,{code:s.replace(/\n$/,""),lang:a,isStreaming:r}):(0,n.jsx)("code",{className:"markdown-inline-code",...i,children:t})},pre:({children:e})=>(0,n.jsx)(n.Fragment,{children:e}),a({href:e,children:t,...r}){delete r.node;let i=s?e5(e,a):null;return i&&s?(0,n.jsx)("a",{href:e,...r,onClick:e=>{if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),s(i))},children:t}):(0,n.jsx)("a",{href:e,...r,target:"_blank",rel:"noopener noreferrer",children:t})},img({src:e,alt:t,...r}){delete r.node;let i="string"==typeof e?e5(e,a):null,s=i?`/api/files/${tn(i)}?type=read`:e;return(0,n.jsx)("img",{src:s,alt:t??"",loading:"lazy",...r})},table:({children:e})=>(0,n.jsx)("div",{className:"markdown-table-wrap",children:(0,n.jsx)("table",{children:e})})}),[a,r,s]);return(0,n.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,n.jsx)(tt.oz,{remarkPlugins:tv,rehypePlugins:ty,components:o,children:l})})}let tG=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,tY=/(?:\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 tZ(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let tX={hideThinkingBlock:!1},tQ=new Set,t0=tX,t1=0;function t2(e){return tQ.add(e),()=>{tQ.delete(e)}}function t4(){return t0}function t5(){return tX}async function t8(e){let t=++t1,r=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/display-settings${r}`,{cache:"no-store"});if(!n.ok)throw Error(`Display settings request failed (${n.status})`);let i=await n.json();t!==t1||i.hideThinkingBlock!==t0.hideThinkingBlock&&(t0={hideThinkingBlock:!0===i.hideThinkingBlock},tQ.forEach(e=>e()))}function t6(){return(0,i.useSyncExternalStore)(t2,t4,t5)}var t3=r(64178);let t7={faces:new Map,pins:new Map},t9=[],re=t7,rt=null,rr=new Map,rn=new Set;function ri(e){return rn.add(e),()=>{rn.delete(e)}}function ra(e){re=e,rn.forEach(e=>e())}function rs(e){return Number.isSafeInteger(e)&&e>0}function rl(e,t){return`${e}:${t}`}function ro(e,t,r){if(!t)return null;if(rs(r)){let e=re.faces.get(rl(t,r));if(e)return e}let n=e?re.pins.get(e):void 0;if(n&&n.provider===t){let e=re.faces.get(rl(t,n.credentialId));if(e)return e}return(0,t3.e$)(t)}async function rd(e,t,r){if(!t||rs(r)||(0,t3.e$)(t))return ro(e,t,r);try{let{data:r}=await (0,t3.ST)(e);if(r?.state==="resolved"&&r.provider===t&&rs(r.credentialId)){let n=new Map(re.pins);n.set(e,{provider:t,credentialId:r.credentialId,observedAt:Date.now()}),ra({faces:re.faces,pins:n})}}catch{}return ro(e,t,void 0)}function rc(e,t,r){let n=!!t&&!rs(r)&&!!e;return(0,i.useEffect)(()=>{n&&e&&t&&function(e,t){let r=Date.now(),n=re.pins.get(e);if(n&&n.provider===t&&r-n.observedAt<3e4)return;let i=`${e}\u0000${t}`,a=rr.get(i);void 0!==a&&r-a<3e4||(rr.set(i,r),(0,t3.ST)(e).then(t=>{let r=t.data;if(!r||"resolved"!==r.state)return;let{provider:n,credentialId:i}=r;if("string"!=typeof n||""===n||!rs(i))return;let a=new Map(re.pins);a.set(e,{provider:n,credentialId:i,observedAt:Date.now()}),ra({faces:re.faces,pins:a})}).catch(()=>{}))}(e,t)},[n,e,t]),(0,i.useSyncExternalStore)(ri,()=>ro(e,t,r),()=>null)}let ru={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":"기본 음성","progress.label":"진행","phase.investigate":"조사","phase.implement":"구현","phase.verify":"검증","phase.report":"보고","phase.current":"지금 단계 {phase}","phase.hint":"도구 호출로 읽은 지금 단계입니다. 고친 뒤 다시 고치면 앞 단계로 돌아갑니다.","progress.todo":"할 일 {completed}/{total} ({percent}%)","eta.label":"예상 시간","eta.elapsed":"경과 {duration}","eta.remaining":"남은 시간 보통 {range} (과거 {samples}건)","eta.percent":"약 {percent}% 추정","eta.overrun":"과거 최장 기록({longest}) 이상 경과","eta.sparseTail":"과거 {samples}건 중 {longerRuns}건만 이보다 오래 걸림","eta.hint":"같은 모델\xb7작업 등급의 과거 첫 시도 가운데 지금 경과보다 오래 걸린 실행들의 남은 시간 분포(가운데 절반)입니다.","eta.byTodo":"할 일 기준 약 {duration} 남음 ({completed}/{total} 단계)","eta.byTodoSoon":"할 일 기준 1분 이내 ({completed}/{total} 단계)","eta.byTodoHint":"todo 완료 비율로만 잰 값입니다. 단계마다 걸리는 시간이 달라 오차가 큽니다.","eta.rework":"재작업 {attempt}차 \xb7 첫 발주부터 {duration}","eta.reworkAttempt":"재작업 {attempt}차","eta.reworkHint":"재작업 시도는 과거 소요 기록이 거의 없어 남은 시간\xb7%를 추정하지 않습니다. 첫 발주부터의 시간에는 시도 사이 Main 검수\xb7대기 시간이 들어 있습니다.","eta.rangeMinutes":"{low}~{high}분","eta.range":"{low}~{high}","duration.seconds":"{seconds}초","duration.minutesSeconds":"{minutes}분 {seconds}초","duration.minutes":"{minutes}분","duration.hours":"{hours}시간","duration.hoursMinutes":"{hours}시간 {minutes}분","duration.underMinute":"1분 미만"},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","progress.label":"Progress","phase.investigate":"Investigate","phase.implement":"Implement","phase.verify":"Verify","phase.report":"Report","phase.current":"current phase {phase}","phase.hint":"Current phase read from tool calls. It goes back when the child edits again after checking.","progress.todo":"todo {completed}/{total} ({percent}%)","eta.label":"Estimate","eta.elapsed":"{duration} elapsed","eta.remaining":"usually {range} left ({samples} past runs)","eta.percent":"about {percent}% (estimate)","eta.overrun":"At or beyond the longest past run ({longest})","eta.sparseTail":"Only {longerRuns} of {samples} past runs took longer","eta.hint":"Middle half of the remaining time among past first attempts of the same model and class that ran longer than this one has so far.","eta.byTodo":"about {duration} left by todo ({completed}/{total} steps)","eta.byTodoSoon":"under a minute left by todo ({completed}/{total} steps)","eta.byTodoHint":"Measured from the todo completion ratio only. Steps take different amounts of time, so this can be far off.","eta.rework":"rework attempt {attempt} \xb7 {duration} since first dispatch","eta.reworkAttempt":"rework attempt {attempt}","eta.reworkHint":"Rework attempts have almost no recorded durations, so no remaining time or % is estimated. Time since the first dispatch includes Main review and waiting between attempts.","eta.rangeMinutes":"{low}–{high} min","eta.range":"{low}–{high}","duration.seconds":"{seconds} s","duration.minutesSeconds":"{minutes} min {seconds} s","duration.minutes":"{minutes} min","duration.hours":"{hours} h","duration.hoursMinutes":"{hours} h {minutes} min","duration.underMinute":"under 1 min"},"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":"默认语音","progress.label":"进度","phase.investigate":"调查","phase.implement":"实现","phase.verify":"验证","phase.report":"报告","phase.current":"当前阶段 {phase}","phase.hint":"根据工具调用判断的当前阶段。验证后再次修改时会回到前一阶段。","progress.todo":"待办 {completed}/{total}({percent}%)","eta.label":"预计时间","eta.elapsed":"已用 {duration}","eta.remaining":"通常还需 {range}(过去 {samples} 次)","eta.percent":"约 {percent}%(估计)","eta.overrun":"已达到或超过过去最长记录({longest})","eta.sparseTail":"过去 {samples} 次中仅 {longerRuns} 次用时更长","eta.hint":"同模型、同等级的过去首次尝试中,运行时间超过当前已用时间的那些实行的剩余时间分布(中间一半)。","eta.byTodo":"按待办约还需 {duration}({completed}/{total} 步)","eta.byTodoSoon":"按待办 1 分钟内({completed}/{total} 步)","eta.byTodoHint":"仅按 todo 完成比例估算。各步骤耗时不同,误差可能很大。","eta.rework":"返工第 {attempt} 次 \xb7 自首次派发 {duration}","eta.reworkAttempt":"返工第 {attempt} 次","eta.reworkHint":"返工尝试几乎没有耗时记录,因此不估算剩余时间和百分比。自首次派发起的时间包含各次尝试之间 Main 审查和等待的时间。","eta.rangeMinutes":"{low}~{high} 分钟","eta.range":"{low}~{high}","duration.seconds":"{seconds} 秒","duration.minutesSeconds":"{minutes} 分 {seconds} 秒","duration.minutes":"{minutes} 分钟","duration.hours":"{hours} 小时","duration.hoursMinutes":"{hours} 小时 {minutes} 分钟","duration.underMinute":"不到 1 分钟"}};function rp(){let{locale:e}=(0,R.s)();return{st:(0,i.useCallback)((t,r)=>(0,J.u0)(e,t,ru,r),[e]),locale:e}}function rh({seed:e,size:t,provider:r}){let[a,s]=(0,i.useState)(!1),[l,o]=(0,i.useState)(!1);return a?(0,n.jsx)("span",{className:"account-avatar account-avatar-mono","data-tone":e%6,style:{width:t,height:t,fontSize:Math.round(.46*t)},"aria-hidden":"true",children:(0,t3.xl)(e).slice(0,1)}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"account-avatar-button",style:{width:t,height:t},onClick:e=>{e.stopPropagation(),o(!0)},"aria-label":(0,t3.xl)(e),children:(0,n.jsx)("img",{className:"account-avatar",src:(0,t3.uk)(e),width:t,height:t,alt:"","aria-hidden":"true",draggable:!1,onError:()=>s(!0)})}),l&&(0,n.jsx)(rf,{seed:e,provider:r,onClose:()=>o(!1)})]})}function rf({seed:e,provider:t,onClose:r}){let{t:a}=(0,R.s)(),s=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]);let l=(0,t3.xl)(e);return(0,F.createPortal)((0,n.jsxs)("dialog",{ref:s,className:"account-avatar-dialog","aria-label":l,onCancel:e=>{e.preventDefault(),r()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),r())},onClick:e=>{e.stopPropagation(),e.target===e.currentTarget&&r()},children:[(0,n.jsx)("img",{className:"account-avatar-full",src:(0,t3.uk)(e),width:256,height:256,alt:l,draggable:!1}),(0,n.jsxs)("p",{className:"account-avatar-caption",children:[(0,n.jsx)("span",{className:"account-avatar-caption-alias",children:l}),t?(0,n.jsx)("span",{className:"account-avatar-caption-provider",children:(0,t3.bN)(t)}):null]}),(0,n.jsx)("button",{type:"button",className:"account-avatar-close",onClick:r,children:a("i18n.close")})]}),document.body)}function rm(e){let t,r=[],n=null,i=0,a=0,s=0,l=0,o=[],d=[],c=()=>({lineNo:null,text:"",type:"empty"}),u=()=>{if(!n){o=[],d=[];return}let e=Math.max(o.length,d.length);for(let t=0;t<e;t++){let e=o[t]?{lineNo:o[t].lineNo,text:o[t].text,type:"removed"}:c(),r=d[t]?{lineNo:d[t].lineNo,text:d[t].text,type:"added"}:c();n.rows.push({type:"line",left:e,right:r})}o=[],d=[]};for(let c of e.split(/\r?\n/)){if(!(s>0||l>0)){if(c.startsWith("--- ")){u(),t=rg(c.slice(4));continue}if(c.startsWith("+++ ")){u(),n={oldPath:t,newPath:rg(c.slice(4)),rows:[]},r.push(n);continue}}let e=c.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){n||(n={rows:[]},r.push(n)),u(),i=Number(e[1]),a=Number(e[3]),s=void 0===e[2]?1:Number(e[2]),l=void 0===e[4]?1:Number(e[4]),n.rows.push({type:"hunk",text:c});continue}if(!n)continue;if(c.startsWith("\\ ")){u(),n.rows.push({type:"hunk",text:c});continue}let p=c[0],h=c.slice(1);" "===p?(u(),n.rows.push({type:"line",left:{lineNo:i++,text:h,type:"context"},right:{lineNo:a++,text:h,type:"context"}}),s>0&&s--,l>0&&l--):"-"===p?(o.push({lineNo:i++,text:h}),s>0&&s--):"+"===p?(d.push({lineNo:a++,text:h}),l>0&&l--):""!==c&&(u(),n.rows.push({type:"hunk",text:c}))}u();let p=r.filter(e=>e.rows.some(e=>"line"===e.type));return p.length>0?p:null}function rg(e){return e.split(" ")[0].trim()}function rx({task:e}){let t="completed"===e.status,r="abandoned"===e.status,i="in_progress"===e.status,a="blocked"===e.status;return(0,n.jsxs)("div",{role:"listitem","aria-label":`${e.status}: ${e.content}`,className:`todo-checklist-row ${t?"is-completed":r?"is-abandoned":a?"is-blocked":i?"is-active":"is-pending"}`,children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"todo-checklist-marker",children:t?"✓":r?"\xd7":a?"!":i?"›":""}),(0,n.jsxs)("span",{className:"todo-checklist-content",children:[e.content,a&&e.blocker?(0,n.jsxs)("span",{className:"todo-checklist-blocker",children:[" (",e.blocker,")"]}):null]})]})}let rv="/icons/catppuccin";function rb({name:e,size:t=14}){let r={width:t,height:t,"--catppuccin-icon-light":`url(${rv}/latte/${e}.svg)`,"--catppuccin-icon-dark":`url(${rv}/mocha/${e}.svg)`};return(0,n.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:r})}function ry({size:e=14,open:t=!1}){return(0,n.jsx)(rb,{name:t?"_folder_open":"_folder",size:e})}function rw({size:e=14}){return(0,n.jsx)(rb,{name:"_file",size:e})}let rk={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 rj(e,t=14){let r=e.toLowerCase(),i="dockerfile"===r||r.startsWith("dockerfile.")?"docker":".env"===r||r.startsWith(".env.")?"env":[".gitignore",".gitattributes",".gitmodules"].includes(r)?"git":"package-lock.json"===r?"npm-lock":"bun.lock"===r?"bun-lock":["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"].includes(r)?"next":[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(r)?"eslint":["yarn.lock","pnpm-lock.yaml","cargo.lock"].includes(r)?"lock":r.endsWith(".config.ts")||r.endsWith(".config.js")||r.endsWith(".config.mjs")||r.endsWith(".config.cjs")?"config":void 0;if(i)return(0,n.jsx)(rb,{name:i,size:t});let a=rk[r.split(".").pop()??""];return a?(0,n.jsx)(rb,{name:a,size:t}):(0,n.jsx)(rw,{size:t})}function rS({files:e,onOpenFile:t}){let{t:r}=(0,R.s)();return 0===e.length?null:(0,n.jsx)("div",{"aria-label":r("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:e.map(({filePath:e})=>{let i=ti(e);return(0,n.jsxs)("button",{type:"button",title:e,"aria-label":r("chat.openWrittenFile",{name:i}),onClick:()=>t?.(e),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:[rj(i,12),(0,n.jsx)("span",{children:i})]},e)})})}var rC=r(59959);let rN={verdicts:new Map,runs:new Map,latestByAgent:new Map};function rI(e){return Array.isArray(e)?e.filter(e=>"object"==typeof e&&null!==e):[]}function rT(e){return"string"==typeof e&&e.trim()?e:null}function rM(e){switch(e){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 r$(e){return"string"==typeof e?e:e.map(e=>"text"===e.type?e.text:"").join("\n")}function rR(e,t){if(t?.isError)return null;let r=rI(e.input.tasks),n=rI(t?.details?.progress),i=Math.max(r.length,n.length),a=[];for(let s=0;s<i;s++){let i=n.find(e=>e.index===s)??n[s],l=r[s],o=rT(i?.id)??rT(l?.name);o&&a.push({key:`${e.toolCallId}#${s}`,toolCallId:e.toolCallId,index:s,agentId:o,agent:rT(i?.agent)??rT(l?.agent),task:rT(i?.task)??rT(l?.task)??"",spawned:!!t})}return a}let rE=/<task-result\b([^>]*)>/g,rL=/(\w+)="([^"]*)"/g;function rz(e,t,r){return t.find(t=>t.parentToolCallId?t.parentToolCallId===e.toolCallId&&t.id===e.agentId:t.id===e.agentId&&r.latestByAgent.get(e.agentId)===e.key)}function rA(e,t,r){let n,i=rz(e,t,r),a=i?{key:e.key,identity:"live",live:i.assignment?i:{...i,assignment:e.task}}:{key:e.key,identity:"live",live:{id:e.agentId,index:e.index,agent:e.agent??"",agentSource:"user",status:"unknown",task:e.task,lastUpdate:0}},s=(0,rC.$V)(a),l=r.runs.get(e.key),o=null;i&&"unknown"!==i.status?(n=i.status,o="live"):l&&"unknown"!==l.status?(n=l.status,o="record"):n=e.spawned?"unobserved":"dispatching";let d=r.verdicts.get(e.key);return{member:e,title:s.title,explicitTitle:s.explicitTitle,stage:i?s.stage:null,model:i?(0,rC.A7)(a):null,run:n,runSource:o,verdict:d&&d.length>0?d[d.length-1]:null}}function rP(e){return"assistant"!==e.role?[]:e.content?.filter(e=>"toolCall"===e.type&&"task"===e.toolName)??[]}function rW(e,t,r){let n=-1;r.forEach((e,t)=>{"user"===e.role&&(n=t)});let i=r.slice(0,n+1).flatMap(rP),a=r.slice(n+1).flatMap(rP),s=t.findIndex(e=>"user"===e.role),l=0===a.length?-1:e.findIndex(e=>"answer"===e.kind&&(-1===s||e.idx<s));return -1===l?{continuing:null,atCompaction:[...i,...a]}:{continuing:{position:l,calls:a},atCompaction:i}}let rF={dispatching:"running",pending:"running",running:"running",completed:"awaiting",failed:"awaiting",aborted:"awaiting",unobserved:null},r_=(0,i.createContext)({ledger:rN,subagents:[],toolResults:new Map});function rD(e,t){if(0===e.length)return null;let r=[...e].sort((e,t)=>e-t),n=(r.length-1)*t,i=Math.floor(n),a=Math.ceil(n);return r[i]+(r[a]-r[i])*(n-i)}let rH=["investigate","implement","verify","report"],rO={edit:!0,write:!0,ast_edit:!0,multiedit:!0,notebookedit:!0},rB={bash:!0,eval:!0};function rU(e){if(e<6e4)return null;let t=Math.round(e/6e4);return{hours:Math.floor(t/60),minutes:t%60}}var rq=r(75514);function rK(e){let[t,r]=(0,i.useState)(()=>Date.now());return(0,i.useEffect)(()=>{let t=setInterval(()=>r(Date.now()),e);return()=>clearInterval(t)},[e]),t}function rV({sessionId:e,snapshots:t,client:r,enabled:n,transcripts:a=!0}){let s=(0,i.useMemo)(()=>t.filter(e=>(0,rq.Ch)(e.status)),[t]),l=n&&!!e&&s.length>0,o=(0,i.useMemo)(()=>s.map(e=>({key:e.id,liveId:e.id,status:e.status})),[s]),d=(0,rq._Z)(o,{sessionId:e??"",client:r,enabled:l&&a}),[c,u]=(0,i.useState)(null),p=s.map(e=>e.id).sort().join("\n");return(0,i.useEffect)(()=>{let t;if(!l||!e)return;let r=new AbortController,n=p.split("\n"),i=`/api/subagents/eta?sessionId=${encodeURIComponent(e)}`,a=!0,s=0;async function o(){try{let t=await fetch(i,{signal:AbortSignal.any([r.signal,AbortSignal.timeout(15e3)])}),s=t.ok?await t.json():null;!r.signal.aborted&&s&&s.sessionId===e&&s.histories&&"object"==typeof s.histories&&(u(s),a=n.some(e=>!s.histories[e]))}catch{}finally{if(!r.signal.aborted){let e=a&&s<3;e&&(s+=1),t=window.setTimeout(o,e?1e4:6e4)}}}return o(),()=>{r.abort(),window.clearTimeout(t)}},[p,l,e]),(0,i.useMemo)(()=>{let t=new Map;if(!l)return t;let r=c&&c.sessionId===e?c.histories:void 0;for(let e of s){let n=(a?d.get(e.id)?.entries??[]:[]).flatMap(e=>"message"in e?[e.message]:[]);t.set(e.id,{phase:function(e){if(0===e.length)return null;let t="investigate",r=!1;for(let n of e){if("assistant"!==n.role)continue;let e=n.content;if(Array.isArray(e))for(let n of e){if("toolCall"!==n.type)continue;let e=(n.toolName??"").toLowerCase().split(/[.:/]/).pop()??"";rO[e]?(r=!0,t="implement"):rB[e]?t=r?"verify":"investigate":"yield"===e&&(t="report",r=!1)}}return t}(n),todo:function(e){let t=new Map;for(let r of e)"toolResult"===r.role&&t.set(r.toolCallId,r);let r=e3([...e],t);if(!r)return null;let n=e7(r);return 0===n.total||null===n.percent?null:{completed:n.completed,total:n.total,percent:n.percent,activeTask:n.activeTask?.content??null}}(n),history:r?.[e.id]??null})}return t},[s,c,l,d,e,a])}function rJ(e,t){let r=rU(t);return r?0===r.hours?e("duration.minutes",{minutes:r.minutes}):0===r.minutes?e("duration.hours",{hours:r.hours}):e("duration.hoursMinutes",{hours:r.hours,minutes:r.minutes}):e("duration.underMinute")}function rG(e,t){let r=Math.floor(t/1e3);return r<60?e("duration.seconds",{seconds:r}):r<3600?e("duration.minutesSeconds",{minutes:Math.floor(r/60),seconds:r%60}):rJ(e,t)}function rY({phase:e}){let{st:t}=rp();return(0,n.jsxs)("span",{className:"subagent-phase-steps","data-phase":e,title:t("phase.hint"),style:{position:"relative"},children:[(0,n.jsx)("span",{className:"sr-only",children:t("phase.current",{phase:t(`phase.${e}`)})}),(0,n.jsx)("span",{"aria-hidden":"true",children:rH.map((r,i)=>(0,n.jsxs)("span",{children:[i>0&&(0,n.jsx)("span",{style:{color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},children:" › "}),(0,n.jsx)("span",{"data-current":r===e?"":void 0,style:r===e?{color:"var(--accent)",fontWeight:700}:{color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},children:t(`phase.${r}`)})]},r))})]})}function rZ(e,t){let r=e("progress.todo",{completed:t.completed,total:t.total,percent:t.percent});return t.activeTask?`${r} \xb7 ${t.activeTask}`:r}function rX({snapshot:e,view:t,id:r}){var i,a,s;let l,o,d,{st:c}=rp(),u=rK(5e3),p="number"!=typeof(l=e.progress?.durationMs)?null:l+(("pending"===e.status||"running"===e.status)&&e.lastUpdate>0?Math.max(0,u-e.lastUpdate):0);if(null===p)return null;let h=function(e,t){if(!e||e.rework||null===t||e.durationsSec.length<3)return null;let r=e.durationsSec.map(e=>1e3*e-t).filter(e=>e>0);if(r.length<3)return{kind:"overrun",longestMs:1e3*Math.max(...e.durationsSec),samples:e.durationsSec.length,longerRuns:r.length};let n=rD(r,.5)??0;return{kind:"remaining",p25Ms:rD(r,.25)??0,medianMs:n,p75Ms:rD(r,.75)??0,samples:r.length,percent:Math.round(t/(t+n)*100)}}(t.history,p),f=(i=t.todo,!i||null===p||0===i.completed||i.completed>=i.total?null:p*(i.total-i.completed)/i.completed),m={color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},g=t.history,x=g?.rework&&null!==g.firstDispatchedAtMs?u-g.firstDispatchedAtMs:null;return(0,n.jsxs)("span",{id:r,className:"subagent-live-eta","data-eta":h?.kind??(g?.rework?"rework":"none"),children:[(0,n.jsx)("span",{"data-elapsed":Math.floor(p/1e3),children:c("eta.elapsed",{duration:rG(c,p)})}),g?.rework&&(0,n.jsxs)(n.Fragment,{children:[" \xb7 ",(0,n.jsx)("span",{style:m,title:c("eta.reworkHint"),children:null!==x&&x>=0?c("eta.rework",{attempt:g.attempt,duration:rG(c,x)}):c("eta.reworkAttempt",{attempt:g.attempt})})]}),h?.kind==="remaining"&&(0,n.jsxs)(n.Fragment,{children:[" \xb7 ",(0,n.jsx)("span",{title:c("eta.hint"),children:c("eta.remaining",{range:(a=h.p25Ms,s=h.p75Ms,o=rU(a),d=rU(s),o&&d&&0===o.hours&&0===d.hours?o.minutes===d.minutes?c("duration.minutes",{minutes:o.minutes}):c("eta.rangeMinutes",{low:o.minutes,high:d.minutes}):c("eta.range",{low:rJ(c,a),high:rJ(c,s)})),samples:h.samples})})," \xb7 ",(0,n.jsx)("span",{style:m,children:c("eta.percent",{percent:h.percent})})]}),h?.kind==="overrun"&&(0,n.jsxs)(n.Fragment,{children:[" \xb7 ",(0,n.jsx)("span",{style:{color:"var(--warning)"},title:c("eta.hint"),children:0===h.longerRuns?c("eta.overrun",{longest:rJ(c,h.longestMs)}):c("eta.sparseTail",{samples:h.samples,longerRuns:h.longerRuns})})]}),null!==f&&t.todo&&(0,n.jsxs)(n.Fragment,{children:[" \xb7 ",(0,n.jsx)("span",{style:m,title:c("eta.byTodoHint"),children:f<6e4?c("eta.byTodoSoon",{completed:t.todo.completed,total:t.todo.total}):c("eta.byTodo",{duration:rJ(c,f),completed:t.todo.completed,total:t.todo.total})})]})]})}let rQ={dispatching:"run.dispatching",pending:"run.pending",running:"run.running",completed:"run.completed",failed:"run.failed",aborted:"run.aborted",unobserved:"run.unobserved"},r0={accepted:"verdict.accepted",rework:"verdict.rework",held:"verdict.held",none:"verdict.none"};function r1({maker:e,st:t}){let r=e.verdict?.verdict??"none",i=e.verdict?.attempt;return(0,n.jsxs)("span",{className:"answer-status-pair",children:[(0,n.jsx)("span",{className:"answer-status-run","data-state":e.run,children:t(rQ[e.run])}),(0,n.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→"}),(0,n.jsxs)("span",{className:"answer-status-verdict","data-verdict":r,children:[t(r0[r]),null!=i&&i>1?` \xb7 ${t("verdict.attempt",{attempt:i})}`:null]})]})}function r2({calls:e}){let{ledger:t,subagents:r,toolResults:a,onOpenPanel:s,focusedDispatch:l,sessionId:o}=(0,i.useContext)(r_),{st:d}=rp(),[c,u]=(0,i.useState)(!1),p=(0,i.useId)(),h=(0,i.useMemo)(()=>(0,rC.Et)(),[]),f=(0,i.useMemo)(()=>e.flatMap(e=>rR(e,a.get(e.toolCallId))??[]).map(e=>rA(e,r,t)),[e,a,r,t]),m=(0,i.useMemo)(()=>f.flatMap(e=>{if("pending"!==e.run&&"running"!==e.run)return[];let n=rz(e.member,r,t);return n?[n]:[]}),[f,r,t]),g=rV({sessionId:o,snapshots:m,client:h,enabled:!0,transcripts:c});if(0===f.length)return null;let x=0,v=0,b=0;for(let e of f)("dispatching"===e.run||"pending"===e.run||"running"===e.run)&&(x+=1),"completed"===e.run&&(v+=1),e.verdict?.verdict==="accepted"&&(b+=1);return(0,n.jsxs)("section",{className:l&&f.some(e=>e.member.key===l)?"answer-dispatch answer-dispatch-flash":"answer-dispatch","aria-label":d("dispatch.title",{count:f.length}),children:[(0,n.jsxs)("button",{type:"button",className:"answer-dispatch-toggle","aria-expanded":c,"aria-controls":p,title:d(c?"dispatch.collapse":"dispatch.expand"),onClick:()=>u(e=>!e),children:[(0,n.jsx)("span",{className:"answer-dispatch-heading",children:d("dispatch.title",{count:f.length})}),(0,n.jsx)("span",{className:"answer-dispatch-tally",children:d("dispatch.tally",{running:x,done:v,accepted:b})}),(0,n.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,n.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),(0,n.jsx)("ul",{className:"answer-dispatch-list",id:p,children:f.map(e=>{let t="pending"===e.run||"running"===e.run,r=t?m.find(t=>t.id===e.member.agentId):void 0,i=r?g.get(r.id):void 0;return(0,n.jsxs)("li",{className:"answer-dispatch-row","data-focused":e.member.key===l?"":void 0,children:[(0,n.jsxs)("div",{className:"answer-dispatch-line",children:[(0,n.jsx)("span",{className:"answer-dispatch-name",title:e.title,children:e.title}),(0,n.jsx)(r1,{maker:e,st:d})]}),r&&i&&(0,n.jsxs)("div",{className:"answer-dispatch-progress",children:[i.phase&&(0,n.jsx)(rY,{phase:i.phase}),i.phase&&i.todo?` \xb7 ${rZ(d,i.todo)}`:null,i.phase?" \xb7 ":null,(0,n.jsx)(rX,{snapshot:r,view:i})]}),c&&(0,n.jsxs)("dl",{className:"answer-dispatch-detail",children:[t&&(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:d("detail.stage")}),(0,n.jsx)("dd",{children:e.stage??d("detail.stageNone")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:d("detail.model")}),(0,n.jsx)("dd",{title:e.model?.model??void 0,children:e.model?.modelShort?`${e.model.modelShort}${e.model.effort?` \xb7 ${e.model.effort}`:""}${e.model.modelIsFallback?` \xb7 ${d("detail.fallback")}`:""}`:d("detail.modelNone")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:d("detail.agentId")}),(0,n.jsxs)("dd",{children:[(0,n.jsx)("span",{className:"answer-mono",children:e.member.agentId}),e.runSource?` \xb7 ${d("live"===e.runSource?"detail.source.live":"detail.source.record")}`:""]})]}),e.verdict?.reason&&(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:d("detail.reason")}),(0,n.jsx)("dd",{children:e.verdict.reason})]})]})]},e.member.key)})}),c&&s&&(0,n.jsxs)("div",{className:"answer-dispatch-links",children:[(0,n.jsx)("button",{type:"button",className:"answer-link",onClick:()=>s("subagents"),children:d("detail.openSubagents")}),(0,n.jsx)("button",{type:"button",className:"answer-link",onClick:()=>s("process"),children:d("detail.openProcess")})]})]})}function r4({summary:e,onOpenFile:t}){let{ledger:r,subagents:a,toolResults:s}=(0,i.useContext)(r_),{st:l}=rp(),[o,d]=(0,i.useState)(!1),c=(0,i.useId)(),u=(0,i.useMemo)(()=>e.dispatchCalls.flatMap(e=>rR(e,s.get(e.toolCallId))??[]).map(e=>rA(e,a,r)),[e.dispatchCalls,s,a,r]),p=e.checks.filter(e=>"failed"===e.state),h=e.checks.filter(e=>"passed"!==e.state),f=u.filter(e=>"failed"===e.run||"aborted"===e.run||"unobserved"===e.run||e.verdict?.verdict!=="accepted"),m=h.length+f.length;if(0===e.files.length&&0===e.checks.length&&0===u.length)return null;let g=[l("summary.files",{count:e.files.length}),l("summary.checks",{count:e.checks.length})];return p.length>0&&g.push(l("summary.checksFailed",{count:p.length})),m>0&&g.push(l("summary.unverified",{count:m})),(0,n.jsxs)("div",{className:"answer-summary",children:[(0,n.jsxs)("button",{type:"button",className:"answer-summary-toggle","aria-expanded":o,"aria-controls":c,title:l(o?"summary.collapse":"summary.expand"),onClick:()=>d(e=>!e),children:[(0,n.jsx)("span",{className:"answer-summary-text","data-unverified":m>0?"":void 0,children:g.join(" \xb7 ")}),(0,n.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,n.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),o&&(0,n.jsxs)("div",{className:"answer-summary-body",id:c,children:[e.files.length>0&&(0,n.jsxs)("section",{children:[(0,n.jsx)("h4",{className:"answer-summary-heading",children:l("summary.heading.files")}),(0,n.jsx)(rS,{files:e.files,onOpenFile:t})]}),e.checks.length>0&&(0,n.jsxs)("section",{children:[(0,n.jsx)("h4",{className:"answer-summary-heading",children:l("summary.heading.checks")}),(0,n.jsx)("ul",{className:"answer-summary-list",children:e.checks.map(e=>(0,n.jsxs)("li",{className:"answer-check","data-state":e.state,children:[(0,n.jsx)("code",{className:"answer-check-command",title:e.command,children:e.command}),(0,n.jsx)("span",{className:"answer-check-result",children:null!==e.exitCode?l("summary.check.exit",{code:e.exitCode}):l("failed"===e.state?"summary.check.error":"summary.check.unobserved")})]},e.toolCallId))})]}),m>0&&(0,n.jsxs)("section",{children:[(0,n.jsx)("h4",{className:"answer-summary-heading",children:l("summary.heading.unverified")}),(0,n.jsxs)("ul",{className:"answer-summary-list",children:[h.map(e=>(0,n.jsx)("li",{children:l("failed"===e.state?"summary.u.checkFailed":"summary.u.checkUnobserved",{command:e.command})},`check-${e.toolCallId}`)),f.map(e=>(0,n.jsxs)("li",{className:"answer-summary-maker",children:[(0,n.jsx)("span",{className:"answer-dispatch-name",title:e.title,children:e.title}),(0,n.jsx)(r1,{maker:e,st:l})]},`maker-${e.member.key}`))]})]})]})]})}let r5=/^att_[0-9a-f]{32}$/,r8=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function r6(e){return"string"==typeof e&&r5.test(e)}function r3(e){return"string"==typeof e&&r8.test(e)}class r7 extends Error{constructor(e,t){super(t),this.code=e,this.name="DocumentAttachmentError"}}let r9={markdown:"text/markdown",text:"text/plain",pdf:"application/pdf"},ne={".txt":!0,".csv":!0,".tsv":!0,".json":!0,".log":!0},nt={"text/plain":!0,"text/csv":!0,"text/tab-separated-values":!0,"application/json":!0,"text/json":!0};function nr(e){let t=e.name.toLocaleLowerCase();if(t.endsWith(".md")||t.endsWith(".markdown"))return"markdown";if(t.endsWith(".pdf"))return"pdf";let r=t.lastIndexOf(".");if(r>0&&ne[t.slice(r)])return"text";let n=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return"text/markdown"===n?"markdown":"application/pdf"===n?"pdf":n&&nt[n]?"text":null}let nn={".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 ni(e){let t=e.name.toLocaleLowerCase(),r=t.lastIndexOf("."),n=r>0?nn[t.slice(r)]:void 0;if(n)return n;let i=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return i?.startsWith("audio/")?i:null}function na(e,t){try{let r=new TextDecoder(e,{fatal:!0}).decode(t);return r.includes("\0")?null:r}catch{return null}}function ns(e){if(!Array.isArray(e))return[];let t=[],r=0,n=0;for(let i of e){if(i&&"object"==typeof i&&"string"==typeof i.name&&i.name.length>0&&("text/markdown"===i.mimeType||"text/plain"===i.mimeType||"application/pdf"===i.mimeType)&&"number"==typeof i.size&&Number.isSafeInteger(i.size)&&i.size>=0&&i.size<=8388608&&"string"==typeof i.text&&i.text.length<=12e4){if(t.length>=3)break;!(r+i.size>0x1000000)&&(n+i.text.length>24e4||(t.push({name:i.name,mimeType:i.mimeType,size:i.size,text:i.text,...r6(i.attachmentId)?{attachmentId:i.attachmentId}:{}}),r+=i.size,n+=i.text.length))}}return t}async function nl(e){let t,r=nr(e);if(!r)throw new r7("unsupported",`Unsupported document type: ${e.name}`);if(e.size>8388608)throw new r7("file_too_large",`${e.name} exceeds the document size limit`);if("pdf"===r)t=await nx(e);else{try{t=await e.text()}catch(e){throw new r7("read_failed",e instanceof Error?e.message:String(e))}nv(t)}return{name:e.name,mimeType:r9[r],size:e.size,text:t}}function no(e,t){let r=ns(t);if(0===r.length)return e;let n={userMessageLength:e.length,documents:r.map(({name:e,mimeType:t,size:r,text:n})=>({name:e,mimeType:t,size:r,textLength:n.length}))},i=`${nb}${JSON.stringify(n)}${ny}
|
|
@@ -16,7 +16,7 @@ Attached: ${r}`:`Attached: ${r}`}(g)).then(()=>{m(!0),setTimeout(()=>m(!1),1500)
|
|
|
16
16
|
${t}`)),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{if(void 0!==a)return;let r=!0;return(function(e,t){let r=`${e}
|
|
17
17
|
${t}`,n=eO.get(r);if(void 0!==n)return Promise.resolve(n);let i=eB.get(r);if(i)return i;let a=fetch(eD(e,t),{cache:"no-store"}).then(async e=>{if(!e.ok)return 0;let t=await e.json(),n=Number.isSafeInteger(t.count)&&t.count>=0?t.count:0;return eO.set(r,n),n}).catch(()=>0).finally(()=>eB.delete(r));return eB.set(r,a),a})(e,t).then(e=>{r&&s(e)}),()=>{r=!1}},[a,e,t]),!a)return null;let u=Array.from({length:a},(e,t)=>t).filter(e=>!d.has(e));return 0===u.length?null:(0,n.jsxs)("div",{className:"tool-image-strip","data-tool-call-id":t,children:[u.map(i=>(0,n.jsx)("button",{type:"button",className:"tool-image-thumb","aria-label":r("i18n.zoomIn"),onClick:()=>o(i),children:(0,n.jsx)("img",{src:eD(e,t,i),alt:"",loading:"lazy",draggable:!1,onError:()=>c(e=>new Set(e).add(i))})},i)),null!==l&&(0,n.jsx)(n_,{src:eD(e,t,l),onClose:()=>o(null)})]})}function n_({src:e,onClose:t}){let{t:r}=(0,R.s)(),a=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=a.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,F.createPortal)((0,n.jsxs)("dialog",{ref:a,className:"tool-image-dialog",onCancel:e=>{e.preventDefault(),t()},onClick:e=>{e.target===e.currentTarget&&t()},children:[(0,n.jsx)("img",{className:"tool-image-full",src:e,alt:"",draggable:!1}),(0,n.jsx)("button",{type:"button",className:"tool-image-close",onClick:t,children:r("i18n.close")})]}),document.body)}function nD({block:e,isStreaming:t,cwd:r,onOpenFile:i}){return(0,n.jsx)(nT,{isStreaming:t,cwd:r,onOpenFile:i,children:e.text})}function nH({block:e,duration:t,sessionId:r,entryId:a,blockIndex:s}){let{t:l}=(0,R.s)(),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!0===e.deferred),[p,h]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!e.deferred){d(null),u(!1),h(null);return}let t=!1;return r&&a?(u(!0),h(null),(function(e,t,r){let n=`${e}:${t}:${r}`,i=nI.get(n);if(i)return nI.delete(n),nI.set(n,i),i;let a=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${r}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw nI.delete(n),e});if(nI.set(n,a),nI.size>100){let e=nI.keys().next().value;e&&nI.delete(e)}return a})(r,a,s).then(e=>{t||d(e)}).catch(e=>{t||h(e instanceof Error?e.message:String(e))}).finally(()=>{t||u(!1)}),()=>{t=!0}):(u(!1),h(l("i18n.thinkingUnavailable")),()=>{t=!0})},[e.deferred,e.thinking,s,a,r,l]);let f=e.deferred?o:e.thinking,m="string"==typeof f&&f.trim().length>0;return(0,n.jsxs)("div",{className:"markdown-thinking","aria-label":l("i18n.thinking"),children:[(0,n.jsx)("div",{className:"markdown-thinking-content",children:c?(0,n.jsx)("span",{className:"markdown-thinking-status",children:l("i18n.loadingThinking")}):p?(0,n.jsx)("span",{className:"markdown-thinking-error",children:p}):m?(0,n.jsx)(tJ,{className:"markdown-thinking-body",children:f}):(0,n.jsx)("span",{className:"markdown-thinking-status",children:l("chat.thinking")})}),void 0!==t&&m&&(0,n.jsxs)("span",{className:"markdown-thinking-duration",children:[t,"s"]})]})}function nO({block:e,result:t,duration:r}){let a,s=e.toolName.toLowerCase(),l="edit"===s||s.startsWith("edit_")||s.endsWith(".edit")||s.endsWith("_edit")||s.includes("str_replace")||s.includes("replace_editor"),[o,d]=(0,i.useState)(l),c=JSON.stringify(e.input,null,2),u="todo"===s||s.endsWith(".todo")||s.endsWith("_todo"),p="bash"===s||s.startsWith("bash ")||s.endsWith(".bash")||s.endsWith("_bash"),h=t&&!t.isError?function(e){let t=e.details;if(!n0(t))return null;let r="string"==typeof t.patch?t.patch:null;if(r)return{text:r};let n="string"==typeof t.diff?t.diff:null;return n?{text:n}:null}(t):null,f=u?"unknown"===(a=e6(e,t)).kind||0===a.phases.length?null:a.phases:null,m=h?h.text.split(/\r?\n/).reduce((e,t)=>(t.startsWith("+")&&!t.startsWith("+++")&&(e.added+=1),t.startsWith("-")&&!t.startsWith("---")&&(e.removed+=1),e),{added:0,removed:0}):null,g=t?t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,x=null!==g&&("(no output)"===g.trim()||""===g.trim()),v=t?.isError??!1;if(p)return(0,n.jsx)(nJ,{command:n0(e.input)&&"string"==typeof e.input.command?e.input.command:"",output:g??"",pending:!t,isError:v,duration:r,local:s.includes("(local)")});if(u&&f)return(0,n.jsx)(nV,{phases:f});let b=!!(f||h),y=function(e,t){if(t){let e=t.flatMap(e=>e.tasks),r=e.filter(e=>"completed"===e.status||"abandoned"===e.status).length;return`${r}/${e.length} tasks`}return function(e){var t;let r=e.input;if(!r||"object"!=typeof r)return"";let n=Object.keys(r);if(0===n.length)return"";let i=e.toolName.toLowerCase();if(t=i,["grep","read","write","glob"].some(e=>t===e||t.endsWith(`.${e}`)||t.endsWith(`_${e}`))&&"string"==typeof r.i){let e=r.i.trim();if(e)return e.slice(0,120)}if(("eval"===i||i.endsWith(".eval")||i.endsWith("_eval"))&&"string"==typeof r.title){let e=r.title.trim();if(e)return e.slice(0,120)}if("command"in r)return String(r.command).slice(0,120);if("path"in r)return String(r.path).slice(0,120);if("file_path"in r)return String(r.file_path).slice(0,120);if("pattern"in r)return String(r.pattern).slice(0,120);if("query"in r)return String(r.query).slice(0,120);let a=n.map(e=>r[e]).find(e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e);if(void 0!==a)return String(a).slice(0,120);try{return JSON.stringify(r).slice(0,120)}catch{return n.join(", ").slice(0,120)}}(e)}(e,f);return(0,n.jsxs)("div",{className:`tool-call-card${v?" is-error":" is-success"}`,style:{borderRadius:7,overflow:"hidden",fontSize:12,border:v?"1px solid var(--danger-line)":"1px solid var(--success-line)",background:v?"var(--danger-soft)":"var(--success-soft)"},children:[(0,n.jsxs)("button",{className:"tool-call-header",onClick:()=>d(e=>!e),"aria-expanded":o,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,n.jsx)(nq,{toolName:e.toolName,isError:v}),(0,n.jsx)("span",{className:"tool-call-name",style:{color:v?"var(--danger)":"var(--success)",fontFamily:"var(--font-mono)",fontWeight:600,fontSize:11,flexShrink:0},children:e.toolName}),(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:y}),m&&(0,n.jsxs)("span",{title:`${m.added} lines added, ${m.removed} lines removed`,"aria-label":`${m.added} lines added, ${m.removed} lines removed`,style:{display:"inline-flex",alignItems:"center",gap:6,flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,fontVariantNumeric:"tabular-nums"},children:[(0,n.jsxs)("span",{style:{color:"var(--success)"},children:["+",m.added]}),(0,n.jsxs)("span",{style:{color:"var(--danger)"},children:["−",m.removed]})]}),void 0!==r&&(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:[r,"s"]}),(0,n.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:o?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,n.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),h&&(0,n.jsx)("div",{style:{maxHeight:o?560:260,overflowY:"auto",overflowX:"hidden",borderTop:"1px solid var(--success-line)"},children:(0,n.jsx)(nG,{diff:h})}),t&&v&&(0,n.jsx)(n1,{text:g??"",isEmpty:x,isError:!0}),o&&!b&&(0,n.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:v?"1px solid var(--danger-line)":"1px solid var(--success-line)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:c}),o&&t&&!b&&!v&&(0,n.jsx)(n1,{text:g??"",isEmpty:x,isError:!1})]})}let nB={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 nU(e,t){let r=e.trim().toLowerCase();return r===t||r.endsWith(`.${t}`)||r.endsWith(`_${t}`)||r.split(/[.\s:_-]+/).includes(t)}function nq({toolName:e,isError:t}){let r,i=(r=e.trim().toLowerCase()).includes("str_replace")||r.includes("replace_editor")||nU(r,"edit")?"edit":nU(r,"read")||nU(r,"cat")?"read":nU(r,"write")||nU(r,"save")?"write":nU(r,"glob")||nU(r,"find")?"glob":nU(r,"grep")||nU(r,"search")?"grep":nU(r,"bash")||nU(r,"shell")||nU(r,"exec")?"bash":nU(r,"todo")?"todo":nU(r,"eval")?"eval":nU(r,"task")||nU(r,"agent")?"task":nU(r,"browser")||nU(r,"web_search")||nU(r,"fetch")?"browser":nU(r,"image")||nU(r,"inspect_image")?"image":"generic",a=t?"var(--danger)":nB[i];return(0,n.jsx)("span",{"aria-hidden":"true","data-tool-icon":i,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0,color:a},children:(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.15",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)(nK,{kind:i})})})}function nK({kind:e}){switch(e){case"read":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,n.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,n.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,n.jsx)("circle",{cx:"6.55",cy:"9.1",r:"0.7",fill:"currentColor",stroke:"none"})]});case"write":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,n.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,n.jsx)("path",{d:"M6.55 6.25v4.15m-1.7-1.55 1.7 1.7 1.7-1.7"})]});case"glob":return(0,n.jsxs)(n.Fragment,{children:[(0,n.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,n.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,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("circle",{cx:"5.9",cy:"5.9",r:"3.25"}),(0,n.jsx)("path",{d:"m8.35 8.35 3.25 3.25"}),(0,n.jsx)("path",{d:"M4.6 5.2h2.5M4.6 6.8h1.7"})]});case"edit":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,n.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,n.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,n.jsx)("path",{d:"m8.45 6.55 1.45 1.45"})]});case"bash":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"1.5",y:"2.1",width:"11",height:"9.8",rx:"1.3"}),(0,n.jsx)("path",{d:"m4 5.2 1.8 1.8L4 8.8M7.2 8.8h2.3"})]});case"todo":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7"}),(0,n.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,n.jsx)(n.Fragment,{children:(0,n.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,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("circle",{cx:"3.1",cy:"3.2",r:"1.25"}),(0,n.jsx)("circle",{cx:"10.9",cy:"3.2",r:"1.25"}),(0,n.jsx)("circle",{cx:"10.9",cy:"10.8",r:"1.25"}),(0,n.jsx)("path",{d:"M4.35 3.2h2.1a2.9 2.9 0 0 1 2.9 2.9v3.45"}),(0,n.jsx)("path",{d:"M9.35 3.2h-1.1"})]});case"browser":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("circle",{cx:"7",cy:"7",r:"5.2"}),(0,n.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,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"1.75",y:"2.25",width:"10.5",height:"9.5",rx:"1.15"}),(0,n.jsx)("circle",{cx:"4.8",cy:"5.1",r:"1"}),(0,n.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,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"1.75",y:"2",width:"10.5",height:"10",rx:"1.3"}),(0,n.jsx)("path",{d:"M4.35 5h5.3M4.35 7.35h3.8M4.35 9.7h4.6"})]})}}function nV({phases:e}){let t=e.reduce((e,t)=>e+t.tasks.length,0),r=e.reduce((e,t)=>e+t.tasks.filter(e=>"completed"===e.status).length,0);return(0,n.jsxs)("div",{className:"todo-checklist-preview",role:"list","aria-label":`Todo ${t} tasks`,children:[(0,n.jsxs)("div",{className:"todo-checklist-header",children:[(0,n.jsxs)("svg",{className:"todo-checklist-icon",width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"}),(0,n.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,n.jsx)("span",{className:"todo-checklist-title",children:"Todo"}),(0,n.jsxs)("span",{className:"todo-checklist-count",children:[t," ",1===t?"task":"tasks"]}),r>0&&r<t&&(0,n.jsxs)("span",{className:"todo-checklist-progress",children:[r,"/",t]})]}),(0,n.jsx)("div",{className:"todo-checklist-body",children:e.map((t,r)=>(0,n.jsxs)("div",{className:"todo-checklist-phase",children:[e.length>1&&(0,n.jsx)("div",{className:"todo-checklist-phase-name",children:t.name}),t.tasks.map((e,t)=>(0,n.jsx)(rx,{task:e},`${e.content}-${t}`))]},`${t.name}-${r}`))})]})}function nJ({command:e,output:t,pending:r,isError:i,duration:a,local:s}){let{isDark:l}=tO(),{t:o}=(0,R.s)(),d=eI(t.split(/\r?\n/)),c=1===d.length&&""===d[0]?[]:d,u=r?o("chat.runningCommand"):i?"failed":"";return(0,n.jsxs)("div",{className:`shell-output-preview${i?" is-error":""}`,children:[(0,n.jsxs)("div",{className:"shell-command-line",children:[(0,n.jsx)("span",{className:"shell-command-prompt","aria-hidden":"true",children:"$"}),(0,n.jsx)(e9.A,{className:"shell-command-code",language:"bash",style:l?te.xJ:te.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:e||" "}),s&&(0,n.jsx)("span",{className:"shell-local-label",children:"local"})]}),(0,n.jsxs)("div",{className:"shell-output-panel",children:[(0,n.jsxs)("div",{className:"shell-output-divider",children:[(0,n.jsx)("span",{className:"shell-output-label",children:"Output"}),u&&(0,n.jsx)("span",{className:`shell-output-status${i?" is-error":r?" is-pending":""}`,children:u})]}),(0,n.jsxs)("div",{className:"shell-output-body","aria-live":r?"polite":void 0,children:[0===c.length&&!r&&(0,n.jsx)("span",{className:"shell-output-empty",children:o("i18n.noOutput")}),c.map((e,t)=>{let r=ej(e).trimStart(),a=i||/^(?:error|fatal|failed|failure|✖|x\b)/i.test(r)?"is-error":/^(?:warning|warn|!)/i.test(r)?"is-warning":/^(?:success|passed|ok\b|✓|\+)/i.test(r)?"is-success":"";return(0,n.jsxs)("div",{className:`shell-output-line ${a}`.trim(),children:[eT(e).map((e,t)=>Object.keys(e.style).length>0?(0,n.jsx)("span",{style:e.style,children:e.text},t):(0,n.jsx)("span",{children:e.text},t)),""===e?"\xa0":null]},t)}),r&&(0,n.jsx)("span",{className:"shell-output-pending","aria-label":o("chat.runningCommand"),children:"▋"})]})]}),void 0!==a&&(0,n.jsxs)("div",{className:"shell-output-footer",children:[a,"s"]})]})}function nG({diff:e}){return(0,n.jsx)("div",{style:{borderTop:"1px solid var(--success-line)",background:"var(--bg)"},children:(0,n.jsx)(nY,{text:e.text})})}function nY({text:e}){let{t}=(0,R.s)(),r=(0,i.useMemo)(()=>rm(e),[e]);if(!r)return(0,n.jsx)(nQ,{text:e});let a=r.length>1;return(0,n.jsx)("div",{style:{background:"var(--bg)"},children:r.map((e,r)=>(0,n.jsxs)("div",{style:{minWidth:0,borderTop:0===r?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55},children:[a&&(0,n.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,n.jsx)(nZ,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,n.jsx)(nZ,{title:e.newPath||t("i18n.after"),side:"right"})]}),(0,n.jsx)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)"},children:e.rows.map((e,t)=>"hunk"===e.type?null:(0,n.jsxs)("div",{style:{display:"contents"},children:[(0,n.jsx)(nX,{cell:e.left,side:"left"}),(0,n.jsx)(nX,{cell:e.right,side:"right"})]},t))})]},r))})}function nZ({title:e,side:t}){return(0,n.jsx)("div",{title:e,style:{padding:"5px 10px",color:"var(--text-dim)",borderRight:"left"===t?"1px solid var(--border)":"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})}function nX({cell:e,side:t}){let r="added"===e.type?"var(--success-soft)":"removed"===e.type?"var(--danger-soft)":"empty"===e.type?"var(--bg-subtle)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",a="added"===e.type?"var(--success)":"removed"===e.type?"var(--danger)":"var(--text-dim)";return(0,n.jsxs)("div",{style:{display:"flex",minWidth:0,background:r,borderRight:"left"===t?"1px solid var(--border)":"none"},children:[(0,n.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:e.lineNo??""}),(0,n.jsx)("span",{style:{width:18,padding:"0 5px",color:a,userSelect:"none",fontWeight:"context"===e.type||"empty"===e.type?400:700,flexShrink:0},children:i}),(0,n.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===e.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:e.text||"\xa0"})]})}function nQ({text:e}){let t=e.split(/\r?\n/);return(0,n.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55,minWidth:0},children:t.map((e,t)=>{let r=e.startsWith("@@")?"hunk":e.startsWith("+")&&!e.startsWith("+++")?"added":e.startsWith("-")&&!e.startsWith("---")?"removed":"context";return(0,n.jsxs)("div",{style:{display:"flex",background:"added"===r?"var(--success-soft)":"removed"===r?"var(--danger-soft)":"hunk"===r?"var(--accent-soft)":"transparent",borderLeft:"added"===r?"3px solid var(--success)":"removed"===r?"3px solid var(--danger)":"hunk"===r?"3px solid var(--accent)":"3px solid transparent"},children:[(0,n.jsx)("span",{style:{width:48,padding:"0 8px",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",textAlign:"right",userSelect:"none",flexShrink:0},children:t+1}),(0,n.jsx)("span",{style:{padding:"0 10px",whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:"added"===r?"var(--success)":"removed"===r?"var(--danger)":"hunk"===r?"var(--accent)":"var(--text)"},children:e||"\xa0"})]},t)})})}function n0(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function n1({text:e,isEmpty:t,isError:r}){let{t:i}=(0,R.s)();return(0,n.jsx)("div",{style:{borderTop:`1px solid ${r?"var(--danger-line)":"var(--success-line)"}`,background:r?"var(--danger-soft)":"var(--bg-subtle)"},children:(0,n.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:r?"var(--danger)":t?"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:t?"italic":"normal",opacity:t?.6:1},children:t?i("i18n.noOutput"):e})})}function n2({message:e}){let{t}=(0,R.s)(),r=n6(e.content),a=(0,i.useMemo)(()=>{let e,t,n,i,a;return e=[],t=[],n=r.match(tY),i=n?.[1]??"",a=n?.index===void 0?r:r.slice(0,n.index),i.replace(tG,(r,n,i)=>{let a=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===n?e.push(...a):t.push(...a),""}),{body:a.trim(),readFiles:e,modifiedFiles:t}},[r]),s=nE(e.timestamp),l=e.details&&"object"==typeof e.details&&"tokensBefore"in e.details&&"number"==typeof e.details.tokensBefore&&e.details.tokensBefore>0?e.details.tokensBefore:null;return(0,n.jsx)("div",{style:{marginBottom:16},children:(0,n.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,n.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,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:"compaction"}),null!==l&&(0,n.jsx)("span",{style:{fontSize:11},children:t("chat.compactedFrom",{tokens:tZ(l)})}),s&&(0,n.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:s})]}),(0,n.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,n.jsx)("div",{style:{color:"var(--text)",fontSize:15,fontWeight:700,lineHeight:1.35},children:t("i18n.conversationCompacted")}),(0,n.jsx)("div",{style:{marginTop:3,marginBottom:10,color:"var(--text)",fontSize:14,lineHeight:1.5},children:t("i18n.compactionDescription")}),a.body?(0,n.jsx)(tJ,{className:"markdown-compaction-message",children:a.body}):(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:t("i18n.noSummary")}),(0,n.jsx)(n4,{readFiles:a.readFiles,modifiedFiles:a.modifiedFiles})]})]})})}function n4({readFiles:e,modifiedFiles:t}){let{t:r}=(0,R.s)();if(0===e.length+t.length)return null;let i=[];return e.length>0&&i.push(`${e.length} read`),t.length>0&&i.push(`${t.length} modified`),(0,n.jsxs)("details",{className:"compaction-file-details",children:[(0,n.jsx)("summary",{children:r("i18n.fileContext",{details:i.join(", ")})}),t.length>0&&(0,n.jsx)(n5,{title:r("i18n.modifiedFiles"),files:t}),e.length>0&&(0,n.jsx)(n5,{title:r("i18n.readFiles"),files:e})]})}function n5({title:e,files:t}){return(0,n.jsxs)("div",{className:"compaction-file-section",children:[(0,n.jsx)("div",{className:"compaction-file-title",children:e}),(0,n.jsx)("ul",{className:"compaction-file-list",children:t.map(e=>(0,n.jsx)("li",{children:e},e))})]})}function n8({message:e,cwd:t,onOpenFile:r}){var a;let s,{t:l}=(0,R.s)(),o=!1===e.display,[d,c]=(0,i.useState)(!o),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(!1),m=n6(e.content),g="string"==typeof(a=e.content)?[]:a.filter(e=>"image"===e.type),x=void 0!==e.details,v=x?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(e.details):"",b=e.customType||"extension",y=nE(e.timestamp);return(0,n.jsx)("div",{style:{marginBottom:16},children:(0,n.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:o?"var(--bg-subtle)":"var(--bg)",opacity:o&&!d?.82:1},children:[(0,n.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,n.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:b}),o&&(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:l("i18n.hiddenExtensionMessage")}),y&&(0,n.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:y})]}),d?(0,n.jsxs)("div",{style:{padding:"6px 9px"},children:[g.length>0&&(0,n.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!m},children:g.map((e,t)=>{let r=n3(e);return r?(0,n.jsx)("img",{src:r,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}},t):null})}),m?(0,n.jsx)(tJ,{className:"markdown-custom-message",cwd:t,onOpenFile:r,children:m}):(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:l("i18n.noMessage")})]}):(0,n.jsx)("button",{onClick:()=>c(!0),style:{display:"block",width:"100%",padding:"8px 10px",border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:12,textAlign:"left"},children:m?(s=m.replace(/\s+/g," ").trim())?s.length>140?`${s.slice(0,140)}...`:s:"Show extension message":l("i18n.showExtensionMessage")}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[m||v?(0,n.jsx)("button",{onClick:()=>{tB(m||v).then(()=>{f(!0),setTimeout(()=>f(!1),1500)})},style:{padding:"3px 7px",border:"none",background:"none",color:h?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:l(h?"i18n.copied":"i18n.copy")}):null,(x||o)&&(0,n.jsx)("button",{onClick:()=>{o?c(e=>!e):p(e=>!e)},style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:l(o?d?"i18n.collapse":"i18n.expand":u?"i18n.hideDetails":"i18n.showDetails")})]}),x&&(o&&d||!o&&u)&&(0,n.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:v})]})})}function n6(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function n3(e){return e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:""}function n7({message:e,sessionId:t}){let[r,a]=(0,i.useState)(null),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(null),c=!e.output&&void 0===e.exitCode&&!e.cancelled,u=e.cancelled||void 0!==e.exitCode&&0!==e.exitCode,p=t&&e.fullOutputPath?`/api/agent/${encodeURIComponent(t)}/bash-output?path=${encodeURIComponent(e.fullOutputPath)}`:null,h=e.truncated&&p&&null===r,f=r??e.output;async function m(){if(p){l(!0),d(null);try{let e=await fetch(p),t=await e.json();t.success?a(t.data?.output??""):d(t.error??"failed")}catch(e){d(String(e))}finally{l(!1)}}}let g=e.excludeFromContext?"bash (local)":"bash",x={type:"toolCall",toolCallId:`bash-${e.timestamp??""}`,toolName:g,input:{command:e.command}},v=c?void 0:{role:"toolResult",toolCallId:x.toolCallId,toolName:g,content:f?[{type:"text",text:f}]:[],isError:u,timestamp:e.timestamp};return(0,n.jsxs)("div",{style:{margin:"6px 0"},children:[(0,n.jsx)(nO,{block:x,result:v}),e.truncated&&p&&(0,n.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[h&&(0,n.jsx)("button",{onClick:m,disabled:s,style:{background:"none",border:"none",color:"var(--accent)",cursor:s?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:s?"loading…":"view full output"}),(0,n.jsx)("a",{href:`${p}&download=1`,style:{marginLeft:10*!!h,color:"var(--accent)",fontSize:11,textDecoration:"underline"},children:"download full output"}),o&&(0,n.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:["(",o,")"]})]})]})}function n9({summary:e,onJump:t,onOpenPanel:r}){let{st:i}=rp();if(!e)return null;let{target:a}=e,s=a.position;if(null===s&&!r)return null;let l=i(null!==s?"dock.jump":"dock.openPanel",{title:a.maker.title});return(0,n.jsxs)("button",{type:"button",className:"run-status-line answer-dock-line","data-tone":"accent",title:l,onClick:()=>{null!==s?t(s,a.maker.member.key):r?.()},children:[(0,n.jsx)("span",{className:"run-status-label",children:i("dock.label")}),(0,n.jsxs)("span",{className:"answer-dock-counts",children:[e.running>0&&(0,n.jsx)("span",{className:"answer-dock-count","data-phase":"running",children:i("dock.running",{count:e.running})}),e.awaiting>0&&(0,n.jsx)("span",{className:"answer-dock-count","data-phase":"awaiting",children:i("dock.awaiting",{count:e.awaiting})})]}),(0,n.jsx)("span",{className:"answer-dock-title",children:a.maker.title}),(0,n.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,n.jsx)("polyline",{points:"18 15 12 9 6 15"})})]})}r(21340);let ie=/(?:^|[^\w-])(?:tests?|typecheck|tsc|lint|eslint|vitest|jest|pytest|build|check|verify|smoke)(?![\w])/i,it="cuelo-chat-search",ir="cuelo-chat-search-active";function ii(e,t){if("u">typeof CSS&&"highlights"in CSS){if(0===t.length||"u"<typeof Highlight)return void CSS.highlights.delete(e);CSS.highlights.set(e,new Highlight(...t))}}function ia({open:e,onClose:t,containerRef:r,index:a,renderedStart:s,renderedEnd:l,contentKey:o,onReveal:d,onProgrammaticScroll:c,focusRequest:u,t:p}){let h=(0,i.useRef)(null),[f,m]=(0,i.useState)(""),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)({index:-1,total:0}),y=(0,i.useDeferredValue)(f),w=e?y.trim().toLowerCase():"",k=(0,i.useRef)(g);k.current=g;let j=(0,i.useRef)([]),S=(0,i.useRef)({key:null,needle:"",rendered:!1});(0,i.useEffect)(()=>{if(!e)return;let t=requestAnimationFrame(()=>h.current?.select());return()=>cancelAnimationFrame(t)},[e,u]),(0,i.useEffect)(()=>()=>{ii(it,[]),ii(ir,[])},[]),(0,i.useLayoutEffect)(()=>{let t=r.current;if(!e||!w||!t){ii(it,[]),ii(ir,[]),j.current=[],S.current={key:null,needle:"",rendered:!1},b(e=>0===e.total&&-1===e.index?e:{index:-1,total:0});return}let n=requestAnimationFrame(()=>{let e=function(e,t){let r=new Map,n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>(e.textContent??"").toLowerCase().includes(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(let e=n.nextNode();e;e=n.nextNode()){let n=e.parentElement?.closest("[data-chat-item]"),i=n?Number(n.dataset.chatItem):NaN;if(!Number.isInteger(i))continue;let a=(e.textContent??"").toLowerCase(),s=r.get(i);s||(s=[],r.set(i,s));for(let r=a.indexOf(t);-1!==r;r=a.indexOf(t,r+t.length)){let n=document.createRange();n.setStart(e,r),n.setEnd(e,r+t.length),s.push(n)}}return r}(t,w),r=new Map;for(let[t,n]of e)r.set(t,n.length);let n=function(e,t,r,n,i){let a=[];if(!t)return a;for(let s=0;s<e.length;s++){let l=s>=n&&s<i?r.get(s)??0:function(e,t){if(!t)return 0;let r=0;for(let n=e.indexOf(t);-1!==n;n=e.indexOf(t,n+t.length))r+=1;return r}(e[s],t);for(let e=0;e<l;e++)a.push({item:s,k:e})}return a}(a,w,r,s,l);j.current=n;let i=e0(n,k.current);b(e=>e.index===i&&e.total===n.length?e:{index:i,total:n.length});let o=[];for(let t of e.values())for(let e of t)o.push(e);if(ii(it,o),i<0){ii(ir,[]),S.current={key:null,needle:w,rendered:!1};return}let u=n[i],p=k.current;p&&p.item===u.item&&p.k===u.k||x(u);let h=u.item>=s&&u.item<l,f=S.current,m=f.needle!==w||f.key?.item!==u.item||f.key?.k!==u.k||!f.rendered&&h;if(S.current={key:u,needle:w,rendered:h},!h){ii(ir,[]),m&&d(u.item);return}let g=e.get(u.item)?.[u.k];if(ii(ir,g?[g]:[]),m)if(c(),g){let e,r;e=g.getBoundingClientRect(),r=t.getBoundingClientRect(),e.height<=0||e.top>=r.top+48&&e.bottom<=r.bottom-48||(t.scrollTop+=e.top-r.top-(t.clientHeight-e.height)/2)}else t.querySelector(`[data-chat-item="${u.item}"] > *`)?.scrollIntoView({block:"center"})});return()=>cancelAnimationFrame(n)},[e,w,a,s,l,o,g,r,d,c]);let C=(0,i.useCallback)(e=>{let t=j.current;if(0===t.length)return;let r=e0(t,k.current);x(t[(r+e+t.length)%t.length])},[]);if(!e)return null;let N=f.trim().length>0?0===v.total?p("chat.searchNoResults"):p("chat.searchCount",{index:v.index+1,total:v.total}):"";return(0,n.jsxs)("div",{className:"chat-find-bar",role:"search","data-dismissible-layer":"",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),t())},children:[(0,n.jsx)("input",{ref:h,type:"search",value:f,onChange:e=>m(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),C(e.shiftKey?-1:1))},placeholder:p("chat.searchPlaceholder"),"aria-label":p("chat.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),(0,n.jsx)("span",{className:"chat-find-count","aria-live":"polite",children:N}),(0,n.jsx)("button",{type:"button",onClick:()=>C(-1),disabled:0===v.total,"aria-label":p("chat.searchPrevious"),title:`${p("chat.searchPrevious")} (Shift+Enter)`,children:(0,n.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,n.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,n.jsx)("button",{type:"button",onClick:()=>C(1),disabled:0===v.total,"aria-label":p("chat.searchNext"),title:`${p("chat.searchNext")} (Enter)`,children:(0,n.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,n.jsx)("path",{d:"m6 9 6 6 6-6"})})}),(0,n.jsx)("button",{type:"button",onClick:t,"aria-label":p("chat.searchClose"),title:`${p("chat.searchClose")} (Esc)`,children:(0,n.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,n.jsx)("path",{d:"M18 6 6 18"}),(0,n.jsx)("path",{d:"m6 6 12 12"})]})})]})}function is({questions:e,containerRef:t,layoutKey:r,onJump:a,label:s}){let l=(0,i.useRef)(null),[o,d]=(0,i.useState)(-1),[c,u]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=setTimeout(()=>u(!0),0);return()=>clearTimeout(e)},[]);let p=c&&e.length>=2;(0,i.useEffect)(()=>{let r=t.current;if(!r||!p)return;let n=0,i=null,a=()=>{n=0,i?.[0]?.isConnected||(i=r.querySelectorAll("[data-chat-item]"));let t=r.getBoundingClientRect().top+8,a=0,s=i.length-1,l=i.length-1;for(;a<=s;){let e=a+s>>1,r=i[e].firstElementChild?.getBoundingClientRect();r&&r.bottom>t?(l=e,s=e-1):a=e+1}let o=l>=0?Number(i[l].dataset.chatItem):-1,c=-1;for(let t of e){if(t.item>o)break;c=t.item}d(c)},s=()=>{n||(n=requestAnimationFrame(a))};return n=requestAnimationFrame(a),r.addEventListener("scroll",s,{passive:!0}),()=>{r.removeEventListener("scroll",s),n&&cancelAnimationFrame(n)}},[e,p,r,t]),(0,i.useEffect)(()=>{let e=l.current,t=e?.querySelector("[aria-current='true']");if(!e||!t)return;let r=t.offsetTop-e.scrollTop;(r<0||r+t.offsetHeight>e.clientHeight)&&(e.scrollTop=t.offsetTop-(e.clientHeight-t.offsetHeight)/2)},[o]);let h=e.length,f=(0,i.useCallback)((e,t)=>{let r="ArrowUp"===e.key?t-1:"ArrowDown"===e.key?t+1:"Home"===e.key?0:"End"===e.key?h-1:null;if(null===r)return;e.preventDefault();let n=Math.max(0,Math.min(h-1,r));l.current?.querySelectorAll("button")[n]?.focus()},[h]);if(!p)return null;let m=e.some(e=>e.item===o)?o:e[0].item;return(0,n.jsx)("nav",{className:"question-rail","aria-label":s,children:(0,n.jsx)("div",{ref:l,className:"question-rail-list",children:e.map((e,t)=>(0,n.jsx)(il,{question:e,position:t,count:h,active:e.item===o,focusable:e.item===m,onJump:a,onMoveFocus:f},e.item))})})}let il=(0,i.memo)(function({question:e,position:t,count:r,active:i,focusable:a,onJump:s,onMoveFocus:l}){let o=e.text.length>140?`${e.text.slice(0,140)}…`:e.text;return(0,n.jsx)("button",{type:"button",className:"question-rail-tick",tabIndex:a?0:-1,"aria-current":i?"true":void 0,"aria-label":`${t+1}/${r} ${o}`,title:o,onClick:()=>s(e.item),onKeyDown:e=>l(e,t),children:(0,n.jsx)("span",{"aria-hidden":"true"})})});function io({label:e,tone:t,children:r}){return(0,n.jsxs)("div",{className:"run-status-line","data-tone":t,role:"status","aria-live":"polite",children:[(0,n.jsx)("span",{className:"run-status-label",children:e}),(0,n.jsx)("span",{className:"run-status-text",children:r})]})}let id={manual:!0,threshold:!0,overflow:!0,idle:!0,incomplete:!0};function ic({compaction:e,t}){let[r,a]=(0,i.useState)(()=>Date.now());if((0,i.useEffect)(()=>{if(!e)return;a(Date.now());let t=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(t)},[e]),!e)return null;let s=Math.max(0,Math.floor((r-e.startedAt)/1e3)),l=e.reason&&!0===id[e.reason]?t(`chat.compactionReason.${e.reason}`):null;return(0,n.jsxs)(io,{label:t("chat.compactionLabel"),tone:"accent",children:[t("chat.compactionProgress",{seconds:s}),l?` \xb7 ${l}`:""]})}function iu({onDismiss:e,t}){return(0,n.jsxs)("div",{className:"interrupted-run-notice",role:"status",children:[(0,n.jsx)("span",{className:"interrupted-run-mark","aria-hidden":"true"}),(0,n.jsxs)("span",{className:"interrupted-run-text",children:[(0,n.jsx)("strong",{children:t("chat.interruptedTitle")}),(0,n.jsx)("span",{children:t("chat.interruptedDetail")})]}),(0,n.jsx)("button",{type:"button",onClick:e,"aria-label":t("chat.interruptedDismiss"),title:t("chat.interruptedDismiss"),children:(0,n.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,n.jsx)("path",{d:"M18 6 6 18"}),(0,n.jsx)("path",{d:"m6 6 12 12"})]})})]})}var ip=r(39092),ih=r.n(ip);let im=["YUKI(유키)","ISANA(이사나)","MIO(미오)","RIN(린)","NOVA(노바)","SHION(시온)","HIKARI(히카리)"],ig={"YUKI(유키)":"yuki","ISANA(이사나)":"isana","MIO(미오)":"mio","RIN(린)":"rin","NOVA(노바)":"nova","SHION(시온)":"shion","HIKARI(히카리)":"hikari"},ix=["approval","choice","done","failed","blocked","working"],iv={approval:"부름",choice:"물음",done:"기쁨",failed:"사과",blocked:"난처",working:"시작"},ib={approval:!1,choice:!1,done:!1,failed:!1,blocked:!1,working:!0};function iy(e){switch(e){case"completed":return"done";case"failed":return"failed";case"aborted":return null;default:return"neutral"}}function iw(e){return void 0===e?"done":"string"==typeof e&&Object.hasOwn(iv,e)?e:null}function ik(e,t){let r=new Map,n=new Map;if(!Array.isArray(e))return{files:r,lines:n};for(let i of e){if("object"!=typeof i||null===i)continue;let{file:e,tag:a,ko:s}=i;if("string"!=typeof e||""===e)continue;let l=iw(a);if(null===l)continue;let o=t+e.replace(/^\/+/,""),d=r.get(l);d?d.push(o):r.set(l,[o]),"string"==typeof s&&""!==s.trim()&&n.set(o,s.trim())}return{files:r,lines:n}}function ij(e,t,r){let n=t&&Object.hasOwn(ig,t)?ig[t]:null;return n?e.get(n)?.get(r)??null:null}async function iS(e=fetch){try{let t=await e("/audio/completion/voices.json");if(!t.ok)return new Map;return function(e){let t=new Map;if("object"!=typeof e||null===e)return t;let{characters:r}=e;if(!Array.isArray(r))return t;for(let e of r){if("object"!=typeof e||null===e)continue;let{id:r,clips:n,stickers:i,captions:a}=e;if("string"!=typeof r||""===r)continue;let s=ik(n,"/audio/completion/"),l=ik(i,"/stickers/"),o=function(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if("object"!=typeof r||null===r)continue;let{tag:e,ko:n}=r;if("string"!=typeof n||""===n.trim())continue;let i=iw(e);if(null===i)continue;let a=t.get(i);a?a.push(n.trim()):t.set(i,[n.trim()])}return t}(a),d=new Map;for(let e of ix){let t=s.files.get(e)??[],r=new Map;for(let e of t){let t=s.lines.get(e);void 0!==t&&r.set(e,t)}d.set(e,{voices:t,stickers:l.files.get(e)??[],lines:r,captions:o.get(e)??[]})}t.set(r,d)}return t}(await t.json())}catch{return new Map}}function iC(e,t,r=Math.random){if(0===e.length)return null;if(1===e.length)return e[0];let n=null===t?-1:e.indexOf(t),i=-1===n?e.length:e.length-1,a=Math.min(i-1,Math.max(0,Math.floor(r()*i)));return e[-1!==n&&a>=n?a+1:a]}function iN(e){let t=[];if("bashExecution"!==e.role){if("string"==typeof e.content)t.push(e.content.trim());else for(let r of e.content)if("text"===r.type)t.push(r.text.trim());else if("toolCall"===r.type){let e="id"in r&&"string"==typeof r.id?r.id:"";t.push(`toolCall:${r.toolCallId||e}`)}}let r="toolResult"===e.role?e.toolCallId:"custom"===e.role?e.customType:"bashExecution"===e.role?e.command:null;return JSON.stringify([e.role,r,t.filter(Boolean)])}let iI=["01","02","03"];function iT(e,t,r){if(!e||"streaming"===t||!im.includes(e))return null;let n="failed"===t?"failed":"done",i=e.slice(0,e.indexOf("(")).toLowerCase(),a=iC(iI.map(e=>`/stickers/${i}/${n}/${e}.webp`),null,()=>(function(e){let t=0x811c9dc5;for(let r=0;r<e.length;r+=1)t=Math.imul(t^e.charCodeAt(r),0x1000193);return(t>>>0)/0x100000000})(r));return a?{src:a,alt:iv[n]}:null}let iM=new Map,i$=(0,i.createContext)(iM);function iR({utterances:e,children:t}){return(0,n.jsx)(i$.Provider,{value:e,children:t})}function iE({turnIndex:e,turnEntryId:t,sessionId:r,cwd:a,onOpenFile:s}){let l=(0,i.useContext)(i$).get(e);return l&&0!==l.length?(0,n.jsx)("div",{className:"inline-utterance-thread","data-turn":e,"data-turn-entry":t,style:{display:"contents"},children:l.map(e=>(0,n.jsx)(iL,{utterance:e,sessionId:r,cwd:a,onOpenFile:s},e.key))}):null}function iL({utterance:e,sessionId:t,cwd:r,onOpenFile:a}){let s=rc(null===e.accountSessionId?void 0:e.accountSessionId??t,e.provider,e.credentialId),[l,o]=(0,i.useState)(!1),[d,c]=(0,i.useState)(!1),u=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=u.current;e&&!l&&c(e.scrollHeight>e.clientHeight+1)},[e.text,l]);let p=e.text.trim().length>0,h=e.label?.trim(),f=s?.alias??h??(0,t3.bN)(e.provider),m=s?.alias.split("(",1)[0]?.trim(),g=s&&h&&h!==s.alias&&h!==m?`작업 \xb7 ${h}`:null,x=iT(s?.alias,e.status,e.key),v="failed"===e.status?"중단됨":"streaming"===e.status&&p?"작업 중":null;return(0,n.jsxs)("div",{className:"inline-utterance","data-status":e.status,style:{marginBottom:16},children:[(0,n.jsxs)("div",{className:"inline-utterance-role",style:{display:"flex",alignItems:"center",gap:9,marginBottom:2,fontSize:11,color:"var(--text-dim)",...s?{minHeight:40}:null},children:[s&&(0,n.jsx)(rh,{seed:s.seed,size:40,provider:e.provider}),(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:f}),v&&(0,n.jsx)("span",{style:{color:"failed"===e.status?"var(--danger)":"var(--text-dim)"},children:v})]}),g&&(0,n.jsx)("div",{style:{marginTop:1,fontSize:11,lineHeight:1.35,color:"var(--text-muted)",overflowWrap:"anywhere"},children:g})]})]}),p?(0,n.jsx)("div",{ref:u,style:{fontSize:12.5,lineHeight:1.6,...l?null:{maxHeight:240,overflow:"hidden"}},children:(0,n.jsx)(tJ,{isStreaming:"streaming"===e.status,cwd:r,onOpenFile:a,children:e.text})}):(0,n.jsx)("div",{role:"status",style:{color:"var(--text-muted)",fontSize:11.5,lineHeight:1.6},children:"failed"===e.status?"발화 없이 중단되었습니다":"아직 발화가 없습니다"}),p&&(d||l)&&(0,n.jsx)("button",{type:"button",onClick:()=>o(e=>!e),"aria-expanded":l,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:l?"접기":"더보기"}),x&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("img",{src:x.src,alt:x.alt,style:{display:"block",width:"min(148px, 34vw)",maxWidth:"100%",height:"auto"},className:"jsx-8e1a78d1ba768be9 inline-utterance-sticker"}),(0,n.jsx)(ih(),{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 iz=/^\[character-summon alias="([^"\r\n]+)" model="([^"\r\n]+)"(?: oauth-position="\d+")?\]\r?$/mu;function iA(e,t,r,n){if("string"!=typeof r)return[];let i=iz.exec(r),a=i?.[1],s=i?.[2];return a&&s?[{toolCallId:e,...t?{name:t}:{},alias:a,model:s,batchSize:n}]:[]}function iP(e){if(!e||"assistant"!==e.role)return[];let t=[];for(let r of e.content??[]){if("toolCall"!==r.type||"task"!==r.toolName)continue;let e=r.input,n=+(void 0!==e.task)+(Array.isArray(e.tasks)?e.tasks.length:0);if(t.push(...iA(r.toolCallId,"string"==typeof e.name?e.name:void 0,e.task,n)),Array.isArray(e.tasks))for(let i of e.tasks)!i||"object"!=typeof i||Array.isArray(i)||t.push(...iA(r.toolCallId,"name"in i&&"string"==typeof i.name?i.name:void 0,"task"in i?i.task:void 0,n))}return t}function iW(e){if(!e||"assistant"!==e.role)return[];let t=[];for(let r of e.content??[])"toolCall"===r.type&&"task"===r.toolName&&t.push(r.toolCallId);return t}let iF=/^agent:\/\/([^/?#]+)\/?$/i;function i_(e,t){if(!e||"assistant"!==e.role)return[];let r=[];for(let n of e.content??[]){if("toolCall"!==n.type||"write"!==n.toolName)continue;let e=n.input,i="string"==typeof e.path?iF.exec(e.path):null,a=i?.[1],s=e.content;if(!a||"string"!=typeof s)continue;let l=t?.get(n.toolCallId);r.push({toolCallId:n.toolCallId,to:a,message:s,...l?.from?{from:l.from}:{},...l?.receipts?{receipts:l.receipts}:{}})}return r}let iD=["greeting","utterance","message","text"],iH=function(e){let t=(0,i.useMemo)(()=>(0,rC.Et)(),[]),r=function(e,t){let[r,n]=(0,i.useState)(null);return(0,i.useEffect)(()=>{if(!t)return void n(null);let r=!1,i=new AbortController;return n(null),e.getArchive(t,i.signal).then(e=>{r||n(e)}).catch(()=>{}),()=>{r=!0,i.abort()}},[e,t]),r}(t,e.sessionId),n=(0,i.useMemo)(()=>{let t=new Set(e.subagents.map(e=>e.id)),n=[];if(r&&r.sessionId===e.sessionId){let i=e.turns.flatMap(e=>e.characterSummons);for(let a of r.subagents){if(t.has(a.name))continue;let r=[...i].reverse().find(e=>e.name===a.name);r&&n.push(function(e,t,r){let n=e.status??"unknown",i={id:e.name,index:r,agent:"",agentSource:"bundled",status:n,task:e.firstTask||void 0,lastUpdate:e.modified,parentToolCallId:t.toolCallId},a="string"==typeof e.model&&e.model.trim()?e.model.trim():void 0,s="string"==typeof e.errorMessage&&e.errorMessage.trim()?e.errorMessage.trim():void 0;return(void 0!==a||void 0!==s)&&(i.progress={index:r,id:e.name,agent:"",status:n,task:e.firstTask,recentTools:[],recentOutput:[],toolCount:0,requests:0,tokens:0,cost:0,durationMs:0,...void 0!==a?{resolvedModel:a,resolvedModelIsFallback:!0===e.modelIsFallback}:{},...void 0!==s?{retryFailure:{attempt:0,errorMessage:s}}:{}}),i}(a,r,e.subagents.length+n.length))}}return function(e,t){let r=new Map;for(let t of e)for(let e of t.characterSummons){let n=r.get(e.toolCallId)??{turnIndex:t.index,requests:[]};n.requests.push(e),r.set(e.toolCallId,n)}return t.flatMap(t=>{let n=t.parentToolCallId?r.get(t.parentToolCallId):void 0;if(!n)return[];let i=n.requests.filter(e=>e.name),a="string"==typeof t.task?iz.exec(t.task):null,s=a?.[1],l=a?.[2],o=i.find(e=>e.name===t.id)??(s&&l?n.requests.find(e=>e.alias===s&&e.model===l):void 0)??(1===n.requests.length&&1===n.requests[0].batchSize?n.requests[0]:void 0);if(!o)return[];let d=e.flatMap(e=>e.peerSends.filter(e=>e.to===t.id||"all"===e.to).map(t=>({turnIndex:e.index,send:t})));return[{snapshot:t,turnIndex:n.turnIndex,summon:o,sends:d}]})}(e.turns,[...e.subagents,...n])},[e.subagents,e.turns,e.sessionId,r]),a=(0,i.useMemo)(()=>n.map(({snapshot:t})=>{let r=t.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||t.id;return e.subagents.some(e=>e.id===t.id)?{key:t.id,liveId:t.id,status:t.status,archiveName:r}:{key:t.id,status:t.status,archiveName:r}}),[n,e.subagents]),s=(0,rq._Z)(a,{sessionId:e.sessionId??"",client:t,enabled:!!e.sessionId&&a.length>0});return(0,i.useMemo)(()=>n.flatMap(t=>(function(e,t,r){var n;let{snapshot:i,summon:a}=e,s="completed"===(n=i.status)||"unknown"===n?"settled":"failed"===n||"aborted"===n?"failed":"streaming",l="failed"===s,o=a?.model.split("/",1)[0]?.trim()||void 0,d=l&&o?o:function(e,t,r){let n="string"==typeof e.progress?.resolvedModel?e.progress.resolvedModel.trim():"",i=n.indexOf("/");if(i>0)return n.slice(0,i);let a=t?.model.trim()??"",s=a.indexOf("/");return s>0?a.slice(0,s):r?.trim()||void 0}(i,a,r),c=i.id.trim()||void 0,u=`subagent:${i.id}`,p=[],h=e.turnIndex,f=0;if((t?.entries??[]).forEach((t,r)=>{var n;let m;if("irc"in t){let{from:r,message:n,truncated:a}=t.irc;if(a||"string"!=typeof r||"string"!=typeof n)return;for(let t=f;t<e.sends.length;t+=1){let a=e.sends[t];if(a.send.message===n&&function(e,t){if(!e.from)return!1;let r=e.receipts;return!!r&&r.some(e=>e.to===t&&("injected"===e.outcome||"woken"===e.outcome||"revived"===e.outcome))}(a.send,i.id)&&a.send.from===r){h=a.turnIndex,f=t+1;break}}return}if("assistant"!==t.message.role)return;let g=t.message.provider||d;if(!g||l&&o&&g!==o)return;let x=((m=((n=t.message).content??[]).filter(e=>"text"===e.type).map(e=>e.text.trim()).filter(e=>e.length>0).join("\n\n")).length>0?m:function(e){let t="";for(let r of e.content??[]){if("toolCall"!==r.type||"yield"!==r.toolName)continue;let e=r.input.data,n="";if("string"==typeof e)n=e;else if("object"==typeof e&&null!==e&&!Array.isArray(e))for(let t of["report",...iD]){let r=e[t];if("string"==typeof r&&r.trim().length>0){n=r;break}}let i=n.trim();i.length>0&&(t=i)}return t}(n))||(l?t.message.errorMessage?.trim()??"":"");0!==x.length&&p.push({key:`${i.id}:${r}`,turnIndex:h,speakerId:u,provider:g,credentialId:t.message.credentialId,accountSessionId:null,label:l&&a?a.alias:c,text:x,status:s})}),0===p.length&&"settled"!==s&&d){let e=l?i.progress?.retryFailure?.errorMessage?.trim():void 0;p.push({key:`${i.id}:pending`,turnIndex:h,speakerId:u,provider:d,accountSessionId:null,label:l&&a?a.alias:c,text:e||"",status:s})}return p})(t,s.get(t.snapshot.id),e.sessionProvider)),[n,s,e.sessionProvider])},iO="web6",iB=[],iU=[],iq=function(e){let t=(0,i.useMemo)(()=>(function(e=(e,t)=>fetch(e,t),t="/api/web6/consults"){return{async listConsults(r,n){let i=r.trim();if(!i)throw Error("sessionId가 필요하다");let a=`${t}?sessionId=${encodeURIComponent(i)}`,s=await e(a,{signal:n});if(!s.ok)throw Error(`HTTP ${s.status}`);let l=await s.json(),o=l&&"object"==typeof l&&"consults"in l?l.consults:null;if(!Array.isArray(o))throw Error("consults 배열이 아니다");return o.flatMap(e=>{let t=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t="string"==typeof e.sessionId?e.sessionId.trim():"";if(!t)return null;let r=e.startedAt;if("number"!=typeof r||!Number.isFinite(r))return null;let n=e.status;if("ok"!==n&&"failed"!==n)return null;let i="number"==typeof e.finishedAt&&Number.isFinite(e.finishedAt)?e.finishedAt:r,{conversationId:a,text:s,error:l}=e;return{sessionId:t,startedAt:r,finishedAt:i,elapsedMs:"number"==typeof e.elapsedMs&&Number.isFinite(e.elapsedMs)?e.elapsedMs:i-r,model:"string"==typeof e.model?e.model:"",status:n,conversationId:"string"==typeof a&&""!==a?a:void 0,text:"string"==typeof s&&""!==s?s:void 0,error:"string"==typeof l&&""!==l?l:void 0}}(e);return t?.sessionId===i?[t]:[]})}}})(),[]),[r,n]=(0,i.useState)(iU),a=(0,i.useRef)(""),s=e.sessionId??"",l=s.length>0;return(0,i.useEffect)(()=>{if(!l){a.current="",n(iU);return}let e=new AbortController,r=async()=>{if("u"<typeof document||"hidden"!==document.visibilityState)try{let r=await t.listConsults(s,e.signal),i=r.map(e=>`${e.startedAt}.${e.finishedAt}.${e.status}`).join("|");if(i===a.current)return;a.current=i,n(r)}catch{}};r();let i=setInterval(()=>void r(),5e3);return()=>{e.abort(),clearInterval(i)}},[t,l,s]),(0,i.useMemo)(()=>(function(e,t,r){if(0===e.length)return iB;let n=function(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e[r];if("user"!==n.role)continue;let i=n.timestamp;"number"==typeof i&&Number.isFinite(i)&&t.push({index:r,openedAt:i})}return t}(t);if(0===n.length)return iB;let i=[];for(let t of[...e].sort((e,t)=>e.startedAt-t.startedAt)){if(t.sessionId!==r||"failed"!==t.status)continue;let e=function(e,t){let r;for(let n of e)n.openedAt>t||(!r||n.openedAt>=r.openedAt)&&(r=n);return r?.index}(n,t.startedAt);if(void 0===e)continue;let a=t.error??"";0!==a.trim().length&&i.push({key:`${iO}:${t.startedAt}:${t.finishedAt}`,turnIndex:e,provider:"web6",speakerId:`${iO}:${t.conversationId??"unknown"}`,text:a,status:"failed"})}return i.length>0?i:iB})(r,e.messages,s),[r,e.messages,s])},iK={sending:!0,accepted:!0,delivered:!1,unconfirmed:!1,failed:!1};function iV(e){return e.trim()}function iJ(e){return iV(e.text)||(e.images>0?"[Image]":"")}function iG(e){let t=e.filter(e=>!iK[e.stage]);if(t.length<=4)return e;let r=new Set(t.slice(0,t.length-4).map(e=>e.id));return e.filter(e=>!r.has(e.id))}function iY(e,t){switch(t.type){case"submit":return iG([...e,{id:t.id,kind:t.kind,text:t.text,images:t.images??0,stage:"sending",inQueue:!1}]);case"ack":return e.map(e=>e.id===t.id&&"sending"===e.stage?{...e,stage:"accepted"}:e);case"fail":return iG(e.map(e=>e.id===t.id&&iK[e.stage]?{...e,stage:"failed",inQueue:!1}:e));case"queue":return function(e,t,r){let n=new Map,i=(e,t)=>{let r=`${e}\u0000${iV(t)}`;n.set(r,(n.get(r)??0)+1)};for(let e of t)i("steer",e);for(let e of r)i("followUp",e);let a=!1,s=e.map(e=>{if(!iK[e.stage])return e;let t=`${e.kind}\u0000${iJ(e)}`,r=n.get(t)??0;return r>0?(n.set(t,r-1),e.inQueue&&"accepted"===e.stage)?e:(a=!0,{...e,stage:"accepted",inQueue:!0}):e.inQueue?(a=!0,{...e,stage:"unconfirmed",inQueue:!1}):e});return a?s:e}(e,t.steering,t.followUp);case"user-message":{let r=iV(t.text);if(!r&&0===t.images)return e;let n=e.find(e=>(iK[e.stage]||"unconfirmed"===e.stage)&&e.kind===t.kind&&iV(e.text)===r&&e.images===t.images);if(!n)return e;return iG(e.map(e=>e===n?{...e,stage:"delivered",inQueue:!1}:e))}case"withdraw":{let r=e=>iK[e.stage]||"unconfirmed"===e.stage;if(void 0===t.text)return e.filter(e=>!r(e));let n=iV(t.text),i=e.find(e=>r(e)&&e.kind===t.kind&&(iV(e.text)===n||iJ(e)===n));return i?e.filter(e=>e!==i):e}case"idle":{let t=e.filter(e=>e.inQueue);return t.length===e.length?e:t}case"reset":return 0===e.length?e:[]}}let iZ={steer:"delivery.kind.steer",followUp:"delivery.kind.followUp"},iX={sending:"delivery.stage.sending",accepted:"delivery.stage.accepted",delivered:"delivery.stage.delivered",unconfirmed:"delivery.stage.unconfirmed",failed:"delivery.stage.failed"};function iQ({rows:e,removeLabel:t,onRemove:r}){let a,{st:s}=rp(),[l,o]=(0,i.useState)(!1),{rows:d,hidden:c}=(a=Math.max(0,e.length-4),l||0===a?{rows:e,hidden:a}:{rows:e.slice(a),hidden:a}),u=e.length>4;return(0,i.useEffect)(()=>{u||o(!1)},[u]),(0,n.jsxs)(n.Fragment,{children:[u&&(0,n.jsx)("button",{type:"button",className:"answer-delivery-toggle","aria-expanded":l,onClick:()=>o(e=>!e),children:l?s("delivery.showRecent",{count:4}):s("delivery.showOlder",{count:c})}),(0,n.jsx)("ul",{className:"answer-delivery-list","aria-live":"polite",children:d.map(e=>{let i=nd(e.text),a=[i?[i.message,i.documents.map(e=>e.name).join(", ")].filter(Boolean).join(" \xb7 "):e.text.trim(),e.images>0?s("delivery.images",{count:e.images}):""].filter(Boolean).join(" \xb7 ");return(0,n.jsxs)("li",{className:"answer-delivery-row","data-kind":e.kind,"data-stage":e.stage,children:[(0,n.jsx)("span",{className:"answer-delivery-kind",children:s(iZ[e.kind])}),(0,n.jsx)("span",{className:"answer-delivery-text",title:a,children:a}),(0,n.jsx)("span",{className:"answer-delivery-stage",children:s(iX[e.stage])}),e.removable&&r&&(0,n.jsx)("button",{type:"button",className:"answer-delivery-remove",title:t,"aria-label":`${t}: ${a}`,onClick:()=>r(e.kind,e.text),children:(0,n.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,n.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]},e.key)})})]})}let i0=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,n.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"})]}),i1=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,n.jsx)("path",{d:"m22 9-6 6m0-6 6 6"})]});function i2({soundEnabled:e,onToggle:t}){let r=e?"완료음 끄기":"완료음 켜기";return(0,n.jsx)("div",{role:"group","aria-label":"오디오",style:{display:"flex",alignItems:"center",gap:6},children:(0,n.jsx)("button",{type:"button",className:`composer-icon-button${e?" is-active":""}`,onClick:t,"aria-pressed":e,title:r,"aria-label":r,children:(0,n.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:e?i0:i1})})})}let i4=RegExp("^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:(?:통화|전화)(?:를|좀|그만)*)?(?:좀|그만)*(?:끊어|끊어봐|끊을게|끊자|끊겠습니다|끊으라고)(?:줘|주세요|요)?$|^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:통화|전화)(?:를|좀|그만)*(?:종료|종료해|종료해봐|종료할게|종료하자|종료하라고)(?:줘|주세요|요)?$","u"),i5={idle:!0,connecting:!0,live:!0,working:!0,error:!0,closed:!0};function i8(e){if("complete"===e.iceGatheringState)return Promise.resolve();let{promise:t,resolve:r}=Promise.withResolvers(),n=()=>{clearTimeout(a),e.removeEventListener("icegatheringstatechange",i),r()},i=()=>{"complete"===e.iceGatheringState&&n()},a=setTimeout(n,3e3);return e.addEventListener("icegatheringstatechange",i),t}function i6(e,t){return 401===e||"live-auth"===t?"auth":502===e||"live-upstream"===t?"upstream":"failed"}let i3={unsupported:"chat.liveUnsupported","mic-denied":"chat.liveMicDenied","mic-unavailable":"chat.liveMicUnavailable",auth:"chat.liveAuthRequired",upstream:"chat.liveUpstreamFailed",failed:"chat.liveFailed"},i7=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,n.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),(0,n.jsx)("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),i9=(0,n.jsx)(n.Fragment,{children:(0,n.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"})});function ae({sessionId:e,onEnsureSession:t,onTranscriptPersisted:r}){let{t:a}=(0,R.s)(),s=function(e,t,r){let{locale:n}=(0,R.s)(),[a,s]=(0,i.useState)("idle"),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(!1),x=(0,i.useRef)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(null),y=(0,i.useRef)(null),w=(0,i.useRef)(null),k=(0,i.useRef)(0);(0,i.useEffect)(()=>{f("u">typeof RTCPeerConnection&&"u">typeof navigator&&"function"==typeof navigator.mediaDevices?.getUserMedia)},[]);let j=(0,i.useCallback)(e=>{k.current+=1;let t=w.current;for(let e of(w.current=null,y.current?.close(),y.current=null,x.current?.close(),x.current=null,v.current?.getTracks()??[]))e.stop();v.current=null;let r=b.current;b.current=null,r&&(r.srcObject=null,r.remove()),t&&fetch(`/api/live/call/${encodeURIComponent(t)}`,{method:"DELETE"}).catch(()=>{}),s(e),p(null),g(!1)},[]),S=(0,i.useCallback)((e,t)=>{o(e),c(t??null),j("error")},[j]),C=(0,i.useCallback)(async()=>{let i,a=k.current+1;k.current=a,o(null),c(null),g(!0),s("connecting");let l=e;if(!l&&t){try{l=await t()}catch{l=void 0}if(k.current!==a)return}if(!l){k.current===a&&(g(!1),S("failed"));return}try{i=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(t){let e=t instanceof DOMException?t.name:"";k.current===a&&(g(!1),S("NotAllowedError"===e||"SecurityError"===e?"mic-denied":"mic-unavailable"));return}if(k.current!==a){for(let e of i.getTracks())e.stop();return}v.current=i;try{let e,t,o=new RTCPeerConnection;for(let e of(x.current=o,i.getTracks()))o.addTrack(e,i);let d=document.createElement("audio");if(d.autoplay=!0,b.current=d,o.ontrack=e=>{let[t]=e.streams;t&&(d.srcObject=t)},await o.setLocalDescription(await o.createOffer()),await i8(o),k.current!==a)return;let c=o.localDescription?.sdp;if(!c)throw Error("The browser produced no offer SDP.");let u=await fetch("/api/live/offer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:l,sdp:c,locale:n})}),h=await u.json().catch(()=>({})),f="",m="";if(h&&"object"==typeof h&&("error"in h&&(e=h.error),"message"in h&&"string"==typeof h.message&&(t=h.message),"callId"in h&&"string"==typeof h.callId&&(f=h.callId),"sdp"in h&&"string"==typeof h.sdp&&(m=h.sdp)),!u.ok||!f||!m){k.current===a&&(g(!1),S(i6(u.status,e),t));return}if(k.current!==a)return void fetch(`/api/live/call/${encodeURIComponent(f)}`,{method:"DELETE"}).catch(()=>{});if(await o.setRemoteDescription({type:"answer",sdp:m}),k.current!==a){o.close(),fetch(`/api/live/call/${encodeURIComponent(f)}`,{method:"DELETE"}).catch(()=>{});return}w.current=f;let v=new EventSource(`/api/live/events?callId=${encodeURIComponent(f)}`);y.current=v,v.onmessage=e=>{let t;if(k.current===a){try{t=JSON.parse(e.data)}catch{return}if(t&&"object"==typeof t&&"type"in t){if("state"===t.type&&"state"in t){var n;if("string"!=typeof t.state||(n=t.state,!0!==i5[n]))return;"closed"===t.state?j("closed"):s(t.state);return}if("transcript"===t.type&&"role"in t&&"text"in t){if(("user"===t.role||"assistant"===t.role)&&"string"==typeof t.text){let e;p({role:t.role,text:t.text}),"final"in t&&!0===t.final&&r&&Promise.resolve().then(()=>r(l)).catch(()=>{}),"final"in t&&!0===t.final&&"user"===t.role&&(e=t.text.normalize("NFC").replace(/[^\p{L}\p{N}]+/gu,"")).length>0&&i4.test(e)&&j("idle")}return}"error"===t.type&&"message"in t&&"string"==typeof t.message&&S("upstream",t.message)}}},v.onerror=()=>{k.current===a&&w.current&&S("failed")},s("live")}catch(e){k.current===a&&S("failed",e instanceof Error?e.message:String(e))}finally{k.current===a&&g(!1)}},[e,t,r,n,S,j]),N=(0,i.useCallback)(()=>{if("idle"===a||"closed"===a||"error"===a){m||C();return}j("idle")},[m,a,C,j]);return(0,i.useEffect)(()=>()=>j("closed"),[j]),{state:a,failure:l,detail:d,transcript:u,supported:h,toggle:N}}(e,t,r),l="connecting"===s.state||"live"===s.state||"working"===s.state,o="connecting"===s.state?"chat.liveConnecting":"working"===s.state?"chat.liveWorking":"live"===s.state?"chat.liveOn":null,d=a(l?"chat.liveStop":"chat.liveStart"),c=!1===s.supported?i3.unsupported:s.failure?i3[s.failure]:null,u=!!(e||t),p=u?null:"chat.liveNeedsSession";return(0,n.jsxs)("div",{role:"group","aria-label":a("chat.liveVoice"),style:{display:"flex",alignItems:"center",gap:6,flex:"0 1 auto",minWidth:0},children:[c&&(0,n.jsx)("span",{role:"status",style:{fontSize:11,color:"var(--danger)",maxWidth:220,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:s.detail??void 0,children:a(c)}),o&&(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a(o)}),(0,n.jsx)("button",{type:"button",className:`composer-icon-button${l?" is-active":""}`,onClick:s.toggle,disabled:!s.supported||!u,"aria-pressed":l,title:p?a(p):d,"aria-label":p?a(p):d,children:(0,n.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:l?i9:i7})})]})}let at={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 ar({sessionId:e}){let{t}=(0,R.s)(),[r,a]=(0,i.useState)(null);return((0,i.useEffect)(()=>{if(!e)return void a(null);let t=!1,r=0,n=!1,i=async()=>{if("visible"===document.visibilityState)try{let r=await fetch("/api/gpt6/handles",{cache:"no-store"});if(!r.ok)return;let i=await r.json();if(t)return;let s=Array.isArray(i.handles)?i.handles:[],l=s.find(t=>t.sessionId===e&&"active"===t.status)?.handle??null;n=null!==l,a(l)}catch{}},s=async()=>{await i(),t||(r=window.setTimeout(()=>void s(),n?5e3:3e4))};return s(),document.addEventListener("visibilitychange",i),()=>{t=!0,window.clearTimeout(r),document.removeEventListener("visibilitychange",i)}},[e]),r)?(0,n.jsx)("span",{style:at,title:t("gpt6.boundBadgeHint",{handle:r}),children:t("gpt6.boundBadge",{handle:r})}):null}function an(e){if(!e||"object"!=typeof e||"string"!=typeof e.data||"string"!=typeof e.mimeType||!e.mimeType.startsWith("image/"))return!1;let t=function(e){if(!e||e.length%4!=0)return null;let t=e.endsWith("==")?2:+!!e.endsWith("="),r=e.length-t;for(let t=0;t<r;t+=1){var n;if(!((n=e.charCodeAt(t))>=65&&n<=90||n>=97&&n<=122||n>=48&&n<=57||43===n||47===n))return null}for(let t=r;t<e.length;t+=1)if("="!==e[t])return null;return e.length/4*3-t}(e.data);return null!==t&&t<=0xa00000}let ai=new Map,aa="ompweb-drafts-for-reload-v1",as=!1,al=new Map,ao=new Map,ad="\0stale",ac=new Map,au=0,ap=new Map,ah=new Map,af=new Map,am=new Map,ag=new Map,ax=(e,t,r)=>ng(e,t,r.length?{sentAttachmentIds:r}:{}),av=null,ab=!1;function ay(){if(as||"u"<typeof sessionStorage)return;as=!0;let e=sessionStorage.getItem(aa);if(e){sessionStorage.removeItem(aa);try{let t=JSON.parse(e);if(!Array.isArray(t))return;for(let e of t){if(!Array.isArray(e)||2!==e.length||"string"!=typeof e[0])continue;let t=e[1];t&&"string"==typeof t.value&&Array.isArray(t.images)&&Array.isArray(t.documents)&&(ai.set(e[0],ak(t)),"string"==typeof t.draftId&&t.draftId&&(al.set(e[0],t.draftId),ao.set(t.draftId,ad)),aR(e[0]))}}catch{}}}function aw(){if("u"<typeof sessionStorage)return{ok:!1,error:"sessionStorage unavailable"};try{return sessionStorage.setItem(aa,JSON.stringify([...ai.entries()].map(([e,t])=>{let r=al.get(e);return[e,r?{...ak(t),draftId:r}:ak(t)]}))),{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function ak(e){return{value:e.value,images:e.images.map(e=>({...e})),documents:e.documents.map(e=>({...e}))}}function aj(e){return!e.value&&0===e.images.length&&0===e.documents.length}function aS(e){ay();let t=ai.get(e);return t?ak(t):null}function aC(e,t){ay(),aj(t)?ai.delete(e):ai.set(e,ak(t)),aR(e)}function aN(e){ai.delete(e),aR(e)}function aI(e,t,r,n,i,a=[]){let s=[...t??[],...n].filter(an).slice(0,10).map(({data:e,mimeType:t})=>({data:e,mimeType:t})),l=ns([...i??[],...a]);return{value:e.trim()?r.trim()?`${e}
|
|
18
18
|
|
|
19
|
-
${r}`:e:r,images:s,documents:l}}function aT(e,t,r){if(e===t)return r?ak(r):aS(t);let n=aS(e),i=r&&!aj(r)?ak(r):n??(r?ak(r):null),a=aS(t),s=al.get(e);if(al.delete(e),s&&!al.has(t)&&al.set(t,s),aN(e),!i)return a;let l=a?aI(a.value,a.images,i.value,i.images,a.documents,i.documents):i;return aC(t,l),ak(l)}function aM(e){let t=[];for(let r of e??[])r.attachmentId&&!t.includes(r.attachmentId)&&t.push(r.attachmentId);return t}function a$(e){ay();let t=al.get(e);return t||(t=function(){let e=globalThis.crypto;if("function"==typeof e?.randomUUID)return e.randomUUID();let t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;let r=[...t].map(e=>e.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}(),al.set(e,t)),t}function aR(e){let t=aM(ai.get(e)?.documents),r=t.length?a$(e):al.get(e);for(let[e,r]of ah){for(let e of t)r.delete(e);0===r.size&&ah.delete(e)}let n=`${r??""}|${t.join(",")}`;am.get(e)!==n&&(0!==t.length||r?am.set(e,n):am.delete(e),aF())}async function aE(e){let t=a$(e);ap.set(t,(ap.get(t)??0)+1),await ag.get(t);let r=!1;return{draftId:t,end(e){if(r)return;r=!0;let n=(ap.get(t)??1)-1;if(n>0?ap.set(t,n):ap.delete(t),e){let r=ah.get(t)??new Set;r.add(e),ah.set(t,r)}ao.set(t,ad),aF()}}}function aL(e,t){let r=af.get(e);if(!r)return[];for(let e of t)r.delete(e);return 0===r.size&&af.delete(e),[...r].sort()}async function az(){if(!ax)return;let e=[...function(){let e=new Map,t=(t,r)=>{let n=e.get(t)??new Set;for(let e of r)n.add(e);e.set(t,n)};for(let[e,r]of al)t(r,aM(ai.get(e)?.documents));for(let{draftId:e,ids:r}of ac.values())t(e,r);for(let[e,r]of ah)t(e,r);for(let e of ao.keys())t(e,[]);for(let e of af.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(ap.has(e))return!1;let r=ao.get(e);return aL(e,t).length>0||(0===t.length?void 0!==r:r!==t.join(","))}),t=ap.size>0,r=!1;for(let[n,i]of[...e.filter(([,e])=>e.length>0),...e.filter(([,e])=>0===e.length)]){if(0===i.length&&t)continue;let e=aL(n,i),a=ax(n,i,e).then(()=>{0===i.length?ao.delete(n):ao.set(n,i.join(","));let t=af.get(n);if(t){for(let r of e)t.delete(r);0===t.size&&af.delete(n)}},()=>{r=!0,i.length>0&&(t=!0)});ag.set(n,a),await a,ag.get(n)===a&&ag.delete(n)}r?function(){if(aW)return;aW=!0;let e=setTimeout(()=>{aW=!1,aF()},aP);"object"==typeof e&&"unref"in e&&e.unref(),aP=Math.min(2*aP,6e4)}():aP=aA}let aA=5e3,aP=5e3,aW=!1;function aF(){if(ax){if(av){ab=!0;return}av=Promise.resolve().then(az).finally(()=>{av=null,ab&&(ab=!1,aF())})}}let a_=Math.floor(Number.MAX_SAFE_INTEGER/1048576),aD=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function aH(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=a_}async function aO(e){let t,r=await e.json().catch(()=>null);if(!e.ok||!r||!aH(r.uploadLimitMb)||"boolean"!=typeof r.autoCleanupEnabled)throw Error("string"==typeof r?.error?r.error:`HTTP ${e.status}`);return{uploadLimitMb:aH((t=r&&"object"==typeof r?r:{}).uploadLimitMb)?t.uploadLimitMb:aD.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:aD.autoCleanupEnabled,orphanGraceDays:7}}async function aB(e={}){return aO(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function aU(e){return aO(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function aq(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let r=/(?:^|\s)@([^\s"]*)$/.exec(e);return r?{start:e.length-(r[1].length+1),query:r[1],quoted:!1}:null}function aK(e){let t=0;for(let r=0;r<e.length;r++)"/"===e[r]&&t++;return t}function aV(e,t){if(!e)return!0;let r=0;for(let n=0;n<t.length&&r<e.length;n++)t[n]===e[r]&&r++;return r===e.length}let aJ="omp-web:model-picks";function aG(){try{let e=JSON.parse(window.localStorage.getItem(aJ)??"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};let t={};for(let[r,n]of Object.entries(e))"number"==typeof n&&Number.isFinite(n)&&n>0&&(t[r]=Math.floor(n));return t}catch{return{}}}function aY(e,t,r,n,i={}){let a=i.gap??8,s=i.margin??8,l=i.prefer??"above",o=Math.min(i.minHeight??120,Math.max(0,r-2*s)),d=Math.max(0,e-a-s),c=Math.max(0,r-t-a-s),u="above"===l?d:c,p="above"===l?c:d,h=u>=n||u>=p;return{side:h?l:"above"===l?"below":"above",maxHeight:Math.max(o,Math.min(n,h?u:p))}}function aZ(e,t,r){return Math.min(e*t,r)}function aX(e,t,r){let{viewportFraction:n,cap:a,gap:s,margin:l,minHeight:o,prefer:d}=r,[c,u]=(0,i.useState)({side:d??"above",maxHeight:a}),p=(0,i.useCallback)(()=>{let t=e.current;if(!t)return;let r=window.visualViewport?.height??window.innerHeight,i=t.getBoundingClientRect(),c=aY(i.top,i.bottom,r,aZ(r,n,a),{gap:s,margin:l,minHeight:o,prefer:d});u(e=>e.side===c.side&&e.maxHeight===c.maxHeight?e:c)},[e,a,s,l,o,d,n]);return(0,i.useEffect)(()=>{if(!t)return;p();let r=e.current,n=r?new ResizeObserver(p):null;return r&&n&&n.observe(r),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),window.visualViewport?.addEventListener("resize",p),window.visualViewport?.addEventListener("scroll",p),()=>{n?.disconnect(),window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0),window.visualViewport?.removeEventListener("resize",p),window.visualViewport?.removeEventListener("scroll",p)}},[e,p,t]),c}var aQ=r(14755);async function a0(e,t,r,n,i,a,s){let l=e.slice(1).split(/\s/,1)[0];try{let o=t?.length?t:await s?.()??[],d=[...si,...o].find(e=>e.name===l||"aliases"in e&&e.aliases?.includes(l));if(a&&(!d||"builtin"===d.source))return i(`/${l} cannot run with attachments. Remove them and retry.`),!1;let c=await r?.(e);if(c?.handled){if(c.error)return!1;return c.prompt&&n(c.prompt),!0}if(d&&"builtin"!==d.source)return n(e),!0;return i(`/${l} is not available in this web session.`),!1}catch(e){return i(e instanceof Error?e.message:String(e)),!1}}function a1(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t}let a2=["off","default","full"],a4={off:"none",default:"default",full:"full"},a5=aQ.IN.join(" \xb7 "),a8=aQ.C1.filter(e=>!aQ.IN.includes(e)).join(" \xb7 ");function a6(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let a3=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),a7=0,a9={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function se(e,t){return a3.compare(e.name||e.modelId,t.name||t.modelId)||a3.compare(e.provider,t.provider)||a3.compare(e.modelId,t.modelId)}let st=["auto","off","minimal","low","medium","high","xhigh","max"],sr=["low","medium","high","xhigh"],sn={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},si=[{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"}],sa=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],ss={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},sl={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function so(e,t,r){let n=e.name.toLowerCase(),i=sd(e,r).toLowerCase();return n===t?0:n.startsWith(t)?1:n.includes(t)?2:i.includes(t)?3:4}function sd(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function sc(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function su(e){return{data:e.data,mimeType:e.mimeType}}function sp(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function sh(e){return(e??[]).filter(an).slice(0,10).map(sp)}let sf=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,sm="\n\nTranscript of the audio ";function sg(e){return ns(e).map(e=>{let t=nh(e),r="audio"===t&&e.attachmentId&&!e.text.includes(sm)?sf.exec(e.text):null;return{...e,id:++a7,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...r?{storedInfo:{path:r[1],mimeType:r[2],size:Number(r[3])}}:{}}})}function sx({name:e,mimeType:t,size:r,text:n,attachmentId:i}){return i?{name:e,mimeType:t,size:r,text:n,attachmentId:i}:{name:e,mimeType:t,size:r,text:n}}function sv(e,t){let r=new Map(t.flatMap(e=>e.attachmentId?[[e.attachmentId,e]]:[]));return[...e.map(e=>{let t=e.attachmentId?r.get(e.attachmentId):void 0;return t?(r.delete(e.attachmentId),{...e,id:t.id,sourceSize:t.sourceSize,storedInfo:t.storedInfo??e.storedInfo,transcription:t.transcription}):e}),...t.filter(e=>"ready"!==e.status)]}class sb extends Error{constructor(e,t,r,n){super(e),this.code=t,this.completedParts=r,this.parts=n}}let sy="composer:unkeyed";async function sw(e){let t=await e.json().catch(()=>null),r=t&&"object"==typeof t?{...t}:{};if(e.ok)return r;throw new sb("string"==typeof r.error?r.error:`HTTP ${e.status}`,"string"==typeof r.code?r.code:null,"number"==typeof r.completedParts?r.completedParts:null,"number"==typeof r.parts?r.parts:null)}function sk(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function sj({tone:e,title:t,body:r}){let i="error"===e?"danger":"warning";return(0,n.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(--${i}-line)`,borderRadius:"var(--radius-control)",background:`var(--${i}-soft)`,color:`var(--${i})`,fontSize:11,lineHeight:1.45},children:[(0,n.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,n.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,n.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,n.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontWeight:600},children:t}),(0,n.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:r})]})]})}function sS({error:e}){return e?(0,n.jsx)(sj,{tone:"error",title:"Model error",body:e}):null}function sC({warnings:e}){return e&&0!==e.length?(0,n.jsx)(sj,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let sN=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:r,onFollowUp:a,isStreaming:l,model:o,isAutoModelSelection:d,modelNames:c,modelList:u,modelError:p,modelScopeWarnings:h,onModelChange:f,onMainPresetChange:m,mainPresetActiveAlias:g,modelRoles:x,onRoleModelChange:v,modelSwitching:b,onCompact:y,onAbortCompaction:w,isCompacting:k,compactError:j,compactResult:S,toolPreset:C,onToolPresetChange:N,thinkingLevel:I,effectiveThinkingLevel:T,thinkingCeiling:M,onThinkingLevelChange:$,availableThinkingLevels:E,thinkingLevelMap:L,fastMode:z=null,fastModeBusy:A=!1,onFastModeToggle:P,retryInfo:F,deliveryRows:_=[],inputHistory:D=[],onRecallQueue:H,onRemoveQueuedMessage:O,slashCommands:B,slashCommandsLoading:U,onLoadSlashCommands:q,onBuiltinCommand:K,soundEnabled:V,onSoundToggle:J,onAudioUnlock:G,onPromptWithStreamingBehavior:Y,draftKey:Z,cwd:X,sessionId:Q,onEnsureSession:ee,onLiveTranscriptPersisted:et},er){let en,ei,ea,es,el,eo,ed,ec,eu,ep,{t:eh}=(0,R.s)(),{st:ef}=rp(),em=_.some(e=>e.removable),eg=W(),[ex,ev]=(0,i.useState)(()=>Z?aS(Z)?.value??"":""),[eb,ey]=(0,i.useState)(!1),[ew,ek]=(0,i.useState)(null),[ej,eS]=(0,i.useState)(""),[eC,eN]=(0,i.useState)({});(0,i.useEffect)(()=>{eb&&eN(aG())},[eb]);let[eI,eT]=(0,i.useState)(!1),[eM,e$]=(0,i.useState)(null),[eR,eE]=(0,i.useState)(!1),[eL,ez]=(0,i.useState)(!1),[eA,eP]=(0,i.useState)(null),[eW,eF]=(0,i.useState)(!1),[e_,eD]=(0,i.useState)(()=>Z?sh(aS(Z)?.images):[]),[eH,eO]=(0,i.useState)(()=>Z?sg(aS(Z)?.documents):[]),[eB,eU]=(0,i.useState)(null),eq=(0,i.useMemo)(()=>eH.filter(e=>"ready"===e.status),[eH]),eK=eH.some(e=>"ready"!==e.status||a1(e)),eV=eH.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(sm))),eJ=ex.trimStart(),eG=0===e_.length&&0===eH.length&&eJ.startsWith("!"),eY=eG&&eJ.startsWith("!!"),[eZ,eX]=(0,i.useState)(!1),[eQ,e0]=(0,i.useState)(0),[e1,e2]=(0,i.useState)(null),[e4,e5]=(0,i.useState)(!1),[e8,e6]=(0,i.useState)(0),[e3,e7]=(0,i.useState)(!1),[e9,te]=(0,i.useState)(0),[tt,tr]=(0,i.useState)(null),[tn,ti]=(0,i.useState)(!1),[ta,ts]=(0,i.useState)(null),[tl,to]=(0,i.useState)(null),td=X&&tl?.cwd===X?tl.values:{},tc=(0,i.useRef)(null),tu=(0,i.useRef)(null),tp=(0,i.useRef)(null),th=(0,i.useRef)(null),tf=(0,i.useRef)(null),tm=(0,i.useRef)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),tb=(0,i.useRef)(null),ty=(0,i.useRef)(null),tw=(0,i.useRef)(!1),tk=(0,i.useRef)(0),tj=(0,i.useRef)(!1),tS=(0,i.useRef)([]),tC=(0,i.useRef)([]),tN=(0,i.useRef)([]),tI=(0,i.useRef)(null),tT=(0,i.useRef)(null),tM=(0,i.useRef)(Z),t$=(0,i.useRef)(ex),tR=(0,i.useRef)(e_),tE=(0,i.useRef)(0),tL=(0,i.useRef)(eH);t$.current=ex,tR.current=e_,tL.current=eH,(0,i.useImperativeHandle)(er,()=>({insertIfEmpty(e){let t=tc.current;(t?t.value:ex).trim()||(t$.current=e,ev(e),e2(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){let t,r,n=tc.current;if(!function(e,t,r,n=0){return!e.trim()&&0===t&&0===r&&0===n}(n?n.value:ex,tR.current.length,tE.current,tL.current.length))return;let i=(t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),nd(t)?.message??t),a=sh("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,r=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof r)return[];let n={data:t,mimeType:r};return an(n)?[n]:[]})),s=sg((r="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),nd(r)?.documents??[]));t$.current=i,tR.current=a,tL.current=s,ev(i),e2(null),e7(!1),eD(e=>(e.forEach(sk),a)),eO(s),requestAnimationFrame(()=>{n&&(n.focus(),n.style.height="auto",n.style.height=`${Math.min(n.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(tM.current!==e)return void aT(e,t);let r={value:t$.current,images:tR.current.map(su),documents:tL.current.filter(e=>"ready"===e.status).map(sx)},n=aT(e,t,r)??{value:"",images:[],documents:[]},i=n.value===r.value&&n.images.length===r.images.length&&n.images.every((e,t)=>e.data===r.images[t]?.data&&e.mimeType===r.images[t]?.mimeType)&&n.documents.length===r.documents.length&&n.documents.every((e,t)=>e.name===r.documents[t]?.name&&e.mimeType===r.documents[t]?.mimeType&&e.size===r.documents[t]?.size&&e.text===r.documents[t]?.text&&e.attachmentId===r.documents[t]?.attachmentId);if(tM.current=t,i)return;let a=sh(n.images),s=sv(sg(n.documents),tL.current),l=n.value;t$.current=l,tR.current=a,tL.current=s,ev(l),eD(e=>(e.forEach(sk),a)),eO(s),e2(null),e7(!1)},restoreSubmission(e,t,r,n){if(!e.trim()&&!t?.length&&!r?.length)return;let i=tM.current,a=n??i,s=a===i,l=!s&&a?aS(a):null,o=aI(e,t,s?t$.current:l?.value??"",s?tR.current.map(su):l?.images??[],r,s?tL.current.filter(e=>"ready"===e.status).map(sx):l?.documents??[]);if(a&&aC(a,o),!s)return;let d=t?.length?[...sh(t).slice(0,Math.max(0,10-tR.current.length)),...tR.current].slice(0,10):tR.current,c=sv(sg(o.documents),tL.current);t$.current=o.value,tR.current=d,tL.current=c,ev(o.value),e2(null),e7(!1),t?.length&&eD(e=>{let r=Math.max(0,10-e.length),n=sh(t).slice(0,r),i=n.length>0?[...n,...e]:e;return tR.current=i,i}),eO(c),requestAnimationFrame(()=>{let e=tc.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},insertText(e){let t=tc.current;if(!t)return void ev(t=>t+(t?" ":"")+e);let r=t.selectionStart??t.value.length,n=t.selectionEnd??t.value.length,i=t.value.slice(0,r),a=t.value.slice(n),s=i.length>0&&!i.endsWith(" ")?" ":"",l=i+s+e+a;t$.current=l,ev(l),e2(null),requestAnimationFrame(()=>{if(!t)return;let n=r+s.length+e.length;t.setSelectionRange(n,n),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){tG(e)}}));let tz=(0,i.useCallback)(async e=>{let t=Math.max(0,10-tR.current.length-tE.current),r=e.filter(e=>e.size>0xa00000);r.length>0&&eU(eh("chat.attachImageTooLarge",{name:r.map(e=>e.name).join(", "),limit:nc(0xa00000)}));let n=e.filter(e=>e.size<=0xa00000),i=n.slice(0,t);if(i.length<n.length&&eU(eh("chat.attachImageLimit",{count:10})),i.length){tE.current+=i.length;try{let e=await Promise.all(i.map(e=>new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let r=n.result.split(",")[1];t({data:r,mimeType:e.type,previewUrl:URL.createObjectURL(e)})},n.onerror=r,n.readAsDataURL(e)})));eD(t=>{let r=e.slice(0,Math.max(0,10-t.length));e.slice(r.length).forEach(sk);let n=[...t,...r];return tR.current=n,n})}finally{tE.current-=i.length}}},[eh]),tA=(0,i.useCallback)(async e=>{for(let t of e){let e=nr(t);if(!e)continue;if(tL.current.length>=3){eU(eh("chat.attachLimit",{count:3}));continue}if(t.size>8388608){eU(eh("chat.attachTooLarge",{name:t.name,limit:nc(8388608)}));continue}if(tL.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eU(eh("chat.attachTotalTooLarge",{limit:nc(0x1000000)}));continue}let r={id:++a7,name:t.name,mimeType:r9[e],size:t.size,text:"",status:"extracting"},n=[...tL.current,r];tL.current=n,eO(n);try{let e=await nl(t);if(tL.current.reduce((e,t)=>e+(t.id===r.id?0:t.text.length),0)+e.text.length>24e4)throw new r7("text_too_large","Total extracted text exceeds 240000 characters");let n=tL.current.map(t=>t.id===r.id?{...e,id:t.id,status:"ready"}:t);tL.current=n,eO(n)}catch(i){let e=tL.current.some(e=>e.id===r.id),n=tL.current.filter(e=>e.id!==r.id);if(tL.current=n,eO(n),!e)continue;i instanceof r7?"text_too_large"===i.code?eU(eh("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===i.code?eU(eh("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===i.code?eU(eh("chat.attachNoPdfText",{name:t.name})):"password_protected"===i.code?eU(eh("chat.attachPasswordProtected",{name:t.name})):eU(eh("chat.attachExtractFailed",{name:t.name})):eU(eh("chat.attachExtractFailed",{name:t.name}))}}},[eh]),tP=(0,i.useCallback)((e,t)=>{if(!tL.current.some(t=>t.id===e))return!1;let r=t?tL.current.map(r=>r.id===e?t:r):tL.current.filter(t=>t.id!==e);return tL.current=r,eO(r),!0},[]),tW=(0,i.useCallback)((e,t)=>{if(!tL.current.some(t=>t.attachmentId===e))return!1;let r=tL.current.map(r=>r.attachmentId===e?t(r):r);return tL.current=r,eO(r),!0},[]),tF=(0,i.useCallback)((e,t,r)=>{if(!e||e===tM.current)return;let n=aS(e);n?.documents.some(e=>e.attachmentId===t)&&aC(e,{...n,documents:sg(n.documents).map(e=>e.attachmentId===t?r(e):e).map(sx)})},[]),t_=(0,i.useRef)(new Map),tD=(0,i.useRef)(new Map),tH=(0,i.useRef)(new Set),tO=(0,i.useCallback)((e,t,r)=>{if(!e.storedInfo)return null;let n=Math.min(12e4,24e4-r.reduce((t,r)=>t+(r.attachmentId===e.attachmentId?0:r.text.length),0)),i=nf({...e.storedInfo,transcript:t},n);return i.length>n?null:{...e,text:i,size:new TextEncoder().encode(i).byteLength,transcription:void 0}},[]),tB=(0,i.useCallback)(e=>e instanceof sb&&"media_tool_unavailable"===e.code?eh("chat.transcribeToolMissing"):e instanceof sb&&"transcription_failed"===e.code&&null!==e.completedParts&&null!==e.parts?eh("chat.transcribePartialFailed",{done:e.completedParts,total:e.parts}):e instanceof Error?e.message:String(e),[eh]),tU=(0,i.useCallback)(async(e,t)=>{let r=tM.current,n=tL.current.find(t=>t.attachmentId===e);if(!n?.storedInfo)return;let i=n.transcription?.state==="confirm"?n.transcription.plan:null;tD.current.get(e)?.abort();let a=new AbortController;tD.current.set(e,a),tW(e,e=>({...e,transcription:{state:"running",plan:i}}));try{let n=await sw(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{confirmed:!0}:{}),signal:a.signal}));if("string"!=typeof n.transcript)throw new sb("Invalid transcription result",null,null,null);let i=n.transcript;tW(e,e=>tO(e,i,tL.current)??{...e,transcription:{state:"failed",error:eh("chat.transcribeTooLong")}})||tF(r,e,e=>tO(e,i,[])??e)}catch(r){if(a.signal.aborted)return void tW(e,e=>({...e,transcription:{state:"skipped"}}));if(r instanceof sb&&"confirmation_required"===r.code)return void tq.current?.(e);let t=tB(r);tW(e,e=>({...e,transcription:{state:"failed",error:t}}))}finally{tD.current.get(e)===a&&tD.current.delete(e)}},[eh,tB,tW,tF,tO]),tq=(0,i.useRef)(null),tK=(0,i.useCallback)(async e=>{let t;tD.current.get(e)?.abort();let r=new AbortController;tD.current.set(e,r),tW(e,e=>({...e,transcription:{state:"planning"}}));try{t=function(e){if("boolean"!=typeof e.requiresConfirmation||"number"!=typeof e.estimatedCalls||"string"!=typeof e.notice||null!==e.durationSeconds&&"number"!=typeof e.durationSeconds||"direct"!==e.processing&&"compress-and-split"!==e.processing)throw new sb("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await sw(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{cache:"no-store",signal:r.signal})))}catch(t){if(r.signal.aborted)tW(e,e=>({...e,transcription:{state:"skipped"}}));else{let r=tB(t);tW(e,e=>({...e,transcription:{state:"failed",error:r}}))}return}finally{tD.current.get(e)===r&&tD.current.delete(e)}t.requiresConfirmation?tW(e,e=>({...e,transcription:{state:"confirm",plan:t}})):await tU(e,!1)},[tU,tB,tW]);tq.current=tK;let tV=(0,i.useCallback)(e=>{let t=tD.current.get(e);t?t.abort():tW(e,e=>({...e,transcription:{state:"skipped"}}))},[tW]),tJ=(0,i.useCallback)(async(e,t)=>{let r=null;for(let n of e){if(tL.current.length>=3){eU(eh("chat.attachLimit",{count:3}));continue}let e="file"===t&&n.size<=8388608,i={id:++a7,name:n.name,mimeType:"text/plain",size:e?n.size:0,text:"",status:e?"extracting":"uploading",sourceSize:n.size},a=[...tL.current,i];tL.current=a,eO(a);let s=(e,t)=>{let r=tL.current.filter(e=>e.id!==i.id);return e<=12e4&&r.reduce((e,t)=>e+t.text.length,0)+e<=24e4&&r.reduce((e,t)=>e+t.size,0)+t<=0x1000000};if(e){let e=await n.arrayBuffer().then(e=>{var t;return 255===(t=new Uint8Array(e))[0]&&254===t[1]?na("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?na("utf-16be",t.subarray(2)):t.includes(0)?null:na("utf-8",t)??na("euc-kr",t)},()=>null);if(null!==e&&s(e.length,n.size)){tP(i.id,{...i,text:e,status:"ready"});continue}}if(null===r&&(r=1048576*(await aB().catch(()=>aD)).uploadLimitMb),n.size>r){tP(i.id,null)&&eU(eh("chat.attachStoredTooLarge",{name:n.name,limit:nc(r)}));continue}let l={...i,stored:t,status:"uploading",size:0};if(!tP(i.id,l))continue;let o=tM.current??sy,d=await aE(o),c=null,u=new AbortController;t_.current.set(i.id,u);try{if(tH.current.has(i.id))continue;let e=await nm(n,{sessionId:Q,draftId:d.draftId,signal:u.signal}),r=tL.current.filter(e=>e.id!==i.id).reduce((e,t)=>e+t.text.length,0),a=nf({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-r)),p=new TextEncoder().encode(a).byteLength;if(!s(a.length,p)){tP(i.id,null)&&eU(eh("chat.attachTotalTooLarge",{limit:nc(0x1000000)}));continue}let h={...l,attachmentId:e.id,text:a,size:p,status:"ready",storedInfo:{path:e.path,size:e.size,mimeType:e.mimeType},..."audio"===t?{transcription:{state:"planning"}}:{}};if(tP(i.id,h))c=e.id;else if(!tH.current.has(i.id)&&o!==tM.current){let t=aS(o)??{value:"",images:[],documents:[]};aC(o,{...t,documents:[...t.documents,sx(h)]}),c=e.id}}catch(e){if(u.signal.aborted)continue;tP(i.id,null)&&eU(eh("chat.attachUploadFailed",{name:n.name,error:e instanceof Error?e.message:String(e)}))}finally{t_.current.delete(i.id),d.end(c)}c&&"audio"===t&&tL.current.some(e=>e.attachmentId===c)&&tK(c)}},[tP,tK,Q,eh]),tG=(0,i.useCallback)(async e=>{eU(null);let{images:t,documents:r,audio:n,files:i}=function(e){let t=[],r=[],n=[],i=[];for(let a of e)a.type.startsWith("image/")?t.push(a):null!==nr(a)?r.push(a):ni(a)?n.push(a):i.push(a);return{images:t,documents:r,audio:n,files:i}}(e),a=r.filter(e=>e.size>8388608);await Promise.all([tz(t),tA(r.filter(e=>e.size<=8388608)),tJ(n,"audio"),tJ([...i,...a],"file")])},[tA,tJ,tz]),tY=(0,i.useCallback)(e=>{eD(t=>{let r=[...t],[n]=r.splice(e,1);return n&&sk(n),tR.current=r,r})},[]),tX=(0,i.useCallback)(e=>{let t=tL.current.find(t=>t.id===e);if(tH.current.add(e),t_.current.get(e)?.abort(),t?.attachmentId){tD.current.get(t.attachmentId)?.abort();var r=t.attachmentId;for(let[e,t]of ah)t.delete(r)&&(0===t.size&&ah.delete(e),aF())}let n=tL.current.filter(t=>t.id!==e);tL.current=n,eO(n)},[]),tQ=(0,i.useCallback)(()=>{tR.current=[],eD(e=>(e.forEach(sk),[]))},[]),t0=(0,i.useCallback)(()=>{tL.current=[],eO([])},[]),t1=(0,i.useCallback)(()=>{t$.current="",ev(""),e2(null),e7(!1),Z&&aN(Z),tM.current&&tM.current!==Z&&aN(tM.current),tQ(),t0(),eU(null),tc.current&&(tc.current.style.height="auto")},[t0,tQ,Z]);(0,i.useEffect)(()=>{Z&&tM.current===Z&&aC(Z,{value:ex,images:e_.map(su),documents:eq.map(sx)})},[e_,Z,eq,ex]),(0,i.useEffect)(()=>{let e=tM.current;if(e===Z)return;e&&aC(e,{value:t$.current,images:tR.current.map(su),documents:tL.current.filter(e=>"ready"===e.status).map(sx)});let t=Z?aS(Z):null;tM.current=Z;let r=t?.value??"",n=sh(t?.images),i=sg(t?.documents);t$.current=r,tR.current=n,tL.current=i,ev(r),e2(null),e7(!1),eD(e=>(e.forEach(sk),n)),eO(i)},[Z]),(0,i.useEffect)(()=>{let e=tc.current;e&&(e.style.height="auto",ex&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[ex]),(0,i.useEffect)(()=>()=>{tR.current.forEach(sk)},[]);let t2=(0,i.useCallback)((e,t)=>{let r=function(e,t){let r=aM(t);if(0===r.length)return()=>{};let n=++au;return ac.set(n,{draftId:a$(e),ids:r}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=ac.get(n);if(t){if(ac.delete(n),"accepted"===e){let e=af.get(t.draftId)??new Set;for(let r of t.ids)e.add(r);af.set(t.draftId,e)}aF()}}}(tM.current??sy,e);Promise.resolve(t()).then(e=>r("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),t4=(0,i.useCallback)(async()=>{let t=ex.trim(),r=eJ.trim(),n=r.startsWith("/")||r.startsWith("!")?r:t;if(!n&&!e_.length&&!eq.length||l||eK)return;G?.();let i=e_.length?e_:void 0,a=eq.length?eq:void 0;if(n.startsWith("/")){await a0(n,B,K,t=>t2(a,()=>e(t,i,a)),eU,!!(i||a),q)&&t1();return}t1(),t2(a,()=>e(n,i,a))},[ex,eJ,e_,eq,eK,l,K,B,q,e,t1,G,t2]),t5=eJ.startsWith("/")&&!/\s/.test(eJ.slice(1))?eJ.slice(1).toLowerCase():null,t8=(()=>{if(null===t5)return[];let e=[...l?[]:si,...B??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),r=sd(e,eh).toLowerCase();return t.includes(t5)||r.includes(t5)}).sort((e,t)=>{let r=so(e,t5,eh)-so(t,t5,eh);return 0!==r?r:sl[e.source]-sl[t.source]||a3.compare(e.name,t.name)}).filter(e=>{let r=e.name.toLowerCase();return!t.has(r)&&(t.add(r),!0)})})(),{commands:t6,groups:t7}=(en=0,{commands:(ei=sa.map(e=>{let t=t8.filter(t=>t.source===e),r="skill"===e?[...t.filter(e=>!sc(e,td)),...t.filter(e=>sc(e,td))]:t;return{source:e,items:r.map(e=>({command:e,index:en++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:ei}),t9=1===t8.length?eh(t5?"chat.match":"chat.command"):eh(t5?"chat.matches":"chat.commands",{count:t8.length}),re=!!ex.trim(),rt=!eK&&(re||e_.length>0||eq.length>0),rr=(0,i.useCallback)((e,t)=>{if(!X)return void e2(null);let r=t??e.length;e2(aq(e.slice(0,r)))},[X]),rn=e1?.query??null,ri=i.useMemo(()=>null!==rn&&tt&&tt.cwd===X?function(e,t,r=20){let n=t.toLowerCase();if(!n)return e.slice(0,r);let i=[];for(let t of e){let e=function(e,t){let r=e.path.toLowerCase(),n=0;if(t.includes("/"))r===t?n=100:r.startsWith(t)?n=80:r.includes(t)?n=50:aV(t,r)&&(n=10);else{let e=r.lastIndexOf("/"),i=-1===e?r:r.slice(e+1);i===t?n=100:i.startsWith(t)?n=80:i.includes(t)?n=50:r.includes(t)?n=30:aV(t,r)&&(n=10)}return e.isDir&&n>0&&(n+=10),n}(t,n);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||aK(e.entry.path)-aK(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,r).map(e=>e.entry)}(tt.entries,rn):[],[rn,tt,X]),ra=!!(rn&&tt?.truncated&&tt.cwd===X);(0,i.useEffect)(()=>{if(!ra||!X||!rn)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(X)}&q=${encodeURIComponent(rn)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>ts({cwd:X,query:rn,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[ra,rn,X]);let rs=ra&&null!==ta&&ta.cwd===X&&ta.query===rn,rl=rs?ta.matches:ri,ro=null===e1?null:`${e1.start}:${+!!e1.quoted}:${e1.query}`;(0,i.useEffect)(()=>{if(null===ro){e5(!1),e6(0);return}e5(!0),e6(0)},[ro]);let rd=null!==e1,rc=aX(tb,e3,{viewportFraction:.44,cap:360}),ru=aX(tb,eZ,{viewportFraction:.56,cap:460}),rh=aX(tb,e4,{viewportFraction:.48,cap:400});(0,i.useEffect)(()=>{if(!rd||!X)return;let e=tI.current;e&&e.cwd===X&&Date.now()-e.fetchedAt<1e4||tT.current===X||(tT.current=X,ti(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{tr({cwd:X,entries:function(e){let t=new Set;for(let r of e){let e=r.indexOf("/");for(;-1!==e;)t.add(r.slice(0,e)),e=r.indexOf("/",e+1)}let r=[];for(let e of t)r.push({path:e,isDir:!0});for(let t of e)t&&r.push({path:t,isDir:!1});return r.sort((e,t)=>aK(e.path)-aK(t.path)||e.path.localeCompare(t.path)),r}(e.files??[]),truncated:!!e.truncated}),tI.current={cwd:X,fetchedAt:Date.now()}}).catch(()=>{tI.current=null}).finally(()=>{tT.current=null,ti(!1)}))},[rd,X]);let rf=(0,i.useCallback)(e=>{if(!e1)return;let t=tc.current,r=t?.selectionStart??ex.length,n=ex.slice(0,e1.start),i=ex.slice(r);e1.quoted&&i.startsWith('"')&&(i=i.slice(1));let a=function(e,t,r=!1){let n=t?`${e}/`:e,i=r||n.includes(" ");if(t){let e=i?`@"${n}"`:`@${n}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let a=i?`@"${n}" `:`@${n} `;return{text:a,cursorOffset:a.length}}(e.path,e.isDir,e1.quoted),s=n+a.text+i,l=n.length+a.cursorOffset;ev(s),e2(aq(s.slice(0,l))),requestAnimationFrame(()=>{let e=tc.current;e&&(e.focus(),e.setSelectionRange(l,l),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[e1,ex]);(0,i.useEffect)(()=>{e8>=rl.length&&e6(Math.max(0,rl.length-1))},[rl.length,e8]),(0,i.useEffect)(()=>{tC.current.length=rl.length},[rl.length]),(0,i.useEffect)(()=>{e4&&tC.current[e8]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e8,e4]),(0,i.useEffect)(()=>{e9>=D.length&&te(Math.max(0,D.length-1))},[D.length,e9]),(0,i.useEffect)(()=>{tN.current.length=D.length},[D.length]),(0,i.useEffect)(()=>{e3&&tN.current[e9]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e9,e3]);let rm=(0,i.useCallback)(e=>{t$.current=e,ev(e),e7(!1),te(0),e2(null),requestAnimationFrame(()=>{let t=tc.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),rg=(0,i.useCallback)(e=>{let t=`/${e.name} `;t$.current=t,ev(t),eX(!1),e0(0),requestAnimationFrame(()=>{let e=tc.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),rx=(0,i.useCallback)(async e=>{let t=ex.trim(),n=eJ.trim(),i=n.startsWith("/")||n.startsWith("!")?n:t,s=eK||!i&&0===e_.length&&0===eq.length?null:{message:i,images:e_.length?e_:void 0,documents:eq.length?eq:void 0};if(!s)return;G?.();let l="steer"===e?"steer":"followUp";if(i.startsWith("/")){await a0(i,B,K,e=>{if(!Y)throw Error("Cannot queue this command while the session is busy.");t2(s.documents,()=>Y(e,l,s.images,s.documents))},eU,!!(s.images?.length||s.documents?.length),q)&&t1();return}t1(),"steer"===e&&r?t2(s.documents,()=>r(s.message,s.images,s.documents)):"followup"===e&&a&&t2(s.documents,()=>a(s.message,s.images,s.documents))},[ex,eJ,e_,eq,eK,B,q,K,Y,r,a,t1,G,t2]),rv=(0,i.useCallback)(e=>{let t=t6.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eQ-1);if("right"===e)return Math.min(t,eQ+1);let r=tS.current[eQ];if(!r)return"down"===e?Math.min(t,eQ+1):Math.max(0,eQ-1);let n=r.getBoundingClientRect(),i=n.left+n.width/2,a=n.top+n.height/2,s=-1,l=1/0;for(let r=0;r<=t;r+=1){if(r===eQ)continue;let t=tS.current[r];if(!t)continue;let n=t.getBoundingClientRect(),o=n.top+n.height/2-a;if("down"===e?o<=4:o>=-4)continue;let d=1e3*Math.abs(o)+Math.abs(n.left+n.width/2-i);d<l&&(s=r,l=d)}return s>=0?s:"down"===e?Math.min(t,eQ+1):Math.max(0,eQ-1)},[t6.length,eQ]),rb=(0,i.useCallback)(e=>{let n=e.nativeEvent,i=Date.now()-tk.current<100,s=tw.current||n.isComposing||229===n.keyCode;if("Enter"===e.key&&!e.shiftKey&&(s||i)){i&&e.preventDefault();return}if(e3&&!s){if("ArrowDown"===e.key){e.preventDefault(),te(e=>Math.min(Math.max(0,D.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),te(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e7(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&D[e9]){e.preventDefault(),rm(D[e9]);return}}if(eZ&&null!==t5){if("ArrowDown"===e.key){e.preventDefault(),e0(rv("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e0(rv("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e0(rv("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e0(rv("left"));return}if("Escape"===e.key){e.preventDefault(),eX(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&t6[eQ]){e.preventDefault(),rg(t6[eQ]);return}}if(e4&&null!==e1&&!s){if("ArrowDown"===e.key){e.preventDefault(),e6(e=>Math.min(Math.max(0,rl.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),e6(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e5(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&rl[e8]){e.preventDefault(),rf(rl[e8]);return}}if("ArrowUp"===e.key&&!s&&!l&&D.length>0&&0===ex.trim().length){e.preventDefault(),eX(!1),e5(!1),te(D.length-1),e7(!0);return}if("Escape"===e.key&&!s&&l&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),l&&(r||a)?rx(r?"steer":"followup"):t4())},[l,r,a,t,eZ,t5,t6,eQ,rg,rx,t4,rv,e4,e1,rl,e8,rf,e3,D,e9,rm,ex]),rw=(0,i.useCallback)(()=>{let e=tc.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),rk=(0,i.useCallback)(e=>{let t=function(e){let t=Array.from(e.files??[]);if(t.length>0)return t;let r=[];for(let t of Array.from(e.items??[])){if("file"!==t.kind)continue;let e=t.getAsFile();e&&r.push(e)}return r}(e.clipboardData);t.length&&(e.preventDefault(),tG(t))},[tG]);(0,i.useEffect)(()=>{if(null===t5){eX(!1),e0(0),tj.current=!1;return}eX(!0),e0(0),!tj.current&&q&&(tj.current=!0,Promise.resolve(q()).catch(()=>{tj.current=!1}))},[t5,q]),(0,i.useEffect)(()=>{if(!eZ||!X)return;let e=!1;return to({cwd:X,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let r={};for(let e of t.skills??[])r[e.name]=e.disableModelInvocation;to({cwd:X,values:r})}).catch(()=>{e||to({cwd:X,values:{}})}),()=>{e=!0}},[eZ,X]),(0,i.useEffect)(()=>{eQ>=t6.length&&e0(Math.max(0,t6.length-1))},[t6.length,eQ]),(0,i.useEffect)(()=>{tS.current.length=t6.length},[t6.length]),(0,i.useEffect)(()=>{eZ&&tS.current[eQ]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eQ,eZ]);let rS=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(se):Object.entries(c??{}).map(([e,t])=>({provider:o?.provider??"unknown",modelId:e,name:t})).sort(se),rC=g??null,rN=t3.bo.find(e=>e.alias===rC)?.provider??null,rI=rN?rS.filter(e=>e.provider===rN):rS,rT=(ea=ej.trim().toLocaleLowerCase())?rI.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(ea)):rI,rM=rI.length>8,r$=[];for(let e of rT){let t=r$.find(t=>t.provider===e.provider);t?t.options.push(e):r$.push({provider:e.provider,options:[e]})}let rR=rN?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),rE=o?rR.find(e=>e.resolved?.provider===o.provider&&e.resolved?.modelId===o.modelId):void 0,rL=ej.trim()?[]:rI.map((e,t)=>{var r,n;return{option:e,order:t,count:eC[r=e.provider,n=e.modelId,`${r}/${n}`]??0}}).filter(e=>e.count>=2).sort((e,t)=>t.count-e.count||e.order-t.order).slice(0,5).map(({option:e,count:t})=>({option:e,count:t})),rz=(e,t,r)=>{let i=e.modelId===o?.modelId&&e.provider===o?.provider;return(0,n.jsxs)("button",{onClick:()=>{if(ey(!1),eS(""),!i||d){var t,r;let n=function(e,t){let r={...e,[t]:(e[t]??0)+1},n=Object.keys(r);if(n.length<=30)return r;for(let e of(n.sort((e,t)=>r[e]-r[t]),n)){if(Object.keys(r).length<=30)break;e!==t&&delete r[e]}return r}(aG(),(t=e.provider,r=e.modelId,`${t}/${r}`));try{window.localStorage.setItem(aJ,JSON.stringify(n))}catch{}eN(n),f?.(e.provider,e.modelId)}},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,n.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,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),e.name,void 0!==r&&r>=2&&(0,n.jsx)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10.5},children:eh("chat.modelPickCount",{count:r})})]},`${t}:${e.provider}:${e.modelId}`)},rA=o?rS.find(e=>e.modelId===o.modelId&&e.provider===o.provider)?.name??o.modelId:null,rP=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,rW=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:eh("chat.compacted")} ${tZ(S.tokensBefore)} -> ${tZ(S.estimatedTokensAfter)} tokens (${eh("chat.tokensSaved",{saved:tZ(rP)})})`:null,rF=e=>{let t=L?.[e];return null!=t&&t!==e?t:null},r_="auto"===(es=I??"auto")?M?`auto ≤ ${rF(M)??M}`:"auto":L?L[es]??es:es,rD=(I??"auto")==="auto"&&T&&"auto"!==T?L?.[T]??T:null,rH=$&&rD?eh("chat.currentReasoning",{level:rD}):null,rO=e=>!E||E.includes(e),rB=[{level:"auto",ceiling:null},...sr.filter(rO).map(e=>({level:"auto",ceiling:e})),...st.filter(e=>"auto"!==e&&rO(e)).map(e=>({level:e,ceiling:null}))],rU=Object.entries(a4).find(([,e])=>e===(C??"default"))?.[0]??"default";(0,i.useEffect)(()=>{let e=e=>{tu.current&&!tu.current.contains(e.target)&&tp.current&&!tp.current.contains(e.target)&&(ey(!1),eS("")),th.current&&!th.current.contains(e.target)&&tf.current&&!tf.current.contains(e.target)&&eT(!1),tm.current&&!tm.current.contains(e.target)&&eE(!1),tg.current&&!tg.current.contains(e.target)&&ez(!1),tx.current&&!tx.current.contains(e.target)&&eF(!1),!tv.current||tv.current.contains(e.target)||tc.current?.contains(e.target)||e7(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{eg||eF(!1)},[eg]);let rq=(0,n.jsx)("button",{type:"button",className:`composer-icon-button${e_.length||eH.length?" is-active":""}`,onClick:()=>ty.current?.click(),title:eh("chat.attachFile"),"aria-label":eh("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:e_.length||eH.length?"var(--accent)":"var(--text-muted)",cursor:"pointer",opacity:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=e_.length||eH.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=e_.length||eH.length?"var(--accent)":"var(--text-muted)"},children:(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,n.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,n.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),rK=m&&t3.bo.length>0?(0,n.jsxs)("div",{ref:th,style:{position:"relative",flexShrink:+!!eg,minWidth:0},children:[(0,n.jsxs)("button",{className:`${eg?"composer-icon-button":"composer-chip"}${eI?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();e$({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ey(!1),eS(""),eT(e=>!e)},disabled:l||b,"aria-haspopup":"menu","aria-expanded":eI,onKeyDown:e=>{"Escape"===e.key&&eI&&(e.stopPropagation(),eT(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:eI?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l||b?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eI?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:eh("chat.mainPreset"),"aria-label":eh("chat.mainPreset"),children:[(0,n.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,n.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"})}),eg?null:(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:eh("chat.mainPreset")})]}),eI&&eM&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:r}=aY(eM.top,eM.bottom,e,aZ(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eM.top+6}:{top:eM.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eM.left,width:"max-content",minWidth:eM.width};return(0,n.jsx)("div",{ref:tf,role:"menu","aria-label":eh("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(eT(!1),th.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:r,display:"flex",flexDirection:"column"},children:(0,n.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:t3.bo.map(e=>{let t=e.alias===rC;return(0,n.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eT(!1),m((0,t3.zq)(e))},title:`${e.provider}/${e.model}`,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:t?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,n.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,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("img",{className:"account-avatar",src:(0,t3.uk)(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,n.jsx)("span",{children:e.alias}),(0,n.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[e.provider,"/",e.model,void 0!==e.oauthPosition?` \xb7 OAuth ${e.oauthPosition}`:""]})]},e.alias)})})})})()]}):null,rV=$?(0,n.jsxs)("div",{ref:tg,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,n.jsxs)("button",{type:"button",className:`${eg?"composer-icon-button":"composer-chip"}${eL?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eP({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ey(!1),eS(""),eT(!1),ez(e=>!e)},disabled:l||b,"aria-haspopup":"menu","aria-expanded":eL,onKeyDown:e=>{"Escape"===e.key&&eL&&(e.stopPropagation(),ez(!1))},title:eh("chat.changeReasoning",{level:r_}),"aria-label":eh("chat.changeReasoning",{level:r_}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eg?0:"8px 12px",height:32,background:eL?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l||b?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eL?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,n.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,n.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,n.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,n.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),eg?null:(0,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:r_})]}),eL&&eA&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:r}=aY(eA.top,eA.bottom,e,aZ(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eA.top+6}:{top:eA.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eA.left,width:"max-content",minWidth:Math.max(180,eA.width)};return(0,n.jsx)("div",{role:"menu","aria-label":eh("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(ez(!1),tg.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:r},children:rB.map(({level:e,ceiling:t})=>{let r=(I??"auto")===e&&("auto"!==e||(M??null)===t),i=t??e,a="auto"===e&&null===t?null:rF(i),s=t?`auto ≤ ${a??t}`:a??e,l=t?eh("chat.thinkingAutoCapped",{level:a??t}):eh(sn[e]);return(0,n.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":r,onClick:()=>{ez(!1),$(e,t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:r?"var(--bg-selected)":"none",border:"none",color:r?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:r?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[r?(0,n.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,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsxs)("span",{style:{flex:1},children:[s,null!==a&&(0,n.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",i,")"]})]}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:l})]},t?`auto-${t}`:e)})})})()]}):null,rJ=P?(el=A?eh("chat.fastModeBusy"):null===z?eh("chat.fastModeUnknown"):z.active?eh("chat.fastModeActive"):z.enabled?eh("chat.fastModeInactive"):eh("chat.fastModeOff"),eo=A||l||b,ed=z?.enabled===!0,(0,n.jsx)("button",{type:"button",className:`composer-icon-button${z?.active?" is-active":""}`,onClick:P,disabled:eo,"aria-pressed":null===z?void 0:z.enabled,"aria-busy":A||void 0,title:el,"aria-label":el,style:{flexShrink:0,opacity:l?.5:1},children:(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:z?.active?"var(--accent)":"none",stroke:ed?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===z?"3 2":void 0,style:{opacity:ed&&!z?.active?.6:1},"aria-hidden":"true",children:(0,n.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})):null,rG=(0,n.jsxs)(n.Fragment,{children:[r&&(0,n.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>rx("steer"),disabled:!rt,title:eK?eh("chat.attachExtractingWait"):eh("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:rt?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:rt?"var(--warning)":"var(--text-dim)",cursor:rt?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,n.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),eh("chat.steer")]}),a&&(0,n.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>rx("followup"),disabled:!rt,title:eK?eh("chat.attachExtractingWait"):eh("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:rt?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:rt?"var(--accent-hover)":"var(--text-dim)",cursor:rt?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,n.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,n.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),eh("chat.followUp")]})]}),rY=void 0!==J?(0,n.jsx)(i2,{soundEnabled:V??!0,onToggle:J}):null;return(0,n.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,n.jsx)("input",{ref:ty,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{tG(Array.from(e.target.files??[])),e.target.value=""}}),(0,n.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:[(0,n.jsx)(sS,{error:p}),(0,n.jsx)(sC,{warnings:h}),_.length>0&&(0,n.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",padding:"5px 0"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,n.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:ef("delivery.title",{count:_.length})}),H&&em&&(0,n.jsxs)("button",{onClick:H,title:eh("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:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,n.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),eh("chat.recall")]})]}),(0,n.jsx)(iQ,{rows:_,removeLabel:eh("chat.queueRemove"),onRemove:O?(e,t)=>O("steer"===e?"steering":"followUp",t):void 0})]}),F&&(0,n.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,n.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,n.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,n.jsx)("path",{d:"M3 3v5h5"})]}),eh("chat.retrying",{attempt:F.attempt,max:F.maxAttempts}),F.errorMessage&&(0,n.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",F.errorMessage]})]}),rW&&(0,n.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,n.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,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),rW]}),j&&(0,n.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:j}),eB&&(0,n.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,n.jsx)("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"},children:eB}),(0,n.jsx)("button",{type:"button",onClick:()=>eU(null),"aria-label":eh("i18n.close"),title:eh("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,n.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,n.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,n.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(e_.length>0||eH.length>0)&&(0,n.jsxs)("div",{role:"list","aria-label":eh("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[e_.map((e,t)=>(0,n.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,n.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",display:"block"}}),(0,n.jsx)("button",{type:"button","aria-label":eh("chat.removeImage",{index:t+1}),onClick:()=>tY(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,n.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,n.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,n.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},`image-${t}`)),eH.map(e=>(0,n.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||a1(e)||void 0,style:{display:"flex",alignItems:"center",gap:7,minWidth:0,maxWidth:320,height:32,padding:"0 7px 0 9px"},children:["ready"!==e.status||e.transcription?.state==="planning"||e.transcription?.state==="running"?(0,n.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"}}):rj(e.name,14),(0,n.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,n.jsx)("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:e.name}),(0,n.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===e.stored?eh("chat.attachKindAudio"):"file"===e.stored?eh("chat.attachKindFile"):a9[e.mimeType]," \xb7 ",nc(e.sourceSize??e.size),"extracting"===e.status?` \xb7 ${eh("chat.attachExtracting")}`:"","uploading"===e.status?` \xb7 ${eh("chat.attachUploading")}`:"",e.transcription?.state==="planning"?` \xb7 ${eh("chat.transcribeChecking")}`:"",e.transcription?.state==="confirm"?` \xb7 ${eh("chat.attachTranscribePending")}`:"",e.transcription?.state==="running"?` \xb7 ${eh("chat.attachTranscribing")}`:"",e.transcription?.state==="failed"&&(0,n.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${eh("chat.attachTranscribeFailed")}`})]})]}),(0,n.jsx)("button",{type:"button",onClick:()=>tX(e.id),"aria-label":eh("chat.removeAttachment",{name:e.name}),title:eh("chat.removeAttachment",{name:e.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,n.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,n.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,n.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},e.id))]}),eV.length>0&&(0,n.jsx)("div",{role:"group","aria-label":eh("chat.transcribeGroup"),"aria-live":"polite",style:{display:"flex",flexDirection:"column",gap:6,marginBottom:6},children:eV.map(e=>{let t,r,i,a,l=e.attachmentId,o=e.transcription,d=o?.state==="confirm"||o?.state==="running"?o.plan:null,c=d?eh("chat.transcribePlanSummary",{duration:null===d.durationSeconds?eh("chat.transcribeDurationUnknown"):(r=Math.floor((t=Math.round(d.durationSeconds))/3600),i=Math.floor(t%3600/60),a=String(t%60).padStart(2,"0"),r>0?`${r}:${String(i).padStart(2,"0")}:${a}`:`${i}:${a}`),calls:d.estimatedCalls}):null,u=o?.state==="confirm"?eh("chat.transcribeConfirmTitle",{name:e.name}):o?.state==="running"?eh("chat.transcribeRunning",{name:e.name}):o?.state==="planning"?`${e.name} \xb7 ${eh("chat.transcribeChecking")}`:o?.state==="failed"?eh("chat.transcribeFailedRow",{name:e.name,error:o.error}):eh("chat.transcribeSkipped",{name:e.name});return(0,n.jsxs)("div",{"data-transcription-state":o?.state??"idle",style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"7px 10px",border:`1px solid ${o?.state==="failed"?"var(--danger-line)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:o?.state==="failed"?"var(--danger-soft)":"var(--bg-panel)",fontSize:12,lineHeight:1.45},children:[(0,n.jsxs)("div",{style:{flex:"1 1 220px",minWidth:0},children:[(0,n.jsx)("div",{style:{color:o?.state==="failed"?"var(--danger)":"var(--text)",overflowWrap:"anywhere"},children:u}),c&&(0,n.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:c}),o?.state==="confirm"&&(0,n.jsxs)(n.Fragment,{children:[o.plan.notice&&(0,n.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:o.plan.notice}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:eh("chat.transcribeUsageNotice")})]})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[o?.state==="confirm"&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void tU(l,!0),children:eh("chat.transcribeStart")}),(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tV(l),children:eh("chat.transcribeSkip")})]}),(o?.state==="planning"||o?.state==="running")&&(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tV(l),children:eh("chat.transcribeCancel")}),(void 0===o||"skipped"===o.state||"failed"===o.state)&&(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void tK(l),children:eh(o?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,n.jsxs)("div",{ref:tb,style:{position:"relative",minWidth:0},children:[e3&&D.length>0&&(0,n.jsxs)("div",{ref:tv,style:{position:"absolute",left:0,right:0,...a6(rc.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:rc.maxHeight},children:[(0,n.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,n.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,n.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,n.jsx)("path",{d:"M3 4v5h5"}),(0,n.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,n.jsx)("div",{style:{maxHeight:Math.max(0,rc.maxHeight-31),overflowY:"auto",padding:4},children:D.map((e,t)=>{let r=t===e9;return(0,n.jsxs)("button",{ref:e=>{tN.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),rm(e)},onMouseEnter:()=>te(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:"var(--radius-control)",background:r?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,n.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,n.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),eZ&&null!==t5&&(0,n.jsxs)("div",{style:{position:"absolute",left:0,right:0,...a6(ru.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:ru.maxHeight},children:[(0,n.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,n.jsx)("span",{children:U?eh("chat.loadingCommands"):eh("chat.slashCommands",{label:t9})}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,n.jsx)("div",{style:{maxHeight:Math.max(0,ru.maxHeight-34),overflowY:"auto",padding:10},children:U||0!==t8.length?t7.map(e=>(0,n.jsxs)("section",{style:{marginBottom:12},children:[(0,n.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,n.jsx)("span",{children:eh(ss[e.source])}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,n.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(({command:e,index:t})=>{let r=t===eQ,i=sc(e,td);return(0,n.jsxs)("button",{ref:e=>{tS.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),rg(e)},onMouseEnter:()=>e0(t),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${r?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:r?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:r?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,n.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:i?"var(--text-dim)":void 0},children:["/",e.name,i&&(0,n.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:eh("chat.dormant")})]}),sd(e,eh)&&(0,n.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:sd(e,eh)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,n.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eh("chat.noCommands")})})]}),e4&&null!==e1&&(ec=tn&&(!tt||tt.cwd!==X),eu=1===rl.length?eh("chat.match"):eh("chat.matches",{count:rl.length}),ep=tt?.truncated&&!rs?e1.query?eh("chat.searchingAll"):eh("chat.indexTruncated"):"",(0,n.jsxs)("div",{style:{position:"absolute",left:0,right:0,...a6(rh.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:rh.maxHeight},children:[(0,n.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,n.jsx)("span",{children:ec?eh("chat.loadingFiles"):eh("chat.files",{label:eu,hint:ep})}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,n.jsx)("div",{style:{maxHeight:Math.max(0,rh.maxHeight-34),overflowY:"auto",padding:4},children:ec||0!==rl.length?rl.map((e,t)=>{let r=t===e8,i=e.path.split("/").pop()??e.path,a=e.path.slice(0,e.path.length-i.length);return(0,n.jsxs)("button",{ref:e=>{tC.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),rf(e)},onMouseEnter:()=>e6(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:"var(--radius-control)",background:r?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,n.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,n.jsx)(ry,{size:14}):rj(i,14)}),(0,n.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[a&&(0,n.jsx)("span",{style:{color:"var(--text-dim)"},children:a}),i,e.isDir&&(0,n.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,n.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:ra&&!rs?eh("chat.searching"):eh("chat.noMatchingFiles")})})]})),(0,n.jsxs)("div",{className:`chat-composer-field${eG?" is-bash":""}${l?" is-streaming":""}`,style:{minWidth:0,display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:`1px solid ${eG?"var(--tool-bg)":l&&(r||a)?"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,n.jsx)("textarea",{className:"chat-composer-textarea",ref:tc,value:ex,onChange:e=>{t$.current=e.target.value,ev(e.target.value),e7(!1),rr(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;rr(t.value,t.selectionStart)},onKeyDown:rb,onCompositionStart:()=>{tw.current=!0},onCompositionEnd:e=>{tw.current=!1,tk.current=Date.now();let t=e.currentTarget;rr(t.value,t.selectionStart)},onInput:rw,onPaste:rk,placeholder:l&&(r||a)?eh("chat.steerPlaceholder"):l?eh("chat.agentPlaceholder"):eh("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"}}),l?eg?null:(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:rG}):(0,n.jsxs)("button",{className:"chat-composer-send",onClick:t4,disabled:!rt,"aria-busy":eK||void 0,"aria-label":eg?eh("chat.send"):void 0,title:eK?eh("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eg?44:void 0,padding:eg?0:"7px 14px",background:rt?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:rt?"var(--accent-hover)":"var(--text-dim)",cursor:rt?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 0.15s"},children:[(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,n.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),eg?null:eh("chat.send")]})]})]}),eG&&(0,n.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eY?"var(--text-muted)":"var(--accent)",marginTop:4},children:[eh("chat.shell")," \xb7 ",eY?eh("chat.outputLocal"):eh("chat.outputModel")]}),(0,n.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,n.jsxs)("div",{style:{flex:eg?"1 1 0%":"0 0 auto",minWidth:eg?"min-content":0,display:"flex",alignItems:"center",gap:2},children:[(!eg||!l)&&rq,!eg&&rK,!(eg&&l)&&(rS.length>0||rA||p)&&f&&(0,n.jsxs)("div",{ref:tu,style:{position:"relative",flex:eg?"1 1 0%":void 0,width:eg?0:void 0,minWidth:44*!!eg},children:[(0,n.jsxs)("button",{className:`composer-chip${eb?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();ek({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ey(e=>(e&&eS(""),!e))},disabled:l||b,"aria-busy":b||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:eg?"flex-start":void 0,padding:eg?"8px 10px":"8px 12px",height:32,width:eg?"100%":void 0,maxWidth:eg?"100%":220,overflow:"hidden",background:eb?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l||b?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eb?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:b?"Switching model":rS.length>0?"Change model":"No available models",children:[b?(0,n.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,n.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,n.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,n.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,n.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,n.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,n.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,n.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,n.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,n.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,n.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:rA??(rS.length>0?"Select model":"No models")})]}),eb&&ew&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:r}=aY(ew.top,ew.bottom,e,aZ(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ew.top+6}:{top:ew.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ew.left,width:"max-content",minWidth:ew.width};return(0,n.jsxs)("div",{ref:tp,style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:r,display:"flex",flexDirection:"column"},children:[rM&&(0,n.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,n.jsx)("input",{value:ej,onChange:e=>eS(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eS(""),ey(!1))},placeholder:eh("chat.filterModels"),"aria-label":eh("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!eg,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,n.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[rL.length>0&&(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eh("chat.frequentModels")}),rL.map(({option:e,count:t})=>rz(e,"frequent",t))]}),rR.length>0&&!ej.trim()&&v&&(0,n.jsxs)("div",{style:{borderTop:rL.length>0?"1px solid var(--border)":"none"},children:[(0,n.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eh("chat.modelRoles")}),rR.map(e=>{let t=rE?.role===e.role,r=e.resolved?.name??e.resolved?.modelId??"";return(0,n.jsxs)("button",{onClick:()=>{ey(!1),eS(""),v(e.role)},title:e.selector??r,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,n.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,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("span",{style:{flexShrink:0,minWidth:58,padding:"1px 6px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-subtle)",color:t?"var(--accent)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:e.tag??e.role.toUpperCase()}),(0,n.jsx)("span",{style:{fontWeight:t?600:500},children:e.name}),(0,n.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[r,e.resolved?.thinkingLevel?` \xb7 ${e.resolved.thinkingLevel}`:""]})]},e.role)}),(0,n.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:eh("chat.allModels")})]}),0===r$.length?(0,n.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:ej.trim()?eh("chat.noMatchingModels"):"No available models"}):r$.map((e,t)=>(0,n.jsxs)("div",{children:[r$.length>1&&(0,n.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:t>0?"1px solid var(--border)":"none"},children:e.provider}),e.options.map(e=>rz(e,"all"))]},e.provider))]})]})})()]}),eg&&l&&(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:rG}),!eg&&rV,!eg&&rJ,!eg&&rH&&(0,n.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:rH}),(0,n.jsx)(ar,{sessionId:Q})]}),(0,n.jsxs)("div",{ref:tx,style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:eg?4:2},children:[eg?(0,n.jsx)("button",{type:"button",className:`composer-icon-button${eW?" is-active":""}`,title:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eW,onClick:()=>{ey(!1),eS(""),eF(e=>!e)},children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,n.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,n.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,n.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:eW?void 0:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eW,onClick:()=>{ey(!1),eS(""),eF(e=>!e)},children:eh("chat.moreControls")}),(0,n.jsxs)("div",{role:"group","aria-label":eh("chat.moreControls"),style:{display:eW?"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:[eg&&(0,n.jsxs)(n.Fragment,{children:[l&&rq,rK,rV,rJ]}),!l&&N&&(0,n.jsxs)("div",{ref:tm,style:{position:"relative"},children:[(0,n.jsxs)("button",{className:`composer-chip${eR?" is-active":""}`,onClick:()=>!l&&eE(e=>!e),disabled:l,title:eh("chat.changeToolPreset")+`: ${rU}`,"aria-label":eh("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:eR?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eR?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.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,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:rU})]}),eR&&(0,n.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:a2.map(e=>{let t=a4[e],r=(C??"default")===t,i="off"===e?eh("chat.noTools"):"default"===e?eh("chat.builtInTools",{tools:a5}):eh("chat.allBuiltInTools",{tools:`${a5} + ${a8}`});return(0,n.jsxs)("button",{onClick:()=>{eE(!1),r||N(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:r?"var(--bg-selected)":"none",border:"none",color:r?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:r?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[r?(0,n.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,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("span",{style:{flex:1},children:e}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:i})]},e)})})]}),!l&&y&&(0,n.jsx)("div",{children:(0,n.jsx)("button",{className:`composer-chip${k?" is-active is-danger":""}`,onClick:k?w:y,disabled:l&&!k,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:k?"var(--danger-soft)":"none",border:"none",borderRadius:"var(--radius-control)",color:k?"var(--danger)":"var(--text-muted)",cursor:l&&!k?"not-allowed":"pointer",fontSize:12,opacity:l&&!k?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!l||k)&&(e.currentTarget.style.background=k?"var(--danger-soft)":"var(--bg-hover)",e.currentTarget.style.color=k?"var(--danger)":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=k?"var(--danger-soft)":"none",e.currentTarget.style.color=k?"var(--danger)":"var(--text-muted)"},title:k?eh("chat.stopCompaction"):eh("chat.compactContext"),"aria-label":k?eh("chat.stopCompaction"):eh("chat.compactContext"),children:k?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,n.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(0,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compacting")})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,n.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,n.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,n.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(0,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compact")})]})})}),eg&&rY,eW&&(0,n.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:eh("chat.collapseControls"),"aria-label":eh("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eE(!1),ez(!1),eF(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,n.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),l&&(0,n.jsxs)("button",{className:"composer-chip is-danger is-active",onClick:t,title:eh("chat.stopAgent"),"aria-label":eg?eh("chat.stopAgent"):void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eg?44:void 0,padding:eg?0:"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:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--danger-soft)"},children:[(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,n.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),eg?null:eh("chat.stop")]}),(0,n.jsx)(ae,{sessionId:Q,onEnsureSession:ee,onTranscriptPersisted:et}),!eg&&rY]})]})]})]})});function sI({statuses:e}){if(0===e.length)return null;let t=[...e].sort((e,t)=>e.key.localeCompare(t.key)).map(({text:e})=>e.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()).join(" "),r=ej(t);return(0,n.jsx)("div",{role:"status","aria-label":r,title:r,style:{display:"flex",alignItems:"center",flexShrink:0,minWidth:0,height:36,padding:"0 12px",borderTop:"1px solid var(--border)",background:"transparent"},children:(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,textOverflow:"ellipsis",whiteSpace:"nowrap"},children:eT(t).map((e,t)=>(0,n.jsx)("span",{style:e.style,children:e.text},t))})})}function sT({phases:e}){let{t}=(0,R.s)(),[r,a]=(0,i.useState)(!1),[s,l]=(0,i.useState)(!1),{currentPhase:o,activeTask:d,remaining:c,completed:u,total:p,percent:h}=e7(e);if(0===p)return null;let f=0===c;return(0,n.jsxs)("div",{className:`todo-strip${f?" is-done":""}`,children:[(0,n.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":r,onClick:()=>a(e=>!e),children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:f?"✓":"›"}),o&&(0,n.jsx)("span",{className:"todo-strip-phase",children:o.name}),(0,n.jsx)("span",{className:"todo-strip-task",children:f?t("todo.allDone",{count:u}):d?.content??""}),(0,n.jsx)("span",{className:"todo-strip-count",children:f?t("todo.progressDone",{percent:h??0,completed:u,total:p}):t("todo.progress",{percent:h??0,completed:u,total:p,remaining:c})})]}),r&&(0,n.jsxs)("div",{className:"todo-strip-body",children:[e.map((t,r)=>{let i=t.tasks.filter(e=>s||"completed"!==e.status);return 0===i.length?null:(0,n.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[e.length>1&&(0,n.jsx)("div",{className:"todo-checklist-phase-name",children:t.name}),i.map((e,t)=>(0,n.jsx)(rx,{task:e},`${e.content}-${t}`))]},`${t.name}-${r}`)}),u>0&&(0,n.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":s,onClick:()=>l(e=>!e),children:t(s?"todo.hideCompleted":"todo.showCompleted",{count:u})})]})]})}function sM(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function s$(e){switch(e.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==e.closed;default:return!1}}async function sR(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let r={body:e.body,...e.tag?{tag:e.tag}:{}};if(t.getServiceWorkerRegistration)try{let n=await t.getServiceWorkerRegistration();if(n)return await n.showNotification(e.title,{...r,data:{url:e.sessionUrl}}),"service-worker"}catch{}try{let n=t.createWindowNotification(e.title,r);return n.onclick=()=>{n.close(),e.onClick()},"window"}catch{return null}}var sE=r(62503);class sL extends Error{constructor(e,t,r,n){super(e),this.status=t,this.code=r,this.accepted=n,this.name="AgentCommandError"}}async function sz(e,t){let r=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),n=await r.json().catch(()=>({}));if(!r.ok||n.error)throw new sL(n.error??`HTTP ${r.status}`,r.status,n.code,n.accepted);return n.data}let sA="ompweb-update-client-id",sP="ompweb-update-resume-intent-v2",sW="ompweb-update-return-v1",sF="cuelo-restart-return-v1",s_="ompweb-update-failure-return-v1",sD="ompweb:update-wake";function sH(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function sO(){let e=sessionStorage.getItem(sA);if(e&&/^[A-Za-z0-9_-]{16,128}$/.test(e))return e;let t="function"==typeof crypto.randomUUID?crypto.randomUUID().replaceAll("-",""):Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("");return sessionStorage.setItem(sA,t),t}function sB(){sessionStorage.removeItem(sP)}function sU(){let e=sessionStorage.getItem(sW);if(!e)return null;try{let t=JSON.parse(e);if(1!==t.schemaVersion||"string"!=typeof t.requestId||!/^[0-9a-f]{32}$/.test(t.requestId)||"string"!=typeof t.stageHash||!/^[0-9a-f]{64}$/.test(t.stageHash)||"boolean"!=typeof t.dismissed)return null;return t}catch{return null}}function sq(e){let t=sU();if(!t||t.requestId!==e)return t;let r={...t,dismissed:!0};try{sessionStorage.setItem(sW,JSON.stringify(r))}catch{}return r}async function sK(e){let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"heartbeat",clientId:sO(),sessionId:e.sessionId,resumeUrl:e.resumeUrl,preservationError:e.preservationError??null,...e.update?{requestId:e.update.requestId,stageHash:e.update.stageHash}:{}}),cache:"no-store"});if(!t.ok)throw Error(`maintenance heartbeat HTTP ${t.status}`);return await t.json()}async function sV(e){if(e.sessionId){let t=await fetch(`/api/sessions/${encodeURIComponent(e.sessionId)}?deferThinking=1&deferMedia=1`,{cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(!t.ok)throw Error(`session resume HTTP ${t.status}`);if((await t.json()).sessionId!==e.sessionId)throw Error("resumed session identity mismatch")}let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"resume-confirm",requestId:e.requestId,stageHash:e.stageHash,clientId:e.clientId,sessionId:e.sessionId}),cache:"no-store"});if(!t.ok)throw Error(`resume confirm HTTP ${t.status}`);let r=await t.json().catch(()=>null);!function(e){let t=sU();if(t&&t.requestId===e.requestId&&t.stageHash===e.stageHash)return;let r={schemaVersion:1,requestId:e.requestId,stageHash:e.stageHash,dismissed:!1};try{sessionStorage.setItem(sW,JSON.stringify(r))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),sB();let n=r?.wake;e.sessionId&&(n?.wake===!0||n?.reason==="already-claimed"||n?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(sD,{detail:{sessionId:e.sessionId}}))}async function sJ(e){let t=function(e){let t=sessionStorage.getItem(s_);if(!t)return null;sessionStorage.removeItem(s_);try{let r=JSON.parse(t);if(1!==r.schemaVersion||r.requestId!==e.requestId||r.stageHash!==e.stageHash||r.clientId!==e.clientId)return null;return{wake:!0===r.wake}}catch{return null}}(e);return t?(sB(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(sD,{detail:{sessionId:e.sessionId}})),"failed"):(await sV(e),"resumed")}function sG(e,t){let r=new Map(e.map(e=>[e.id,e]));for(let e of t)r.set(e.id,function(e,t){return e&&(void 0!==e.parentToolCallId&&void 0!==t.parentToolCallId?e.parentToolCallId===t.parentToolCallId:void 0===e.sessionFile||void 0===t.sessionFile||e.sessionFile===t.sessionFile)?{...t,index:e.index,agent:e.agent,agentSource:e.agentSource,description:e.description??t.description,task:e.task??t.task,assignment:e.assignment??t.assignment,sessionFile:t.sessionFile??e.sessionFile,parentToolCallId:t.parentToolCallId??e.parentToolCallId}:t}(r.get(e.id),e));let n=[...r.values()];return[...n.filter(e=>"pending"===e.status||"running"===e.status).sort((e,t)=>e.index-t.index||e.id.localeCompare(t.id)),...n.filter(e=>"pending"!==e.status&&"running"!==e.status).sort((e,t)=>t.lastUpdate-e.lastUpdate||e.id.localeCompare(t.id))].slice(0,128)}function sY(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"update":return{isStreaming:!0,streamingMessage:t.message};case"end":case"reset":return{isStreaming:!1,streamingMessage:null};default:return e}}function sZ(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function sX(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function sQ(e){return t=>{let r=e?.isCompacting?e.compaction:null;if(!r)return t;let n=Date.now()-r.elapsedMs;return{startedAt:t?Math.min(t.startedAt,n):n,reason:t?.reason??r.reason}}}function s0(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){let n=e[r],i=t[r];if(!n||!i||n.name!==i.name||n.tasks.length!==i.tasks.length)return!1;for(let e=0;e<n.tasks.length;e+=1){let t=n.tasks[e],r=i.tasks[e];if(!t||!r||t.content!==r.content||t.status!==r.status||t.blocker!==r.blocker)return!1}}return!0}function s1(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function s2(e,t){for(let r=e.length-1;r>=0;r--){let n=t[r]??null;if(!eJ(n??void 0))return{message:e[r],entryId:n}}return null}let s4=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class s5 extends Error{constructor(e){super("timeout"===e?"Timed out connecting to the agent event stream. Please try again.":"Failed to connect to the agent event stream. Please try again."),this.status=e,this.name="EventStreamConnectionError"}}function s8(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function s6(e){return new Promise(t=>setTimeout(t,e))}function s3(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,r)=>r===t?{...e,exiting:!0}:e)}function s7(e,t){switch(t.type){case"add":if(e.visible.some(e=>e.exiting)||e.visible.length>=5)return{visible:e.visible.some(e=>e.exiting)?e.visible:s3(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:s3(e.visible)};case"remove":return function(e,t){let r=e,n=t;for(;n.length>0&&r.length<5;){let[e,...t]=n;r=[...r,e],n=t}return n.length>0&&!r.some(e=>e.exiting)&&(r=s3(r)),{visible:r,pending:n}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function s9(e){if(!e||"object"!=typeof e||"image"!==e.type)return"";let t=e.source;return t&&"object"==typeof t?["url"===t.type?"url":"base64","string"==typeof t.media_type?t.media_type:"","string"==typeof t.data?t.data:"","string"==typeof t.url?t.url:""].join(":"):["base64","string"==typeof e.mimeType?e.mimeType:"","string"==typeof e.data?e.data:"",""].join(":")}function le(e){let t,r=e.content;return"string"==typeof r?JSON.stringify({text:r,images:[]}):Array.isArray(r)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:r.map(s9).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function lt(e){return"user"===e.role?`user:${le(e)}`:"bashExecution"===e.role?JSON.stringify({role:e.role,command:e.command,output:e.output,exitCode:e.exitCode,cancelled:e.cancelled,truncated:e.truncated,fullOutputPath:e.fullOutputPath,excludeFromContext:e.excludeFromContext}):JSON.stringify({role:e.role,content:e.content,model:e.model,provider:e.provider,customType:e.customType})}function lr(e,t){return e&&"object"==typeof e?"number"!=typeof e.tokensBefore||"number"!=typeof e.estimatedTokensAfter?null:{reason:t,tokensBefore:e.tokensBefore,estimatedTokensAfter:e.estimatedTokensAfter}:null}function ln(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}function li(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let la=!1,ls={width:0,height:0},ll=new Set,lo=null;function ld(){let e=window.visualViewport,t=li();ls.width!==window.innerWidth?ls={width:window.innerWidth,height:window.innerHeight}:t||(ls.height=Math.max(ls.height,window.innerHeight));let r=function({hasFocusedEditable:e,innerHeight:t,viewportHeight:r,viewportScale:n,baselineHeight:i}){return!(!e||Math.abs(n-1)>=.01)&&(t-r>120||i-t>120)}({hasFocusedEditable:t,innerHeight:window.innerHeight,viewportHeight:e?.height??window.innerHeight,viewportScale:e?.scale??1,baselineHeight:ls.height});if(r!==la)for(let e of(la=r,ll))e()}function lc(e){if(ll.add(e),!lo){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,ld()})},r=window.visualViewport;r?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),ld(),lo=()=>{r?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{ll.delete(e),0===ll.size&&lo&&(lo(),lo=null)}}function lu(){return(0,i.useSyncExternalStore)(lc,()=>la,()=>!1)}let lp={count:50,end:null};function lh(e,t){let r=Math.max(e,0),n=null===t.end?r:Math.min(Math.max(t.end,0),r),i=Math.min(Math.max(t.count,0),n),a=n-i;return{startIndex:a,endIndex:n,hasMore:a>0,hasLater:n<r}}function lf(e,t,r){let{startIndex:n,endIndex:i}=lh(e,r);if(t>=n&&t<i)return r;let a=Math.max(0,t-10),s=Math.max(t+1,a+50);return s>=e?{count:e-a,end:null}:{count:s-a,end:s}}function lm({sticker:e,text:t,tag:r,followRef:a}){let s=(0,i.useRef)(null);return((0,i.useEffect)(()=>{(!a||a.current)&&s.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,n.jsxs)("div",{ref:s,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,n.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:iv[r]}),t&&(0,n.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,n.jsx)(ih(),{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 lg(e){if("user"!==e.role)return null;let t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),r=(nd(t)?.message??t).trim();return r.length>0?r:null}function lx(e){return`omp-cues:${e}`}function lv(e,t){let r=[];for(let n of t)n.sessionId===e&&null!==n.anchorEntryId&&r.push({id:n.id,anchorEntryId:n.anchorEntryId,sticker:n.sticker,text:n.text,tag:n.tag});try{window.localStorage.setItem(lx(e),JSON.stringify(r.slice(-200)))}catch{}}let lb=[];function ly(e){return`omp-web:interrupted-dismissed:${e}`}let lw=(0,i.memo)(function({messages:e,entryIds:t,toolResultsMap:r,modelNames:a,messageCwd:s,onOpenFile:l,sessionBusy:o,isNew:d,isStreaming:c,handleFork:u,forkingEntryId:p,handleNavigate:h,handleEditContent:f,sessionId:m,main:g,process:x,dispatchSlots:v,compactedDispatch:b,startIndex:y,endIndex:w,sentinelRef:k,laterSentinelRef:j,flashItem:S,t:C,onProcessLogChange:N,cues:I,cueFollowRef:T}){(0,i.useEffect)(()=>{N({groups:x,messages:e,entryIds:t,toolResults:r,modelNames:a,cwd:s,sessionId:m})},[N,x,e,t,r,a,s,m]);let M=(0,i.useMemo)(()=>{let t=new Map;for(let[n,i]of function(e,t,r,n){let i=new Map;e.forEach((e,t)=>{"answer"===e.kind&&i.set(e.idx,t)});let a=new Map,s=new Map;for(let e of t){let t=s.get(e.anchorIdx);for(let l of(t||(t=new Set,s.set(e.anchorIdx,t)),e.entries)){let e=r[l.idx];if(e?.role!=="assistant")continue;let s=Math.max(0,(l.blocks?i.get(l.idx):void 0)??l.afterMainIndex??-1),o=t;!function(e,t,r){for(let n of e){if("toolCall"!==n.type||"learn"!==n.toolName&&"manage_skill"!==n.toolName)continue;let e=t?.get(n.toolCallId);if(!e||e.isError)continue;let i=n.input??{};if("manage_skill"===n.toolName){let e=eX(i.action);if(!0===eZ[e]){let t={kind:"skill",action:e,name:eX(i.name)};r(JSON.stringify(t),t)}continue}let a=eX(i.memory),s=i.skill,l=s?{action:eX(s.action),name:eX(s.name)}:void 0;r(JSON.stringify({kind:"lesson",memory:a,skill:l}),{kind:"lesson",memory:a.length>160?`${a.slice(0,160)}…`:a,...l?{skill:l}:{}})}}(l.blocks??e.content??[],n,(e,t)=>{if(o.has(e))return;o.add(e);let r=a.get(s);r?r.push(t):a.set(s,[t])})}}return a}(g,x,e,r)){let e=i.map(e=>{if("skill"===e.kind)return C("chat.savedSkill",{action:e.action,name:e.name});let t=C("chat.savedLesson",{memory:e.memory});return e.skill?`${t} (${C("chat.savedSkill",e.skill)})`:t});t.set(n,{role:"custom",customType:eq,content:[C("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[g,x,e,r,C]),$=(0,i.useMemo)(()=>{let t=null;if(o)for(let r of g)"message"===r.kind&&e[r.idx]?.role==="user"&&(t=r.idx);let n=new Map;for(let[i,a]of function(e,t,r){let n=new Map,i=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user").map(e=>e.idx),a=new Map;for(let[s,l]of(e.forEach((e,t)=>{"answer"===e.kind&&a.set(e.anchorIdx,t)}),a)){if(s===r)continue;let e=i.find(e=>e>s);n.set(l,{from:s+1,to:e??t.length})}return n}(g,e,t))n.set(i,function(e,t,r){let n=[],i=[];for(let r of e){if("toolCall"!==r.type)continue;if("task"===r.toolName){i.push(r);continue}if("bash"!==r.toolName)continue;let e="string"==typeof r.input.command?r.input.command.trim():"";if(!e||!ie.test(e))continue;let a=t.get(r.toolCallId),s=a?function(e){let t=e.details;if("number"==typeof t?.exitCode)return t.exitCode;let r=e.content.map(e=>"text"===e.type?e.text:"").join("\n"),n=/Command exited with code (-?\d+)\s*$/.exec(r.trimEnd());return n?Number(n[1]):null}(a):null,l=null===s?a?.isError?"failed":"unobserved":0===s?"passed":"failed";n.push({toolCallId:r.toolCallId,command:e,state:l,exitCode:s})}return{checks:n,dispatchCalls:i,files:e8(e,t,r)}}(function(e,t,r){let n=[];for(let i=Math.max(0,t);i<Math.min(e.length,r);i++){let t=e[i];"assistant"===t.role&&n.push(...t.content??[])}return n}(e,a.from,a.to),r,s));return n},[g,e,r,s,o]),R=y>0,E=w<g.length,L=(i,g={})=>{let x=g.messageOverride??e[i],v=i-1;for(;v>=0&&eJ(t[v]);)v-=1;let b="user"===x.role&&v>=0&&"assistant"===e[v].role?t[v]:void 0,y=g.keyPrefix??"message",w=!1;if("assistant"===x.role){w=!0;for(let t=i+1;t<e.length;t++){let r=e[t].role;if("user"===r)break;if("assistant"===r){w=!1;break}}w&&c&&i===e.length-1&&(w=!1)}return void 0!==g.showTimestamp&&(w=g.showTimestamp),(0,n.jsx)(nL,{message:x,toolResults:r,modelNames:a,cwd:s,onOpenFile:l,entryId:t[i],onFork:o||d||0===i&&"user"===x.role?void 0:u,forking:p===t[i],onNavigate:o?void 0:h,prevAssistantEntryId:o?void 0:b,onEditContent:f,showTimestamp:w,prevTimestamp:i>0?e[i-1].timestamp:void 0,sessionId:m,writtenFiles:g.writtenFiles,dispatchSlot:g.dispatchSlot,turnSummary:g.turnSummary},`${y}-view-${i}`)},z=(t,r)=>{let i=g[t],a="message"===i.kind&&e[i.idx]?.role==="user";return(0,n.jsx)("div",{"data-chat-item":t,"data-chat-question":a?"":void 0,className:S===t?"chat-item chat-jump-flash":"chat-item",children:r})};return(0,n.jsxs)(n.Fragment,{children:[R&&(0,n.jsx)("div",{ref:k,className:"py-3 text-center text-xs text-text-muted",children:C("chat.loadEarlier",{count:y})}),g.slice(y,w).map((a,o)=>{let d=y+o,c=b?.position===d?(0,n.jsx)(r2,{calls:b.calls}):null,u="message"===a.kind?a.anchorIdx??a.idx:a.anchorIdx,p=g[d+1],h=p?"message"===p.kind?p.anchorIdx??p.idx:p.anchorIdx:null,f=p?p.idx:1/0,x=I.filter(r=>{let n=null!==r.anchorEntryId?t.indexOf(r.anchorEntryId):Math.min(r.liveIndex??-1,e.length-1);return n>=a.idx&&n<f}).map(e=>(0,n.jsx)(lm,{sticker:e.sticker,text:e.text,tag:e.tag,followRef:T},`cue-${e.id}`)),w=h!==u,k=M.get(d),j=k?(0,n.jsx)(nL,{message:k,cwd:s,onOpenFile:l},`saved-lessons-${d}`):null,S=w?(0,n.jsx)(iE,{turnIndex:u,turnEntryId:t[u],sessionId:m,cwd:s,onOpenFile:l}):null;if("message"===a.kind)return(0,n.jsxs)(i.Fragment,{children:[c,z(d,L(a.idx)),j,S,x]},`message-${a.idx}`);let C=e8(a.precedingBlocks,r,s);return(0,n.jsxs)(i.Fragment,{children:[c,z(d,L(a.idx,{keyPrefix:`answer-${a.runIndex}`,messageOverride:eA(e[a.idx],a.blocks),writtenFiles:C,dispatchSlot:v.get(d),turnSummary:$.get(d)})),j,S,x]},`answer-${a.idx}-${a.runIndex}`)}),b?.position===g.length&&w===g.length&&(0,n.jsx)(r2,{calls:b.calls}),E&&(0,n.jsx)("div",{ref:j,className:"py-3 text-center text-xs text-text-muted",children:C("chat.loadLater",{count:g.length-w})})]})});function lk({session:e,newSessionCwd:t,initialSessionData:a,transitioning:s=!1,onAgentEnd:l,onAttentionNeeded:o,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:f,onSessionStatsChange:m,onSessionStatsPanelOpen:g,onContextUsageChange:x,onSubagentsChange:b,onMainIdentityChange:y,onOpenWorkspaceView:w,onProcessLogChange:k,onOpenFile:j,transcriptReplacement:S,onComposerFocusChange:C,onSessionBusyChange:N,onWaitingChange:I,onAttentionChange:T,soundEnabled:M=!0,onSoundToggle:$,playCueSound:E=async()=>({sticker:null,text:null}),preloadCueSound:L,unlockAudio:z,jumpRequest:A=null,onJumpHandled:P}){var _,D;let H,O,B,{t:U}=(0,R.s)(),q=lu(),K=W(),J=q&&K,G=(0,i.useRef)(E);G.current=E;let Y=(0,i.useRef)(null),Z=(0,i.useRef)(L);Z.current=L;let[X,Q]=(0,i.useState)([]),ee=(0,i.useRef)(X);ee.current=X;let et=(0,i.useRef)(0),er=(0,i.useRef)([]),en=(0,i.useRef)([]),ei=(0,i.useRef)(null),ea=(0,i.useRef)(0),es=(0,i.useRef)(-1),el=(0,i.useRef)(-1),eo=(0,i.useCallback)(()=>{let e=ei.current?.current;return e?{sessionId:e,turn:ea.current}:null},[]),ed=(0,i.useCallback)(e=>ei.current?.current===e.sessionId&&ea.current===e.turn,[]),ec=(0,i.useCallback)((e,t,r,n)=>{if(!e.sticker&&!e.text)return;et.current=Math.max(et.current+1,Date.now());let i={id:et.current,sticker:e.sticker,text:e.text,tag:t,sessionId:r.sessionId},a="entry"===n.kind?{...i,anchorEntryId:n.entryId}:{...i,anchorEntryId:null,liveIndex:n.liveIndex,intent:n.intent};Q(e=>{let t=[...e,a];return null!==a.anchorEntryId&&lv(r.sessionId,t),t})},[]),eu=(0,i.useCallback)((e,t,r,n)=>{let i=()=>ed(r)&&("working"!==t||el.current!==r.turn);i()&&G.current(e,t,i).then(e=>{null!==t&&null!==n&&i()&&ec(e,t,r,n)}).catch(()=>{})},[ed,ec]),ep=(0,i.useCallback)(async(e,t,r)=>{let n=(await rd(e,t,r))?.alias??null;return n&&Z.current?.(n),n},[]),eh=(0,i.useCallback)((e,t,r,n)=>{let i=function(e,t){let r=e.length-1;if(r<0)return null;let n=Math.min(e.length,t.length);if(r<n)return{kind:"entry",entryId:t[r]};let i=iN(e[r]),a=0;for(let t=n;t<=r;t++)iN(e[t])===i&&(a+=1);return{kind:"pending",liveIndex:r,intent:{baseEntryId:n>0?t[n-1]:null,identity:i,occurrence:a}}}(er.current,en.current);ep(t.sessionId,r,n).then(r=>{eu(r,e,t,i)})},[eu,ep]),[ef,em]=(0,i.useState)(0),eg=(0,i.useRef)([]),ex=(0,i.useCallback)(e=>{if(ea.current+=1,null!==iy(e.outcome)){let t=e.sessionId;eg.current.push({completion:e,trigger:t?{sessionId:t,turn:ea.current}:null}),em(e=>e+1)}l?.(e)},[l]);(0,i.useEffect)(()=>{for(let{completion:e,trigger:t}of eg.current.splice(0)){let r=iy(e.outcome),n="neutral"===r?null:r;t?eh(n,t,e.provider,e.credentialId):G.current(null,n).catch(()=>{})}},[ef,eh]);let ev=(0,i.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:eb,error:ey,messages:ew,entryIds:ek,streamState:eS,agentRunning:eC,bashRunning:eN,pendingBash:eI,modelNames:eT,modelList:eM,modelError:e$,modelScopeWarnings:eR,modelThinkingLevels:eE,modelThinkingLevelMaps:eL,modelRoles:ez,toolPreset:eP,thinkingLevel:eD,effectiveThinkingLevel:eO,thinkingCeiling:eB,fastMode:eq,fastModeBusy:eZ,handleFastModeToggle:eX,retryInfo:e0,contextUsage:e1,forkingEntryId:e2,isCompacting:e4,compaction:e5,compactError:e8,compactResult:e6,displayModel:e7,modelSwitching:e9,sessionStats:te,runStateKnown:tt,compactedWork:tr,slashCommands:tn,slashCommandsLoading:ti,deliveryRows:ta,subagents:ts,todoPhases:tl,notices:to,extensionDialog:td,extensionResponse:tc,extensionCustomUi:tu,extensionStatuses:tp,extensionWidgets:th,respondToExtensionUi:tf,sendExtensionCustomInput:tm,isAutoModelSelection:tg,agentPhase:tx,isNew:tv,autoFollowPaused:tb,resumeAutoFollow:ty,pauseAutoFollow:tw,goalStatus:tk,sessionIdRef:tj,messagesEndRef:tS,scrollContainerRef:tC,handleSend:tN,handleAbort:tI,handleFork:tT,handleNavigate:tM,handleModelChange:t$,handleRoleModelChange:tR,handleMainPresetChange:tE,newSessionAccount:tL,handleCompact:tz,handleSteer:tA,handleFollowUp:tP,handlePromptWithStreamingBehavior:tW,handleAbortCompaction:tF,handleRecallQueue:t_,handleRemoveQueuedMessage:tD,handleBuiltinSlashCommand:tH,handleToolPresetChange:tO,handleThinkingLevelChange:tB,loadSlashCommands:tU,ensureNewSession:tq,refreshLiveTranscript:tK}=function(e){let{session:t,newSessionCwd:n,initialData:a,onAgentEnd:s,onAttentionNeeded:l,onSessionCreated:o,onSessionForked:d,modelsRefreshKey:c,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,f=null===t&&null!==n,m=a&&a.sessionId===t?.id?a:null,[g,x]=(0,i.useState)(m),[v,b]=(0,i.useState)(!f&&!m),[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(m?.leafId??null),[S,C]=(0,i.useState)(m?.context.messages??[]),[N,I]=(0,i.useState)(m?.context.entryIds??[]),[T,M]=(0,i.useState)(m?.context.compactedWork??null),[$,R]=(0,i.useReducer)(sY,{isStreaming:!1,streamingMessage:null}),[E,L]=(0,i.useState)(!1),[z,A]=(0,i.useState)(!1),[P,W]=(0,i.useState)(null),[F,_]=(0,i.useState)({}),[D,H]=(0,i.useState)([]),[O,B]=(0,i.useState)(null),[U,q]=(0,i.useState)([]),[K,V]=(0,i.useState)({}),[J,G]=(0,i.useState)({}),[Y,Z]=(0,i.useState)([]),[X,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(null),[er,en]=(0,i.useState)(null),[ei,ea]=(0,i.useState)("default"),[es,el]=(0,i.useState)(()=>{let e=m?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[eo,ed]=(0,i.useState)(),[ec,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(null),[ef,em]=(0,i.useState)(!1),eg=(0,i.useRef)(0),ex=(0,i.useRef)(0),ev=(0,i.useRef)(""),[eb,ey]=(0,i.useState)(null),[ew,ek]=(0,i.useState)(m?.contextUsage??null),[eS,eC]=(0,i.useState)(null),[eN,eI]=(0,i.useState)(null),[eT,eM]=(0,i.useState)(null),[e$,eR]=(0,i.useState)(null),[eE,eL]=(0,i.useState)(!1),[ez,eA]=(0,i.useState)(!1),[eP,eW]=(0,i.useState)(null),[eF,e_]=(0,i.useState)(null),[eD,eH]=(0,i.useState)(null),eO=(0,i.useRef)(null),[eB,eq]=(0,i.useState)(!1),[eK,eY]=(0,i.useState)(null),[eZ,eX]=(0,i.useState)([]),[eQ,e0]=(0,i.useState)(!1),[e1,e2]=(0,i.useReducer)(s7,{visible:[],pending:[]}),[e4,e5]=(0,i.useState)(null),[e8,e6]=(0,i.useState)(null),[e3,e7]=(0,i.useState)(null),e9=(0,i.useRef)(null),[te,tt]=(0,i.useState)(null),[tr,tn]=(0,i.useState)([]),[ti,ta]=(0,i.useState)([]),[ts,tl]=(0,i.useState)({steering:[],followUp:[]}),[to,td]=(0,i.useState)([]),[tc,tu]=(0,i.useReducer)(iY,[]),tp=(0,i.useRef)(0);(0,i.useEffect)(()=>{tu({type:"queue",steering:ts.steering,followUp:ts.followUp})},[ts]),(0,i.useEffect)(()=>{E||tu({type:"idle"})},[E]),(0,i.useEffect)(()=>{tu({type:"reset"})},[t?.id]);let th=(0,i.useMemo)(()=>(function(e,t){let r=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${iJ(t)}`;r.set(e,(r.get(e)??0)+1)}let n=[],i=(e,t)=>{t.forEach((t,i)=>{let a=`${e}\u0000${iV(t)}`,s=r.get(a)??0;s>0?r.set(a,s-1):n.push({key:`queue-${e}-${i}`,kind:e,text:t,images:0,stage:"accepted",removable:!0})})};for(let r of(i("steer",t?.steering??[]),i("followUp",t?.followUp??[]),e))n.push({key:`sent-${r.id}`,kind:r.kind,text:r.text,images:r.images,stage:r.stage,removable:r.inQueue});return n})(tc,ts),[tc,ts]),[tf,tm]=(0,i.useState)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),tb=(0,i.useRef)(null),ty=(0,i.useRef)(null),tw=(0,i.useRef)(0),tk=(0,i.useRef)(!1),tj=(0,i.useRef)(t?.id??null),tS=(0,i.useRef)(m?.leafId??null),tC=(0,i.useRef)(S),tN=(0,i.useRef)(N);tC.current=S,tN.current=N;let tI=(0,i.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),tT=(0,i.useRef)(!1),tM=(0,i.useRef)(!1),t$=(0,i.useRef)(!1),tR=(0,i.useRef)(-1),tE=(0,i.useRef)("unknown"),tL=(0,i.useRef)(null),tz=(0,i.useRef)(null),tA=(0,i.useRef)(0),tP=(0,i.useRef)(!1),tW=(0,i.useRef)(0),tF=(0,i.useRef)(null),t_=(0,i.useRef)(null),tD=(0,i.useRef)(null),tH=(0,i.useRef)(!1),tO=(0,i.useRef)(!0),[tB,tU]=(0,i.useState)(!1),[tq,tK]=(0,i.useState)(null),tV=(0,i.useRef)(void 0),tJ=(0,i.useRef)(0),tG=(0,i.useRef)(0),tY=(0,i.useRef)(()=>{}),tZ=(0,i.useRef)(null),tX=(0,i.useRef)(null),tQ=(0,i.useRef)(null),t0=(0,i.useRef)(null),t1=(0,i.useRef)(!1),t2=(0,i.useRef)(null),t4=(0,i.useRef)(null),t5=(0,i.useRef)(null),t8=(0,i.useRef)(null),t6=(0,i.useRef)(0),t3=(0,i.useRef)(null),t7=(0,i.useRef)(null),t9=(0,i.useRef)(!1);t9.current=e.transitioning??!1;let re=(0,i.useRef)(Date.now()),rt=(0,i.useRef)(0),rr=(0,i.useRef)(0),rn=(0,i.useRef)(null),ri=(0,i.useRef)(!1),ra=(0,i.useRef)(Promise.resolve()),rs=e.setToolPreset??ea,rl=eT??g?.context.model??e$??null,ro=f?X??er:rl,rd=(0,i.useMemo)(()=>{if(e4)return{...e4,totalActiveMs:g?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},r=0,n=0,i=0,a=0,s=0;for(let t of S){if("user"===t.role&&(n+=1),"toolResult"===t.role&&(a+=1),"assistant"!==t.role)continue;i+=1;let l=t.usage;s+=t.content.filter(e=>"toolCall"===e.type).length,l&&(e.input+=l.input??0,e.output+=l.output??0,e.cacheRead+=l.cacheRead??0,e.cacheWrite+=l.cacheWrite??0,r+=l.cost?.total??0)}return(e.total=e.input+e.output+e.cacheRead+e.cacheWrite,0===e.total&&0===S.length)?null:{sessionFile:g?.filePath||void 0,sessionId:tj.current??t?.id??"",sessionName:t?.name,userMessages:n,assistantMessages:i,toolCalls:s,toolResults:a,totalMessages:S.length,tokens:e,cost:r,totalActiveMs:g?.totalActiveMs,...ew?{contextUsage:ew}:{}}},[S,e4,ew,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),rc=(0,i.useRef)(0),ru=(0,i.useCallback)((e,t)=>{e&&tj.current===e&&Array.isArray(t)&&(rc.current+=1,tm(r=>r?.sid===e&&s0(r.phases,t)?r:{sid:e,phases:t}))},[]),rp=(0,i.useCallback)((e,t,r)=>{tj.current===e&&rc.current===r&&Array.isArray(t)&&tm(r=>r?.sid===e&&s0(r.phases,t)?r:{sid:e,phases:t})},[]),rh=(0,i.useCallback)(e=>{let t="function"==typeof e?e(tC.current):e;tC.current=t,C(t)},[]),rf=(0,i.useCallback)(e=>{tN.current=e,I(e)},[]),rm=(0,i.useCallback)(async(e,t=!1,r=!1,n)=>{let i=!1;try{t&&b(!0);let a=n??null;if(!a){let r=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),n=await fetch(`/api/sessions/${encodeURIComponent(e)}?${r}`);if(404===n.status)return t&&(x(null),j(null),rh([]),M(null),w(null)),null;if(!n.ok)throw Error(`HTTP ${n.status}`);a=await n.json()}if(tj.current!==e)return null;x(a),j(a.leafId),tS.current=a.leafId??null;let s=eG(a.context.messages,a.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);rh(s.messages),rf(s.entryIds),M(a.context.compactedWork??null),ek(a.contextUsage??null),eM(e=>ri.current?e:null),w(null);let l=!r&&t8.current===e;if(l||(el(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)),eu(a.context.thinkingCeiling??null),i=!0,t&&b(!1),!r){if(l)try{let t=t6.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(r.ok&&tj.current===e){let n=await r.json();tj.current===e&&t6.current===t&&(n.state?.thinkingLevel!==void 0?(el(n.state.configuredThinkingLevel??n.state.thinkingLevel),ed(n.state.thinkingLevel)):n.running||(t8.current=null,el(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=rc.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let n=await r.json();if(tj.current!==e)return null;let i=n.state;return i?(void 0!==i.contextUsage&&ek(i.contextUsage??null),void 0!==i.systemPrompt&&eC(i.systemPrompt??null),void 0!==i.thinkingLevel&&(t8.current=e,el(i.configuredThinkingLevel??i.thinkingLevel),ed(i.thinkingLevel)),void 0!==i.thinkingCeiling&&eu(i.thinkingCeiling??null),void 0!==i.extensionStatuses&&tn(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&ta(i.extensionWidgets??[]),void 0!==i.queuedMessages&&tl(sZ(i.queuedMessages)),void 0!==i.subagents&&td(e=>sG(e,i.subagents??[])),rp(e,i.todoPhases,t)):n.running||tl({steering:[],followUp:[]}),n}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),null}finally{t&&!i&&b(!1)}},[rp,rf,rh]),rg=(0,i.useCallback)(e=>{let t=ra.current.then(async()=>{tj.current===e&&await rm(e)});return ra.current=t.catch(()=>{}),t},[rm]),rx=(0,i.useCallback)(async(e,t)=>{let r=++ex.current;try{let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&n.set("leafId",t);let i=`/api/sessions/${encodeURIComponent(e)}/context?${n}`,a=await fetch(i);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();if(ex.current!==r||tj.current!==e)return;tS.current=t;let l=eG(s.context.messages,s.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);rh(l.messages),rf(l.entryIds),M(s.context.compactedWork??null),ek(s.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[rf,rh]),rv=(0,i.useCallback)(async e=>{try{let t=await sz(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(r.bind(r,14755));rs(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[rs]),rb=(0,i.useCallback)((e=0,t="(no messages)")=>{let r=tj.current;f&&n&&r&&!t1.current&&(t1.current=!0,o?.({id:r,path:"",cwd:n,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t,transient:!0}))},[f,n,o]),ry=(0,i.useCallback)(async()=>{if(tQ.current)return tQ.current;let e=tj.current;if(e&&t7.current!==e||!e&&(!f||!n))return e;let t=(async()=>{let t=e;if(!t){let e=t2.current,r=t5.current,i=t4.current;e&&eR(e);let a={cwd:n,type:"ensure_session",toolNames:(0,aQ.xG)(ei),...e?{provider:e.provider,modelId:e.modelId}:{},...r?{thinkingLevel:r}:{},...e&&null!==i?{oauthPosition:i}:{}},s=JSON.stringify(a),l=t0.current,o=l?.body===s?l.createRequestId:s8();t0.current={body:s,createRequestId:o};let d=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...a,createRequestId:o})});if(!d.ok)throw Error(`HTTP ${d.status}`);let c=await d.json();t0.current=null,t=c.sessionId,tj.current=t,null!==t3.current&&(t7.current=t),c.model&&t2.current===e&&(eR(c.model),e||en(c.model)),c.thinkingLevel&&t5.current===r&&(el(c.configuredThinkingLevel??c.thinkingLevel),ed(c.thinkingLevel))}for(;t7.current===t;){let e=t3.current;await sz(t,{type:"set_thinking_ceiling",ceiling:e}),t3.current===e&&t7.current===t&&(t7.current=null)}return t})();tQ.current=t;try{return await t}finally{tQ.current=null}},[f,n,ei]),rw=(0,i.useCallback)(async()=>{let e=tj.current??await ry();if(!e)return eX([]),[];e0(!0);try{let t=await sz(e,{type:"get_commands"}),r=t?.commands??[];return eX(r),r}catch(e){return console.error("Failed to load slash commands:",e),eX([]),[]}finally{e0(!1)}},[ry]),rk=(0,i.useCallback)(()=>{tw.current+=1,tk.current=!1,ty.current&&(clearTimeout(ty.current),ty.current=null)},[]),rj=(0,i.useCallback)(()=>{tg.current?.close(),tg.current=null,tx.current=null,tv.current=null},[]),rS=(0,i.useCallback)(()=>{tb.current?.close(),tb.current=null},[]),rC=(0,i.useCallback)(e=>{rS();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);tb.current=t,t.onmessage=t=>{try{let r=JSON.parse(t.data);"session_snapshot"===r.type?tF.current?.(r):"agent_start"===r.type&&t_.current?.(e)}catch{}}},[rS]),rN=(0,i.useCallback)(e=>{rj();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);tg.current=t,tx.current=e;let r=new Promise(r=>{let n=!1,i=e=>{n||(n=!0,clearTimeout(a),tv.current?.source===t&&(tv.current.pending=!1),r({status:e,source:t}))},a=setTimeout(()=>i("timeout"),5e3);t.onmessage=e=>{try{let t=JSON.parse(e.data);"update_maintenance"===t.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:t})),"connected"===t.type&&i("connected"),tF.current?.(t)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(i("closed"),tg.current===t&&(tT.current||tk.current))){tg.current=null,tx.current=null,tv.current=null;let t=tw.current;setTimeout(()=>{t===tw.current&&!tg.current&&(tT.current||tk.current)&&rN(e)},1e3)}}});return tv.current={source:t,promise:r,pending:!0},r},[rj]),rI=(0,i.useCallback)(async e=>{let t=tg.current;if(t&&tx.current===e){if(t.readyState===EventSource.OPEN)return;let e=tv.current;if(e?.source===t&&e.pending&&(await e.promise,tg.current===t&&t.readyState===EventSource.OPEN))return}let r=await rN(e);if("connected"!==r.status&&r.source.readyState!==EventSource.OPEN)throw tg.current===r.source&&(tg.current=null),tx.current===e&&(tx.current=null),tv.current?.source===r.source&&(tv.current=null),r.source.close(),new s5(r.status)},[rN]),rT=(0,i.useCallback)(async(e,t)=>{let r=e9.current;if(r?.id===e.id&&"sending"===r.status)return;let n=tj.current,i=e=>{e9.current=e,e7(e)};if(!n)return void i({id:e.id,status:"failed",error:"no session"});i({id:e.id,status:"sending"});try{await sz(n,{type:"extension_ui_response",id:e.id,...t})}catch(t){i({id:e.id,status:"failed",error:t instanceof Error?t.message:String(t)});return}i(null),e6(t=>t?.id===e.id?null:t)},[]),rM=(0,i.useCallback)(async(e,t)=>{let r=tj.current;if(r)try{await sz(r,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),r$=(0,i.useCallback)(e=>{let t=e.message.trim();t&&e2({type:"add",notice:{id:e.id??s8(),message:t,type:e.type??"info"}})},[]),rR=(0,i.useCallback)(e=>{let t={role:"custom",customType:eU,content:ej(e).trim(),display:!0,timestamp:Date.now()},r=tI.current,n=tj.current;r.sessionId!==n&&(r.sessionId=n,r.outputs=[]);let i=tN.current.slice(0,tC.current.length),a=null;for(let e=i.length-1;e>=0;e--)if(!eJ(i[e])){a=i[e];break}r.seq+=1,r.outputs.push({entryId:`${eV}${r.seq}`,baseEntryId:a,message:t}),rh(e=>[...e,t])},[rh]),rE=(0,i.useCallback)(t=>{if("custom"!==t.method&&"closed"in t&&t.closed){e6(e=>e?.id===t.id?null:e),e9.current?.id===t.id&&(e9.current=null,e7(null));return}switch(s$(t)&&l?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":e6(t);break;case"notify":r$({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":tn(e=>{let r=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...r,{key:t.statusKey,text:t.statusText}]:r});break;case"setWidget":ta(e=>{let r=e.filter(e=>e.key!==t.widgetKey);return t.widgetLines?[...r,{key:t.widgetKey,lines:t.widgetLines,placement:t.widgetPlacement??"aboveEditor"}]:r});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":tt(e=>t.closed?e?.id===t.id?null:e:t)}},[r$,l,e.chatInputRef]),rL=(0,i.useCallback)(()=>{let e=tT.current;return tT.current=!1,L(!1),eY(null),ey(null),R({type:"end"}),e},[]),rz=(0,i.useCallback)(()=>{tE.current="unknown",tL.current=null;let e=s2(tC.current,tN.current);tz.current=e?{entryId:e.entryId,key:lt(e.message)}:null,tA.current+=1},[]),rA=(0,i.useCallback)(()=>{let e=tE.current,t=tL.current;if("unknown"===e){let r=s2(tC.current,tN.current),n=r?.message,i=tz.current;null!==r&&(null===i||(null!==r.entryId&&null!==i.entryId?r.entryId!==i.entryId:lt(r.message)!==i.key))&&n?.role==="assistant"&&n.stopReason&&(e=s1(n),t??={provider:n.provider,...void 0!==n.credentialId?{credentialId:n.credentialId}:{}})}return{outcome:e,sessionId:tj.current,...t?{provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),rP=(0,i.useCallback)(e=>{let t=rA();if("unknown"!==t.outcome||!e)return void s?.(t);let r=tA.current;e.catch(()=>void 0).then(()=>{let e=tj.current===t.sessionId&&tA.current===r;s?.(e?rA():t)})},[s,rA]),rW=(0,i.useCallback)((e,t)=>tR.current!==e&&(tR.current=e,rP(t),!0),[rP]),rF=(0,i.useCallback)(e=>{rk(),tk.current=!0;let t=tw.current,r=async()=>{if(t===tw.current&&tj.current===e&&tk.current)try{let n=rc.current,i=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let a=await i.json();if(t!==tw.current||tj.current!==e||!tk.current)return;let s=a.state;if(td(e=>sG(e,s?.subagents??[])),rp(e,s?.todoPhases,n),a.running&&s&&(s.isStreaming||s.isPromptRunning||s.isHandoffRunning)){tk.current=!1,ty.current=null,tM.current=!!s?.isStreaming,t$.current=!!s?.isPromptRunning,tT.current=!0,L(!0),eY(s?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(a.running&&s?.isCompacting){eA(!0),eH(sQ(s)),ty.current=setTimeout(()=>void r(),600);return}if(a.running&&(s?.subagents?.length??0)>0){ty.current=setTimeout(()=>void r(),1e3);return}tk.current=!1,ty.current=null,rj()}catch{if(t!==tw.current||tj.current!==e||!tk.current)return;ty.current=setTimeout(()=>void r(),600)}};ty.current=setTimeout(()=>void r(),3e4)},[rp,rk,rj]),r_=(0,i.useCallback)(async(e=tj.current,t=rt.current)=>{if(rt.current===t)try{e&&await rm(e)}finally{if(rt.current!==t)return;let r=t$.current,n=tM.current;t$.current=!1,tM.current=!1,rn.current=null;let i=rL();r?rW(t):n&&i&&rP(),e&&rF(e)}},[rm,rP,rW,rF,rL]),rD=(0,i.useCallback)(async(e,t)=>{await s6(800);let r=Date.now();for(;tT.current&&Date.now()-r<2e4;){if(void 0!==t&&rt.current!==t)return;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(r.ok){let n=await r.json(),i=n.state;if(!n.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await r_(e,t)}}catch{}await s6(600)}},[r_]),rH=(0,i.useCallback)(async e=>{let t=tW.current+1;for(tW.current=t;tP.current&&tW.current===t&&tj.current===e;){await s6(1e3);try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)continue;let n=await r.json();if(n.state?.isBashRunning)continue;if(await rm(e),tW.current!==t||tj.current!==e)return;tP.current=!1,A(!1),W(null);return}catch{}}},[rm]),rO=(0,i.useCallback)(async e=>{if(!tT.current)return;let t=rt.current;try{let r=rc.current,n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)return;let i=await n.json();if(rt.current!==t)return;let a=i.state;if(eA(a?.isCompacting??!1),eH(sQ(a)),tl(sZ(a?.queuedMessages)),a?.contextUsage!==void 0&&ek(a.contextUsage??null),td(e=>sG(e,a?.subagents??[])),rp(e,a?.todoPhases,r),i.running&&a&&(a.isStreaming||a.isPromptRunning||a.isCompacting||a.isHandoffRunning)||!tT.current)return;a&&(void 0!==a.systemPrompt&&eC(a.systemPrompt??null),void 0!==a.extensionStatuses&&tn(a.extensionStatuses??[]),void 0!==a.extensionWidgets&&ta(a.extensionWidgets??[])),await r_(e,t)}catch{}},[rp,r_]),rB=(0,i.useCallback)(async e=>{let t=await rm(e,!1,!0),r=t?.state;return!!t?.running&&!!r&&tj.current===e&&!tT.current&&!!(r.isStreaming||r.isPromptRunning||r.isHandoffRunning)&&(tM.current=!!r.isStreaming,t$.current=!!r.isPromptRunning,tT.current=!0,L(!0),eY(r.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),R({type:"start"}),rN(e),!r.isStreaming&&r.isPromptRunning&&rD(e),!0)},[rN,rm,rD]),rU=(0,i.useCallback)(async(e,t=rt.current)=>{let r=rr.current+1;rr.current=r;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)return;let i=await n.json();if(r!==rr.current||tj.current!==e||rt.current!==t)return;i.state?.contextUsage!==void 0&&ek(i.state.contextUsage??null)}catch{}},[]);(0,i.useEffect)(()=>{if(!ez){eO.current=null,eH(null);return}eH(e=>e??{startedAt:Date.now(),reason:eO.current})},[ez]),(0,i.useEffect)(()=>{if(!E&&!ez)return;let e=()=>{let e=tj.current;e&&rU(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[E,ez,rU]),(0,i.useEffect)(()=>{if(!E)return;let e=()=>{let e=tj.current;e&&rO(e)},t=()=>{"visible"===document.visibilityState&&e()},r=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(r),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[E,rO]),(0,i.useEffect)(()=>{if(E)return;let e=()=>{let e=tj.current;e&&!tT.current&&rB(e)},t=()=>{"visible"===document.visibilityState&&e()},r=e=>{let t=tj.current,r=e.detail?.sessionId;t&&r===t&&!tT.current&&rB(t).then(e=>{e||tj.current!==t||tT.current||rm(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(sD,r),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(sD,r)}},[E,rB,rm]),t_.current=e=>{if(tj.current!==e||tT.current||tg.current||tD.current)return;let t=rB(e).then(async t=>{t||tj.current!==e||tT.current||await rm(e)}).catch(()=>{}).finally(()=>{tD.current===t&&(tD.current=null)});tD.current=t},(0,i.useEffect)(()=>{tT.current=E},[E]),tF.current=(0,i.useCallback)(e=>{switch(e.type){case"session_snapshot":{let t=function(e,t,r,n,i){if("session_snapshot"!==e.type||"string"!=typeof e.sessionId||e.sessionId!==t||"string"!=typeof e.entryId||""===e.entryId||e.entryId===r||!e.context||!Array.isArray(e.context.messages)||!Array.isArray(e.context.entryIds)||e.context.messages.length!==e.context.entryIds.length)return null;let a=e.context.messages,s=new Map;for(let e of a){let t=lt(e);s.set(t,(s.get(t)??0)+1)}let l=Math.min(n.length,i.length);for(let e of n.slice(0,l)){let t=lt(e),r=s.get(t)??0;r>0&&s.set(t,r-1)}let o=n.slice(l).filter(e=>{let t=lt(e),r=s.get(t)??0;return 0===r||(s.set(t,r-1),!1)});return{entryId:e.entryId,messages:[...a,...o],entryIds:[...e.context.entryIds],compactedWork:e.context.compactedWork??null}}(e,tj.current,tS.current,tC.current,tN.current);if(!t)break;tS.current=t.entryId;let r=eG(t.messages,t.entryIds,tI.current.sessionId===tj.current?tI.current.outputs:[]);rh(r.messages),rf(r.entryIds),M(t.compactedWork);break}case"agent_start":{let e=!tT.current;rk(),e&&rz(),tM.current=!0,tT.current=!0,L(!0),eY({kind:"waiting_model"}),R({type:"start"});break}case"agent_end":if(!tT.current)break;if(eY(null),ey(null),R({type:"end"}),tj.current){rm(tj.current);let e=rc.current;fetch(`/api/agent/${encodeURIComponent(tj.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&ek(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eC(t.state.systemPrompt??null),t.state?.extensionStatuses!==void 0&&tn(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&ta(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&td(e=>sG(e,t.state?.subagents??[])),tj.current&&rp(tj.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tK(t.state.goal??null),tl(sZ(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tK(e.status??null);break;case"agent_settled":{let e=tM.current;if(tM.current=!1,!e||t$.current)break;let t=tj.current,r=rL();eA(!1);let n=t?rm(t):void 0;t&&rF(t),r&&rP(n);break}case"prompt_done":{let e=rt.current,t=t$.current;t$.current=!1,rn.current=null;let r=tR.current!==e;if(!t&&!r)break;let n=tj.current;rW(e,n?rm(n):void 0),!tM.current&&(rL(),n&&rF(n))}break;case"prompt_error":tE.current="failed",r$({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":tE.current="failed",r$({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!tT.current)break;let t=e.message;if(t?.role!=="assistant")break;t&&R({type:"update",message:(0,sE.B)(t)}),eY(null);break}case"message_end":{if(!tT.current)break;let t=e.message;if(t?.role==="assistant"&&(tL.current={provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}},tE.current=s1(t)),t&&"user"===t.role){let e=(0,sE.B)(t),r=le(e),n=rn.current;rn.current=null,rh(t=>{let i=t[t.length-1];return n&&i?.role==="user"&&le(i)===n?n===r?t:[...t.slice(0,-1),e]:[...t,e]}),n||tu({type:"user-message",kind:"steering"in e&&!0===e.steering?"steer":"followUp",text:"user"!==e.role?"":"string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),images:"user"!==e.role||"string"==typeof e.content?0:e.content.filter(e=>"image"===e.type).length})}else t&&rh(e=>[...e,(0,sE.B)(t)]);let r=tj.current;r&&rU(r),R({type:"reset"}),eY({kind:"waiting_model"});break}case"thinking_level_changed":{let t=tj.current,r=e.thinkingLevel;t&&void 0!==r&&(t8.current=t,t6.current+=1,el(e.configured??r),ed(r));break}case"todo_changed":ru(tj.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,r=e.toolName,n=e.args;eY(e=>{let i=e?.kind==="running_tools"?[...e.tools]:[];return i.some(e=>e.id===t)||i.push({id:t,name:r,args:n}),{kind:"running_tools",tools:i}});break}case"tool_execution_end":{let t=e.toolCallId;eY(e=>{if(e?.kind!=="running_tools")return e;let r=e.tools.filter(e=>e.id!==t);return 0===r.length?{kind:"waiting_model"}:{kind:"running_tools",tools:r}});break}case"subagent_lifecycle":{let t=e.payload;if(!t?.id)break;if("started"!==t.status){let e="failed"===t.status?"failed":"aborted"===t.status?"aborted":"completed";td(r=>{let n=r.find(e=>e.id===t.id);return sG(r,[{id:t.id,index:t.index??n?.index??0,agent:t.agent??n?.agent??t.id,agentSource:t.agentSource??n?.agentSource??"bundled",description:t.description??n?.description,status:e,task:n?.task,assignment:n?.assignment,sessionFile:t.sessionFile??n?.sessionFile,parentToolCallId:t.parentToolCallId??n?.parentToolCallId,lastUpdate:Date.now(),progress:n?.progress?{...n.progress,status:e}:void 0}])});break}let r={id:t.id,index:t.index??0,agent:t.agent??t.id,agentSource:t.agentSource??"bundled",description:t.description,status:"running",sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now()};td(e=>sG(e,[r]));break}case"subagent_progress":{let t=e.payload;if(!t?.progress)break;let r=t.progress,n={id:r.id,index:t.index??r.index,agent:t.agent??r.agent,agentSource:t.agentSource??"bundled",description:r.description,status:r.status,task:t.task??r.task,assignment:t.assignment??r.assignment,sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now(),progress:r};td(e=>sG(e,[n]));break}case"queue_update":tl({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":ey({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":ey(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof e.reason){eO.current=e.reason;let t=e.reason;eH(e=>e?{...e,reason:t}:e)}eA(!0),eW(null),e_(null);break;case"auto_compaction_end":case"compaction_end":if(eA(!1),e.errorMessage)eW(e.errorMessage),e_(null);else if(!e.aborted){e_(lr(e.result,e.reason??"auto"));let t=tj.current;t&&(rm(t),rU(t))}break;case"extension_ui_request":rE(e)}},[r$,ru,rp,rk,rE,rm,rP,rW,rU,rz,rF,rL,rf,rh]);let rq=(0,i.useCallback)(async(r,i,a)=>{let s=r.trim();if(!s&&!i?.length&&!a?.length)return"returned";if(tT.current||tP.current||ri.current)return"unknown";let l=no(r,a??[]),o=!i?.length&&!a?.length&&s.startsWith("/");if(!i?.length&&!a?.length&&s.startsWith("!")){let e=s.startsWith("!!"),t=(e?s.slice(2):s.slice(1)).trim();return t?(await tV.current?.(t,e),"accepted"):"unknown"}rz();let d=rt.current+1;rk(),t$.current=!0;let c=i?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),u={role:"user",content:c?.length?[...l.trim()?[{type:"text",text:l}]:[],...c]:l,timestamp:Date.now()};rh(e=>[...e,u]),rn.current=le(u),rt.current=d,tT.current=!0,L(!0),eY(o?{kind:"running_command"}:{kind:"waiting_model"}),R({type:"start"}),tY.current(!0);let p=i?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),h=null,m=!1,g="unknown";try{if(f&&n){let e=tj.current??await tQ.current,t=await ry();t&&(h=t,X&&(eR(X),e&&await sz(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await rI(t),m=!0,await sz(t,{type:"prompt",message:l,...p?.length?{images:p}:{}}),rb(1,r),g="accepted")}else t&&(h=t.id,await rI(t.id),m=!0,await sz(t.id,{type:"prompt",message:l,...p?.length?{images:p}:{}}),g="accepted");return o&&h&&rD(h,d),g}catch(l){console.error("Failed to send message:",l);let n=l instanceof sL&&"update_draining"===l.code&&!1===l.accepted;if(!(!m||l instanceof sL&&"prompt_rejected"===l.code&&!1===l.accepted||n)&&h)return rD(h,d),"unknown";t$.current=!1,tT.current=!1,rj();let s=rn.current;return s&&rh(e=>{let t=e[e.length-1];return t?.role==="user"&&le(t)===s?e.slice(0,-1):e}),r$({type:"error",message:l instanceof Error?l.message:String(l)}),e.chatInputRef?.current?.restoreSubmission?.(r,ln(i),a,t?.id??h??void 0),rn.current=null,L(!1),eY(null),R({type:"end"}),"returned"}},[f,n,X,t,ry,rI,rb,rD,r$,rk,rj,e.chatInputRef,rz,rh]);tV.current=(0,i.useCallback)(async(r,n)=>{if(tT.current||tP.current)return;let i=`${n?"!!":"!"}${r}`;tP.current=!0,tY.current(!0),W({command:r,excludeFromContext:n}),A(!0);try{let e=tj.current??t?.id??await ry();if(!e)throw Error("Unable to create a session for the shell command");await sz(e,{type:"bash",command:r,excludeFromContext:n}),await rm(e),rb(1,i)}catch(t){console.error("Failed to execute shell command:",t),r$({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(i)}finally{tP.current=!1,W(null),A(!1)}},[r$,ry,rm,e.chatInputRef,rb,t]);let rK=(0,i.useCallback)(async()=>{let e=tj.current;if(e){if(tP.current){try{await sz(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await sz(e,{type:"abort"}),tE.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),rV=(0,i.useCallback)(async e=>{if(tP.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let t=tj.current;if(!t)return{forked:!1,error:"No active session to fork"};eI(e??null);try{let{cancelled:r,newSessionId:n}=await sz(t,{type:"fork",...e?{entryId:e}:{}})??{};if(!r&&n)return d?.(n),{forked:!0};return{forked:!1,error:"Fork was cancelled"}}catch(e){return console.error("Fork failed:",e),{forked:!1,error:e instanceof Error?e.message:String(e)}}finally{eI(null)}},[d]),rJ=(0,i.useCallback)(async e=>{if(tP.current)return;let t=tj.current;t&&(sz(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await rx(t,e))},[rx]),rG=(0,i.useCallback)(async e=>{if(tP.current)return;j(e);let t=tj.current;t&&(await rx(t,e),e&&sz(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[rx]),rY=(0,i.useCallback)(async(e,t)=>{if(f){let r={provider:e,modelId:t},n=t2.current?.provider===e;t2.current=r,n||(t4.current=null,et(null)),Q(r),eR(r);let i=tj.current??await tQ.current;if(!i)return;try{await sz(i,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let r=tj.current;if(r&&!ri.current){ri.current=!0,eM({provider:e,modelId:t}),eL(!0);try{await sz(r,{type:"set_model",provider:e,modelId:t}),ri.current=!1,await rm(r)}catch(e){console.error("Failed to set model:",e),ri.current=!1,eM(eT),r$({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await rm(r)}finally{ri.current=!1,eL(!1)}}},[r$,eT,f,rm,Q]),rZ=(0,i.useCallback)(async e=>{let t={provider:e.provider,modelId:e.modelId},r=e.oauthPosition,n={type:"set_model",provider:e.provider,modelId:e.modelId,thinkingLevel:"auto",...void 0!==r?{oauthPosition:r}:{}},i=t=>`${e.alias} preset was not applied: ${t instanceof Error?t.message:String(t)}`;if(f){if(ri.current)return!1;ri.current=!0,eL(!0);let e=t2.current,a=t4.current,s=t5.current;try{t2.current=t,t4.current=r??null,t5.current="auto";let e=tj.current??await tQ.current;return e&&await sz(e,n),Q(t),et(r??null),eR(t),el("auto"),ed(void 0),e&&await rm(e),!0}catch(r){console.error("Failed to apply Main preset:",r),t2.current=e,t4.current=a,t5.current=s,r$({type:"error",message:i(r)});let t=tj.current;return t&&await rm(t),!1}finally{ri.current=!1,eL(!1)}}let a=tj.current;if(!a||ri.current)return!1;ri.current=!0,eM(t),eL(!0);try{return await sz(a,n),await rm(a),!0}catch(e){return console.error("Failed to apply Main preset:",e),eM(eT),r$({type:"error",message:i(e)}),await rm(a),!1}finally{ri.current=!1,eL(!1)}},[r$,eT,eo,f,rm,Q,es]),rX=(0,i.useCallback)(async e=>{let t=Y.find(t=>t.role===e),r=t?.resolved;if(!r)return;if(f){let e={provider:r.provider,modelId:r.modelId},t=r.thinkingLevel;t5.current=t??null,el(t??"auto"),ed(void 0),t2.current=e,t4.current=null,et(null),Q(e),eR(e)}let n=tj.current??(f?await tQ.current:null);if(n)try{await sz(n,{type:"set_role_model",role:e}),f||eM({provider:r.provider,modelId:r.modelId})}catch(e){console.error("Failed to set role model:",e)}},[f,Y,Q]),rQ=(0,i.useCallback)(async()=>{let e=tj.current;if(e&&!ez){eO.current="manual",eA(!0),eW(null),e_(null);try{let t=await sz(e,{type:"compact"});e_(lr(t,"manual")),await rm(e,!0)}catch(e){eW(e instanceof Error?e.message:String(e)),e_(null)}finally{eA(!1)}}},[ez,rm]),r0=(0,i.useCallback)(async e=>{let r=n??t?.cwd??"",i=r?`/api/models?cwd=${encodeURIComponent(r)}`:"/api/models",a=await fetch(i,e?{signal:e}:void 0);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();_(s.models),B(s.modelError??null),q(s.modelScopeWarnings??[]),V(s.thinkingLevels??{}),G(s.thinkingLevelMaps??{}),Z(s.roles??[]);let l=s.modelList??[];if(H(l),f&&!tj.current){let e=(s.defaultModel?l.find(e=>e.id===s.defaultModel?.modelId&&e.provider===s.defaultModel?.provider):void 0)??l[0];en(e?{provider:e.provider,modelId:e.id}:null);let t=e&&s.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===t5.current&&el(t??"auto")}},[f,n,t?.cwd]),r1=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,r,n=""]=t,i=n.trim(),a=await ry(),s=e=>(e.handled&&(e.error?r$({type:"error",message:e.error}):"openSessionStats"!==e.action&&r$({type:"success",message:e.message??"Command completed"})),e);try{switch(r){case"compact":{if(!a||ez)return s({handled:!0,error:"No active session to compact"});eO.current="manual",eA(!0),eW(null),e_(null);let e=await sz(a,{type:"compact",...i?{customInstructions:i}:{}});return e_(lr(e,"manual")),await rm(a,!0)&&rb(),s({handled:!0,message:"Compacted context"})}case"reload":if(!a)return s({handled:!0,error:"No active session to reload"});return await sz(a,{type:"reload"}),await Promise.all([rm(a,!1,!0),rv(a),rw(),r0()]),s({handled:!0,message:"Reloaded session resources"});case"name":if(!a)return s({handled:!0,error:"No active session to name"});if(!i)return s({handled:!0,error:"Usage: /name <name>"});return await sz(a,{type:"set_session_name",name:i}),await rm(a)&&rb(),s({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!a)return s({handled:!0,error:"No active session"});let e=await sz(a,{type:"get_session_stats"});return e&&e5(e),h?.(),s({handled:!0,action:"openSessionStats"})}case"copy":{if(!a)return s({handled:!0,error:"No active session"});let e=await sz(a,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return s({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),s({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!a)return s({handled:!0,error:"No active session to fork"});let e=await rV();if(!e.forked)return s({handled:!0,error:e.error??"Fork failed"});return s({handled:!0,message:"Forked a new session"})}case"goal":{if(!a)return s({handled:!0,error:"No active session"});let e=await sz(a,{type:"goal",args:i});if(tK(e?.status??null),e?.error)return s({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(rR(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&r$({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return s({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!a)return s({handled:!0,error:"No active session"});if(tT.current||tP.current)return s({handled:!0,error:"Cannot hand off while the session is busy"});tT.current=!0,L(!0),eY({kind:"running_command"});try{await rI(a);let e=await sz(a,{type:"handoff",...i?{customInstructions:i}:{}});if(!e||e.cancelled)return s({handled:!0,error:"Handoff cancelled"});return await rm(a,!0)&&rb(),s({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tT.current=!1,L(!1),eY(null),tj.current===a&&rF(a)}default:{if(!a)return s({handled:!0,error:"No active session"});let t=await sz(a,{type:"execute_slash_command",message:e});if(!t?.handled)return{handled:!1};let r=t.output?.filter(e=>e.trim()).join("\n\n")??"";if(r&&rR(r),t.prompt)return{handled:!0,prompt:t.prompt};if(r)return{handled:!0};return s({handled:!0,message:"Command completed"})}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===r&&eA(!1)}},[r$,rR,rI,ry,rV,ez,r0,rm,rw,rv,rb,h,rF]),r2=(0,i.useCallback)(async(t,r,n)=>{let i=tj.current;if(!i)return r$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(r),n),"returned";let a=no(t,n??[]),s=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:"steer",text:a,images:s?.length??0});try{return await sz(i,{type:"steer",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:l}),"accepted"}catch(a){return tu({type:"fail",id:l}),console.error("Failed to steer:",a),r$({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(r),n,i),"returned"}},[r$,e.chatInputRef]),r4=(0,i.useCallback)(async(t,r,n,i)=>{let a=tj.current;if(!a)return r$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(n),i),"returned";let s=no(t,i??[]),l=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:r,text:s,images:l?.length??0});try{return await sz(a,{type:"prompt",message:s,streamingBehavior:r,...l?.length?{images:l}:{}}),tu({type:"ack",id:o}),"accepted"}catch(r){return tu({type:"fail",id:o}),console.error("Failed to queue prompt:",r),r$({type:"error",message:r instanceof Error?r.message:String(r)}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(n),i,a),"returned"}},[r$,e.chatInputRef]),r5=(0,i.useCallback)(async(t,r,n)=>{let i=tj.current;if(!i)return r$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(r),n),"returned";let a=no(t,n??[]),s=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:"followUp",text:a,images:s?.length??0});try{return await sz(i,{type:"follow_up",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:l}),"accepted"}catch(a){return tu({type:"fail",id:l}),console.error("Failed to follow up:",a),r$({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(r),n,i),"returned"}},[r$,e.chatInputRef]),r8=(0,i.useCallback)(async()=>{let e=tj.current;if(e)try{await sz(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),r6=(0,i.useCallback)(async()=>{let t=tj.current;if(t)try{var r;let n=await sz(t,{type:"clear_queue"});tu({type:"withdraw"}),tl({steering:[],followUp:[]});let i={text:(r=[...n?.steering??[],...n?.followUp??[]]).map(({text:e,images:t})=>t?.length&&"[Image]"===e?"":e).filter(e=>e.trim()).join("\n\n"),images:r.flatMap(({images:e})=>e??[]).map(({data:e,mimeType:t})=>({data:e,mimeType:t}))};e.chatInputRef?.current?.restoreSubmission?.(i.text,i.images.length?i.images:void 0,void 0,t)}catch(e){console.error("Failed to recall queued messages:",e),r$({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,r$]),r3=(0,i.useCallback)(async(e,t)=>{let r=tj.current;if(r)try{let n=await sz(r,{type:"remove_queued_message",message:t,queue:e});if(!n?.removed)return;tu({type:"withdraw",kind:"steering"===e?"steer":"followUp",text:t}),tl(r=>{let n=r[e].indexOf(t);return(n<0&&""===t.trim()&&(n=r[e].indexOf("[Image]")),n<0)?r:{...r,[e]:r[e].filter((e,t)=>t!==n)}})}catch(e){console.error("Failed to remove queued message:",e),r$({type:"error",message:"Failed to remove queued message"})}},[r$]),r7=(0,i.useCallback)(async(e,t=null)=>{let r="auto"===e?t:null,n=r!==ec;el(e),eu(r),f&&(!tj.current||t7.current===tj.current)&&(t5.current=e,t3.current=r),ed(void 0);let i=tj.current??await tQ.current;if(i)try{t7.current===i?await ry():n&&await sz(i,{type:"set_thinking_ceiling",ceiling:r}),await sz(i,{type:"set_thinking_level",level:e}),await rm(i)}catch(e){console.error("Failed to set thinking level:",e),r$({type:"error",message:"Failed to set thinking level"}),await rm(i)}},[f,rm,r$,ec,ry]);ev.current=ro?`${ro.provider}/${ro.modelId}`:"";let r9=e=>e?`${e}|${ev.current}`:null,ne=t?.id??tj.current,nt=r9(ne),nr=ep&&ep.key===nt?ep.value:null;(0,i.useEffect)(()=>{let e=++eg.current;nt&&ne&&!E&&!eE&&fetch(`/api/agent/${encodeURIComponent(ne)}`).then(e=>e.json()).then(t=>{eg.current===e&&r9(tj.current)===nt&&eh({key:nt,value:(t.running?sX(t.state):void 0)??null})}).catch(()=>{})},[nt,E,eE]);let nn=(0,i.useCallback)(async()=>{let e=tj.current??await ry(),t=r9(tj.current);if(!e||!t)return;let r=++eg.current,n=()=>eg.current===r&&r9(tj.current)===t,i=e=>{n()&&eh({key:t,value:e})};em(!0);try{let r=ep?.key===t?ep.value?.enabled:void 0;if(void 0===r){let t=sX(await sz(e,{type:"get_state"}));if(!t)throw Error("Could not read the session's Fast state");r=t.enabled}if(!n())return;let a=await sz(e,{type:"set_fast_mode",enabled:!r});i({enabled:a?.enabled===!0,active:a?.active===!0})}catch(t){if(!n())return;r$({type:"error",message:t instanceof Error?t.message:String(t)});try{i(sX(await sz(e,{type:"get_state"}))??null)}catch{i(null)}}finally{em(!1)}},[ry,ep,r$]),ni=(0,i.useCallback)(async e=>{let t=(0,aQ.xG)(e);rs(e);let r=tj.current??await tQ.current;if(r)try{await sz(r,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[rs]),na=(0,i.useCallback)(e=>{tO.current=e,tU(t=>!e===t?t:!e)},[]);tY.current=na;let ns=(0,i.useCallback)((e="smooth")=>{tG.current=Date.now()+700,tZ.current?.scrollIntoView({behavior:e})},[]),nl=(0,i.useCallback)(()=>{tJ.current=0,na(!0),ns("smooth")},[ns,na]),nd=(0,i.useCallback)(()=>{tJ.current=0,na(!1)},[na]),nc=(0,i.useCallback)(e=>{e instanceof KeyboardEvent&&(!s4.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tJ.current=Date.now()+1200)},[]),nu=(0,i.useCallback)(()=>{if(!tT.current&&!tP.current)return;let e=tX.current;if(!e)return;let t=Date.now()<=tJ.current;!t&&Date.now()<tG.current||(e.scrollHeight-e.scrollTop-e.clientHeight<=72?na(!0):t&&na(!1))},[na]);return(0,i.useEffect)(()=>(tj.current=t?.id??null,tI.current.sessionId!==tj.current&&(tI.current={sessionId:tj.current,outputs:[],seq:0}),t&&rm(t.id,!m,!0,m).then(e=>{if(tj.current!==t.id)return;rC(t.id),e?.running&&(rv(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(tM.current=!!e.state.isStreaming,t$.current=!!e.state.isPromptRunning,tT.current=!0,L(!0),eY(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),R({type:"start"}),rN(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&rD(t.id)),e.state?.isBashRunning&&(tP.current=!0,A(!0),rH(t.id)),(e.state?.subagents?.length??0)>0&&rN(t.id));let r=e?.state;r&&(void 0!==r.isCompacting&&eA(r.isCompacting),eH(sQ(r)),void 0!==r.contextUsage&&ek(r.contextUsage??null),void 0!==r.systemPrompt&&eC(r.systemPrompt??null),void 0!==r.thinkingLevel&&(t8.current=t.id,el(r.configuredThinkingLevel??r.thinkingLevel),ed(r.thinkingLevel)),void 0!==r.thinkingCeiling&&eu(r.thinkingCeiling??null),void 0!==r.extensionStatuses&&tn(r.extensionStatuses??[]),void 0!==r.extensionWidgets&&ta(r.extensionWidgets??[]),void 0!==r.queuedMessages&&tl(sZ(r.queuedMessages)),void 0!==r.subagents&&td(e=>sG(e,r.subagents??[])),void 0!==r.goal&&tK(r.goal??null)),e&&eq(!0)}),()=>{tW.current+=1,rk(),rj(),rS()}),[t?.id]),(0,i.useEffect)(()=>{p?.(eS)},[eS,p]),(0,i.useEffect)(()=>{u&&u(g?.tree??[],k,rG)},[g?.tree,k,rG,u]),(0,i.useEffect)(()=>(window.addEventListener("keydown",nc),()=>{window.removeEventListener("keydown",nc)}),[nc]),(0,i.useEffect)(()=>{let e=tX.current;if(e)return e.addEventListener("pointerdown",nc,{passive:!0}),e.addEventListener("wheel",nc,{passive:!0}),e.addEventListener("touchstart",nc,{passive:!0}),e.addEventListener("scroll",nu,{passive:!0}),()=>{e.removeEventListener("pointerdown",nc),e.removeEventListener("wheel",nc),e.removeEventListener("touchstart",nc),e.removeEventListener("scroll",nu)}},[S.length,v,nu,nc]),(0,i.useEffect)(()=>{if(t9.current||!E&&!z||!tO.current)return;let e=tX.current;if(!e)return;let t=requestAnimationFrame(()=>{tG.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"})});return()=>cancelAnimationFrame(t)},[E,z,S.length,$.streamingMessage,eK,P,e.transitioning]),(0,i.useLayoutEffect)(()=>{if(0!==S.length){if(!tH.current){tH.current=!0,ns("instant");return}if(!t9.current&&tO.current){let e=Date.now()-re.current<1500;ns(tT.current||tP.current||e?"instant":"smooth")}}},[S.length,E,z,ns,e.transitioning]),(0,i.useEffect)(()=>{let e=new AbortController;return r0(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[r0,c]),(0,i.useEffect)(()=>{if(!eF)return;let e=setTimeout(()=>e_(null),6e3);return()=>clearTimeout(e)},[eF]),(0,i.useEffect)(()=>{if(0===e1.visible.length)return;let e=e1.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{e2({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!e1.visible[0])return;let t=setTimeout(()=>{e2({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[e1.visible]),(0,i.useEffect)(()=>{e5(null)},[S.length,ew?.tokens,ew?.percent,ew?.contextWindow]),{data:g,loading:v,error:y,activeLeafId:k,messages:S,entryIds:N,streamState:$,agentRunning:E,modelNames:F,modelList:D,modelError:O,modelScopeWarnings:U,modelThinkingLevels:K,modelThinkingLevelMaps:J,modelRoles:Y,newSessionModel:X,toolPreset:ei,thinkingLevel:es,effectiveThinkingLevel:eo,thinkingCeiling:ec,retryInfo:eb,contextUsage:ew,systemPrompt:eS,forkingEntryId:eN,isCompacting:ez,compaction:eD,compactError:eP,compactResult:eF,currentModel:rl,displayModel:ro,modelSwitching:eE,sessionStats:rd,runStateKnown:eB,slashCommands:eZ,slashCommandsLoading:eQ,queuedMessages:ts,deliveryRows:th,subagents:to,todoPhases:tf&&tf.sid===tj.current?tf.phases:null,compactedWork:T,notices:e1.visible,extensionDialog:e8,extensionResponse:e3,extensionCustomUi:te,extensionStatuses:tr,extensionWidgets:ti,respondToExtensionUi:rT,sendExtensionCustomInput:rM,isAutoModelSelection:f&&null===X,agentPhase:eK,isNew:f,autoFollowPaused:tB,resumeAutoFollow:nl,pauseAutoFollow:nd,goalStatus:tq,sessionIdRef:tj,eventSourceRef:tg,messagesEndRef:tZ,scrollContainerRef:tX,handleSend:rq,handleAbort:rK,handleFork:rV,handleNavigate:rJ,handleModelChange:rY,handleRoleModelChange:rX,handleMainPresetChange:rZ,newSessionAccount:ee,handleCompact:rQ,handleSteer:r2,handleFollowUp:r5,handlePromptWithStreamingBehavior:r4,handleAbortCompaction:r8,handleRecallQueue:r6,handleRemoveQueuedMessage:r3,handleBuiltinSlashCommand:r1,handleToolPresetChange:ni,handleThinkingLevelChange:r7,fastMode:nr,fastModeBusy:ef,handleFastModeToggle:nn,loadTools:rv,loadSlashCommands:rw,ensureNewSession:ry,refreshLiveTranscript:rg,setActiveLeafId:j,setData:x,setMessages:C,dispatch:R,setAgentRunning:L,setForkingEntryId:eI,bashRunning:z,pendingBash:P,handleAgentEventRef:tF}}({session:e,newSessionCwd:t,initialData:a,transitioning:s,onAgentEnd:ex,onAttentionNeeded:o,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:f,onSessionStatsPanelOpen:g}),tV=rc(e?.id,e7?.provider,void 0),tJ=tV?.alias;(0,i.useEffect)(()=>{tJ&&Z.current?.(tJ)},[tJ]);let tG=(0,i.useMemo)(()=>{if(!e7)return null;let e=tv?tL:t3.bo.find(e=>e.alias===tV?.alias)?.oauthPosition;return t3.bo.find(t=>t.provider===e7.provider&&(void 0===t.oauthPosition||t.oauthPosition===e))?.alias??null},[e7,tv,tL,tV]),tY=e7?.provider,tZ=e7?.modelId,tX=tV?.alias,tQ=tV?.seed,t0=(0,i.useRef)(tV);t0.current=tV,(0,i.useEffect)(()=>{y&&y(tY&&tZ?{provider:tY,modelId:tZ,face:t0.current,presetAlias:tG,isNew:tv}:null)},[y,tY,tZ,tX,tQ,tG,tv]),(0,i.useEffect)(()=>()=>{y?.(null)},[y]);let t1=eC||eN,t2=e?.id;er.current=ew,en.current=ek,ei.current=tj;let t4=(0,i.useRef)(!0);t4.current=!tb;let t5=(0,i.useRef)(!1);(0,i.useEffect)(()=>{eC&&!t5.current&&(ea.current+=1),t5.current=eC},[eC]),(0,i.useEffect)(()=>()=>{ea.current+=1},[]),(0,i.useEffect)(()=>{Q(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(lx(e))??"[]");if(!Array.isArray(t))return[];return t.filter(e=>e&&"string"==typeof e.anchorEntryId).map(t=>({..."string"==typeof t.sticker?{...t,sticker:t.sticker.replace(/^(\/stickers\/.+)\.png$/,"$1.webp")}:t,sessionId:e}))}catch{return[]}}(t2),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===t2)])},[t2]),(0,i.useEffect)(()=>{let e=tj.current;e&&ee.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&Q(t=>{let r=!1,n=[];for(let i of t){if(null!==i.anchorEntryId||!i.intent||i.sessionId!==e){n.push(i);continue}let a=function(e,t,r){let n=Math.min(t.length,r.length),i=0;if(null!==e.baseEntryId){let t=r.indexOf(e.baseEntryId);if(-1===t||t>=n)return{kind:"drop"};i=t+1}let a=0;for(let s=i;s<n;s++)if(iN(t[s])===e.identity&&(a+=1)===e.occurrence)return{kind:"entry",entryId:r[s]};return null}(i.intent,ew,ek);if(null===a){n.push(i);continue}r=!0,"drop"!==a.kind&&("working"===i.tag&&[...t,...n].some(e=>"working"===e.tag&&e.anchorEntryId===a.entryId)||n.push({id:i.id,anchorEntryId:a.entryId,sticker:i.sticker,text:i.text,tag:i.tag,sessionId:i.sessionId}))}return r?(lv(e,n),n):t})},[ew,ek,tj]);let t7=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tj.current,t=t7.current;if(t7.current=e?{sessionId:e,entryIds:ek}:null,!e||!t||t.sessionId!==e)return;let r=function(e,t,r){if(0===e.length||t.length<=e.length)return[];for(let r=0;r<e.length;r++)if(e[r]!==t[r])return[];let n=[],i=Math.min(r.length,t.length);for(let a=e.length;a<i;a++){let e=r[a];"assistant"===e.role&&"web6"===e.provider&&"ChatGPT 6PRO"===e.model&&n.push(t[a])}return n}(t.entryIds,ek,ew),n=eo();if(0===r.length||!n)return;let i=ro(e,"web6",void 0)?.alias??null;for(let e of r)ee.current.some(t=>t.anchorEntryId===e)||eu(i,"done",n,{kind:"entry",entryId:e})},[ek,ew,tj,eo,eu]);let t9=eC&&tx?.kind==="running_tools"&&tx.tools.length>0&&tx.tools.every(e=>"wait"===e.name),re=eb||s,{hideThinkingBlock:rt}=(_=t??e?.cwd??null,H=t6(),(0,i.useEffect)(()=>{t8(_).catch(()=>{})},[_]),H),rr=(0,i.useMemo)(()=>({hideThinking:rt}),[rt]);(0,i.useEffect)(()=>{if(!td||Y.current===td.id)return;Y.current=td.id;let e=eo();if(e){var t;el.current=e.turn,eh("select"===(t=td.method)||"ask"===t?"choice":"approval",e,e7?.provider,void 0)}},[td,e7?.provider,eo,eh]),(0,i.useEffect)(()=>(v=t1?tI:null,()=>void(v=null)),[t1,tI]),(0,i.useEffect)(()=>{N?.(t1)},[N,t1]),(0,i.useEffect)(()=>()=>N?.(!1),[N]),(0,i.useEffect)(()=>{I?.(t9)},[t9,I]),(0,i.useEffect)(()=>()=>I?.(!1),[I]),(0,i.useEffect)(()=>{T?.(null!==td)},[T,td]),(0,i.useEffect)(()=>()=>T?.(!1),[T]);let{main:rn,process:ri}=(0,i.useMemo)(()=>(function(e,t,r={}){let n=[],i=[],a=-1,s=null,l=(e,t,r)=>{if(0===t.length)return;let a=(s&&s.anchorIdx===e||(s={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},i.push(s)),s),l=n.length-1;for(let e of t)a.entries.push({...e,afterMainIndex:l});a.messageCount+=t.length,a.toolCallCount+=r},o=eH(e),d=new Map,c=(e,t)=>{let r=d.get(e)??0;d.set(e,r+1),n.push({kind:"answer",anchorIdx:a,idx:e,runIndex:r,blocks:o.attach(t),precedingBlocks:[]})},u=()=>{let e=o.takeRemaining();e&&c(e.idx,e.blocks)};for(let i of t){if("answer"===i.kind){n.push(i);continue}if("process"===i.kind){l(i.anchorIdx,i.entries,i.toolCallCount);continue}let t=e[i.idx];if(!t)continue;if("user"===t.role){u(),a=i.idx,n.push(i);continue}if(eK(t)){n.push(void 0!==i.anchorIdx||a<0?i:{...i,anchorIdx:a});continue}if("assistant"!==t.role){"toolResult"!==t.role&&l(a,[{idx:i.idx}],0);continue}let s=eF(t,r),d=!1;for(let e of s){if("answer"===e.kind){c(i.idx,e.blocks),d=!0;continue}l(a,[{idx:i.idx,blocks:e.blocks}],e_(e.blocks)),o.collect(i.idx,e.blocks)}!d&&eW(t,r)&&c(i.idx,[])}return u(),{main:n,process:i}})(ew,function(e,t={}){let r=-1;for(let t=e.length-1;t>=0;t--)if(eY(e[t])){r=t;break}let n=[];for(let i=0;i<e.length;){if(!eY(e[i])){n.push({kind:"message",idx:i}),i+=1;continue}let a=i,s=a+1;for(;s<e.length&&!eY(e[s]);)s+=1;if((t.sessionBusy||t.isStreaming)&&s===e.length&&a===r||!function(e,t,r){for(let n=t;n<r;n++)if(e[n]?.role==="assistant")return!0;return!1}(e,a+1,s)){for(let e=a;e<s;e++)n.push({kind:"message",idx:e});i=s;continue}for(let r of(n.push({kind:"message",idx:a}),function(e,t,r,n){let i=[],a=[],s=0,l=[],o=0,d=0,c=eH(e.slice(t+1,r)),u=()=>{0!==a.length&&(i.push({kind:"process",anchorIdx:t,idx:a[0].idx,groupIndex:d++,entries:a,messageCount:a.length,toolCallCount:s,turnHasAnswer:!1}),a=[],s=0)},p=(e,r)=>{u(),i.push({kind:"answer",anchorIdx:t,idx:e,runIndex:o++,blocks:c.attach(r),precedingBlocks:l}),l=[]};for(let o=t+1;o<r;o++){let r=e[o];if("assistant"!==r.role){if(eK(r)){u(),i.push({kind:"message",idx:o,anchorIdx:t});continue}"toolResult"!==r.role&&a.push({idx:o});continue}let d=eF(r,n),h=d.reduce((e,t)=>"answer"===t.kind?e+1:e,0);for(let e of d){if("answer"===e.kind){p(o,e.blocks);continue}for(let t of(a.push(h>0?{idx:o,blocks:e.blocks}:{idx:o}),s+=e_(e.blocks),c.collect(o,e.blocks),e.blocks))l.push(t)}0===h&&eW(r,n)&&p(o,[])}u();let h=c.takeRemaining();h&&i.push({kind:"answer",anchorIdx:t,idx:h.idx,runIndex:o++,blocks:h.blocks,precedingBlocks:[]});let f=i.some(e=>"answer"===e.kind);for(let e of i)"process"===e.kind&&(e.turnHasAnswer=f);return i}(e,a,s,{hideThinking:t.hideThinking})))n.push(r);i=s}return n}(ew,{sessionBusy:t1,isStreaming:eS.isStreaming,hideThinking:rr.hideThinking}),rr),[ew,t1,eS.isStreaming,rr]),ra=(0,i.useMemo)(()=>(function(e,t,r=[]){let n=new Map,i=e.map((e,t)=>({item:e,position:t})).filter(e=>"answer"===e.item.kind);if(0===i.length)return n;let a=-1,s=-1;t.forEach((e,t)=>{let r=rP(e);if(r.length>0){let e=i.filter(e=>e.item.anchorIdx===a||e.item.anchorIdx===s),l=e.filter(e=>e.item.idx<=t).pop(),o=l??e.find(e=>e.item.idx>t);if(o){let e=n.get(o.position);e?e.calls.push(...r):n.set(o.position,{calls:[...r],placement:l?"after":"before"})}}"user"===e.role&&(a=t),eY(e)&&(s=t)});let{continuing:l}=rW(e,t,r);if(l){let e=n.get(l.position);e?e.calls.unshift(...l.calls):n.set(l.position,{calls:l.calls,placement:"before"})}return n})(rn,ew,tr?.messages),[rn,ew,tr]),rs=(0,i.useMemo)(()=>(function(e,t,r=[]){let{atCompaction:n}=rW(e,t,r);if(0===n.length)return null;let i=-1;t.forEach((e,t)=>{"custom"===e.role&&"compaction"===e.customType&&(i=t)});let a=e.findIndex(e=>e.idx>i),s=-1===a?e.length:a;return{position:s,jumpTo:s<e.length?s:e.length>0?e.length-1:null,calls:n}})(rn,ew,tr?.messages),[rn,ew,tr]),[rl,ru]=(0,i.useState)(lp),{startIndex:rp,endIndex:rh,hasLater:rf}=lh(rn.length,rl),rm=null!==rl.end&&rf,rg=(0,i.useRef)(rn.length);rg.current=rn.length;let rx=(0,i.useRef)(null),rv=(0,i.useRef)(null),rb=(0,i.useRef)(null);(0,i.useEffect)(()=>{null!==rl.end&&rl.end>=rn.length&&ru(e=>({count:e.count,end:null}))},[rl.end,rn.length]),(0,i.useEffect)(()=>{let e=rx.current,t=tC.current;if(!e||!t)return;let r=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(rb.current=t.scrollHeight-t.scrollTop,ru(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return r.observe(e),()=>r.disconnect()},[rl,rn.length,tC]),(0,i.useEffect)(()=>{if(null==rb.current)return;let e=tC.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-rb.current),rb.current=null}},[rl.count,tC]),(0,i.useEffect)(()=>{let e=rv.current,t=tC.current;if(!e||!t)return;let r=new IntersectionObserver(e=>{e[0]?.isIntersecting&&ru(e=>(function(e,t,r=50){if(null===t.end)return t;let{startIndex:n,endIndex:i}=lh(e,t),a=i+r;return a>=e?{count:e-n,end:null}:{count:a-n,end:a}})(rg.current,e))},{root:t,threshold:0});return r.observe(e),()=>r.disconnect()},[rl,rn.length,tC]);let[ry,rw]=(0,i.useState)(null),[rk,rj]=(0,i.useState)(null),[rS,rC]=(0,i.useState)(0),rN=(0,i.useRef)(null),rz=(0,i.useCallback)((e,t=null)=>{tw(),rN.current={item:e,dispatchKey:t},rw(null),rj(null),ru(t=>lf(rg.current,e,t)),rC(e=>e+1)},[tw]);(0,i.useLayoutEffect)(()=>{let e,t=rN.current,r=tC.current;if(null===t||!r)return;let n=r.querySelector(`[data-chat-item="${t.item}"]`);if(!n)return;rN.current=null;let i=t.dispatchKey?n.querySelector(".answer-dispatch"):null;if(i)e=i.getBoundingClientRect().top;else{let t=document.createRange();t.selectNodeContents(n),e=t.getBoundingClientRect().top}r.scrollTop+=e-r.getBoundingClientRect().top-24,i&&t.dispatchKey?rj(t.dispatchKey):rw(t.item)},[rS,rl,rn,tC]),(0,i.useEffect)(()=>{if(null===ry)return;let e=setTimeout(()=>rw(null),1800);return()=>clearTimeout(e)},[ry]),(0,i.useEffect)(()=>{if(null===rk)return;let e=setTimeout(()=>rj(null),1800);return()=>clearTimeout(e)},[rk]);let rD=(0,i.useCallback)(()=>{(0,F.flushSync)(()=>ru(lp));let e=tC.current;e&&(e.scrollTop=e.scrollHeight)},[tC]),rH=(0,i.useCallback)(()=>{rm&&rD(),ty()},[rm,rD,ty]),rO=(0,i.useRef)(null),[rB,rU]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!A||rO.current===A.id||A.sessionId!==e?.id||eb||0===ew.length)return;rO.current=A.id,P?.(A.id);let t=ek.indexOf(A.entryId);if(t<0)return void rU(!0);let r=0;for(let e=0;e<rn.length;e++){let n=rn[e].idx;if(n>t||(r=e,n===t))break}rz(r)},[A,e?.id,eb,ew.length,ek,rn,rz,P]),(0,i.useEffect)(()=>{if(!rB)return;let e=setTimeout(()=>rU(!1),6e3);return()=>clearTimeout(e)},[rB]);let[rq,rK]=(0,i.useState)(!1),[rV,rJ]=(0,i.useState)(0),rG=(0,i.useMemo)(()=>rq?rn.map(e=>(function(e,t){if("answer"===e.kind)return eQ(e.blocks);let r=t[e.idx];return r&&"content"in r?eQ(r.content):""})(e,ew).toLowerCase()):lb,[rq,rn,ew]),rY=(0,i.useCallback)(e=>{tw(),ru(t=>lf(rg.current,e,t))},[tw]),rZ=(0,i.useCallback)(()=>rK(!1),[]);(0,i.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.shiftKey||!(e.ctrlKey||e.metaKey)||"f"!==e.key.toLowerCase())return;let t=tC.current;if(!t||!t.checkVisibility({visibilityProperty:!0}))return;let r=e.target instanceof Element?e.target:null;if(r?.closest("[data-capture-keys], [role='dialog']"))return;let n=r?.closest("input, textarea, select, [contenteditable='true']");(!n||n.closest("[data-chat-composer], .chat-find-bar"))&&(e.preventDefault(),rK(!0),rJ(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tC]);let rX=(0,i.useMemo)(()=>{let e=[];return rn.forEach((t,r)=>{if("message"!==t.kind)return;let n=lg(ew[t.idx]);null!==n&&e.push({item:r,text:n})}),e},[rn,ew]),rQ=`${rp}:${rh}`,r0=ek.length>0?ek[ek.length-1]:null,[r1,r2]=(0,i.useState)(null),r4=(0,i.useRef)(!1);(0,i.useEffect)(()=>{r4.current||!tt||eb||!e?.id||(r4.current=!0,t1||!r0||!function(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if("user"===r.role||"toolResult"===r.role)return!0;if("assistant"===r.role){if(!r.stopReason)return!0;if("aborted"===r.stopReason||"error"===r.stopReason||"length"===r.stopReason)break;return r.content.some(e=>"toolCall"===e.type)}}return!1}(ew)||function(e){try{return window.localStorage.getItem(ly(e))}catch{return null}}(e.id)!==r0&&r2(r0))},[tt,eb,e?.id,t1,r0,ew]);let r5=(0,i.useCallback)(()=>{e?.id&&r1&&function(e,t){try{window.localStorage.setItem(ly(e),t)}catch{}}(e.id,r1),r2(null)},[e?.id,r1]),r8=null!==r1&&r1===r0&&!t1&&!rm,r6=te?[te.sessionId,te.sessionFile??"",te.sessionName??"",te.userMessages,te.assistantMessages,te.toolCalls,te.toolResults,te.totalMessages,te.tokens.input,te.tokens.output,te.tokens.cacheRead,te.tokens.cacheWrite,te.tokens.total,te.cost??0,te.totalActiveMs??0].join("|"):null,r3=(0,i.useRef)(te);r3.current=te,(0,i.useEffect)(()=>{m?.(r3.current)},[r6,m]),(0,i.useEffect)(()=>()=>{m?.(null)},[m]);let r7=e1?`${e1.percent??"null"}|${e1.contextWindow}|${e1.tokens??"null"}`:null,r9=(0,i.useRef)(e1);r9.current=e1,(0,i.useEffect)(()=>{x?.(r9.current)},[r7,x]),(0,i.useEffect)(()=>()=>{x?.(null)},[x]),(0,i.useEffect)(()=>{b?.(ts)},[b,ts]),(0,i.useEffect)(()=>()=>{b?.([])},[b]);let{isDragOver:ne,handleDragEnter:nt,handleDragOver:nr,handleDragLeave:nn,handleDrop:ni}=function(e){let[t,r]=(0,i.useState)(!1),n=(0,i.useRef)(0),a=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),n.current+=1,r(!0))},[]),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:a,handleDragOver:s,handleDragLeave:(0,i.useCallback)(()=>{n.current-=1,n.current<=0&&(n.current=0,r(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),n.current=0,r(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{t1||p?.current?.addAttachments(e)},[t1,p])),na=(0,i.useMemo)(()=>{var e;return e=tr?.messages,e&&e.length>0?[...e,...ew]:ew},[tr,ew]),ns=(0,i.useMemo)(()=>{let e=new Map;for(let t of na)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[na]),nl=(0,i.useMemo)(()=>{let e,t,r,n;return e=new Map,t=new Map,r=new Map,n=(e,n,i)=>{let a=r.get(e);a&&n&&t.set(a,{status:n,order:i})},na.forEach((t,i)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=ns.get(e.toolCallId);if(t)for(let n of rR(e,t)??[])r.set(n.agentId,n.key)}return}if("toolResult"===t.role){if("routing_verdict"===t.toolName){let r=function(e){let t=function(e){if(e.isError)return null;let t=e.details?.record;if("object"!=typeof t||null===t)try{let r=JSON.parse(r$(e.content));t=r?.ok===!0?r.record:void 0}catch{return null}return"object"==typeof t&&null!==t?t:null}(e);if(!t)return null;let r=t.verdict;if("accepted"!==r&&"rework"!==r&&"held"!==r)return null;let n=rT(t.assignmentId),i=n?.split("#")??[];if(i.length<3)return null;let a=i[i.length-1],s=i.slice(1,-1).join("#");return/^\d+$/.test(a)&&s?{key:`${s}#${a}`,record:{verdict:r,attempt:"number"==typeof t.attempt?t.attempt:null,reason:rT(t.reason)}}:null}(t);if(!r)return;let n=e.get(r.key)??[];n.push({...r.record,order:i}),e.set(r.key,n);return}if("wait"===t.toolName)for(let e of rI(t.details?.jobs)){if("task"!==e.type)continue;let t=rT(e.id);t&&n(t,rM(e.status),i)}return}if("custom"===t.role&&"async-result"===t.customType)for(let e of r$(t.content).matchAll(rE)){let t=Object.fromEntries([...e[1].matchAll(rL)].map(e=>[e[1],e[2]]));t.id&&n(t.id,rM(t.status),i)}}),{verdicts:e,runs:t,latestByAgent:r}},[na,ns]),nd=(0,i.useMemo)(()=>({ledger:nl,subagents:ts,toolResults:ns,onOpenPanel:w,focusedDispatch:rk,sessionId:e?.id??null}),[nl,ts,ns,w,rk,e?.id]),nc=(0,i.useMemo)(()=>(function(e,t,r,n,i,a,s=null){let l=-1;e.forEach((e,t)=>{"user"===e.role&&(l=t)});let o=new Map;for(let[e,t]of r)for(let r of t.calls)o.set(r.toolCallId,e);if(s?.jumpTo!=null)for(let e of s.calls)o.set(e.toolCallId,s.jumpTo);let d=[];if(e.forEach((e,r)=>{if("assistant"!==e.role)return;let s=r>l;for(let r of e.content??[])if("toolCall"===r.type&&"task"===r.toolName)for(let e of rR(r,t.get(r.toolCallId))??[]){let t=rA(e,n,i),l=rF[t.run],c=null;"running"===l&&("live"===t.runSource||s&&a)?c="running":"awaiting"===l&&s&&!t.verdict&&(c="awaiting"),c&&d.push({maker:t,phase:c,position:o.get(r.toolCallId)??null})}}),0===d.length)return null;let c=0;for(let e of d)"running"===e.phase&&(c+=1);let u=d.filter(e=>null!==e.position);return{running:c,awaiting:d.length-c,target:u.length>0?u[u.length-1]:d[d.length-1]}})(na,ns,ra,ts,nl,t1,rs),[na,ns,ra,ts,nl,t1,rs]),nu=(0,i.useMemo)(()=>w?()=>w("subagents"):void 0,[w]),np=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let r=ew.length-1;r>=0;r-=1){let n=lg(ew[r]);if(!(!n||e.has(n))&&(e.add(n),t.push(n),t.length>=50))break}return t.reverse()},[ew]),nh=(0,i.useMemo)(()=>e3(ew,ns,tl,tr?.todoPhases??null),[ew,ns,tl,tr]),nf=(0,i.useMemo)(()=>iW(eS.streamingMessage).join("|"),[eS.streamingMessage]),nm=(0,i.useMemo)(()=>JSON.stringify(iP(eS.streamingMessage)),[eS.streamingMessage]),ng=(0,i.useMemo)(()=>JSON.stringify(i_(eS.streamingMessage)),[eS.streamingMessage]),nx=(0,i.useMemo)(()=>(function(e,t,r=[],n=[],i=[]){let a=function(e){let t=new Map;for(let r of e){if("toolResult"!==r.role||"write"!==r.toolName)continue;let e=r.details;if(!e||"object"!=typeof e||Array.isArray(e))continue;let n=e.message;if(!n||"object"!=typeof n||Array.isArray(n)||"send"!==n.op)continue;let i=Array.isArray(n.receipts)?n.receipts.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)).map(e=>({to:"string"==typeof e.to?e.to:void 0,outcome:"string"==typeof e.outcome?e.outcome:void 0})):void 0;t.set(r.toolCallId,{from:"string"==typeof n.from?n.from:void 0,receipts:i})}return t}(e),s=[],l=new Map,o=-1;for(let r=0;r<e.length;r+=1){let n=e[r];if("user"===n.role){o=r;continue}let i=iW(n),d=i_(n,a);if(0===i.length&&0===d.length||o<0)continue;let c=iP(n),u=l.get(o);u||(u={index:o,entryId:t[o],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(o,u),s.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...i],u.characterSummons=[...u.characterSummons,...c],u.peerSends=[...u.peerSends,...d]}if(r.length>0||i.length>0){let a=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){a=t;break}if(a>=0){let e=l.get(a);e||(e={index:a,entryId:t[a],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(a,e),s.push(e));let o=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...r.filter(e=>!o.has(e))];let d=new Set(e.characterSummons.map(e=>`${e.toolCallId} ${e.name??""}`));e.characterSummons=[...e.characterSummons,...n.filter(e=>!d.has(`${e.toolCallId} ${e.name??""}`))];let c=new Set(e.peerSends.map(e=>e.toolCallId));e.peerSends=[...e.peerSends,...i.filter(e=>!c.has(e.toolCallId))]}}return s.sort((e,t)=>e.index-t.index)})(ew,ek,nf.length>0?nf.split("|"):[],JSON.parse(nm),JSON.parse(ng)),[ew,ek,nf,nm,ng]),nv=e?.id??tj.current??void 0,nb=(O=iH(D=(0,i.useMemo)(()=>({sessionId:nv,sessionProvider:e7?.provider,turns:nx,messages:ew,subagents:ts}),[nv,e7?.provider,nx,ew,ts])),B=iq(D),(0,i.useMemo)(()=>(function(e){let t=new Map;for(let r of e){let e=t.get(r.turnIndex);e?e.push(r):t.set(r.turnIndex,[r])}return t})(function(e){let t=[];for(let r of e){let e=t[t.length-1];if(e&&e.speakerId===r.speakerId&&e.turnIndex===r.turnIndex&&e.text===r.text){t[t.length-1]=r;continue}t.push(r)}return t}([...O,...B])),[O,B])),ny=tv&&0===ew.length&&!eS.isStreaming&&!t1,nw=e?.cwd??t??void 0,nk=e7?eE[`${e7.provider}:${e7.modelId}`]??null:null,nj=e7?eL[`${e7.provider}:${e7.modelId}`]??null:null,nS=(0,i.useRef)(null),nC=(0,i.useRef)(null),nN=(0,i.useCallback)(()=>{nS.current?.querySelector("textarea")?.focus({preventScroll:!0})},[]);(0,i.useEffect)(()=>(C?.(nN),()=>C?.(null)),[nN,C]),(0,i.useLayoutEffect)(()=>{let e=nC.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let r=tC.current?.clientHeight??0,n=()=>{let n=Math.ceil(e.getBoundingClientRect().height);n>0&&t.style.setProperty("--omp-dock-h",`${n}px`);let i=tC.current;if(!i)return;let a=r-i.clientHeight;r=i.clientHeight,a<=0||i.scrollHeight-i.scrollTop-i.clientHeight-a<=1&&(i.scrollTop+=a)};n();let i=new ResizeObserver(n);return i.observe(e),()=>i.disconnect()},[eb,tC]);let nI=(0,i.useCallback)((...e)=>(null!==rl.end&&rD(),tN(...e)),[tN,rl.end,rD]),nT=(0,n.jsx)("div",{ref:nS,"data-chat-composer":"",style:{display:"contents"},children:(0,n.jsx)(sN,{ref:p,sessionId:e?.id??tj.current??void 0,onEnsureSession:tv&&t?tq:void 0,onLiveTranscriptPersisted:tK,onSend:nI,onAbort:tI,onSteer:eC?tA:void 0,onFollowUp:eC?tP:void 0,onPromptWithStreamingBehavior:eC?tW:void 0,isStreaming:t1,model:e7,isAutoModelSelection:tg,modelNames:eT,modelList:eM,modelError:e$,modelScopeWarnings:eR,onModelChange:t$,onMainPresetChange:e||tv?tE:void 0,mainPresetActiveAlias:tG,modelRoles:ez,onRoleModelChange:tR,modelSwitching:e9,onCompact:e||tv?tz:void 0,onAbortCompaction:tF,isCompacting:e4,compactError:e8,compactResult:e6,toolPreset:eP,onToolPresetChange:e||tv?tO:void 0,thinkingLevel:eD,effectiveThinkingLevel:eO,thinkingCeiling:eB,onThinkingLevelChange:e||tv?tB:void 0,fastMode:eq,fastModeBusy:eZ,onFastModeToggle:e||tv?eX:void 0,availableThinkingLevels:nk,thinkingLevelMap:nj,retryInfo:e0,deliveryRows:ta,inputHistory:np,onRecallQueue:t_,onRemoveQueuedMessage:tD,slashCommands:tn,slashCommandsLoading:ti,onLoadSlashCommands:tU,onBuiltinCommand:tH,soundEnabled:M,onSoundToggle:$,onAudioUnlock:z,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t})}),nM=eS.streamingMessage,n$=(0,i.useMemo)(()=>nM?eF(nM,{isStreaming:!0}):[],[nM]),nR=(0,i.useMemo)(()=>n$.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[n$]),nE=(0,i.useMemo)(()=>n$.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[n$]),nz=nM?.role==="assistant"?nM:null,nA=eC&&(tx?.kind==="running_tools"||(nz?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),nP=nz?.provider??e7?.provider,nW=nz?.credentialId;(0,i.useEffect)(()=>{if(!nA)return;let e=eo();e&&es.current!==e.turn&&el.current!==e.turn&&(es.current=e.turn,eh("working",e,nP,nW))},[nA,nP,nW,eo,eh]);let[nF,n_]=(0,i.useState)(null),nD=(0,i.useCallback)(e=>{n_(e)},[]),nH=(0,i.useMemo)(()=>eI?{role:"bashExecution",command:eI.command,output:"",excludeFromContext:eI.excludeFromContext}:null,[eI]),nO=(0,i.useMemo)(()=>{let e=[eC&&!nM&&tx?function(e,t){if(e?.kind==="running_tools"){let r=e.tools.map(e=>e.name);return 0===r.length?t("chat.runningTool"):1===r.length?t("chat.runningNamedTool",{name:r[0]}):r.length<=3?t("chat.runningTools",{names:r.join(", ")}):t("chat.runningToolsMore",{names:r.slice(0,2).join(", "),count:r.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(tx,U):null,eN&&!eI?U("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[eC,nM,tx,eN,eI,U]);(0,i.useEffect)(()=>{if(!nF)return void k?.(null);let e=[],t=[],r=0;if(nM&&nE.length>0){let n=nF.messages.length+e.length;for(let i of(e.push(nM),nE))t.push({idx:n,blocks:i}),r+=e_(i)}if(nH&&(t.push({idx:nF.messages.length+e.length}),e.push(nH)),0===t.length)return void k?.(nO?{...nF,status:nO}:nF);let n=-1;for(let e=nF.messages.length-1;e>=0;e--)if(eY(nF.messages[e])){n=e;break}let i=nF.groups.slice(),a=i.length>0?i[i.length-1]:void 0;a&&a.anchorIdx===n?i[i.length-1]={...a,entries:[...a.entries,...t],messageCount:a.messageCount+t.length,toolCallCount:a.toolCallCount+r}:i.push({anchorIdx:n,entries:t,messageCount:t.length,toolCallCount:r}),k?.({...nF,groups:i,messages:[...nF.messages,...e],status:nO})},[nF,nE,nM,nH,nO,k]),(0,i.useEffect)(()=>()=>k?.(null),[k]);let nB=th.filter(e=>"belowEditor"!==e.placement),nU=th.filter(e=>"belowEditor"===e.placement);return ey?(0,n.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ey}):(0,n.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":re,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:nt,onDragOver:nr,onDragLeave:nn,onDrop:ni,children:[re?(0,n.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,n.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:U("chat.loadingSession")})}):null,ne&&!t1&&(0,n.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,n.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:U("chat.attachFile")})}),tu&&(0,n.jsx)(lT,{request:tu,onInput:tm}),ny&&!S?(0,n.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,n.jsxs)("div",{className:"my-auto w-full max-w-[820px] py-8",children:[(0,n.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,n.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,n.jsx)(V,{})}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.10.21"]})]}),(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.11.3"]})]})]})]}),(0,n.jsx)(lC,{notices:to,align:"right"})]})}):(0,n.jsxs)(n.Fragment,{children:[S&&(0,n.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:S}),(0,n.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!S,style:{display:S?"none":"flex"},children:[(0,n.jsx)("div",{style:{position:"absolute",top:12,left:0,right:0,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,n.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,n.jsx)(ia,{open:rq,onClose:rZ,containerRef:tC,index:rG,renderedStart:rp,renderedEnd:rh,contentKey:ew,onReveal:rY,onProgrammaticScroll:tw,focusRequest:rV,t:U}),rB&&(0,n.jsx)("div",{className:"chat-jump-missing",role:"status",children:U("chat.jumpMissing")}),(0,n.jsx)(lC,{notices:to,floating:!0,align:"right"})]})}),(0,n.jsx)("div",{ref:tC,className:"chat-session-scroll relative min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",children:(0,n.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,n.jsxs)("div",{className:"chat-column-cap",style:{width:"100%",minWidth:0,maxWidth:820,margin:"0 auto"},children:[(0,n.jsx)(lS,{widgets:nB}),(0,n.jsx)(r_.Provider,{value:nd,children:(0,n.jsx)(iR,{utterances:nb,children:(0,n.jsx)(lw,{messages:ew,entryIds:ek,toolResultsMap:ns,modelNames:eT,messageCwd:nw,onOpenFile:j,sessionBusy:t1,isNew:tv,isStreaming:eS.isStreaming,handleFork:tT,forkingEntryId:e2,handleNavigate:tM,handleEditContent:ev,sessionId:e?.id??tj.current??void 0,main:rn,dispatchSlots:ra,compactedDispatch:rs,process:ri,startIndex:rp,endIndex:rh,sentinelRef:rx,laterSentinelRef:rv,flashItem:ry,t:U,cues:X,cueFollowRef:t4,onProcessLogChange:nD})})}),!rm&&eS.isStreaming&&eS.streamingMessage&&nR.length>0&&(0,n.jsx)(nL,{message:eA(eS.streamingMessage,nR),sessionId:e?.id??tj.current??void 0,isStreaming:!0,modelNames:eT,cwd:nw,onOpenFile:j}),r8&&(0,n.jsx)(iu,{onDismiss:r5,t:U}),(0,n.jsx)("div",{ref:tS})]})})}),(0,n.jsx)(is,{questions:rX,containerRef:tC,layoutKey:rQ,onJump:rz,label:U("chat.questionRail")}),(t1&&tb||rm)&&(0,n.jsxs)("button",{type:"button",onClick:rH,"aria-label":U("chat.jumpToBottom"),title:U("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",minHeight:K?44:void 0,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,n.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,n.jsx)("path",{d:"M12 5v14"}),(0,n.jsx)("path",{d:"m19 12-7 7-7-7"})]}),U("chat.jumpToBottom")]})]})]}),(0,n.jsxs)("div",{ref:nC,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[td&&(0,n.jsx)("div",{style:{padding:"0 16px"},children:(0,n.jsx)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:(0,n.jsx)(lI,{request:td,onRespond:tf,onActivity:e=>void tm(e,"activity"),delivery:tc})})}),(0,n.jsx)("div",{className:"min-h-0 overflow-y-auto",style:{padding:"0 16px"},children:(0,n.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:[(0,n.jsx)(ic,{compaction:e5,t:U}),(0,n.jsx)(lj,{goal:tk,t:U}),!J&&(0,n.jsx)(n9,{summary:nc,onJump:rz,onOpenPanel:nu}),(0,n.jsx)(lS,{widgets:nU}),nh&&!J&&(0,n.jsx)(sT,{phases:nh})]})}),nT,(0,n.jsx)(sI,{statuses:tp})]})]})}function lj({goal:e,t}){if(!e)return null;let r=!e.enabled,i=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:tZ(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:tZ(e.tokensUsed)});return(0,n.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:r?.7:1},children:[(0,n.jsx)("span",{style:{color:r?"var(--text-dim)":"var(--accent)",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",flexShrink:0},children:t("chat.goalLabel")}),(0,n.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:e.objective}),(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:r?t("chat.goalPaused"):e.status}),(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:i})]})}function lS({widgets:e}){return 0===e.length?null:(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,n.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,n.jsx)("div",{style:{padding:"5px 9px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:e.key}),(0,n.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:e.lines.join("\n")})]},e.key))})}function lC({notices:e,floating:t=!1,align:r="left"}){return 0===e.length?null:(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===r?"flex-end":"stretch",marginBottom:10*!t},children:e.map((r,i)=>{let a="error"===r.type?"var(--danger)":"warning"===r.type?"var(--warning)":"success"===r.type?"var(--success)":"var(--accent)";return(0,n.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:60,height:60,maxHeight:60,marginBottom:6*(i!==e.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:t?"var(--seed-shadow-s3)":"var(--seed-shadow-s2)",fontSize:18,lineHeight:1.45,transformOrigin:"top center",animation:r.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a,flexShrink:0}}),(0,n.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r.message})]},r.id)})})}function lN({focusKey:e,label:t,labelledBy:r,maxBlockSize:a="min(56dvh, 620px)",onCancel:s,delivery:l,children:o}){let{t:d}=(0,R.s)(),c=(0,i.useRef)(null),u=(0,i.useRef)({key:"",element:null});if(u.current.key!==e){let t="u"<typeof document?null:document.activeElement;u.current={key:e,element:t instanceof HTMLElement&&!c.current?.contains(t)?t:null}}return(0,i.useEffect)(()=>{let e=c.current;e&&!e.contains(document.activeElement)&&(e.querySelector('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')??e).focus();let t=u.current.element;return()=>{if(!t?.isConnected)return;let r=document.activeElement;(null===r||r===document.body||e?.contains(r))&&t.focus()}},[e]),(0,n.jsxs)("div",{ref:c,role:"dialog","aria-modal":"false","aria-label":t,"aria-labelledby":r,className:"chat-response-surface",tabIndex:-1,onKeyDown:s?e=>{"Escape"===e.key&&(e.stopPropagation(),s())}:void 0,"aria-busy":l?.status==="sending"||void 0,style:{maxBlockSize:a},children:[l?(0,n.jsx)("p",{className:"chat-response-delivery",role:"failed"===l.status?"alert":"status","data-state":l.status,children:"sending"===l.status?d("chat.responseSending"):`${d("chat.responseFailed")}${l.error?` (${l.error})`:""}`}):null,o]})}function lI({request:e,onRespond:t,onActivity:r,delivery:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[d,c]=(0,i.useState)({}),[u,p]=(0,i.useState)({}),[h,f]=(0,i.useState)(""),m=(0,i.useRef)(0),g=(0,i.useCallback)(()=>{if("ask"!==e.method||!e.timeout||!r)return;let t=Date.now();t-m.current<1e3||(m.current=t,r(e))},[e,r]);(0,i.useEffect)(()=>{if(o("editor"===e.method?e.prefill??"":""),f(""),p({}),"ask"!==e.method)return void c({});let t={};for(let r of e.questions)t[r.id]=void 0!==r.recommended&&void 0!==r.options[r.recommended]?[r.recommended]:[];c(t)},[e]);let x=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:l})};if("ask"===e.method){let r=e.questions.every(e=>(d[e.id]?.length??0)>0||(u[e.id]?.trim().length??0)>0),i=()=>{r&&t(e,{value:JSON.stringify({kind:"submit",results:e.questions.map(e=>{let t=u[e.id]?.trim();return{id:e.id,question:e.question,options:e.options.map(e=>e.label),multi:e.multi??!1,selectedOptions:(d[e.id]??[]).map(t=>e.options[t]?.label).filter(e=>void 0!==e),...t?{customInput:t}:{}}})})})};return(0,n.jsx)(lN,{focusKey:e.id,label:s("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:s("chat.agentQuestion")}),(0,n.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentQuestionHint")}),e.timeout?(0,n.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,n.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,n.jsx)("div",{style:{display:"grid",gap:20},children:e.questions.map((t,r)=>{let a=d[t.id]??[];return(0,n.jsxs)("section",{style:{paddingTop:20*(0!==r),borderTop:0===r?"none":"1px solid var(--hairline)"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[t.header&&(0,n.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.header}),e.questions.length>1&&(0,n.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[r+1,"/",e.questions.length]})]}),(0,n.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:t.question}),(0,n.jsx)("div",{role:t.multi?"group":"radiogroup","aria-label":t.question,style:{display:"grid",gap:4},children:t.options.map((e,r)=>{let i=a.includes(r),l=t.recommended===r;return(0,n.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":i,onClick:()=>{var e,n;return e=t.id,n=t.multi??!1,void(g(),c(t=>{let i=t[e]??[],a=n?i.includes(r)?i.filter(e=>e!==r):[...i,r]:[r];return{...t,[e]:a}}))},style:{display:"grid",gridTemplateColumns:"18px minmax(0, 1fr) auto",alignItems:"start",gap:9,width:"100%",minHeight:40,padding:"9px 10px",border:`1px solid ${i?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:i?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,n.jsx)("span",{"aria-hidden":"true",style:{display:"grid",placeItems:"center",width:16,height:16,marginTop:1,border:`1px solid ${i?"var(--text)":"var(--text-dim)"}`,borderRadius:t.multi?"var(--radius-control)":"50%",background:i?"var(--seed-color-fg-neutral)":"transparent",color:"var(--seed-color-fg-neutral-inverted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1},children:i&&(t.multi?(0,n.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,n.jsx)("polyline",{points:"2 5.2 4.1 7.2 8 2.8"})}):(0,n.jsx)("span",{style:{width:5,height:5,borderRadius:"50%",background:"currentColor"}}))}),(0,n.jsxs)("span",{style:{minWidth:0},children:[(0,n.jsx)("span",{style:{display:"block",fontSize:"var(--seed-font-size-t4-static)",fontWeight:i?600:500},children:e.label}),e.description&&(0,n.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.45},children:e.description}),i&&e.preview&&(0,n.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:e.preview})]}),l&&(0,n.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.recommended")})]},`${t.id}:${r}`)})}),(0,n.jsx)("input",{value:u[t.id]??"",onChange:e=>{g(),p(r=>({...r,[t.id]:e.target.value}))},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&i()},placeholder:s("chat.customAnswer"),"aria-label":s("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)"}})]},t.id)})})}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{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:s("chat.cancel")}),(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{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:s("chat.chatAboutThis")}),(0,n.jsx)("button",{type:"button",disabled:!r||a?.status==="sending",onClick:i,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:r&&a?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:r&&a?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:r&&a?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:a?.status==="sending"?s("chat.responseSending"):s("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,n.jsx)(lN,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:a,children:(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,n.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.planApproval")}),(0,n.jsx)("div",{id:`plan-review-${e.id}`,style:{marginTop:4,color:"var(--text)",fontSize:"var(--seed-font-size-t5-static)",fontWeight:600},children:e.title}),(0,n.jsx)("div",{style:{marginTop:5,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)",overflowWrap:"anywhere"},children:e.planFilePath})]}),(0,n.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,n.jsx)(tJ,{children:e.planContent})}),(0,n.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("textarea",{value:h,onChange:e=>f(e.target.value),placeholder:s("chat.planFeedback"),"aria-label":s("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,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"refine",feedback:h.trim()})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.refinePlan")}),(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{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:s("chat.approvePlan")})]})]})]})}):(0,n.jsx)(lN,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,n.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{id:`extension-request-${e.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:e.title}),(0,n.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:s("chat.extensionRequest")})]}),(0,n.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===e.method&&(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,n.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(r=>(0,n.jsx)("button",{onClick:()=>t(e,{value:r}),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:r},r))}),"input"===e.method&&(0,n.jsx)("input",{autoFocus:!0,value:l,placeholder:e.placeholder,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&x()},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"===e.method&&(0,n.jsx)("textarea",{autoFocus:!0,value:l,onChange:e=>o(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&x()},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,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("button",{onClick:()=>t(e,{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:s("chat.cancel")}),"confirm"===e.method?(0,n.jsx)("button",{onClick:x,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:s("chat.confirm")}):"select"!==e.method?(0,n.jsx)("button",{onClick:x,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:s("chat.submit")}):null]})]})})}function lT({request:e,onInput:t}){let{t:r}=(0,R.s)(),a=(0,i.useRef)(null),s=(0,i.useRef)(!1),l=eI(e.lines);return(0,i.useEffect)(()=>{a.current?.focus()},[e.id]),(0,n.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,n.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:e=>{e.target.closest("button")||a.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,n.jsx)("textarea",{ref:a,"aria-label":r("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:r=>{if(s.current||r.nativeEvent.isComposing)return;let n=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=e$[e.key];if(t)return t;if(1===e.key.length)return`\x1b${e.key}`}return"Enter"===e.key?e.shiftKey?"\n":"\r":"Tab"===e.key?e.shiftKey?"\x1b[Z":" ":eM[e.key]??null}(r);n&&(r.preventDefault(),r.stopPropagation(),t(e,n))},onInput:r=>{if(s.current||r.nativeEvent.isComposing)return;let n=r.currentTarget.value;r.currentTarget.value="",n&&t(e,n)},onCompositionStart:()=>{s.current=!0},onCompositionEnd:r=>{s.current=!1;let n=r.currentTarget;queueMicrotask(()=>{let r=n.value;n.value="",r&&t(e,r)})},onPaste:r=>{r.preventDefault();let n=r.clipboardData.getData("text");n&&t(e,`\x1b[200~${n}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:r("chat.extensionPanel")}),(0,n.jsx)("button",{onClick:()=>t(e,"\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:r("chat.close")})]}),(0,n.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:(l.length?l:[""]).map((e,t,r)=>{var a;return(0,n.jsxs)(i.Fragment,{children:[(a=`line-${t}`,eT(e).map((e,t)=>Object.keys(e.style).length>0?(0,n.jsx)("span",{style:e.style,children:e.text},`${a}-${t}`):e.text)),t<r.length-1?"\n":null]},t)})})]})})}function lM({onPick:e,t}){let[r,a]=(0,i.useState)(""),[s,l]=(0,i.useState)({kind:"idle"}),o=(0,i.useRef)(null),d=r.trim();(0,i.useEffect)(()=>{if(d.length<2)return void l({kind:"idle"});let e=new AbortController;l({kind:"loading"});let t=setTimeout(()=>{fetch(`/api/sessions/search?q=${encodeURIComponent(d)}`,{signal:e.signal,cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);l({kind:"done",data:await e.json()})}).catch(()=>{e.signal.aborted||l({kind:"error"})})},250);return()=>{clearTimeout(t),e.abort()}},[d]);let c=e=>{let t=o.current?.querySelectorAll("button");t&&0!==t.length&&t[Math.max(0,Math.min(t.length-1,e))]?.focus()},u="done"===s.kind?s.data:null,p=u?.truncated?t(`palette.searchTruncated.${u.truncated}`,{scanned:u.scannedSessions,total:u.totalSessions}):null;return(0,n.jsxs)("div",{className:"palette-search",children:[(0,n.jsx)("input",{type:"search",value:r,onChange:e=>a(e.target.value),onKeyDown:t=>{if(!t.nativeEvent.isComposing){if("ArrowDown"===t.key)t.preventDefault(),c(0);else if("Enter"===t.key&&u&&u.hits.length>0){t.preventDefault();let r=u.hits[0],n=u.sessions[r.sessionId];n&&e(n,r,u.query)}}},placeholder:t("palette.searchPlaceholder"),"aria-label":t("palette.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),d.length>=2&&(0,n.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":t("palette.searchResults"),"aria-busy":"loading"===s.kind,children:[(0,n.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===s.kind&&t("palette.searching"),"error"===s.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),p?` \xb7 ${p}`:"",u&&u.compactedHits>0?` \xb7 ${t("palette.searchCompacted",{count:u.compactedHits})}`:""]}),u&&u.hits.length>0&&(0,n.jsx)("div",{ref:o,className:"palette-search-list",children:u.hits.map((r,i)=>{let a=u.sessions[r.sessionId],s=r.matchStart+u.query.length;return(0,n.jsxs)("button",{type:"button",disabled:!a,onClick:()=>a&&e(a,r,u.query),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),c(i+("ArrowDown"===e.key?1:-1)))},children:[(0,n.jsxs)("span",{className:"palette-search-title",children:[(0,n.jsx)("span",{children:a?a.name?.trim()||a.firstMessage?.trim()||a.id:""}),(0,n.jsx)("small",{children:"user"===r.role?t("palette.searchRoleUser"):t("palette.searchRoleAssistant")})]}),(0,n.jsxs)("span",{className:"palette-search-snippet",children:[r.snippet.slice(0,r.matchStart),(0,n.jsx)("mark",{children:r.snippet.slice(r.matchStart,s)}),r.snippet.slice(s)]})]},`${r.sessionId}:${r.entryId}`)})})]})]})}var l$=r(50640),lR=r(73620);let lE=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function lL(e){return function e(t,r){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(r.has(t))return"[Circular]";r.add(t);try{return t.map(t=>e(t,r)).filter(Boolean).join(", ")}finally{r.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}let lz=["tags","categories","keywords","tag","category"];function lA({data:e}){var t;if(!e)return null;let r=Object.entries(e);if(0===r.length)return null;let i="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,a=lz.find(t=>Array.isArray(e[t])),s=a?e[a].map(lL).filter(Boolean):[],l=r.filter(([e])=>e!==a&&("title"!==e||!i));return(0,n.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,n.jsx)("div",{className:"markdown-frontmatter-title",children:i}),s.length>0&&(0,n.jsx)("div",{className:"markdown-frontmatter-tags",children:s.map((e,t)=>(0,n.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),l.length>0&&(0,n.jsx)("dl",{className:"markdown-frontmatter-rows",children:l.map(([e,t])=>(0,n.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,n.jsx)("dt",{children:e}),(0,n.jsx)("dd",{children:function(e){let t=lL(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,n.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(t)})]},e))})]})}let lP={source:"Source",preview:"Preview",diff:"Diff"},lW={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},lF={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 l_(){return(0,n.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,n.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,n.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function lD(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function lH(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let r=t.getRangeAt(0);if(!e.contains(r.startContainer)||!e.contains(r.endContainer))return null;let n=lD(r.startContainer),i=lD(r.endContainer);if(!n||!i||!e.contains(n)||!e.contains(i))return null;let a=Number(n.dataset.lineNumber),s=Number(i.dataset.lineNumber);if(!Number.isInteger(a)||!Number.isInteger(s))return null;if(a<s){let e=n.querySelector(".file-source-line-content");if(e?.contains(r.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(r.startContainer,r.startOffset),0===t.toString().length){let e=n.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(a=Number((n=e).dataset.lineNumber))}}let t=i.querySelector(".file-source-line-content");if(t?.contains(r.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(r.endContainer,r.endOffset),0===e.toString().length){let e=i.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((i=e).dataset.lineNumber))}}}return a>s?null:{startLine:a,endLine:s}}function lO({rows:e,stylesheet:t,useInlineStyles:r,wrapLines:i}){return e.map((e,a)=>{let s=e.children??[],l=s[0]?.properties?.className,o=Array.isArray(l)&&l.includes("react-syntax-highlighter-line-number"),d=o?s[0]:null,c=o?s.slice(1):s;return(0,n.jsxs)("span",{className:"file-source-line","data-line-number":a+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,l$.Ay)({node:d,stylesheet:t,useInlineStyles:r,key:`source-line-number-${a}`}),(0,n.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:i?"anywhere":"normal",whiteSpace:i?"pre-wrap":"pre"},children:c.map((e,n)=>(0,l$.Ay)({node:e,stylesheet:t,useInlineStyles:r,key:`source-token-${a}-${n}`}))})]},`source-line-${a}`)})}function lB(e,t,r,n={}){let i=tn(e),a=new URLSearchParams({type:t});for(let[e,t]of(r&&a.set("sessionId",r),Object.entries(n)))void 0!==t&&a.set(e,String(t));return`/api/files/${i}?${a.toString()}`}function lU({filePath:e,sourceSessionId:t}){let{t:r}=(0,R.s)();return(0,n.jsx)("a",{href:lB(e,"download",t),download:ti(e),title:r("i18n.downloadFile"),"aria-label":r("i18n.downloadFile"),className:"file-viewer-icon-button",children:(0,n.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,n.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,n.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,n.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})}function lq(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function lK({patch:e}){let t,{t:r}=(0,R.s)(),i=(t=rm(e))?t.flatMap(e=>e.rows.flatMap(e=>{if("hunk"===e.type)return[];if("context"===e.left.type&&"context"===e.right.type)return[{type:"unchanged",text:e.right.text,oldLineNo:e.left.lineNo,newLineNo:e.right.lineNo}];let t=[];return"removed"===e.left.type&&t.push({type:"removed",text:e.left.text,oldLineNo:e.left.lineNo,newLineNo:null}),"added"===e.right.type&&t.push({type:"added",text:e.right.text,oldLineNo:null,newLineNo:e.right.lineNo}),t})):[];if(!i.some(e=>"unchanged"!==e.type))return(0,n.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:r("i18n.noChanges")});let a=new Set(i.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),s=new Set;for(let e of a)for(let t=Math.max(0,e-3);t<=Math.min(i.length-1,e+3);t++)s.add(t);let l=[],o=0;for(;o<i.length;)if(s.has(o)){let e=[];for(;o<i.length&&s.has(o);)e.push(i[o]),o++;l.push({hidden:!1,lines:e})}else{let e=0;for(;o<i.length&&!s.has(o);)e++,o++;l.push({hidden:!0,count:e})}return(0,n.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...lW},children:l.map((e,t)=>{if(e.hidden)return(0,n.jsxs)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:["... ",e.count," unchanged lines ..."]},t);let r=e.lines.map((e,t)=>{let r="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",a="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,n.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:r,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,n.jsx)("span",{style:lF,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,n.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:a,userSelect:"none",flexShrink:0,fontWeight:600},children:i}),(0,n.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},t)});return(0,n.jsx)("div",{children:r},t)})})}function lV({filePath:e,cwd:t,sourceSessionId:r}){let{t:a}=(0,R.s)(),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(null),g=(0,i.useRef)(null),x=ti(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{d(0),u(null),h(null),m(null),l(!1),g.current&&(g.current.close(),g.current=null);let t=new EventSource(lB(e,"watch",r));return g.current=t,t.addEventListener("connected",()=>l(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&u(t.size)}catch{}d(e=>e+1)}),t.addEventListener("error",()=>l(!1)),t.onerror=()=>l(!1),()=>{t.close(),g.current=null}},[e,r]);let v=lB(e,"read",r,o?{v:o}:void 0),b=null!=c?lq(c):null;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.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,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:ta(e,t)}),(0,n.jsx)("span",{style:{marginLeft:"auto"},children:x||"image"}),p&&(0,n.jsxs)("span",{children:[p.w," \xd7 ",p.h]}),b&&(0,n.jsx)("span",{children:b}),(0,n.jsxs)("span",{title:a(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)"},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]}),(0,n.jsx)(lU,{filePath:e,sourceSessionId:r})]}),(0,n.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:f?(0,n.jsx)("div",{style:{color:"#f87171",fontSize:13},children:f}):(0,n.jsx)("img",{src:v,alt:e,onLoad:e=>{let t=e.currentTarget;h({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>m("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function lJ({filePath:e,cwd:t,sourceSessionId:r}){let{t:a}=(0,R.s)(),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(null),g=(0,i.useRef)(null),x=ti(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{d(0),u(null),h(null),m(null),l(!1),g.current&&(g.current.close(),g.current=null);let t=new EventSource(lB(e,"watch",r));return g.current=t,t.addEventListener("connected",()=>l(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&u(t.size)}catch{}h(null),m(null),d(e=>e+1)}),t.addEventListener("error",()=>l(!1)),t.onerror=()=>l(!1),()=>{t.close(),g.current=null}},[e,r]);let v=lB(e,"read",r,o?{v:o}:void 0);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.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,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:ta(e,t)}),(0,n.jsx)("span",{style:{marginLeft:"auto"},children:x||"audio"}),null!=p&&(0,n.jsx)("span",{children:function(e){if(!Number.isFinite(e))return"";let t=Math.round(e),r=Math.floor(t/60);return`${r}:${String(t%60).padStart(2,"0")}`}(p)}),null!=c&&(0,n.jsx)("span",{children:lq(c)}),(0,n.jsxs)("span",{title:a(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)"},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]}),(0,n.jsx)(lU,{filePath:e,sourceSessionId:r})]}),(0,n.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,n.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[f&&(0,n.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:f}),(0,n.jsx)("audio",{controls:!0,preload:"metadata",src:v,onLoadedMetadata:e=>h(e.currentTarget.duration),onError:()=>m("Failed to load audio"),style:{width:"100%"}},v)]})})]})}function lG({filePath:e,cwd:t,sourceSessionId:r}){let{t:a}=(0,R.s)(),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),f=(0,i.useRef)(null),m=eL(e),g="pdf"===m,x=g?lB(e,"read",r,o?{v:o}:void 0):lB(e,"preview",r,o?{v:o}:void 0);return(0,i.useEffect)(()=>{d(0),u(null),h(null),l(!1),f.current&&(f.current.close(),f.current=null),fetch(lB(e,"meta",r)).then(e=>e.json()).then(e=>{e.error&&h(e.error),"number"==typeof e.size&&(u(e.size),!g&&e.size>0xa00000&&h("DOCX too large for preview (>10MB)"))}).catch(e=>h(String(e)));let t=new EventSource(lB(e,"watch",r));return f.current=t,t.addEventListener("connected",()=>l(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(u(t.size),!g&&t.size>0xa00000))return void h("DOCX too large for preview (>10MB)")}catch{}h(null),d(e=>e+1)}),t.addEventListener("error",()=>l(!1)),t.onerror=()=>l(!1),()=>{t.close(),f.current=null}},[e,g,r]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.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,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:ta(e,t)}),(0,n.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===m?"docx preview":"pdf"}),null!=c&&(0,n.jsx)("span",{children:lq(c)}),(0,n.jsx)(lU,{filePath:e,sourceSessionId:r}),(0,n.jsxs)("span",{title:a(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]})]}),(0,n.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:p?(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:p}):(0,n.jsx)("iframe",{src:x,sandbox:g?void 0:"allow-same-origin",title:a("i18n.previewFile",{file:ti(e)}),style:{width:"100%",height:"100%",border:"none",background:g?"var(--bg)":"#eef1f5"}},x)})]})}function lY({filePath:e,cwd:t,sourceSessionId:r,onOpenFile:i,onMentionLines:a,onAtMention:s,gitRefreshKey:l,initialDisplayMode:o}){let d;return ez(e)?(0,n.jsx)(lV,{filePath:e,cwd:t,sourceSessionId:r}):null!==(eE[eL(e)]??null)?(0,n.jsx)(lJ,{filePath:e,cwd:t,sourceSessionId:r}):null!==("pdf"===(d=eL(e))||"docx"===d?d:null)?(0,n.jsx)(lG,{filePath:e,cwd:t,sourceSessionId:r}):(0,n.jsx)(lZ,{filePath:e,cwd:t,sourceSessionId:r,onOpenFile:i,onMentionLines:a,onAtMention:s,gitRefreshKey:l,initialDisplayMode:o})}function lZ({filePath:e,cwd:t,sourceSessionId:r,onOpenFile:a,onMentionLines:s,onAtMention:l,gitRefreshKey:o,initialDisplayMode:d}){let c,u,{isDark:p}=tO(),{t:h}=(0,R.s)(),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(!1),[y,w]=(0,i.useState)(!0),[k,j]=(0,i.useState)(null),[S,C]=(0,i.useState)("source"),[N,I]=(0,i.useState)(!1),[T,M]=(0,i.useState)(!1),$=(0,i.useRef)(null),E=(0,i.useRef)(0),L=(0,i.useRef)(null),[z,A]=(0,i.useState)(null),P=(0,i.useCallback)(e=>fetch(lB(e,"read",r)).then(e=>e.json()).then(e=>e.error?(j(e.error),null):(j(null),m(e),e)).catch(e=>(j(String(e)),null)),[r]),W=(0,i.useCallback)(async e=>{let r=++E.current;if(b(!0),!t){x(null),b(!1);return}try{let n=new URLSearchParams({cwd:t,path:e}),i=await fetch(`/api/git/diff?${n.toString()}`),a=await i.json();if(r!==E.current)return;x(i.ok&&a.supported&&"string"==typeof a.patch?a:null)}catch{r===E.current&&x(null)}finally{r===E.current&&b(!1)}},[t]);(0,i.useEffect)(()=>{w(!0),j(null),m(null),x(null),C("source"),I(!1),M(!1),$.current&&($.current.close(),$.current=null),P(e).finally(()=>w(!1));let t=new EventSource(lB(e,"watch",r));return $.current=t,t.addEventListener("connected",()=>{M(!0)}),t.addEventListener("change",()=>{P(e),W(e)}),t.addEventListener("error",()=>{M(!1)}),t.onerror=()=>{M(!1)},()=>{t.close(),$.current=null}},[e,P,W,r]),(0,i.useEffect)(()=>{W(e)},[W,e,o]),(0,i.useEffect)(()=>{(f?.language==="markdown"||f?.language==="html")&&"diff"!==d&&C("preview")},[f?.language,d]);let F=g?.supported===!0&&"string"==typeof g.patch,_=F&&"deleted"===g.status;(0,i.useEffect)(()=>{F||"diff"!==S||C("source")},[S,F]),(0,i.useEffect)(()=>{_&&$.current&&($.current.close(),$.current=null,M(!1))},[_]);let D=(0,i.useRef)(!1);(0,i.useEffect)(()=>{D.current=!1},[e]),(0,i.useEffect)(()=>{"diff"===d&&F&&!D.current&&(D.current=!0,C("diff"))},[d,F]);let H=(0,i.useMemo)(()=>f?.language==="markdown"?tf(f.content):"",[f]),O=(0,i.useMemo)(()=>f?.language==="markdown"?function(e){let t=function(e){let t=lE.exec(e);if(!t)return null;let r=/^---[ \t]*(?:(?:\r\n|\n|\r)|$)/gm;r.lastIndex=t[0].length;let n=r.exec(e);return n?{yaml:e.slice(t[0].length,n.index).replace(/(?:\r\n|\n|\r)$/,""),rest:e.slice(n.index+n[0].length)}:null}(e);if(!t)return{data:null,rest:e};try{let e=(0,lR.Hh)(t.yaml);if(e&&"object"==typeof e&&!Array.isArray(e))return{data:e,rest:t.rest}}catch{}return{data:null,rest:t.rest}}(f.content):null,[f]);(0,i.useEffect)(()=>{let e=()=>{let e=L.current;A(s&&"source"===S&&e?lH(e,window.getSelection()):null)};if(e(),s&&"source"===S)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[f?.content,S,s]);let B=(0,i.useCallback)(r=>{s&&r&&s(ta(e,t),r.startLine,r.endLine)},[t,e,s]);if((0,i.useEffect)(()=>{if(!s||"source"!==S)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let r=L.current,n=r?lH(r,window.getSelection()):null;n&&(e.preventDefault(),B(n))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[S,B,s]),y||"diff"===d&&v&&!f)return(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:h("i18n.loading")});if(k&&!_)return(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:k});if(!f&&!_)return null;let U=f?.language??"text",q=f?.content??"",K="html"===U,V="markdown"===U,J=(u=(c=tr(e).replace(/\/+$/,"")).lastIndexOf("/"))<0?"":0===u?"/":2===u&&/^[a-zA-Z]:\//.test(c)?c.slice(0,3):c.slice(0,u),G=q.split("\n"),Y=_?"diff":S,Z=_?["diff"]:["source",...K||V?["preview"]:[],...F?["diff"]:[]],X=_?h("files.deleted"):`${U} \xb7 ${G.length} lines \xb7 ${lq(f.size)}`;return(0,n.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.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,n.jsx)("span",{className:"file-viewer-path",style:{fontFamily:"var(--font-mono)"},title:e,children:ta(e,t)}),(0,n.jsx)("span",{className:"file-viewer-meta",title:X,children:X}),!_&&(0,n.jsx)("span",{title:T?h("i18n.liveSync"):h("i18n.notWatching"),"aria-label":T?h("i18n.liveSync"):h("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:T?"#4ade80":"var(--border)",boxShadow:T?"0 0 4px #4ade80":"none"}}),(0,n.jsxs)("div",{className:"file-viewer-controls",children:[Z.length>1&&(0,n.jsx)("div",{className:"file-viewer-mode-switch","aria-label":h("i18n.fileViewMode"),children:Z.map(e=>{let t=Y===e;return(0,n.jsx)("button",{type:"button",onClick:()=>C(e),title:"diff"===e?h("i18n.compareHead"):void 0,"aria-pressed":t,className:"file-viewer-mode-button",style:{background:t?"var(--bg-selected)":"transparent",color:t?"var(--text)":"var(--text-muted)"},children:lP[e]},e)})}),(0,n.jsxs)("div",{className:"file-viewer-actions",children:[(l||s)&&(0,n.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{z&&s?B(z):l?.(ta(e,t),!1)},title:z&&s?`${h("i18n.mentionSelectedLines")} (L${z.startLine}${z.startLine!==z.endLine?`-L${z.endLine}`:""})`:h("files.insertPath"),"aria-label":h("files.mention"),disabled:!l&&!s,className:"file-viewer-icon-button",children:(0,n.jsx)(l_,{})}),"source"===Y&&(0,n.jsx)(n.Fragment,{children:(0,n.jsx)("button",{type:"button",onClick:()=>I(e=>!e),title:N?h("i18n.disableWrap"):h("i18n.enableWrap"),"aria-label":N?h("i18n.disableWrap"):h("i18n.enableWrap"),"aria-pressed":N,className:"file-viewer-icon-button",style:{background:N?"var(--bg-selected)":"transparent",color:N?"var(--text)":"var(--text-muted)"},children:(0,n.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,n.jsx)("path",{d:"M3 6h18"}),(0,n.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,n.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,n.jsx)("path",{d:"M3 18h7"})]})})})]}),!_&&(0,n.jsx)(lU,{filePath:e,sourceSessionId:r})]})]}),(0,n.jsx)("div",{ref:L,className:"file-viewer-content",style:{flex:1,overflow:"auto",background:"var(--bg)"},children:"diff"===Y&&F?(0,n.jsx)(lK,{patch:g.patch}):K&&"preview"===Y?(0,n.jsx)("iframe",{srcDoc:q,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:h("i18n.htmlPreview")}):V&&"preview"===Y?(0,n.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[O?.data&&(0,n.jsx)(lA,{data:O.data}),(0,n.jsx)(tt.oz,{remarkPlugins:tb,rehypePlugins:tw,components:{code({className:e,children:t,...r}){let i=e?.replace("language-","").toLowerCase()??"",a=String(t);return e?.includes("language-")||a.includes("\n")?"mermaid"===i?(0,n.jsx)(tq,{code:a.replace(/\n$/,""),defaultPreview:!0}):(0,n.jsx)(tV,{code:a.replace(/\n$/,""),lang:i}):(0,n.jsx)("code",{className:e,...r,children:t})},pre:({children:e})=>(0,n.jsx)(n.Fragment,{children:e}),a({href:e,children:r,...i}){delete i.node;let s=a?e5(e,J,t??J):null;return s&&a?(0,n.jsx)("a",{href:e,...i,onClick:e=>{e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),a(s))},children:r}):(0,n.jsx)("a",{href:e,...i,children:r})},img({src:e,alt:i,...a}){delete a.node;let s="string"==typeof e?e5(e,J,t??J):null,l=s?lB(s,"read",r):e;return(0,n.jsx)("img",{src:l,alt:i??"",loading:"lazy",...a})},table:({children:e})=>(0,n.jsx)("div",{className:"markdown-table-wrap",children:(0,n.jsx)("table",{children:e})})},children:H})]}):(0,n.jsx)(e9.A,{className:N?"file-source-view is-wrapped":"file-source-view",language:"text"===U?"plaintext":U,style:p?te.xJ:te.vs,showLineNumbers:!0,lineNumberStyle:{...lF},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...lW,width:N?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",overflowWrap:N?"anywhere":"normal"}},renderer:e=>(0,n.jsx)(lO,{...e,wrapLines:N}),wrapLongLines:N,children:q})})]})}function lX({tabs:e,activeTabId:t,onSelectTab:r,onCloseTab:a}){let{t:s,locale:l}=(0,R.s)(),[o,d]=(0,i.useState)(null);return(0,n.jsx)("div",{className:"file-tab-list",role:"tablist","aria-label":"ko"===l?"열린 파일 탭":"Open file tabs",style:{display:"flex",alignItems:"flex-end",overflowX:"auto",flexShrink:0,height:36},children:e.map(e=>{let i=e.id===t;return(0,n.jsxs)("div",{className:`file-tab${i?" is-active":""}`,role:"presentation",onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:t=>{1===t.button&&(t.preventDefault(),t.stopPropagation(),a(e.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,n.jsxs)("button",{type:"button",role:"tab","aria-selected":i,onClick:()=>r(e.id),title:e.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,n.jsx)("span",{style:{flexShrink:0,opacity:i?1:.7,display:"flex",alignItems:"center"},children:rj(e.label,13)}),(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:i?500:400},children:e.label})]}),(0,n.jsx)("button",{className:"file-tab-close",onClick:t=>{t.stopPropagation(),a(e.id)},onMouseEnter:()=>d(e.id),onMouseLeave:()=>d(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:o===e.id?"var(--bg-hover)":"transparent",border:"none",color:o===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:s("i18n.close"),"aria-label":`${s("i18n.close")} ${e.label}`,children:(0,n.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,n.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,n.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})})}let lQ=["inherit","off","auto","minimal","low","medium","high","xhigh","max"],l0=new Set(lQ);function l1(e){return void 0!==e&&l0.has(e)}function l2(e){if(!e)return[...lQ];let t=new Set(e);return lQ.filter(e=>"inherit"===e||"off"===e||"auto"===e||t.has(e))}function l4(e){if(!e)return"inherit";let t=e.lastIndexOf(":"),r=t>=0?e.slice(t+1):void 0;return l1(r)?r:"inherit"}function l5(e,t){let r=e.lastIndexOf(":"),n=l1(r>=0?e.slice(r+1):void 0)?e.slice(0,r):e;return"inherit"===t?n:`${n}:${t}`}var l8=r(98795),l6=r.n(l8);function l3(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase()}function l7({value:e,options:t,onChange:r,disabled:a=!1,placeholder:s="Select…",searchPlaceholder:l="Search options…",noResultsLabel:o="No matching options",ariaLabel:d,className:c,style:u}){let p=(0,i.useRef)(null),h=(0,i.useRef)(null),f=(0,i.useRef)(null),m=(0,i.useRef)([]),[g,x]=(0,i.useState)(!1),[v,b]=(0,i.useState)(""),[y,w]=(0,i.useState)(0),k=(0,i.useId)(),j=t.find(t=>t.value===e),S=(0,i.useMemo)(()=>{let e=l3(v.trim());return e?t.filter(t=>l3(`${t.label} ${t.value} ${t.searchText??""}`).includes(e)):t},[t,v]);(0,i.useEffect)(()=>{if(!g)return;let e=e=>{p.current?.contains(e.target)||x(!1)};return document.addEventListener("pointerdown",e),()=>document.removeEventListener("pointerdown",e)},[g]),(0,i.useEffect)(()=>{g?requestAnimationFrame(()=>f.current?.focus()):b("")},[g]),(0,i.useEffect)(()=>{if(!g)return;let t=S.findIndex(t=>t.value===e&&!t.disabled);w(t>=0?t:Math.max(0,S.findIndex(e=>!e.disabled)))},[S,g,e]),(0,i.useEffect)(()=>{(y>=S.length||S[y]?.disabled)&&w(Math.max(0,S.findIndex(e=>!e.disabled)))},[y,S]),(0,i.useEffect)(()=>{g&&m.current[y]?.scrollIntoView({block:"nearest"})},[y,g]);let{side:C,maxHeight:N}=aX(p,g,{viewportFraction:.6,cap:296,gap:5,prefer:"below",minHeight:160}),I=e=>{e.disabled||(r(e.value),x(!1))},T=e=>{if(!S.length)return;let t=y;for(let r=0;r<S.length;r+=1)if(t=(t+e+S.length)%S.length,!S[t].disabled)return void w(t)};return(0,n.jsxs)("div",{ref:p,className:`${l6().root}${c?` ${c}`:""}`,style:u,children:[(0,n.jsxs)("button",{ref:h,type:"button",className:l6().trigger,disabled:a,"aria-label":d,"aria-haspopup":"listbox","aria-expanded":g,"aria-controls":g?k:void 0,onClick:()=>x(e=>!e),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),x(!0))},children:[(0,n.jsx)("span",{className:j?l6().value:l6().placeholder,children:j?.label??(e||s)}),(0,n.jsx)("svg",{className:l6().chevron,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m3 4.5 3 3 3-3"})})]}),g&&(0,n.jsxs)("div",{className:l6().popover,style:"above"===C?{bottom:"calc(100% + 5px)",maxHeight:N}:{top:"calc(100% + 5px)",maxHeight:N},"data-dismissible-layer":"searchable-select",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),x(!1),h.current?.focus())},children:[(0,n.jsxs)("div",{className:l6().searchWrap,children:[(0,n.jsxs)("svg",{className:l6().searchIcon,viewBox:"0 0 16 16","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"7",cy:"7",r:"4.25"}),(0,n.jsx)("path",{d:"m10.2 10.2 3.1 3.1"})]}),(0,n.jsx)("input",{ref:f,className:l6().search,value:v,placeholder:l,"aria-label":l,role:"combobox","aria-expanded":"true","aria-controls":k,"aria-activedescendant":S[y]?`${k}-${y}`:void 0,autoComplete:"off",spellCheck:!1,onChange:e=>{b(e.target.value),w(0)},onKeyDown:e=>{if("ArrowDown"===e.key)e.preventDefault(),T(1);else if("ArrowUp"===e.key)e.preventDefault(),T(-1);else if("Enter"===e.key){e.preventDefault();let t=S[y];t&&I(t)}else"Tab"===e.key&&x(!1)}})]}),(0,n.jsx)("div",{id:k,className:l6().options,role:"listbox","aria-label":d,style:{maxHeight:Math.max(0,N-46)},children:S.length?S.map((t,r)=>(0,n.jsxs)("button",{ref:e=>{m.current[r]=e},id:`${k}-${r}`,type:"button",role:"option","aria-selected":t.value===e,className:l6().option,"data-active":r===y,"data-selected":t.value===e,disabled:t.disabled,onMouseEnter:()=>w(r),onClick:()=>I(t),children:[(0,n.jsxs)("span",{className:l6().optionCopy,children:[(0,n.jsx)("span",{className:l6().optionLabel,children:t.label}),t.description&&(0,n.jsx)("span",{className:l6().optionDescription,children:t.description})]}),t.value===e&&(0,n.jsx)("svg",{className:l6().check,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m2.3 6.2 2.2 2.2 5.2-5.2"})})]},t.value)):(0,n.jsx)("div",{className:l6().empty,children:o})})]})]})}let l9=["global","project"],oe=["implSonnet","implOpus","implDeepSeek","makerHardUiOpus","makerHardCodeOpus","makerHardCodeSonnet"];function ot(e){return`${e.provider}/${e.id}`}function or({cwd:e,onRolesChanged:t}){let{t:r}=(0,R.s)(),[a,s]=(0,i.useState)([]),[l,o]=(0,i.useState)([]),[d,c]=(0,i.useState)({}),[u,p]=(0,i.useState)("global"),[h,f]=(0,i.useState)(!0),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),b=(0,i.useCallback)(async t=>{if(!e){s([]),o([]),c({}),f(!1);return}f(!0),g(null);try{let r=`?cwd=${encodeURIComponent(e)}`,[n,i]=await Promise.all([fetch(`/api/model-roles${r}`,t?{signal:t}:void 0),fetch(`/api/models${r}`,t?{signal:t}:void 0)]);if(!n.ok)throw Error(`HTTP ${n.status}`);let a=await n.json();if(a.error)throw Error(a.error);if(!i.ok)throw Error(`HTTP ${i.status}`);let l=await i.json();s(a.roles??[]),o(l.modelList??[]),c(l.thinkingLevels??{})}catch(e){if("AbortError"===e.name)return;g(e instanceof Error?e.message:String(e))}finally{f(!1)}},[e]);(0,i.useEffect)(()=>{let e=new AbortController;return b(e.signal),()=>e.abort()},[b]);let y=(0,i.useCallback)(async(r,n)=>{if(e){v(r),g(null);try{let i=await fetch("/api/model-roles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,role:r,selector:n,scope:u})}),a=await i.json();if(!i.ok||a.error)throw Error(a.error??`HTTP ${i.status}`);s(a.roles??[]),t?.()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(null)}}},[e,u,t]),w=(0,i.useMemo)(()=>a.filter(e=>!e.hidden),[a]),k=w.some(e=>oe.includes(e.role)&&!e.selector);return e?(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{fontSize:13,fontWeight:700,color:"var(--text)",marginBottom:4},children:r("roles.title")}),(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:r("roles.description")}),!h&&k&&(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",lineHeight:1.5,marginTop:4},children:r("roles.harnessNote")})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8},children:[(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:r("roles.scope")}),(0,n.jsx)("div",{style:{display:"flex",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,overflow:"hidden"},children:l9.map(e=>(0,n.jsx)("button",{onClick:()=>p(e),style:{padding:"4px 10px",border:"none",background:u===e?"var(--bg-selected)":"transparent",color:u===e?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:u===e?600:400},children:"global"===e?r("roles.scopeGlobal"):r("roles.scopeProject")},e))}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"global"===u?"~/.omp/agent/config.yml":".omp/config.yml"})]}),m&&(0,n.jsx)("div",{style:{fontSize:12,color:"var(--danger, #ff4757)"},children:m}),h?(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:r("i18n.loading")}):(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:w.map(e=>{let t=e.resolved?`${e.resolved.provider}/${e.resolved.modelId}`:l5(e.selector??"","inherit"),i=l4(e.selector),a=l2(d[e.resolved?`${e.resolved.provider}:${e.resolved.modelId}`:""]),s=oe.includes(e.role);return(0,n.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,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,rowGap:6},children:[(0,n.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:e.tag??e.role.toUpperCase()}),(0,n.jsxs)("div",{style:{minWidth:0,flex:"0 0 auto",width:128},children:[(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontWeight:600},children:e.name}),s&&(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-muted)",lineHeight:1.35},children:r(`roles.harness.${e.role}`)}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)"},children:s&&!e.selector?r("roles.harnessUnset"):r(`roles.source.${e.source}`)})]}),(0,n.jsx)(l7,{value:t,disabled:x===e.role,ariaLabel:e.name,style:{flex:"1 1 160px",minWidth:0},onChange:t=>{if(!t)return void y(e.role,null);let r=l.find(e=>ot(e)===t),n=r?d[`${r.provider}:${r.id}`]:void 0,i=l4(e.selector),a=l2(n).includes(i)?i:"inherit";y(e.role,l5(t,a))},options:[{value:"",label:r("roles.unset")},...l.map(e=>({value:ot(e),label:`${e.name} — ${e.provider}`,searchText:ot(e)})),...t&&!l.some(e=>ot(e)===t)?[{value:t,label:t}]:[]]}),e.warning&&(0,n.jsx)("span",{title:e.warning,style:{color:"var(--warning, #ffb347)",fontSize:12},children:"!"})]}),e.resolved&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",paddingLeft:72},children:[(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,whiteSpace:"nowrap"},children:r("roles.thinking")}),(0,n.jsx)("div",{role:"group","aria-label":`${e.name} ${r("roles.thinking")}`,style:{display:"flex",flex:"1 1 auto",minWidth:0,flexWrap:"wrap",gap:3},children:a.map(a=>{let s=i===a;return(0,n.jsx)("button",{type:"button","aria-pressed":s,disabled:x===e.role,title:"inherit"===a?r("roles.thinkingInherit"):a,onClick:()=>{s||y(e.role,l5(t,a))},style:{padding:"3px 7px",border:`1px solid ${s?"var(--accent)":"var(--border)"}`,borderRadius:4,background:s?"var(--bg-selected)":"transparent",color:s?"var(--accent)":"var(--text-muted)",cursor:x===e.role?"not-allowed":"pointer",fontFamily:"var(--font-mono)",fontSize:10,fontWeight:s?700:500,lineHeight:1.2,opacity:x===e.role?.55:1},children:a},a)})})]})]},e.role)})})]}):(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:r("roles.needsProject")})}function on(e){window.open(e,"_blank","noopener,noreferrer")}var oi=r(67381),oa=r(64433),os=r(70350),ol=r(88195),oo=r(9312),od=r(87275),oc=r(22008),ou=r(95476),op=r(35029),oh=r(14489),of=r(78728),om=r(19872),og=r(7751),ox=r(92526),ov=r(48238),ob=r(57794),oy=r(41098),ow=r(84604),ok=r(15315),oj=r(74278),oS=r(55457),oC=r(71437),oN=r(29167),oI=r(97283),oT=r(34166),oM=r(33889),o$=r(85486),oR=r(74068),oE=r(83546),oL=r(83709);let oz={anthropic:{Icon:oi.A,hasColor:!1},openai:{Icon:oa.A,hasColor:!1},"openai-codex":{Icon:oa.A,hasColor:!1},google:{Icon:os.A,hasColor:!0},"google-vertex":{Icon:os.A,hasColor:!0},"ant-ling":{Icon:oM.A,hasColor:!0},deepseek:{Icon:ol.A,hasColor:!0},groq:{Icon:oo.A,hasColor:!1},mistral:{Icon:od.A,hasColor:!0},moonshotai:{Icon:oc.A,hasColor:!1},"moonshotai-cn":{Icon:oc.A,hasColor:!1},moonshot:{Icon:oc.A,hasColor:!1},minimax:{Icon:ou.A,hasColor:!0},"minimax-cn":{Icon:ou.A,hasColor:!0},fireworks:{Icon:op.A,hasColor:!0},huggingface:{Icon:oh.A,hasColor:!0},cerebras:{Icon:of.A,hasColor:!0},openrouter:{Icon:om.A,hasColor:!1},xai:{Icon:og.A,hasColor:!1},"cloudflare-ai-gateway":{Icon:ox.A,hasColor:!0},"cloudflare-workers-ai":{Icon:ox.A,hasColor:!0},"vercel-ai-gateway":{Icon:ov.A,hasColor:!1},"github-copilot":{Icon:ob.A,hasColor:!1},"amazon-bedrock":{Icon:oy.A,hasColor:!0},"azure-openai-responses":{Icon:ow.A,hasColor:!0},"kimi-coding":{Icon:ok.A,hasColor:!0},nvidia:{Icon:o$.A,hasColor:!0},opencode:{Icon:oR.A,hasColor:!1},"opencode-go":{Icon:oR.A,hasColor:!1},qwen:{Icon:oj.A,hasColor:!0},xiaomi:{Icon:oE.A,hasColor:!1},"xiaomi-token-plan-ams":{Icon:oE.A,hasColor:!1},"xiaomi-token-plan-cn":{Icon:oE.A,hasColor:!1},"xiaomi-token-plan-sgp":{Icon:oE.A,hasColor:!1},zai:{Icon:oL.A,hasColor:!1},"zai-coding-cn":{Icon:oL.A,hasColor:!1},zhipu:{Icon:oS.A,hasColor:!0},cohere:{Icon:oC.A,hasColor:!0},perplexity:{Icon:oN.A,hasColor:!0},together:{Icon:oI.A,hasColor:!0},grok:{Icon:oT.A,hasColor:!1}},oA=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function oP({label:e,children:t}){return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("label",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:e}),t]})}let oW={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 oF({value:e,onChange:t,placeholder:r,mono:i}){return(0,n.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:r,style:{...oW,fontFamily:i?"var(--font-mono)":"inherit"}})}function o_({value:e,onChange:t,placeholder:r,mono:a,onKeyDown:s,autoComplete:l="off",spellCheck:o=!1,style:d}){let[c,u]=(0,i.useState)(!1),{t:p}=(0,R.s)();return(0,i.useEffect)(()=>{e||u(!1)},[e]),(0,n.jsxs)("div",{style:{position:"relative",width:"100%",...d},children:[(0,n.jsx)("input",{type:c?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:s,placeholder:r,style:{...oW,paddingRight:34,fontFamily:a?"var(--font-mono)":"inherit"},autoComplete:l,spellCheck:o}),(0,n.jsx)("button",{type:"button",onClick:()=>u(e=>!e),"aria-label":p(c?"i18n.hideDetails":"i18n.showDetails"),title:p(c?"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:c?(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.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,n.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,n.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,n.jsx)("path",{d:"M1 1l22 22"})]}):(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,n.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function oD({value:e,onChange:t,placeholder:r}){return(0,n.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:r,style:oW})}function oH({value:e,onChange:t,options:r,required:i}){let{t:a}=(0,R.s)();return(0,n.jsx)(l7,{value:e,onChange:t,options:[...i?[]:[{value:"",label:`— ${a("i18n.default")} / none —`}],...r.map(e=>({value:e,label:e}))]})}function oO({label:e,checked:t,onChange:r}){return(0,n.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,n.jsx)("input",{type:"checkbox",checked:t,onChange:e=>r(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function oB({children:e}){return(0,n.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:e})}function oU({name:e,provider:t,onChange:r,onRename:a,onDelete:s,onAddModels:l}){let{t:o}=(0,R.s)(),[d,c]=(0,i.useState)(e),[u,p]=(0,i.useState)({phase:"idle"}),[h,f]=(0,i.useState)(""),[m,g]=(0,i.useState)([]),x=(0,i.useRef)(0),v=(0,i.useRef)(null);(0,i.useEffect)(()=>c(e),[e]);let b=(e,n)=>r({...t,[e]:n});(0,i.useEffect)(()=>{t.api||r({...t,api:"openai-completions"})},[t.api]),(0,i.useEffect)(()=>{x.current+=1,p({phase:"idle"}),f(""),g([])},[e,t.baseUrl,t.api,t.apiKey]);let y=(0,i.useCallback)(async()=>{if(!t.baseUrl?.trim()||"loading"===u.phase)return;let r=++x.current;p({phase:"loading"}),g([]);try{let n=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:{...t,models:void 0}})}),i=await n.json();if(r!==x.current)return;if(!n.ok||i.error||!i.models)return void p({phase:"error",message:i.error??`HTTP ${n.status}`});p({phase:"success",models:i.models,endpoint:i.endpoint??t.baseUrl})}catch(e){if(r!==x.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,e,t]),w=new Set((t.models??[]).map(e=>e.id)),k="success"===u.phase?u.models:[],j=h.trim().toLocaleLowerCase(),S=k.filter(e=>!j||e.id.toLocaleLowerCase().includes(j)||e.name?.toLocaleLowerCase().includes(j)),C=S.slice(0,300),N=C.filter(e=>!w.has(e.id)).map(e=>e.id),I=m.filter(e=>!w.has(e)).length,T=N.length>0&&N.every(e=>m.includes(e)),M=!T&&N.some(e=>m.includes(e));return(0,i.useEffect)(()=>{v.current&&(v.current.indeterminate=M)},[M]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(oB,{children:o("i18n.provider")}),(0,n.jsx)("button",{onClick:s,style:{padding:"3px 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11},children:o("i18n.delete")})]}),(0,n.jsxs)(oP,{label:o("i18n.providerName"),children:[(0,n.jsx)(oF,{value:d,onChange:c,placeholder:"provider-name",mono:!0}),d!==e&&d.trim()&&(0,n.jsx)("button",{onClick:()=>a(d.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:o("i18n.rename")})]}),(0,n.jsx)(oP,{label:"Base URL",children:(0,n.jsx)(oF,{value:t.baseUrl??"",onChange:e=>b("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,n.jsxs)(oP,{label:"API Key",children:[(0,n.jsx)(o_,{value:t.apiKey??"",onChange:e=>b("apiKey",e||void 0),placeholder:"ENV_VAR_NAME, !shell-command, or literal key",mono:!0}),(0,n.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:["Prefix with ",(0,n.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:"!"})," to run a shell command, or use an env var name"]})]}),(0,n.jsx)(oP,{label:"API",children:(0,n.jsx)(oH,{value:t.api??"openai-completions",onChange:e=>b("api",e),options:oA,required:!0})}),(0,n.jsxs)(oP,{label:"Headers",children:[(0,n.jsx)(oG,{headers:t.headers,onChange:e=>b("headers",e)}),(0,n.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,n.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==u.phase&&(0,n.jsx)("button",{onClick:y,disabled:!t.baseUrl?.trim()||"loading"===u.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:t.baseUrl?.trim()&&"loading"!==u.phase?"var(--text-muted)":"var(--text-dim)",cursor:t.baseUrl?.trim()&&"loading"!==u.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===u.phase?o("models.discoveryFetching"):o("models.discoveryFetch")}),"error"===u.phase&&(0,n.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:u.message}),"success"===u.phase&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("input",{value:h,onChange:e=>f(e.target.value),placeholder:o("models.discoveryFilterPlaceholder",{count:u.models.length}),"aria-label":o("models.discoveryFilter"),style:{...oW,width:"100%",minWidth:0}}),(0,n.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,n.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:N.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,n.jsx)("input",{ref:v,type:"checkbox",checked:T,disabled:0===N.length,onChange:()=>{let e=new Set(N);g(t=>T?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...N])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),o("models.discoverySelectShown")]}),0===C.length?(0,n.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:o("models.discoveryNoMatches")}):C.map((e,t)=>{let r=w.has(e.id),i=m.includes(e.id);return(0,n.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:r?"default":"pointer",opacity:r?.65:1},children:[(0,n.jsx)("input",{type:"checkbox",checked:i||r,disabled:r,onChange:()=>{var t;return t=e.id,void g(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,n.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,n.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,n.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),r&&(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:o("models.discoveryAdded")})]},e.id)})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,n.jsx)("span",{title:u.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:S.length>C.length?o("models.discoveryShowing",{shown:C.length,total:S.length}):o("models.discoveryFetched",{count:u.models.length})}),(0,n.jsx)("button",{onClick:()=>{if("success"!==u.phase)return;let e=new Set(m),t=u.models.filter(t=>e.has(t.id)&&!w.has(t.id));0!==t.length&&(l(t),g([]))},disabled:0===I,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:I?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",color:I?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:I?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:I?o("models.discoveryAddSelectedCount",{count:I}):o("models.discoveryAddSelected")})]})]})]})]})}let oq=["off","minimal","low","medium","high","xhigh","max"],oK={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function oV({value:e,onChange:t}){let r=e??{},i=(e,n)=>{let i={...r};"omit"===n?delete i[e]:i[e]=n,t(Object.keys(i).length?i:void 0)};return(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:oq.map(e=>{let t=r[e],a=e in r?null===t?"null":"string":"omit",s="string"==typeof t?t:"",l=oK[e],o={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},d={background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontWeight:600};return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,n.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:l,flexShrink:0,opacity:"null"===a?.3:1}}),(0,n.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===a?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===a?"line-through":"none"},children:e})]}),(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,n.jsx)("button",{onClick:()=>i(e,"omit"),style:{...o,..."omit"===a?d:{}},children:"Default"}),(0,n.jsx)("button",{onClick:()=>i(e,null),style:{...o,borderLeft:"1px solid var(--border)",..."null"===a?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===a?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,n.jsx)("button",{onClick:()=>i(e,s||e),style:{...o,..."string"===a?d:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,n.jsx)("input",{value:s,onChange:t=>i(e,t.target.value),onFocus:()=>{"string"!==a&&i(e,s||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===a?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===a?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let oJ={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function oG({headers:e,onChange:t}){let[r,a]=(0,i.useState)(()=>Object.entries(e??{}).map(([e,t],r)=>({id:r,name:e,value:t}))),s=(0,i.useRef)(r.length),l=e=>{a(e),t(function(e){let t={};for(let r of e){let e=r.name.trim();e&&(t[e]=r.value)}return Object.keys(t).length?t:void 0}(e))},o=(e,t)=>{l(r.map(r=>r.id===e?{...r,...t}:r))},d={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[r.map(e=>(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsx)("input",{value:e.name,onChange:t=>o(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...oW,fontFamily:"var(--font-mono)",flex:1}}),(0,n.jsx)("input",{value:e.value,onChange:t=>o(e.id,{value:t.target.value}),placeholder:"value",style:{...oW,fontFamily:"var(--font-mono)",flex:1}}),(0,n.jsx)("button",{onClick:()=>{var t;return t=e.id,void l(r.filter(e=>e.id!==t))},style:d,children:"✕"})]},e.id)),(0,n.jsx)("button",{onClick:()=>a(e=>[...e,{id:s.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 oY({providerName:e,provider:t,model:r,onChange:a,onDelete:s}){let[l,o]=(0,i.useState)({phase:"idle"}),{t:d}=(0,R.s)(),[c,u]=(0,i.useState)({phase:"idle"}),p=(0,i.useRef)(0),h=(0,i.useRef)(null),f=(e,t)=>a({...r,[e]:t}),m=(()=>{if("idle"===l.phase)return null;if("testing"===l.phase)return d("i18n.testingModel");let e=[void 0!==l.latencyMs?`${l.latencyMs}ms`:null,void 0!==l.status?`HTTP ${l.status}`:null].filter(Boolean);return"success"===l.phase?[d("i18n.connected"),...e,l.responseText||null].filter(Boolean).join(" \xb7 "):[d("i18n.failed"),...e,l.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>{o({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,r.id,r.api]),(0,i.useEffect)(()=>{p.current+=1,u({phase:"idle"}),h.current=null},[e,t.baseUrl,r.id]);let g=(0,i.useCallback)(async()=>{if(r.id.trim()&&"testing"!==l.phase){o({phase:"testing"});try{let n=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:r})}),i=await n.json();if(!n.ok||!i.ok)return void o({phase:"error",message:i.error??`HTTP ${n.status}`,latencyMs:i.latencyMs,status:i.status});o({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(e){o({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[r,t,e,l.phase]),x=(0,i.useCallback)(async()=>{let n=r.id.trim();if(!n||"loading"===c.phase)return;let i=++p.current;u({phase:"loading"});try{let s=new URLSearchParams({q:n,provider:e,limit:"50"});t.baseUrl?.trim()&&s.set("baseUrl",t.baseUrl.trim());let l=await fetch(`/api/models-config/catalog?${s}`),o=await l.json();if(i!==p.current)return;if(!l.ok||o.error||!o.recommendation)return void u({phase:"error",message:o.error??`HTTP ${l.status}`});let d=function(e,t){let r={...e},n=0;if(!e.name?.trim()&&t.name&&(r.name=t.name,n+=1),void 0===e.reasoning&&!0===t.reasoning&&(r.reasoning=!0,n+=1),!e.input?.length&&t.input?.length&&(r.input=[...t.input],n+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(r.contextWindow=t.contextWindow,n+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(r.maxTokens=t.maxTokens,n+=1),t.cost){let i={...e.cost??{}},a=!1;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],a=!0,n+=1);a&&(r.cost=i)}return{model:r,appliedCount:n}}(r,o.recommendation.preset);d.appliedCount>0&&(h.current=r,a(d.model)),u({phase:"success",recommendation:o.recommendation,appliedCount:d.appliedCount})}catch(e){if(i!==p.current)return;u({phase:"error",message:e instanceof Error?e.message:String(e)})}},[c.phase,r,a,t.baseUrl,e]),v=(()=>{if("success"!==c.phase)return null;let{recommendation:t,appliedCount:r}=c,n=r>0?d("models.catalogFilled",{count:r}):d("models.catalogNoEmptyFields");if("unreliable"===t.price.status){let e="no-exact-match"===t.price.reason?d("models.catalogNoExactMatch"):d("models.catalogPriceUnreliable");return`${n} \xb7 ${e}`}let i="provider"===t.price.method?d("models.catalogPriceProvider",{provider:t.price.providerName??t.price.providerId??e}):"base-url"===t.price.method?d("models.catalogPriceBaseUrl",{provider:t.price.providerName??t.price.providerId??e}):d("models.catalogPriceConsensus",{support:t.price.support,total:t.price.total});return`${n} \xb7 ${i}`})(),b="error"===c.phase?c.message:v,y="error"===c.phase?"#ef4444":"success"===c.phase&&"unreliable"===c.recommendation.price.status?"#d97706":"var(--text-dim)";return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(oB,{children:d("i18n.model")}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[m&&(0,n.jsx)("span",{title:m,style:{maxWidth:260,height:24,padding:"0 8px",border:`1px solid ${"error"===l.phase?"#fecaca":"success"===l.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===l.phase?"#fee2e2":"success"===l.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:m}),(0,n.jsxs)("button",{onClick:g,disabled:!r.id.trim()||"testing"===l.phase,title:d("i18n.testConnection"),style:{height:24,padding:"0 8px",background:"success"===l.phase?"#16a34a":"none",border:`1px solid ${"success"===l.phase?"#16a34a":"var(--border)"}`,borderRadius:4,color:"success"===l.phase?"#fff":r.id.trim()&&"testing"!==l.phase?"var(--text-muted)":"var(--text-dim)",cursor:r.id.trim()&&"testing"!==l.phase?"pointer":"not-allowed",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",gap:5},children:["success"===l.phase&&(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===l.phase?d("i18n.checking"):"success"===l.phase?d("common.ok"):d("i18n.test")]}),(0,n.jsx)("button",{onClick:s,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:d("i18n.remove")})]})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,n.jsx)(oP,{label:"ID *",children:(0,n.jsx)(oF,{value:r.id,onChange:e=>f("id",e),placeholder:"model-id",mono:!0})}),(0,n.jsx)(oP,{label:"Name",children:(0,n.jsx)(oF,{value:r.name??"",onChange:e=>f("name",e||void 0),placeholder:"Display name"})})]}),(0,n.jsxs)("div",{style:{padding:"10px 0",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,n.jsx)("button",{onClick:()=>void x(),disabled:!r.id.trim()||"loading"===c.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:r.id.trim()&&"loading"!==c.phase?"var(--text-muted)":"var(--text-dim)",cursor:r.id.trim()&&"loading"!==c.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===c.phase?d("models.catalogFilling"):d("models.catalogFill")}),(0,n.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:d("models.catalogSource")})]}),(0,n.jsxs)("div",{"aria-live":"polite",style:{marginTop:6,height:20,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:y,fontSize:10},children:[(0,n.jsx)("span",{title:b??void 0,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b}),h.current&&(0,n.jsx)("button",{onClick:()=>{let e=h.current;e&&(h.current=null,a(e),u({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:d("models.catalogUndo")})]})]}),(0,n.jsx)(oP,{label:"API override",children:(0,n.jsx)(oH,{value:r.api??"",onChange:e=>f("api",e||void 0),options:oA})}),(0,n.jsxs)(oP,{label:"Headers",children:[(0,n.jsx)(oG,{headers:r.headers,onChange:e=>f("headers",e)}),(0,n.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,n.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,n.jsx)(oO,{label:"Reasoning / thinking",checked:r.reasoning??!1,onChange:e=>f("reasoning",e||void 0)}),(0,n.jsx)(oO,{label:"Image input",checked:r.input?.includes("image")??!1,onChange:e=>f("input",e?["text","image"]:void 0)})]}),r.reasoning&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oO,{label:"DeepSeek thinking compat",checked:r.compat?.thinkingFormat==="deepseek",onChange:e=>a(function(e,t){if(t)return{...e,compat:{...e.compat??{},...oJ}};if(!e.compat)return e;let r={...e.compat};return delete r.thinkingFormat,delete r.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(r).length?r:void 0}}(r,e))}),(0,n.jsx)(oO,{label:"Use 'developer' role for the system prompt (disable if server rejects it)",checked:!1!==({...t.compat??{},...r.compat??{}}).supportsDeveloperRole,onChange:e=>a({...r,compat:{...r.compat??{},supportsDeveloperRole:e}})}),(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,n.jsx)(oB,{children:"Thinking level map"}),r.thinkingLevelMap&&(0,n.jsx)("button",{onClick:()=>f("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,n.jsx)(oV,{value:r.thinkingLevelMap,onChange:e=>f("thinkingLevelMap",e)})]})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,n.jsx)(oP,{label:"Context window (tokens)",children:(0,n.jsx)(oD,{value:void 0!==r.contextWindow?String(r.contextWindow):"",onChange:e=>f("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,n.jsx)(oP,{label:"Max output tokens",children:(0,n.jsx)(oD,{value:void 0!==r.maxTokens?String(r.maxTokens):"",onChange:e=>f("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(oB,{children:"Cost (per million tokens)"}),(0,n.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8},children:["input","output","cacheRead","cacheWrite"].map(e=>(0,n.jsx)(oP,{label:e,children:(0,n.jsx)(oD,{value:r.cost?.[e]!==void 0?String(r.cost[e]):"",onChange:t=>{let n;return n=parseFloat(t),void a({...r,cost:{...r.cost??{},[e]:isNaN(n)?void 0:n}})},placeholder:"0"})},e))})]})]})}let oZ={checking:"relogin.checking",recovered:"relogin.recovered","still-failing":"relogin.stillFailing",unknown:"relogin.unknown"};function oX({provider:e,onRefresh:t,relogin:r}){let a=r?.onLoginSucceeded,[s,l]=(0,i.useState)({phase:"idle"}),{t:o}=(0,R.s)(),[d,c]=(0,i.useState)(""),u=(0,i.useRef)(null),p=(0,i.useRef)(!1),h=(0,i.useRef)(null),f=(0,i.useRef)(null),m=void 0!==r;(0,i.useEffect)(()=>{m&&f.current?.focus()},[m]),(0,i.useEffect)(()=>{("auth"===s.phase||"prompt"===s.phase)&&setTimeout(()=>h.current?.focus(),50)},[s.phase]),(0,i.useEffect)(()=>{l({phase:"idle"}),c(""),u.current?.close(),u.current=null},[e.id]),(0,i.useEffect)(()=>()=>{u.current?.close()},[]);let g=(0,i.useCallback)(()=>{u.current?.close(),p.current||(p.current=!0,c(""),l({phase:"success"}),t(),a?.())},[t,a]),x=(0,i.useCallback)(()=>{u.current?.close(),p.current=!1,l({phase:"connecting"}),c("");let t=new EventSource(`/api/auth/login/${encodeURIComponent(e.id)}`);u.current=t,t.onmessage=e=>{let r=JSON.parse(e.data);"auth"===r.type?(l({phase:"auth",url:r.url,instructions:r.instructions??null,token:r.token}),on(r.url)):"device_code"===r.type?(l({phase:"device_code",userCode:r.userCode,verificationUri:r.verificationUri,intervalSeconds:r.intervalSeconds??null,expiresInSeconds:r.expiresInSeconds??null}),on(r.verificationUri)):"prompt_request"===r.type?l({phase:"prompt",message:r.message,placeholder:r.placeholder??null,token:r.token}):"select_request"===r.type?l({phase:"select",message:r.message,options:r.options??[],token:r.token}):"progress"===r.type?l({phase:"progress",message:r.message}):"success"===r.type?g():"error"===r.type?(t.close(),l({phase:"error",message:r.message})):"cancelled"===r.type&&(t.close(),l({phase:"idle"}))},t.onerror=()=>{t.close(),l(e=>"success"===e.phase||"auth"===e.phase||"prompt"===e.phase||"select"===e.phase?e:{phase:"error",message:"Connection lost"})}},[e.id,g]),v=(0,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(e.id)}`,{method:"POST"}),l({phase:"idle"}),t()},[e.id,t]),b=(0,i.useCallback)(async(t,r,n)=>{l({phase:"progress",message:n});try{let n=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:r})}),i=await n.json().catch(()=>({}));if(!n.ok)return void l({phase:"error",message:i.error??`Server error ${n.status}`});if(c(""),"success"===i.state)return void g();u.current?.readyState===EventSource.CLOSED&&l({phase:"error",message:"Connection lost. Start the login again."})}catch(e){l({phase:"error",message:e instanceof Error?e.message:"Network error"})}},[e.id,g]),y=(0,i.useCallback)(async(e,t)=>{t.trim()&&await b(e,t.trim(),"Verifying…")},[b]),w=(0,i.useCallback)(async(e,t)=>{await b(e,t,"Continuing…")},[b]),k="connecting"===s.phase||"progress"===s.phase||"auth"===s.phase||"device_code"===s.phase||"prompt"===s.phase||"select"===s.phase;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(oB,{children:o("i18n.subscription")}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,n.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"#4ade80":"var(--text-dim)"},children:o(e.loggedIn?"i18n.connected":"i18n.notConnected")})]})]}),r&&(0,n.jsxs)("div",{role:"note","aria-label":o("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,n.jsx)(rh,{seed:r.target.seed,size:32,provider:r.target.provider}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0},children:[(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:o("relogin.title")}),(0,n.jsxs)("span",{style:{fontSize:13,fontWeight:600,color:"var(--text)",overflowWrap:"anywhere"},children:[r.target.alias,r.target.masked&&(0,n.jsx)("span",{style:{marginLeft:6,fontSize:11,fontWeight:400,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:r.target.masked})]}),r.target.reason&&(0,n.jsx)("span",{style:{fontSize:12,color:"var(--seed-color-fg-critical-contrast)",lineHeight:1.5,overflowWrap:"anywhere"},children:r.target.reason})]})]}),(0,n.jsxs)("div",{style:{minHeight:48},children:["idle"===s.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:r?o("relogin.guide",{action:o(e.loggedIn?"i18n.relogin":"i18n.login")}):e.loggedIn?"Already connected. You can re-login or disconnect.":`Connect your ${e.name} account.`}),"connecting"===s.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:o("i18n.openingBrowser")}),"select"===s.phase&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:s.message}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s.options.map(e=>(0,n.jsx)("button",{onClick:()=>w(s.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),("auth"===s.phase||"prompt"===s.phase)&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"auth"===s.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.":s.message}),"auth"===s.phase&&(0,n.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:["If the browser window did not open,"," ",(0,n.jsx)("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:"click here to open the login page"}),"."]}),(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsx)("input",{ref:h,value:d,onChange:e=>c(e.target.value),onKeyDown:e=>{"Enter"===e.key&&y(s.token,d)},placeholder:"auth"===s.phase?"Paste the redirect URL or code":s.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,n.jsx)("button",{onClick:()=>y(s.token,d),disabled:!d.trim(),style:{padding:"6px 12px",background:d.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:d.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:d.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,flexShrink:0},children:o("i18n.submit")})]})]}),"device_code"===s.phase&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,n.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:s.userCode}),(0,n.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,n.jsx)("a",{href:s.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:s.verificationUri}),s.expiresInSeconds?` Expires in ${Math.ceil(s.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===s.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:s.message}),"success"===s.phase&&(r?(0,n.jsxs)("div",{role:"status",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:o("relogin.done")}),r.outcome&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"recovered"===r.outcome?"var(--seed-color-fg-positive-contrast)":"still-failing"===r.outcome?"var(--seed-color-fg-critical-contrast)":"var(--text-muted)"},children:o(oZ[r.outcome],{account:r.target.alias})})]}):(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:o("i18n.connectedSuccessfully")})),"error"===s.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:s.message})]}),(0,n.jsx)("div",{style:{display:"flex",gap:8},children:k?(0,n.jsx)("button",{onClick:()=>{u.current?.close(),l({phase:"idle"})},style:{padding:"5px 12px",background:"none",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:o("i18n.cancel")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{ref:f,onClick:x,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:o(e.loggedIn?"i18n.relogin":"i18n.login")}),e.loggedIn&&!r&&(0,n.jsx)("button",{onClick:v,style:{padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:"pointer",fontSize:12},children:o("i18n.disconnect")})]})})]})}function oQ({provider:e,onRefresh:t}){let[r,a]=(0,i.useState)(""),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),{t:f}=(0,R.s)();(0,i.useEffect)(()=>{a(""),u(null),h(!1)},[e.id]);let m=(0,i.useCallback)(async()=>{if(r.trim()){l(!0),u(null),h(!1);try{let n=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:r.trim()})}),i=await n.json();!n.ok||i.error?u(i.error??`HTTP ${n.status}`):(a(""),h(!0),setTimeout(()=>h(!1),2e3),t())}catch(e){u(String(e))}finally{l(!1)}}},[r,e.id,t]),g=(0,i.useCallback)(async()=>{d(!0),u(null);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),n=await r.json();!r.ok||n.error?u(n.error??`HTTP ${r.status}`):t()}catch(e){u(String(e))}finally{d(!1)}},[e.id,t]);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(oB,{children:"API Key"}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,n.jsx)("span",{style:{fontSize:11,color:e.configured?"#4ade80":"var(--text-dim)"},children:f(e.configured?"i18n.configured":"i18n.notConfigured")})]})]}),(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.configured?"API key is stored. Enter a new key below to replace it, or disconnect to remove it.":`Enter your ${e.displayName} API key to enable ${e.modelCount} model${1!==e.modelCount?"s":""}.`}),(0,n.jsx)(oP,{label:"API Key",children:(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsx)(o_,{value:r,onChange:a,onKeyDown:e=>{"Enter"===e.key&&r.trim()&&m()},placeholder:e.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,n.jsxs)("button",{onClick:m,disabled:s||!r.trim()||p,style:{padding:"6px 12px",background:p?"#16a34a":r.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:p?"#fff":r.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:s||!r.trim()||p?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[p&&(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),f(p?"i18n.saved":s?"i18n.saving":"i18n.save")]})]})}),c&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:c}),e.configured&&(0,n.jsx)("button",{onClick:g,disabled:o,style:{alignSelf:"flex-start",padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:o?"not-allowed":"pointer",fontSize:12},children:f(o?"i18n.removing":"i18n.disconnect")})]})}function o0({id:e,size:t}){let r=oz[e];if(!r){let r=e.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,n.jsx)("span",{"aria-hidden":"true",style:{width:t,height:t,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*t)),fontWeight:700,lineHeight:1},children:r})}return r.hasColor?(0,n.jsx)(r.Icon,{size:t}):(0,n.jsx)(r.Icon,{size:t,style:{color:"var(--text-muted)"}})}function o1({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:r,onSelectApiKey:a,onAddCustom:s,onClose:l}){let[o,d]=(0,i.useState)(""),{t:c}=(0,R.s)(),u=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let p=o.trim().toLowerCase(),h=e.filter(e=>!e.loggedIn&&(!p||e.name.toLowerCase().includes(p))),f=t.filter(e=>!e.configured&&(!p||e.displayName.toLowerCase().includes(p)||e.id.toLowerCase().includes(p))),m=!p||"custom".includes(p)||"openai-compatible".includes(p)||"anthropic-compatible".includes(p),g=h.length+f.length+ +!!m,x={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,n.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&l()},children:(0,n.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,n.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,n.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,n.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,n.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,n.jsx)("input",{ref:u,value:o,onChange:e=>d(e.target.value),onKeyDown:e=>{"Escape"===e.key&&l()},placeholder:c("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===g?(0,n.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:c("i18n.noProviders")}):(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[m&&(0,n.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.custom")}),m&&(0,n.jsxs)("button",{onClick:()=>{s(),l()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:c("i18n.customEndpoint")})]}),(0,n.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,n.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,n.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,n.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),h.length>0&&(0,n.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!m,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.subscriptions")}),h.map(e=>(0,n.jsxs)("button",{onClick:()=>{r(e.id),l()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,n.jsx)(o0,{id:e.id,size:28})]},e.id)),f.length>0&&(0,n.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(h.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),f.map(e=>(0,n.jsxs)("button",{onClick:()=>{a(e.id),l()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,n.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[e.modelCount," models"]})]}),(0,n.jsx)(o0,{id:e.id,size:28})]},e.id))]})})]})})}function o2({cwd:e,onClose:t,embedded:r=!1,onModelsChanged:a,relogin:s}){let l=W(),{t:o}=(0,R.s)(),[d,c]=(0,i.useState)({providers:{}}),[u,p]=(0,i.useState)(!0),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(s?{type:"oauth",providerId:s.target.provider}:{type:"roles"}),[w,k]=(0,i.useState)([]),[j,S]=(0,i.useState)([]),[C,N]=(0,i.useState)(!1),I=(0,i.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>k(e.providers)).catch(()=>{})},[]),T=(0,i.useCallback)(()=>{fetch("/api/auth/all-providers").then(e=>e.json()).then(e=>S(e.providers)).catch(()=>{})},[]),M=(0,i.useCallback)(()=>{I(),T()},[I,T]);(0,i.useEffect)(()=>{fetch("/api/models-config").then(e=>e.json()).then(e=>{c(e.providers?e:{...e,providers:{}})}).catch(()=>c({providers:{}})).finally(()=>p(!1)),M()},[M]);let $=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;d.providers?.[e];)e=`new-provider-${t++}`;c(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),y({type:"provider",name:e})},[d.providers]),E=(0,i.useCallback)((e,t)=>{c(r=>({...r,providers:{...r.providers??{},[e]:t}}))},[]),L=(0,i.useCallback)((e,t)=>{c(r=>{let n=Object.entries(r.providers??{}),i=n.findIndex(([t])=>t===e);return -1===i?r:(n[i]=[t,n[i][1]],{...r,providers:Object.fromEntries(n)})}),y(r=>r?"provider"===r.type&&r.name===e?{type:"provider",name:t}:"model"===r.type&&r.providerName===e?{...r,providerName:t}:r:r)},[]),z=(0,i.useCallback)(e=>{c(t=>{let r={...t.providers??{}};return delete r[e],{...t,providers:r}}),c(e=>{let t=Object.keys(e.providers??{});return y(t.length>0?{type:"provider",name:t[0]}:null),e})},[]),A=(0,i.useCallback)(e=>{c(t=>{let r=t.providers?.[e]??{},n=[...r.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...r,models:n}}}}),c(t=>{let r=(t.providers?.[e]?.models?.length??1)-1;return y({type:"model",providerName:e,index:r}),t})},[]),P=(0,i.useCallback)((e,t)=>{c(r=>{let n=r.providers?.[e]??{},i=[...n.models??[]],a=new Set(i.map(e=>e.id));for(let e of t)a.has(e.id)||(a.add(e.id),i.push({id:e.id,name:e.name}));return{...r,providers:{...r.providers??{},[e]:{...n,models:i}}}})},[]),F=(0,i.useCallback)((e,t,r)=>{c(n=>{let i=n.providers?.[e]??{},a=[...i.models??[]];return a[t]=r,{...n,providers:{...n.providers??{},[e]:{...i,models:a}}}})},[]),_=(0,i.useCallback)((e,t)=>{c(r=>{let n=r.providers?.[e]??{},i=[...n.models??[]];return i.splice(t,1),{...r,providers:{...r.providers??{},[e]:{...n,models:i.length?i:void 0}}}}),y({type:"provider",name:e})},[]),D=(0,i.useCallback)(async()=>{f(!0),g(null),v(!1);try{let e=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}),t=await e.json();!e.ok||t.error?g(t.error??`HTTP ${e.status}`):(v(!0),a?.(),setTimeout(()=>v(!1),2e3))}catch(e){g(String(e))}finally{f(!1)}},[d,a]),H=Object.entries(d.providers??{}),O=w.filter(e=>e.loggedIn),B=j.filter(e=>e.configured),U=(()=>{if(!b)return null;if("roles"===b.type)return(0,n.jsx)(or,{cwd:e??null,onRolesChanged:a});if("oauth"===b.type){let e=w.find(e=>e.id===b.providerId);return e?(0,n.jsx)(oX,{provider:e,onRefresh:M,relogin:s?.target.provider===e.id?s:void 0},e.id):null}if("apikey"===b.type){let e=j.find(e=>e.id===b.providerId);return e?(0,n.jsx)(oQ,{provider:e,onRefresh:M},e.id):null}if("provider"===b.type){let e=d.providers?.[b.name];return e?(0,n.jsx)(oU,{name:b.name,provider:e,onChange:e=>E(b.name,e),onRename:e=>L(b.name,e),onDelete:()=>z(b.name),onAddModels:e=>P(b.name,e)},b.name):null}let t=d.providers?.[b.providerName],r=t?.models?.[b.index];return r?(0,n.jsx)(oY,{providerName:b.providerName,provider:t,model:r,onChange:e=>F(b.providerName,b.index,e),onDelete:()=>_(b.providerName,b.index)},`${b.providerName}-${b.index}`):null})();return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{style:{position:r?"relative":"fixed",inset:r?void 0:0,width:"100%",height:"100%",zIndex:r?void 0:1e3,background:r?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{r||e.target!==e.currentTarget||t()},...r?{}:{role:"dialog","aria-modal":!0,"aria-label":o("common.models"),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),t())}},children:(0,n.jsxs)("div",{style:{width:r?"100%":l?"calc(100vw - 16px)":860,maxWidth:r?"none":"calc(100vw - 16px)",height:r?"100%":l?"calc(100dvh - 16px)":"78vh",maxHeight:r?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:r?"none":"1px solid var(--border)",borderRadius:10*!r,display:"flex",flexDirection:"column",boxShadow:r?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:o("common.models")}),(0,n.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.omp/agent/models.yml"})]}),(0,n.jsx)("button",{onClick:t,"aria-label":o("i18n.close"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:l?"column":"row",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{width:l?"100%":210,maxHeight:l?"40vh":void 0,borderRight:l?"none":"1px solid var(--border)",borderBottom:l?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[(0,n.jsxs)("div",{onClick:()=>y({type:"roles"}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:b?.type==="roles"?"var(--bg-selected)":"none"},onMouseEnter:e=>{b?.type!=="roles"&&(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{b?.type!=="roles"&&(e.currentTarget.style.background="none")},children:[(0,n.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,n.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,n.jsx)("circle",{cx:"9",cy:"7",r:"2.2"}),(0,n.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,n.jsx)("circle",{cx:"15",cy:"17",r:"2.2"})]}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1},children:o("roles.title")})]}),(0,n.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),O.map(e=>{let t=b?.type==="oauth"&&b.providerId===e.id;return(0,n.jsxs)("div",{onClick:()=>y({type:"oauth",providerId:e.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,n.jsx)(o0,{id:e.id,size:16}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.id)}),B.map(e=>{let t=b?.type==="apikey"&&b.providerId===e.id;return(0,n.jsxs)("div",{onClick:()=>y({type:"apikey",providerId:e.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,n.jsx)(o0,{id:e.id,size:16}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName})]},e.id)}),(O.length>0||B.length>0)&&H.length>0&&(0,n.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),u?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:o("i18n.loading")}):H.map(([e,t])=>{let r=b?.type==="provider"&&b.name===e,i=t.models??[];return(0,n.jsxs)("div",{style:{marginBottom:2},children:[(0,n.jsxs)("div",{onClick:()=>y({type:"provider",name:e}),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:r?"var(--bg-selected)":"none"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[(0,n.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,n.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,n.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,n.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,n.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,n.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,n.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,n.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,n.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,n.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,n.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,n.jsx)("span",{style:{fontSize:12,fontWeight:r?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})]}),i.map((t,r)=>{let i=b?.type==="model"&&b.providerName===e&&b.index===r;return(0,n.jsxs)("div",{onClick:()=>y({type:"model",providerName:e,index:r}),style:{display:"flex",alignItems:"center",gap:6,padding:"5px 8px 5px 26px",borderRadius:5,cursor:"pointer",background:i?"var(--bg-selected)":"none"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[(0,n.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:t.id?"var(--text-muted)":"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.id||o("i18n.newModel")}),t.reasoning&&(0,n.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"})]},r)}),(0,n.jsx)("div",{onClick:t=>{t.stopPropagation(),A(e)},style:{display:"flex",alignItems:"center",gap:4,padding:"4px 8px 4px 26px",borderRadius:5,cursor:"pointer",color:"var(--text-dim)"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,n.jsxs)("span",{style:{fontSize:11},children:["+ ",o("i18n.model")]})})]},e)})]}),(0,n.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 6px"},children:(0,n.jsxs)("button",{onClick:()=>N(!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:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.color="var(--text-muted)"},children:["+ ",o("i18n.addProvider")]})})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:u?null:U??(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:o("i18n.selectProviderModel")})})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:10,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[m&&(0,n.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:m}),(0,n.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:o("i18n.cancel")}),(0,n.jsxs)("button",{onClick:D,disabled:h||x,style:{position:"relative",padding:"6px 16px",minWidth:92,background:x?"#16a34a":h?"var(--bg-panel)":"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:6,color:x?"#fff":h?"var(--text-muted)":"var(--seed-color-fg-neutral-inverted)",cursor:h||x?"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:x?"saved-pop 0.45s ease":void 0},children:[x&&(0,n.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,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,n.jsx)("span",{children:x?o("i18n.saved"):h?o("i18n.saving"):o("i18n.save")})]})]})]})}),C&&(0,n.jsx)(o1,{oauthProviders:w,apiKeyProviders:j,onSelectOAuth:e=>y({type:"oauth",providerId:e}),onSelectApiKey:e=>y({type:"apikey",providerId:e}),onAddCustom:$,onClose:()=>N(!1)})]})}function o4(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function o5(e){let t=e.sourceInfo?.source,r=e.sourceInfo?.scope;return"user"===r||"user"===t?"global":"project"===r||"project"===t?"project":"path"}function o8(e){let t=o5(e);return"path"===t?t:e.install?.skillsShUrl?`${t} / skills.sh`:t}function o6(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function o3(e){return e?e.slice(0,8):"unknown"}function o7({enabled:e,loading:t,onToggle:r}){let{t:i}=(0,R.s)();return(0,n.jsx)("button",{onClick:r,disabled:t,title:i(e?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),style:{flexShrink:0,width:40,height:22,borderRadius:11,border:"none",padding:0,cursor:t?"wait":"pointer",background:e?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none"},children:(0,n.jsx)("span",{style:{position:"absolute",top:3,left:e?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 o9({skill:e,cwd:t,onToggle:r,toggling:i,saveError:a,updateStatus:s,checkingUpdate:l,updating:o,updateError:d,onCheckUpdate:c,onUpdate:u}){let{t:p}=(0,R.s)(),h=o5(e),f=!e.disableModelInvocation;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7},children:[(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===h?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===h?"rgba(99,102,241,0.8)":"var(--text-dim)"},children:h}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:function(e){if("project"===h&&e.startsWith(t)){let r=e.slice(t.length).replace(/^[/\\]/,"");return`./${r}`}return o4(e)}(e.filePath)}),(0,n.jsx)(o7,{enabled:f,loading:i,onToggle:()=>r(e)})]}),(0,n.jsxs)("div",{style:{minHeight:16,display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,flexWrap:"wrap",textAlign:"right"},children:[!f&&(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:p("i18n.hiddenButInvocable")}),a&&(0,n.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:a})]})]}),e.install?.skillsShUrl&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Source"}),(0,n.jsx)("a",{href:e.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:e.install.skillsShUrl,style:{display:"flex",alignItems:"center",gap:8,width:"fit-content",maxWidth:"100%",color:"var(--accent)",textDecoration:"none"},children:(0,n.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})]}),e.install&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Version"}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text-muted)"},children:o3(s?.currentVersion??e.install.versionHash)}),e.install.canCheckForUpdates&&(0,n.jsx)("button",{onClick:c,disabled:l||o,style:{padding:"4px 9px",border:"1px solid var(--border)",borderRadius:5,background:"none",color:"var(--text-muted)",cursor:l||o?"not-allowed":"pointer",opacity:l||o?.5:1,fontSize:11},children:p("i18n.check")}),s?.state==="update-available"&&(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"#d97706"},children:o3(s.latestVersion)}),(l||s&&"update-available"!==s.state)&&(0,n.jsx)("span",{style:{fontSize:12,color:l?"var(--accent)":s?.state==="up-to-date"?"#16a34a":s?.state==="error"?"#ef4444":"var(--text-dim)"},children:l?p("i18n.checking"):s?.state==="up-to-date"?p("i18n.upToDate"):s?.state==="unsupported"?p("i18n.automaticChecksUnavailable"):s?.message||p("i18n.checkFailed")}),s?.state==="update-available"&&(0,n.jsx)("button",{onClick:u,disabled:o||l,style:{padding:"4px 10px",border:"none",borderRadius:5,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:o||l?"not-allowed":"pointer",opacity:o||l?.5:1,fontSize:11,fontWeight:600},children:p(o?"i18n.updating":"i18n.update")})]}),d&&(0,n.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:d})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Name"}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:14,color:"var(--text)"},children:e.name})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Description"}),(0,n.jsx)("span",{style:{fontSize:14,color:"var(--text-muted)",lineHeight:1.6},children:e.description})]})]})}function de({cwd:e,installedPackages:t,projectResourcesLoaded:r,onInstalled:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)(""),[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(new Set),[w,k]=(0,i.useState)("global"),j=(0,i.useRef)(null);(0,i.useEffect)(()=>{j.current?.focus()},[]);let S=(0,i.useCallback)(async e=>{if(e.trim()){p(!0),f(null),c([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),r=await t.json();if(r.error)return void f(r.error);c(r.results??[]),0===(r.results??[]).length&&f("No skills found")}catch(e){f(String(e))}finally{p(!1)}}},[]),C=(0,i.useCallback)(async t=>{g(t),v(null);try{let r=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:w,cwd:e})}),n=await r.json();if(!r.ok||n.error)return void v(n.error??`HTTP ${r.status}`);y(e=>new Set(e).add(`${w}:${t}`)),a()}catch(e){v(String(e))}finally{g(null)}},[a,w,e]),N="global"===w?"~/.claude/skills/":`${o4(e)}/.claude/skills/`;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,n.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:s("i18n.addSkill")}),(0,n.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,n.jsx)("input",{ref:j,value:l,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&S(l)},placeholder:s("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,n.jsx)("button",{onClick:()=>S(l),disabled:u||!l.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:u||!l.trim()?"not-allowed":"pointer",opacity:u||!l.trim()?.5:1,flexShrink:0},children:u?s("i18n.searching"):s("i18n.search")})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,n.jsx)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(e=>(0,n.jsx)("button",{onClick:()=>{("global"===e||r)&&k(e)},disabled:"project"===e&&!r,title:"project"!==e||r?void 0:s("trust.projectScopeUnavailable"),style:{padding:"3px 10px",border:"none",cursor:"project"!==e||r?"pointer":"not-allowed",background:w===e?"var(--bg-selected)":"none",color:w===e?"var(--text)":"var(--text-dim)",fontWeight:w===e?600:400,opacity:"project"!==e||r?1:.45,borderRight:"global"===e?"1px solid var(--border)":"none"},children:e},e))}),(0,n.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",N]})]}),h&&(0,n.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:h}),x&&(0,n.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:x})]}),d.length>0?(0,n.jsx)("div",{style:{flex:1,overflowY:"auto"},children:d.map(e=>{let r=t[w].has(e.package)||b.has(`${w}:${e.package}`),i=m===e.package,a=e.package.indexOf("@"),l=a>-1?e.package.slice(0,a):e.package,o=a>-1?e.package.slice(a+1):null;return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:o??l}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:l}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,n.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,n.jsx)("button",{onClick:()=>!r&&!i&&C(e.package),disabled:r||i||null!==m,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:5,border:"1px solid var(--border)",cursor:r||i||null!==m?"not-allowed":"pointer",background:r?"rgba(34,197,94,0.1)":"none",color:r?"#16a34a":i?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:r?`✓ ${s("i18n.installed")}`:i?s("i18n.installing"):s("i18n.install")})]},e.package)})}):!h&&!u&&(0,n.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:["Search"," ",(0,n.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 dt({cwd:e,onClose:t,embedded:r=!1}){let a=W(),{t:s}=(0,R.s)(),[l,o]=(0,i.useState)([]),[d,c]=(0,i.useState)(!0),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(new Set),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(!1),[w,k]=(0,i.useState)({}),[j,S]=(0,i.useState)(new Set),[C,N]=(0,i.useState)(!1),[I,T]=(0,i.useState)(null),[M,$]=(0,i.useState)(null),[E,L]=(0,i.useState)(!0),[z,A]=(0,i.useState)({}),P=(0,i.useCallback)(async()=>{c(!0),p(null);try{let t=await fetch(`/api/skills?cwd=${encodeURIComponent(e)}`),r=await t.json();if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);let n=r.skills??[];if(o(n),L(r.projectResourcesLoaded??!0),n.length>0&&!h){let e=n.find(e=>!e.disableModelInvocation)??n[0];f(e.filePath),e.disableModelInvocation&&A(t=>({...t,[o8(e)]:!0}))}return n}catch(e){return p(String(e)),[]}finally{c(!1)}},[e,h]);(0,i.useEffect)(()=>{k({}),$(null),P()},[e]);let F=(0,i.useCallback)(async t=>{let r=(t?[t]:l.filter(e=>!!e.install)).map(o6).filter(e=>!!e);if(0!==r.length){$(null),S(e=>new Set([...e,...r])),t||N(!0);try{let r=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t?.install?.package,scope:t?.install?.scope})}),n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);k(e=>{let t={...e};for(let e of n.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){$(e instanceof Error?e.message:String(e))}finally{S(e=>{let t=new Set(e);for(let e of r)t.delete(e);return t}),t||N(!1)}}},[e,l]),_=(0,i.useCallback)(async t=>{if(!t.install)return;let r=o6(t);T(r),$(null);try{let n=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t.install.package,scope:t.install.scope})}),i=await n.json();if(!n.ok||i.error||!i.success)throw Error(i.error??`HTTP ${n.status}`);await P();let a=i.skill?.install?.versionHash;k(e=>({...e,[r]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:a,latestVersion:a}}))}catch(e){$(e instanceof Error?e.message:String(e))}finally{T(null)}},[e,P]),D=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;g(t=>new Set(t).add(e.filePath)),v(null);try{let r=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),n=await r.json();if(!r.ok||n.error)return void v(n.error??`HTTP ${r.status}`);o(r=>r.map(r=>r.filePath===e.filePath?{...r,disableModelInvocation:t}:r)),t&&A(t=>({...t,[o8(e)]:!0}))}catch(e){v(String(e))}finally{g(t=>{let r=new Set(t);return r.delete(e.filePath),r})}},[]),H=l.find(e=>e.filePath===h)??null;return(0,n.jsx)("div",{style:{position:r?"relative":"fixed",inset:r?void 0:0,width:"100%",height:"100%",zIndex:r?void 0:1e3,background:r?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{r||e.target!==e.currentTarget||t()},children:(0,n.jsxs)("div",{style:{width:r?"100%":a?"calc(100vw - 16px)":860,maxWidth:r?"none":"calc(100vw - 16px)",height:r?"100%":a?"calc(100dvh - 16px)":"78vh",maxHeight:r?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:r?"none":"1px solid var(--border)",borderRadius:10*!r,display:"flex",flexDirection:"column",boxShadow:r?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:s("common.skills")}),(0,n.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o4(e)})]}),(0,n.jsx)("button",{onClick:t,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!E&&(0,n.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:s("trust.skillsNotLoaded")}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:a?"column":"row",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{width:a?"100%":210,maxHeight:a?"40vh":void 0,borderRight:a?"none":"1px solid var(--border)",borderBottom:a?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:d?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:s("i18n.loading")}):u?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#f87171"},children:u}):0===l.length?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:s("i18n.noSkills")}):(()=>{let e=[];for(let{label:t,matches:r}of[{label:"project / skills.sh",matches:e=>"project"===o5(e)&&!!e.install?.skillsShUrl},{label:"project",matches:e=>"project"===o5(e)&&!e.install?.skillsShUrl},{label:"global / skills.sh",matches:e=>"global"===o5(e)&&!!e.install?.skillsShUrl},{label:"global",matches:e=>"global"===o5(e)&&!e.install?.skillsShUrl},{label:"path",matches:e=>"path"===o5(e)}]){let n=l.filter(r);n.length>0&&e.push({label:t,skills:n})}let t=e=>{let t,r,i=!b&&h===e.filePath,a=e.disableModelInvocation;return(0,n.jsxs)("div",{onClick:()=>{f(e.filePath),y(!1)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:i?"var(--bg-selected)":"none"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[(0,n.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:a?"var(--border)":"var(--accent)",boxShadow:a?"none":"0 0 4px var(--accent)",transition:"background 0.15s, box-shadow 0.15s"}}),(0,n.jsx)("span",{style:{fontSize:12,fontWeight:i?600:400,color:a?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(r=(t=o6(e))?w[t]:void 0,r?.state!=="update-available"?null:(0,n.jsx)("span",{title:s("i18n.updateAvailable"),style:{color:"#d97706",fontSize:13,lineHeight:1,flexShrink:0},children:"↑"}))]},e.filePath)};return e.map(({label:e,skills:r})=>{let i=r.filter(e=>!e.disableModelInvocation),a=r.filter(e=>e.disableModelInvocation),l=z[e]??!1;return(0,n.jsxs)("div",{style:{marginBottom:6},children:[(0,n.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em"},children:e}),i.map(t),a.length>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{onClick:()=>A(t=>({...t,[e]:!l})),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,n.jsx)("span",{style:{fontSize:8},children:l?"▾":"▸"}),s("i18n.dormant")," (",a.length,")"]}),l&&a.map(t)]})]},e)})})()}),(0,n.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,n.jsxs)("div",{onClick:()=>y(!0),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:b?"var(--bg-selected)":"none",color:b?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:e=>{b||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{b||(e.currentTarget.style.background="none")},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,n.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s("i18n.addSkill")]})})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,n.jsx)(de,{cwd:e,projectResourcesLoaded:E,installedPackages:{global:new Set(l.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(l.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{P()}}):d?null:H?(0,n.jsx)(o9,{skill:H,cwd:e,onToggle:D,toggling:m.has(H.filePath),saveError:x,updateStatus:o6(H)?w[o6(H)]:void 0,checkingUpdate:!!o6(H)&&j.has(o6(H)),updating:I===o6(H),updateError:M,onCheckUpdate:()=>void F(H),onUpdate:()=>void _(H)},H.filePath):(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:s("i18n.selectSkill")})})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[l.some(e=>!!e.install)&&(0,n.jsx)("button",{onClick:()=>void F(),disabled:C||null!==I,style:{padding:"6px 12px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:C||null!==I?"not-allowed":"pointer",opacity:C||null!==I?.5:1,fontSize:12},children:C?s("i18n.checking"):s("i18n.checkUpdates")}),Object.values(w).filter(e=>"update-available"===e.state).length>0&&(0,n.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(w).filter(e=>"update-available"===e.state).length," ",1===Object.values(w).filter(e=>"update-available"===e.state).length?s("i18n.update"):s("i18n.updates")]})]}),(0,n.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:s("i18n.close")})]})]})})}let dr="global";function dn(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function di(e){let t=e.trim().match(/^\$?\s*omp\s+plugin\s+(?:add|install)\s+(\S+)\s*$/);return t?.[1]??e}function da(e){return`${e.scope}\0${e.source}`}function ds(e,t){if(e.disabled)return t("i18n.disabled");let r=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t("i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t("i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t("i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t("i18n.themeShort")}):""].filter(Boolean);return r.length?r.join(" \xb7 "):t("i18n.noResources")}function dl(e,t){let r=[];return e.version&&r.push(t("i18n.installedVersion",{version:e.version})),e.configuredVersion&&r.push(t("i18n.configuredVersion",{version:e.configuredVersion})),r.length?r.join(" \xb7 "):t("i18n.unknown")}function dd(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function dc({pkg:e}){let{t}=(0,R.s)(),r=[["extension",t("i18n.extensions")],["skill",t("i18n.skills")],["prompt",t("i18n.prompts")],["theme",t("i18n.themes")]].map(([t,r])=>({kind:t,label:r,resources:e.resources.filter(e=>e.kind===t)})).filter(e=>e.resources.length>0);return 0===r.length?(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:t(e.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:r.map((e,t)=>(0,n.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,n.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function du({scope:e}){return(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===e?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===e?"rgba(99,102,241,0.85)":"var(--text-dim)"},children:e})}function dp(e,t){return{padding:"6px 12px",background:t?"rgba(239,68,68,0.08)":"none",border:"1px solid var(--border)",borderRadius:6,color:t?"#ef4444":"var(--text-muted)",cursor:e?"not-allowed":"pointer",fontSize:12,opacity:e?.5:1}}function dh({enabled:e,loading:t,onToggle:r,label:i}){return(0,n.jsx)("button",{type:"button",onClick:r,disabled:t,title:i,"aria-label":i,"aria-pressed":e,style:{flexShrink:0,width:40,height:22,borderRadius:11,border:"none",padding:0,cursor:t?"wait":"pointer",background:e?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none",opacity:t?.65:1},children:(0,n.jsx)("span",{style:{position:"absolute",top:3,left:e?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 df({installDir:e,source:t,busy:r,actionError:a,onSourceChange:s,onInstall:l}){let{t:o}=(0,R.s)(),d=(0,i.useRef)(null);return(0,i.useEffect)(()=>{d.current?.focus()},[]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:660,minHeight:"100%"},children:[(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,n.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:o("i18n.addPlugin")}),(0,n.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,n.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",style:{flexShrink:0},children:[(0,n.jsx)("path",{fill:"#000",fillRule:"evenodd",d:"M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"}),(0,n.jsx)("path",{fill:"#000",d:"M517.36 400H634.72V634.72H517.36Z"})]}),"oh-my-pi plugins"]})]}),e&&(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:dn(e)})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,n.jsx)("label",{htmlFor:"plugin-source",style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Source"}),(0,n.jsx)("input",{id:"plugin-source",ref:d,value:t,onChange:e=>s(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),r=di(t);r!==t&&(e.preventDefault(),s(r))},onBlur:e=>s(di(e.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:e=>{"Enter"===e.key&&t.trim()&&!r&&l()}})]}),(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:(0,n.jsx)("button",{type:"button",onClick:l,disabled:r||!t.trim(),style:{...dp(r||!t.trim()),background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",borderColor:"transparent"},children:o(r?"i18n.installing":"i18n.install")})}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Examples"}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:["@scope/omp-plugin","github:user/repo","pkg[feature]"].map(e=>(0,n.jsx)("button",{type:"button",onClick:()=>s(e),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:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-panel)",e.currentTarget.style.color="var(--text-dim)"},children:e},e))})]}),a&&(0,n.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:a})]})}function dm({pkg:e,cwd:t,busyKey:r,actionError:i,actionMessage:a,sessionId:s,onAction:l,onReloadSession:o}){let{t:d}=(0,R.s)(),c=da(e),u=r?.endsWith(c)??!1,p="reload"===r,h=!e.disabled;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20,maxWidth:680},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,minWidth:0,flexWrap:"wrap"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:180,flex:1},children:[(0,n.jsx)(dh,{enabled:h,loading:u||p,onToggle:()=>l(e.disabled?"enable":"disable",e),label:d(e.disabled?"i18n.enablePackage":"i18n.disablePackage")}),(0,n.jsx)(du,{scope:e.scope}),e.disabled?(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:d("i18n.disabled")}):e.filtered&&(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:d("i18n.filtered")}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source})]}),(0,n.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[(0,n.jsx)("button",{onClick:()=>l("update",e),disabled:u||p,style:dp(u||p),children:d(r===`update:${c}`?"i18n.updating":"i18n.update")}),(0,n.jsx)("button",{onClick:o,disabled:!s||p||u,style:dp(!s||p||u),title:d(s?"i18n.reloadSessionHint":"i18n.openSessionToReload"),children:d(p?"i18n.reloading":"i18n.reloadSession")}),(0,n.jsx)("button",{onClick:()=>l("remove",e),disabled:u||p,style:dp(u||p,!0),children:d(r===`remove:${c}`?"i18n.removing":"i18n.remove")})]})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.status")}),(0,n.jsx)("div",{style:{color:dd(e.status),textTransform:"capitalize"},children:e.status}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.version")}),(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:dl(e,d)}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.package")}),(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.packageName??d("i18n.unknown")}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.resources")}),(0,n.jsx)("div",{style:{color:"var(--text-muted)"},children:ds(e,d)}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.installedPath")}),(0,n.jsx)("div",{style:{color:e.installedPath?"var(--text-muted)":"#ef4444",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.installedPath?dn(e.installedPath):d("i18n.notFound")}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.cwd")}),(0,n.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:dn(t)})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)"},children:d("i18n.resolvedResources")}),(0,n.jsx)(dc,{pkg:e})]}),a&&(0,n.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:a}),i&&(0,n.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:i})]})}function dg({cwd:e,sessionId:t,onClose:r,onReloaded:a,embedded:s=!1}){let l=W(),{t:o}=(0,R.s)(),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!0),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(""),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),I=(0,i.useMemo)(()=>d?.packages??[],[d?.packages]),T=I.find(e=>da(e)===m)??null,M=d?.projectResourcesLoaded??!0,$=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:I.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[I]),E=(0,i.useCallback)(async()=>{p(!0),f(null);try{let t=await fetch(`/api/plugins?cwd=${encodeURIComponent(e)}`),r=await t.json();if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);c(r),v(e=>0===r.packages.length||e),g(e=>e&&r.packages.some(t=>da(t)===e)?e:r.packages[0]?da(r.packages[0]):null)}catch(e){f(e instanceof Error?e.message:String(e))}finally{p(!1)}},[e]);(0,i.useEffect)(()=>{E()},[E]);let L=(0,i.useCallback)(async(t,r)=>{let n=da(r);k(`${t}:${n}`),S(null),N(null);try{let n=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:r.source,scope:r.scope,cwd:e})}),i=await n.json();if(!n.ok||i.error)throw Error(i.error??`HTTP ${n.status}`);if(c(i),"remove"===t)g(i.packages[0]?da(i.packages[0]):null),0===i.packages.length&&v(!0),N(o("i18n.packageRemoved"));else{let e={install:o("i18n.packageInstalled"),update:o("i18n.packageUpdated"),disable:o("i18n.packageDisabledRestartRequired"),enable:o("i18n.packageEnabled")};N(e[t])}}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}},[e,o]),z=(0,i.useCallback)(async()=>{let t=di(b).trim();if(!t)return;y(t);let r=`${dr}\0${t}`;k(`install:${r}`),S(null),N(null);try{var n;let i,a,s=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:dr,cwd:e})}),l=await s.json();if(!s.ok||l.error)throw Error(l.error??`HTTP ${s.status}`);c(l);let d=(n=l.packages,a=(i=t.trim()).startsWith("npm:")?i.slice(4):i,n.find(e=>e.scope===dr&&e.source===i)??n.find(e=>e.scope===dr&&e.source===`npm:${a}`)??n.find(e=>e.scope===dr&&e.source.endsWith(i)));g(d?da(d):r),v(!1),y(""),N(o("i18n.packageInstalled"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}},[e,b,o]),A=(0,i.useCallback)(async()=>{if(t){k("reload"),S(null),N(null);try{await sz(t,{type:"reload"}),a?.(),await E(),N(o("i18n.sessionReloaded"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}}},[E,a,t,o]),P=w?.startsWith("install:")??!1;return(0,n.jsx)("div",{style:{position:s?"relative":"fixed",inset:s?void 0:0,width:"100%",height:"100%",zIndex:s?void 0:1e3,background:s?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{s||e.target!==e.currentTarget||r()},children:(0,n.jsxs)("div",{style:{width:s?"100%":l?"calc(100vw - 16px)":860,maxWidth:s?"none":"calc(100vw - 16px)",height:s?"100%":l?"calc(100dvh - 16px)":"76vh",maxHeight:s?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:s?"none":"1px solid var(--border)",borderRadius:8*!s,display:"flex",flexDirection:"column",boxShadow:s?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:o("common.plugins")}),(0,n.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:dn(e)})]}),(0,n.jsx)("button",{onClick:r,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!M&&(0,n.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:o("trust.pluginsNotLoaded")}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:l?"column":"row",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{width:l?"100%":245,maxHeight:l?"40vh":void 0,borderRight:l?"none":"1px solid var(--border)",borderBottom:l?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:u?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:"Loading..."}):h?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#ef4444"},children:h}):0===I.length?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:"No plugins configured"}):$.map(e=>(0,n.jsxs)("div",{style:{marginBottom:6},children:[(0,n.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase"},children:e.scope}),e.packages.map(e=>{let t=da(e),r=!x&&m===t;return(0,n.jsxs)("div",{onClick:()=>{g(t),v(!1),S(null),N(null)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:r?"var(--bg-selected)":"none"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[(0,n.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:dd(e.status)}}),(0,n.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:r?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:ds(e,o)}),(e.version||e.configuredVersion)&&(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:dl(e,o)})]})]},t)})]},e.scope))}),(0,n.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,n.jsxs)("button",{type:"button",onClick:()=>{v(!0),S(null),N(null)},style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,border:"none",width:"100%",cursor:"pointer",background:x?"var(--bg-selected)":"none",color:x?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:e=>{x||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{x||(e.currentTarget.style.background="none")},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,n.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),o("i18n.addPlugin")]})})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:x?(0,n.jsx)(df,{installDir:d?.installDir,source:b,busy:P,actionError:j,onSourceChange:y,onInstall:z}):u?null:T?(0,n.jsx)(dm,{pkg:T,cwd:e,busyKey:w,actionError:j,actionMessage:C,sessionId:t,onAction:L,onReloadSession:A},da(T)):(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:o("i18n.selectPackage")})})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsx)("div",{style:{minWidth:0,flex:1,fontSize:11,color:"var(--text-dim)",overflow:"hidden"},children:d?.diagnostics.length?(0,n.jsxs)("span",{title:d.diagnostics.map(e=>`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`).join("\n"),style:{color:d.diagnostics.some(e=>"error"===e.type)?"#ef4444":"#d97706"},children:[d.diagnostics.length," diagnostic",1===d.diagnostics.length?"":"s"]}):(0,n.jsx)("span",{children:d?`${d.totals.extensions} ext \xb7 ${d.totals.skills} skills \xb7 ${d.totals.prompts} prompts \xb7 ${d.totals.themes} themes`:""})}),(0,n.jsx)("button",{onClick:()=>void E(),disabled:u||null!==w,style:dp(u||null!==w),children:o("i18n.refresh")}),(0,n.jsx)("button",{onClick:r,style:dp(!1),children:o("i18n.close")})]})]})})}var dx=r(13004),dv=r.n(dx);function db(){let[e,t]=(0,i.useState)(null),[r,a]=(0,i.useState)(null),[s,l]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(""),[f,m]=(0,i.useState)(""),g=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/web-access",{cache:"no-store"}),r=await e.json();if(!e.ok||r.error)throw Error(r.error??`HTTP ${e.status}`);t(r),a(null)}catch(e){a(e instanceof Error?e.message:String(e))}},[]);(0,i.useEffect)(()=>{g()},[g]);let x=(0,i.useCallback)(async(e,r={})=>{u(!0),l(null),d(null);try{let n=await fetch("/api/web-access",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,...r})}),i=await n.json();if(!n.ok||i.error)throw Error(i.error??`HTTP ${n.status}`);return t(i),i}catch(e){return l(e instanceof Error?e.message:String(e)),null}finally{u(!1)}},[]),v=(0,i.useCallback)(async()=>{if(p!==f)return void l("The two passwords do not match.");let e=await x("set-password",{password:p});e&&(h(""),m(""),d(`Password saved and password access turned on. The browser will ask for the username "${e.username}" and this password on the next request.`))},[f,p,x]),b=(0,i.useCallback)(async()=>{if(!e)return;let t=await x(e.enabled?"disable":"enable");t&&d(t.enabled?`Password access is on. The browser will ask for the username "${t.username}" and your password on the next request.`:"Password access is off. The stored password is kept and can be switched back on here.")},[x,e]),y=(0,i.useCallback)(async()=>{await x("clear")&&d("The stored password was removed and password access is off.")},[x]);if(!e)return(0,n.jsx)("div",{className:dv().empty,children:r??"Loading password access…"});let w=e.managedByEnvironment,k=!c&&!w&&p.length>=8&&p===f;return(0,n.jsxs)("div",{className:dv().scrollContent,children:[(0,n.jsxs)("header",{className:dv().contentHeader,children:[(0,n.jsx)("h2",{className:dv().contentTitle,children:"Access"}),(0,n.jsxs)("p",{className:dv().contentDescription,children:["A password locks the web interface and every API endpoint behind HTTP Basic Auth, with the fixed username ",(0,n.jsx)("code",{children:e.username}),". It is stored as a scrypt hash in ",(0,n.jsx)("code",{children:e.file})," — CUELO never keeps the password itself, which is why forgetting it means recovering rather than reading it back."]}),w&&(0,n.jsxs)("div",{className:dv().readOnlyNotice,children:["Read-only \xb7 ",(0,n.jsx)("code",{children:"CUELO_PASSWORD"})," is set and overrides the stored credential. Unset it and restart CUELO to manage the password here."]}),o&&(0,n.jsx)("div",{className:dv().reloadNotice,children:(0,n.jsx)("span",{children:o})})]}),(0,n.jsxs)("div",{className:dv().settingsBody,children:[(0,n.jsxs)("section",{className:dv().group,children:[(0,n.jsx)("h3",{className:dv().groupTitle,children:"Password access"}),(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:dv().settingLabel,children:"Require a password"}),(0,n.jsx)("div",{className:dv().settingDescription,children:e.managedByEnvironment?"Every request needs the password from CUELO_PASSWORD.":e.unreadable?"The credential file exists but could not be read, so every request is being refused.":e.configured?e.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."}),!e.configured&&!w&&(0,n.jsx)("div",{className:dv().settingDescription,children:"Set a password below before turning this on."}),s&&(0,n.jsx)("div",{className:dv().error,children:s})]}),(0,n.jsx)("div",{className:dv().settingControl,children:(0,n.jsx)("button",{type:"button",className:dv().switch,"data-on":e.enabled,"aria-pressed":e.enabled,"aria-label":"Require a password",disabled:c||w||!e.enabled&&!e.stored,onClick:()=>void b()})})]})]}),(0,n.jsxs)("section",{className:dv().group,children:[(0,n.jsx)("h3",{className:dv().groupTitle,children:e.stored?"Replace the password":"Set a password"}),(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:dv().settingLabel,children:"New password"}),(0,n.jsxs)("div",{className:dv().settingDescription,children:["At least ",8," characters. Saving a password also turns password access on."]})]}),(0,n.jsx)("div",{className:dv().settingControl,children:(0,n.jsx)("input",{className:dv().textInput,type:"password",autoComplete:"new-password",value:p,disabled:c||w,onChange:e=>h(e.target.value)})})]}),(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:dv().settingLabel,children:"Confirm password"}),(0,n.jsx)("div",{className:dv().settingDescription,children:"Both entries have to match before it can be saved."})]}),(0,n.jsx)("div",{className:dv().settingControl,children:(0,n.jsx)("input",{className:dv().textInput,type:"password",autoComplete:"new-password",value:f,disabled:c||w,onChange:e=>m(e.target.value),onKeyDown:e=>{"Enter"===e.key&&k&&v()}})})]}),(0,n.jsxs)("div",{className:dv().editorActions,children:[(0,n.jsx)("div",{children:(0,n.jsx)("div",{className:dv().saveState,children:e.stored&&e.updatedAt?`Last changed ${new Date(e.updatedAt).toLocaleString()}`:"No password stored yet"})}),(0,n.jsxs)("div",{style:{display:"flex",gap:8},children:[e.stored&&!w&&(0,n.jsx)("button",{type:"button",className:dv().dangerButton,disabled:c,onClick:()=>void y(),children:"Remove password"}),(0,n.jsx)("button",{type:"button",className:dv().primaryButton,disabled:!k,onClick:()=>void v(),children:c?"Saving…":"Save password"})]})]})]}),(0,n.jsxs)("section",{className:dv().group,children:[(0,n.jsx)("h3",{className:dv().groupTitle,children:"If you forget it"}),(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:dv().settingLabel,children:"Recovery"}),(0,n.jsxs)("div",{className:dv().settingDescription,children:["Run ",(0,n.jsx)("code",{children:"cuelo --reset-password"})," on this machine to set a new one, or open ",(0,n.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,n.jsx)("div",{className:dv().settingControl,children:(0,n.jsx)("a",{className:dv().linkButton,href:"/recover",target:"_blank",rel:"noreferrer",children:"Open /recover"})})]}),(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:dv().settingLabel,children:"Basic Auth is not encryption"}),(0,n.jsx)("div",{className:dv().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,n.jsx)("div",{className:dv().settingControl})]})]})]})]})}function dy(){let{t:e}=(0,R.s)(),[t,r]=(0,i.useState)(null),[a,s]=(0,i.useState)(!1),[l,o]=(0,i.useState)(null),d=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/live/voices",{cache:"no-store"}),t=await e.json().catch(()=>({}));if(!e.ok||!Array.isArray(t.voices)||"string"!=typeof t.defaultVoice)throw Error(`HTTP ${e.status}`);r({voices:t.voices,defaultVoice:t.defaultVoice})}catch(e){o(e instanceof Error?e.message:String(e))}},[]);(0,i.useEffect)(()=>{d()},[d]);let c=async e=>{s(!0),o(null);try{let t=await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:"live.voice",value:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);let i="string"==typeof n.value?n.value:e;r(e=>e?{...e,defaultVoice:i}:e)}catch(e){o(e instanceof Error?e.message:String(e))}finally{s(!1)}};return t?(0,n.jsxs)("div",{className:dv().scrollContent,children:[(0,n.jsxs)("header",{className:dv().contentHeader,children:[(0,n.jsx)("h2",{className:dv().contentTitle,children:e("chat.liveVoiceSettingsTitle")}),(0,n.jsx)("p",{className:dv().contentDescription,children:e("chat.liveVoiceSettingsDescription")})]}),(0,n.jsx)("div",{className:dv().settingsBody,children:(0,n.jsxs)("section",{className:dv().group,children:[(0,n.jsx)("h3",{className:dv().groupTitle,children:e("chat.liveVoiceSpeakerGroup")}),(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{className:dv().settingLabel,children:e("chat.liveVoiceCodexLabel")}),(0,n.jsx)("div",{className:dv().settingDescription,children:e("chat.liveVoiceCodexHelp")}),l&&(0,n.jsx)("div",{className:dv().error,role:"alert",style:{overflowWrap:"anywhere"},children:l})]}),(0,n.jsx)("div",{className:dv().settingControl,children:(0,n.jsx)(l7,{value:t.defaultVoice,disabled:a,ariaLabel:e("chat.liveVoiceCodexLabel"),options:t.voices,onChange:e=>{e!==t.defaultVoice&&c(e)}})})]})]})})]}):(0,n.jsx)("div",{className:dv().empty,children:l?`${e("chat.liveVoiceLoadFailed")}: ${l}`:"…"})}function dw(){let{t:e}=(0,R.s)(),t=(0,i.useId)(),r=(0,i.useId)(),[a,s]=(0,i.useState)(null),[l,o]=(0,i.useState)(""),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=new AbortController;return aB({signal:e.signal}).then(e=>{s(e),o(String(e.uploadLimitMb))}).catch(t=>{e.signal.aborted||c(t instanceof Error?t.message:String(t))}),()=>e.abort()},[]);let m=(0,i.useCallback)(async e=>{p(!0),c(null),f(!1);try{let t=await aU(e);s(t),o(String(t.uploadLimitMb)),f(!0)}catch(e){c(e instanceof Error?e.message:String(e))}finally{p(!1)}},[]);return a?(0,n.jsxs)("div",{className:dv().scrollContent,children:[(0,n.jsxs)("header",{className:dv().contentHeader,children:[(0,n.jsx)("h2",{className:dv().contentTitle,children:e("chat.attachmentSettingsTitle")}),(0,n.jsx)("p",{className:dv().contentDescription,children:e("chat.attachmentSettingsDescription")})]}),(0,n.jsx)("div",{className:dv().settingsBody,children:(0,n.jsxs)("section",{className:dv().group,children:[(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{htmlFor:t,className:dv().settingLabel,style:{display:"block"},children:e("chat.attachmentUploadLimit")}),(0,n.jsx)("div",{className:dv().settingDescription,children:e("chat.attachmentUploadLimitHelp")})]}),(0,n.jsx)("div",{className:dv().settingControl,children:(0,n.jsx)("input",{id:t,className:dv().numberInput,type:"number",inputMode:"numeric",min:1,step:1,value:l,disabled:u,onChange:e=>o(e.target.value),onBlur:()=>{let t=l.trim();if(t===String(a.uploadLimitMb))return;let r=Number(t);if(!/^\d+$/.test(t)||!Number.isSafeInteger(r)||r<1){f(!1),c(e("chat.attachmentUploadLimitInvalid"));return}m({uploadLimitMb:r})},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})})]}),(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{id:r,className:dv().settingLabel,children:e("chat.attachmentAutoCleanup")}),(0,n.jsx)("div",{className:dv().settingDescription,children:e("chat.attachmentAutoCleanupHelp",{days:a.orphanGraceDays})})]}),(0,n.jsx)("div",{className:dv().settingControl,children:(0,n.jsx)("button",{type:"button",className:dv().switch,"data-on":a.autoCleanupEnabled,"aria-pressed":a.autoCleanupEnabled,"aria-labelledby":r,disabled:u,onClick:()=>void m({autoCleanupEnabled:!a.autoCleanupEnabled})})})]}),d&&(0,n.jsx)("div",{className:dv().error,role:"alert",style:{overflowWrap:"anywhere"},children:d}),h&&!d&&(0,n.jsx)("div",{className:dv().saveState,role:"status",children:e("chat.attachmentSettingsSaved")})]})})]}):(0,n.jsx)("div",{className:dv().empty,children:d?`${e("chat.attachmentSettingsLoadFailed")}: ${d}`:"…"})}function dk({cwd:e}){let{t}=(0,R.s)(),[r,a]=(0,i.useState)(null),[s,l]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)({}),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(new Map);(0,i.useEffect)(()=>{g&&c!==g&&(v.current.get(g)?.querySelector("button:not(:disabled)")?.focus(),x(null))},[c,r,g]);let b=(0,i.useRef)(0),y=(0,i.useRef)(null),w=(0,i.useRef)(null),k=(0,i.useRef)(!1),j=(0,i.useCallback)(async()=>{if(k.current||"visible"!==document.visibilityState)return;let r=++b.current;y.current?.abort();let n=new AbortController;y.current=n;try{let i=e?`?include=${encodeURIComponent(e)}`:"",s=await fetch(`/api/project-trust${i}`,{cache:"no-store",signal:n.signal}),o=await s.json();if(r!==b.current||n.signal.aborted)return;if(!s.ok||!o.projects)throw Error(o.error??`HTTP ${s.status}`);let d=o.projects.find(e=>null===e.pending&&!e.error&&w.current?.some(t=>t.cwd===e.cwd&&("grant"===t.pending?e.trusted:"revoke"===t.pending&&!e.trusted)));w.current=o.projects,a(o.projects),l(null),d&&m({cwd:d.cwd,text:t("trust.doneApplied")})}catch(e){if(r!==b.current||n.signal.aborted)return;l(e instanceof Error?e.message:String(e))}finally{y.current===n&&(y.current=null)}},[e,t]);(0,i.useEffect)(()=>(j(),()=>{y.current?.abort()}),[j]);let S=r?.some(e=>null!==e.pending)??!1;(0,i.useEffect)(()=>{let e;if(!S||null!==c||null!==o)return;let t=()=>{window.clearTimeout(e),e="visible"===document.visibilityState?window.setTimeout(()=>void j(),2500):void 0},r=()=>{"visible"===document.visibilityState?j():(t(),++b.current,y.current?.abort())};return t(),document.addEventListener("visibilitychange",r),()=>{window.clearTimeout(e),document.removeEventListener("visibilitychange",r)}},[c,o,r,S,j]);let C=(0,i.useCallback)(async(e,r)=>{if(!k.current){k.current=!0,++b.current,y.current?.abort(),u(e),d(null),x(e),m(null),h(t=>{let r={...t};return delete r[e],r});try{let n=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,action:r})}),i=await n.json();if(!n.ok)throw Error(i.error??`HTTP ${n.status}`);let s=w.current?.map(t=>t.cwd===e?{...i,cwd:e}:t)??null;w.current=s,a(s),"cancel"===r?m({cwd:e,text:t("trust.doneCancelled")}):i.error||null!==i.pending||m({cwd:e,text:t("trust.doneApplied")})}catch(t){h(r=>({...r,[e]:t instanceof Error?t.message:String(t)}))}finally{k.current=!1,u(null)}}},[t]);if(!r)return(0,n.jsxs)("div",{className:dv().empty,children:[s?t("trust.loadFailed",{error:s}):"…",s&&(0,n.jsx)("button",{type:"button",className:dv().linkButton,onClick:()=>void j(),children:t("trust.refresh")})]});let N=null!==c;return(0,n.jsxs)("div",{className:dv().scrollContent,children:[(0,n.jsxs)("header",{className:dv().contentHeader,children:[(0,n.jsx)("h2",{className:dv().contentTitle,children:t("trust.settingsNav")}),(0,n.jsx)("p",{className:dv().contentDescription,children:t("trust.settingsDescription")}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,marginTop:12},children:[(0,n.jsx)("button",{type:"button",className:dv().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void j(),children:t("trust.refresh")}),s&&(0,n.jsx)("div",{className:dv().error,role:"alert",children:t("trust.loadFailed",{error:s})})]})]}),(0,n.jsx)("div",{className:dv().settingsBody,children:(0,n.jsxs)("section",{className:dv().group,children:[0===r.length&&(0,n.jsx)("div",{className:dv().settingDescription,children:t("trust.settingsEmpty")}),r.map(e=>{var r;let i=c===e.cwd,a=o?.cwd===e.cwd?o:null,s=e.requiresTrust?e.trusted?t("trust.stateTrusted"):t("trust.stateRestricted"):t("trust.stateNotRequired"),l=p[e.cwd]??(e.error?t("trust.applyFailed",{error:e.error}):null);return(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsxs)("div",{className:dv().settingLabel,style:{display:"flex",alignItems:"center",gap:7},children:[(0,n.jsx)("span",{className:dv().statusDot,"data-off":!e.trusted||!e.requiresTrust,"aria-hidden":"true"}),(0,n.jsx)("span",{children:(r=e.cwd).split(/[\\/]/).filter(Boolean).pop()??r}),(0,n.jsx)("span",{className:dv().settingDescription,style:{fontWeight:600},children:s})]}),(0,n.jsx)("code",{className:dv().settingDescription,style:{display:"block",overflowWrap:"anywhere"},children:e.cwd}),(0,n.jsx)("div",{className:dv().saveState,children:t("trust.runtime",{sessions:e.runtime.sessions,running:e.runtime.running,loaded:e.requiresTrust?e.runtime.projectCodeLoaded:0})}),(0,n.jsxs)("div",{"aria-live":"polite",children:["grant"===e.pending&&(0,n.jsx)("div",{className:dv().settingDescription,children:t("trust.pendingGrant")}),"revoke"===e.pending&&(0,n.jsx)("div",{className:dv().settingDescription,children:t("trust.pendingRevoke",{count:e.runtime.projectCodeLoaded})}),a&&(0,n.jsx)("div",{className:dv().settingDescription,style:{color:"var(--text)"},children:"revoke"===a.action?t("trust.confirmRevoke"):a.again?t("trust.confirmTrustAgain"):t("trust.confirmGrant")}),f?.cwd===e.cwd&&(0,n.jsx)("div",{className:dv().saveState,children:f.text})]}),l&&(0,n.jsx)("div",{className:dv().error,role:"alert",children:l})]}),(0,n.jsx)("div",{ref:t=>{t?v.current.set(e.cwd,t):v.current.delete(e.cwd)},className:dv().settingControl,style:{flexWrap:"wrap",gap:8,alignItems:"flex-start"},children:a?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:dv().linkButton,style:{background:"transparent",cursor:"pointer"},autoFocus:!0,onClick:()=>{d(null),x(e.cwd)},children:t("trust.cancel")}),(0,n.jsx)("button",{type:"button",className:"revoke"===a.action?dv().dangerButton:dv().primaryButton,disabled:N,onClick:()=>void C(e.cwd,a.action),children:"revoke"===a.action?t("trust.revoke"):t("trust.confirm")})]}):i?(0,n.jsx)("button",{type:"button",className:dv().primaryButton,disabled:!0,children:t("trust.working")}):(0,n.jsxs)(n.Fragment,{children:["grant"===e.pending&&(0,n.jsx)("button",{type:"button",className:dv().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void C(e.cwd,"cancel"),children:t("trust.cancelSchedule")}),e.requiresTrust&&!e.trusted&&"grant"!==e.pending&&(0,n.jsx)("button",{type:"button",className:dv().primaryButton,disabled:N,onClick:()=>d({cwd:e.cwd,action:"grant",again:"revoke"===e.pending}),children:"revoke"===e.pending?t("trust.trustAgain"):t("trust.trustProject")}),e.trusted&&(0,n.jsx)("button",{type:"button",className:dv().dangerButton,disabled:N,onClick:()=>d({cwd:e.cwd,action:"revoke",again:!1}),children:t("trust.revoke")})]})})]},e.cwd)})]})})]})}let dj=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이다"}}}'),dS=[{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"}],dC={model:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"}),(0,n.jsx)("path",{d:"M9 9h6v6H9zM9 1v3m6-3v3M9 20v3m6-3v3M1 9h3m16 0h3M1 15h3m16 0h3"})]}),theme:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("circle",{cx:"12",cy:"12",r:"8"}),(0,n.jsx)("path",{d:"M12 4a8 8 0 0 0 0 16z"})]}),skill:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"m12 3 8 4-8 4-8-4 8-4Z"}),(0,n.jsx)("path",{d:"m4 12 8 4 8-4M4 17l8 4 8-4"})]}),plugin:(0,n.jsx)(n.Fragment,{children:(0,n.jsx)("path",{d:"M8 3v5m8-5v5M6 8h12v5a6 6 0 0 1-12 0V8Zm6 11v3"})}),mcp:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("circle",{cx:"6",cy:"6",r:"2"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"2"}),(0,n.jsx)("circle",{cx:"12",cy:"18",r:"2"}),(0,n.jsx)("path",{d:"M8 7.5 11 16m5-8.5L13 16M8 6h8"})]}),access:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"4",y:"10",width:"16",height:"10",rx:"2"}),(0,n.jsx)("path",{d:"M8 10V7a4 4 0 0 1 8 0v3M12 14v2"})]}),trust:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,n.jsx)("path",{d:"m9 12 2 2 4-4"})]}),liveVoice:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,n.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2M12 19v3"})]}),attachments:(0,n.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,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,n.jsx)("path",{d:"M12 3v18M3 12h18"})]}),interaction:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M4 5h16v11H9l-5 4V5Z"}),(0,n.jsx)("path",{d:"M8 9h8m-8 3h5"})]}),context:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M5 3h11l3 3v15H5z"}),(0,n.jsx)("path",{d:"M15 3v4h4M8 11h8m-8 4h8"})]}),memory:(0,n.jsx)(n.Fragment,{children:(0,n.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,n.jsx)(n.Fragment,{children:(0,n.jsx)("path",{d:"M3 6h7l2 2h9v11H3z"})}),shell:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),(0,n.jsx)("path",{d:"m7 9 3 3-3 3m6 0h4"})]}),tools:(0,n.jsx)(n.Fragment,{children:(0,n.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,n.jsx)(n.Fragment,{children:(0,n.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,n.jsx)(n.Fragment,{children:(0,n.jsx)("path",{d:"M7 4h10v5H7zM4 15h6v5H4zm10 0h6v5h-6zM12 9v3m-5 0h10M7 12v3m10-3v3"})})};function dN({kind:e}){return(0,n.jsx)("svg",{className:dv().navIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:dC[e]??dC.tools})}function dI({field:e,busy:t,onSave:r}){let[a,s]=(0,i.useState)("secret"===e.type?"":String(e.value??""));(0,i.useEffect)(()=>{s("secret"===e.type?"":String(e.value??""))},[e.path,e.type,e.value]);let l="secret"===e.type?"":String(e.value??"");return(0,n.jsx)("input",{className:dv().textInput,type:"secret"===e.type?"password":"text",value:a,disabled:t,placeholder:"secret"===e.type&&e.configured?"Configured — enter to replace":void 0,onChange:e=>s(e.target.value),onBlur:()=>{a!==l&&("secret"!==e.type||a.length>0)&&r(a)},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})}function dT({field:e,busy:t,onSave:r}){let a=JSON.stringify(e.value??{},null,2),[s,l]=(0,i.useState)(a),[o,d]=(0,i.useState)(null);return(0,i.useEffect)(()=>{l(a),d(null)},[a]),(0,n.jsxs)("div",{style:{width:"100%"},children:[(0,n.jsx)("textarea",{className:dv().jsonEditor,style:{minHeight:92},value:s,disabled:t,onChange:e=>l(e.target.value),onBlur:()=>{if(s!==a)try{r(JSON.parse(s)),d(null)}catch(e){d(e instanceof Error?e.message:String(e))}}}),o&&(0,n.jsx)("div",{className:dv().error,children:o})]})}function dM({field:e,busy:t,onSave:r}){let i=Array.isArray(e.value)?e.value:[],a=(e,t)=>{let n=e+t;if(n<0||n>=i.length)return;let a=[...i];[a[e],a[n]]=[a[n],a[e]],r(a)};return(0,n.jsx)("div",{className:dv().multiSelect,children:e.options?.map(s=>{let l=i.indexOf(s.value);return(0,n.jsxs)("span",{className:dv().choice,"data-selected":l>=0,title:s.description,children:[(0,n.jsx)("button",{type:"button",className:dv().choiceToggle,disabled:t,onClick:()=>{let e;return e=s.value,r(i.includes(e)?i.filter(t=>t!==e):[...i,e])},children:s.label}),e.ordered&&l>=0&&(0,n.jsxs)("span",{className:dv().reorder,children:[(0,n.jsx)("button",{type:"button",disabled:t||0===l,onClick:()=>a(l,-1),children:"←"}),(0,n.jsx)("button",{type:"button",disabled:t||l===i.length-1,onClick:()=>a(l,1),children:"→"})]})]},s.value)})})}function d$({field:e,busy:t,onSave:r}){return"boolean"===e.type?(0,n.jsx)("button",{type:"button",className:dv().switch,"data-on":!0===e.value,disabled:t,"aria-pressed":!0===e.value,onClick:()=>r(!0!==e.value)}):"select"===e.type?(0,n.jsx)(l7,{value:String(e.value??""),disabled:t,ariaLabel:e.label,options:(e.options??[]).map(e=>({value:e.value,label:e.label,description:e.description})),onChange:t=>r("number"==typeof e.value||"number"==typeof e.defaultValue?Number(t):t)}):"multiselect"===e.type?(0,n.jsx)(dM,{field:e,busy:t,onSave:r}):"providerLimits"===e.type?(0,n.jsx)(dT,{field:e,busy:t,onSave:r}):(0,n.jsx)(dI,{field:e,busy:t,onSave:r})}function dR({field:e,busy:t,error:r,onSave:i}){return(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:dv().settingLabel,children:e.label}),(0,n.jsx)("div",{className:dv().settingDescription,children:e.description}),r&&(0,n.jsx)("div",{className:dv().error,children:r})]}),(0,n.jsx)("div",{className:dv().settingControl,children:(0,n.jsx)(d$,{field:e,busy:t,onSave:i})})]})}function dE({mode:e,palette:t}){let r=t.variables["--omp-md-heading"];return(0,n.jsxs)("div",{className:dv().themePreview,"data-seed-color-mode":"dark"===e?"dark-only":"light-only",children:[(0,n.jsx)("div",{className:dv().themePreviewBar,style:r?{background:r}:void 0}),(0,n.jsxs)("div",{className:dv().themePreviewPanel,children:[(0,n.jsx)("div",{className:dv().themePreviewLine}),(0,n.jsx)("div",{className:dv().themePreviewLine})]})]})}let dL='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',dz=new Set(["hideThinkingBlock"]);function dA({cwd:e,sessionId:t,initialSection:r="models",onClose:a,onModelsChanged:s,onReloaded:l}){let[o,d]=(0,i.useState)(r),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!0),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(""),[v,b]=(0,i.useState)(new Set),[y,w]=(0,i.useState)({}),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),{theme:N,setPreference:I}=tO(),{locale:T,t:M}=(0,R.s)(),$=(0,i.useRef)(null),E=e=>"ko"===T?dj.shell[e]??e:e,L=(0,i.useCallback)(async()=>{h(!0),m(null);try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/settings${t}`,{cache:"no-store"}),n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);u(n)}catch(e){m(e instanceof Error?e.message:String(e))}finally{h(!1)}},[e]);(0,i.useEffect)(()=>{L()},[L]),(0,i.useEffect)(()=>{let e=$.current;if(!e)return;(Array.from(e.querySelectorAll(dL)).find(e=>e.getClientRects().length>0)??e).focus();let t=t=>{if("Tab"!==t.key)return;let r=Array.from(e.querySelectorAll(dL)).filter(e=>e.getClientRects().length>0),n=document.activeElement;if(0===r.length){t.preventDefault(),e.focus();return}let i=r[0],a=r[r.length-1];t.shiftKey&&(n===i||!e.contains(n))?(t.preventDefault(),a.focus()):t.shiftKey||n!==a&&e.contains(n)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)},[]);let z=(0,i.useCallback)(async(t,r)=>{b(e=>new Set(e).add(t.path)),w(e=>{let r={...e};return delete r[t.path],r});try{let n=await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,value:r})}),i=await n.json();if(!n.ok||i.error)throw Error(i.error??`HTTP ${n.status}`);u(e=>e?{...e,fields:e.fields.map(e=>e.path===t.path?{...e,value:i.value??r,configured:!0}:e)}:e),"theme.dark"===t.path||"theme.light"===t.path?(await tH(e),await L()):dz.has(t.path)?await t8(e):j(!0)}catch(e){w(r=>({...r,[t.path]:e instanceof Error?e.message:String(e)}))}finally{b(e=>{let r=new Set(e);return r.delete(t.path),r})}},[e,L]),A=(0,i.useMemo)(()=>new Map(c?.fields.map(e=>[e.path,e.value])??[]),[c?.fields]),P=(0,i.useMemo)(()=>c?.fields.filter(e=>(function(e,t){switch(e.condition){case void 0:default:return!0;case"hasImageProtocol":return!1;case"advisorEnabled":return!0===t.get("advisor.enabled");case"hindsightActive":return"hindsight"===t.get("memory.backend");case"mnemopiActive":return"mnemopi"===t.get("memory.backend");case"autolearnActive":return!0===t.get("autolearn.enabled");case"autoThinkingActive":return"auto"===t.get("defaultThinkingLevel");case"usageAwareFallbackEnabled":return!0===t.get("retry.usageAwareFallback");case"planModeEnabled":return!0===t.get("plan.enabled");case"unexpectedStopDetection":return!0===t.get("features.unexpectedStopDetection")}})(e,A))??[],[c?.fields,A]),W=o.startsWith("settings:")?o.slice(9):null,F=(0,i.useMemo)(()=>{let e=g.trim().toLowerCase();return e?P.filter(t=>`${t.label} ${t.description} ${t.path} ${t.group??""}`.toLowerCase().includes(e)):W?P.filter(e=>e.tab===W&&("appearance"!==W||"Theme"!==e.group)):[]},[W,g,P]),_=(0,i.useCallback)(()=>{s?.(),a()},[a,s]),D=(0,i.useCallback)(async()=>{if(t){C(!0);try{await sz(t,{type:"reload"}),j(!1),l?.()}catch(e){m(e instanceof Error?e.message:String(e))}finally{C(!1)}}},[l,t]),H=c?.tabs.find(e=>e.id===W),O=g.trim()?`${E("Search")} \xb7 ${F.length}`:H?.label??E("Settings"),B=(e,t)=>[...new Set([...t,...e.map(e=>e.group??"General").filter(e=>!t.includes(e))])].map(t=>{let r=e.filter(e=>(e.group??"General")===t);return r.length?(0,n.jsxs)("section",{className:dv().group,children:[(0,n.jsx)("h3",{className:dv().groupTitle,children:t}),r.map(e=>(0,n.jsx)(dR,{field:e,busy:v.has(e.path),error:y[e.path],onSave:t=>void z(e,t)},e.path))]},t):null}),U=()=>p?(0,n.jsx)("div",{className:dv().empty,children:E("Loading omp settings…")}):f||!c?(0,n.jsx)("div",{className:dv().empty,children:f??E("Settings unavailable")}):(0,n.jsxs)("div",{className:dv().scrollContent,children:[(0,n.jsxs)("header",{className:dv().contentHeader,children:[(0,n.jsx)("h2",{className:dv().contentTitle,children:O}),(0,n.jsx)("p",{className:dv().contentDescription,children:E(g.trim()?"Matching canonical /settings entries across every category.":"Canonical omp /settings values. Changes are saved immediately to the shared agent configuration.")}),k&&t&&(0,n.jsxs)("div",{className:dv().reloadNotice,children:[(0,n.jsx)("span",{children:E("Saved. Reload the active session to apply runtime settings.")}),(0,n.jsx)("button",{type:"button",onClick:()=>void D(),disabled:S,children:E(S?"Reloading…":"Reload session")})]})]}),(0,n.jsx)("div",{className:dv().settingsBody,children:F.length?B(F,H?.groups??[]):(0,n.jsx)("div",{className:dv().empty,children:E("No settings match this search.")})})]});return(0,n.jsx)("div",{className:dv().backdrop,onMouseDown:e=>{e.target===e.currentTarget&&_()},children:(0,n.jsxs)("div",{ref:$,tabIndex:-1,className:dv().window,role:"dialog","aria-modal":"true","aria-label":E("Settings"),children:[(0,n.jsxs)("aside",{className:dv().sidebar,children:[(0,n.jsxs)("div",{className:dv().brand,children:[(0,n.jsx)("div",{className:dv().eyebrow,children:"omp /settings"}),(0,n.jsx)("h1",{className:dv().title,children:E("Settings")}),(0,n.jsx)("code",{className:dv().context,title:e??E("Global configuration"),children:e??E("Global configuration")})]}),(0,n.jsxs)("div",{className:dv().searchWrap,children:[(0,n.jsxs)("svg",{className:dv().searchIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,n.jsx)("path",{d:"m20 20-4-4"})]}),(0,n.jsx)("input",{className:dv().search,value:g,"aria-label":E("Search /settings"),placeholder:E("Search /settings"),onChange:e=>x(e.target.value)})]}),(0,n.jsxs)("nav",{className:dv().nav,children:[(0,n.jsx)("div",{className:dv().navLabel,children:E("Configuration")}),dS.map(t=>{let r=t.labelKey?M(t.labelKey):E(t.label);return(0,n.jsxs)("button",{type:"button",className:dv().navButton,"data-active":!g&&o===t.id,disabled:t.requiresCwd&&!e,title:t.requiresCwd&&!e?`${r} ${E("requires a project")}`:r,onClick:()=>{x(""),d(t.id)},children:[(0,n.jsx)(dN,{kind:t.icon}),(0,n.jsx)("span",{children:r})]},t.id)}),(0,n.jsx)("div",{className:dv().navLabel,children:E("OMP settings")}),c?.tabs.map(e=>(0,n.jsxs)("button",{type:"button",className:dv().navButton,"data-active":!g&&W===e.id,onClick:()=>{x(""),d(`settings:${e.id}`)},children:[(0,n.jsx)(dN,{kind:e.id}),(0,n.jsx)("span",{children:e.label})]},e.id))]}),(0,n.jsx)("div",{className:dv().closeRail,children:(0,n.jsxs)("button",{type:"button",className:dv().closeButton,onClick:_,children:[(0,n.jsx)("span",{children:E("Close settings")}),(0,n.jsx)("span",{"aria-hidden":"true",children:"\xd7"})]})})]}),(0,n.jsx)("main",{className:dv().content,children:g.trim()?U():"models"===o?(0,n.jsx)(o2,{cwd:e,embedded:!0,onClose:_,onModelsChanged:s}):"themes"===o?c?(0,n.jsxs)("div",{className:dv().scrollContent,children:[(0,n.jsxs)("header",{className:dv().contentHeader,children:[(0,n.jsx)("h2",{className:dv().contentTitle,children:E("Themes")}),(0,n.jsxs)("p",{className:dv().contentDescription,children:[E("The web interface uses the same dark and light theme mappings as omp. Changes are persisted to "),(0,n.jsx)("code",{children:"~/.omp/agent/config.yml"}),E(" and applied here immediately.")]})]}),(0,n.jsxs)("div",{className:dv().settingsBody,children:[(0,n.jsx)("div",{className:dv().themeGrid,children:["dark","light"].map(e=>{let t=c.fields.find(t=>t.path===`theme.${e}`),r=c.theme.palettes[e];return(0,n.jsxs)("div",{className:dv().themeCard,children:[(0,n.jsx)(dE,{mode:e,palette:r}),(0,n.jsxs)("div",{className:dv().themeCardBody,children:[(0,n.jsxs)("div",{className:dv().themeCardHeader,children:[(0,n.jsxs)("span",{className:dv().themeSlot,children:[e,E(" mapping")]}),N===e&&(0,n.jsx)("span",{className:dv().themeActive,children:E("Active on web")})]}),(0,n.jsx)(l7,{value:String(t.value),disabled:v.has(t.path),ariaLabel:`${e} theme`,options:(t.options??[]).map(e=>({value:e.value,label:e.label,description:e.description})),onChange:e=>void z(t,e)}),N!==e&&(0,n.jsxs)("button",{type:"button",className:dv().closeButton,style:{marginTop:8},onClick:()=>I(e),children:[E("Preview "),e]})]})]},e)})}),B(c.fields.filter(e=>"appearance"===e.tab&&"Theme"===e.group&&!e.path.startsWith("theme.")),["Theme"])]})]}):(0,n.jsx)("div",{className:dv().empty,children:p?E("Loading themes…"):f??E("Themes unavailable")}):"skills"===o&&e?(0,n.jsx)(dt,{cwd:e,embedded:!0,onClose:_}):"plugins"===o&&e?(0,n.jsx)(dg,{cwd:e,sessionId:t,embedded:!0,onClose:_,onReloaded:l}):"mcp"===o?(0,n.jsx)(dP,{cwd:e,sessionId:t,onReloaded:l}):"access"===o?(0,n.jsx)(db,{}):"trust"===o?(0,n.jsx)(dk,{cwd:e}):"live-voice"===o?(0,n.jsx)(dy,{}):"attachments"===o?(0,n.jsx)(dw,{}):U()})]})})}function dP({cwd:e,sessionId:t,onReloaded:r}){let[a,s]=(0,i.useState)(null),[l,o]=(0,i.useState)("user"),[d,c]=(0,i.useState)(0),[u,p]=(0,i.useState)(""),[h,f]=(0,i.useState)(""),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(null),w=(0,i.useCallback)(async()=>{try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/mcp${t}`,{cache:"no-store"}),n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);s(n),g(null)}catch(e){g(e instanceof Error?e.message:String(e))}},[e]);(0,i.useEffect)(()=>{w()},[w]);let k=a?"user"===l?a.user:a.project:null,j=k?.servers[d]??null;(0,i.useEffect)(()=>{f(j?.name??""),p(j?JSON.stringify(j.config,null,2):"")},[j]);let S=e=>{s(t=>{if(!t)return t;let r={..."user"===l?t.user:t.project,servers:e};return"user"===l?{...t,user:r}:{...t,project:r}})},C=async()=>{if(k){v(!0),g(null);try{let t,r=(t=k?.servers??[],(j?.editable===!1?t:t.map((e,t)=>t===d?{...e,name:h,config:JSON.parse(u)}:e)).filter(e=>!1!==e.editable).map(({name:e,config:t})=>({name:e,config:t}))),n=e?`?cwd=${encodeURIComponent(e)}`:"",i=await fetch(`/api/mcp${n}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:l,servers:r})}),a=await i.json();if(!i.ok||a.error)throw Error(a.error??`HTTP ${i.status}`);await w()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(!1)}}},N=async n=>{y(`${l}:${n.name}`),g(null);try{let i=e?`?cwd=${encodeURIComponent(e)}`:"",a=await fetch(`/api/mcp${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:l,name:n.name,enabled:!n.enabled})}),s=await a.json();if(!a.ok||s.error)throw Error(s.error??`HTTP ${a.status}`);await w(),t&&(await sz(t,{type:"reload"}),r?.())}catch(e){g(e instanceof Error?e.message:String(e))}finally{y(null)}};return(0,n.jsxs)("div",{className:dv().scrollContent,children:[(0,n.jsxs)("header",{className:dv().contentHeader,children:[(0,n.jsx)("h2",{className:dv().contentTitle,children:"MCP servers"}),(0,n.jsx)("p",{className:dv().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,n.jsx)("div",{className:dv().settingsBody,children:a?(0,n.jsxs)("div",{className:dv().mcpLayout,children:[(0,n.jsxs)("aside",{className:dv().mcpList,children:[(0,n.jsxs)("div",{className:dv().scopeTabs,children:[(0,n.jsxs)("button",{type:"button",className:dv().scopeButton,"data-active":"user"===l,onClick:()=>{o("user"),c(0)},children:["User \xb7 ",a.user.servers.length]}),(0,n.jsxs)("button",{type:"button",className:dv().scopeButton,"data-active":"project"===l,disabled:!a.project,onClick:()=>{o("project"),c(0)},children:["Project \xb7 ",a.project?.servers.length??0]})]}),k?.error?(0,n.jsx)("div",{className:dv().error,style:{padding:12},children:k.error}):(0,n.jsx)("div",{className:dv().serverRows,children:k?.servers.length?k.servers.map((e,t)=>{let r=`${l}:${e.name}`;return(0,n.jsxs)("div",{className:dv().serverRow,"data-active":d===t,children:[(0,n.jsxs)("button",{type:"button",className:dv().serverSelect,title:e.source?.path,onClick:()=>c(t),children:[(0,n.jsx)("span",{className:dv().statusDot,"data-off":!e.enabled}),(0,n.jsx)("span",{className:dv().serverName,children:e.name}),!1===e.editable&&(0,n.jsx)("span",{className:dv().sourceBadge,children:e.source?.provider??"external"})]}),(0,n.jsx)("button",{type:"button",className:dv().serverToggle,"data-on":e.enabled,disabled:b===r,"aria-pressed":e.enabled,"aria-label":`${e.enabled?"Disable":"Enable"} ${e.name}`,title:`${e.enabled?"Disable":"Enable"} ${e.name}`,onClick:()=>void N(e),children:b===r?"…":e.enabled?"ON":"OFF"})]},`${e.name}-${e.source?.path??t}`)}):(0,n.jsx)("div",{className:dv().serverListEmpty,children:"No servers in this scope."})}),(0,n.jsx)("button",{type:"button",className:dv().addServer,disabled:!!k?.error,onClick:()=>{if(!k)return;let e="new-server",t=2;for(;k.servers.some(t=>t.name===e);)e=`new-server-${t++}`;let r=[...k.servers,{name:e,config:{type:"stdio",command:""},enabled:!0,editable:!0}];S(r),c(r.length-1)},children:"+ Add OMP server"})]}),(0,n.jsx)("section",{className:dv().mcpEditor,children:j?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:dv().editorHeader,children:[(0,n.jsx)("input",{className:dv().textInput,value:h,readOnly:!1===j.editable,onChange:e=>f(e.target.value),placeholder:"server-name"}),!1!==j.editable&&(0,n.jsx)("button",{type:"button",className:dv().dangerButton,onClick:()=>{k&&j&&!1!==j.editable&&(S(k.servers.filter((e,t)=>t!==d)),c(Math.max(0,d-1)))},children:"Delete"})]}),!1===j.editable&&(0,n.jsxs)("div",{className:dv().readOnlyNotice,children:["Configuration read-only \xb7 managed by ",j.source?.provider??"an external provider",". Status can be changed from the server list."]}),(0,n.jsx)("textarea",{className:dv().jsonEditor,value:u,readOnly:!1===j.editable,spellCheck:!1,onChange:e=>p(e.target.value)}),(0,n.jsxs)("div",{className:dv().editorActions,children:[(0,n.jsxs)("div",{children:[m&&(0,n.jsx)("div",{className:dv().error,children:m}),(0,n.jsx)("div",{className:dv().saveState,children:j.source?.path??k?.path})]}),!1!==j.editable&&(0,n.jsx)("button",{type:"button",className:dv().primaryButton,disabled:x,onClick:()=>void C(),children:x?"Saving…":"Save MCP"})]})]}):(0,n.jsx)("div",{className:dv().empty,children:"Add or select an MCP server."})})]}):(0,n.jsx)("div",{className:dv().empty,children:m??"Loading MCP configuration…"})})]})}let dW="cuelo-notification-prompt-dismissed";function dF({variant:e,locale:t,permission:r,dismissed:i,request:a,dismiss:s}){let l="ko"===t;return null===r||"granted"===r?null:"banner"===e?"default"!==r||i?null:(0,n.jsxs)("div",{className:"workspace-update-banner",role:"region","aria-label":l?"알림 권한 안내":"Notification permission",children:[(0,n.jsx)("span",{className:"workspace-update-banner-detail",style:{fontFamily:"inherit",fontSize:"inherit",color:"inherit"},children:l?"백그라운드 작업 완료 알림을 받으세요.":"Get notified when background work finishes."}),(0,n.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:a,children:l?"알림 켜기":"Enable notifications"}),(0,n.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:s,"aria-label":l?"알림 권한 안내 닫기":"Dismiss notification prompt",children:l?"닫기":"Dismiss"})]}):(0,n.jsx)(d.k.Item,{disabled:"denied"===r,onClick:"default"===r?a:void 0,children:(0,n.jsxs)(d.k.ItemBody,{children:[(0,n.jsx)(d.k.ItemLabel,{children:"default"===r?l?"알림 켜기":"Enable notifications":l?"알림 차단됨":"Notifications blocked"}),"denied"===r&&(0,n.jsx)(d.k.ItemDescription,{children:l?"주소창 옆 사이트 설정에서 알림을 허용하세요.":"Allow notifications in site settings beside the address bar."})]})})}function d_({cwd:e,busy:t,scheduled:r,error:a,onCancel:s,onConfirm:l,onCancelSchedule:o}){let{t:d}=(0,R.s)(),c=(0,i.useRef)(null);(0,i.useEffect)(()=>{c.current?.focus()},[r]);let u={height:32,padding:"0 12px",borderRadius:5,cursor:t?"not-allowed":"pointer",fontSize:12};return(0,n.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:e=>{t||e.target!==e.currentTarget||s()},children:(0,n.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,n.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,n.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,n.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),r?(0,n.jsx)("path",{d:"M12 8v4l2 2"}):(0,n.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{id:"project-trust-title",style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:d(r?"trust.scheduledTitle":"trust.dialogTitle")}),(0,n.jsx)("div",{id:"project-trust-body","aria-live":"polite",style:{marginTop:7,fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:d(r?"trust.scheduledBody":"trust.dialogBody")}),(0,n.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:e}),a&&(0,n.jsx)("div",{role:"alert",style:{marginTop:10,color:"#ef4444",fontSize:12,lineHeight:1.5},children:a})]})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[r&&(0,n.jsx)("button",{type:"button",onClick:o,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:d("trust.cancelSchedule")}),(0,n.jsx)("button",{ref:c,type:"button",onClick:s,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:d(r?"trust.close":"trust.cancel")}),!r&&(0,n.jsx)("button",{type:"button",onClick:l,disabled:t,style:{...u,border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:t?"wait":"pointer",opacity:t?.7:1,fontWeight:600},children:d(t?"trust.trusting":"trust.trustProject")})]})]})})}var dD=r(70451),dH=r(54265);let dO={kind:"loading"};function dB(e){return"failed"===e.status?"var(--danger)":"aborted"===e.status||e.progress?.retryState?"var(--warning)":(0,rq.Ch)(e.status)?"var(--accent)":"var(--success)"}function dU(e){return"live-archive"===e.identity?"실시간 + 디스크":"live"===e.identity?"실시간":"디스크 기록"}let dq={bundled:"기본 제공",user:"사용자 정의",project:"프로젝트 정의"};function dK(e){return e.lastUpdate||e.progress?.durationMs||0}function dV(){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 dJ({sessionId:e,sessionCwd:t,record:r,client:a,visible:s,onBack:l}){let o=(0,i.useMemo)(()=>[{key:r.key,liveId:r.live?.id,status:r.live?.status,archiveName:r.archive?.name}],[r.key,r.live?.id,r.live?.status,r.archive?.name]),d=(0,i.useRef)(null),c=(0,rq._Z)(o,{sessionId:e,client:a,enabled:s}).get(r.key)?.state??dO;(0,i.useEffect)(()=>{if(!s||"ready-live"!==c.kind&&"ready-archive"!==c.kind)return;let e=requestAnimationFrame(()=>{let e=d.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[c,s]);let u="ready-live"===c.kind?c.entries:[],p=(0,i.useMemo)(()=>{let e=new Map;for(let t of u)"message"in t&&"toolResult"===t.message.role&&e.set(t.message.toolCallId,t.message);return e},[u]),h=r.live?.id||r.archive?.name||"Subagent";return(0,n.jsxs)("div",{role:"dialog","aria-label":`${h} 기록`,style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("button",{type:"button",onClick:l,"aria-label":"Subagent 목록으로 돌아가기",title:"목록",style:dV(),children:(0,n.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,n.jsx)("path",{d:"m10.5 3-5 5 5 5"})})}),(0,n.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,n.jsx)("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11.5,fontWeight:700},children:h}),(0,n.jsx)("div",{style:{marginTop:2,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9},children:dU(r)})]}),r.live&&(0,n.jsx)("span",{style:{color:dB(r.live),fontFamily:"var(--font-mono)",fontSize:9.5},children:r.live.status})]}),(0,n.jsxs)("div",{ref:d,style:{flex:1,minHeight:0,overflowY:"auto",padding:"10px 12px 18px"},children:["loading"===c.kind&&(0,n.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"기록 불러오는 중…"}),"ready-live"===c.kind&&c.entries.flatMap((e,r)=>{if(!("message"in e))return[];let i=c.entries[r-1];return[(0,n.jsx)(nL,{message:e.message,toolResults:p,cwd:t,showTimestamp:!0,prevTimestamp:i&&"message"in i?i.message.timestamp:void 0},e.id)]}),"ready-archive"===c.kind&&(0,n.jsxs)(n.Fragment,{children:[c.note&&(0,n.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--text-muted)",fontSize:9.5,lineHeight:1.5},children:c.note}),c.truncated&&(0,n.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--warning)",fontSize:9.5},children:"최근 400개 기록만 표시합니다."}),c.entries.map((e,t)=>(0,n.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,n.jsxs)("div",{style:{marginBottom:5,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:8.5,letterSpacing:"0.04em"},children:[e.role," \xb7 ",e.kind]}),e.text||"(내용 없음)"]},`${e.at??0}:${t}`))]}),"empty"===c.kind&&(0,n.jsxs)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:[c.note&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{children:c.note}),(0,n.jsx)("br",{})]}),"대화 내용이 없습니다."]}),"unreachable"===c.kind&&(0,n.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:c.message}),"error"===c.kind&&(0,n.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:c.message})]})]})}function dG({record:e,view:t,onSelect:r}){let{st:a}=rp(),s=(0,i.useId)(),l=e.live,o=e.archive,d=(0,rC.$V)(e),c=!!(l&&(0,rq.Ch)(l.status)),u=c?d.stage:null,p=c&&t?t:null,h=p?.phase?a("phase.current",{phase:a(`phase.${p.phase}`)}):"",f=p?.todo?rZ(a,p.todo):"",m=l?.id||o?.name||"Subagent",g=dU(e),x=(0,rC.wX)(e),v=(0,rC.A7)(e),b=v.modelShort??"모델 미확인",y=v.effort??"추론 미확인",w="known"===x.kind?x.label:"역할 미확인";return(0,n.jsxs)("button",{type:"button",role:"listitem",onClick:r,"data-identity":e.identity,title:`${m}
|
|
19
|
+
${r}`:e:r,images:s,documents:l}}function aT(e,t,r){if(e===t)return r?ak(r):aS(t);let n=aS(e),i=r&&!aj(r)?ak(r):n??(r?ak(r):null),a=aS(t),s=al.get(e);if(al.delete(e),s&&!al.has(t)&&al.set(t,s),aN(e),!i)return a;let l=a?aI(a.value,a.images,i.value,i.images,a.documents,i.documents):i;return aC(t,l),ak(l)}function aM(e){let t=[];for(let r of e??[])r.attachmentId&&!t.includes(r.attachmentId)&&t.push(r.attachmentId);return t}function a$(e){ay();let t=al.get(e);return t||(t=function(){let e=globalThis.crypto;if("function"==typeof e?.randomUUID)return e.randomUUID();let t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;let r=[...t].map(e=>e.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}(),al.set(e,t)),t}function aR(e){let t=aM(ai.get(e)?.documents),r=t.length?a$(e):al.get(e);for(let[e,r]of ah){for(let e of t)r.delete(e);0===r.size&&ah.delete(e)}let n=`${r??""}|${t.join(",")}`;am.get(e)!==n&&(0!==t.length||r?am.set(e,n):am.delete(e),aF())}async function aE(e){let t=a$(e);ap.set(t,(ap.get(t)??0)+1),await ag.get(t);let r=!1;return{draftId:t,end(e){if(r)return;r=!0;let n=(ap.get(t)??1)-1;if(n>0?ap.set(t,n):ap.delete(t),e){let r=ah.get(t)??new Set;r.add(e),ah.set(t,r)}ao.set(t,ad),aF()}}}function aL(e,t){let r=af.get(e);if(!r)return[];for(let e of t)r.delete(e);return 0===r.size&&af.delete(e),[...r].sort()}async function az(){if(!ax)return;let e=[...function(){let e=new Map,t=(t,r)=>{let n=e.get(t)??new Set;for(let e of r)n.add(e);e.set(t,n)};for(let[e,r]of al)t(r,aM(ai.get(e)?.documents));for(let{draftId:e,ids:r}of ac.values())t(e,r);for(let[e,r]of ah)t(e,r);for(let e of ao.keys())t(e,[]);for(let e of af.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(ap.has(e))return!1;let r=ao.get(e);return aL(e,t).length>0||(0===t.length?void 0!==r:r!==t.join(","))}),t=ap.size>0,r=!1;for(let[n,i]of[...e.filter(([,e])=>e.length>0),...e.filter(([,e])=>0===e.length)]){if(0===i.length&&t)continue;let e=aL(n,i),a=ax(n,i,e).then(()=>{0===i.length?ao.delete(n):ao.set(n,i.join(","));let t=af.get(n);if(t){for(let r of e)t.delete(r);0===t.size&&af.delete(n)}},()=>{r=!0,i.length>0&&(t=!0)});ag.set(n,a),await a,ag.get(n)===a&&ag.delete(n)}r?function(){if(aW)return;aW=!0;let e=setTimeout(()=>{aW=!1,aF()},aP);"object"==typeof e&&"unref"in e&&e.unref(),aP=Math.min(2*aP,6e4)}():aP=aA}let aA=5e3,aP=5e3,aW=!1;function aF(){if(ax){if(av){ab=!0;return}av=Promise.resolve().then(az).finally(()=>{av=null,ab&&(ab=!1,aF())})}}let a_=Math.floor(Number.MAX_SAFE_INTEGER/1048576),aD=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function aH(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=a_}async function aO(e){let t,r=await e.json().catch(()=>null);if(!e.ok||!r||!aH(r.uploadLimitMb)||"boolean"!=typeof r.autoCleanupEnabled)throw Error("string"==typeof r?.error?r.error:`HTTP ${e.status}`);return{uploadLimitMb:aH((t=r&&"object"==typeof r?r:{}).uploadLimitMb)?t.uploadLimitMb:aD.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:aD.autoCleanupEnabled,orphanGraceDays:7}}async function aB(e={}){return aO(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function aU(e){return aO(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function aq(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let r=/(?:^|\s)@([^\s"]*)$/.exec(e);return r?{start:e.length-(r[1].length+1),query:r[1],quoted:!1}:null}function aK(e){let t=0;for(let r=0;r<e.length;r++)"/"===e[r]&&t++;return t}function aV(e,t){if(!e)return!0;let r=0;for(let n=0;n<t.length&&r<e.length;n++)t[n]===e[r]&&r++;return r===e.length}let aJ="omp-web:model-picks";function aG(){try{let e=JSON.parse(window.localStorage.getItem(aJ)??"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};let t={};for(let[r,n]of Object.entries(e))"number"==typeof n&&Number.isFinite(n)&&n>0&&(t[r]=Math.floor(n));return t}catch{return{}}}function aY(e,t,r,n,i={}){let a=i.gap??8,s=i.margin??8,l=i.prefer??"above",o=Math.min(i.minHeight??120,Math.max(0,r-2*s)),d=Math.max(0,e-a-s),c=Math.max(0,r-t-a-s),u="above"===l?d:c,p="above"===l?c:d,h=u>=n||u>=p;return{side:h?l:"above"===l?"below":"above",maxHeight:Math.max(o,Math.min(n,h?u:p))}}function aZ(e,t,r){return Math.min(e*t,r)}function aX(e,t,r){let{viewportFraction:n,cap:a,gap:s,margin:l,minHeight:o,prefer:d}=r,[c,u]=(0,i.useState)({side:d??"above",maxHeight:a}),p=(0,i.useCallback)(()=>{let t=e.current;if(!t)return;let r=window.visualViewport?.height??window.innerHeight,i=t.getBoundingClientRect(),c=aY(i.top,i.bottom,r,aZ(r,n,a),{gap:s,margin:l,minHeight:o,prefer:d});u(e=>e.side===c.side&&e.maxHeight===c.maxHeight?e:c)},[e,a,s,l,o,d,n]);return(0,i.useEffect)(()=>{if(!t)return;p();let r=e.current,n=r?new ResizeObserver(p):null;return r&&n&&n.observe(r),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),window.visualViewport?.addEventListener("resize",p),window.visualViewport?.addEventListener("scroll",p),()=>{n?.disconnect(),window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0),window.visualViewport?.removeEventListener("resize",p),window.visualViewport?.removeEventListener("scroll",p)}},[e,p,t]),c}var aQ=r(14755);async function a0(e,t,r,n,i,a,s){let l=e.slice(1).split(/\s/,1)[0];try{let o=t?.length?t:await s?.()??[],d=[...si,...o].find(e=>e.name===l||"aliases"in e&&e.aliases?.includes(l));if(a&&(!d||"builtin"===d.source))return i(`/${l} cannot run with attachments. Remove them and retry.`),!1;let c=await r?.(e);if(c?.handled){if(c.error)return!1;return c.prompt&&n(c.prompt),!0}if(d&&"builtin"!==d.source)return n(e),!0;return i(`/${l} is not available in this web session.`),!1}catch(e){return i(e instanceof Error?e.message:String(e)),!1}}function a1(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t}let a2=["off","default","full"],a4={off:"none",default:"default",full:"full"},a5=aQ.IN.join(" \xb7 "),a8=aQ.C1.filter(e=>!aQ.IN.includes(e)).join(" \xb7 ");function a6(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let a3=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),a7=0,a9={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function se(e,t){return a3.compare(e.name||e.modelId,t.name||t.modelId)||a3.compare(e.provider,t.provider)||a3.compare(e.modelId,t.modelId)}let st=["auto","off","minimal","low","medium","high","xhigh","max"],sr=["low","medium","high","xhigh"],sn={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},si=[{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"}],sa=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],ss={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},sl={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function so(e,t,r){let n=e.name.toLowerCase(),i=sd(e,r).toLowerCase();return n===t?0:n.startsWith(t)?1:n.includes(t)?2:i.includes(t)?3:4}function sd(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function sc(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function su(e){return{data:e.data,mimeType:e.mimeType}}function sp(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function sh(e){return(e??[]).filter(an).slice(0,10).map(sp)}let sf=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,sm="\n\nTranscript of the audio ";function sg(e){return ns(e).map(e=>{let t=nh(e),r="audio"===t&&e.attachmentId&&!e.text.includes(sm)?sf.exec(e.text):null;return{...e,id:++a7,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...r?{storedInfo:{path:r[1],mimeType:r[2],size:Number(r[3])}}:{}}})}function sx({name:e,mimeType:t,size:r,text:n,attachmentId:i}){return i?{name:e,mimeType:t,size:r,text:n,attachmentId:i}:{name:e,mimeType:t,size:r,text:n}}function sv(e,t){let r=new Map(t.flatMap(e=>e.attachmentId?[[e.attachmentId,e]]:[]));return[...e.map(e=>{let t=e.attachmentId?r.get(e.attachmentId):void 0;return t?(r.delete(e.attachmentId),{...e,id:t.id,sourceSize:t.sourceSize,storedInfo:t.storedInfo??e.storedInfo,transcription:t.transcription}):e}),...t.filter(e=>"ready"!==e.status)]}class sb extends Error{constructor(e,t,r,n){super(e),this.code=t,this.completedParts=r,this.parts=n}}let sy="composer:unkeyed";async function sw(e){let t=await e.json().catch(()=>null),r=t&&"object"==typeof t?{...t}:{};if(e.ok)return r;throw new sb("string"==typeof r.error?r.error:`HTTP ${e.status}`,"string"==typeof r.code?r.code:null,"number"==typeof r.completedParts?r.completedParts:null,"number"==typeof r.parts?r.parts:null)}function sk(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function sj({tone:e,title:t,body:r}){let i="error"===e?"danger":"warning";return(0,n.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(--${i}-line)`,borderRadius:"var(--radius-control)",background:`var(--${i}-soft)`,color:`var(--${i})`,fontSize:11,lineHeight:1.45},children:[(0,n.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,n.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,n.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,n.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontWeight:600},children:t}),(0,n.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:r})]})]})}function sS({error:e}){return e?(0,n.jsx)(sj,{tone:"error",title:"Model error",body:e}):null}function sC({warnings:e}){return e&&0!==e.length?(0,n.jsx)(sj,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let sN=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:r,onFollowUp:a,isStreaming:l,model:o,isAutoModelSelection:d,modelNames:c,modelList:u,modelError:p,modelScopeWarnings:h,onModelChange:f,onMainPresetChange:m,mainPresetActiveAlias:g,modelRoles:x,onRoleModelChange:v,modelSwitching:b,onCompact:y,onAbortCompaction:w,isCompacting:k,compactError:j,compactResult:S,toolPreset:C,onToolPresetChange:N,thinkingLevel:I,effectiveThinkingLevel:T,thinkingCeiling:M,onThinkingLevelChange:$,availableThinkingLevels:E,thinkingLevelMap:L,fastMode:z=null,fastModeBusy:A=!1,onFastModeToggle:P,retryInfo:F,deliveryRows:_=[],inputHistory:D=[],onRecallQueue:H,onRemoveQueuedMessage:O,slashCommands:B,slashCommandsLoading:U,onLoadSlashCommands:q,onBuiltinCommand:K,soundEnabled:V,onSoundToggle:J,onAudioUnlock:G,onPromptWithStreamingBehavior:Y,draftKey:Z,cwd:X,sessionId:Q,onEnsureSession:ee,onLiveTranscriptPersisted:et},er){let en,ei,ea,es,el,eo,ed,ec,eu,ep,{t:eh}=(0,R.s)(),{st:ef}=rp(),em=_.some(e=>e.removable),eg=W(),[ex,ev]=(0,i.useState)(()=>Z?aS(Z)?.value??"":""),[eb,ey]=(0,i.useState)(!1),[ew,ek]=(0,i.useState)(null),[ej,eS]=(0,i.useState)(""),[eC,eN]=(0,i.useState)({});(0,i.useEffect)(()=>{eb&&eN(aG())},[eb]);let[eI,eT]=(0,i.useState)(!1),[eM,e$]=(0,i.useState)(null),[eR,eE]=(0,i.useState)(!1),[eL,ez]=(0,i.useState)(!1),[eA,eP]=(0,i.useState)(null),[eW,eF]=(0,i.useState)(!1),[e_,eD]=(0,i.useState)(()=>Z?sh(aS(Z)?.images):[]),[eH,eO]=(0,i.useState)(()=>Z?sg(aS(Z)?.documents):[]),[eB,eU]=(0,i.useState)(null),eq=(0,i.useMemo)(()=>eH.filter(e=>"ready"===e.status),[eH]),eK=eH.some(e=>"ready"!==e.status||a1(e)),eV=eH.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(sm))),eJ=ex.trimStart(),eG=0===e_.length&&0===eH.length&&eJ.startsWith("!"),eY=eG&&eJ.startsWith("!!"),[eZ,eX]=(0,i.useState)(!1),[eQ,e0]=(0,i.useState)(0),[e1,e2]=(0,i.useState)(null),[e4,e5]=(0,i.useState)(!1),[e8,e6]=(0,i.useState)(0),[e3,e7]=(0,i.useState)(!1),[e9,te]=(0,i.useState)(0),[tt,tr]=(0,i.useState)(null),[tn,ti]=(0,i.useState)(!1),[ta,ts]=(0,i.useState)(null),[tl,to]=(0,i.useState)(null),td=X&&tl?.cwd===X?tl.values:{},tc=(0,i.useRef)(null),tu=(0,i.useRef)(null),tp=(0,i.useRef)(null),th=(0,i.useRef)(null),tf=(0,i.useRef)(null),tm=(0,i.useRef)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),tb=(0,i.useRef)(null),ty=(0,i.useRef)(null),tw=(0,i.useRef)(!1),tk=(0,i.useRef)(0),tj=(0,i.useRef)(!1),tS=(0,i.useRef)([]),tC=(0,i.useRef)([]),tN=(0,i.useRef)([]),tI=(0,i.useRef)(null),tT=(0,i.useRef)(null),tM=(0,i.useRef)(Z),t$=(0,i.useRef)(ex),tR=(0,i.useRef)(e_),tE=(0,i.useRef)(0),tL=(0,i.useRef)(eH);t$.current=ex,tR.current=e_,tL.current=eH,(0,i.useImperativeHandle)(er,()=>({insertIfEmpty(e){let t=tc.current;(t?t.value:ex).trim()||(t$.current=e,ev(e),e2(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){let t,r,n=tc.current;if(!function(e,t,r,n=0){return!e.trim()&&0===t&&0===r&&0===n}(n?n.value:ex,tR.current.length,tE.current,tL.current.length))return;let i=(t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),nd(t)?.message??t),a=sh("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,r=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof r)return[];let n={data:t,mimeType:r};return an(n)?[n]:[]})),s=sg((r="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),nd(r)?.documents??[]));t$.current=i,tR.current=a,tL.current=s,ev(i),e2(null),e7(!1),eD(e=>(e.forEach(sk),a)),eO(s),requestAnimationFrame(()=>{n&&(n.focus(),n.style.height="auto",n.style.height=`${Math.min(n.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(tM.current!==e)return void aT(e,t);let r={value:t$.current,images:tR.current.map(su),documents:tL.current.filter(e=>"ready"===e.status).map(sx)},n=aT(e,t,r)??{value:"",images:[],documents:[]},i=n.value===r.value&&n.images.length===r.images.length&&n.images.every((e,t)=>e.data===r.images[t]?.data&&e.mimeType===r.images[t]?.mimeType)&&n.documents.length===r.documents.length&&n.documents.every((e,t)=>e.name===r.documents[t]?.name&&e.mimeType===r.documents[t]?.mimeType&&e.size===r.documents[t]?.size&&e.text===r.documents[t]?.text&&e.attachmentId===r.documents[t]?.attachmentId);if(tM.current=t,i)return;let a=sh(n.images),s=sv(sg(n.documents),tL.current),l=n.value;t$.current=l,tR.current=a,tL.current=s,ev(l),eD(e=>(e.forEach(sk),a)),eO(s),e2(null),e7(!1)},restoreSubmission(e,t,r,n){if(!e.trim()&&!t?.length&&!r?.length)return;let i=tM.current,a=n??i,s=a===i,l=!s&&a?aS(a):null,o=aI(e,t,s?t$.current:l?.value??"",s?tR.current.map(su):l?.images??[],r,s?tL.current.filter(e=>"ready"===e.status).map(sx):l?.documents??[]);if(a&&aC(a,o),!s)return;let d=t?.length?[...sh(t).slice(0,Math.max(0,10-tR.current.length)),...tR.current].slice(0,10):tR.current,c=sv(sg(o.documents),tL.current);t$.current=o.value,tR.current=d,tL.current=c,ev(o.value),e2(null),e7(!1),t?.length&&eD(e=>{let r=Math.max(0,10-e.length),n=sh(t).slice(0,r),i=n.length>0?[...n,...e]:e;return tR.current=i,i}),eO(c),requestAnimationFrame(()=>{let e=tc.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},insertText(e){let t=tc.current;if(!t)return void ev(t=>t+(t?" ":"")+e);let r=t.selectionStart??t.value.length,n=t.selectionEnd??t.value.length,i=t.value.slice(0,r),a=t.value.slice(n),s=i.length>0&&!i.endsWith(" ")?" ":"",l=i+s+e+a;t$.current=l,ev(l),e2(null),requestAnimationFrame(()=>{if(!t)return;let n=r+s.length+e.length;t.setSelectionRange(n,n),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){tG(e)}}));let tz=(0,i.useCallback)(async e=>{let t=Math.max(0,10-tR.current.length-tE.current),r=e.filter(e=>e.size>0xa00000);r.length>0&&eU(eh("chat.attachImageTooLarge",{name:r.map(e=>e.name).join(", "),limit:nc(0xa00000)}));let n=e.filter(e=>e.size<=0xa00000),i=n.slice(0,t);if(i.length<n.length&&eU(eh("chat.attachImageLimit",{count:10})),i.length){tE.current+=i.length;try{let e=await Promise.all(i.map(e=>new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let r=n.result.split(",")[1];t({data:r,mimeType:e.type,previewUrl:URL.createObjectURL(e)})},n.onerror=r,n.readAsDataURL(e)})));eD(t=>{let r=e.slice(0,Math.max(0,10-t.length));e.slice(r.length).forEach(sk);let n=[...t,...r];return tR.current=n,n})}finally{tE.current-=i.length}}},[eh]),tA=(0,i.useCallback)(async e=>{for(let t of e){let e=nr(t);if(!e)continue;if(tL.current.length>=3){eU(eh("chat.attachLimit",{count:3}));continue}if(t.size>8388608){eU(eh("chat.attachTooLarge",{name:t.name,limit:nc(8388608)}));continue}if(tL.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eU(eh("chat.attachTotalTooLarge",{limit:nc(0x1000000)}));continue}let r={id:++a7,name:t.name,mimeType:r9[e],size:t.size,text:"",status:"extracting"},n=[...tL.current,r];tL.current=n,eO(n);try{let e=await nl(t);if(tL.current.reduce((e,t)=>e+(t.id===r.id?0:t.text.length),0)+e.text.length>24e4)throw new r7("text_too_large","Total extracted text exceeds 240000 characters");let n=tL.current.map(t=>t.id===r.id?{...e,id:t.id,status:"ready"}:t);tL.current=n,eO(n)}catch(i){let e=tL.current.some(e=>e.id===r.id),n=tL.current.filter(e=>e.id!==r.id);if(tL.current=n,eO(n),!e)continue;i instanceof r7?"text_too_large"===i.code?eU(eh("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===i.code?eU(eh("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===i.code?eU(eh("chat.attachNoPdfText",{name:t.name})):"password_protected"===i.code?eU(eh("chat.attachPasswordProtected",{name:t.name})):eU(eh("chat.attachExtractFailed",{name:t.name})):eU(eh("chat.attachExtractFailed",{name:t.name}))}}},[eh]),tP=(0,i.useCallback)((e,t)=>{if(!tL.current.some(t=>t.id===e))return!1;let r=t?tL.current.map(r=>r.id===e?t:r):tL.current.filter(t=>t.id!==e);return tL.current=r,eO(r),!0},[]),tW=(0,i.useCallback)((e,t)=>{if(!tL.current.some(t=>t.attachmentId===e))return!1;let r=tL.current.map(r=>r.attachmentId===e?t(r):r);return tL.current=r,eO(r),!0},[]),tF=(0,i.useCallback)((e,t,r)=>{if(!e||e===tM.current)return;let n=aS(e);n?.documents.some(e=>e.attachmentId===t)&&aC(e,{...n,documents:sg(n.documents).map(e=>e.attachmentId===t?r(e):e).map(sx)})},[]),t_=(0,i.useRef)(new Map),tD=(0,i.useRef)(new Map),tH=(0,i.useRef)(new Set),tO=(0,i.useCallback)((e,t,r)=>{if(!e.storedInfo)return null;let n=Math.min(12e4,24e4-r.reduce((t,r)=>t+(r.attachmentId===e.attachmentId?0:r.text.length),0)),i=nf({...e.storedInfo,transcript:t},n);return i.length>n?null:{...e,text:i,size:new TextEncoder().encode(i).byteLength,transcription:void 0}},[]),tB=(0,i.useCallback)(e=>e instanceof sb&&"media_tool_unavailable"===e.code?eh("chat.transcribeToolMissing"):e instanceof sb&&"transcription_failed"===e.code&&null!==e.completedParts&&null!==e.parts?eh("chat.transcribePartialFailed",{done:e.completedParts,total:e.parts}):e instanceof Error?e.message:String(e),[eh]),tU=(0,i.useCallback)(async(e,t)=>{let r=tM.current,n=tL.current.find(t=>t.attachmentId===e);if(!n?.storedInfo)return;let i=n.transcription?.state==="confirm"?n.transcription.plan:null;tD.current.get(e)?.abort();let a=new AbortController;tD.current.set(e,a),tW(e,e=>({...e,transcription:{state:"running",plan:i}}));try{let n=await sw(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{confirmed:!0}:{}),signal:a.signal}));if("string"!=typeof n.transcript)throw new sb("Invalid transcription result",null,null,null);let i=n.transcript;tW(e,e=>tO(e,i,tL.current)??{...e,transcription:{state:"failed",error:eh("chat.transcribeTooLong")}})||tF(r,e,e=>tO(e,i,[])??e)}catch(r){if(a.signal.aborted)return void tW(e,e=>({...e,transcription:{state:"skipped"}}));if(r instanceof sb&&"confirmation_required"===r.code)return void tq.current?.(e);let t=tB(r);tW(e,e=>({...e,transcription:{state:"failed",error:t}}))}finally{tD.current.get(e)===a&&tD.current.delete(e)}},[eh,tB,tW,tF,tO]),tq=(0,i.useRef)(null),tK=(0,i.useCallback)(async e=>{let t;tD.current.get(e)?.abort();let r=new AbortController;tD.current.set(e,r),tW(e,e=>({...e,transcription:{state:"planning"}}));try{t=function(e){if("boolean"!=typeof e.requiresConfirmation||"number"!=typeof e.estimatedCalls||"string"!=typeof e.notice||null!==e.durationSeconds&&"number"!=typeof e.durationSeconds||"direct"!==e.processing&&"compress-and-split"!==e.processing)throw new sb("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await sw(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{cache:"no-store",signal:r.signal})))}catch(t){if(r.signal.aborted)tW(e,e=>({...e,transcription:{state:"skipped"}}));else{let r=tB(t);tW(e,e=>({...e,transcription:{state:"failed",error:r}}))}return}finally{tD.current.get(e)===r&&tD.current.delete(e)}t.requiresConfirmation?tW(e,e=>({...e,transcription:{state:"confirm",plan:t}})):await tU(e,!1)},[tU,tB,tW]);tq.current=tK;let tV=(0,i.useCallback)(e=>{let t=tD.current.get(e);t?t.abort():tW(e,e=>({...e,transcription:{state:"skipped"}}))},[tW]),tJ=(0,i.useCallback)(async(e,t)=>{let r=null;for(let n of e){if(tL.current.length>=3){eU(eh("chat.attachLimit",{count:3}));continue}let e="file"===t&&n.size<=8388608,i={id:++a7,name:n.name,mimeType:"text/plain",size:e?n.size:0,text:"",status:e?"extracting":"uploading",sourceSize:n.size},a=[...tL.current,i];tL.current=a,eO(a);let s=(e,t)=>{let r=tL.current.filter(e=>e.id!==i.id);return e<=12e4&&r.reduce((e,t)=>e+t.text.length,0)+e<=24e4&&r.reduce((e,t)=>e+t.size,0)+t<=0x1000000};if(e){let e=await n.arrayBuffer().then(e=>{var t;return 255===(t=new Uint8Array(e))[0]&&254===t[1]?na("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?na("utf-16be",t.subarray(2)):t.includes(0)?null:na("utf-8",t)??na("euc-kr",t)},()=>null);if(null!==e&&s(e.length,n.size)){tP(i.id,{...i,text:e,status:"ready"});continue}}if(null===r&&(r=1048576*(await aB().catch(()=>aD)).uploadLimitMb),n.size>r){tP(i.id,null)&&eU(eh("chat.attachStoredTooLarge",{name:n.name,limit:nc(r)}));continue}let l={...i,stored:t,status:"uploading",size:0};if(!tP(i.id,l))continue;let o=tM.current??sy,d=await aE(o),c=null,u=new AbortController;t_.current.set(i.id,u);try{if(tH.current.has(i.id))continue;let e=await nm(n,{sessionId:Q,draftId:d.draftId,signal:u.signal}),r=tL.current.filter(e=>e.id!==i.id).reduce((e,t)=>e+t.text.length,0),a=nf({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-r)),p=new TextEncoder().encode(a).byteLength;if(!s(a.length,p)){tP(i.id,null)&&eU(eh("chat.attachTotalTooLarge",{limit:nc(0x1000000)}));continue}let h={...l,attachmentId:e.id,text:a,size:p,status:"ready",storedInfo:{path:e.path,size:e.size,mimeType:e.mimeType},..."audio"===t?{transcription:{state:"planning"}}:{}};if(tP(i.id,h))c=e.id;else if(!tH.current.has(i.id)&&o!==tM.current){let t=aS(o)??{value:"",images:[],documents:[]};aC(o,{...t,documents:[...t.documents,sx(h)]}),c=e.id}}catch(e){if(u.signal.aborted)continue;tP(i.id,null)&&eU(eh("chat.attachUploadFailed",{name:n.name,error:e instanceof Error?e.message:String(e)}))}finally{t_.current.delete(i.id),d.end(c)}c&&"audio"===t&&tL.current.some(e=>e.attachmentId===c)&&tK(c)}},[tP,tK,Q,eh]),tG=(0,i.useCallback)(async e=>{eU(null);let{images:t,documents:r,audio:n,files:i}=function(e){let t=[],r=[],n=[],i=[];for(let a of e)a.type.startsWith("image/")?t.push(a):null!==nr(a)?r.push(a):ni(a)?n.push(a):i.push(a);return{images:t,documents:r,audio:n,files:i}}(e),a=r.filter(e=>e.size>8388608);await Promise.all([tz(t),tA(r.filter(e=>e.size<=8388608)),tJ(n,"audio"),tJ([...i,...a],"file")])},[tA,tJ,tz]),tY=(0,i.useCallback)(e=>{eD(t=>{let r=[...t],[n]=r.splice(e,1);return n&&sk(n),tR.current=r,r})},[]),tX=(0,i.useCallback)(e=>{let t=tL.current.find(t=>t.id===e);if(tH.current.add(e),t_.current.get(e)?.abort(),t?.attachmentId){tD.current.get(t.attachmentId)?.abort();var r=t.attachmentId;for(let[e,t]of ah)t.delete(r)&&(0===t.size&&ah.delete(e),aF())}let n=tL.current.filter(t=>t.id!==e);tL.current=n,eO(n)},[]),tQ=(0,i.useCallback)(()=>{tR.current=[],eD(e=>(e.forEach(sk),[]))},[]),t0=(0,i.useCallback)(()=>{tL.current=[],eO([])},[]),t1=(0,i.useCallback)(()=>{t$.current="",ev(""),e2(null),e7(!1),Z&&aN(Z),tM.current&&tM.current!==Z&&aN(tM.current),tQ(),t0(),eU(null),tc.current&&(tc.current.style.height="auto")},[t0,tQ,Z]);(0,i.useEffect)(()=>{Z&&tM.current===Z&&aC(Z,{value:ex,images:e_.map(su),documents:eq.map(sx)})},[e_,Z,eq,ex]),(0,i.useEffect)(()=>{let e=tM.current;if(e===Z)return;e&&aC(e,{value:t$.current,images:tR.current.map(su),documents:tL.current.filter(e=>"ready"===e.status).map(sx)});let t=Z?aS(Z):null;tM.current=Z;let r=t?.value??"",n=sh(t?.images),i=sg(t?.documents);t$.current=r,tR.current=n,tL.current=i,ev(r),e2(null),e7(!1),eD(e=>(e.forEach(sk),n)),eO(i)},[Z]),(0,i.useEffect)(()=>{let e=tc.current;e&&(e.style.height="auto",ex&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[ex]),(0,i.useEffect)(()=>()=>{tR.current.forEach(sk)},[]);let t2=(0,i.useCallback)((e,t)=>{let r=function(e,t){let r=aM(t);if(0===r.length)return()=>{};let n=++au;return ac.set(n,{draftId:a$(e),ids:r}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=ac.get(n);if(t){if(ac.delete(n),"accepted"===e){let e=af.get(t.draftId)??new Set;for(let r of t.ids)e.add(r);af.set(t.draftId,e)}aF()}}}(tM.current??sy,e);Promise.resolve(t()).then(e=>r("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),t4=(0,i.useCallback)(async()=>{let t=ex.trim(),r=eJ.trim(),n=r.startsWith("/")||r.startsWith("!")?r:t;if(!n&&!e_.length&&!eq.length||l||eK)return;G?.();let i=e_.length?e_:void 0,a=eq.length?eq:void 0;if(n.startsWith("/")){await a0(n,B,K,t=>t2(a,()=>e(t,i,a)),eU,!!(i||a),q)&&t1();return}t1(),t2(a,()=>e(n,i,a))},[ex,eJ,e_,eq,eK,l,K,B,q,e,t1,G,t2]),t5=eJ.startsWith("/")&&!/\s/.test(eJ.slice(1))?eJ.slice(1).toLowerCase():null,t8=(()=>{if(null===t5)return[];let e=[...l?[]:si,...B??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),r=sd(e,eh).toLowerCase();return t.includes(t5)||r.includes(t5)}).sort((e,t)=>{let r=so(e,t5,eh)-so(t,t5,eh);return 0!==r?r:sl[e.source]-sl[t.source]||a3.compare(e.name,t.name)}).filter(e=>{let r=e.name.toLowerCase();return!t.has(r)&&(t.add(r),!0)})})(),{commands:t6,groups:t7}=(en=0,{commands:(ei=sa.map(e=>{let t=t8.filter(t=>t.source===e),r="skill"===e?[...t.filter(e=>!sc(e,td)),...t.filter(e=>sc(e,td))]:t;return{source:e,items:r.map(e=>({command:e,index:en++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:ei}),t9=1===t8.length?eh(t5?"chat.match":"chat.command"):eh(t5?"chat.matches":"chat.commands",{count:t8.length}),re=!!ex.trim(),rt=!eK&&(re||e_.length>0||eq.length>0),rr=(0,i.useCallback)((e,t)=>{if(!X)return void e2(null);let r=t??e.length;e2(aq(e.slice(0,r)))},[X]),rn=e1?.query??null,ri=i.useMemo(()=>null!==rn&&tt&&tt.cwd===X?function(e,t,r=20){let n=t.toLowerCase();if(!n)return e.slice(0,r);let i=[];for(let t of e){let e=function(e,t){let r=e.path.toLowerCase(),n=0;if(t.includes("/"))r===t?n=100:r.startsWith(t)?n=80:r.includes(t)?n=50:aV(t,r)&&(n=10);else{let e=r.lastIndexOf("/"),i=-1===e?r:r.slice(e+1);i===t?n=100:i.startsWith(t)?n=80:i.includes(t)?n=50:r.includes(t)?n=30:aV(t,r)&&(n=10)}return e.isDir&&n>0&&(n+=10),n}(t,n);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||aK(e.entry.path)-aK(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,r).map(e=>e.entry)}(tt.entries,rn):[],[rn,tt,X]),ra=!!(rn&&tt?.truncated&&tt.cwd===X);(0,i.useEffect)(()=>{if(!ra||!X||!rn)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(X)}&q=${encodeURIComponent(rn)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>ts({cwd:X,query:rn,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[ra,rn,X]);let rs=ra&&null!==ta&&ta.cwd===X&&ta.query===rn,rl=rs?ta.matches:ri,ro=null===e1?null:`${e1.start}:${+!!e1.quoted}:${e1.query}`;(0,i.useEffect)(()=>{if(null===ro){e5(!1),e6(0);return}e5(!0),e6(0)},[ro]);let rd=null!==e1,rc=aX(tb,e3,{viewportFraction:.44,cap:360}),ru=aX(tb,eZ,{viewportFraction:.56,cap:460}),rh=aX(tb,e4,{viewportFraction:.48,cap:400});(0,i.useEffect)(()=>{if(!rd||!X)return;let e=tI.current;e&&e.cwd===X&&Date.now()-e.fetchedAt<1e4||tT.current===X||(tT.current=X,ti(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{tr({cwd:X,entries:function(e){let t=new Set;for(let r of e){let e=r.indexOf("/");for(;-1!==e;)t.add(r.slice(0,e)),e=r.indexOf("/",e+1)}let r=[];for(let e of t)r.push({path:e,isDir:!0});for(let t of e)t&&r.push({path:t,isDir:!1});return r.sort((e,t)=>aK(e.path)-aK(t.path)||e.path.localeCompare(t.path)),r}(e.files??[]),truncated:!!e.truncated}),tI.current={cwd:X,fetchedAt:Date.now()}}).catch(()=>{tI.current=null}).finally(()=>{tT.current=null,ti(!1)}))},[rd,X]);let rf=(0,i.useCallback)(e=>{if(!e1)return;let t=tc.current,r=t?.selectionStart??ex.length,n=ex.slice(0,e1.start),i=ex.slice(r);e1.quoted&&i.startsWith('"')&&(i=i.slice(1));let a=function(e,t,r=!1){let n=t?`${e}/`:e,i=r||n.includes(" ");if(t){let e=i?`@"${n}"`:`@${n}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let a=i?`@"${n}" `:`@${n} `;return{text:a,cursorOffset:a.length}}(e.path,e.isDir,e1.quoted),s=n+a.text+i,l=n.length+a.cursorOffset;ev(s),e2(aq(s.slice(0,l))),requestAnimationFrame(()=>{let e=tc.current;e&&(e.focus(),e.setSelectionRange(l,l),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[e1,ex]);(0,i.useEffect)(()=>{e8>=rl.length&&e6(Math.max(0,rl.length-1))},[rl.length,e8]),(0,i.useEffect)(()=>{tC.current.length=rl.length},[rl.length]),(0,i.useEffect)(()=>{e4&&tC.current[e8]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e8,e4]),(0,i.useEffect)(()=>{e9>=D.length&&te(Math.max(0,D.length-1))},[D.length,e9]),(0,i.useEffect)(()=>{tN.current.length=D.length},[D.length]),(0,i.useEffect)(()=>{e3&&tN.current[e9]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e9,e3]);let rm=(0,i.useCallback)(e=>{t$.current=e,ev(e),e7(!1),te(0),e2(null),requestAnimationFrame(()=>{let t=tc.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),rg=(0,i.useCallback)(e=>{let t=`/${e.name} `;t$.current=t,ev(t),eX(!1),e0(0),requestAnimationFrame(()=>{let e=tc.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),rx=(0,i.useCallback)(async e=>{let t=ex.trim(),n=eJ.trim(),i=n.startsWith("/")||n.startsWith("!")?n:t,s=eK||!i&&0===e_.length&&0===eq.length?null:{message:i,images:e_.length?e_:void 0,documents:eq.length?eq:void 0};if(!s)return;G?.();let l="steer"===e?"steer":"followUp";if(i.startsWith("/")){await a0(i,B,K,e=>{if(!Y)throw Error("Cannot queue this command while the session is busy.");t2(s.documents,()=>Y(e,l,s.images,s.documents))},eU,!!(s.images?.length||s.documents?.length),q)&&t1();return}t1(),"steer"===e&&r?t2(s.documents,()=>r(s.message,s.images,s.documents)):"followup"===e&&a&&t2(s.documents,()=>a(s.message,s.images,s.documents))},[ex,eJ,e_,eq,eK,B,q,K,Y,r,a,t1,G,t2]),rv=(0,i.useCallback)(e=>{let t=t6.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eQ-1);if("right"===e)return Math.min(t,eQ+1);let r=tS.current[eQ];if(!r)return"down"===e?Math.min(t,eQ+1):Math.max(0,eQ-1);let n=r.getBoundingClientRect(),i=n.left+n.width/2,a=n.top+n.height/2,s=-1,l=1/0;for(let r=0;r<=t;r+=1){if(r===eQ)continue;let t=tS.current[r];if(!t)continue;let n=t.getBoundingClientRect(),o=n.top+n.height/2-a;if("down"===e?o<=4:o>=-4)continue;let d=1e3*Math.abs(o)+Math.abs(n.left+n.width/2-i);d<l&&(s=r,l=d)}return s>=0?s:"down"===e?Math.min(t,eQ+1):Math.max(0,eQ-1)},[t6.length,eQ]),rb=(0,i.useCallback)(e=>{let n=e.nativeEvent,i=Date.now()-tk.current<100,s=tw.current||n.isComposing||229===n.keyCode;if("Enter"===e.key&&!e.shiftKey&&(s||i)){i&&e.preventDefault();return}if(e3&&!s){if("ArrowDown"===e.key){e.preventDefault(),te(e=>Math.min(Math.max(0,D.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),te(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e7(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&D[e9]){e.preventDefault(),rm(D[e9]);return}}if(eZ&&null!==t5){if("ArrowDown"===e.key){e.preventDefault(),e0(rv("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e0(rv("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e0(rv("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e0(rv("left"));return}if("Escape"===e.key){e.preventDefault(),eX(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&t6[eQ]){e.preventDefault(),rg(t6[eQ]);return}}if(e4&&null!==e1&&!s){if("ArrowDown"===e.key){e.preventDefault(),e6(e=>Math.min(Math.max(0,rl.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),e6(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e5(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&rl[e8]){e.preventDefault(),rf(rl[e8]);return}}if("ArrowUp"===e.key&&!s&&!l&&D.length>0&&0===ex.trim().length){e.preventDefault(),eX(!1),e5(!1),te(D.length-1),e7(!0);return}if("Escape"===e.key&&!s&&l&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),l&&(r||a)?rx(r?"steer":"followup"):t4())},[l,r,a,t,eZ,t5,t6,eQ,rg,rx,t4,rv,e4,e1,rl,e8,rf,e3,D,e9,rm,ex]),rw=(0,i.useCallback)(()=>{let e=tc.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),rk=(0,i.useCallback)(e=>{let t=function(e){let t=Array.from(e.files??[]);if(t.length>0)return t;let r=[];for(let t of Array.from(e.items??[])){if("file"!==t.kind)continue;let e=t.getAsFile();e&&r.push(e)}return r}(e.clipboardData);t.length&&(e.preventDefault(),tG(t))},[tG]);(0,i.useEffect)(()=>{if(null===t5){eX(!1),e0(0),tj.current=!1;return}eX(!0),e0(0),!tj.current&&q&&(tj.current=!0,Promise.resolve(q()).catch(()=>{tj.current=!1}))},[t5,q]),(0,i.useEffect)(()=>{if(!eZ||!X)return;let e=!1;return to({cwd:X,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let r={};for(let e of t.skills??[])r[e.name]=e.disableModelInvocation;to({cwd:X,values:r})}).catch(()=>{e||to({cwd:X,values:{}})}),()=>{e=!0}},[eZ,X]),(0,i.useEffect)(()=>{eQ>=t6.length&&e0(Math.max(0,t6.length-1))},[t6.length,eQ]),(0,i.useEffect)(()=>{tS.current.length=t6.length},[t6.length]),(0,i.useEffect)(()=>{eZ&&tS.current[eQ]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eQ,eZ]);let rS=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(se):Object.entries(c??{}).map(([e,t])=>({provider:o?.provider??"unknown",modelId:e,name:t})).sort(se),rC=g??null,rN=t3.bo.find(e=>e.alias===rC)?.provider??null,rI=rN?rS.filter(e=>e.provider===rN):rS,rT=(ea=ej.trim().toLocaleLowerCase())?rI.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(ea)):rI,rM=rI.length>8,r$=[];for(let e of rT){let t=r$.find(t=>t.provider===e.provider);t?t.options.push(e):r$.push({provider:e.provider,options:[e]})}let rR=rN?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),rE=o?rR.find(e=>e.resolved?.provider===o.provider&&e.resolved?.modelId===o.modelId):void 0,rL=ej.trim()?[]:rI.map((e,t)=>{var r,n;return{option:e,order:t,count:eC[r=e.provider,n=e.modelId,`${r}/${n}`]??0}}).filter(e=>e.count>=2).sort((e,t)=>t.count-e.count||e.order-t.order).slice(0,5).map(({option:e,count:t})=>({option:e,count:t})),rz=(e,t,r)=>{let i=e.modelId===o?.modelId&&e.provider===o?.provider;return(0,n.jsxs)("button",{onClick:()=>{if(ey(!1),eS(""),!i||d){var t,r;let n=function(e,t){let r={...e,[t]:(e[t]??0)+1},n=Object.keys(r);if(n.length<=30)return r;for(let e of(n.sort((e,t)=>r[e]-r[t]),n)){if(Object.keys(r).length<=30)break;e!==t&&delete r[e]}return r}(aG(),(t=e.provider,r=e.modelId,`${t}/${r}`));try{window.localStorage.setItem(aJ,JSON.stringify(n))}catch{}eN(n),f?.(e.provider,e.modelId)}},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,n.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,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),e.name,void 0!==r&&r>=2&&(0,n.jsx)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10.5},children:eh("chat.modelPickCount",{count:r})})]},`${t}:${e.provider}:${e.modelId}`)},rA=o?rS.find(e=>e.modelId===o.modelId&&e.provider===o.provider)?.name??o.modelId:null,rP=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,rW=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:eh("chat.compacted")} ${tZ(S.tokensBefore)} -> ${tZ(S.estimatedTokensAfter)} tokens (${eh("chat.tokensSaved",{saved:tZ(rP)})})`:null,rF=e=>{let t=L?.[e];return null!=t&&t!==e?t:null},r_="auto"===(es=I??"auto")?M?`auto ≤ ${rF(M)??M}`:"auto":L?L[es]??es:es,rD=(I??"auto")==="auto"&&T&&"auto"!==T?L?.[T]??T:null,rH=$&&rD?eh("chat.currentReasoning",{level:rD}):null,rO=e=>!E||E.includes(e),rB=[{level:"auto",ceiling:null},...sr.filter(rO).map(e=>({level:"auto",ceiling:e})),...st.filter(e=>"auto"!==e&&rO(e)).map(e=>({level:e,ceiling:null}))],rU=Object.entries(a4).find(([,e])=>e===(C??"default"))?.[0]??"default";(0,i.useEffect)(()=>{let e=e=>{tu.current&&!tu.current.contains(e.target)&&tp.current&&!tp.current.contains(e.target)&&(ey(!1),eS("")),th.current&&!th.current.contains(e.target)&&tf.current&&!tf.current.contains(e.target)&&eT(!1),tm.current&&!tm.current.contains(e.target)&&eE(!1),tg.current&&!tg.current.contains(e.target)&&ez(!1),tx.current&&!tx.current.contains(e.target)&&eF(!1),!tv.current||tv.current.contains(e.target)||tc.current?.contains(e.target)||e7(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{eg||eF(!1)},[eg]);let rq=(0,n.jsx)("button",{type:"button",className:`composer-icon-button${e_.length||eH.length?" is-active":""}`,onClick:()=>ty.current?.click(),title:eh("chat.attachFile"),"aria-label":eh("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:e_.length||eH.length?"var(--accent)":"var(--text-muted)",cursor:"pointer",opacity:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=e_.length||eH.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=e_.length||eH.length?"var(--accent)":"var(--text-muted)"},children:(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,n.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,n.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),rK=m&&t3.bo.length>0?(0,n.jsxs)("div",{ref:th,style:{position:"relative",flexShrink:+!!eg,minWidth:0},children:[(0,n.jsxs)("button",{className:`${eg?"composer-icon-button":"composer-chip"}${eI?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();e$({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ey(!1),eS(""),eT(e=>!e)},disabled:l||b,"aria-haspopup":"menu","aria-expanded":eI,onKeyDown:e=>{"Escape"===e.key&&eI&&(e.stopPropagation(),eT(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:eI?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l||b?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eI?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:eh("chat.mainPreset"),"aria-label":eh("chat.mainPreset"),children:[(0,n.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,n.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"})}),eg?null:(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:eh("chat.mainPreset")})]}),eI&&eM&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:r}=aY(eM.top,eM.bottom,e,aZ(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eM.top+6}:{top:eM.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eM.left,width:"max-content",minWidth:eM.width};return(0,n.jsx)("div",{ref:tf,role:"menu","aria-label":eh("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(eT(!1),th.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:r,display:"flex",flexDirection:"column"},children:(0,n.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:t3.bo.map(e=>{let t=e.alias===rC;return(0,n.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eT(!1),m((0,t3.zq)(e))},title:`${e.provider}/${e.model}`,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:t?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,n.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,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("img",{className:"account-avatar",src:(0,t3.uk)(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,n.jsx)("span",{children:e.alias}),(0,n.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[e.provider,"/",e.model,void 0!==e.oauthPosition?` \xb7 OAuth ${e.oauthPosition}`:""]})]},e.alias)})})})})()]}):null,rV=$?(0,n.jsxs)("div",{ref:tg,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,n.jsxs)("button",{type:"button",className:`${eg?"composer-icon-button":"composer-chip"}${eL?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eP({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ey(!1),eS(""),eT(!1),ez(e=>!e)},disabled:l||b,"aria-haspopup":"menu","aria-expanded":eL,onKeyDown:e=>{"Escape"===e.key&&eL&&(e.stopPropagation(),ez(!1))},title:eh("chat.changeReasoning",{level:r_}),"aria-label":eh("chat.changeReasoning",{level:r_}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eg?0:"8px 12px",height:32,background:eL?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l||b?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eL?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,n.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,n.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,n.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,n.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),eg?null:(0,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:r_})]}),eL&&eA&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:r}=aY(eA.top,eA.bottom,e,aZ(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eA.top+6}:{top:eA.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eA.left,width:"max-content",minWidth:Math.max(180,eA.width)};return(0,n.jsx)("div",{role:"menu","aria-label":eh("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(ez(!1),tg.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:r},children:rB.map(({level:e,ceiling:t})=>{let r=(I??"auto")===e&&("auto"!==e||(M??null)===t),i=t??e,a="auto"===e&&null===t?null:rF(i),s=t?`auto ≤ ${a??t}`:a??e,l=t?eh("chat.thinkingAutoCapped",{level:a??t}):eh(sn[e]);return(0,n.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":r,onClick:()=>{ez(!1),$(e,t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:r?"var(--bg-selected)":"none",border:"none",color:r?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:r?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[r?(0,n.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,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsxs)("span",{style:{flex:1},children:[s,null!==a&&(0,n.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",i,")"]})]}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:l})]},t?`auto-${t}`:e)})})})()]}):null,rJ=P?(el=A?eh("chat.fastModeBusy"):null===z?eh("chat.fastModeUnknown"):z.active?eh("chat.fastModeActive"):z.enabled?eh("chat.fastModeInactive"):eh("chat.fastModeOff"),eo=A||l||b,ed=z?.enabled===!0,(0,n.jsx)("button",{type:"button",className:`composer-icon-button${z?.active?" is-active":""}`,onClick:P,disabled:eo,"aria-pressed":null===z?void 0:z.enabled,"aria-busy":A||void 0,title:el,"aria-label":el,style:{flexShrink:0,opacity:l?.5:1},children:(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:z?.active?"var(--accent)":"none",stroke:ed?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===z?"3 2":void 0,style:{opacity:ed&&!z?.active?.6:1},"aria-hidden":"true",children:(0,n.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})):null,rG=(0,n.jsxs)(n.Fragment,{children:[r&&(0,n.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>rx("steer"),disabled:!rt,title:eK?eh("chat.attachExtractingWait"):eh("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:rt?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:rt?"var(--warning)":"var(--text-dim)",cursor:rt?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,n.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),eh("chat.steer")]}),a&&(0,n.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>rx("followup"),disabled:!rt,title:eK?eh("chat.attachExtractingWait"):eh("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:rt?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:rt?"var(--accent-hover)":"var(--text-dim)",cursor:rt?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,n.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,n.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),eh("chat.followUp")]})]}),rY=void 0!==J?(0,n.jsx)(i2,{soundEnabled:V??!0,onToggle:J}):null;return(0,n.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,n.jsx)("input",{ref:ty,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{tG(Array.from(e.target.files??[])),e.target.value=""}}),(0,n.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:[(0,n.jsx)(sS,{error:p}),(0,n.jsx)(sC,{warnings:h}),_.length>0&&(0,n.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",padding:"5px 0"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,n.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:ef("delivery.title",{count:_.length})}),H&&em&&(0,n.jsxs)("button",{onClick:H,title:eh("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:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,n.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),eh("chat.recall")]})]}),(0,n.jsx)(iQ,{rows:_,removeLabel:eh("chat.queueRemove"),onRemove:O?(e,t)=>O("steer"===e?"steering":"followUp",t):void 0})]}),F&&(0,n.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,n.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,n.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,n.jsx)("path",{d:"M3 3v5h5"})]}),eh("chat.retrying",{attempt:F.attempt,max:F.maxAttempts}),F.errorMessage&&(0,n.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",F.errorMessage]})]}),rW&&(0,n.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,n.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,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),rW]}),j&&(0,n.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:j}),eB&&(0,n.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,n.jsx)("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"},children:eB}),(0,n.jsx)("button",{type:"button",onClick:()=>eU(null),"aria-label":eh("i18n.close"),title:eh("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,n.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,n.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,n.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(e_.length>0||eH.length>0)&&(0,n.jsxs)("div",{role:"list","aria-label":eh("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[e_.map((e,t)=>(0,n.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,n.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",display:"block"}}),(0,n.jsx)("button",{type:"button","aria-label":eh("chat.removeImage",{index:t+1}),onClick:()=>tY(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,n.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,n.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,n.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},`image-${t}`)),eH.map(e=>(0,n.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||a1(e)||void 0,style:{display:"flex",alignItems:"center",gap:7,minWidth:0,maxWidth:320,height:32,padding:"0 7px 0 9px"},children:["ready"!==e.status||e.transcription?.state==="planning"||e.transcription?.state==="running"?(0,n.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"}}):rj(e.name,14),(0,n.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,n.jsx)("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:e.name}),(0,n.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===e.stored?eh("chat.attachKindAudio"):"file"===e.stored?eh("chat.attachKindFile"):a9[e.mimeType]," \xb7 ",nc(e.sourceSize??e.size),"extracting"===e.status?` \xb7 ${eh("chat.attachExtracting")}`:"","uploading"===e.status?` \xb7 ${eh("chat.attachUploading")}`:"",e.transcription?.state==="planning"?` \xb7 ${eh("chat.transcribeChecking")}`:"",e.transcription?.state==="confirm"?` \xb7 ${eh("chat.attachTranscribePending")}`:"",e.transcription?.state==="running"?` \xb7 ${eh("chat.attachTranscribing")}`:"",e.transcription?.state==="failed"&&(0,n.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${eh("chat.attachTranscribeFailed")}`})]})]}),(0,n.jsx)("button",{type:"button",onClick:()=>tX(e.id),"aria-label":eh("chat.removeAttachment",{name:e.name}),title:eh("chat.removeAttachment",{name:e.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,n.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,n.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,n.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},e.id))]}),eV.length>0&&(0,n.jsx)("div",{role:"group","aria-label":eh("chat.transcribeGroup"),"aria-live":"polite",style:{display:"flex",flexDirection:"column",gap:6,marginBottom:6},children:eV.map(e=>{let t,r,i,a,l=e.attachmentId,o=e.transcription,d=o?.state==="confirm"||o?.state==="running"?o.plan:null,c=d?eh("chat.transcribePlanSummary",{duration:null===d.durationSeconds?eh("chat.transcribeDurationUnknown"):(r=Math.floor((t=Math.round(d.durationSeconds))/3600),i=Math.floor(t%3600/60),a=String(t%60).padStart(2,"0"),r>0?`${r}:${String(i).padStart(2,"0")}:${a}`:`${i}:${a}`),calls:d.estimatedCalls}):null,u=o?.state==="confirm"?eh("chat.transcribeConfirmTitle",{name:e.name}):o?.state==="running"?eh("chat.transcribeRunning",{name:e.name}):o?.state==="planning"?`${e.name} \xb7 ${eh("chat.transcribeChecking")}`:o?.state==="failed"?eh("chat.transcribeFailedRow",{name:e.name,error:o.error}):eh("chat.transcribeSkipped",{name:e.name});return(0,n.jsxs)("div",{"data-transcription-state":o?.state??"idle",style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"7px 10px",border:`1px solid ${o?.state==="failed"?"var(--danger-line)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:o?.state==="failed"?"var(--danger-soft)":"var(--bg-panel)",fontSize:12,lineHeight:1.45},children:[(0,n.jsxs)("div",{style:{flex:"1 1 220px",minWidth:0},children:[(0,n.jsx)("div",{style:{color:o?.state==="failed"?"var(--danger)":"var(--text)",overflowWrap:"anywhere"},children:u}),c&&(0,n.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:c}),o?.state==="confirm"&&(0,n.jsxs)(n.Fragment,{children:[o.plan.notice&&(0,n.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:o.plan.notice}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:eh("chat.transcribeUsageNotice")})]})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[o?.state==="confirm"&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void tU(l,!0),children:eh("chat.transcribeStart")}),(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tV(l),children:eh("chat.transcribeSkip")})]}),(o?.state==="planning"||o?.state==="running")&&(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tV(l),children:eh("chat.transcribeCancel")}),(void 0===o||"skipped"===o.state||"failed"===o.state)&&(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void tK(l),children:eh(o?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,n.jsxs)("div",{ref:tb,style:{position:"relative",minWidth:0},children:[e3&&D.length>0&&(0,n.jsxs)("div",{ref:tv,style:{position:"absolute",left:0,right:0,...a6(rc.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:rc.maxHeight},children:[(0,n.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,n.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,n.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,n.jsx)("path",{d:"M3 4v5h5"}),(0,n.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,n.jsx)("div",{style:{maxHeight:Math.max(0,rc.maxHeight-31),overflowY:"auto",padding:4},children:D.map((e,t)=>{let r=t===e9;return(0,n.jsxs)("button",{ref:e=>{tN.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),rm(e)},onMouseEnter:()=>te(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:"var(--radius-control)",background:r?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,n.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,n.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),eZ&&null!==t5&&(0,n.jsxs)("div",{style:{position:"absolute",left:0,right:0,...a6(ru.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:ru.maxHeight},children:[(0,n.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,n.jsx)("span",{children:U?eh("chat.loadingCommands"):eh("chat.slashCommands",{label:t9})}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,n.jsx)("div",{style:{maxHeight:Math.max(0,ru.maxHeight-34),overflowY:"auto",padding:10},children:U||0!==t8.length?t7.map(e=>(0,n.jsxs)("section",{style:{marginBottom:12},children:[(0,n.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,n.jsx)("span",{children:eh(ss[e.source])}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,n.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(({command:e,index:t})=>{let r=t===eQ,i=sc(e,td);return(0,n.jsxs)("button",{ref:e=>{tS.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),rg(e)},onMouseEnter:()=>e0(t),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${r?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:r?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:r?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,n.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:i?"var(--text-dim)":void 0},children:["/",e.name,i&&(0,n.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:eh("chat.dormant")})]}),sd(e,eh)&&(0,n.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:sd(e,eh)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,n.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eh("chat.noCommands")})})]}),e4&&null!==e1&&(ec=tn&&(!tt||tt.cwd!==X),eu=1===rl.length?eh("chat.match"):eh("chat.matches",{count:rl.length}),ep=tt?.truncated&&!rs?e1.query?eh("chat.searchingAll"):eh("chat.indexTruncated"):"",(0,n.jsxs)("div",{style:{position:"absolute",left:0,right:0,...a6(rh.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:rh.maxHeight},children:[(0,n.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,n.jsx)("span",{children:ec?eh("chat.loadingFiles"):eh("chat.files",{label:eu,hint:ep})}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,n.jsx)("div",{style:{maxHeight:Math.max(0,rh.maxHeight-34),overflowY:"auto",padding:4},children:ec||0!==rl.length?rl.map((e,t)=>{let r=t===e8,i=e.path.split("/").pop()??e.path,a=e.path.slice(0,e.path.length-i.length);return(0,n.jsxs)("button",{ref:e=>{tC.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),rf(e)},onMouseEnter:()=>e6(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:"var(--radius-control)",background:r?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,n.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,n.jsx)(ry,{size:14}):rj(i,14)}),(0,n.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[a&&(0,n.jsx)("span",{style:{color:"var(--text-dim)"},children:a}),i,e.isDir&&(0,n.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,n.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:ra&&!rs?eh("chat.searching"):eh("chat.noMatchingFiles")})})]})),(0,n.jsxs)("div",{className:`chat-composer-field${eG?" is-bash":""}${l?" is-streaming":""}`,style:{minWidth:0,display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:`1px solid ${eG?"var(--tool-bg)":l&&(r||a)?"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,n.jsx)("textarea",{className:"chat-composer-textarea",ref:tc,value:ex,onChange:e=>{t$.current=e.target.value,ev(e.target.value),e7(!1),rr(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;rr(t.value,t.selectionStart)},onKeyDown:rb,onCompositionStart:()=>{tw.current=!0},onCompositionEnd:e=>{tw.current=!1,tk.current=Date.now();let t=e.currentTarget;rr(t.value,t.selectionStart)},onInput:rw,onPaste:rk,placeholder:l&&(r||a)?eh("chat.steerPlaceholder"):l?eh("chat.agentPlaceholder"):eh("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"}}),l?eg?null:(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:rG}):(0,n.jsxs)("button",{className:"chat-composer-send",onClick:t4,disabled:!rt,"aria-busy":eK||void 0,"aria-label":eg?eh("chat.send"):void 0,title:eK?eh("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eg?44:void 0,padding:eg?0:"7px 14px",background:rt?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:rt?"var(--accent-hover)":"var(--text-dim)",cursor:rt?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 0.15s"},children:[(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,n.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),eg?null:eh("chat.send")]})]})]}),eG&&(0,n.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eY?"var(--text-muted)":"var(--accent)",marginTop:4},children:[eh("chat.shell")," \xb7 ",eY?eh("chat.outputLocal"):eh("chat.outputModel")]}),(0,n.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,n.jsxs)("div",{style:{flex:eg?"1 1 0%":"0 0 auto",minWidth:eg?"min-content":0,display:"flex",alignItems:"center",gap:2},children:[(!eg||!l)&&rq,!eg&&rK,!(eg&&l)&&(rS.length>0||rA||p)&&f&&(0,n.jsxs)("div",{ref:tu,style:{position:"relative",flex:eg?"1 1 0%":void 0,width:eg?0:void 0,minWidth:44*!!eg},children:[(0,n.jsxs)("button",{className:`composer-chip${eb?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();ek({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ey(e=>(e&&eS(""),!e))},disabled:l||b,"aria-busy":b||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:eg?"flex-start":void 0,padding:eg?"8px 10px":"8px 12px",height:32,width:eg?"100%":void 0,maxWidth:eg?"100%":220,overflow:"hidden",background:eb?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l||b?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eb?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:b?"Switching model":rS.length>0?"Change model":"No available models",children:[b?(0,n.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,n.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,n.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,n.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,n.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,n.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,n.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,n.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,n.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,n.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,n.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:rA??(rS.length>0?"Select model":"No models")})]}),eb&&ew&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:r}=aY(ew.top,ew.bottom,e,aZ(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ew.top+6}:{top:ew.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ew.left,width:"max-content",minWidth:ew.width};return(0,n.jsxs)("div",{ref:tp,style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:r,display:"flex",flexDirection:"column"},children:[rM&&(0,n.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,n.jsx)("input",{value:ej,onChange:e=>eS(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eS(""),ey(!1))},placeholder:eh("chat.filterModels"),"aria-label":eh("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!eg,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,n.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[rL.length>0&&(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eh("chat.frequentModels")}),rL.map(({option:e,count:t})=>rz(e,"frequent",t))]}),rR.length>0&&!ej.trim()&&v&&(0,n.jsxs)("div",{style:{borderTop:rL.length>0?"1px solid var(--border)":"none"},children:[(0,n.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eh("chat.modelRoles")}),rR.map(e=>{let t=rE?.role===e.role,r=e.resolved?.name??e.resolved?.modelId??"";return(0,n.jsxs)("button",{onClick:()=>{ey(!1),eS(""),v(e.role)},title:e.selector??r,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,n.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,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("span",{style:{flexShrink:0,minWidth:58,padding:"1px 6px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-subtle)",color:t?"var(--accent)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:e.tag??e.role.toUpperCase()}),(0,n.jsx)("span",{style:{fontWeight:t?600:500},children:e.name}),(0,n.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[r,e.resolved?.thinkingLevel?` \xb7 ${e.resolved.thinkingLevel}`:""]})]},e.role)}),(0,n.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:eh("chat.allModels")})]}),0===r$.length?(0,n.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:ej.trim()?eh("chat.noMatchingModels"):"No available models"}):r$.map((e,t)=>(0,n.jsxs)("div",{children:[r$.length>1&&(0,n.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:t>0?"1px solid var(--border)":"none"},children:e.provider}),e.options.map(e=>rz(e,"all"))]},e.provider))]})]})})()]}),eg&&l&&(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:rG}),!eg&&rV,!eg&&rJ,!eg&&rH&&(0,n.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:rH}),(0,n.jsx)(ar,{sessionId:Q})]}),(0,n.jsxs)("div",{ref:tx,style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:eg?4:2},children:[eg?(0,n.jsx)("button",{type:"button",className:`composer-icon-button${eW?" is-active":""}`,title:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eW,onClick:()=>{ey(!1),eS(""),eF(e=>!e)},children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,n.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,n.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,n.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:eW?void 0:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eW,onClick:()=>{ey(!1),eS(""),eF(e=>!e)},children:eh("chat.moreControls")}),(0,n.jsxs)("div",{role:"group","aria-label":eh("chat.moreControls"),style:{display:eW?"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:[eg&&(0,n.jsxs)(n.Fragment,{children:[l&&rq,rK,rV,rJ]}),!l&&N&&(0,n.jsxs)("div",{ref:tm,style:{position:"relative"},children:[(0,n.jsxs)("button",{className:`composer-chip${eR?" is-active":""}`,onClick:()=>!l&&eE(e=>!e),disabled:l,title:eh("chat.changeToolPreset")+`: ${rU}`,"aria-label":eh("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:eR?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eR?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.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,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:rU})]}),eR&&(0,n.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:a2.map(e=>{let t=a4[e],r=(C??"default")===t,i="off"===e?eh("chat.noTools"):"default"===e?eh("chat.builtInTools",{tools:a5}):eh("chat.allBuiltInTools",{tools:`${a5} + ${a8}`});return(0,n.jsxs)("button",{onClick:()=>{eE(!1),r||N(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:r?"var(--bg-selected)":"none",border:"none",color:r?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:r?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[r?(0,n.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,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("span",{style:{flex:1},children:e}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:i})]},e)})})]}),!l&&y&&(0,n.jsx)("div",{children:(0,n.jsx)("button",{className:`composer-chip${k?" is-active is-danger":""}`,onClick:k?w:y,disabled:l&&!k,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:k?"var(--danger-soft)":"none",border:"none",borderRadius:"var(--radius-control)",color:k?"var(--danger)":"var(--text-muted)",cursor:l&&!k?"not-allowed":"pointer",fontSize:12,opacity:l&&!k?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!l||k)&&(e.currentTarget.style.background=k?"var(--danger-soft)":"var(--bg-hover)",e.currentTarget.style.color=k?"var(--danger)":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=k?"var(--danger-soft)":"none",e.currentTarget.style.color=k?"var(--danger)":"var(--text-muted)"},title:k?eh("chat.stopCompaction"):eh("chat.compactContext"),"aria-label":k?eh("chat.stopCompaction"):eh("chat.compactContext"),children:k?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,n.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(0,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compacting")})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,n.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,n.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,n.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(0,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compact")})]})})}),eg&&rY,eW&&(0,n.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:eh("chat.collapseControls"),"aria-label":eh("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eE(!1),ez(!1),eF(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,n.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),l&&(0,n.jsxs)("button",{className:"composer-chip is-danger is-active",onClick:t,title:eh("chat.stopAgent"),"aria-label":eg?eh("chat.stopAgent"):void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eg?44:void 0,padding:eg?0:"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:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--danger-soft)"},children:[(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,n.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),eg?null:eh("chat.stop")]}),(0,n.jsx)(ae,{sessionId:Q,onEnsureSession:ee,onTranscriptPersisted:et}),!eg&&rY]})]})]})]})});function sI({statuses:e}){if(0===e.length)return null;let t=[...e].sort((e,t)=>e.key.localeCompare(t.key)).map(({text:e})=>e.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()).join(" "),r=ej(t);return(0,n.jsx)("div",{role:"status","aria-label":r,title:r,style:{display:"flex",alignItems:"center",flexShrink:0,minWidth:0,height:36,padding:"0 12px",borderTop:"1px solid var(--border)",background:"transparent"},children:(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,textOverflow:"ellipsis",whiteSpace:"nowrap"},children:eT(t).map((e,t)=>(0,n.jsx)("span",{style:e.style,children:e.text},t))})})}function sT({phases:e}){let{t}=(0,R.s)(),[r,a]=(0,i.useState)(!1),[s,l]=(0,i.useState)(!1),{currentPhase:o,activeTask:d,remaining:c,completed:u,total:p,percent:h}=e7(e);if(0===p)return null;let f=0===c;return(0,n.jsxs)("div",{className:`todo-strip${f?" is-done":""}`,children:[(0,n.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":r,onClick:()=>a(e=>!e),children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:f?"✓":"›"}),o&&(0,n.jsx)("span",{className:"todo-strip-phase",children:o.name}),(0,n.jsx)("span",{className:"todo-strip-task",children:f?t("todo.allDone",{count:u}):d?.content??""}),(0,n.jsx)("span",{className:"todo-strip-count",children:f?t("todo.progressDone",{percent:h??0,completed:u,total:p}):t("todo.progress",{percent:h??0,completed:u,total:p,remaining:c})})]}),r&&(0,n.jsxs)("div",{className:"todo-strip-body",children:[e.map((t,r)=>{let i=t.tasks.filter(e=>s||"completed"!==e.status);return 0===i.length?null:(0,n.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[e.length>1&&(0,n.jsx)("div",{className:"todo-checklist-phase-name",children:t.name}),i.map((e,t)=>(0,n.jsx)(rx,{task:e},`${e.content}-${t}`))]},`${t.name}-${r}`)}),u>0&&(0,n.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":s,onClick:()=>l(e=>!e),children:t(s?"todo.hideCompleted":"todo.showCompleted",{count:u})})]})]})}function sM(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function s$(e){switch(e.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==e.closed;default:return!1}}async function sR(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let r={body:e.body,...e.tag?{tag:e.tag}:{}};if(t.getServiceWorkerRegistration)try{let n=await t.getServiceWorkerRegistration();if(n)return await n.showNotification(e.title,{...r,data:{url:e.sessionUrl}}),"service-worker"}catch{}try{let n=t.createWindowNotification(e.title,r);return n.onclick=()=>{n.close(),e.onClick()},"window"}catch{return null}}var sE=r(62503);class sL extends Error{constructor(e,t,r,n){super(e),this.status=t,this.code=r,this.accepted=n,this.name="AgentCommandError"}}async function sz(e,t){let r=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),n=await r.json().catch(()=>({}));if(!r.ok||n.error)throw new sL(n.error??`HTTP ${r.status}`,r.status,n.code,n.accepted);return n.data}let sA="ompweb-update-client-id",sP="ompweb-update-resume-intent-v2",sW="ompweb-update-return-v1",sF="cuelo-restart-return-v1",s_="ompweb-update-failure-return-v1",sD="ompweb:update-wake";function sH(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function sO(){let e=sessionStorage.getItem(sA);if(e&&/^[A-Za-z0-9_-]{16,128}$/.test(e))return e;let t="function"==typeof crypto.randomUUID?crypto.randomUUID().replaceAll("-",""):Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("");return sessionStorage.setItem(sA,t),t}function sB(){sessionStorage.removeItem(sP)}function sU(){let e=sessionStorage.getItem(sW);if(!e)return null;try{let t=JSON.parse(e);if(1!==t.schemaVersion||"string"!=typeof t.requestId||!/^[0-9a-f]{32}$/.test(t.requestId)||"string"!=typeof t.stageHash||!/^[0-9a-f]{64}$/.test(t.stageHash)||"boolean"!=typeof t.dismissed)return null;return t}catch{return null}}function sq(e){let t=sU();if(!t||t.requestId!==e)return t;let r={...t,dismissed:!0};try{sessionStorage.setItem(sW,JSON.stringify(r))}catch{}return r}async function sK(e){let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"heartbeat",clientId:sO(),sessionId:e.sessionId,resumeUrl:e.resumeUrl,preservationError:e.preservationError??null,...e.update?{requestId:e.update.requestId,stageHash:e.update.stageHash}:{}}),cache:"no-store"});if(!t.ok)throw Error(`maintenance heartbeat HTTP ${t.status}`);return await t.json()}async function sV(e){if(e.sessionId){let t=await fetch(`/api/sessions/${encodeURIComponent(e.sessionId)}?deferThinking=1&deferMedia=1`,{cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(!t.ok)throw Error(`session resume HTTP ${t.status}`);if((await t.json()).sessionId!==e.sessionId)throw Error("resumed session identity mismatch")}let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"resume-confirm",requestId:e.requestId,stageHash:e.stageHash,clientId:e.clientId,sessionId:e.sessionId}),cache:"no-store"});if(!t.ok)throw Error(`resume confirm HTTP ${t.status}`);let r=await t.json().catch(()=>null);!function(e){let t=sU();if(t&&t.requestId===e.requestId&&t.stageHash===e.stageHash)return;let r={schemaVersion:1,requestId:e.requestId,stageHash:e.stageHash,dismissed:!1};try{sessionStorage.setItem(sW,JSON.stringify(r))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),sB();let n=r?.wake;e.sessionId&&(n?.wake===!0||n?.reason==="already-claimed"||n?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(sD,{detail:{sessionId:e.sessionId}}))}async function sJ(e){let t=function(e){let t=sessionStorage.getItem(s_);if(!t)return null;sessionStorage.removeItem(s_);try{let r=JSON.parse(t);if(1!==r.schemaVersion||r.requestId!==e.requestId||r.stageHash!==e.stageHash||r.clientId!==e.clientId)return null;return{wake:!0===r.wake}}catch{return null}}(e);return t?(sB(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(sD,{detail:{sessionId:e.sessionId}})),"failed"):(await sV(e),"resumed")}function sG(e,t){let r=new Map(e.map(e=>[e.id,e]));for(let e of t)r.set(e.id,function(e,t){return e&&(void 0!==e.parentToolCallId&&void 0!==t.parentToolCallId?e.parentToolCallId===t.parentToolCallId:void 0===e.sessionFile||void 0===t.sessionFile||e.sessionFile===t.sessionFile)?{...t,index:e.index,agent:e.agent,agentSource:e.agentSource,description:e.description??t.description,task:e.task??t.task,assignment:e.assignment??t.assignment,sessionFile:t.sessionFile??e.sessionFile,parentToolCallId:t.parentToolCallId??e.parentToolCallId}:t}(r.get(e.id),e));let n=[...r.values()];return[...n.filter(e=>"pending"===e.status||"running"===e.status).sort((e,t)=>e.index-t.index||e.id.localeCompare(t.id)),...n.filter(e=>"pending"!==e.status&&"running"!==e.status).sort((e,t)=>t.lastUpdate-e.lastUpdate||e.id.localeCompare(t.id))].slice(0,128)}function sY(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"update":return{isStreaming:!0,streamingMessage:t.message};case"end":case"reset":return{isStreaming:!1,streamingMessage:null};default:return e}}function sZ(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function sX(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function sQ(e){return t=>{let r=e?.isCompacting?e.compaction:null;if(!r)return t;let n=Date.now()-r.elapsedMs;return{startedAt:t?Math.min(t.startedAt,n):n,reason:t?.reason??r.reason}}}function s0(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){let n=e[r],i=t[r];if(!n||!i||n.name!==i.name||n.tasks.length!==i.tasks.length)return!1;for(let e=0;e<n.tasks.length;e+=1){let t=n.tasks[e],r=i.tasks[e];if(!t||!r||t.content!==r.content||t.status!==r.status||t.blocker!==r.blocker)return!1}}return!0}function s1(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function s2(e,t){for(let r=e.length-1;r>=0;r--){let n=t[r]??null;if(!eJ(n??void 0))return{message:e[r],entryId:n}}return null}let s4=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class s5 extends Error{constructor(e){super("timeout"===e?"Timed out connecting to the agent event stream. Please try again.":"Failed to connect to the agent event stream. Please try again."),this.status=e,this.name="EventStreamConnectionError"}}function s8(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function s6(e){return new Promise(t=>setTimeout(t,e))}function s3(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,r)=>r===t?{...e,exiting:!0}:e)}function s7(e,t){switch(t.type){case"add":if(e.visible.some(e=>e.exiting)||e.visible.length>=5)return{visible:e.visible.some(e=>e.exiting)?e.visible:s3(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:s3(e.visible)};case"remove":return function(e,t){let r=e,n=t;for(;n.length>0&&r.length<5;){let[e,...t]=n;r=[...r,e],n=t}return n.length>0&&!r.some(e=>e.exiting)&&(r=s3(r)),{visible:r,pending:n}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function s9(e){if(!e||"object"!=typeof e||"image"!==e.type)return"";let t=e.source;return t&&"object"==typeof t?["url"===t.type?"url":"base64","string"==typeof t.media_type?t.media_type:"","string"==typeof t.data?t.data:"","string"==typeof t.url?t.url:""].join(":"):["base64","string"==typeof e.mimeType?e.mimeType:"","string"==typeof e.data?e.data:"",""].join(":")}function le(e){let t,r=e.content;return"string"==typeof r?JSON.stringify({text:r,images:[]}):Array.isArray(r)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:r.map(s9).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function lt(e){return"user"===e.role?`user:${le(e)}`:"bashExecution"===e.role?JSON.stringify({role:e.role,command:e.command,output:e.output,exitCode:e.exitCode,cancelled:e.cancelled,truncated:e.truncated,fullOutputPath:e.fullOutputPath,excludeFromContext:e.excludeFromContext}):JSON.stringify({role:e.role,content:e.content,model:e.model,provider:e.provider,customType:e.customType})}function lr(e,t){return e&&"object"==typeof e?"number"!=typeof e.tokensBefore||"number"!=typeof e.estimatedTokensAfter?null:{reason:t,tokensBefore:e.tokensBefore,estimatedTokensAfter:e.estimatedTokensAfter}:null}function ln(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}function li(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let la=!1,ls={width:0,height:0},ll=new Set,lo=null;function ld(){let e=window.visualViewport,t=li();ls.width!==window.innerWidth?ls={width:window.innerWidth,height:window.innerHeight}:t||(ls.height=Math.max(ls.height,window.innerHeight));let r=function({hasFocusedEditable:e,innerHeight:t,viewportHeight:r,viewportScale:n,baselineHeight:i}){return!(!e||Math.abs(n-1)>=.01)&&(t-r>120||i-t>120)}({hasFocusedEditable:t,innerHeight:window.innerHeight,viewportHeight:e?.height??window.innerHeight,viewportScale:e?.scale??1,baselineHeight:ls.height});if(r!==la)for(let e of(la=r,ll))e()}function lc(e){if(ll.add(e),!lo){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,ld()})},r=window.visualViewport;r?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),ld(),lo=()=>{r?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{ll.delete(e),0===ll.size&&lo&&(lo(),lo=null)}}function lu(){return(0,i.useSyncExternalStore)(lc,()=>la,()=>!1)}let lp={count:50,end:null};function lh(e,t){let r=Math.max(e,0),n=null===t.end?r:Math.min(Math.max(t.end,0),r),i=Math.min(Math.max(t.count,0),n),a=n-i;return{startIndex:a,endIndex:n,hasMore:a>0,hasLater:n<r}}function lf(e,t,r){let{startIndex:n,endIndex:i}=lh(e,r);if(t>=n&&t<i)return r;let a=Math.max(0,t-10),s=Math.max(t+1,a+50);return s>=e?{count:e-a,end:null}:{count:s-a,end:s}}function lm({sticker:e,text:t,tag:r,followRef:a}){let s=(0,i.useRef)(null);return((0,i.useEffect)(()=>{(!a||a.current)&&s.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,n.jsxs)("div",{ref:s,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,n.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:iv[r]}),t&&(0,n.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,n.jsx)(ih(),{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 lg(e){if("user"!==e.role)return null;let t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),r=(nd(t)?.message??t).trim();return r.length>0?r:null}function lx(e){return`omp-cues:${e}`}function lv(e,t){let r=[];for(let n of t)n.sessionId===e&&null!==n.anchorEntryId&&r.push({id:n.id,anchorEntryId:n.anchorEntryId,sticker:n.sticker,text:n.text,tag:n.tag});try{window.localStorage.setItem(lx(e),JSON.stringify(r.slice(-200)))}catch{}}let lb=[];function ly(e){return`omp-web:interrupted-dismissed:${e}`}let lw=(0,i.memo)(function({messages:e,entryIds:t,toolResultsMap:r,modelNames:a,messageCwd:s,onOpenFile:l,sessionBusy:o,isNew:d,isStreaming:c,handleFork:u,forkingEntryId:p,handleNavigate:h,handleEditContent:f,sessionId:m,main:g,process:x,dispatchSlots:v,compactedDispatch:b,startIndex:y,endIndex:w,sentinelRef:k,laterSentinelRef:j,flashItem:S,t:C,onProcessLogChange:N,cues:I,cueFollowRef:T}){(0,i.useEffect)(()=>{N({groups:x,messages:e,entryIds:t,toolResults:r,modelNames:a,cwd:s,sessionId:m})},[N,x,e,t,r,a,s,m]);let M=(0,i.useMemo)(()=>{let t=new Map;for(let[n,i]of function(e,t,r,n){let i=new Map;e.forEach((e,t)=>{"answer"===e.kind&&i.set(e.idx,t)});let a=new Map,s=new Map;for(let e of t){let t=s.get(e.anchorIdx);for(let l of(t||(t=new Set,s.set(e.anchorIdx,t)),e.entries)){let e=r[l.idx];if(e?.role!=="assistant")continue;let s=Math.max(0,(l.blocks?i.get(l.idx):void 0)??l.afterMainIndex??-1),o=t;!function(e,t,r){for(let n of e){if("toolCall"!==n.type||"learn"!==n.toolName&&"manage_skill"!==n.toolName)continue;let e=t?.get(n.toolCallId);if(!e||e.isError)continue;let i=n.input??{};if("manage_skill"===n.toolName){let e=eX(i.action);if(!0===eZ[e]){let t={kind:"skill",action:e,name:eX(i.name)};r(JSON.stringify(t),t)}continue}let a=eX(i.memory),s=i.skill,l=s?{action:eX(s.action),name:eX(s.name)}:void 0;r(JSON.stringify({kind:"lesson",memory:a,skill:l}),{kind:"lesson",memory:a.length>160?`${a.slice(0,160)}…`:a,...l?{skill:l}:{}})}}(l.blocks??e.content??[],n,(e,t)=>{if(o.has(e))return;o.add(e);let r=a.get(s);r?r.push(t):a.set(s,[t])})}}return a}(g,x,e,r)){let e=i.map(e=>{if("skill"===e.kind)return C("chat.savedSkill",{action:e.action,name:e.name});let t=C("chat.savedLesson",{memory:e.memory});return e.skill?`${t} (${C("chat.savedSkill",e.skill)})`:t});t.set(n,{role:"custom",customType:eq,content:[C("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[g,x,e,r,C]),$=(0,i.useMemo)(()=>{let t=null;if(o)for(let r of g)"message"===r.kind&&e[r.idx]?.role==="user"&&(t=r.idx);let n=new Map;for(let[i,a]of function(e,t,r){let n=new Map,i=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user").map(e=>e.idx),a=new Map;for(let[s,l]of(e.forEach((e,t)=>{"answer"===e.kind&&a.set(e.anchorIdx,t)}),a)){if(s===r)continue;let e=i.find(e=>e>s);n.set(l,{from:s+1,to:e??t.length})}return n}(g,e,t))n.set(i,function(e,t,r){let n=[],i=[];for(let r of e){if("toolCall"!==r.type)continue;if("task"===r.toolName){i.push(r);continue}if("bash"!==r.toolName)continue;let e="string"==typeof r.input.command?r.input.command.trim():"";if(!e||!ie.test(e))continue;let a=t.get(r.toolCallId),s=a?function(e){let t=e.details;if("number"==typeof t?.exitCode)return t.exitCode;let r=e.content.map(e=>"text"===e.type?e.text:"").join("\n"),n=/Command exited with code (-?\d+)\s*$/.exec(r.trimEnd());return n?Number(n[1]):null}(a):null,l=null===s?a?.isError?"failed":"unobserved":0===s?"passed":"failed";n.push({toolCallId:r.toolCallId,command:e,state:l,exitCode:s})}return{checks:n,dispatchCalls:i,files:e8(e,t,r)}}(function(e,t,r){let n=[];for(let i=Math.max(0,t);i<Math.min(e.length,r);i++){let t=e[i];"assistant"===t.role&&n.push(...t.content??[])}return n}(e,a.from,a.to),r,s));return n},[g,e,r,s,o]),R=y>0,E=w<g.length,L=(i,g={})=>{let x=g.messageOverride??e[i],v=i-1;for(;v>=0&&eJ(t[v]);)v-=1;let b="user"===x.role&&v>=0&&"assistant"===e[v].role?t[v]:void 0,y=g.keyPrefix??"message",w=!1;if("assistant"===x.role){w=!0;for(let t=i+1;t<e.length;t++){let r=e[t].role;if("user"===r)break;if("assistant"===r){w=!1;break}}w&&c&&i===e.length-1&&(w=!1)}return void 0!==g.showTimestamp&&(w=g.showTimestamp),(0,n.jsx)(nL,{message:x,toolResults:r,modelNames:a,cwd:s,onOpenFile:l,entryId:t[i],onFork:o||d||0===i&&"user"===x.role?void 0:u,forking:p===t[i],onNavigate:o?void 0:h,prevAssistantEntryId:o?void 0:b,onEditContent:f,showTimestamp:w,prevTimestamp:i>0?e[i-1].timestamp:void 0,sessionId:m,writtenFiles:g.writtenFiles,dispatchSlot:g.dispatchSlot,turnSummary:g.turnSummary},`${y}-view-${i}`)},z=(t,r)=>{let i=g[t],a="message"===i.kind&&e[i.idx]?.role==="user";return(0,n.jsx)("div",{"data-chat-item":t,"data-chat-question":a?"":void 0,className:S===t?"chat-item chat-jump-flash":"chat-item",children:r})};return(0,n.jsxs)(n.Fragment,{children:[R&&(0,n.jsx)("div",{ref:k,className:"py-3 text-center text-xs text-text-muted",children:C("chat.loadEarlier",{count:y})}),g.slice(y,w).map((a,o)=>{let d=y+o,c=b?.position===d?(0,n.jsx)(r2,{calls:b.calls}):null,u="message"===a.kind?a.anchorIdx??a.idx:a.anchorIdx,p=g[d+1],h=p?"message"===p.kind?p.anchorIdx??p.idx:p.anchorIdx:null,f=p?p.idx:1/0,x=I.filter(r=>{let n=null!==r.anchorEntryId?t.indexOf(r.anchorEntryId):Math.min(r.liveIndex??-1,e.length-1);return n>=a.idx&&n<f}).map(e=>(0,n.jsx)(lm,{sticker:e.sticker,text:e.text,tag:e.tag,followRef:T},`cue-${e.id}`)),w=h!==u,k=M.get(d),j=k?(0,n.jsx)(nL,{message:k,cwd:s,onOpenFile:l},`saved-lessons-${d}`):null,S=w?(0,n.jsx)(iE,{turnIndex:u,turnEntryId:t[u],sessionId:m,cwd:s,onOpenFile:l}):null;if("message"===a.kind)return(0,n.jsxs)(i.Fragment,{children:[c,z(d,L(a.idx)),j,S,x]},`message-${a.idx}`);let C=e8(a.precedingBlocks,r,s);return(0,n.jsxs)(i.Fragment,{children:[c,z(d,L(a.idx,{keyPrefix:`answer-${a.runIndex}`,messageOverride:eA(e[a.idx],a.blocks),writtenFiles:C,dispatchSlot:v.get(d),turnSummary:$.get(d)})),j,S,x]},`answer-${a.idx}-${a.runIndex}`)}),b?.position===g.length&&w===g.length&&(0,n.jsx)(r2,{calls:b.calls}),E&&(0,n.jsx)("div",{ref:j,className:"py-3 text-center text-xs text-text-muted",children:C("chat.loadLater",{count:g.length-w})})]})});function lk({session:e,newSessionCwd:t,initialSessionData:a,transitioning:s=!1,onAgentEnd:l,onAttentionNeeded:o,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:f,onSessionStatsChange:m,onSessionStatsPanelOpen:g,onContextUsageChange:x,onSubagentsChange:b,onMainIdentityChange:y,onOpenWorkspaceView:w,onProcessLogChange:k,onOpenFile:j,transcriptReplacement:S,onComposerFocusChange:C,onSessionBusyChange:N,onWaitingChange:I,onAttentionChange:T,soundEnabled:M=!0,onSoundToggle:$,playCueSound:E=async()=>({sticker:null,text:null}),preloadCueSound:L,unlockAudio:z,jumpRequest:A=null,onJumpHandled:P}){var _,D;let H,O,B,{t:U}=(0,R.s)(),q=lu(),K=W(),J=q&&K,G=(0,i.useRef)(E);G.current=E;let Y=(0,i.useRef)(null),Z=(0,i.useRef)(L);Z.current=L;let[X,Q]=(0,i.useState)([]),ee=(0,i.useRef)(X);ee.current=X;let et=(0,i.useRef)(0),er=(0,i.useRef)([]),en=(0,i.useRef)([]),ei=(0,i.useRef)(null),ea=(0,i.useRef)(0),es=(0,i.useRef)(-1),el=(0,i.useRef)(-1),eo=(0,i.useCallback)(()=>{let e=ei.current?.current;return e?{sessionId:e,turn:ea.current}:null},[]),ed=(0,i.useCallback)(e=>ei.current?.current===e.sessionId&&ea.current===e.turn,[]),ec=(0,i.useCallback)((e,t,r,n)=>{if(!e.sticker&&!e.text)return;et.current=Math.max(et.current+1,Date.now());let i={id:et.current,sticker:e.sticker,text:e.text,tag:t,sessionId:r.sessionId},a="entry"===n.kind?{...i,anchorEntryId:n.entryId}:{...i,anchorEntryId:null,liveIndex:n.liveIndex,intent:n.intent};Q(e=>{let t=[...e,a];return null!==a.anchorEntryId&&lv(r.sessionId,t),t})},[]),eu=(0,i.useCallback)((e,t,r,n)=>{let i=()=>ed(r)&&("working"!==t||el.current!==r.turn);i()&&G.current(e,t,i).then(e=>{null!==t&&null!==n&&i()&&ec(e,t,r,n)}).catch(()=>{})},[ed,ec]),ep=(0,i.useCallback)(async(e,t,r)=>{let n=(await rd(e,t,r))?.alias??null;return n&&Z.current?.(n),n},[]),eh=(0,i.useCallback)((e,t,r,n)=>{let i=function(e,t){let r=e.length-1;if(r<0)return null;let n=Math.min(e.length,t.length);if(r<n)return{kind:"entry",entryId:t[r]};let i=iN(e[r]),a=0;for(let t=n;t<=r;t++)iN(e[t])===i&&(a+=1);return{kind:"pending",liveIndex:r,intent:{baseEntryId:n>0?t[n-1]:null,identity:i,occurrence:a}}}(er.current,en.current);ep(t.sessionId,r,n).then(r=>{eu(r,e,t,i)})},[eu,ep]),[ef,em]=(0,i.useState)(0),eg=(0,i.useRef)([]),ex=(0,i.useCallback)(e=>{if(ea.current+=1,null!==iy(e.outcome)){let t=e.sessionId;eg.current.push({completion:e,trigger:t?{sessionId:t,turn:ea.current}:null}),em(e=>e+1)}l?.(e)},[l]);(0,i.useEffect)(()=>{for(let{completion:e,trigger:t}of eg.current.splice(0)){let r=iy(e.outcome),n="neutral"===r?null:r;t?eh(n,t,e.provider,e.credentialId):G.current(null,n).catch(()=>{})}},[ef,eh]);let ev=(0,i.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:eb,error:ey,messages:ew,entryIds:ek,streamState:eS,agentRunning:eC,bashRunning:eN,pendingBash:eI,modelNames:eT,modelList:eM,modelError:e$,modelScopeWarnings:eR,modelThinkingLevels:eE,modelThinkingLevelMaps:eL,modelRoles:ez,toolPreset:eP,thinkingLevel:eD,effectiveThinkingLevel:eO,thinkingCeiling:eB,fastMode:eq,fastModeBusy:eZ,handleFastModeToggle:eX,retryInfo:e0,contextUsage:e1,forkingEntryId:e2,isCompacting:e4,compaction:e5,compactError:e8,compactResult:e6,displayModel:e7,modelSwitching:e9,sessionStats:te,runStateKnown:tt,compactedWork:tr,slashCommands:tn,slashCommandsLoading:ti,deliveryRows:ta,subagents:ts,todoPhases:tl,notices:to,extensionDialog:td,extensionResponse:tc,extensionCustomUi:tu,extensionStatuses:tp,extensionWidgets:th,respondToExtensionUi:tf,sendExtensionCustomInput:tm,isAutoModelSelection:tg,agentPhase:tx,isNew:tv,autoFollowPaused:tb,resumeAutoFollow:ty,pauseAutoFollow:tw,goalStatus:tk,sessionIdRef:tj,messagesEndRef:tS,scrollContainerRef:tC,handleSend:tN,handleAbort:tI,handleFork:tT,handleNavigate:tM,handleModelChange:t$,handleRoleModelChange:tR,handleMainPresetChange:tE,newSessionAccount:tL,handleCompact:tz,handleSteer:tA,handleFollowUp:tP,handlePromptWithStreamingBehavior:tW,handleAbortCompaction:tF,handleRecallQueue:t_,handleRemoveQueuedMessage:tD,handleBuiltinSlashCommand:tH,handleToolPresetChange:tO,handleThinkingLevelChange:tB,loadSlashCommands:tU,ensureNewSession:tq,refreshLiveTranscript:tK}=function(e){let{session:t,newSessionCwd:n,initialData:a,onAgentEnd:s,onAttentionNeeded:l,onSessionCreated:o,onSessionForked:d,modelsRefreshKey:c,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,f=null===t&&null!==n,m=a&&a.sessionId===t?.id?a:null,[g,x]=(0,i.useState)(m),[v,b]=(0,i.useState)(!f&&!m),[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(m?.leafId??null),[S,C]=(0,i.useState)(m?.context.messages??[]),[N,I]=(0,i.useState)(m?.context.entryIds??[]),[T,M]=(0,i.useState)(m?.context.compactedWork??null),[$,R]=(0,i.useReducer)(sY,{isStreaming:!1,streamingMessage:null}),[E,L]=(0,i.useState)(!1),[z,A]=(0,i.useState)(!1),[P,W]=(0,i.useState)(null),[F,_]=(0,i.useState)({}),[D,H]=(0,i.useState)([]),[O,B]=(0,i.useState)(null),[U,q]=(0,i.useState)([]),[K,V]=(0,i.useState)({}),[J,G]=(0,i.useState)({}),[Y,Z]=(0,i.useState)([]),[X,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(null),[er,en]=(0,i.useState)(null),[ei,ea]=(0,i.useState)("default"),[es,el]=(0,i.useState)(()=>{let e=m?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[eo,ed]=(0,i.useState)(),[ec,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(null),[ef,em]=(0,i.useState)(!1),eg=(0,i.useRef)(0),ex=(0,i.useRef)(0),ev=(0,i.useRef)(""),[eb,ey]=(0,i.useState)(null),[ew,ek]=(0,i.useState)(m?.contextUsage??null),[eS,eC]=(0,i.useState)(null),[eN,eI]=(0,i.useState)(null),[eT,eM]=(0,i.useState)(null),[e$,eR]=(0,i.useState)(null),[eE,eL]=(0,i.useState)(!1),[ez,eA]=(0,i.useState)(!1),[eP,eW]=(0,i.useState)(null),[eF,e_]=(0,i.useState)(null),[eD,eH]=(0,i.useState)(null),eO=(0,i.useRef)(null),[eB,eq]=(0,i.useState)(!1),[eK,eY]=(0,i.useState)(null),[eZ,eX]=(0,i.useState)([]),[eQ,e0]=(0,i.useState)(!1),[e1,e2]=(0,i.useReducer)(s7,{visible:[],pending:[]}),[e4,e5]=(0,i.useState)(null),[e8,e6]=(0,i.useState)(null),[e3,e7]=(0,i.useState)(null),e9=(0,i.useRef)(null),[te,tt]=(0,i.useState)(null),[tr,tn]=(0,i.useState)([]),[ti,ta]=(0,i.useState)([]),[ts,tl]=(0,i.useState)({steering:[],followUp:[]}),[to,td]=(0,i.useState)([]),[tc,tu]=(0,i.useReducer)(iY,[]),tp=(0,i.useRef)(0);(0,i.useEffect)(()=>{tu({type:"queue",steering:ts.steering,followUp:ts.followUp})},[ts]),(0,i.useEffect)(()=>{E||tu({type:"idle"})},[E]),(0,i.useEffect)(()=>{tu({type:"reset"})},[t?.id]);let th=(0,i.useMemo)(()=>(function(e,t){let r=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${iJ(t)}`;r.set(e,(r.get(e)??0)+1)}let n=[],i=(e,t)=>{t.forEach((t,i)=>{let a=`${e}\u0000${iV(t)}`,s=r.get(a)??0;s>0?r.set(a,s-1):n.push({key:`queue-${e}-${i}`,kind:e,text:t,images:0,stage:"accepted",removable:!0})})};for(let r of(i("steer",t?.steering??[]),i("followUp",t?.followUp??[]),e))n.push({key:`sent-${r.id}`,kind:r.kind,text:r.text,images:r.images,stage:r.stage,removable:r.inQueue});return n})(tc,ts),[tc,ts]),[tf,tm]=(0,i.useState)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),tb=(0,i.useRef)(null),ty=(0,i.useRef)(null),tw=(0,i.useRef)(0),tk=(0,i.useRef)(!1),tj=(0,i.useRef)(t?.id??null),tS=(0,i.useRef)(m?.leafId??null),tC=(0,i.useRef)(S),tN=(0,i.useRef)(N);tC.current=S,tN.current=N;let tI=(0,i.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),tT=(0,i.useRef)(!1),tM=(0,i.useRef)(!1),t$=(0,i.useRef)(!1),tR=(0,i.useRef)(-1),tE=(0,i.useRef)("unknown"),tL=(0,i.useRef)(null),tz=(0,i.useRef)(null),tA=(0,i.useRef)(0),tP=(0,i.useRef)(!1),tW=(0,i.useRef)(0),tF=(0,i.useRef)(null),t_=(0,i.useRef)(null),tD=(0,i.useRef)(null),tH=(0,i.useRef)(!1),tO=(0,i.useRef)(!0),[tB,tU]=(0,i.useState)(!1),[tq,tK]=(0,i.useState)(null),tV=(0,i.useRef)(void 0),tJ=(0,i.useRef)(0),tG=(0,i.useRef)(0),tY=(0,i.useRef)(()=>{}),tZ=(0,i.useRef)(null),tX=(0,i.useRef)(null),tQ=(0,i.useRef)(null),t0=(0,i.useRef)(null),t1=(0,i.useRef)(!1),t2=(0,i.useRef)(null),t4=(0,i.useRef)(null),t5=(0,i.useRef)(null),t8=(0,i.useRef)(null),t6=(0,i.useRef)(0),t3=(0,i.useRef)(null),t7=(0,i.useRef)(null),t9=(0,i.useRef)(!1);t9.current=e.transitioning??!1;let re=(0,i.useRef)(Date.now()),rt=(0,i.useRef)(0),rr=(0,i.useRef)(0),rn=(0,i.useRef)(null),ri=(0,i.useRef)(!1),ra=(0,i.useRef)(Promise.resolve()),rs=e.setToolPreset??ea,rl=eT??g?.context.model??e$??null,ro=f?X??er:rl,rd=(0,i.useMemo)(()=>{if(e4)return{...e4,totalActiveMs:g?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},r=0,n=0,i=0,a=0,s=0;for(let t of S){if("user"===t.role&&(n+=1),"toolResult"===t.role&&(a+=1),"assistant"!==t.role)continue;i+=1;let l=t.usage;s+=t.content.filter(e=>"toolCall"===e.type).length,l&&(e.input+=l.input??0,e.output+=l.output??0,e.cacheRead+=l.cacheRead??0,e.cacheWrite+=l.cacheWrite??0,r+=l.cost?.total??0)}return(e.total=e.input+e.output+e.cacheRead+e.cacheWrite,0===e.total&&0===S.length)?null:{sessionFile:g?.filePath||void 0,sessionId:tj.current??t?.id??"",sessionName:t?.name,userMessages:n,assistantMessages:i,toolCalls:s,toolResults:a,totalMessages:S.length,tokens:e,cost:r,totalActiveMs:g?.totalActiveMs,...ew?{contextUsage:ew}:{}}},[S,e4,ew,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),rc=(0,i.useRef)(0),ru=(0,i.useCallback)((e,t)=>{e&&tj.current===e&&Array.isArray(t)&&(rc.current+=1,tm(r=>r?.sid===e&&s0(r.phases,t)?r:{sid:e,phases:t}))},[]),rp=(0,i.useCallback)((e,t,r)=>{tj.current===e&&rc.current===r&&Array.isArray(t)&&tm(r=>r?.sid===e&&s0(r.phases,t)?r:{sid:e,phases:t})},[]),rh=(0,i.useCallback)(e=>{let t="function"==typeof e?e(tC.current):e;tC.current=t,C(t)},[]),rf=(0,i.useCallback)(e=>{tN.current=e,I(e)},[]),rm=(0,i.useCallback)(async(e,t=!1,r=!1,n)=>{let i=!1;try{t&&b(!0);let a=n??null;if(!a){let r=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),n=await fetch(`/api/sessions/${encodeURIComponent(e)}?${r}`);if(404===n.status)return t&&(x(null),j(null),rh([]),M(null),w(null)),null;if(!n.ok)throw Error(`HTTP ${n.status}`);a=await n.json()}if(tj.current!==e)return null;x(a),j(a.leafId),tS.current=a.leafId??null;let s=eG(a.context.messages,a.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);rh(s.messages),rf(s.entryIds),M(a.context.compactedWork??null),ek(a.contextUsage??null),eM(e=>ri.current?e:null),w(null);let l=!r&&t8.current===e;if(l||(el(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)),eu(a.context.thinkingCeiling??null),i=!0,t&&b(!1),!r){if(l)try{let t=t6.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(r.ok&&tj.current===e){let n=await r.json();tj.current===e&&t6.current===t&&(n.state?.thinkingLevel!==void 0?(el(n.state.configuredThinkingLevel??n.state.thinkingLevel),ed(n.state.thinkingLevel)):n.running||(t8.current=null,el(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=rc.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let n=await r.json();if(tj.current!==e)return null;let i=n.state;return i?(void 0!==i.contextUsage&&ek(i.contextUsage??null),void 0!==i.systemPrompt&&eC(i.systemPrompt??null),void 0!==i.thinkingLevel&&(t8.current=e,el(i.configuredThinkingLevel??i.thinkingLevel),ed(i.thinkingLevel)),void 0!==i.thinkingCeiling&&eu(i.thinkingCeiling??null),void 0!==i.extensionStatuses&&tn(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&ta(i.extensionWidgets??[]),void 0!==i.queuedMessages&&tl(sZ(i.queuedMessages)),void 0!==i.subagents&&td(e=>sG(e,i.subagents??[])),rp(e,i.todoPhases,t)):n.running||tl({steering:[],followUp:[]}),n}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),null}finally{t&&!i&&b(!1)}},[rp,rf,rh]),rg=(0,i.useCallback)(e=>{let t=ra.current.then(async()=>{tj.current===e&&await rm(e)});return ra.current=t.catch(()=>{}),t},[rm]),rx=(0,i.useCallback)(async(e,t)=>{let r=++ex.current;try{let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&n.set("leafId",t);let i=`/api/sessions/${encodeURIComponent(e)}/context?${n}`,a=await fetch(i);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();if(ex.current!==r||tj.current!==e)return;tS.current=t;let l=eG(s.context.messages,s.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);rh(l.messages),rf(l.entryIds),M(s.context.compactedWork??null),ek(s.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[rf,rh]),rv=(0,i.useCallback)(async e=>{try{let t=await sz(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(r.bind(r,14755));rs(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[rs]),rb=(0,i.useCallback)((e=0,t="(no messages)")=>{let r=tj.current;f&&n&&r&&!t1.current&&(t1.current=!0,o?.({id:r,path:"",cwd:n,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t,transient:!0}))},[f,n,o]),ry=(0,i.useCallback)(async()=>{if(tQ.current)return tQ.current;let e=tj.current;if(e&&t7.current!==e||!e&&(!f||!n))return e;let t=(async()=>{let t=e;if(!t){let e=t2.current,r=t5.current,i=t4.current;e&&eR(e);let a={cwd:n,type:"ensure_session",toolNames:(0,aQ.xG)(ei),...e?{provider:e.provider,modelId:e.modelId}:{},...r?{thinkingLevel:r}:{},...e&&null!==i?{oauthPosition:i}:{}},s=JSON.stringify(a),l=t0.current,o=l?.body===s?l.createRequestId:s8();t0.current={body:s,createRequestId:o};let d=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...a,createRequestId:o})});if(!d.ok)throw Error(`HTTP ${d.status}`);let c=await d.json();t0.current=null,t=c.sessionId,tj.current=t,null!==t3.current&&(t7.current=t),c.model&&t2.current===e&&(eR(c.model),e||en(c.model)),c.thinkingLevel&&t5.current===r&&(el(c.configuredThinkingLevel??c.thinkingLevel),ed(c.thinkingLevel))}for(;t7.current===t;){let e=t3.current;await sz(t,{type:"set_thinking_ceiling",ceiling:e}),t3.current===e&&t7.current===t&&(t7.current=null)}return t})();tQ.current=t;try{return await t}finally{tQ.current=null}},[f,n,ei]),rw=(0,i.useCallback)(async()=>{let e=tj.current??await ry();if(!e)return eX([]),[];e0(!0);try{let t=await sz(e,{type:"get_commands"}),r=t?.commands??[];return eX(r),r}catch(e){return console.error("Failed to load slash commands:",e),eX([]),[]}finally{e0(!1)}},[ry]),rk=(0,i.useCallback)(()=>{tw.current+=1,tk.current=!1,ty.current&&(clearTimeout(ty.current),ty.current=null)},[]),rj=(0,i.useCallback)(()=>{tg.current?.close(),tg.current=null,tx.current=null,tv.current=null},[]),rS=(0,i.useCallback)(()=>{tb.current?.close(),tb.current=null},[]),rC=(0,i.useCallback)(e=>{rS();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);tb.current=t,t.onmessage=t=>{try{let r=JSON.parse(t.data);"session_snapshot"===r.type?tF.current?.(r):"agent_start"===r.type&&t_.current?.(e)}catch{}}},[rS]),rN=(0,i.useCallback)(e=>{rj();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);tg.current=t,tx.current=e;let r=new Promise(r=>{let n=!1,i=e=>{n||(n=!0,clearTimeout(a),tv.current?.source===t&&(tv.current.pending=!1),r({status:e,source:t}))},a=setTimeout(()=>i("timeout"),5e3);t.onmessage=e=>{try{let t=JSON.parse(e.data);"update_maintenance"===t.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:t})),"connected"===t.type&&i("connected"),tF.current?.(t)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(i("closed"),tg.current===t&&(tT.current||tk.current))){tg.current=null,tx.current=null,tv.current=null;let t=tw.current;setTimeout(()=>{t===tw.current&&!tg.current&&(tT.current||tk.current)&&rN(e)},1e3)}}});return tv.current={source:t,promise:r,pending:!0},r},[rj]),rI=(0,i.useCallback)(async e=>{let t=tg.current;if(t&&tx.current===e){if(t.readyState===EventSource.OPEN)return;let e=tv.current;if(e?.source===t&&e.pending&&(await e.promise,tg.current===t&&t.readyState===EventSource.OPEN))return}let r=await rN(e);if("connected"!==r.status&&r.source.readyState!==EventSource.OPEN)throw tg.current===r.source&&(tg.current=null),tx.current===e&&(tx.current=null),tv.current?.source===r.source&&(tv.current=null),r.source.close(),new s5(r.status)},[rN]),rT=(0,i.useCallback)(async(e,t)=>{let r=e9.current;if(r?.id===e.id&&"sending"===r.status)return;let n=tj.current,i=e=>{e9.current=e,e7(e)};if(!n)return void i({id:e.id,status:"failed",error:"no session"});i({id:e.id,status:"sending"});try{await sz(n,{type:"extension_ui_response",id:e.id,...t})}catch(t){i({id:e.id,status:"failed",error:t instanceof Error?t.message:String(t)});return}i(null),e6(t=>t?.id===e.id?null:t)},[]),rM=(0,i.useCallback)(async(e,t)=>{let r=tj.current;if(r)try{await sz(r,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),r$=(0,i.useCallback)(e=>{let t=e.message.trim();t&&e2({type:"add",notice:{id:e.id??s8(),message:t,type:e.type??"info"}})},[]),rR=(0,i.useCallback)(e=>{let t={role:"custom",customType:eU,content:ej(e).trim(),display:!0,timestamp:Date.now()},r=tI.current,n=tj.current;r.sessionId!==n&&(r.sessionId=n,r.outputs=[]);let i=tN.current.slice(0,tC.current.length),a=null;for(let e=i.length-1;e>=0;e--)if(!eJ(i[e])){a=i[e];break}r.seq+=1,r.outputs.push({entryId:`${eV}${r.seq}`,baseEntryId:a,message:t}),rh(e=>[...e,t])},[rh]),rE=(0,i.useCallback)(t=>{if("custom"!==t.method&&"closed"in t&&t.closed){e6(e=>e?.id===t.id?null:e),e9.current?.id===t.id&&(e9.current=null,e7(null));return}switch(s$(t)&&l?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":e6(t);break;case"notify":r$({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":tn(e=>{let r=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...r,{key:t.statusKey,text:t.statusText}]:r});break;case"setWidget":ta(e=>{let r=e.filter(e=>e.key!==t.widgetKey);return t.widgetLines?[...r,{key:t.widgetKey,lines:t.widgetLines,placement:t.widgetPlacement??"aboveEditor"}]:r});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":tt(e=>t.closed?e?.id===t.id?null:e:t)}},[r$,l,e.chatInputRef]),rL=(0,i.useCallback)(()=>{let e=tT.current;return tT.current=!1,L(!1),eY(null),ey(null),R({type:"end"}),e},[]),rz=(0,i.useCallback)(()=>{tE.current="unknown",tL.current=null;let e=s2(tC.current,tN.current);tz.current=e?{entryId:e.entryId,key:lt(e.message)}:null,tA.current+=1},[]),rA=(0,i.useCallback)(()=>{let e=tE.current,t=tL.current;if("unknown"===e){let r=s2(tC.current,tN.current),n=r?.message,i=tz.current;null!==r&&(null===i||(null!==r.entryId&&null!==i.entryId?r.entryId!==i.entryId:lt(r.message)!==i.key))&&n?.role==="assistant"&&n.stopReason&&(e=s1(n),t??={provider:n.provider,...void 0!==n.credentialId?{credentialId:n.credentialId}:{}})}return{outcome:e,sessionId:tj.current,...t?{provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),rP=(0,i.useCallback)(e=>{let t=rA();if("unknown"!==t.outcome||!e)return void s?.(t);let r=tA.current;e.catch(()=>void 0).then(()=>{let e=tj.current===t.sessionId&&tA.current===r;s?.(e?rA():t)})},[s,rA]),rW=(0,i.useCallback)((e,t)=>tR.current!==e&&(tR.current=e,rP(t),!0),[rP]),rF=(0,i.useCallback)(e=>{rk(),tk.current=!0;let t=tw.current,r=async()=>{if(t===tw.current&&tj.current===e&&tk.current)try{let n=rc.current,i=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let a=await i.json();if(t!==tw.current||tj.current!==e||!tk.current)return;let s=a.state;if(td(e=>sG(e,s?.subagents??[])),rp(e,s?.todoPhases,n),a.running&&s&&(s.isStreaming||s.isPromptRunning||s.isHandoffRunning)){tk.current=!1,ty.current=null,tM.current=!!s?.isStreaming,t$.current=!!s?.isPromptRunning,tT.current=!0,L(!0),eY(s?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(a.running&&s?.isCompacting){eA(!0),eH(sQ(s)),ty.current=setTimeout(()=>void r(),600);return}if(a.running&&(s?.subagents?.length??0)>0){ty.current=setTimeout(()=>void r(),1e3);return}tk.current=!1,ty.current=null,rj()}catch{if(t!==tw.current||tj.current!==e||!tk.current)return;ty.current=setTimeout(()=>void r(),600)}};ty.current=setTimeout(()=>void r(),3e4)},[rp,rk,rj]),r_=(0,i.useCallback)(async(e=tj.current,t=rt.current)=>{if(rt.current===t)try{e&&await rm(e)}finally{if(rt.current!==t)return;let r=t$.current,n=tM.current;t$.current=!1,tM.current=!1,rn.current=null;let i=rL();r?rW(t):n&&i&&rP(),e&&rF(e)}},[rm,rP,rW,rF,rL]),rD=(0,i.useCallback)(async(e,t)=>{await s6(800);let r=Date.now();for(;tT.current&&Date.now()-r<2e4;){if(void 0!==t&&rt.current!==t)return;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(r.ok){let n=await r.json(),i=n.state;if(!n.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await r_(e,t)}}catch{}await s6(600)}},[r_]),rH=(0,i.useCallback)(async e=>{let t=tW.current+1;for(tW.current=t;tP.current&&tW.current===t&&tj.current===e;){await s6(1e3);try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)continue;let n=await r.json();if(n.state?.isBashRunning)continue;if(await rm(e),tW.current!==t||tj.current!==e)return;tP.current=!1,A(!1),W(null);return}catch{}}},[rm]),rO=(0,i.useCallback)(async e=>{if(!tT.current)return;let t=rt.current;try{let r=rc.current,n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)return;let i=await n.json();if(rt.current!==t)return;let a=i.state;if(eA(a?.isCompacting??!1),eH(sQ(a)),tl(sZ(a?.queuedMessages)),a?.contextUsage!==void 0&&ek(a.contextUsage??null),td(e=>sG(e,a?.subagents??[])),rp(e,a?.todoPhases,r),i.running&&a&&(a.isStreaming||a.isPromptRunning||a.isCompacting||a.isHandoffRunning)||!tT.current)return;a&&(void 0!==a.systemPrompt&&eC(a.systemPrompt??null),void 0!==a.extensionStatuses&&tn(a.extensionStatuses??[]),void 0!==a.extensionWidgets&&ta(a.extensionWidgets??[])),await r_(e,t)}catch{}},[rp,r_]),rB=(0,i.useCallback)(async e=>{let t=await rm(e,!1,!0),r=t?.state;return!!t?.running&&!!r&&tj.current===e&&!tT.current&&!!(r.isStreaming||r.isPromptRunning||r.isHandoffRunning)&&(tM.current=!!r.isStreaming,t$.current=!!r.isPromptRunning,tT.current=!0,L(!0),eY(r.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),R({type:"start"}),rN(e),!r.isStreaming&&r.isPromptRunning&&rD(e),!0)},[rN,rm,rD]),rU=(0,i.useCallback)(async(e,t=rt.current)=>{let r=rr.current+1;rr.current=r;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)return;let i=await n.json();if(r!==rr.current||tj.current!==e||rt.current!==t)return;i.state?.contextUsage!==void 0&&ek(i.state.contextUsage??null)}catch{}},[]);(0,i.useEffect)(()=>{if(!ez){eO.current=null,eH(null);return}eH(e=>e??{startedAt:Date.now(),reason:eO.current})},[ez]),(0,i.useEffect)(()=>{if(!E&&!ez)return;let e=()=>{let e=tj.current;e&&rU(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[E,ez,rU]),(0,i.useEffect)(()=>{if(!E)return;let e=()=>{let e=tj.current;e&&rO(e)},t=()=>{"visible"===document.visibilityState&&e()},r=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(r),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[E,rO]),(0,i.useEffect)(()=>{if(E)return;let e=()=>{let e=tj.current;e&&!tT.current&&rB(e)},t=()=>{"visible"===document.visibilityState&&e()},r=e=>{let t=tj.current,r=e.detail?.sessionId;t&&r===t&&!tT.current&&rB(t).then(e=>{e||tj.current!==t||tT.current||rm(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(sD,r),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(sD,r)}},[E,rB,rm]),t_.current=e=>{if(tj.current!==e||tT.current||tg.current||tD.current)return;let t=rB(e).then(async t=>{t||tj.current!==e||tT.current||await rm(e)}).catch(()=>{}).finally(()=>{tD.current===t&&(tD.current=null)});tD.current=t},(0,i.useEffect)(()=>{tT.current=E},[E]),tF.current=(0,i.useCallback)(e=>{switch(e.type){case"session_snapshot":{let t=function(e,t,r,n,i){if("session_snapshot"!==e.type||"string"!=typeof e.sessionId||e.sessionId!==t||"string"!=typeof e.entryId||""===e.entryId||e.entryId===r||!e.context||!Array.isArray(e.context.messages)||!Array.isArray(e.context.entryIds)||e.context.messages.length!==e.context.entryIds.length)return null;let a=e.context.messages,s=new Map;for(let e of a){let t=lt(e);s.set(t,(s.get(t)??0)+1)}let l=Math.min(n.length,i.length);for(let e of n.slice(0,l)){let t=lt(e),r=s.get(t)??0;r>0&&s.set(t,r-1)}let o=n.slice(l).filter(e=>{let t=lt(e),r=s.get(t)??0;return 0===r||(s.set(t,r-1),!1)});return{entryId:e.entryId,messages:[...a,...o],entryIds:[...e.context.entryIds],compactedWork:e.context.compactedWork??null}}(e,tj.current,tS.current,tC.current,tN.current);if(!t)break;tS.current=t.entryId;let r=eG(t.messages,t.entryIds,tI.current.sessionId===tj.current?tI.current.outputs:[]);rh(r.messages),rf(r.entryIds),M(t.compactedWork);break}case"agent_start":{let e=!tT.current;rk(),e&&rz(),tM.current=!0,tT.current=!0,L(!0),eY({kind:"waiting_model"}),R({type:"start"});break}case"agent_end":if(!tT.current)break;if(eY(null),ey(null),R({type:"end"}),tj.current){rm(tj.current);let e=rc.current;fetch(`/api/agent/${encodeURIComponent(tj.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&ek(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eC(t.state.systemPrompt??null),t.state?.extensionStatuses!==void 0&&tn(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&ta(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&td(e=>sG(e,t.state?.subagents??[])),tj.current&&rp(tj.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tK(t.state.goal??null),tl(sZ(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tK(e.status??null);break;case"agent_settled":{let e=tM.current;if(tM.current=!1,!e||t$.current)break;let t=tj.current,r=rL();eA(!1);let n=t?rm(t):void 0;t&&rF(t),r&&rP(n);break}case"prompt_done":{let e=rt.current,t=t$.current;t$.current=!1,rn.current=null;let r=tR.current!==e;if(!t&&!r)break;let n=tj.current;rW(e,n?rm(n):void 0),!tM.current&&(rL(),n&&rF(n))}break;case"prompt_error":tE.current="failed",r$({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":tE.current="failed",r$({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!tT.current)break;let t=e.message;if(t?.role!=="assistant")break;t&&R({type:"update",message:(0,sE.B)(t)}),eY(null);break}case"message_end":{if(!tT.current)break;let t=e.message;if(t?.role==="assistant"&&(tL.current={provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}},tE.current=s1(t)),t&&"user"===t.role){let e=(0,sE.B)(t),r=le(e),n=rn.current;rn.current=null,rh(t=>{let i=t[t.length-1];return n&&i?.role==="user"&&le(i)===n?n===r?t:[...t.slice(0,-1),e]:[...t,e]}),n||tu({type:"user-message",kind:"steering"in e&&!0===e.steering?"steer":"followUp",text:"user"!==e.role?"":"string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),images:"user"!==e.role||"string"==typeof e.content?0:e.content.filter(e=>"image"===e.type).length})}else t&&rh(e=>[...e,(0,sE.B)(t)]);let r=tj.current;r&&rU(r),R({type:"reset"}),eY({kind:"waiting_model"});break}case"thinking_level_changed":{let t=tj.current,r=e.thinkingLevel;t&&void 0!==r&&(t8.current=t,t6.current+=1,el(e.configured??r),ed(r));break}case"todo_changed":ru(tj.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,r=e.toolName,n=e.args;eY(e=>{let i=e?.kind==="running_tools"?[...e.tools]:[];return i.some(e=>e.id===t)||i.push({id:t,name:r,args:n}),{kind:"running_tools",tools:i}});break}case"tool_execution_end":{let t=e.toolCallId;eY(e=>{if(e?.kind!=="running_tools")return e;let r=e.tools.filter(e=>e.id!==t);return 0===r.length?{kind:"waiting_model"}:{kind:"running_tools",tools:r}});break}case"subagent_lifecycle":{let t=e.payload;if(!t?.id)break;if("started"!==t.status){let e="failed"===t.status?"failed":"aborted"===t.status?"aborted":"completed";td(r=>{let n=r.find(e=>e.id===t.id);return sG(r,[{id:t.id,index:t.index??n?.index??0,agent:t.agent??n?.agent??t.id,agentSource:t.agentSource??n?.agentSource??"bundled",description:t.description??n?.description,status:e,task:n?.task,assignment:n?.assignment,sessionFile:t.sessionFile??n?.sessionFile,parentToolCallId:t.parentToolCallId??n?.parentToolCallId,lastUpdate:Date.now(),progress:n?.progress?{...n.progress,status:e}:void 0}])});break}let r={id:t.id,index:t.index??0,agent:t.agent??t.id,agentSource:t.agentSource??"bundled",description:t.description,status:"running",sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now()};td(e=>sG(e,[r]));break}case"subagent_progress":{let t=e.payload;if(!t?.progress)break;let r=t.progress,n={id:r.id,index:t.index??r.index,agent:t.agent??r.agent,agentSource:t.agentSource??"bundled",description:r.description,status:r.status,task:t.task??r.task,assignment:t.assignment??r.assignment,sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now(),progress:r};td(e=>sG(e,[n]));break}case"queue_update":tl({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":ey({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":ey(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof e.reason){eO.current=e.reason;let t=e.reason;eH(e=>e?{...e,reason:t}:e)}eA(!0),eW(null),e_(null);break;case"auto_compaction_end":case"compaction_end":if(eA(!1),e.errorMessage)eW(e.errorMessage),e_(null);else if(!e.aborted){e_(lr(e.result,e.reason??"auto"));let t=tj.current;t&&(rm(t),rU(t))}break;case"extension_ui_request":rE(e)}},[r$,ru,rp,rk,rE,rm,rP,rW,rU,rz,rF,rL,rf,rh]);let rq=(0,i.useCallback)(async(r,i,a)=>{let s=r.trim();if(!s&&!i?.length&&!a?.length)return"returned";if(tT.current||tP.current||ri.current)return"unknown";let l=no(r,a??[]),o=!i?.length&&!a?.length&&s.startsWith("/");if(!i?.length&&!a?.length&&s.startsWith("!")){let e=s.startsWith("!!"),t=(e?s.slice(2):s.slice(1)).trim();return t?(await tV.current?.(t,e),"accepted"):"unknown"}rz();let d=rt.current+1;rk(),t$.current=!0;let c=i?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),u={role:"user",content:c?.length?[...l.trim()?[{type:"text",text:l}]:[],...c]:l,timestamp:Date.now()};rh(e=>[...e,u]),rn.current=le(u),rt.current=d,tT.current=!0,L(!0),eY(o?{kind:"running_command"}:{kind:"waiting_model"}),R({type:"start"}),tY.current(!0);let p=i?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),h=null,m=!1,g="unknown";try{if(f&&n){let e=tj.current??await tQ.current,t=await ry();t&&(h=t,X&&(eR(X),e&&await sz(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await rI(t),m=!0,await sz(t,{type:"prompt",message:l,...p?.length?{images:p}:{}}),rb(1,r),g="accepted")}else t&&(h=t.id,await rI(t.id),m=!0,await sz(t.id,{type:"prompt",message:l,...p?.length?{images:p}:{}}),g="accepted");return o&&h&&rD(h,d),g}catch(l){console.error("Failed to send message:",l);let n=l instanceof sL&&"update_draining"===l.code&&!1===l.accepted;if(!(!m||l instanceof sL&&"prompt_rejected"===l.code&&!1===l.accepted||n)&&h)return rD(h,d),"unknown";t$.current=!1,tT.current=!1,rj();let s=rn.current;return s&&rh(e=>{let t=e[e.length-1];return t?.role==="user"&&le(t)===s?e.slice(0,-1):e}),r$({type:"error",message:l instanceof Error?l.message:String(l)}),e.chatInputRef?.current?.restoreSubmission?.(r,ln(i),a,t?.id??h??void 0),rn.current=null,L(!1),eY(null),R({type:"end"}),"returned"}},[f,n,X,t,ry,rI,rb,rD,r$,rk,rj,e.chatInputRef,rz,rh]);tV.current=(0,i.useCallback)(async(r,n)=>{if(tT.current||tP.current)return;let i=`${n?"!!":"!"}${r}`;tP.current=!0,tY.current(!0),W({command:r,excludeFromContext:n}),A(!0);try{let e=tj.current??t?.id??await ry();if(!e)throw Error("Unable to create a session for the shell command");await sz(e,{type:"bash",command:r,excludeFromContext:n}),await rm(e),rb(1,i)}catch(t){console.error("Failed to execute shell command:",t),r$({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(i)}finally{tP.current=!1,W(null),A(!1)}},[r$,ry,rm,e.chatInputRef,rb,t]);let rK=(0,i.useCallback)(async()=>{let e=tj.current;if(e){if(tP.current){try{await sz(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await sz(e,{type:"abort"}),tE.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),rV=(0,i.useCallback)(async e=>{if(tP.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let t=tj.current;if(!t)return{forked:!1,error:"No active session to fork"};eI(e??null);try{let{cancelled:r,newSessionId:n}=await sz(t,{type:"fork",...e?{entryId:e}:{}})??{};if(!r&&n)return d?.(n),{forked:!0};return{forked:!1,error:"Fork was cancelled"}}catch(e){return console.error("Fork failed:",e),{forked:!1,error:e instanceof Error?e.message:String(e)}}finally{eI(null)}},[d]),rJ=(0,i.useCallback)(async e=>{if(tP.current)return;let t=tj.current;t&&(sz(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await rx(t,e))},[rx]),rG=(0,i.useCallback)(async e=>{if(tP.current)return;j(e);let t=tj.current;t&&(await rx(t,e),e&&sz(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[rx]),rY=(0,i.useCallback)(async(e,t)=>{if(f){let r={provider:e,modelId:t},n=t2.current?.provider===e;t2.current=r,n||(t4.current=null,et(null)),Q(r),eR(r);let i=tj.current??await tQ.current;if(!i)return;try{await sz(i,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let r=tj.current;if(r&&!ri.current){ri.current=!0,eM({provider:e,modelId:t}),eL(!0);try{await sz(r,{type:"set_model",provider:e,modelId:t}),ri.current=!1,await rm(r)}catch(e){console.error("Failed to set model:",e),ri.current=!1,eM(eT),r$({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await rm(r)}finally{ri.current=!1,eL(!1)}}},[r$,eT,f,rm,Q]),rZ=(0,i.useCallback)(async e=>{let t={provider:e.provider,modelId:e.modelId},r=e.oauthPosition,n={type:"set_model",provider:e.provider,modelId:e.modelId,thinkingLevel:"auto",...void 0!==r?{oauthPosition:r}:{}},i=t=>`${e.alias} preset was not applied: ${t instanceof Error?t.message:String(t)}`;if(f){if(ri.current)return!1;ri.current=!0,eL(!0);let e=t2.current,a=t4.current,s=t5.current;try{t2.current=t,t4.current=r??null,t5.current="auto";let e=tj.current??await tQ.current;return e&&await sz(e,n),Q(t),et(r??null),eR(t),el("auto"),ed(void 0),e&&await rm(e),!0}catch(r){console.error("Failed to apply Main preset:",r),t2.current=e,t4.current=a,t5.current=s,r$({type:"error",message:i(r)});let t=tj.current;return t&&await rm(t),!1}finally{ri.current=!1,eL(!1)}}let a=tj.current;if(!a||ri.current)return!1;ri.current=!0,eM(t),eL(!0);try{return await sz(a,n),await rm(a),!0}catch(e){return console.error("Failed to apply Main preset:",e),eM(eT),r$({type:"error",message:i(e)}),await rm(a),!1}finally{ri.current=!1,eL(!1)}},[r$,eT,eo,f,rm,Q,es]),rX=(0,i.useCallback)(async e=>{let t=Y.find(t=>t.role===e),r=t?.resolved;if(!r)return;if(f){let e={provider:r.provider,modelId:r.modelId},t=r.thinkingLevel;t5.current=t??null,el(t??"auto"),ed(void 0),t2.current=e,t4.current=null,et(null),Q(e),eR(e)}let n=tj.current??(f?await tQ.current:null);if(n)try{await sz(n,{type:"set_role_model",role:e}),f||eM({provider:r.provider,modelId:r.modelId})}catch(e){console.error("Failed to set role model:",e)}},[f,Y,Q]),rQ=(0,i.useCallback)(async()=>{let e=tj.current;if(e&&!ez){eO.current="manual",eA(!0),eW(null),e_(null);try{let t=await sz(e,{type:"compact"});e_(lr(t,"manual")),await rm(e,!0)}catch(e){eW(e instanceof Error?e.message:String(e)),e_(null)}finally{eA(!1)}}},[ez,rm]),r0=(0,i.useCallback)(async e=>{let r=n??t?.cwd??"",i=r?`/api/models?cwd=${encodeURIComponent(r)}`:"/api/models",a=await fetch(i,e?{signal:e}:void 0);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();_(s.models),B(s.modelError??null),q(s.modelScopeWarnings??[]),V(s.thinkingLevels??{}),G(s.thinkingLevelMaps??{}),Z(s.roles??[]);let l=s.modelList??[];if(H(l),f&&!tj.current){let e=(s.defaultModel?l.find(e=>e.id===s.defaultModel?.modelId&&e.provider===s.defaultModel?.provider):void 0)??l[0];en(e?{provider:e.provider,modelId:e.id}:null);let t=e&&s.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===t5.current&&el(t??"auto")}},[f,n,t?.cwd]),r1=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,r,n=""]=t,i=n.trim(),a=await ry(),s=e=>(e.handled&&(e.error?r$({type:"error",message:e.error}):"openSessionStats"!==e.action&&r$({type:"success",message:e.message??"Command completed"})),e);try{switch(r){case"compact":{if(!a||ez)return s({handled:!0,error:"No active session to compact"});eO.current="manual",eA(!0),eW(null),e_(null);let e=await sz(a,{type:"compact",...i?{customInstructions:i}:{}});return e_(lr(e,"manual")),await rm(a,!0)&&rb(),s({handled:!0,message:"Compacted context"})}case"reload":if(!a)return s({handled:!0,error:"No active session to reload"});return await sz(a,{type:"reload"}),await Promise.all([rm(a,!1,!0),rv(a),rw(),r0()]),s({handled:!0,message:"Reloaded session resources"});case"name":if(!a)return s({handled:!0,error:"No active session to name"});if(!i)return s({handled:!0,error:"Usage: /name <name>"});return await sz(a,{type:"set_session_name",name:i}),await rm(a)&&rb(),s({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!a)return s({handled:!0,error:"No active session"});let e=await sz(a,{type:"get_session_stats"});return e&&e5(e),h?.(),s({handled:!0,action:"openSessionStats"})}case"copy":{if(!a)return s({handled:!0,error:"No active session"});let e=await sz(a,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return s({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),s({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!a)return s({handled:!0,error:"No active session to fork"});let e=await rV();if(!e.forked)return s({handled:!0,error:e.error??"Fork failed"});return s({handled:!0,message:"Forked a new session"})}case"goal":{if(!a)return s({handled:!0,error:"No active session"});let e=await sz(a,{type:"goal",args:i});if(tK(e?.status??null),e?.error)return s({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(rR(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&r$({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return s({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!a)return s({handled:!0,error:"No active session"});if(tT.current||tP.current)return s({handled:!0,error:"Cannot hand off while the session is busy"});tT.current=!0,L(!0),eY({kind:"running_command"});try{await rI(a);let e=await sz(a,{type:"handoff",...i?{customInstructions:i}:{}});if(!e||e.cancelled)return s({handled:!0,error:"Handoff cancelled"});return await rm(a,!0)&&rb(),s({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tT.current=!1,L(!1),eY(null),tj.current===a&&rF(a)}default:{if(!a)return s({handled:!0,error:"No active session"});let t=await sz(a,{type:"execute_slash_command",message:e});if(!t?.handled)return{handled:!1};let r=t.output?.filter(e=>e.trim()).join("\n\n")??"";if(r&&rR(r),t.prompt)return{handled:!0,prompt:t.prompt};if(r)return{handled:!0};return s({handled:!0,message:"Command completed"})}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===r&&eA(!1)}},[r$,rR,rI,ry,rV,ez,r0,rm,rw,rv,rb,h,rF]),r2=(0,i.useCallback)(async(t,r,n)=>{let i=tj.current;if(!i)return r$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(r),n),"returned";let a=no(t,n??[]),s=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:"steer",text:a,images:s?.length??0});try{return await sz(i,{type:"steer",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:l}),"accepted"}catch(a){return tu({type:"fail",id:l}),console.error("Failed to steer:",a),r$({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(r),n,i),"returned"}},[r$,e.chatInputRef]),r4=(0,i.useCallback)(async(t,r,n,i)=>{let a=tj.current;if(!a)return r$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(n),i),"returned";let s=no(t,i??[]),l=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:r,text:s,images:l?.length??0});try{return await sz(a,{type:"prompt",message:s,streamingBehavior:r,...l?.length?{images:l}:{}}),tu({type:"ack",id:o}),"accepted"}catch(r){return tu({type:"fail",id:o}),console.error("Failed to queue prompt:",r),r$({type:"error",message:r instanceof Error?r.message:String(r)}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(n),i,a),"returned"}},[r$,e.chatInputRef]),r5=(0,i.useCallback)(async(t,r,n)=>{let i=tj.current;if(!i)return r$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(r),n),"returned";let a=no(t,n??[]),s=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:"followUp",text:a,images:s?.length??0});try{return await sz(i,{type:"follow_up",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:l}),"accepted"}catch(a){return tu({type:"fail",id:l}),console.error("Failed to follow up:",a),r$({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(r),n,i),"returned"}},[r$,e.chatInputRef]),r8=(0,i.useCallback)(async()=>{let e=tj.current;if(e)try{await sz(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),r6=(0,i.useCallback)(async()=>{let t=tj.current;if(t)try{var r;let n=await sz(t,{type:"clear_queue"});tu({type:"withdraw"}),tl({steering:[],followUp:[]});let i={text:(r=[...n?.steering??[],...n?.followUp??[]]).map(({text:e,images:t})=>t?.length&&"[Image]"===e?"":e).filter(e=>e.trim()).join("\n\n"),images:r.flatMap(({images:e})=>e??[]).map(({data:e,mimeType:t})=>({data:e,mimeType:t}))};e.chatInputRef?.current?.restoreSubmission?.(i.text,i.images.length?i.images:void 0,void 0,t)}catch(e){console.error("Failed to recall queued messages:",e),r$({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,r$]),r3=(0,i.useCallback)(async(e,t)=>{let r=tj.current;if(r)try{let n=await sz(r,{type:"remove_queued_message",message:t,queue:e});if(!n?.removed)return;tu({type:"withdraw",kind:"steering"===e?"steer":"followUp",text:t}),tl(r=>{let n=r[e].indexOf(t);return(n<0&&""===t.trim()&&(n=r[e].indexOf("[Image]")),n<0)?r:{...r,[e]:r[e].filter((e,t)=>t!==n)}})}catch(e){console.error("Failed to remove queued message:",e),r$({type:"error",message:"Failed to remove queued message"})}},[r$]),r7=(0,i.useCallback)(async(e,t=null)=>{let r="auto"===e?t:null,n=r!==ec;el(e),eu(r),f&&(!tj.current||t7.current===tj.current)&&(t5.current=e,t3.current=r),ed(void 0);let i=tj.current??await tQ.current;if(i)try{t7.current===i?await ry():n&&await sz(i,{type:"set_thinking_ceiling",ceiling:r}),await sz(i,{type:"set_thinking_level",level:e}),await rm(i)}catch(e){console.error("Failed to set thinking level:",e),r$({type:"error",message:"Failed to set thinking level"}),await rm(i)}},[f,rm,r$,ec,ry]);ev.current=ro?`${ro.provider}/${ro.modelId}`:"";let r9=e=>e?`${e}|${ev.current}`:null,ne=t?.id??tj.current,nt=r9(ne),nr=ep&&ep.key===nt?ep.value:null;(0,i.useEffect)(()=>{let e=++eg.current;nt&&ne&&!E&&!eE&&fetch(`/api/agent/${encodeURIComponent(ne)}`).then(e=>e.json()).then(t=>{eg.current===e&&r9(tj.current)===nt&&eh({key:nt,value:(t.running?sX(t.state):void 0)??null})}).catch(()=>{})},[nt,E,eE]);let nn=(0,i.useCallback)(async()=>{let e=tj.current??await ry(),t=r9(tj.current);if(!e||!t)return;let r=++eg.current,n=()=>eg.current===r&&r9(tj.current)===t,i=e=>{n()&&eh({key:t,value:e})};em(!0);try{let r=ep?.key===t?ep.value?.enabled:void 0;if(void 0===r){let t=sX(await sz(e,{type:"get_state"}));if(!t)throw Error("Could not read the session's Fast state");r=t.enabled}if(!n())return;let a=await sz(e,{type:"set_fast_mode",enabled:!r});i({enabled:a?.enabled===!0,active:a?.active===!0})}catch(t){if(!n())return;r$({type:"error",message:t instanceof Error?t.message:String(t)});try{i(sX(await sz(e,{type:"get_state"}))??null)}catch{i(null)}}finally{em(!1)}},[ry,ep,r$]),ni=(0,i.useCallback)(async e=>{let t=(0,aQ.xG)(e);rs(e);let r=tj.current??await tQ.current;if(r)try{await sz(r,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[rs]),na=(0,i.useCallback)(e=>{tO.current=e,tU(t=>!e===t?t:!e)},[]);tY.current=na;let ns=(0,i.useCallback)((e="smooth")=>{tG.current=Date.now()+700,tZ.current?.scrollIntoView({behavior:e})},[]),nl=(0,i.useCallback)(()=>{tJ.current=0,na(!0),ns("smooth")},[ns,na]),nd=(0,i.useCallback)(()=>{tJ.current=0,na(!1)},[na]),nc=(0,i.useCallback)(e=>{e instanceof KeyboardEvent&&(!s4.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tJ.current=Date.now()+1200)},[]),nu=(0,i.useCallback)(()=>{if(!tT.current&&!tP.current)return;let e=tX.current;if(!e)return;let t=Date.now()<=tJ.current;!t&&Date.now()<tG.current||(e.scrollHeight-e.scrollTop-e.clientHeight<=72?na(!0):t&&na(!1))},[na]);return(0,i.useEffect)(()=>(tj.current=t?.id??null,tI.current.sessionId!==tj.current&&(tI.current={sessionId:tj.current,outputs:[],seq:0}),t&&rm(t.id,!m,!0,m).then(e=>{if(tj.current!==t.id)return;rC(t.id),e?.running&&(rv(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(tM.current=!!e.state.isStreaming,t$.current=!!e.state.isPromptRunning,tT.current=!0,L(!0),eY(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),R({type:"start"}),rN(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&rD(t.id)),e.state?.isBashRunning&&(tP.current=!0,A(!0),rH(t.id)),(e.state?.subagents?.length??0)>0&&rN(t.id));let r=e?.state;r&&(void 0!==r.isCompacting&&eA(r.isCompacting),eH(sQ(r)),void 0!==r.contextUsage&&ek(r.contextUsage??null),void 0!==r.systemPrompt&&eC(r.systemPrompt??null),void 0!==r.thinkingLevel&&(t8.current=t.id,el(r.configuredThinkingLevel??r.thinkingLevel),ed(r.thinkingLevel)),void 0!==r.thinkingCeiling&&eu(r.thinkingCeiling??null),void 0!==r.extensionStatuses&&tn(r.extensionStatuses??[]),void 0!==r.extensionWidgets&&ta(r.extensionWidgets??[]),void 0!==r.queuedMessages&&tl(sZ(r.queuedMessages)),void 0!==r.subagents&&td(e=>sG(e,r.subagents??[])),void 0!==r.goal&&tK(r.goal??null)),e&&eq(!0)}),()=>{tW.current+=1,rk(),rj(),rS()}),[t?.id]),(0,i.useEffect)(()=>{p?.(eS)},[eS,p]),(0,i.useEffect)(()=>{u&&u(g?.tree??[],k,rG)},[g?.tree,k,rG,u]),(0,i.useEffect)(()=>(window.addEventListener("keydown",nc),()=>{window.removeEventListener("keydown",nc)}),[nc]),(0,i.useEffect)(()=>{let e=tX.current;if(e)return e.addEventListener("pointerdown",nc,{passive:!0}),e.addEventListener("wheel",nc,{passive:!0}),e.addEventListener("touchstart",nc,{passive:!0}),e.addEventListener("scroll",nu,{passive:!0}),()=>{e.removeEventListener("pointerdown",nc),e.removeEventListener("wheel",nc),e.removeEventListener("touchstart",nc),e.removeEventListener("scroll",nu)}},[S.length,v,nu,nc]),(0,i.useEffect)(()=>{if(t9.current||!E&&!z||!tO.current)return;let e=tX.current;if(!e)return;let t=requestAnimationFrame(()=>{tG.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"})});return()=>cancelAnimationFrame(t)},[E,z,S.length,$.streamingMessage,eK,P,e.transitioning]),(0,i.useLayoutEffect)(()=>{if(0!==S.length){if(!tH.current){tH.current=!0,ns("instant");return}if(!t9.current&&tO.current){let e=Date.now()-re.current<1500;ns(tT.current||tP.current||e?"instant":"smooth")}}},[S.length,E,z,ns,e.transitioning]),(0,i.useEffect)(()=>{let e=new AbortController;return r0(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[r0,c]),(0,i.useEffect)(()=>{if(!eF)return;let e=setTimeout(()=>e_(null),6e3);return()=>clearTimeout(e)},[eF]),(0,i.useEffect)(()=>{if(0===e1.visible.length)return;let e=e1.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{e2({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!e1.visible[0])return;let t=setTimeout(()=>{e2({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[e1.visible]),(0,i.useEffect)(()=>{e5(null)},[S.length,ew?.tokens,ew?.percent,ew?.contextWindow]),{data:g,loading:v,error:y,activeLeafId:k,messages:S,entryIds:N,streamState:$,agentRunning:E,modelNames:F,modelList:D,modelError:O,modelScopeWarnings:U,modelThinkingLevels:K,modelThinkingLevelMaps:J,modelRoles:Y,newSessionModel:X,toolPreset:ei,thinkingLevel:es,effectiveThinkingLevel:eo,thinkingCeiling:ec,retryInfo:eb,contextUsage:ew,systemPrompt:eS,forkingEntryId:eN,isCompacting:ez,compaction:eD,compactError:eP,compactResult:eF,currentModel:rl,displayModel:ro,modelSwitching:eE,sessionStats:rd,runStateKnown:eB,slashCommands:eZ,slashCommandsLoading:eQ,queuedMessages:ts,deliveryRows:th,subagents:to,todoPhases:tf&&tf.sid===tj.current?tf.phases:null,compactedWork:T,notices:e1.visible,extensionDialog:e8,extensionResponse:e3,extensionCustomUi:te,extensionStatuses:tr,extensionWidgets:ti,respondToExtensionUi:rT,sendExtensionCustomInput:rM,isAutoModelSelection:f&&null===X,agentPhase:eK,isNew:f,autoFollowPaused:tB,resumeAutoFollow:nl,pauseAutoFollow:nd,goalStatus:tq,sessionIdRef:tj,eventSourceRef:tg,messagesEndRef:tZ,scrollContainerRef:tX,handleSend:rq,handleAbort:rK,handleFork:rV,handleNavigate:rJ,handleModelChange:rY,handleRoleModelChange:rX,handleMainPresetChange:rZ,newSessionAccount:ee,handleCompact:rQ,handleSteer:r2,handleFollowUp:r5,handlePromptWithStreamingBehavior:r4,handleAbortCompaction:r8,handleRecallQueue:r6,handleRemoveQueuedMessage:r3,handleBuiltinSlashCommand:r1,handleToolPresetChange:ni,handleThinkingLevelChange:r7,fastMode:nr,fastModeBusy:ef,handleFastModeToggle:nn,loadTools:rv,loadSlashCommands:rw,ensureNewSession:ry,refreshLiveTranscript:rg,setActiveLeafId:j,setData:x,setMessages:C,dispatch:R,setAgentRunning:L,setForkingEntryId:eI,bashRunning:z,pendingBash:P,handleAgentEventRef:tF}}({session:e,newSessionCwd:t,initialData:a,transitioning:s,onAgentEnd:ex,onAttentionNeeded:o,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:f,onSessionStatsPanelOpen:g}),tV=rc(e?.id,e7?.provider,void 0),tJ=tV?.alias;(0,i.useEffect)(()=>{tJ&&Z.current?.(tJ)},[tJ]);let tG=(0,i.useMemo)(()=>{if(!e7)return null;let e=tv?tL:t3.bo.find(e=>e.alias===tV?.alias)?.oauthPosition;return t3.bo.find(t=>t.provider===e7.provider&&(void 0===t.oauthPosition||t.oauthPosition===e))?.alias??null},[e7,tv,tL,tV]),tY=e7?.provider,tZ=e7?.modelId,tX=tV?.alias,tQ=tV?.seed,t0=(0,i.useRef)(tV);t0.current=tV,(0,i.useEffect)(()=>{y&&y(tY&&tZ?{provider:tY,modelId:tZ,face:t0.current,presetAlias:tG,isNew:tv}:null)},[y,tY,tZ,tX,tQ,tG,tv]),(0,i.useEffect)(()=>()=>{y?.(null)},[y]);let t1=eC||eN,t2=e?.id;er.current=ew,en.current=ek,ei.current=tj;let t4=(0,i.useRef)(!0);t4.current=!tb;let t5=(0,i.useRef)(!1);(0,i.useEffect)(()=>{eC&&!t5.current&&(ea.current+=1),t5.current=eC},[eC]),(0,i.useEffect)(()=>()=>{ea.current+=1},[]),(0,i.useEffect)(()=>{Q(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(lx(e))??"[]");if(!Array.isArray(t))return[];return t.filter(e=>e&&"string"==typeof e.anchorEntryId).map(t=>({..."string"==typeof t.sticker?{...t,sticker:t.sticker.replace(/^(\/stickers\/.+)\.png$/,"$1.webp")}:t,sessionId:e}))}catch{return[]}}(t2),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===t2)])},[t2]),(0,i.useEffect)(()=>{let e=tj.current;e&&ee.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&Q(t=>{let r=!1,n=[];for(let i of t){if(null!==i.anchorEntryId||!i.intent||i.sessionId!==e){n.push(i);continue}let a=function(e,t,r){let n=Math.min(t.length,r.length),i=0;if(null!==e.baseEntryId){let t=r.indexOf(e.baseEntryId);if(-1===t||t>=n)return{kind:"drop"};i=t+1}let a=0;for(let s=i;s<n;s++)if(iN(t[s])===e.identity&&(a+=1)===e.occurrence)return{kind:"entry",entryId:r[s]};return null}(i.intent,ew,ek);if(null===a){n.push(i);continue}r=!0,"drop"!==a.kind&&("working"===i.tag&&[...t,...n].some(e=>"working"===e.tag&&e.anchorEntryId===a.entryId)||n.push({id:i.id,anchorEntryId:a.entryId,sticker:i.sticker,text:i.text,tag:i.tag,sessionId:i.sessionId}))}return r?(lv(e,n),n):t})},[ew,ek,tj]);let t7=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tj.current,t=t7.current;if(t7.current=e?{sessionId:e,entryIds:ek}:null,!e||!t||t.sessionId!==e)return;let r=function(e,t,r){if(0===e.length||t.length<=e.length)return[];for(let r=0;r<e.length;r++)if(e[r]!==t[r])return[];let n=[],i=Math.min(r.length,t.length);for(let a=e.length;a<i;a++){let e=r[a];"assistant"===e.role&&"web6"===e.provider&&"ChatGPT 6PRO"===e.model&&n.push(t[a])}return n}(t.entryIds,ek,ew),n=eo();if(0===r.length||!n)return;let i=ro(e,"web6",void 0)?.alias??null;for(let e of r)ee.current.some(t=>t.anchorEntryId===e)||eu(i,"done",n,{kind:"entry",entryId:e})},[ek,ew,tj,eo,eu]);let t9=eC&&tx?.kind==="running_tools"&&tx.tools.length>0&&tx.tools.every(e=>"wait"===e.name),re=eb||s,{hideThinkingBlock:rt}=(_=t??e?.cwd??null,H=t6(),(0,i.useEffect)(()=>{t8(_).catch(()=>{})},[_]),H),rr=(0,i.useMemo)(()=>({hideThinking:rt}),[rt]);(0,i.useEffect)(()=>{if(!td||Y.current===td.id)return;Y.current=td.id;let e=eo();if(e){var t;el.current=e.turn,eh("select"===(t=td.method)||"ask"===t?"choice":"approval",e,e7?.provider,void 0)}},[td,e7?.provider,eo,eh]),(0,i.useEffect)(()=>(v=t1?tI:null,()=>void(v=null)),[t1,tI]),(0,i.useEffect)(()=>{N?.(t1)},[N,t1]),(0,i.useEffect)(()=>()=>N?.(!1),[N]),(0,i.useEffect)(()=>{I?.(t9)},[t9,I]),(0,i.useEffect)(()=>()=>I?.(!1),[I]),(0,i.useEffect)(()=>{T?.(null!==td)},[T,td]),(0,i.useEffect)(()=>()=>T?.(!1),[T]);let{main:rn,process:ri}=(0,i.useMemo)(()=>(function(e,t,r={}){let n=[],i=[],a=-1,s=null,l=(e,t,r)=>{if(0===t.length)return;let a=(s&&s.anchorIdx===e||(s={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},i.push(s)),s),l=n.length-1;for(let e of t)a.entries.push({...e,afterMainIndex:l});a.messageCount+=t.length,a.toolCallCount+=r},o=eH(e),d=new Map,c=(e,t)=>{let r=d.get(e)??0;d.set(e,r+1),n.push({kind:"answer",anchorIdx:a,idx:e,runIndex:r,blocks:o.attach(t),precedingBlocks:[]})},u=()=>{let e=o.takeRemaining();e&&c(e.idx,e.blocks)};for(let i of t){if("answer"===i.kind){n.push(i);continue}if("process"===i.kind){l(i.anchorIdx,i.entries,i.toolCallCount);continue}let t=e[i.idx];if(!t)continue;if("user"===t.role){u(),a=i.idx,n.push(i);continue}if(eK(t)){n.push(void 0!==i.anchorIdx||a<0?i:{...i,anchorIdx:a});continue}if("assistant"!==t.role){"toolResult"!==t.role&&l(a,[{idx:i.idx}],0);continue}let s=eF(t,r),d=!1;for(let e of s){if("answer"===e.kind){c(i.idx,e.blocks),d=!0;continue}l(a,[{idx:i.idx,blocks:e.blocks}],e_(e.blocks)),o.collect(i.idx,e.blocks)}!d&&eW(t,r)&&c(i.idx,[])}return u(),{main:n,process:i}})(ew,function(e,t={}){let r=-1;for(let t=e.length-1;t>=0;t--)if(eY(e[t])){r=t;break}let n=[];for(let i=0;i<e.length;){if(!eY(e[i])){n.push({kind:"message",idx:i}),i+=1;continue}let a=i,s=a+1;for(;s<e.length&&!eY(e[s]);)s+=1;if((t.sessionBusy||t.isStreaming)&&s===e.length&&a===r||!function(e,t,r){for(let n=t;n<r;n++)if(e[n]?.role==="assistant")return!0;return!1}(e,a+1,s)){for(let e=a;e<s;e++)n.push({kind:"message",idx:e});i=s;continue}for(let r of(n.push({kind:"message",idx:a}),function(e,t,r,n){let i=[],a=[],s=0,l=[],o=0,d=0,c=eH(e.slice(t+1,r)),u=()=>{0!==a.length&&(i.push({kind:"process",anchorIdx:t,idx:a[0].idx,groupIndex:d++,entries:a,messageCount:a.length,toolCallCount:s,turnHasAnswer:!1}),a=[],s=0)},p=(e,r)=>{u(),i.push({kind:"answer",anchorIdx:t,idx:e,runIndex:o++,blocks:c.attach(r),precedingBlocks:l}),l=[]};for(let o=t+1;o<r;o++){let r=e[o];if("assistant"!==r.role){if(eK(r)){u(),i.push({kind:"message",idx:o,anchorIdx:t});continue}"toolResult"!==r.role&&a.push({idx:o});continue}let d=eF(r,n),h=d.reduce((e,t)=>"answer"===t.kind?e+1:e,0);for(let e of d){if("answer"===e.kind){p(o,e.blocks);continue}for(let t of(a.push(h>0?{idx:o,blocks:e.blocks}:{idx:o}),s+=e_(e.blocks),c.collect(o,e.blocks),e.blocks))l.push(t)}0===h&&eW(r,n)&&p(o,[])}u();let h=c.takeRemaining();h&&i.push({kind:"answer",anchorIdx:t,idx:h.idx,runIndex:o++,blocks:h.blocks,precedingBlocks:[]});let f=i.some(e=>"answer"===e.kind);for(let e of i)"process"===e.kind&&(e.turnHasAnswer=f);return i}(e,a,s,{hideThinking:t.hideThinking})))n.push(r);i=s}return n}(ew,{sessionBusy:t1,isStreaming:eS.isStreaming,hideThinking:rr.hideThinking}),rr),[ew,t1,eS.isStreaming,rr]),ra=(0,i.useMemo)(()=>(function(e,t,r=[]){let n=new Map,i=e.map((e,t)=>({item:e,position:t})).filter(e=>"answer"===e.item.kind);if(0===i.length)return n;let a=-1,s=-1;t.forEach((e,t)=>{let r=rP(e);if(r.length>0){let e=i.filter(e=>e.item.anchorIdx===a||e.item.anchorIdx===s),l=e.filter(e=>e.item.idx<=t).pop(),o=l??e.find(e=>e.item.idx>t);if(o){let e=n.get(o.position);e?e.calls.push(...r):n.set(o.position,{calls:[...r],placement:l?"after":"before"})}}"user"===e.role&&(a=t),eY(e)&&(s=t)});let{continuing:l}=rW(e,t,r);if(l){let e=n.get(l.position);e?e.calls.unshift(...l.calls):n.set(l.position,{calls:l.calls,placement:"before"})}return n})(rn,ew,tr?.messages),[rn,ew,tr]),rs=(0,i.useMemo)(()=>(function(e,t,r=[]){let{atCompaction:n}=rW(e,t,r);if(0===n.length)return null;let i=-1;t.forEach((e,t)=>{"custom"===e.role&&"compaction"===e.customType&&(i=t)});let a=e.findIndex(e=>e.idx>i),s=-1===a?e.length:a;return{position:s,jumpTo:s<e.length?s:e.length>0?e.length-1:null,calls:n}})(rn,ew,tr?.messages),[rn,ew,tr]),[rl,ru]=(0,i.useState)(lp),{startIndex:rp,endIndex:rh,hasLater:rf}=lh(rn.length,rl),rm=null!==rl.end&&rf,rg=(0,i.useRef)(rn.length);rg.current=rn.length;let rx=(0,i.useRef)(null),rv=(0,i.useRef)(null),rb=(0,i.useRef)(null);(0,i.useEffect)(()=>{null!==rl.end&&rl.end>=rn.length&&ru(e=>({count:e.count,end:null}))},[rl.end,rn.length]),(0,i.useEffect)(()=>{let e=rx.current,t=tC.current;if(!e||!t)return;let r=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(rb.current=t.scrollHeight-t.scrollTop,ru(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return r.observe(e),()=>r.disconnect()},[rl,rn.length,tC]),(0,i.useEffect)(()=>{if(null==rb.current)return;let e=tC.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-rb.current),rb.current=null}},[rl.count,tC]),(0,i.useEffect)(()=>{let e=rv.current,t=tC.current;if(!e||!t)return;let r=new IntersectionObserver(e=>{e[0]?.isIntersecting&&ru(e=>(function(e,t,r=50){if(null===t.end)return t;let{startIndex:n,endIndex:i}=lh(e,t),a=i+r;return a>=e?{count:e-n,end:null}:{count:a-n,end:a}})(rg.current,e))},{root:t,threshold:0});return r.observe(e),()=>r.disconnect()},[rl,rn.length,tC]);let[ry,rw]=(0,i.useState)(null),[rk,rj]=(0,i.useState)(null),[rS,rC]=(0,i.useState)(0),rN=(0,i.useRef)(null),rz=(0,i.useCallback)((e,t=null)=>{tw(),rN.current={item:e,dispatchKey:t},rw(null),rj(null),ru(t=>lf(rg.current,e,t)),rC(e=>e+1)},[tw]);(0,i.useLayoutEffect)(()=>{let e,t=rN.current,r=tC.current;if(null===t||!r)return;let n=r.querySelector(`[data-chat-item="${t.item}"]`);if(!n)return;rN.current=null;let i=t.dispatchKey?n.querySelector(".answer-dispatch"):null;if(i)e=i.getBoundingClientRect().top;else{let t=document.createRange();t.selectNodeContents(n),e=t.getBoundingClientRect().top}r.scrollTop+=e-r.getBoundingClientRect().top-24,i&&t.dispatchKey?rj(t.dispatchKey):rw(t.item)},[rS,rl,rn,tC]),(0,i.useEffect)(()=>{if(null===ry)return;let e=setTimeout(()=>rw(null),1800);return()=>clearTimeout(e)},[ry]),(0,i.useEffect)(()=>{if(null===rk)return;let e=setTimeout(()=>rj(null),1800);return()=>clearTimeout(e)},[rk]);let rD=(0,i.useCallback)(()=>{(0,F.flushSync)(()=>ru(lp));let e=tC.current;e&&(e.scrollTop=e.scrollHeight)},[tC]),rH=(0,i.useCallback)(()=>{rm&&rD(),ty()},[rm,rD,ty]),rO=(0,i.useRef)(null),[rB,rU]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!A||rO.current===A.id||A.sessionId!==e?.id||eb||0===ew.length)return;rO.current=A.id,P?.(A.id);let t=ek.indexOf(A.entryId);if(t<0)return void rU(!0);let r=0;for(let e=0;e<rn.length;e++){let n=rn[e].idx;if(n>t||(r=e,n===t))break}rz(r)},[A,e?.id,eb,ew.length,ek,rn,rz,P]),(0,i.useEffect)(()=>{if(!rB)return;let e=setTimeout(()=>rU(!1),6e3);return()=>clearTimeout(e)},[rB]);let[rq,rK]=(0,i.useState)(!1),[rV,rJ]=(0,i.useState)(0),rG=(0,i.useMemo)(()=>rq?rn.map(e=>(function(e,t){if("answer"===e.kind)return eQ(e.blocks);let r=t[e.idx];return r&&"content"in r?eQ(r.content):""})(e,ew).toLowerCase()):lb,[rq,rn,ew]),rY=(0,i.useCallback)(e=>{tw(),ru(t=>lf(rg.current,e,t))},[tw]),rZ=(0,i.useCallback)(()=>rK(!1),[]);(0,i.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.shiftKey||!(e.ctrlKey||e.metaKey)||"f"!==e.key.toLowerCase())return;let t=tC.current;if(!t||!t.checkVisibility({visibilityProperty:!0}))return;let r=e.target instanceof Element?e.target:null;if(r?.closest("[data-capture-keys], [role='dialog']"))return;let n=r?.closest("input, textarea, select, [contenteditable='true']");(!n||n.closest("[data-chat-composer], .chat-find-bar"))&&(e.preventDefault(),rK(!0),rJ(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tC]);let rX=(0,i.useMemo)(()=>{let e=[];return rn.forEach((t,r)=>{if("message"!==t.kind)return;let n=lg(ew[t.idx]);null!==n&&e.push({item:r,text:n})}),e},[rn,ew]),rQ=`${rp}:${rh}`,r0=ek.length>0?ek[ek.length-1]:null,[r1,r2]=(0,i.useState)(null),r4=(0,i.useRef)(!1);(0,i.useEffect)(()=>{r4.current||!tt||eb||!e?.id||(r4.current=!0,t1||!r0||!function(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if("user"===r.role||"toolResult"===r.role)return!0;if("assistant"===r.role){if(!r.stopReason)return!0;if("aborted"===r.stopReason||"error"===r.stopReason||"length"===r.stopReason)break;return r.content.some(e=>"toolCall"===e.type)}}return!1}(ew)||function(e){try{return window.localStorage.getItem(ly(e))}catch{return null}}(e.id)!==r0&&r2(r0))},[tt,eb,e?.id,t1,r0,ew]);let r5=(0,i.useCallback)(()=>{e?.id&&r1&&function(e,t){try{window.localStorage.setItem(ly(e),t)}catch{}}(e.id,r1),r2(null)},[e?.id,r1]),r8=null!==r1&&r1===r0&&!t1&&!rm,r6=te?[te.sessionId,te.sessionFile??"",te.sessionName??"",te.userMessages,te.assistantMessages,te.toolCalls,te.toolResults,te.totalMessages,te.tokens.input,te.tokens.output,te.tokens.cacheRead,te.tokens.cacheWrite,te.tokens.total,te.cost??0,te.totalActiveMs??0].join("|"):null,r3=(0,i.useRef)(te);r3.current=te,(0,i.useEffect)(()=>{m?.(r3.current)},[r6,m]),(0,i.useEffect)(()=>()=>{m?.(null)},[m]);let r7=e1?`${e1.percent??"null"}|${e1.contextWindow}|${e1.tokens??"null"}`:null,r9=(0,i.useRef)(e1);r9.current=e1,(0,i.useEffect)(()=>{x?.(r9.current)},[r7,x]),(0,i.useEffect)(()=>()=>{x?.(null)},[x]),(0,i.useEffect)(()=>{b?.(ts)},[b,ts]),(0,i.useEffect)(()=>()=>{b?.([])},[b]);let{isDragOver:ne,handleDragEnter:nt,handleDragOver:nr,handleDragLeave:nn,handleDrop:ni}=function(e){let[t,r]=(0,i.useState)(!1),n=(0,i.useRef)(0),a=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),n.current+=1,r(!0))},[]),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:a,handleDragOver:s,handleDragLeave:(0,i.useCallback)(()=>{n.current-=1,n.current<=0&&(n.current=0,r(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),n.current=0,r(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{t1||p?.current?.addAttachments(e)},[t1,p])),na=(0,i.useMemo)(()=>{var e;return e=tr?.messages,e&&e.length>0?[...e,...ew]:ew},[tr,ew]),ns=(0,i.useMemo)(()=>{let e=new Map;for(let t of na)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[na]),nl=(0,i.useMemo)(()=>{let e,t,r,n;return e=new Map,t=new Map,r=new Map,n=(e,n,i)=>{let a=r.get(e);a&&n&&t.set(a,{status:n,order:i})},na.forEach((t,i)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=ns.get(e.toolCallId);if(t)for(let n of rR(e,t)??[])r.set(n.agentId,n.key)}return}if("toolResult"===t.role){if("routing_verdict"===t.toolName){let r=function(e){let t=function(e){if(e.isError)return null;let t=e.details?.record;if("object"!=typeof t||null===t)try{let r=JSON.parse(r$(e.content));t=r?.ok===!0?r.record:void 0}catch{return null}return"object"==typeof t&&null!==t?t:null}(e);if(!t)return null;let r=t.verdict;if("accepted"!==r&&"rework"!==r&&"held"!==r)return null;let n=rT(t.assignmentId),i=n?.split("#")??[];if(i.length<3)return null;let a=i[i.length-1],s=i.slice(1,-1).join("#");return/^\d+$/.test(a)&&s?{key:`${s}#${a}`,record:{verdict:r,attempt:"number"==typeof t.attempt?t.attempt:null,reason:rT(t.reason)}}:null}(t);if(!r)return;let n=e.get(r.key)??[];n.push({...r.record,order:i}),e.set(r.key,n);return}if("wait"===t.toolName)for(let e of rI(t.details?.jobs)){if("task"!==e.type)continue;let t=rT(e.id);t&&n(t,rM(e.status),i)}return}if("custom"===t.role&&"async-result"===t.customType)for(let e of r$(t.content).matchAll(rE)){let t=Object.fromEntries([...e[1].matchAll(rL)].map(e=>[e[1],e[2]]));t.id&&n(t.id,rM(t.status),i)}}),{verdicts:e,runs:t,latestByAgent:r}},[na,ns]),nd=(0,i.useMemo)(()=>({ledger:nl,subagents:ts,toolResults:ns,onOpenPanel:w,focusedDispatch:rk,sessionId:e?.id??null}),[nl,ts,ns,w,rk,e?.id]),nc=(0,i.useMemo)(()=>(function(e,t,r,n,i,a,s=null){let l=-1;e.forEach((e,t)=>{"user"===e.role&&(l=t)});let o=new Map;for(let[e,t]of r)for(let r of t.calls)o.set(r.toolCallId,e);if(s?.jumpTo!=null)for(let e of s.calls)o.set(e.toolCallId,s.jumpTo);let d=[];if(e.forEach((e,r)=>{if("assistant"!==e.role)return;let s=r>l;for(let r of e.content??[])if("toolCall"===r.type&&"task"===r.toolName)for(let e of rR(r,t.get(r.toolCallId))??[]){let t=rA(e,n,i),l=rF[t.run],c=null;"running"===l&&("live"===t.runSource||s&&a)?c="running":"awaiting"===l&&s&&!t.verdict&&(c="awaiting"),c&&d.push({maker:t,phase:c,position:o.get(r.toolCallId)??null})}}),0===d.length)return null;let c=0;for(let e of d)"running"===e.phase&&(c+=1);let u=d.filter(e=>null!==e.position);return{running:c,awaiting:d.length-c,target:u.length>0?u[u.length-1]:d[d.length-1]}})(na,ns,ra,ts,nl,t1,rs),[na,ns,ra,ts,nl,t1,rs]),nu=(0,i.useMemo)(()=>w?()=>w("subagents"):void 0,[w]),np=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let r=ew.length-1;r>=0;r-=1){let n=lg(ew[r]);if(!(!n||e.has(n))&&(e.add(n),t.push(n),t.length>=50))break}return t.reverse()},[ew]),nh=(0,i.useMemo)(()=>e3(ew,ns,tl,tr?.todoPhases??null),[ew,ns,tl,tr]),nf=(0,i.useMemo)(()=>iW(eS.streamingMessage).join("|"),[eS.streamingMessage]),nm=(0,i.useMemo)(()=>JSON.stringify(iP(eS.streamingMessage)),[eS.streamingMessage]),ng=(0,i.useMemo)(()=>JSON.stringify(i_(eS.streamingMessage)),[eS.streamingMessage]),nx=(0,i.useMemo)(()=>(function(e,t,r=[],n=[],i=[]){let a=function(e){let t=new Map;for(let r of e){if("toolResult"!==r.role||"write"!==r.toolName)continue;let e=r.details;if(!e||"object"!=typeof e||Array.isArray(e))continue;let n=e.message;if(!n||"object"!=typeof n||Array.isArray(n)||"send"!==n.op)continue;let i=Array.isArray(n.receipts)?n.receipts.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)).map(e=>({to:"string"==typeof e.to?e.to:void 0,outcome:"string"==typeof e.outcome?e.outcome:void 0})):void 0;t.set(r.toolCallId,{from:"string"==typeof n.from?n.from:void 0,receipts:i})}return t}(e),s=[],l=new Map,o=-1;for(let r=0;r<e.length;r+=1){let n=e[r];if("user"===n.role){o=r;continue}let i=iW(n),d=i_(n,a);if(0===i.length&&0===d.length||o<0)continue;let c=iP(n),u=l.get(o);u||(u={index:o,entryId:t[o],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(o,u),s.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...i],u.characterSummons=[...u.characterSummons,...c],u.peerSends=[...u.peerSends,...d]}if(r.length>0||i.length>0){let a=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){a=t;break}if(a>=0){let e=l.get(a);e||(e={index:a,entryId:t[a],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(a,e),s.push(e));let o=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...r.filter(e=>!o.has(e))];let d=new Set(e.characterSummons.map(e=>`${e.toolCallId} ${e.name??""}`));e.characterSummons=[...e.characterSummons,...n.filter(e=>!d.has(`${e.toolCallId} ${e.name??""}`))];let c=new Set(e.peerSends.map(e=>e.toolCallId));e.peerSends=[...e.peerSends,...i.filter(e=>!c.has(e.toolCallId))]}}return s.sort((e,t)=>e.index-t.index)})(ew,ek,nf.length>0?nf.split("|"):[],JSON.parse(nm),JSON.parse(ng)),[ew,ek,nf,nm,ng]),nv=e?.id??tj.current??void 0,nb=(O=iH(D=(0,i.useMemo)(()=>({sessionId:nv,sessionProvider:e7?.provider,turns:nx,messages:ew,subagents:ts}),[nv,e7?.provider,nx,ew,ts])),B=iq(D),(0,i.useMemo)(()=>(function(e){let t=new Map;for(let r of e){let e=t.get(r.turnIndex);e?e.push(r):t.set(r.turnIndex,[r])}return t})(function(e){let t=[];for(let r of e){let e=t[t.length-1];if(e&&e.speakerId===r.speakerId&&e.turnIndex===r.turnIndex&&e.text===r.text){t[t.length-1]=r;continue}t.push(r)}return t}([...O,...B])),[O,B])),ny=tv&&0===ew.length&&!eS.isStreaming&&!t1,nw=e?.cwd??t??void 0,nk=e7?eE[`${e7.provider}:${e7.modelId}`]??null:null,nj=e7?eL[`${e7.provider}:${e7.modelId}`]??null:null,nS=(0,i.useRef)(null),nC=(0,i.useRef)(null),nN=(0,i.useCallback)(()=>{nS.current?.querySelector("textarea")?.focus({preventScroll:!0})},[]);(0,i.useEffect)(()=>(C?.(nN),()=>C?.(null)),[nN,C]),(0,i.useLayoutEffect)(()=>{let e=nC.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let r=tC.current?.clientHeight??0,n=()=>{let n=Math.ceil(e.getBoundingClientRect().height);n>0&&t.style.setProperty("--omp-dock-h",`${n}px`);let i=tC.current;if(!i)return;let a=r-i.clientHeight;r=i.clientHeight,a<=0||i.scrollHeight-i.scrollTop-i.clientHeight-a<=1&&(i.scrollTop+=a)};n();let i=new ResizeObserver(n);return i.observe(e),()=>i.disconnect()},[eb,tC]);let nI=(0,i.useCallback)((...e)=>(null!==rl.end&&rD(),tN(...e)),[tN,rl.end,rD]),nT=(0,n.jsx)("div",{ref:nS,"data-chat-composer":"",style:{display:"contents"},children:(0,n.jsx)(sN,{ref:p,sessionId:e?.id??tj.current??void 0,onEnsureSession:tv&&t?tq:void 0,onLiveTranscriptPersisted:tK,onSend:nI,onAbort:tI,onSteer:eC?tA:void 0,onFollowUp:eC?tP:void 0,onPromptWithStreamingBehavior:eC?tW:void 0,isStreaming:t1,model:e7,isAutoModelSelection:tg,modelNames:eT,modelList:eM,modelError:e$,modelScopeWarnings:eR,onModelChange:t$,onMainPresetChange:e||tv?tE:void 0,mainPresetActiveAlias:tG,modelRoles:ez,onRoleModelChange:tR,modelSwitching:e9,onCompact:e||tv?tz:void 0,onAbortCompaction:tF,isCompacting:e4,compactError:e8,compactResult:e6,toolPreset:eP,onToolPresetChange:e||tv?tO:void 0,thinkingLevel:eD,effectiveThinkingLevel:eO,thinkingCeiling:eB,onThinkingLevelChange:e||tv?tB:void 0,fastMode:eq,fastModeBusy:eZ,onFastModeToggle:e||tv?eX:void 0,availableThinkingLevels:nk,thinkingLevelMap:nj,retryInfo:e0,deliveryRows:ta,inputHistory:np,onRecallQueue:t_,onRemoveQueuedMessage:tD,slashCommands:tn,slashCommandsLoading:ti,onLoadSlashCommands:tU,onBuiltinCommand:tH,soundEnabled:M,onSoundToggle:$,onAudioUnlock:z,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t})}),nM=eS.streamingMessage,n$=(0,i.useMemo)(()=>nM?eF(nM,{isStreaming:!0}):[],[nM]),nR=(0,i.useMemo)(()=>n$.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[n$]),nE=(0,i.useMemo)(()=>n$.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[n$]),nz=nM?.role==="assistant"?nM:null,nA=eC&&(tx?.kind==="running_tools"||(nz?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),nP=nz?.provider??e7?.provider,nW=nz?.credentialId;(0,i.useEffect)(()=>{if(!nA)return;let e=eo();e&&es.current!==e.turn&&el.current!==e.turn&&(es.current=e.turn,eh("working",e,nP,nW))},[nA,nP,nW,eo,eh]);let[nF,n_]=(0,i.useState)(null),nD=(0,i.useCallback)(e=>{n_(e)},[]),nH=(0,i.useMemo)(()=>eI?{role:"bashExecution",command:eI.command,output:"",excludeFromContext:eI.excludeFromContext}:null,[eI]),nO=(0,i.useMemo)(()=>{let e=[eC&&!nM&&tx?function(e,t){if(e?.kind==="running_tools"){let r=e.tools.map(e=>e.name);return 0===r.length?t("chat.runningTool"):1===r.length?t("chat.runningNamedTool",{name:r[0]}):r.length<=3?t("chat.runningTools",{names:r.join(", ")}):t("chat.runningToolsMore",{names:r.slice(0,2).join(", "),count:r.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(tx,U):null,eN&&!eI?U("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[eC,nM,tx,eN,eI,U]);(0,i.useEffect)(()=>{if(!nF)return void k?.(null);let e=[],t=[],r=0;if(nM&&nE.length>0){let n=nF.messages.length+e.length;for(let i of(e.push(nM),nE))t.push({idx:n,blocks:i}),r+=e_(i)}if(nH&&(t.push({idx:nF.messages.length+e.length}),e.push(nH)),0===t.length)return void k?.(nO?{...nF,status:nO}:nF);let n=-1;for(let e=nF.messages.length-1;e>=0;e--)if(eY(nF.messages[e])){n=e;break}let i=nF.groups.slice(),a=i.length>0?i[i.length-1]:void 0;a&&a.anchorIdx===n?i[i.length-1]={...a,entries:[...a.entries,...t],messageCount:a.messageCount+t.length,toolCallCount:a.toolCallCount+r}:i.push({anchorIdx:n,entries:t,messageCount:t.length,toolCallCount:r}),k?.({...nF,groups:i,messages:[...nF.messages,...e],status:nO})},[nF,nE,nM,nH,nO,k]),(0,i.useEffect)(()=>()=>k?.(null),[k]);let nB=th.filter(e=>"belowEditor"!==e.placement),nU=th.filter(e=>"belowEditor"===e.placement);return ey?(0,n.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ey}):(0,n.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":re,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:nt,onDragOver:nr,onDragLeave:nn,onDrop:ni,children:[re?(0,n.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,n.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:U("chat.loadingSession")})}):null,ne&&!t1&&(0,n.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,n.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:U("chat.attachFile")})}),tu&&(0,n.jsx)(lT,{request:tu,onInput:tm}),ny&&!S?(0,n.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,n.jsxs)("div",{className:"my-auto w-full max-w-[820px] py-8",children:[(0,n.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,n.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,n.jsx)(V,{})}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.10.22"]})]}),(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.11.3"]})]})]})]}),(0,n.jsx)(lC,{notices:to,align:"right"})]})}):(0,n.jsxs)(n.Fragment,{children:[S&&(0,n.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:S}),(0,n.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!S,style:{display:S?"none":"flex"},children:[(0,n.jsx)("div",{style:{position:"absolute",top:12,left:0,right:0,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,n.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,n.jsx)(ia,{open:rq,onClose:rZ,containerRef:tC,index:rG,renderedStart:rp,renderedEnd:rh,contentKey:ew,onReveal:rY,onProgrammaticScroll:tw,focusRequest:rV,t:U}),rB&&(0,n.jsx)("div",{className:"chat-jump-missing",role:"status",children:U("chat.jumpMissing")}),(0,n.jsx)(lC,{notices:to,floating:!0,align:"right"})]})}),(0,n.jsx)("div",{ref:tC,className:"chat-session-scroll relative min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",children:(0,n.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,n.jsxs)("div",{className:"chat-column-cap",style:{width:"100%",minWidth:0,maxWidth:820,margin:"0 auto"},children:[(0,n.jsx)(lS,{widgets:nB}),(0,n.jsx)(r_.Provider,{value:nd,children:(0,n.jsx)(iR,{utterances:nb,children:(0,n.jsx)(lw,{messages:ew,entryIds:ek,toolResultsMap:ns,modelNames:eT,messageCwd:nw,onOpenFile:j,sessionBusy:t1,isNew:tv,isStreaming:eS.isStreaming,handleFork:tT,forkingEntryId:e2,handleNavigate:tM,handleEditContent:ev,sessionId:e?.id??tj.current??void 0,main:rn,dispatchSlots:ra,compactedDispatch:rs,process:ri,startIndex:rp,endIndex:rh,sentinelRef:rx,laterSentinelRef:rv,flashItem:ry,t:U,cues:X,cueFollowRef:t4,onProcessLogChange:nD})})}),!rm&&eS.isStreaming&&eS.streamingMessage&&nR.length>0&&(0,n.jsx)(nL,{message:eA(eS.streamingMessage,nR),sessionId:e?.id??tj.current??void 0,isStreaming:!0,modelNames:eT,cwd:nw,onOpenFile:j}),r8&&(0,n.jsx)(iu,{onDismiss:r5,t:U}),(0,n.jsx)("div",{ref:tS})]})})}),(0,n.jsx)(is,{questions:rX,containerRef:tC,layoutKey:rQ,onJump:rz,label:U("chat.questionRail")}),(t1&&tb||rm)&&(0,n.jsxs)("button",{type:"button",onClick:rH,"aria-label":U("chat.jumpToBottom"),title:U("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",minHeight:K?44:void 0,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,n.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,n.jsx)("path",{d:"M12 5v14"}),(0,n.jsx)("path",{d:"m19 12-7 7-7-7"})]}),U("chat.jumpToBottom")]})]})]}),(0,n.jsxs)("div",{ref:nC,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[td&&(0,n.jsx)("div",{style:{padding:"0 16px"},children:(0,n.jsx)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:(0,n.jsx)(lI,{request:td,onRespond:tf,onActivity:e=>void tm(e,"activity"),delivery:tc})})}),(0,n.jsx)("div",{className:"min-h-0 overflow-y-auto",style:{padding:"0 16px"},children:(0,n.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:[(0,n.jsx)(ic,{compaction:e5,t:U}),(0,n.jsx)(lj,{goal:tk,t:U}),!J&&(0,n.jsx)(n9,{summary:nc,onJump:rz,onOpenPanel:nu}),(0,n.jsx)(lS,{widgets:nU}),nh&&!J&&(0,n.jsx)(sT,{phases:nh})]})}),nT,(0,n.jsx)(sI,{statuses:tp})]})]})}function lj({goal:e,t}){if(!e)return null;let r=!e.enabled,i=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:tZ(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:tZ(e.tokensUsed)});return(0,n.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:r?.7:1},children:[(0,n.jsx)("span",{style:{color:r?"var(--text-dim)":"var(--accent)",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",flexShrink:0},children:t("chat.goalLabel")}),(0,n.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:e.objective}),(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:r?t("chat.goalPaused"):e.status}),(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:i})]})}function lS({widgets:e}){return 0===e.length?null:(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,n.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,n.jsx)("div",{style:{padding:"5px 9px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:e.key}),(0,n.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:e.lines.join("\n")})]},e.key))})}function lC({notices:e,floating:t=!1,align:r="left"}){return 0===e.length?null:(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===r?"flex-end":"stretch",marginBottom:10*!t},children:e.map((r,i)=>{let a="error"===r.type?"var(--danger)":"warning"===r.type?"var(--warning)":"success"===r.type?"var(--success)":"var(--accent)";return(0,n.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:60,height:60,maxHeight:60,marginBottom:6*(i!==e.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:t?"var(--seed-shadow-s3)":"var(--seed-shadow-s2)",fontSize:18,lineHeight:1.45,transformOrigin:"top center",animation:r.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a,flexShrink:0}}),(0,n.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r.message})]},r.id)})})}function lN({focusKey:e,label:t,labelledBy:r,maxBlockSize:a="min(56dvh, 620px)",onCancel:s,delivery:l,children:o}){let{t:d}=(0,R.s)(),c=(0,i.useRef)(null),u=(0,i.useRef)({key:"",element:null});if(u.current.key!==e){let t="u"<typeof document?null:document.activeElement;u.current={key:e,element:t instanceof HTMLElement&&!c.current?.contains(t)?t:null}}return(0,i.useEffect)(()=>{let e=c.current;e&&!e.contains(document.activeElement)&&(e.querySelector('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')??e).focus();let t=u.current.element;return()=>{if(!t?.isConnected)return;let r=document.activeElement;(null===r||r===document.body||e?.contains(r))&&t.focus()}},[e]),(0,n.jsxs)("div",{ref:c,role:"dialog","aria-modal":"false","aria-label":t,"aria-labelledby":r,className:"chat-response-surface",tabIndex:-1,onKeyDown:s?e=>{"Escape"===e.key&&(e.stopPropagation(),s())}:void 0,"aria-busy":l?.status==="sending"||void 0,style:{maxBlockSize:a},children:[l?(0,n.jsx)("p",{className:"chat-response-delivery",role:"failed"===l.status?"alert":"status","data-state":l.status,children:"sending"===l.status?d("chat.responseSending"):`${d("chat.responseFailed")}${l.error?` (${l.error})`:""}`}):null,o]})}function lI({request:e,onRespond:t,onActivity:r,delivery:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[d,c]=(0,i.useState)({}),[u,p]=(0,i.useState)({}),[h,f]=(0,i.useState)(""),m=(0,i.useRef)(0),g=(0,i.useCallback)(()=>{if("ask"!==e.method||!e.timeout||!r)return;let t=Date.now();t-m.current<1e3||(m.current=t,r(e))},[e,r]);(0,i.useEffect)(()=>{if(o("editor"===e.method?e.prefill??"":""),f(""),p({}),"ask"!==e.method)return void c({});let t={};for(let r of e.questions)t[r.id]=void 0!==r.recommended&&void 0!==r.options[r.recommended]?[r.recommended]:[];c(t)},[e]);let x=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:l})};if("ask"===e.method){let r=e.questions.every(e=>(d[e.id]?.length??0)>0||(u[e.id]?.trim().length??0)>0),i=()=>{r&&t(e,{value:JSON.stringify({kind:"submit",results:e.questions.map(e=>{let t=u[e.id]?.trim();return{id:e.id,question:e.question,options:e.options.map(e=>e.label),multi:e.multi??!1,selectedOptions:(d[e.id]??[]).map(t=>e.options[t]?.label).filter(e=>void 0!==e),...t?{customInput:t}:{}}})})})};return(0,n.jsx)(lN,{focusKey:e.id,label:s("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:s("chat.agentQuestion")}),(0,n.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentQuestionHint")}),e.timeout?(0,n.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,n.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,n.jsx)("div",{style:{display:"grid",gap:20},children:e.questions.map((t,r)=>{let a=d[t.id]??[];return(0,n.jsxs)("section",{style:{paddingTop:20*(0!==r),borderTop:0===r?"none":"1px solid var(--hairline)"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[t.header&&(0,n.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.header}),e.questions.length>1&&(0,n.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[r+1,"/",e.questions.length]})]}),(0,n.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:t.question}),(0,n.jsx)("div",{role:t.multi?"group":"radiogroup","aria-label":t.question,style:{display:"grid",gap:4},children:t.options.map((e,r)=>{let i=a.includes(r),l=t.recommended===r;return(0,n.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":i,onClick:()=>{var e,n;return e=t.id,n=t.multi??!1,void(g(),c(t=>{let i=t[e]??[],a=n?i.includes(r)?i.filter(e=>e!==r):[...i,r]:[r];return{...t,[e]:a}}))},style:{display:"grid",gridTemplateColumns:"18px minmax(0, 1fr) auto",alignItems:"start",gap:9,width:"100%",minHeight:40,padding:"9px 10px",border:`1px solid ${i?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:i?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,n.jsx)("span",{"aria-hidden":"true",style:{display:"grid",placeItems:"center",width:16,height:16,marginTop:1,border:`1px solid ${i?"var(--text)":"var(--text-dim)"}`,borderRadius:t.multi?"var(--radius-control)":"50%",background:i?"var(--seed-color-fg-neutral)":"transparent",color:"var(--seed-color-fg-neutral-inverted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1},children:i&&(t.multi?(0,n.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,n.jsx)("polyline",{points:"2 5.2 4.1 7.2 8 2.8"})}):(0,n.jsx)("span",{style:{width:5,height:5,borderRadius:"50%",background:"currentColor"}}))}),(0,n.jsxs)("span",{style:{minWidth:0},children:[(0,n.jsx)("span",{style:{display:"block",fontSize:"var(--seed-font-size-t4-static)",fontWeight:i?600:500},children:e.label}),e.description&&(0,n.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.45},children:e.description}),i&&e.preview&&(0,n.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:e.preview})]}),l&&(0,n.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.recommended")})]},`${t.id}:${r}`)})}),(0,n.jsx)("input",{value:u[t.id]??"",onChange:e=>{g(),p(r=>({...r,[t.id]:e.target.value}))},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&i()},placeholder:s("chat.customAnswer"),"aria-label":s("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)"}})]},t.id)})})}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{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:s("chat.cancel")}),(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{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:s("chat.chatAboutThis")}),(0,n.jsx)("button",{type:"button",disabled:!r||a?.status==="sending",onClick:i,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:r&&a?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:r&&a?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:r&&a?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:a?.status==="sending"?s("chat.responseSending"):s("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,n.jsx)(lN,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:a,children:(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,n.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.planApproval")}),(0,n.jsx)("div",{id:`plan-review-${e.id}`,style:{marginTop:4,color:"var(--text)",fontSize:"var(--seed-font-size-t5-static)",fontWeight:600},children:e.title}),(0,n.jsx)("div",{style:{marginTop:5,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)",overflowWrap:"anywhere"},children:e.planFilePath})]}),(0,n.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,n.jsx)(tJ,{children:e.planContent})}),(0,n.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("textarea",{value:h,onChange:e=>f(e.target.value),placeholder:s("chat.planFeedback"),"aria-label":s("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,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"refine",feedback:h.trim()})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.refinePlan")}),(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{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:s("chat.approvePlan")})]})]})]})}):(0,n.jsx)(lN,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,n.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{id:`extension-request-${e.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:e.title}),(0,n.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:s("chat.extensionRequest")})]}),(0,n.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===e.method&&(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,n.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(r=>(0,n.jsx)("button",{onClick:()=>t(e,{value:r}),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:r},r))}),"input"===e.method&&(0,n.jsx)("input",{autoFocus:!0,value:l,placeholder:e.placeholder,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&x()},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"===e.method&&(0,n.jsx)("textarea",{autoFocus:!0,value:l,onChange:e=>o(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&x()},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,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("button",{onClick:()=>t(e,{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:s("chat.cancel")}),"confirm"===e.method?(0,n.jsx)("button",{onClick:x,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:s("chat.confirm")}):"select"!==e.method?(0,n.jsx)("button",{onClick:x,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:s("chat.submit")}):null]})]})})}function lT({request:e,onInput:t}){let{t:r}=(0,R.s)(),a=(0,i.useRef)(null),s=(0,i.useRef)(!1),l=eI(e.lines);return(0,i.useEffect)(()=>{a.current?.focus()},[e.id]),(0,n.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,n.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:e=>{e.target.closest("button")||a.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,n.jsx)("textarea",{ref:a,"aria-label":r("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:r=>{if(s.current||r.nativeEvent.isComposing)return;let n=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=e$[e.key];if(t)return t;if(1===e.key.length)return`\x1b${e.key}`}return"Enter"===e.key?e.shiftKey?"\n":"\r":"Tab"===e.key?e.shiftKey?"\x1b[Z":" ":eM[e.key]??null}(r);n&&(r.preventDefault(),r.stopPropagation(),t(e,n))},onInput:r=>{if(s.current||r.nativeEvent.isComposing)return;let n=r.currentTarget.value;r.currentTarget.value="",n&&t(e,n)},onCompositionStart:()=>{s.current=!0},onCompositionEnd:r=>{s.current=!1;let n=r.currentTarget;queueMicrotask(()=>{let r=n.value;n.value="",r&&t(e,r)})},onPaste:r=>{r.preventDefault();let n=r.clipboardData.getData("text");n&&t(e,`\x1b[200~${n}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:r("chat.extensionPanel")}),(0,n.jsx)("button",{onClick:()=>t(e,"\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:r("chat.close")})]}),(0,n.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:(l.length?l:[""]).map((e,t,r)=>{var a;return(0,n.jsxs)(i.Fragment,{children:[(a=`line-${t}`,eT(e).map((e,t)=>Object.keys(e.style).length>0?(0,n.jsx)("span",{style:e.style,children:e.text},`${a}-${t}`):e.text)),t<r.length-1?"\n":null]},t)})})]})})}function lM({onPick:e,t}){let[r,a]=(0,i.useState)(""),[s,l]=(0,i.useState)({kind:"idle"}),o=(0,i.useRef)(null),d=r.trim();(0,i.useEffect)(()=>{if(d.length<2)return void l({kind:"idle"});let e=new AbortController;l({kind:"loading"});let t=setTimeout(()=>{fetch(`/api/sessions/search?q=${encodeURIComponent(d)}`,{signal:e.signal,cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);l({kind:"done",data:await e.json()})}).catch(()=>{e.signal.aborted||l({kind:"error"})})},250);return()=>{clearTimeout(t),e.abort()}},[d]);let c=e=>{let t=o.current?.querySelectorAll("button");t&&0!==t.length&&t[Math.max(0,Math.min(t.length-1,e))]?.focus()},u="done"===s.kind?s.data:null,p=u?.truncated?t(`palette.searchTruncated.${u.truncated}`,{scanned:u.scannedSessions,total:u.totalSessions}):null;return(0,n.jsxs)("div",{className:"palette-search",children:[(0,n.jsx)("input",{type:"search",value:r,onChange:e=>a(e.target.value),onKeyDown:t=>{if(!t.nativeEvent.isComposing){if("ArrowDown"===t.key)t.preventDefault(),c(0);else if("Enter"===t.key&&u&&u.hits.length>0){t.preventDefault();let r=u.hits[0],n=u.sessions[r.sessionId];n&&e(n,r,u.query)}}},placeholder:t("palette.searchPlaceholder"),"aria-label":t("palette.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),d.length>=2&&(0,n.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":t("palette.searchResults"),"aria-busy":"loading"===s.kind,children:[(0,n.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===s.kind&&t("palette.searching"),"error"===s.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),p?` \xb7 ${p}`:"",u&&u.compactedHits>0?` \xb7 ${t("palette.searchCompacted",{count:u.compactedHits})}`:""]}),u&&u.hits.length>0&&(0,n.jsx)("div",{ref:o,className:"palette-search-list",children:u.hits.map((r,i)=>{let a=u.sessions[r.sessionId],s=r.matchStart+u.query.length;return(0,n.jsxs)("button",{type:"button",disabled:!a,onClick:()=>a&&e(a,r,u.query),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),c(i+("ArrowDown"===e.key?1:-1)))},children:[(0,n.jsxs)("span",{className:"palette-search-title",children:[(0,n.jsx)("span",{children:a?a.name?.trim()||a.firstMessage?.trim()||a.id:""}),(0,n.jsx)("small",{children:"user"===r.role?t("palette.searchRoleUser"):t("palette.searchRoleAssistant")})]}),(0,n.jsxs)("span",{className:"palette-search-snippet",children:[r.snippet.slice(0,r.matchStart),(0,n.jsx)("mark",{children:r.snippet.slice(r.matchStart,s)}),r.snippet.slice(s)]})]},`${r.sessionId}:${r.entryId}`)})})]})]})}var l$=r(50640),lR=r(73620);let lE=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function lL(e){return function e(t,r){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(r.has(t))return"[Circular]";r.add(t);try{return t.map(t=>e(t,r)).filter(Boolean).join(", ")}finally{r.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}let lz=["tags","categories","keywords","tag","category"];function lA({data:e}){var t;if(!e)return null;let r=Object.entries(e);if(0===r.length)return null;let i="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,a=lz.find(t=>Array.isArray(e[t])),s=a?e[a].map(lL).filter(Boolean):[],l=r.filter(([e])=>e!==a&&("title"!==e||!i));return(0,n.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,n.jsx)("div",{className:"markdown-frontmatter-title",children:i}),s.length>0&&(0,n.jsx)("div",{className:"markdown-frontmatter-tags",children:s.map((e,t)=>(0,n.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),l.length>0&&(0,n.jsx)("dl",{className:"markdown-frontmatter-rows",children:l.map(([e,t])=>(0,n.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,n.jsx)("dt",{children:e}),(0,n.jsx)("dd",{children:function(e){let t=lL(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,n.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(t)})]},e))})]})}let lP={source:"Source",preview:"Preview",diff:"Diff"},lW={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},lF={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 l_(){return(0,n.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,n.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,n.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function lD(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function lH(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let r=t.getRangeAt(0);if(!e.contains(r.startContainer)||!e.contains(r.endContainer))return null;let n=lD(r.startContainer),i=lD(r.endContainer);if(!n||!i||!e.contains(n)||!e.contains(i))return null;let a=Number(n.dataset.lineNumber),s=Number(i.dataset.lineNumber);if(!Number.isInteger(a)||!Number.isInteger(s))return null;if(a<s){let e=n.querySelector(".file-source-line-content");if(e?.contains(r.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(r.startContainer,r.startOffset),0===t.toString().length){let e=n.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(a=Number((n=e).dataset.lineNumber))}}let t=i.querySelector(".file-source-line-content");if(t?.contains(r.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(r.endContainer,r.endOffset),0===e.toString().length){let e=i.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((i=e).dataset.lineNumber))}}}return a>s?null:{startLine:a,endLine:s}}function lO({rows:e,stylesheet:t,useInlineStyles:r,wrapLines:i}){return e.map((e,a)=>{let s=e.children??[],l=s[0]?.properties?.className,o=Array.isArray(l)&&l.includes("react-syntax-highlighter-line-number"),d=o?s[0]:null,c=o?s.slice(1):s;return(0,n.jsxs)("span",{className:"file-source-line","data-line-number":a+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,l$.Ay)({node:d,stylesheet:t,useInlineStyles:r,key:`source-line-number-${a}`}),(0,n.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:i?"anywhere":"normal",whiteSpace:i?"pre-wrap":"pre"},children:c.map((e,n)=>(0,l$.Ay)({node:e,stylesheet:t,useInlineStyles:r,key:`source-token-${a}-${n}`}))})]},`source-line-${a}`)})}function lB(e,t,r,n={}){let i=tn(e),a=new URLSearchParams({type:t});for(let[e,t]of(r&&a.set("sessionId",r),Object.entries(n)))void 0!==t&&a.set(e,String(t));return`/api/files/${i}?${a.toString()}`}function lU({filePath:e,sourceSessionId:t}){let{t:r}=(0,R.s)();return(0,n.jsx)("a",{href:lB(e,"download",t),download:ti(e),title:r("i18n.downloadFile"),"aria-label":r("i18n.downloadFile"),className:"file-viewer-icon-button",children:(0,n.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,n.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,n.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,n.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})}function lq(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function lK({patch:e}){let t,{t:r}=(0,R.s)(),i=(t=rm(e))?t.flatMap(e=>e.rows.flatMap(e=>{if("hunk"===e.type)return[];if("context"===e.left.type&&"context"===e.right.type)return[{type:"unchanged",text:e.right.text,oldLineNo:e.left.lineNo,newLineNo:e.right.lineNo}];let t=[];return"removed"===e.left.type&&t.push({type:"removed",text:e.left.text,oldLineNo:e.left.lineNo,newLineNo:null}),"added"===e.right.type&&t.push({type:"added",text:e.right.text,oldLineNo:null,newLineNo:e.right.lineNo}),t})):[];if(!i.some(e=>"unchanged"!==e.type))return(0,n.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:r("i18n.noChanges")});let a=new Set(i.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),s=new Set;for(let e of a)for(let t=Math.max(0,e-3);t<=Math.min(i.length-1,e+3);t++)s.add(t);let l=[],o=0;for(;o<i.length;)if(s.has(o)){let e=[];for(;o<i.length&&s.has(o);)e.push(i[o]),o++;l.push({hidden:!1,lines:e})}else{let e=0;for(;o<i.length&&!s.has(o);)e++,o++;l.push({hidden:!0,count:e})}return(0,n.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...lW},children:l.map((e,t)=>{if(e.hidden)return(0,n.jsxs)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:["... ",e.count," unchanged lines ..."]},t);let r=e.lines.map((e,t)=>{let r="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",a="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,n.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:r,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,n.jsx)("span",{style:lF,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,n.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:a,userSelect:"none",flexShrink:0,fontWeight:600},children:i}),(0,n.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},t)});return(0,n.jsx)("div",{children:r},t)})})}function lV({filePath:e,cwd:t,sourceSessionId:r}){let{t:a}=(0,R.s)(),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(null),g=(0,i.useRef)(null),x=ti(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{d(0),u(null),h(null),m(null),l(!1),g.current&&(g.current.close(),g.current=null);let t=new EventSource(lB(e,"watch",r));return g.current=t,t.addEventListener("connected",()=>l(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&u(t.size)}catch{}d(e=>e+1)}),t.addEventListener("error",()=>l(!1)),t.onerror=()=>l(!1),()=>{t.close(),g.current=null}},[e,r]);let v=lB(e,"read",r,o?{v:o}:void 0),b=null!=c?lq(c):null;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.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,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:ta(e,t)}),(0,n.jsx)("span",{style:{marginLeft:"auto"},children:x||"image"}),p&&(0,n.jsxs)("span",{children:[p.w," \xd7 ",p.h]}),b&&(0,n.jsx)("span",{children:b}),(0,n.jsxs)("span",{title:a(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)"},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]}),(0,n.jsx)(lU,{filePath:e,sourceSessionId:r})]}),(0,n.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:f?(0,n.jsx)("div",{style:{color:"#f87171",fontSize:13},children:f}):(0,n.jsx)("img",{src:v,alt:e,onLoad:e=>{let t=e.currentTarget;h({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>m("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function lJ({filePath:e,cwd:t,sourceSessionId:r}){let{t:a}=(0,R.s)(),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(null),g=(0,i.useRef)(null),x=ti(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{d(0),u(null),h(null),m(null),l(!1),g.current&&(g.current.close(),g.current=null);let t=new EventSource(lB(e,"watch",r));return g.current=t,t.addEventListener("connected",()=>l(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&u(t.size)}catch{}h(null),m(null),d(e=>e+1)}),t.addEventListener("error",()=>l(!1)),t.onerror=()=>l(!1),()=>{t.close(),g.current=null}},[e,r]);let v=lB(e,"read",r,o?{v:o}:void 0);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.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,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:ta(e,t)}),(0,n.jsx)("span",{style:{marginLeft:"auto"},children:x||"audio"}),null!=p&&(0,n.jsx)("span",{children:function(e){if(!Number.isFinite(e))return"";let t=Math.round(e),r=Math.floor(t/60);return`${r}:${String(t%60).padStart(2,"0")}`}(p)}),null!=c&&(0,n.jsx)("span",{children:lq(c)}),(0,n.jsxs)("span",{title:a(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)"},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]}),(0,n.jsx)(lU,{filePath:e,sourceSessionId:r})]}),(0,n.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,n.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[f&&(0,n.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:f}),(0,n.jsx)("audio",{controls:!0,preload:"metadata",src:v,onLoadedMetadata:e=>h(e.currentTarget.duration),onError:()=>m("Failed to load audio"),style:{width:"100%"}},v)]})})]})}function lG({filePath:e,cwd:t,sourceSessionId:r}){let{t:a}=(0,R.s)(),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),f=(0,i.useRef)(null),m=eL(e),g="pdf"===m,x=g?lB(e,"read",r,o?{v:o}:void 0):lB(e,"preview",r,o?{v:o}:void 0);return(0,i.useEffect)(()=>{d(0),u(null),h(null),l(!1),f.current&&(f.current.close(),f.current=null),fetch(lB(e,"meta",r)).then(e=>e.json()).then(e=>{e.error&&h(e.error),"number"==typeof e.size&&(u(e.size),!g&&e.size>0xa00000&&h("DOCX too large for preview (>10MB)"))}).catch(e=>h(String(e)));let t=new EventSource(lB(e,"watch",r));return f.current=t,t.addEventListener("connected",()=>l(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(u(t.size),!g&&t.size>0xa00000))return void h("DOCX too large for preview (>10MB)")}catch{}h(null),d(e=>e+1)}),t.addEventListener("error",()=>l(!1)),t.onerror=()=>l(!1),()=>{t.close(),f.current=null}},[e,g,r]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.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,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:ta(e,t)}),(0,n.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===m?"docx preview":"pdf"}),null!=c&&(0,n.jsx)("span",{children:lq(c)}),(0,n.jsx)(lU,{filePath:e,sourceSessionId:r}),(0,n.jsxs)("span",{title:a(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]})]}),(0,n.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:p?(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:p}):(0,n.jsx)("iframe",{src:x,sandbox:g?void 0:"allow-same-origin",title:a("i18n.previewFile",{file:ti(e)}),style:{width:"100%",height:"100%",border:"none",background:g?"var(--bg)":"#eef1f5"}},x)})]})}function lY({filePath:e,cwd:t,sourceSessionId:r,onOpenFile:i,onMentionLines:a,onAtMention:s,gitRefreshKey:l,initialDisplayMode:o}){let d;return ez(e)?(0,n.jsx)(lV,{filePath:e,cwd:t,sourceSessionId:r}):null!==(eE[eL(e)]??null)?(0,n.jsx)(lJ,{filePath:e,cwd:t,sourceSessionId:r}):null!==("pdf"===(d=eL(e))||"docx"===d?d:null)?(0,n.jsx)(lG,{filePath:e,cwd:t,sourceSessionId:r}):(0,n.jsx)(lZ,{filePath:e,cwd:t,sourceSessionId:r,onOpenFile:i,onMentionLines:a,onAtMention:s,gitRefreshKey:l,initialDisplayMode:o})}function lZ({filePath:e,cwd:t,sourceSessionId:r,onOpenFile:a,onMentionLines:s,onAtMention:l,gitRefreshKey:o,initialDisplayMode:d}){let c,u,{isDark:p}=tO(),{t:h}=(0,R.s)(),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(!1),[y,w]=(0,i.useState)(!0),[k,j]=(0,i.useState)(null),[S,C]=(0,i.useState)("source"),[N,I]=(0,i.useState)(!1),[T,M]=(0,i.useState)(!1),$=(0,i.useRef)(null),E=(0,i.useRef)(0),L=(0,i.useRef)(null),[z,A]=(0,i.useState)(null),P=(0,i.useCallback)(e=>fetch(lB(e,"read",r)).then(e=>e.json()).then(e=>e.error?(j(e.error),null):(j(null),m(e),e)).catch(e=>(j(String(e)),null)),[r]),W=(0,i.useCallback)(async e=>{let r=++E.current;if(b(!0),!t){x(null),b(!1);return}try{let n=new URLSearchParams({cwd:t,path:e}),i=await fetch(`/api/git/diff?${n.toString()}`),a=await i.json();if(r!==E.current)return;x(i.ok&&a.supported&&"string"==typeof a.patch?a:null)}catch{r===E.current&&x(null)}finally{r===E.current&&b(!1)}},[t]);(0,i.useEffect)(()=>{w(!0),j(null),m(null),x(null),C("source"),I(!1),M(!1),$.current&&($.current.close(),$.current=null),P(e).finally(()=>w(!1));let t=new EventSource(lB(e,"watch",r));return $.current=t,t.addEventListener("connected",()=>{M(!0)}),t.addEventListener("change",()=>{P(e),W(e)}),t.addEventListener("error",()=>{M(!1)}),t.onerror=()=>{M(!1)},()=>{t.close(),$.current=null}},[e,P,W,r]),(0,i.useEffect)(()=>{W(e)},[W,e,o]),(0,i.useEffect)(()=>{(f?.language==="markdown"||f?.language==="html")&&"diff"!==d&&C("preview")},[f?.language,d]);let F=g?.supported===!0&&"string"==typeof g.patch,_=F&&"deleted"===g.status;(0,i.useEffect)(()=>{F||"diff"!==S||C("source")},[S,F]),(0,i.useEffect)(()=>{_&&$.current&&($.current.close(),$.current=null,M(!1))},[_]);let D=(0,i.useRef)(!1);(0,i.useEffect)(()=>{D.current=!1},[e]),(0,i.useEffect)(()=>{"diff"===d&&F&&!D.current&&(D.current=!0,C("diff"))},[d,F]);let H=(0,i.useMemo)(()=>f?.language==="markdown"?tf(f.content):"",[f]),O=(0,i.useMemo)(()=>f?.language==="markdown"?function(e){let t=function(e){let t=lE.exec(e);if(!t)return null;let r=/^---[ \t]*(?:(?:\r\n|\n|\r)|$)/gm;r.lastIndex=t[0].length;let n=r.exec(e);return n?{yaml:e.slice(t[0].length,n.index).replace(/(?:\r\n|\n|\r)$/,""),rest:e.slice(n.index+n[0].length)}:null}(e);if(!t)return{data:null,rest:e};try{let e=(0,lR.Hh)(t.yaml);if(e&&"object"==typeof e&&!Array.isArray(e))return{data:e,rest:t.rest}}catch{}return{data:null,rest:t.rest}}(f.content):null,[f]);(0,i.useEffect)(()=>{let e=()=>{let e=L.current;A(s&&"source"===S&&e?lH(e,window.getSelection()):null)};if(e(),s&&"source"===S)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[f?.content,S,s]);let B=(0,i.useCallback)(r=>{s&&r&&s(ta(e,t),r.startLine,r.endLine)},[t,e,s]);if((0,i.useEffect)(()=>{if(!s||"source"!==S)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let r=L.current,n=r?lH(r,window.getSelection()):null;n&&(e.preventDefault(),B(n))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[S,B,s]),y||"diff"===d&&v&&!f)return(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:h("i18n.loading")});if(k&&!_)return(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:k});if(!f&&!_)return null;let U=f?.language??"text",q=f?.content??"",K="html"===U,V="markdown"===U,J=(u=(c=tr(e).replace(/\/+$/,"")).lastIndexOf("/"))<0?"":0===u?"/":2===u&&/^[a-zA-Z]:\//.test(c)?c.slice(0,3):c.slice(0,u),G=q.split("\n"),Y=_?"diff":S,Z=_?["diff"]:["source",...K||V?["preview"]:[],...F?["diff"]:[]],X=_?h("files.deleted"):`${U} \xb7 ${G.length} lines \xb7 ${lq(f.size)}`;return(0,n.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.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,n.jsx)("span",{className:"file-viewer-path",style:{fontFamily:"var(--font-mono)"},title:e,children:ta(e,t)}),(0,n.jsx)("span",{className:"file-viewer-meta",title:X,children:X}),!_&&(0,n.jsx)("span",{title:T?h("i18n.liveSync"):h("i18n.notWatching"),"aria-label":T?h("i18n.liveSync"):h("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:T?"#4ade80":"var(--border)",boxShadow:T?"0 0 4px #4ade80":"none"}}),(0,n.jsxs)("div",{className:"file-viewer-controls",children:[Z.length>1&&(0,n.jsx)("div",{className:"file-viewer-mode-switch","aria-label":h("i18n.fileViewMode"),children:Z.map(e=>{let t=Y===e;return(0,n.jsx)("button",{type:"button",onClick:()=>C(e),title:"diff"===e?h("i18n.compareHead"):void 0,"aria-pressed":t,className:"file-viewer-mode-button",style:{background:t?"var(--bg-selected)":"transparent",color:t?"var(--text)":"var(--text-muted)"},children:lP[e]},e)})}),(0,n.jsxs)("div",{className:"file-viewer-actions",children:[(l||s)&&(0,n.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{z&&s?B(z):l?.(ta(e,t),!1)},title:z&&s?`${h("i18n.mentionSelectedLines")} (L${z.startLine}${z.startLine!==z.endLine?`-L${z.endLine}`:""})`:h("files.insertPath"),"aria-label":h("files.mention"),disabled:!l&&!s,className:"file-viewer-icon-button",children:(0,n.jsx)(l_,{})}),"source"===Y&&(0,n.jsx)(n.Fragment,{children:(0,n.jsx)("button",{type:"button",onClick:()=>I(e=>!e),title:N?h("i18n.disableWrap"):h("i18n.enableWrap"),"aria-label":N?h("i18n.disableWrap"):h("i18n.enableWrap"),"aria-pressed":N,className:"file-viewer-icon-button",style:{background:N?"var(--bg-selected)":"transparent",color:N?"var(--text)":"var(--text-muted)"},children:(0,n.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,n.jsx)("path",{d:"M3 6h18"}),(0,n.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,n.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,n.jsx)("path",{d:"M3 18h7"})]})})})]}),!_&&(0,n.jsx)(lU,{filePath:e,sourceSessionId:r})]})]}),(0,n.jsx)("div",{ref:L,className:"file-viewer-content",style:{flex:1,overflow:"auto",background:"var(--bg)"},children:"diff"===Y&&F?(0,n.jsx)(lK,{patch:g.patch}):K&&"preview"===Y?(0,n.jsx)("iframe",{srcDoc:q,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:h("i18n.htmlPreview")}):V&&"preview"===Y?(0,n.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[O?.data&&(0,n.jsx)(lA,{data:O.data}),(0,n.jsx)(tt.oz,{remarkPlugins:tb,rehypePlugins:tw,components:{code({className:e,children:t,...r}){let i=e?.replace("language-","").toLowerCase()??"",a=String(t);return e?.includes("language-")||a.includes("\n")?"mermaid"===i?(0,n.jsx)(tq,{code:a.replace(/\n$/,""),defaultPreview:!0}):(0,n.jsx)(tV,{code:a.replace(/\n$/,""),lang:i}):(0,n.jsx)("code",{className:e,...r,children:t})},pre:({children:e})=>(0,n.jsx)(n.Fragment,{children:e}),a({href:e,children:r,...i}){delete i.node;let s=a?e5(e,J,t??J):null;return s&&a?(0,n.jsx)("a",{href:e,...i,onClick:e=>{e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),a(s))},children:r}):(0,n.jsx)("a",{href:e,...i,children:r})},img({src:e,alt:i,...a}){delete a.node;let s="string"==typeof e?e5(e,J,t??J):null,l=s?lB(s,"read",r):e;return(0,n.jsx)("img",{src:l,alt:i??"",loading:"lazy",...a})},table:({children:e})=>(0,n.jsx)("div",{className:"markdown-table-wrap",children:(0,n.jsx)("table",{children:e})})},children:H})]}):(0,n.jsx)(e9.A,{className:N?"file-source-view is-wrapped":"file-source-view",language:"text"===U?"plaintext":U,style:p?te.xJ:te.vs,showLineNumbers:!0,lineNumberStyle:{...lF},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...lW,width:N?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",overflowWrap:N?"anywhere":"normal"}},renderer:e=>(0,n.jsx)(lO,{...e,wrapLines:N}),wrapLongLines:N,children:q})})]})}function lX({tabs:e,activeTabId:t,onSelectTab:r,onCloseTab:a}){let{t:s,locale:l}=(0,R.s)(),[o,d]=(0,i.useState)(null);return(0,n.jsx)("div",{className:"file-tab-list",role:"tablist","aria-label":"ko"===l?"열린 파일 탭":"Open file tabs",style:{display:"flex",alignItems:"flex-end",overflowX:"auto",flexShrink:0,height:36},children:e.map(e=>{let i=e.id===t;return(0,n.jsxs)("div",{className:`file-tab${i?" is-active":""}`,role:"presentation",onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:t=>{1===t.button&&(t.preventDefault(),t.stopPropagation(),a(e.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,n.jsxs)("button",{type:"button",role:"tab","aria-selected":i,onClick:()=>r(e.id),title:e.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,n.jsx)("span",{style:{flexShrink:0,opacity:i?1:.7,display:"flex",alignItems:"center"},children:rj(e.label,13)}),(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:i?500:400},children:e.label})]}),(0,n.jsx)("button",{className:"file-tab-close",onClick:t=>{t.stopPropagation(),a(e.id)},onMouseEnter:()=>d(e.id),onMouseLeave:()=>d(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:o===e.id?"var(--bg-hover)":"transparent",border:"none",color:o===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:s("i18n.close"),"aria-label":`${s("i18n.close")} ${e.label}`,children:(0,n.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,n.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,n.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})})}let lQ=["inherit","off","auto","minimal","low","medium","high","xhigh","max"],l0=new Set(lQ);function l1(e){return void 0!==e&&l0.has(e)}function l2(e){if(!e)return[...lQ];let t=new Set(e);return lQ.filter(e=>"inherit"===e||"off"===e||"auto"===e||t.has(e))}function l4(e){if(!e)return"inherit";let t=e.lastIndexOf(":"),r=t>=0?e.slice(t+1):void 0;return l1(r)?r:"inherit"}function l5(e,t){let r=e.lastIndexOf(":"),n=l1(r>=0?e.slice(r+1):void 0)?e.slice(0,r):e;return"inherit"===t?n:`${n}:${t}`}var l8=r(98795),l6=r.n(l8);function l3(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase()}function l7({value:e,options:t,onChange:r,disabled:a=!1,placeholder:s="Select…",searchPlaceholder:l="Search options…",noResultsLabel:o="No matching options",ariaLabel:d,className:c,style:u}){let p=(0,i.useRef)(null),h=(0,i.useRef)(null),f=(0,i.useRef)(null),m=(0,i.useRef)([]),[g,x]=(0,i.useState)(!1),[v,b]=(0,i.useState)(""),[y,w]=(0,i.useState)(0),k=(0,i.useId)(),j=t.find(t=>t.value===e),S=(0,i.useMemo)(()=>{let e=l3(v.trim());return e?t.filter(t=>l3(`${t.label} ${t.value} ${t.searchText??""}`).includes(e)):t},[t,v]);(0,i.useEffect)(()=>{if(!g)return;let e=e=>{p.current?.contains(e.target)||x(!1)};return document.addEventListener("pointerdown",e),()=>document.removeEventListener("pointerdown",e)},[g]),(0,i.useEffect)(()=>{g?requestAnimationFrame(()=>f.current?.focus()):b("")},[g]),(0,i.useEffect)(()=>{if(!g)return;let t=S.findIndex(t=>t.value===e&&!t.disabled);w(t>=0?t:Math.max(0,S.findIndex(e=>!e.disabled)))},[S,g,e]),(0,i.useEffect)(()=>{(y>=S.length||S[y]?.disabled)&&w(Math.max(0,S.findIndex(e=>!e.disabled)))},[y,S]),(0,i.useEffect)(()=>{g&&m.current[y]?.scrollIntoView({block:"nearest"})},[y,g]);let{side:C,maxHeight:N}=aX(p,g,{viewportFraction:.6,cap:296,gap:5,prefer:"below",minHeight:160}),I=e=>{e.disabled||(r(e.value),x(!1))},T=e=>{if(!S.length)return;let t=y;for(let r=0;r<S.length;r+=1)if(t=(t+e+S.length)%S.length,!S[t].disabled)return void w(t)};return(0,n.jsxs)("div",{ref:p,className:`${l6().root}${c?` ${c}`:""}`,style:u,children:[(0,n.jsxs)("button",{ref:h,type:"button",className:l6().trigger,disabled:a,"aria-label":d,"aria-haspopup":"listbox","aria-expanded":g,"aria-controls":g?k:void 0,onClick:()=>x(e=>!e),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),x(!0))},children:[(0,n.jsx)("span",{className:j?l6().value:l6().placeholder,children:j?.label??(e||s)}),(0,n.jsx)("svg",{className:l6().chevron,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m3 4.5 3 3 3-3"})})]}),g&&(0,n.jsxs)("div",{className:l6().popover,style:"above"===C?{bottom:"calc(100% + 5px)",maxHeight:N}:{top:"calc(100% + 5px)",maxHeight:N},"data-dismissible-layer":"searchable-select",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),x(!1),h.current?.focus())},children:[(0,n.jsxs)("div",{className:l6().searchWrap,children:[(0,n.jsxs)("svg",{className:l6().searchIcon,viewBox:"0 0 16 16","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"7",cy:"7",r:"4.25"}),(0,n.jsx)("path",{d:"m10.2 10.2 3.1 3.1"})]}),(0,n.jsx)("input",{ref:f,className:l6().search,value:v,placeholder:l,"aria-label":l,role:"combobox","aria-expanded":"true","aria-controls":k,"aria-activedescendant":S[y]?`${k}-${y}`:void 0,autoComplete:"off",spellCheck:!1,onChange:e=>{b(e.target.value),w(0)},onKeyDown:e=>{if("ArrowDown"===e.key)e.preventDefault(),T(1);else if("ArrowUp"===e.key)e.preventDefault(),T(-1);else if("Enter"===e.key){e.preventDefault();let t=S[y];t&&I(t)}else"Tab"===e.key&&x(!1)}})]}),(0,n.jsx)("div",{id:k,className:l6().options,role:"listbox","aria-label":d,style:{maxHeight:Math.max(0,N-46)},children:S.length?S.map((t,r)=>(0,n.jsxs)("button",{ref:e=>{m.current[r]=e},id:`${k}-${r}`,type:"button",role:"option","aria-selected":t.value===e,className:l6().option,"data-active":r===y,"data-selected":t.value===e,disabled:t.disabled,onMouseEnter:()=>w(r),onClick:()=>I(t),children:[(0,n.jsxs)("span",{className:l6().optionCopy,children:[(0,n.jsx)("span",{className:l6().optionLabel,children:t.label}),t.description&&(0,n.jsx)("span",{className:l6().optionDescription,children:t.description})]}),t.value===e&&(0,n.jsx)("svg",{className:l6().check,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m2.3 6.2 2.2 2.2 5.2-5.2"})})]},t.value)):(0,n.jsx)("div",{className:l6().empty,children:o})})]})]})}let l9=["global","project"],oe=["implSonnet","implOpus","implDeepSeek","makerHardUiOpus","makerHardCodeOpus","makerHardCodeSonnet"];function ot(e){return`${e.provider}/${e.id}`}function or({cwd:e,onRolesChanged:t}){let{t:r}=(0,R.s)(),[a,s]=(0,i.useState)([]),[l,o]=(0,i.useState)([]),[d,c]=(0,i.useState)({}),[u,p]=(0,i.useState)("global"),[h,f]=(0,i.useState)(!0),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),b=(0,i.useCallback)(async t=>{if(!e){s([]),o([]),c({}),f(!1);return}f(!0),g(null);try{let r=`?cwd=${encodeURIComponent(e)}`,[n,i]=await Promise.all([fetch(`/api/model-roles${r}`,t?{signal:t}:void 0),fetch(`/api/models${r}`,t?{signal:t}:void 0)]);if(!n.ok)throw Error(`HTTP ${n.status}`);let a=await n.json();if(a.error)throw Error(a.error);if(!i.ok)throw Error(`HTTP ${i.status}`);let l=await i.json();s(a.roles??[]),o(l.modelList??[]),c(l.thinkingLevels??{})}catch(e){if("AbortError"===e.name)return;g(e instanceof Error?e.message:String(e))}finally{f(!1)}},[e]);(0,i.useEffect)(()=>{let e=new AbortController;return b(e.signal),()=>e.abort()},[b]);let y=(0,i.useCallback)(async(r,n)=>{if(e){v(r),g(null);try{let i=await fetch("/api/model-roles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,role:r,selector:n,scope:u})}),a=await i.json();if(!i.ok||a.error)throw Error(a.error??`HTTP ${i.status}`);s(a.roles??[]),t?.()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(null)}}},[e,u,t]),w=(0,i.useMemo)(()=>a.filter(e=>!e.hidden),[a]),k=w.some(e=>oe.includes(e.role)&&!e.selector);return e?(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{fontSize:13,fontWeight:700,color:"var(--text)",marginBottom:4},children:r("roles.title")}),(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:r("roles.description")}),!h&&k&&(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",lineHeight:1.5,marginTop:4},children:r("roles.harnessNote")})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8},children:[(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:r("roles.scope")}),(0,n.jsx)("div",{style:{display:"flex",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,overflow:"hidden"},children:l9.map(e=>(0,n.jsx)("button",{onClick:()=>p(e),style:{padding:"4px 10px",border:"none",background:u===e?"var(--bg-selected)":"transparent",color:u===e?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:u===e?600:400},children:"global"===e?r("roles.scopeGlobal"):r("roles.scopeProject")},e))}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"global"===u?"~/.omp/agent/config.yml":".omp/config.yml"})]}),m&&(0,n.jsx)("div",{style:{fontSize:12,color:"var(--danger, #ff4757)"},children:m}),h?(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:r("i18n.loading")}):(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:w.map(e=>{let t=e.resolved?`${e.resolved.provider}/${e.resolved.modelId}`:l5(e.selector??"","inherit"),i=l4(e.selector),a=l2(d[e.resolved?`${e.resolved.provider}:${e.resolved.modelId}`:""]),s=oe.includes(e.role);return(0,n.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,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,rowGap:6},children:[(0,n.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:e.tag??e.role.toUpperCase()}),(0,n.jsxs)("div",{style:{minWidth:0,flex:"0 0 auto",width:128},children:[(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontWeight:600},children:e.name}),s&&(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-muted)",lineHeight:1.35},children:r(`roles.harness.${e.role}`)}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)"},children:s&&!e.selector?r("roles.harnessUnset"):r(`roles.source.${e.source}`)})]}),(0,n.jsx)(l7,{value:t,disabled:x===e.role,ariaLabel:e.name,style:{flex:"1 1 160px",minWidth:0},onChange:t=>{if(!t)return void y(e.role,null);let r=l.find(e=>ot(e)===t),n=r?d[`${r.provider}:${r.id}`]:void 0,i=l4(e.selector),a=l2(n).includes(i)?i:"inherit";y(e.role,l5(t,a))},options:[{value:"",label:r("roles.unset")},...l.map(e=>({value:ot(e),label:`${e.name} — ${e.provider}`,searchText:ot(e)})),...t&&!l.some(e=>ot(e)===t)?[{value:t,label:t}]:[]]}),e.warning&&(0,n.jsx)("span",{title:e.warning,style:{color:"var(--warning, #ffb347)",fontSize:12},children:"!"})]}),e.resolved&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",paddingLeft:72},children:[(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,whiteSpace:"nowrap"},children:r("roles.thinking")}),(0,n.jsx)("div",{role:"group","aria-label":`${e.name} ${r("roles.thinking")}`,style:{display:"flex",flex:"1 1 auto",minWidth:0,flexWrap:"wrap",gap:3},children:a.map(a=>{let s=i===a;return(0,n.jsx)("button",{type:"button","aria-pressed":s,disabled:x===e.role,title:"inherit"===a?r("roles.thinkingInherit"):a,onClick:()=>{s||y(e.role,l5(t,a))},style:{padding:"3px 7px",border:`1px solid ${s?"var(--accent)":"var(--border)"}`,borderRadius:4,background:s?"var(--bg-selected)":"transparent",color:s?"var(--accent)":"var(--text-muted)",cursor:x===e.role?"not-allowed":"pointer",fontFamily:"var(--font-mono)",fontSize:10,fontWeight:s?700:500,lineHeight:1.2,opacity:x===e.role?.55:1},children:a},a)})})]})]},e.role)})})]}):(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:r("roles.needsProject")})}function on(e){window.open(e,"_blank","noopener,noreferrer")}var oi=r(67381),oa=r(64433),os=r(70350),ol=r(88195),oo=r(9312),od=r(87275),oc=r(22008),ou=r(95476),op=r(35029),oh=r(14489),of=r(78728),om=r(19872),og=r(7751),ox=r(92526),ov=r(48238),ob=r(57794),oy=r(41098),ow=r(84604),ok=r(15315),oj=r(74278),oS=r(55457),oC=r(71437),oN=r(29167),oI=r(97283),oT=r(34166),oM=r(33889),o$=r(85486),oR=r(74068),oE=r(83546),oL=r(83709);let oz={anthropic:{Icon:oi.A,hasColor:!1},openai:{Icon:oa.A,hasColor:!1},"openai-codex":{Icon:oa.A,hasColor:!1},google:{Icon:os.A,hasColor:!0},"google-vertex":{Icon:os.A,hasColor:!0},"ant-ling":{Icon:oM.A,hasColor:!0},deepseek:{Icon:ol.A,hasColor:!0},groq:{Icon:oo.A,hasColor:!1},mistral:{Icon:od.A,hasColor:!0},moonshotai:{Icon:oc.A,hasColor:!1},"moonshotai-cn":{Icon:oc.A,hasColor:!1},moonshot:{Icon:oc.A,hasColor:!1},minimax:{Icon:ou.A,hasColor:!0},"minimax-cn":{Icon:ou.A,hasColor:!0},fireworks:{Icon:op.A,hasColor:!0},huggingface:{Icon:oh.A,hasColor:!0},cerebras:{Icon:of.A,hasColor:!0},openrouter:{Icon:om.A,hasColor:!1},xai:{Icon:og.A,hasColor:!1},"cloudflare-ai-gateway":{Icon:ox.A,hasColor:!0},"cloudflare-workers-ai":{Icon:ox.A,hasColor:!0},"vercel-ai-gateway":{Icon:ov.A,hasColor:!1},"github-copilot":{Icon:ob.A,hasColor:!1},"amazon-bedrock":{Icon:oy.A,hasColor:!0},"azure-openai-responses":{Icon:ow.A,hasColor:!0},"kimi-coding":{Icon:ok.A,hasColor:!0},nvidia:{Icon:o$.A,hasColor:!0},opencode:{Icon:oR.A,hasColor:!1},"opencode-go":{Icon:oR.A,hasColor:!1},qwen:{Icon:oj.A,hasColor:!0},xiaomi:{Icon:oE.A,hasColor:!1},"xiaomi-token-plan-ams":{Icon:oE.A,hasColor:!1},"xiaomi-token-plan-cn":{Icon:oE.A,hasColor:!1},"xiaomi-token-plan-sgp":{Icon:oE.A,hasColor:!1},zai:{Icon:oL.A,hasColor:!1},"zai-coding-cn":{Icon:oL.A,hasColor:!1},zhipu:{Icon:oS.A,hasColor:!0},cohere:{Icon:oC.A,hasColor:!0},perplexity:{Icon:oN.A,hasColor:!0},together:{Icon:oI.A,hasColor:!0},grok:{Icon:oT.A,hasColor:!1}},oA=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function oP({label:e,children:t}){return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("label",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:e}),t]})}let oW={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 oF({value:e,onChange:t,placeholder:r,mono:i}){return(0,n.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:r,style:{...oW,fontFamily:i?"var(--font-mono)":"inherit"}})}function o_({value:e,onChange:t,placeholder:r,mono:a,onKeyDown:s,autoComplete:l="off",spellCheck:o=!1,style:d}){let[c,u]=(0,i.useState)(!1),{t:p}=(0,R.s)();return(0,i.useEffect)(()=>{e||u(!1)},[e]),(0,n.jsxs)("div",{style:{position:"relative",width:"100%",...d},children:[(0,n.jsx)("input",{type:c?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:s,placeholder:r,style:{...oW,paddingRight:34,fontFamily:a?"var(--font-mono)":"inherit"},autoComplete:l,spellCheck:o}),(0,n.jsx)("button",{type:"button",onClick:()=>u(e=>!e),"aria-label":p(c?"i18n.hideDetails":"i18n.showDetails"),title:p(c?"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:c?(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.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,n.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,n.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,n.jsx)("path",{d:"M1 1l22 22"})]}):(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,n.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function oD({value:e,onChange:t,placeholder:r}){return(0,n.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:r,style:oW})}function oH({value:e,onChange:t,options:r,required:i}){let{t:a}=(0,R.s)();return(0,n.jsx)(l7,{value:e,onChange:t,options:[...i?[]:[{value:"",label:`— ${a("i18n.default")} / none —`}],...r.map(e=>({value:e,label:e}))]})}function oO({label:e,checked:t,onChange:r}){return(0,n.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,n.jsx)("input",{type:"checkbox",checked:t,onChange:e=>r(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function oB({children:e}){return(0,n.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:e})}function oU({name:e,provider:t,onChange:r,onRename:a,onDelete:s,onAddModels:l}){let{t:o}=(0,R.s)(),[d,c]=(0,i.useState)(e),[u,p]=(0,i.useState)({phase:"idle"}),[h,f]=(0,i.useState)(""),[m,g]=(0,i.useState)([]),x=(0,i.useRef)(0),v=(0,i.useRef)(null);(0,i.useEffect)(()=>c(e),[e]);let b=(e,n)=>r({...t,[e]:n});(0,i.useEffect)(()=>{t.api||r({...t,api:"openai-completions"})},[t.api]),(0,i.useEffect)(()=>{x.current+=1,p({phase:"idle"}),f(""),g([])},[e,t.baseUrl,t.api,t.apiKey]);let y=(0,i.useCallback)(async()=>{if(!t.baseUrl?.trim()||"loading"===u.phase)return;let r=++x.current;p({phase:"loading"}),g([]);try{let n=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:{...t,models:void 0}})}),i=await n.json();if(r!==x.current)return;if(!n.ok||i.error||!i.models)return void p({phase:"error",message:i.error??`HTTP ${n.status}`});p({phase:"success",models:i.models,endpoint:i.endpoint??t.baseUrl})}catch(e){if(r!==x.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,e,t]),w=new Set((t.models??[]).map(e=>e.id)),k="success"===u.phase?u.models:[],j=h.trim().toLocaleLowerCase(),S=k.filter(e=>!j||e.id.toLocaleLowerCase().includes(j)||e.name?.toLocaleLowerCase().includes(j)),C=S.slice(0,300),N=C.filter(e=>!w.has(e.id)).map(e=>e.id),I=m.filter(e=>!w.has(e)).length,T=N.length>0&&N.every(e=>m.includes(e)),M=!T&&N.some(e=>m.includes(e));return(0,i.useEffect)(()=>{v.current&&(v.current.indeterminate=M)},[M]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(oB,{children:o("i18n.provider")}),(0,n.jsx)("button",{onClick:s,style:{padding:"3px 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11},children:o("i18n.delete")})]}),(0,n.jsxs)(oP,{label:o("i18n.providerName"),children:[(0,n.jsx)(oF,{value:d,onChange:c,placeholder:"provider-name",mono:!0}),d!==e&&d.trim()&&(0,n.jsx)("button",{onClick:()=>a(d.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:o("i18n.rename")})]}),(0,n.jsx)(oP,{label:"Base URL",children:(0,n.jsx)(oF,{value:t.baseUrl??"",onChange:e=>b("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,n.jsxs)(oP,{label:"API Key",children:[(0,n.jsx)(o_,{value:t.apiKey??"",onChange:e=>b("apiKey",e||void 0),placeholder:"ENV_VAR_NAME, !shell-command, or literal key",mono:!0}),(0,n.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:["Prefix with ",(0,n.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:"!"})," to run a shell command, or use an env var name"]})]}),(0,n.jsx)(oP,{label:"API",children:(0,n.jsx)(oH,{value:t.api??"openai-completions",onChange:e=>b("api",e),options:oA,required:!0})}),(0,n.jsxs)(oP,{label:"Headers",children:[(0,n.jsx)(oG,{headers:t.headers,onChange:e=>b("headers",e)}),(0,n.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,n.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==u.phase&&(0,n.jsx)("button",{onClick:y,disabled:!t.baseUrl?.trim()||"loading"===u.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:t.baseUrl?.trim()&&"loading"!==u.phase?"var(--text-muted)":"var(--text-dim)",cursor:t.baseUrl?.trim()&&"loading"!==u.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===u.phase?o("models.discoveryFetching"):o("models.discoveryFetch")}),"error"===u.phase&&(0,n.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:u.message}),"success"===u.phase&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("input",{value:h,onChange:e=>f(e.target.value),placeholder:o("models.discoveryFilterPlaceholder",{count:u.models.length}),"aria-label":o("models.discoveryFilter"),style:{...oW,width:"100%",minWidth:0}}),(0,n.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,n.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:N.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,n.jsx)("input",{ref:v,type:"checkbox",checked:T,disabled:0===N.length,onChange:()=>{let e=new Set(N);g(t=>T?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...N])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),o("models.discoverySelectShown")]}),0===C.length?(0,n.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:o("models.discoveryNoMatches")}):C.map((e,t)=>{let r=w.has(e.id),i=m.includes(e.id);return(0,n.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:r?"default":"pointer",opacity:r?.65:1},children:[(0,n.jsx)("input",{type:"checkbox",checked:i||r,disabled:r,onChange:()=>{var t;return t=e.id,void g(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,n.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,n.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,n.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),r&&(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:o("models.discoveryAdded")})]},e.id)})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,n.jsx)("span",{title:u.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:S.length>C.length?o("models.discoveryShowing",{shown:C.length,total:S.length}):o("models.discoveryFetched",{count:u.models.length})}),(0,n.jsx)("button",{onClick:()=>{if("success"!==u.phase)return;let e=new Set(m),t=u.models.filter(t=>e.has(t.id)&&!w.has(t.id));0!==t.length&&(l(t),g([]))},disabled:0===I,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:I?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",color:I?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:I?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:I?o("models.discoveryAddSelectedCount",{count:I}):o("models.discoveryAddSelected")})]})]})]})]})}let oq=["off","minimal","low","medium","high","xhigh","max"],oK={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function oV({value:e,onChange:t}){let r=e??{},i=(e,n)=>{let i={...r};"omit"===n?delete i[e]:i[e]=n,t(Object.keys(i).length?i:void 0)};return(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:oq.map(e=>{let t=r[e],a=e in r?null===t?"null":"string":"omit",s="string"==typeof t?t:"",l=oK[e],o={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},d={background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontWeight:600};return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,n.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:l,flexShrink:0,opacity:"null"===a?.3:1}}),(0,n.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===a?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===a?"line-through":"none"},children:e})]}),(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,n.jsx)("button",{onClick:()=>i(e,"omit"),style:{...o,..."omit"===a?d:{}},children:"Default"}),(0,n.jsx)("button",{onClick:()=>i(e,null),style:{...o,borderLeft:"1px solid var(--border)",..."null"===a?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===a?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,n.jsx)("button",{onClick:()=>i(e,s||e),style:{...o,..."string"===a?d:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,n.jsx)("input",{value:s,onChange:t=>i(e,t.target.value),onFocus:()=>{"string"!==a&&i(e,s||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===a?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===a?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let oJ={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function oG({headers:e,onChange:t}){let[r,a]=(0,i.useState)(()=>Object.entries(e??{}).map(([e,t],r)=>({id:r,name:e,value:t}))),s=(0,i.useRef)(r.length),l=e=>{a(e),t(function(e){let t={};for(let r of e){let e=r.name.trim();e&&(t[e]=r.value)}return Object.keys(t).length?t:void 0}(e))},o=(e,t)=>{l(r.map(r=>r.id===e?{...r,...t}:r))},d={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[r.map(e=>(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsx)("input",{value:e.name,onChange:t=>o(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...oW,fontFamily:"var(--font-mono)",flex:1}}),(0,n.jsx)("input",{value:e.value,onChange:t=>o(e.id,{value:t.target.value}),placeholder:"value",style:{...oW,fontFamily:"var(--font-mono)",flex:1}}),(0,n.jsx)("button",{onClick:()=>{var t;return t=e.id,void l(r.filter(e=>e.id!==t))},style:d,children:"✕"})]},e.id)),(0,n.jsx)("button",{onClick:()=>a(e=>[...e,{id:s.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 oY({providerName:e,provider:t,model:r,onChange:a,onDelete:s}){let[l,o]=(0,i.useState)({phase:"idle"}),{t:d}=(0,R.s)(),[c,u]=(0,i.useState)({phase:"idle"}),p=(0,i.useRef)(0),h=(0,i.useRef)(null),f=(e,t)=>a({...r,[e]:t}),m=(()=>{if("idle"===l.phase)return null;if("testing"===l.phase)return d("i18n.testingModel");let e=[void 0!==l.latencyMs?`${l.latencyMs}ms`:null,void 0!==l.status?`HTTP ${l.status}`:null].filter(Boolean);return"success"===l.phase?[d("i18n.connected"),...e,l.responseText||null].filter(Boolean).join(" \xb7 "):[d("i18n.failed"),...e,l.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>{o({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,r.id,r.api]),(0,i.useEffect)(()=>{p.current+=1,u({phase:"idle"}),h.current=null},[e,t.baseUrl,r.id]);let g=(0,i.useCallback)(async()=>{if(r.id.trim()&&"testing"!==l.phase){o({phase:"testing"});try{let n=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:r})}),i=await n.json();if(!n.ok||!i.ok)return void o({phase:"error",message:i.error??`HTTP ${n.status}`,latencyMs:i.latencyMs,status:i.status});o({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(e){o({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[r,t,e,l.phase]),x=(0,i.useCallback)(async()=>{let n=r.id.trim();if(!n||"loading"===c.phase)return;let i=++p.current;u({phase:"loading"});try{let s=new URLSearchParams({q:n,provider:e,limit:"50"});t.baseUrl?.trim()&&s.set("baseUrl",t.baseUrl.trim());let l=await fetch(`/api/models-config/catalog?${s}`),o=await l.json();if(i!==p.current)return;if(!l.ok||o.error||!o.recommendation)return void u({phase:"error",message:o.error??`HTTP ${l.status}`});let d=function(e,t){let r={...e},n=0;if(!e.name?.trim()&&t.name&&(r.name=t.name,n+=1),void 0===e.reasoning&&!0===t.reasoning&&(r.reasoning=!0,n+=1),!e.input?.length&&t.input?.length&&(r.input=[...t.input],n+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(r.contextWindow=t.contextWindow,n+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(r.maxTokens=t.maxTokens,n+=1),t.cost){let i={...e.cost??{}},a=!1;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],a=!0,n+=1);a&&(r.cost=i)}return{model:r,appliedCount:n}}(r,o.recommendation.preset);d.appliedCount>0&&(h.current=r,a(d.model)),u({phase:"success",recommendation:o.recommendation,appliedCount:d.appliedCount})}catch(e){if(i!==p.current)return;u({phase:"error",message:e instanceof Error?e.message:String(e)})}},[c.phase,r,a,t.baseUrl,e]),v=(()=>{if("success"!==c.phase)return null;let{recommendation:t,appliedCount:r}=c,n=r>0?d("models.catalogFilled",{count:r}):d("models.catalogNoEmptyFields");if("unreliable"===t.price.status){let e="no-exact-match"===t.price.reason?d("models.catalogNoExactMatch"):d("models.catalogPriceUnreliable");return`${n} \xb7 ${e}`}let i="provider"===t.price.method?d("models.catalogPriceProvider",{provider:t.price.providerName??t.price.providerId??e}):"base-url"===t.price.method?d("models.catalogPriceBaseUrl",{provider:t.price.providerName??t.price.providerId??e}):d("models.catalogPriceConsensus",{support:t.price.support,total:t.price.total});return`${n} \xb7 ${i}`})(),b="error"===c.phase?c.message:v,y="error"===c.phase?"#ef4444":"success"===c.phase&&"unreliable"===c.recommendation.price.status?"#d97706":"var(--text-dim)";return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(oB,{children:d("i18n.model")}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[m&&(0,n.jsx)("span",{title:m,style:{maxWidth:260,height:24,padding:"0 8px",border:`1px solid ${"error"===l.phase?"#fecaca":"success"===l.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===l.phase?"#fee2e2":"success"===l.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:m}),(0,n.jsxs)("button",{onClick:g,disabled:!r.id.trim()||"testing"===l.phase,title:d("i18n.testConnection"),style:{height:24,padding:"0 8px",background:"success"===l.phase?"#16a34a":"none",border:`1px solid ${"success"===l.phase?"#16a34a":"var(--border)"}`,borderRadius:4,color:"success"===l.phase?"#fff":r.id.trim()&&"testing"!==l.phase?"var(--text-muted)":"var(--text-dim)",cursor:r.id.trim()&&"testing"!==l.phase?"pointer":"not-allowed",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",gap:5},children:["success"===l.phase&&(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===l.phase?d("i18n.checking"):"success"===l.phase?d("common.ok"):d("i18n.test")]}),(0,n.jsx)("button",{onClick:s,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:d("i18n.remove")})]})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,n.jsx)(oP,{label:"ID *",children:(0,n.jsx)(oF,{value:r.id,onChange:e=>f("id",e),placeholder:"model-id",mono:!0})}),(0,n.jsx)(oP,{label:"Name",children:(0,n.jsx)(oF,{value:r.name??"",onChange:e=>f("name",e||void 0),placeholder:"Display name"})})]}),(0,n.jsxs)("div",{style:{padding:"10px 0",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,n.jsx)("button",{onClick:()=>void x(),disabled:!r.id.trim()||"loading"===c.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:r.id.trim()&&"loading"!==c.phase?"var(--text-muted)":"var(--text-dim)",cursor:r.id.trim()&&"loading"!==c.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===c.phase?d("models.catalogFilling"):d("models.catalogFill")}),(0,n.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:d("models.catalogSource")})]}),(0,n.jsxs)("div",{"aria-live":"polite",style:{marginTop:6,height:20,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:y,fontSize:10},children:[(0,n.jsx)("span",{title:b??void 0,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b}),h.current&&(0,n.jsx)("button",{onClick:()=>{let e=h.current;e&&(h.current=null,a(e),u({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:d("models.catalogUndo")})]})]}),(0,n.jsx)(oP,{label:"API override",children:(0,n.jsx)(oH,{value:r.api??"",onChange:e=>f("api",e||void 0),options:oA})}),(0,n.jsxs)(oP,{label:"Headers",children:[(0,n.jsx)(oG,{headers:r.headers,onChange:e=>f("headers",e)}),(0,n.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,n.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,n.jsx)(oO,{label:"Reasoning / thinking",checked:r.reasoning??!1,onChange:e=>f("reasoning",e||void 0)}),(0,n.jsx)(oO,{label:"Image input",checked:r.input?.includes("image")??!1,onChange:e=>f("input",e?["text","image"]:void 0)})]}),r.reasoning&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oO,{label:"DeepSeek thinking compat",checked:r.compat?.thinkingFormat==="deepseek",onChange:e=>a(function(e,t){if(t)return{...e,compat:{...e.compat??{},...oJ}};if(!e.compat)return e;let r={...e.compat};return delete r.thinkingFormat,delete r.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(r).length?r:void 0}}(r,e))}),(0,n.jsx)(oO,{label:"Use 'developer' role for the system prompt (disable if server rejects it)",checked:!1!==({...t.compat??{},...r.compat??{}}).supportsDeveloperRole,onChange:e=>a({...r,compat:{...r.compat??{},supportsDeveloperRole:e}})}),(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,n.jsx)(oB,{children:"Thinking level map"}),r.thinkingLevelMap&&(0,n.jsx)("button",{onClick:()=>f("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,n.jsx)(oV,{value:r.thinkingLevelMap,onChange:e=>f("thinkingLevelMap",e)})]})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,n.jsx)(oP,{label:"Context window (tokens)",children:(0,n.jsx)(oD,{value:void 0!==r.contextWindow?String(r.contextWindow):"",onChange:e=>f("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,n.jsx)(oP,{label:"Max output tokens",children:(0,n.jsx)(oD,{value:void 0!==r.maxTokens?String(r.maxTokens):"",onChange:e=>f("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(oB,{children:"Cost (per million tokens)"}),(0,n.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8},children:["input","output","cacheRead","cacheWrite"].map(e=>(0,n.jsx)(oP,{label:e,children:(0,n.jsx)(oD,{value:r.cost?.[e]!==void 0?String(r.cost[e]):"",onChange:t=>{let n;return n=parseFloat(t),void a({...r,cost:{...r.cost??{},[e]:isNaN(n)?void 0:n}})},placeholder:"0"})},e))})]})]})}let oZ={checking:"relogin.checking",recovered:"relogin.recovered","still-failing":"relogin.stillFailing",unknown:"relogin.unknown"};function oX({provider:e,onRefresh:t,relogin:r}){let a=r?.onLoginSucceeded,[s,l]=(0,i.useState)({phase:"idle"}),{t:o}=(0,R.s)(),[d,c]=(0,i.useState)(""),u=(0,i.useRef)(null),p=(0,i.useRef)(!1),h=(0,i.useRef)(null),f=(0,i.useRef)(null),m=void 0!==r;(0,i.useEffect)(()=>{m&&f.current?.focus()},[m]),(0,i.useEffect)(()=>{("auth"===s.phase||"prompt"===s.phase)&&setTimeout(()=>h.current?.focus(),50)},[s.phase]),(0,i.useEffect)(()=>{l({phase:"idle"}),c(""),u.current?.close(),u.current=null},[e.id]),(0,i.useEffect)(()=>()=>{u.current?.close()},[]);let g=(0,i.useCallback)(()=>{u.current?.close(),p.current||(p.current=!0,c(""),l({phase:"success"}),t(),a?.())},[t,a]),x=(0,i.useCallback)(()=>{u.current?.close(),p.current=!1,l({phase:"connecting"}),c("");let t=new EventSource(`/api/auth/login/${encodeURIComponent(e.id)}`);u.current=t,t.onmessage=e=>{let r=JSON.parse(e.data);"auth"===r.type?(l({phase:"auth",url:r.url,instructions:r.instructions??null,token:r.token}),on(r.url)):"device_code"===r.type?(l({phase:"device_code",userCode:r.userCode,verificationUri:r.verificationUri,intervalSeconds:r.intervalSeconds??null,expiresInSeconds:r.expiresInSeconds??null}),on(r.verificationUri)):"prompt_request"===r.type?l({phase:"prompt",message:r.message,placeholder:r.placeholder??null,token:r.token}):"select_request"===r.type?l({phase:"select",message:r.message,options:r.options??[],token:r.token}):"progress"===r.type?l({phase:"progress",message:r.message}):"success"===r.type?g():"error"===r.type?(t.close(),l({phase:"error",message:r.message})):"cancelled"===r.type&&(t.close(),l({phase:"idle"}))},t.onerror=()=>{t.close(),l(e=>"success"===e.phase||"auth"===e.phase||"prompt"===e.phase||"select"===e.phase?e:{phase:"error",message:"Connection lost"})}},[e.id,g]),v=(0,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(e.id)}`,{method:"POST"}),l({phase:"idle"}),t()},[e.id,t]),b=(0,i.useCallback)(async(t,r,n)=>{l({phase:"progress",message:n});try{let n=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:r})}),i=await n.json().catch(()=>({}));if(!n.ok)return void l({phase:"error",message:i.error??`Server error ${n.status}`});if(c(""),"success"===i.state)return void g();u.current?.readyState===EventSource.CLOSED&&l({phase:"error",message:"Connection lost. Start the login again."})}catch(e){l({phase:"error",message:e instanceof Error?e.message:"Network error"})}},[e.id,g]),y=(0,i.useCallback)(async(e,t)=>{t.trim()&&await b(e,t.trim(),"Verifying…")},[b]),w=(0,i.useCallback)(async(e,t)=>{await b(e,t,"Continuing…")},[b]),k="connecting"===s.phase||"progress"===s.phase||"auth"===s.phase||"device_code"===s.phase||"prompt"===s.phase||"select"===s.phase;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(oB,{children:o("i18n.subscription")}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,n.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"#4ade80":"var(--text-dim)"},children:o(e.loggedIn?"i18n.connected":"i18n.notConnected")})]})]}),r&&(0,n.jsxs)("div",{role:"note","aria-label":o("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,n.jsx)(rh,{seed:r.target.seed,size:32,provider:r.target.provider}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0},children:[(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:o("relogin.title")}),(0,n.jsxs)("span",{style:{fontSize:13,fontWeight:600,color:"var(--text)",overflowWrap:"anywhere"},children:[r.target.alias,r.target.masked&&(0,n.jsx)("span",{style:{marginLeft:6,fontSize:11,fontWeight:400,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:r.target.masked})]}),r.target.reason&&(0,n.jsx)("span",{style:{fontSize:12,color:"var(--seed-color-fg-critical-contrast)",lineHeight:1.5,overflowWrap:"anywhere"},children:r.target.reason})]})]}),(0,n.jsxs)("div",{style:{minHeight:48},children:["idle"===s.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:r?o("relogin.guide",{action:o(e.loggedIn?"i18n.relogin":"i18n.login")}):e.loggedIn?"Already connected. You can re-login or disconnect.":`Connect your ${e.name} account.`}),"connecting"===s.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:o("i18n.openingBrowser")}),"select"===s.phase&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:s.message}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s.options.map(e=>(0,n.jsx)("button",{onClick:()=>w(s.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),("auth"===s.phase||"prompt"===s.phase)&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"auth"===s.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.":s.message}),"auth"===s.phase&&(0,n.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:["If the browser window did not open,"," ",(0,n.jsx)("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:"click here to open the login page"}),"."]}),(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsx)("input",{ref:h,value:d,onChange:e=>c(e.target.value),onKeyDown:e=>{"Enter"===e.key&&y(s.token,d)},placeholder:"auth"===s.phase?"Paste the redirect URL or code":s.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,n.jsx)("button",{onClick:()=>y(s.token,d),disabled:!d.trim(),style:{padding:"6px 12px",background:d.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:d.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:d.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,flexShrink:0},children:o("i18n.submit")})]})]}),"device_code"===s.phase&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,n.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:s.userCode}),(0,n.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,n.jsx)("a",{href:s.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:s.verificationUri}),s.expiresInSeconds?` Expires in ${Math.ceil(s.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===s.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:s.message}),"success"===s.phase&&(r?(0,n.jsxs)("div",{role:"status",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:o("relogin.done")}),r.outcome&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"recovered"===r.outcome?"var(--seed-color-fg-positive-contrast)":"still-failing"===r.outcome?"var(--seed-color-fg-critical-contrast)":"var(--text-muted)"},children:o(oZ[r.outcome],{account:r.target.alias})})]}):(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:o("i18n.connectedSuccessfully")})),"error"===s.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:s.message})]}),(0,n.jsx)("div",{style:{display:"flex",gap:8},children:k?(0,n.jsx)("button",{onClick:()=>{u.current?.close(),l({phase:"idle"})},style:{padding:"5px 12px",background:"none",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:o("i18n.cancel")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{ref:f,onClick:x,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:o(e.loggedIn?"i18n.relogin":"i18n.login")}),e.loggedIn&&!r&&(0,n.jsx)("button",{onClick:v,style:{padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:"pointer",fontSize:12},children:o("i18n.disconnect")})]})})]})}function oQ({provider:e,onRefresh:t}){let[r,a]=(0,i.useState)(""),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),{t:f}=(0,R.s)();(0,i.useEffect)(()=>{a(""),u(null),h(!1)},[e.id]);let m=(0,i.useCallback)(async()=>{if(r.trim()){l(!0),u(null),h(!1);try{let n=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:r.trim()})}),i=await n.json();!n.ok||i.error?u(i.error??`HTTP ${n.status}`):(a(""),h(!0),setTimeout(()=>h(!1),2e3),t())}catch(e){u(String(e))}finally{l(!1)}}},[r,e.id,t]),g=(0,i.useCallback)(async()=>{d(!0),u(null);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),n=await r.json();!r.ok||n.error?u(n.error??`HTTP ${r.status}`):t()}catch(e){u(String(e))}finally{d(!1)}},[e.id,t]);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(oB,{children:"API Key"}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,n.jsx)("span",{style:{fontSize:11,color:e.configured?"#4ade80":"var(--text-dim)"},children:f(e.configured?"i18n.configured":"i18n.notConfigured")})]})]}),(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.configured?"API key is stored. Enter a new key below to replace it, or disconnect to remove it.":`Enter your ${e.displayName} API key to enable ${e.modelCount} model${1!==e.modelCount?"s":""}.`}),(0,n.jsx)(oP,{label:"API Key",children:(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsx)(o_,{value:r,onChange:a,onKeyDown:e=>{"Enter"===e.key&&r.trim()&&m()},placeholder:e.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,n.jsxs)("button",{onClick:m,disabled:s||!r.trim()||p,style:{padding:"6px 12px",background:p?"#16a34a":r.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:p?"#fff":r.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:s||!r.trim()||p?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[p&&(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),f(p?"i18n.saved":s?"i18n.saving":"i18n.save")]})]})}),c&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:c}),e.configured&&(0,n.jsx)("button",{onClick:g,disabled:o,style:{alignSelf:"flex-start",padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:o?"not-allowed":"pointer",fontSize:12},children:f(o?"i18n.removing":"i18n.disconnect")})]})}function o0({id:e,size:t}){let r=oz[e];if(!r){let r=e.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,n.jsx)("span",{"aria-hidden":"true",style:{width:t,height:t,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*t)),fontWeight:700,lineHeight:1},children:r})}return r.hasColor?(0,n.jsx)(r.Icon,{size:t}):(0,n.jsx)(r.Icon,{size:t,style:{color:"var(--text-muted)"}})}function o1({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:r,onSelectApiKey:a,onAddCustom:s,onClose:l}){let[o,d]=(0,i.useState)(""),{t:c}=(0,R.s)(),u=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let p=o.trim().toLowerCase(),h=e.filter(e=>!e.loggedIn&&(!p||e.name.toLowerCase().includes(p))),f=t.filter(e=>!e.configured&&(!p||e.displayName.toLowerCase().includes(p)||e.id.toLowerCase().includes(p))),m=!p||"custom".includes(p)||"openai-compatible".includes(p)||"anthropic-compatible".includes(p),g=h.length+f.length+ +!!m,x={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,n.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&l()},children:(0,n.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,n.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,n.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,n.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,n.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,n.jsx)("input",{ref:u,value:o,onChange:e=>d(e.target.value),onKeyDown:e=>{"Escape"===e.key&&l()},placeholder:c("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===g?(0,n.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:c("i18n.noProviders")}):(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[m&&(0,n.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.custom")}),m&&(0,n.jsxs)("button",{onClick:()=>{s(),l()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:c("i18n.customEndpoint")})]}),(0,n.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,n.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,n.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,n.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),h.length>0&&(0,n.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!m,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.subscriptions")}),h.map(e=>(0,n.jsxs)("button",{onClick:()=>{r(e.id),l()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,n.jsx)(o0,{id:e.id,size:28})]},e.id)),f.length>0&&(0,n.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(h.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),f.map(e=>(0,n.jsxs)("button",{onClick:()=>{a(e.id),l()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,n.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[e.modelCount," models"]})]}),(0,n.jsx)(o0,{id:e.id,size:28})]},e.id))]})})]})})}function o2({cwd:e,onClose:t,embedded:r=!1,onModelsChanged:a,relogin:s}){let l=W(),{t:o}=(0,R.s)(),[d,c]=(0,i.useState)({providers:{}}),[u,p]=(0,i.useState)(!0),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(s?{type:"oauth",providerId:s.target.provider}:{type:"roles"}),[w,k]=(0,i.useState)([]),[j,S]=(0,i.useState)([]),[C,N]=(0,i.useState)(!1),I=(0,i.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>k(e.providers)).catch(()=>{})},[]),T=(0,i.useCallback)(()=>{fetch("/api/auth/all-providers").then(e=>e.json()).then(e=>S(e.providers)).catch(()=>{})},[]),M=(0,i.useCallback)(()=>{I(),T()},[I,T]);(0,i.useEffect)(()=>{fetch("/api/models-config").then(e=>e.json()).then(e=>{c(e.providers?e:{...e,providers:{}})}).catch(()=>c({providers:{}})).finally(()=>p(!1)),M()},[M]);let $=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;d.providers?.[e];)e=`new-provider-${t++}`;c(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),y({type:"provider",name:e})},[d.providers]),E=(0,i.useCallback)((e,t)=>{c(r=>({...r,providers:{...r.providers??{},[e]:t}}))},[]),L=(0,i.useCallback)((e,t)=>{c(r=>{let n=Object.entries(r.providers??{}),i=n.findIndex(([t])=>t===e);return -1===i?r:(n[i]=[t,n[i][1]],{...r,providers:Object.fromEntries(n)})}),y(r=>r?"provider"===r.type&&r.name===e?{type:"provider",name:t}:"model"===r.type&&r.providerName===e?{...r,providerName:t}:r:r)},[]),z=(0,i.useCallback)(e=>{c(t=>{let r={...t.providers??{}};return delete r[e],{...t,providers:r}}),c(e=>{let t=Object.keys(e.providers??{});return y(t.length>0?{type:"provider",name:t[0]}:null),e})},[]),A=(0,i.useCallback)(e=>{c(t=>{let r=t.providers?.[e]??{},n=[...r.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...r,models:n}}}}),c(t=>{let r=(t.providers?.[e]?.models?.length??1)-1;return y({type:"model",providerName:e,index:r}),t})},[]),P=(0,i.useCallback)((e,t)=>{c(r=>{let n=r.providers?.[e]??{},i=[...n.models??[]],a=new Set(i.map(e=>e.id));for(let e of t)a.has(e.id)||(a.add(e.id),i.push({id:e.id,name:e.name}));return{...r,providers:{...r.providers??{},[e]:{...n,models:i}}}})},[]),F=(0,i.useCallback)((e,t,r)=>{c(n=>{let i=n.providers?.[e]??{},a=[...i.models??[]];return a[t]=r,{...n,providers:{...n.providers??{},[e]:{...i,models:a}}}})},[]),_=(0,i.useCallback)((e,t)=>{c(r=>{let n=r.providers?.[e]??{},i=[...n.models??[]];return i.splice(t,1),{...r,providers:{...r.providers??{},[e]:{...n,models:i.length?i:void 0}}}}),y({type:"provider",name:e})},[]),D=(0,i.useCallback)(async()=>{f(!0),g(null),v(!1);try{let e=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}),t=await e.json();!e.ok||t.error?g(t.error??`HTTP ${e.status}`):(v(!0),a?.(),setTimeout(()=>v(!1),2e3))}catch(e){g(String(e))}finally{f(!1)}},[d,a]),H=Object.entries(d.providers??{}),O=w.filter(e=>e.loggedIn),B=j.filter(e=>e.configured),U=(()=>{if(!b)return null;if("roles"===b.type)return(0,n.jsx)(or,{cwd:e??null,onRolesChanged:a});if("oauth"===b.type){let e=w.find(e=>e.id===b.providerId);return e?(0,n.jsx)(oX,{provider:e,onRefresh:M,relogin:s?.target.provider===e.id?s:void 0},e.id):null}if("apikey"===b.type){let e=j.find(e=>e.id===b.providerId);return e?(0,n.jsx)(oQ,{provider:e,onRefresh:M},e.id):null}if("provider"===b.type){let e=d.providers?.[b.name];return e?(0,n.jsx)(oU,{name:b.name,provider:e,onChange:e=>E(b.name,e),onRename:e=>L(b.name,e),onDelete:()=>z(b.name),onAddModels:e=>P(b.name,e)},b.name):null}let t=d.providers?.[b.providerName],r=t?.models?.[b.index];return r?(0,n.jsx)(oY,{providerName:b.providerName,provider:t,model:r,onChange:e=>F(b.providerName,b.index,e),onDelete:()=>_(b.providerName,b.index)},`${b.providerName}-${b.index}`):null})();return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{style:{position:r?"relative":"fixed",inset:r?void 0:0,width:"100%",height:"100%",zIndex:r?void 0:1e3,background:r?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{r||e.target!==e.currentTarget||t()},...r?{}:{role:"dialog","aria-modal":!0,"aria-label":o("common.models"),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),t())}},children:(0,n.jsxs)("div",{style:{width:r?"100%":l?"calc(100vw - 16px)":860,maxWidth:r?"none":"calc(100vw - 16px)",height:r?"100%":l?"calc(100dvh - 16px)":"78vh",maxHeight:r?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:r?"none":"1px solid var(--border)",borderRadius:10*!r,display:"flex",flexDirection:"column",boxShadow:r?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:o("common.models")}),(0,n.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.omp/agent/models.yml"})]}),(0,n.jsx)("button",{onClick:t,"aria-label":o("i18n.close"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:l?"column":"row",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{width:l?"100%":210,maxHeight:l?"40vh":void 0,borderRight:l?"none":"1px solid var(--border)",borderBottom:l?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[(0,n.jsxs)("div",{onClick:()=>y({type:"roles"}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:b?.type==="roles"?"var(--bg-selected)":"none"},onMouseEnter:e=>{b?.type!=="roles"&&(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{b?.type!=="roles"&&(e.currentTarget.style.background="none")},children:[(0,n.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,n.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,n.jsx)("circle",{cx:"9",cy:"7",r:"2.2"}),(0,n.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,n.jsx)("circle",{cx:"15",cy:"17",r:"2.2"})]}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1},children:o("roles.title")})]}),(0,n.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),O.map(e=>{let t=b?.type==="oauth"&&b.providerId===e.id;return(0,n.jsxs)("div",{onClick:()=>y({type:"oauth",providerId:e.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,n.jsx)(o0,{id:e.id,size:16}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.id)}),B.map(e=>{let t=b?.type==="apikey"&&b.providerId===e.id;return(0,n.jsxs)("div",{onClick:()=>y({type:"apikey",providerId:e.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,n.jsx)(o0,{id:e.id,size:16}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName})]},e.id)}),(O.length>0||B.length>0)&&H.length>0&&(0,n.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),u?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:o("i18n.loading")}):H.map(([e,t])=>{let r=b?.type==="provider"&&b.name===e,i=t.models??[];return(0,n.jsxs)("div",{style:{marginBottom:2},children:[(0,n.jsxs)("div",{onClick:()=>y({type:"provider",name:e}),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:r?"var(--bg-selected)":"none"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[(0,n.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,n.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,n.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,n.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,n.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,n.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,n.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,n.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,n.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,n.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,n.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,n.jsx)("span",{style:{fontSize:12,fontWeight:r?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})]}),i.map((t,r)=>{let i=b?.type==="model"&&b.providerName===e&&b.index===r;return(0,n.jsxs)("div",{onClick:()=>y({type:"model",providerName:e,index:r}),style:{display:"flex",alignItems:"center",gap:6,padding:"5px 8px 5px 26px",borderRadius:5,cursor:"pointer",background:i?"var(--bg-selected)":"none"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[(0,n.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:t.id?"var(--text-muted)":"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.id||o("i18n.newModel")}),t.reasoning&&(0,n.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"})]},r)}),(0,n.jsx)("div",{onClick:t=>{t.stopPropagation(),A(e)},style:{display:"flex",alignItems:"center",gap:4,padding:"4px 8px 4px 26px",borderRadius:5,cursor:"pointer",color:"var(--text-dim)"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,n.jsxs)("span",{style:{fontSize:11},children:["+ ",o("i18n.model")]})})]},e)})]}),(0,n.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 6px"},children:(0,n.jsxs)("button",{onClick:()=>N(!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:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.color="var(--text-muted)"},children:["+ ",o("i18n.addProvider")]})})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:u?null:U??(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:o("i18n.selectProviderModel")})})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:10,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[m&&(0,n.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:m}),(0,n.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:o("i18n.cancel")}),(0,n.jsxs)("button",{onClick:D,disabled:h||x,style:{position:"relative",padding:"6px 16px",minWidth:92,background:x?"#16a34a":h?"var(--bg-panel)":"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:6,color:x?"#fff":h?"var(--text-muted)":"var(--seed-color-fg-neutral-inverted)",cursor:h||x?"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:x?"saved-pop 0.45s ease":void 0},children:[x&&(0,n.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,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,n.jsx)("span",{children:x?o("i18n.saved"):h?o("i18n.saving"):o("i18n.save")})]})]})]})}),C&&(0,n.jsx)(o1,{oauthProviders:w,apiKeyProviders:j,onSelectOAuth:e=>y({type:"oauth",providerId:e}),onSelectApiKey:e=>y({type:"apikey",providerId:e}),onAddCustom:$,onClose:()=>N(!1)})]})}function o4(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function o5(e){let t=e.sourceInfo?.source,r=e.sourceInfo?.scope;return"user"===r||"user"===t?"global":"project"===r||"project"===t?"project":"path"}function o8(e){let t=o5(e);return"path"===t?t:e.install?.skillsShUrl?`${t} / skills.sh`:t}function o6(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function o3(e){return e?e.slice(0,8):"unknown"}function o7({enabled:e,loading:t,onToggle:r}){let{t:i}=(0,R.s)();return(0,n.jsx)("button",{onClick:r,disabled:t,title:i(e?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),style:{flexShrink:0,width:40,height:22,borderRadius:11,border:"none",padding:0,cursor:t?"wait":"pointer",background:e?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none"},children:(0,n.jsx)("span",{style:{position:"absolute",top:3,left:e?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 o9({skill:e,cwd:t,onToggle:r,toggling:i,saveError:a,updateStatus:s,checkingUpdate:l,updating:o,updateError:d,onCheckUpdate:c,onUpdate:u}){let{t:p}=(0,R.s)(),h=o5(e),f=!e.disableModelInvocation;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7},children:[(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===h?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===h?"rgba(99,102,241,0.8)":"var(--text-dim)"},children:h}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:function(e){if("project"===h&&e.startsWith(t)){let r=e.slice(t.length).replace(/^[/\\]/,"");return`./${r}`}return o4(e)}(e.filePath)}),(0,n.jsx)(o7,{enabled:f,loading:i,onToggle:()=>r(e)})]}),(0,n.jsxs)("div",{style:{minHeight:16,display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,flexWrap:"wrap",textAlign:"right"},children:[!f&&(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:p("i18n.hiddenButInvocable")}),a&&(0,n.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:a})]})]}),e.install?.skillsShUrl&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Source"}),(0,n.jsx)("a",{href:e.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:e.install.skillsShUrl,style:{display:"flex",alignItems:"center",gap:8,width:"fit-content",maxWidth:"100%",color:"var(--accent)",textDecoration:"none"},children:(0,n.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})]}),e.install&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Version"}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text-muted)"},children:o3(s?.currentVersion??e.install.versionHash)}),e.install.canCheckForUpdates&&(0,n.jsx)("button",{onClick:c,disabled:l||o,style:{padding:"4px 9px",border:"1px solid var(--border)",borderRadius:5,background:"none",color:"var(--text-muted)",cursor:l||o?"not-allowed":"pointer",opacity:l||o?.5:1,fontSize:11},children:p("i18n.check")}),s?.state==="update-available"&&(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"#d97706"},children:o3(s.latestVersion)}),(l||s&&"update-available"!==s.state)&&(0,n.jsx)("span",{style:{fontSize:12,color:l?"var(--accent)":s?.state==="up-to-date"?"#16a34a":s?.state==="error"?"#ef4444":"var(--text-dim)"},children:l?p("i18n.checking"):s?.state==="up-to-date"?p("i18n.upToDate"):s?.state==="unsupported"?p("i18n.automaticChecksUnavailable"):s?.message||p("i18n.checkFailed")}),s?.state==="update-available"&&(0,n.jsx)("button",{onClick:u,disabled:o||l,style:{padding:"4px 10px",border:"none",borderRadius:5,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:o||l?"not-allowed":"pointer",opacity:o||l?.5:1,fontSize:11,fontWeight:600},children:p(o?"i18n.updating":"i18n.update")})]}),d&&(0,n.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:d})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Name"}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:14,color:"var(--text)"},children:e.name})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Description"}),(0,n.jsx)("span",{style:{fontSize:14,color:"var(--text-muted)",lineHeight:1.6},children:e.description})]})]})}function de({cwd:e,installedPackages:t,projectResourcesLoaded:r,onInstalled:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)(""),[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(new Set),[w,k]=(0,i.useState)("global"),j=(0,i.useRef)(null);(0,i.useEffect)(()=>{j.current?.focus()},[]);let S=(0,i.useCallback)(async e=>{if(e.trim()){p(!0),f(null),c([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),r=await t.json();if(r.error)return void f(r.error);c(r.results??[]),0===(r.results??[]).length&&f("No skills found")}catch(e){f(String(e))}finally{p(!1)}}},[]),C=(0,i.useCallback)(async t=>{g(t),v(null);try{let r=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:w,cwd:e})}),n=await r.json();if(!r.ok||n.error)return void v(n.error??`HTTP ${r.status}`);y(e=>new Set(e).add(`${w}:${t}`)),a()}catch(e){v(String(e))}finally{g(null)}},[a,w,e]),N="global"===w?"~/.claude/skills/":`${o4(e)}/.claude/skills/`;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,n.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:s("i18n.addSkill")}),(0,n.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,n.jsx)("input",{ref:j,value:l,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&S(l)},placeholder:s("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,n.jsx)("button",{onClick:()=>S(l),disabled:u||!l.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:u||!l.trim()?"not-allowed":"pointer",opacity:u||!l.trim()?.5:1,flexShrink:0},children:u?s("i18n.searching"):s("i18n.search")})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,n.jsx)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(e=>(0,n.jsx)("button",{onClick:()=>{("global"===e||r)&&k(e)},disabled:"project"===e&&!r,title:"project"!==e||r?void 0:s("trust.projectScopeUnavailable"),style:{padding:"3px 10px",border:"none",cursor:"project"!==e||r?"pointer":"not-allowed",background:w===e?"var(--bg-selected)":"none",color:w===e?"var(--text)":"var(--text-dim)",fontWeight:w===e?600:400,opacity:"project"!==e||r?1:.45,borderRight:"global"===e?"1px solid var(--border)":"none"},children:e},e))}),(0,n.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",N]})]}),h&&(0,n.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:h}),x&&(0,n.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:x})]}),d.length>0?(0,n.jsx)("div",{style:{flex:1,overflowY:"auto"},children:d.map(e=>{let r=t[w].has(e.package)||b.has(`${w}:${e.package}`),i=m===e.package,a=e.package.indexOf("@"),l=a>-1?e.package.slice(0,a):e.package,o=a>-1?e.package.slice(a+1):null;return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:o??l}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:l}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,n.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,n.jsx)("button",{onClick:()=>!r&&!i&&C(e.package),disabled:r||i||null!==m,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:5,border:"1px solid var(--border)",cursor:r||i||null!==m?"not-allowed":"pointer",background:r?"rgba(34,197,94,0.1)":"none",color:r?"#16a34a":i?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:r?`✓ ${s("i18n.installed")}`:i?s("i18n.installing"):s("i18n.install")})]},e.package)})}):!h&&!u&&(0,n.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:["Search"," ",(0,n.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 dt({cwd:e,onClose:t,embedded:r=!1}){let a=W(),{t:s}=(0,R.s)(),[l,o]=(0,i.useState)([]),[d,c]=(0,i.useState)(!0),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(new Set),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(!1),[w,k]=(0,i.useState)({}),[j,S]=(0,i.useState)(new Set),[C,N]=(0,i.useState)(!1),[I,T]=(0,i.useState)(null),[M,$]=(0,i.useState)(null),[E,L]=(0,i.useState)(!0),[z,A]=(0,i.useState)({}),P=(0,i.useCallback)(async()=>{c(!0),p(null);try{let t=await fetch(`/api/skills?cwd=${encodeURIComponent(e)}`),r=await t.json();if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);let n=r.skills??[];if(o(n),L(r.projectResourcesLoaded??!0),n.length>0&&!h){let e=n.find(e=>!e.disableModelInvocation)??n[0];f(e.filePath),e.disableModelInvocation&&A(t=>({...t,[o8(e)]:!0}))}return n}catch(e){return p(String(e)),[]}finally{c(!1)}},[e,h]);(0,i.useEffect)(()=>{k({}),$(null),P()},[e]);let F=(0,i.useCallback)(async t=>{let r=(t?[t]:l.filter(e=>!!e.install)).map(o6).filter(e=>!!e);if(0!==r.length){$(null),S(e=>new Set([...e,...r])),t||N(!0);try{let r=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t?.install?.package,scope:t?.install?.scope})}),n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);k(e=>{let t={...e};for(let e of n.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){$(e instanceof Error?e.message:String(e))}finally{S(e=>{let t=new Set(e);for(let e of r)t.delete(e);return t}),t||N(!1)}}},[e,l]),_=(0,i.useCallback)(async t=>{if(!t.install)return;let r=o6(t);T(r),$(null);try{let n=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t.install.package,scope:t.install.scope})}),i=await n.json();if(!n.ok||i.error||!i.success)throw Error(i.error??`HTTP ${n.status}`);await P();let a=i.skill?.install?.versionHash;k(e=>({...e,[r]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:a,latestVersion:a}}))}catch(e){$(e instanceof Error?e.message:String(e))}finally{T(null)}},[e,P]),D=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;g(t=>new Set(t).add(e.filePath)),v(null);try{let r=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),n=await r.json();if(!r.ok||n.error)return void v(n.error??`HTTP ${r.status}`);o(r=>r.map(r=>r.filePath===e.filePath?{...r,disableModelInvocation:t}:r)),t&&A(t=>({...t,[o8(e)]:!0}))}catch(e){v(String(e))}finally{g(t=>{let r=new Set(t);return r.delete(e.filePath),r})}},[]),H=l.find(e=>e.filePath===h)??null;return(0,n.jsx)("div",{style:{position:r?"relative":"fixed",inset:r?void 0:0,width:"100%",height:"100%",zIndex:r?void 0:1e3,background:r?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{r||e.target!==e.currentTarget||t()},children:(0,n.jsxs)("div",{style:{width:r?"100%":a?"calc(100vw - 16px)":860,maxWidth:r?"none":"calc(100vw - 16px)",height:r?"100%":a?"calc(100dvh - 16px)":"78vh",maxHeight:r?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:r?"none":"1px solid var(--border)",borderRadius:10*!r,display:"flex",flexDirection:"column",boxShadow:r?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:s("common.skills")}),(0,n.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o4(e)})]}),(0,n.jsx)("button",{onClick:t,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!E&&(0,n.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:s("trust.skillsNotLoaded")}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:a?"column":"row",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{width:a?"100%":210,maxHeight:a?"40vh":void 0,borderRight:a?"none":"1px solid var(--border)",borderBottom:a?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:d?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:s("i18n.loading")}):u?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#f87171"},children:u}):0===l.length?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:s("i18n.noSkills")}):(()=>{let e=[];for(let{label:t,matches:r}of[{label:"project / skills.sh",matches:e=>"project"===o5(e)&&!!e.install?.skillsShUrl},{label:"project",matches:e=>"project"===o5(e)&&!e.install?.skillsShUrl},{label:"global / skills.sh",matches:e=>"global"===o5(e)&&!!e.install?.skillsShUrl},{label:"global",matches:e=>"global"===o5(e)&&!e.install?.skillsShUrl},{label:"path",matches:e=>"path"===o5(e)}]){let n=l.filter(r);n.length>0&&e.push({label:t,skills:n})}let t=e=>{let t,r,i=!b&&h===e.filePath,a=e.disableModelInvocation;return(0,n.jsxs)("div",{onClick:()=>{f(e.filePath),y(!1)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:i?"var(--bg-selected)":"none"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[(0,n.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:a?"var(--border)":"var(--accent)",boxShadow:a?"none":"0 0 4px var(--accent)",transition:"background 0.15s, box-shadow 0.15s"}}),(0,n.jsx)("span",{style:{fontSize:12,fontWeight:i?600:400,color:a?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(r=(t=o6(e))?w[t]:void 0,r?.state!=="update-available"?null:(0,n.jsx)("span",{title:s("i18n.updateAvailable"),style:{color:"#d97706",fontSize:13,lineHeight:1,flexShrink:0},children:"↑"}))]},e.filePath)};return e.map(({label:e,skills:r})=>{let i=r.filter(e=>!e.disableModelInvocation),a=r.filter(e=>e.disableModelInvocation),l=z[e]??!1;return(0,n.jsxs)("div",{style:{marginBottom:6},children:[(0,n.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em"},children:e}),i.map(t),a.length>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{onClick:()=>A(t=>({...t,[e]:!l})),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,n.jsx)("span",{style:{fontSize:8},children:l?"▾":"▸"}),s("i18n.dormant")," (",a.length,")"]}),l&&a.map(t)]})]},e)})})()}),(0,n.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,n.jsxs)("div",{onClick:()=>y(!0),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:b?"var(--bg-selected)":"none",color:b?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:e=>{b||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{b||(e.currentTarget.style.background="none")},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,n.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s("i18n.addSkill")]})})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,n.jsx)(de,{cwd:e,projectResourcesLoaded:E,installedPackages:{global:new Set(l.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(l.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{P()}}):d?null:H?(0,n.jsx)(o9,{skill:H,cwd:e,onToggle:D,toggling:m.has(H.filePath),saveError:x,updateStatus:o6(H)?w[o6(H)]:void 0,checkingUpdate:!!o6(H)&&j.has(o6(H)),updating:I===o6(H),updateError:M,onCheckUpdate:()=>void F(H),onUpdate:()=>void _(H)},H.filePath):(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:s("i18n.selectSkill")})})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[l.some(e=>!!e.install)&&(0,n.jsx)("button",{onClick:()=>void F(),disabled:C||null!==I,style:{padding:"6px 12px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:C||null!==I?"not-allowed":"pointer",opacity:C||null!==I?.5:1,fontSize:12},children:C?s("i18n.checking"):s("i18n.checkUpdates")}),Object.values(w).filter(e=>"update-available"===e.state).length>0&&(0,n.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(w).filter(e=>"update-available"===e.state).length," ",1===Object.values(w).filter(e=>"update-available"===e.state).length?s("i18n.update"):s("i18n.updates")]})]}),(0,n.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:s("i18n.close")})]})]})})}let dr="global";function dn(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function di(e){let t=e.trim().match(/^\$?\s*omp\s+plugin\s+(?:add|install)\s+(\S+)\s*$/);return t?.[1]??e}function da(e){return`${e.scope}\0${e.source}`}function ds(e,t){if(e.disabled)return t("i18n.disabled");let r=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t("i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t("i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t("i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t("i18n.themeShort")}):""].filter(Boolean);return r.length?r.join(" \xb7 "):t("i18n.noResources")}function dl(e,t){let r=[];return e.version&&r.push(t("i18n.installedVersion",{version:e.version})),e.configuredVersion&&r.push(t("i18n.configuredVersion",{version:e.configuredVersion})),r.length?r.join(" \xb7 "):t("i18n.unknown")}function dd(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function dc({pkg:e}){let{t}=(0,R.s)(),r=[["extension",t("i18n.extensions")],["skill",t("i18n.skills")],["prompt",t("i18n.prompts")],["theme",t("i18n.themes")]].map(([t,r])=>({kind:t,label:r,resources:e.resources.filter(e=>e.kind===t)})).filter(e=>e.resources.length>0);return 0===r.length?(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:t(e.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:r.map((e,t)=>(0,n.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,n.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function du({scope:e}){return(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===e?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===e?"rgba(99,102,241,0.85)":"var(--text-dim)"},children:e})}function dp(e,t){return{padding:"6px 12px",background:t?"rgba(239,68,68,0.08)":"none",border:"1px solid var(--border)",borderRadius:6,color:t?"#ef4444":"var(--text-muted)",cursor:e?"not-allowed":"pointer",fontSize:12,opacity:e?.5:1}}function dh({enabled:e,loading:t,onToggle:r,label:i}){return(0,n.jsx)("button",{type:"button",onClick:r,disabled:t,title:i,"aria-label":i,"aria-pressed":e,style:{flexShrink:0,width:40,height:22,borderRadius:11,border:"none",padding:0,cursor:t?"wait":"pointer",background:e?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none",opacity:t?.65:1},children:(0,n.jsx)("span",{style:{position:"absolute",top:3,left:e?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 df({installDir:e,source:t,busy:r,actionError:a,onSourceChange:s,onInstall:l}){let{t:o}=(0,R.s)(),d=(0,i.useRef)(null);return(0,i.useEffect)(()=>{d.current?.focus()},[]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:660,minHeight:"100%"},children:[(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,n.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:o("i18n.addPlugin")}),(0,n.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,n.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",style:{flexShrink:0},children:[(0,n.jsx)("path",{fill:"#000",fillRule:"evenodd",d:"M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"}),(0,n.jsx)("path",{fill:"#000",d:"M517.36 400H634.72V634.72H517.36Z"})]}),"oh-my-pi plugins"]})]}),e&&(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:dn(e)})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,n.jsx)("label",{htmlFor:"plugin-source",style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Source"}),(0,n.jsx)("input",{id:"plugin-source",ref:d,value:t,onChange:e=>s(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),r=di(t);r!==t&&(e.preventDefault(),s(r))},onBlur:e=>s(di(e.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:e=>{"Enter"===e.key&&t.trim()&&!r&&l()}})]}),(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:(0,n.jsx)("button",{type:"button",onClick:l,disabled:r||!t.trim(),style:{...dp(r||!t.trim()),background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",borderColor:"transparent"},children:o(r?"i18n.installing":"i18n.install")})}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Examples"}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:["@scope/omp-plugin","github:user/repo","pkg[feature]"].map(e=>(0,n.jsx)("button",{type:"button",onClick:()=>s(e),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:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-panel)",e.currentTarget.style.color="var(--text-dim)"},children:e},e))})]}),a&&(0,n.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:a})]})}function dm({pkg:e,cwd:t,busyKey:r,actionError:i,actionMessage:a,sessionId:s,onAction:l,onReloadSession:o}){let{t:d}=(0,R.s)(),c=da(e),u=r?.endsWith(c)??!1,p="reload"===r,h=!e.disabled;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20,maxWidth:680},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,minWidth:0,flexWrap:"wrap"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:180,flex:1},children:[(0,n.jsx)(dh,{enabled:h,loading:u||p,onToggle:()=>l(e.disabled?"enable":"disable",e),label:d(e.disabled?"i18n.enablePackage":"i18n.disablePackage")}),(0,n.jsx)(du,{scope:e.scope}),e.disabled?(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:d("i18n.disabled")}):e.filtered&&(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:d("i18n.filtered")}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source})]}),(0,n.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[(0,n.jsx)("button",{onClick:()=>l("update",e),disabled:u||p,style:dp(u||p),children:d(r===`update:${c}`?"i18n.updating":"i18n.update")}),(0,n.jsx)("button",{onClick:o,disabled:!s||p||u,style:dp(!s||p||u),title:d(s?"i18n.reloadSessionHint":"i18n.openSessionToReload"),children:d(p?"i18n.reloading":"i18n.reloadSession")}),(0,n.jsx)("button",{onClick:()=>l("remove",e),disabled:u||p,style:dp(u||p,!0),children:d(r===`remove:${c}`?"i18n.removing":"i18n.remove")})]})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.status")}),(0,n.jsx)("div",{style:{color:dd(e.status),textTransform:"capitalize"},children:e.status}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.version")}),(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:dl(e,d)}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.package")}),(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.packageName??d("i18n.unknown")}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.resources")}),(0,n.jsx)("div",{style:{color:"var(--text-muted)"},children:ds(e,d)}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.installedPath")}),(0,n.jsx)("div",{style:{color:e.installedPath?"var(--text-muted)":"#ef4444",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.installedPath?dn(e.installedPath):d("i18n.notFound")}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.cwd")}),(0,n.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:dn(t)})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)"},children:d("i18n.resolvedResources")}),(0,n.jsx)(dc,{pkg:e})]}),a&&(0,n.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:a}),i&&(0,n.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:i})]})}function dg({cwd:e,sessionId:t,onClose:r,onReloaded:a,embedded:s=!1}){let l=W(),{t:o}=(0,R.s)(),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!0),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(""),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),I=(0,i.useMemo)(()=>d?.packages??[],[d?.packages]),T=I.find(e=>da(e)===m)??null,M=d?.projectResourcesLoaded??!0,$=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:I.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[I]),E=(0,i.useCallback)(async()=>{p(!0),f(null);try{let t=await fetch(`/api/plugins?cwd=${encodeURIComponent(e)}`),r=await t.json();if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);c(r),v(e=>0===r.packages.length||e),g(e=>e&&r.packages.some(t=>da(t)===e)?e:r.packages[0]?da(r.packages[0]):null)}catch(e){f(e instanceof Error?e.message:String(e))}finally{p(!1)}},[e]);(0,i.useEffect)(()=>{E()},[E]);let L=(0,i.useCallback)(async(t,r)=>{let n=da(r);k(`${t}:${n}`),S(null),N(null);try{let n=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:r.source,scope:r.scope,cwd:e})}),i=await n.json();if(!n.ok||i.error)throw Error(i.error??`HTTP ${n.status}`);if(c(i),"remove"===t)g(i.packages[0]?da(i.packages[0]):null),0===i.packages.length&&v(!0),N(o("i18n.packageRemoved"));else{let e={install:o("i18n.packageInstalled"),update:o("i18n.packageUpdated"),disable:o("i18n.packageDisabledRestartRequired"),enable:o("i18n.packageEnabled")};N(e[t])}}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}},[e,o]),z=(0,i.useCallback)(async()=>{let t=di(b).trim();if(!t)return;y(t);let r=`${dr}\0${t}`;k(`install:${r}`),S(null),N(null);try{var n;let i,a,s=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:dr,cwd:e})}),l=await s.json();if(!s.ok||l.error)throw Error(l.error??`HTTP ${s.status}`);c(l);let d=(n=l.packages,a=(i=t.trim()).startsWith("npm:")?i.slice(4):i,n.find(e=>e.scope===dr&&e.source===i)??n.find(e=>e.scope===dr&&e.source===`npm:${a}`)??n.find(e=>e.scope===dr&&e.source.endsWith(i)));g(d?da(d):r),v(!1),y(""),N(o("i18n.packageInstalled"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}},[e,b,o]),A=(0,i.useCallback)(async()=>{if(t){k("reload"),S(null),N(null);try{await sz(t,{type:"reload"}),a?.(),await E(),N(o("i18n.sessionReloaded"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}}},[E,a,t,o]),P=w?.startsWith("install:")??!1;return(0,n.jsx)("div",{style:{position:s?"relative":"fixed",inset:s?void 0:0,width:"100%",height:"100%",zIndex:s?void 0:1e3,background:s?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{s||e.target!==e.currentTarget||r()},children:(0,n.jsxs)("div",{style:{width:s?"100%":l?"calc(100vw - 16px)":860,maxWidth:s?"none":"calc(100vw - 16px)",height:s?"100%":l?"calc(100dvh - 16px)":"76vh",maxHeight:s?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:s?"none":"1px solid var(--border)",borderRadius:8*!s,display:"flex",flexDirection:"column",boxShadow:s?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:o("common.plugins")}),(0,n.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:dn(e)})]}),(0,n.jsx)("button",{onClick:r,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!M&&(0,n.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:o("trust.pluginsNotLoaded")}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:l?"column":"row",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{width:l?"100%":245,maxHeight:l?"40vh":void 0,borderRight:l?"none":"1px solid var(--border)",borderBottom:l?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:u?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:"Loading..."}):h?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#ef4444"},children:h}):0===I.length?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:"No plugins configured"}):$.map(e=>(0,n.jsxs)("div",{style:{marginBottom:6},children:[(0,n.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase"},children:e.scope}),e.packages.map(e=>{let t=da(e),r=!x&&m===t;return(0,n.jsxs)("div",{onClick:()=>{g(t),v(!1),S(null),N(null)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:r?"var(--bg-selected)":"none"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[(0,n.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:dd(e.status)}}),(0,n.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:r?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:ds(e,o)}),(e.version||e.configuredVersion)&&(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:dl(e,o)})]})]},t)})]},e.scope))}),(0,n.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,n.jsxs)("button",{type:"button",onClick:()=>{v(!0),S(null),N(null)},style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,border:"none",width:"100%",cursor:"pointer",background:x?"var(--bg-selected)":"none",color:x?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:e=>{x||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{x||(e.currentTarget.style.background="none")},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,n.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),o("i18n.addPlugin")]})})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:x?(0,n.jsx)(df,{installDir:d?.installDir,source:b,busy:P,actionError:j,onSourceChange:y,onInstall:z}):u?null:T?(0,n.jsx)(dm,{pkg:T,cwd:e,busyKey:w,actionError:j,actionMessage:C,sessionId:t,onAction:L,onReloadSession:A},da(T)):(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:o("i18n.selectPackage")})})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsx)("div",{style:{minWidth:0,flex:1,fontSize:11,color:"var(--text-dim)",overflow:"hidden"},children:d?.diagnostics.length?(0,n.jsxs)("span",{title:d.diagnostics.map(e=>`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`).join("\n"),style:{color:d.diagnostics.some(e=>"error"===e.type)?"#ef4444":"#d97706"},children:[d.diagnostics.length," diagnostic",1===d.diagnostics.length?"":"s"]}):(0,n.jsx)("span",{children:d?`${d.totals.extensions} ext \xb7 ${d.totals.skills} skills \xb7 ${d.totals.prompts} prompts \xb7 ${d.totals.themes} themes`:""})}),(0,n.jsx)("button",{onClick:()=>void E(),disabled:u||null!==w,style:dp(u||null!==w),children:o("i18n.refresh")}),(0,n.jsx)("button",{onClick:r,style:dp(!1),children:o("i18n.close")})]})]})})}var dx=r(13004),dv=r.n(dx);function db(){let[e,t]=(0,i.useState)(null),[r,a]=(0,i.useState)(null),[s,l]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(""),[f,m]=(0,i.useState)(""),g=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/web-access",{cache:"no-store"}),r=await e.json();if(!e.ok||r.error)throw Error(r.error??`HTTP ${e.status}`);t(r),a(null)}catch(e){a(e instanceof Error?e.message:String(e))}},[]);(0,i.useEffect)(()=>{g()},[g]);let x=(0,i.useCallback)(async(e,r={})=>{u(!0),l(null),d(null);try{let n=await fetch("/api/web-access",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,...r})}),i=await n.json();if(!n.ok||i.error)throw Error(i.error??`HTTP ${n.status}`);return t(i),i}catch(e){return l(e instanceof Error?e.message:String(e)),null}finally{u(!1)}},[]),v=(0,i.useCallback)(async()=>{if(p!==f)return void l("The two passwords do not match.");let e=await x("set-password",{password:p});e&&(h(""),m(""),d(`Password saved and password access turned on. The browser will ask for the username "${e.username}" and this password on the next request.`))},[f,p,x]),b=(0,i.useCallback)(async()=>{if(!e)return;let t=await x(e.enabled?"disable":"enable");t&&d(t.enabled?`Password access is on. The browser will ask for the username "${t.username}" and your password on the next request.`:"Password access is off. The stored password is kept and can be switched back on here.")},[x,e]),y=(0,i.useCallback)(async()=>{await x("clear")&&d("The stored password was removed and password access is off.")},[x]);if(!e)return(0,n.jsx)("div",{className:dv().empty,children:r??"Loading password access…"});let w=e.managedByEnvironment,k=!c&&!w&&p.length>=8&&p===f;return(0,n.jsxs)("div",{className:dv().scrollContent,children:[(0,n.jsxs)("header",{className:dv().contentHeader,children:[(0,n.jsx)("h2",{className:dv().contentTitle,children:"Access"}),(0,n.jsxs)("p",{className:dv().contentDescription,children:["A password locks the web interface and every API endpoint behind HTTP Basic Auth, with the fixed username ",(0,n.jsx)("code",{children:e.username}),". It is stored as a scrypt hash in ",(0,n.jsx)("code",{children:e.file})," — CUELO never keeps the password itself, which is why forgetting it means recovering rather than reading it back."]}),w&&(0,n.jsxs)("div",{className:dv().readOnlyNotice,children:["Read-only \xb7 ",(0,n.jsx)("code",{children:"CUELO_PASSWORD"})," is set and overrides the stored credential. Unset it and restart CUELO to manage the password here."]}),o&&(0,n.jsx)("div",{className:dv().reloadNotice,children:(0,n.jsx)("span",{children:o})})]}),(0,n.jsxs)("div",{className:dv().settingsBody,children:[(0,n.jsxs)("section",{className:dv().group,children:[(0,n.jsx)("h3",{className:dv().groupTitle,children:"Password access"}),(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:dv().settingLabel,children:"Require a password"}),(0,n.jsx)("div",{className:dv().settingDescription,children:e.managedByEnvironment?"Every request needs the password from CUELO_PASSWORD.":e.unreadable?"The credential file exists but could not be read, so every request is being refused.":e.configured?e.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."}),!e.configured&&!w&&(0,n.jsx)("div",{className:dv().settingDescription,children:"Set a password below before turning this on."}),s&&(0,n.jsx)("div",{className:dv().error,children:s})]}),(0,n.jsx)("div",{className:dv().settingControl,children:(0,n.jsx)("button",{type:"button",className:dv().switch,"data-on":e.enabled,"aria-pressed":e.enabled,"aria-label":"Require a password",disabled:c||w||!e.enabled&&!e.stored,onClick:()=>void b()})})]})]}),(0,n.jsxs)("section",{className:dv().group,children:[(0,n.jsx)("h3",{className:dv().groupTitle,children:e.stored?"Replace the password":"Set a password"}),(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:dv().settingLabel,children:"New password"}),(0,n.jsxs)("div",{className:dv().settingDescription,children:["At least ",8," characters. Saving a password also turns password access on."]})]}),(0,n.jsx)("div",{className:dv().settingControl,children:(0,n.jsx)("input",{className:dv().textInput,type:"password",autoComplete:"new-password",value:p,disabled:c||w,onChange:e=>h(e.target.value)})})]}),(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:dv().settingLabel,children:"Confirm password"}),(0,n.jsx)("div",{className:dv().settingDescription,children:"Both entries have to match before it can be saved."})]}),(0,n.jsx)("div",{className:dv().settingControl,children:(0,n.jsx)("input",{className:dv().textInput,type:"password",autoComplete:"new-password",value:f,disabled:c||w,onChange:e=>m(e.target.value),onKeyDown:e=>{"Enter"===e.key&&k&&v()}})})]}),(0,n.jsxs)("div",{className:dv().editorActions,children:[(0,n.jsx)("div",{children:(0,n.jsx)("div",{className:dv().saveState,children:e.stored&&e.updatedAt?`Last changed ${new Date(e.updatedAt).toLocaleString()}`:"No password stored yet"})}),(0,n.jsxs)("div",{style:{display:"flex",gap:8},children:[e.stored&&!w&&(0,n.jsx)("button",{type:"button",className:dv().dangerButton,disabled:c,onClick:()=>void y(),children:"Remove password"}),(0,n.jsx)("button",{type:"button",className:dv().primaryButton,disabled:!k,onClick:()=>void v(),children:c?"Saving…":"Save password"})]})]})]}),(0,n.jsxs)("section",{className:dv().group,children:[(0,n.jsx)("h3",{className:dv().groupTitle,children:"If you forget it"}),(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:dv().settingLabel,children:"Recovery"}),(0,n.jsxs)("div",{className:dv().settingDescription,children:["Run ",(0,n.jsx)("code",{children:"cuelo --reset-password"})," on this machine to set a new one, or open ",(0,n.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,n.jsx)("div",{className:dv().settingControl,children:(0,n.jsx)("a",{className:dv().linkButton,href:"/recover",target:"_blank",rel:"noreferrer",children:"Open /recover"})})]}),(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:dv().settingLabel,children:"Basic Auth is not encryption"}),(0,n.jsx)("div",{className:dv().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,n.jsx)("div",{className:dv().settingControl})]})]})]})]})}function dy(){let{t:e}=(0,R.s)(),[t,r]=(0,i.useState)(null),[a,s]=(0,i.useState)(!1),[l,o]=(0,i.useState)(null),d=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/live/voices",{cache:"no-store"}),t=await e.json().catch(()=>({}));if(!e.ok||!Array.isArray(t.voices)||"string"!=typeof t.defaultVoice)throw Error(`HTTP ${e.status}`);r({voices:t.voices,defaultVoice:t.defaultVoice})}catch(e){o(e instanceof Error?e.message:String(e))}},[]);(0,i.useEffect)(()=>{d()},[d]);let c=async e=>{s(!0),o(null);try{let t=await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:"live.voice",value:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);let i="string"==typeof n.value?n.value:e;r(e=>e?{...e,defaultVoice:i}:e)}catch(e){o(e instanceof Error?e.message:String(e))}finally{s(!1)}};return t?(0,n.jsxs)("div",{className:dv().scrollContent,children:[(0,n.jsxs)("header",{className:dv().contentHeader,children:[(0,n.jsx)("h2",{className:dv().contentTitle,children:e("chat.liveVoiceSettingsTitle")}),(0,n.jsx)("p",{className:dv().contentDescription,children:e("chat.liveVoiceSettingsDescription")})]}),(0,n.jsx)("div",{className:dv().settingsBody,children:(0,n.jsxs)("section",{className:dv().group,children:[(0,n.jsx)("h3",{className:dv().groupTitle,children:e("chat.liveVoiceSpeakerGroup")}),(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{className:dv().settingLabel,children:e("chat.liveVoiceCodexLabel")}),(0,n.jsx)("div",{className:dv().settingDescription,children:e("chat.liveVoiceCodexHelp")}),l&&(0,n.jsx)("div",{className:dv().error,role:"alert",style:{overflowWrap:"anywhere"},children:l})]}),(0,n.jsx)("div",{className:dv().settingControl,children:(0,n.jsx)(l7,{value:t.defaultVoice,disabled:a,ariaLabel:e("chat.liveVoiceCodexLabel"),options:t.voices,onChange:e=>{e!==t.defaultVoice&&c(e)}})})]})]})})]}):(0,n.jsx)("div",{className:dv().empty,children:l?`${e("chat.liveVoiceLoadFailed")}: ${l}`:"…"})}function dw(){let{t:e}=(0,R.s)(),t=(0,i.useId)(),r=(0,i.useId)(),[a,s]=(0,i.useState)(null),[l,o]=(0,i.useState)(""),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=new AbortController;return aB({signal:e.signal}).then(e=>{s(e),o(String(e.uploadLimitMb))}).catch(t=>{e.signal.aborted||c(t instanceof Error?t.message:String(t))}),()=>e.abort()},[]);let m=(0,i.useCallback)(async e=>{p(!0),c(null),f(!1);try{let t=await aU(e);s(t),o(String(t.uploadLimitMb)),f(!0)}catch(e){c(e instanceof Error?e.message:String(e))}finally{p(!1)}},[]);return a?(0,n.jsxs)("div",{className:dv().scrollContent,children:[(0,n.jsxs)("header",{className:dv().contentHeader,children:[(0,n.jsx)("h2",{className:dv().contentTitle,children:e("chat.attachmentSettingsTitle")}),(0,n.jsx)("p",{className:dv().contentDescription,children:e("chat.attachmentSettingsDescription")})]}),(0,n.jsx)("div",{className:dv().settingsBody,children:(0,n.jsxs)("section",{className:dv().group,children:[(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{htmlFor:t,className:dv().settingLabel,style:{display:"block"},children:e("chat.attachmentUploadLimit")}),(0,n.jsx)("div",{className:dv().settingDescription,children:e("chat.attachmentUploadLimitHelp")})]}),(0,n.jsx)("div",{className:dv().settingControl,children:(0,n.jsx)("input",{id:t,className:dv().numberInput,type:"number",inputMode:"numeric",min:1,step:1,value:l,disabled:u,onChange:e=>o(e.target.value),onBlur:()=>{let t=l.trim();if(t===String(a.uploadLimitMb))return;let r=Number(t);if(!/^\d+$/.test(t)||!Number.isSafeInteger(r)||r<1){f(!1),c(e("chat.attachmentUploadLimitInvalid"));return}m({uploadLimitMb:r})},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})})]}),(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{id:r,className:dv().settingLabel,children:e("chat.attachmentAutoCleanup")}),(0,n.jsx)("div",{className:dv().settingDescription,children:e("chat.attachmentAutoCleanupHelp",{days:a.orphanGraceDays})})]}),(0,n.jsx)("div",{className:dv().settingControl,children:(0,n.jsx)("button",{type:"button",className:dv().switch,"data-on":a.autoCleanupEnabled,"aria-pressed":a.autoCleanupEnabled,"aria-labelledby":r,disabled:u,onClick:()=>void m({autoCleanupEnabled:!a.autoCleanupEnabled})})})]}),d&&(0,n.jsx)("div",{className:dv().error,role:"alert",style:{overflowWrap:"anywhere"},children:d}),h&&!d&&(0,n.jsx)("div",{className:dv().saveState,role:"status",children:e("chat.attachmentSettingsSaved")})]})})]}):(0,n.jsx)("div",{className:dv().empty,children:d?`${e("chat.attachmentSettingsLoadFailed")}: ${d}`:"…"})}function dk({cwd:e}){let{t}=(0,R.s)(),[r,a]=(0,i.useState)(null),[s,l]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)({}),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(new Map);(0,i.useEffect)(()=>{g&&c!==g&&(v.current.get(g)?.querySelector("button:not(:disabled)")?.focus(),x(null))},[c,r,g]);let b=(0,i.useRef)(0),y=(0,i.useRef)(null),w=(0,i.useRef)(null),k=(0,i.useRef)(!1),j=(0,i.useCallback)(async()=>{if(k.current||"visible"!==document.visibilityState)return;let r=++b.current;y.current?.abort();let n=new AbortController;y.current=n;try{let i=e?`?include=${encodeURIComponent(e)}`:"",s=await fetch(`/api/project-trust${i}`,{cache:"no-store",signal:n.signal}),o=await s.json();if(r!==b.current||n.signal.aborted)return;if(!s.ok||!o.projects)throw Error(o.error??`HTTP ${s.status}`);let d=o.projects.find(e=>null===e.pending&&!e.error&&w.current?.some(t=>t.cwd===e.cwd&&("grant"===t.pending?e.trusted:"revoke"===t.pending&&!e.trusted)));w.current=o.projects,a(o.projects),l(null),d&&m({cwd:d.cwd,text:t("trust.doneApplied")})}catch(e){if(r!==b.current||n.signal.aborted)return;l(e instanceof Error?e.message:String(e))}finally{y.current===n&&(y.current=null)}},[e,t]);(0,i.useEffect)(()=>(j(),()=>{y.current?.abort()}),[j]);let S=r?.some(e=>null!==e.pending)??!1;(0,i.useEffect)(()=>{let e;if(!S||null!==c||null!==o)return;let t=()=>{window.clearTimeout(e),e="visible"===document.visibilityState?window.setTimeout(()=>void j(),2500):void 0},r=()=>{"visible"===document.visibilityState?j():(t(),++b.current,y.current?.abort())};return t(),document.addEventListener("visibilitychange",r),()=>{window.clearTimeout(e),document.removeEventListener("visibilitychange",r)}},[c,o,r,S,j]);let C=(0,i.useCallback)(async(e,r)=>{if(!k.current){k.current=!0,++b.current,y.current?.abort(),u(e),d(null),x(e),m(null),h(t=>{let r={...t};return delete r[e],r});try{let n=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,action:r})}),i=await n.json();if(!n.ok)throw Error(i.error??`HTTP ${n.status}`);let s=w.current?.map(t=>t.cwd===e?{...i,cwd:e}:t)??null;w.current=s,a(s),"cancel"===r?m({cwd:e,text:t("trust.doneCancelled")}):i.error||null!==i.pending||m({cwd:e,text:t("trust.doneApplied")})}catch(t){h(r=>({...r,[e]:t instanceof Error?t.message:String(t)}))}finally{k.current=!1,u(null)}}},[t]);if(!r)return(0,n.jsxs)("div",{className:dv().empty,children:[s?t("trust.loadFailed",{error:s}):"…",s&&(0,n.jsx)("button",{type:"button",className:dv().linkButton,onClick:()=>void j(),children:t("trust.refresh")})]});let N=null!==c;return(0,n.jsxs)("div",{className:dv().scrollContent,children:[(0,n.jsxs)("header",{className:dv().contentHeader,children:[(0,n.jsx)("h2",{className:dv().contentTitle,children:t("trust.settingsNav")}),(0,n.jsx)("p",{className:dv().contentDescription,children:t("trust.settingsDescription")}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,marginTop:12},children:[(0,n.jsx)("button",{type:"button",className:dv().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void j(),children:t("trust.refresh")}),s&&(0,n.jsx)("div",{className:dv().error,role:"alert",children:t("trust.loadFailed",{error:s})})]})]}),(0,n.jsx)("div",{className:dv().settingsBody,children:(0,n.jsxs)("section",{className:dv().group,children:[0===r.length&&(0,n.jsx)("div",{className:dv().settingDescription,children:t("trust.settingsEmpty")}),r.map(e=>{var r;let i=c===e.cwd,a=o?.cwd===e.cwd?o:null,s=e.requiresTrust?e.trusted?t("trust.stateTrusted"):t("trust.stateRestricted"):t("trust.stateNotRequired"),l=p[e.cwd]??(e.error?t("trust.applyFailed",{error:e.error}):null);return(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsxs)("div",{className:dv().settingLabel,style:{display:"flex",alignItems:"center",gap:7},children:[(0,n.jsx)("span",{className:dv().statusDot,"data-off":!e.trusted||!e.requiresTrust,"aria-hidden":"true"}),(0,n.jsx)("span",{children:(r=e.cwd).split(/[\\/]/).filter(Boolean).pop()??r}),(0,n.jsx)("span",{className:dv().settingDescription,style:{fontWeight:600},children:s})]}),(0,n.jsx)("code",{className:dv().settingDescription,style:{display:"block",overflowWrap:"anywhere"},children:e.cwd}),(0,n.jsx)("div",{className:dv().saveState,children:t("trust.runtime",{sessions:e.runtime.sessions,running:e.runtime.running,loaded:e.requiresTrust?e.runtime.projectCodeLoaded:0})}),(0,n.jsxs)("div",{"aria-live":"polite",children:["grant"===e.pending&&(0,n.jsx)("div",{className:dv().settingDescription,children:t("trust.pendingGrant")}),"revoke"===e.pending&&(0,n.jsx)("div",{className:dv().settingDescription,children:t("trust.pendingRevoke",{count:e.runtime.projectCodeLoaded})}),a&&(0,n.jsx)("div",{className:dv().settingDescription,style:{color:"var(--text)"},children:"revoke"===a.action?t("trust.confirmRevoke"):a.again?t("trust.confirmTrustAgain"):t("trust.confirmGrant")}),f?.cwd===e.cwd&&(0,n.jsx)("div",{className:dv().saveState,children:f.text})]}),l&&(0,n.jsx)("div",{className:dv().error,role:"alert",children:l})]}),(0,n.jsx)("div",{ref:t=>{t?v.current.set(e.cwd,t):v.current.delete(e.cwd)},className:dv().settingControl,style:{flexWrap:"wrap",gap:8,alignItems:"flex-start"},children:a?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:dv().linkButton,style:{background:"transparent",cursor:"pointer"},autoFocus:!0,onClick:()=>{d(null),x(e.cwd)},children:t("trust.cancel")}),(0,n.jsx)("button",{type:"button",className:"revoke"===a.action?dv().dangerButton:dv().primaryButton,disabled:N,onClick:()=>void C(e.cwd,a.action),children:"revoke"===a.action?t("trust.revoke"):t("trust.confirm")})]}):i?(0,n.jsx)("button",{type:"button",className:dv().primaryButton,disabled:!0,children:t("trust.working")}):(0,n.jsxs)(n.Fragment,{children:["grant"===e.pending&&(0,n.jsx)("button",{type:"button",className:dv().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void C(e.cwd,"cancel"),children:t("trust.cancelSchedule")}),e.requiresTrust&&!e.trusted&&"grant"!==e.pending&&(0,n.jsx)("button",{type:"button",className:dv().primaryButton,disabled:N,onClick:()=>d({cwd:e.cwd,action:"grant",again:"revoke"===e.pending}),children:"revoke"===e.pending?t("trust.trustAgain"):t("trust.trustProject")}),e.trusted&&(0,n.jsx)("button",{type:"button",className:dv().dangerButton,disabled:N,onClick:()=>d({cwd:e.cwd,action:"revoke",again:!1}),children:t("trust.revoke")})]})})]},e.cwd)})]})})]})}let dj=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이다"}}}'),dS=[{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"}],dC={model:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"}),(0,n.jsx)("path",{d:"M9 9h6v6H9zM9 1v3m6-3v3M9 20v3m6-3v3M1 9h3m16 0h3M1 15h3m16 0h3"})]}),theme:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("circle",{cx:"12",cy:"12",r:"8"}),(0,n.jsx)("path",{d:"M12 4a8 8 0 0 0 0 16z"})]}),skill:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"m12 3 8 4-8 4-8-4 8-4Z"}),(0,n.jsx)("path",{d:"m4 12 8 4 8-4M4 17l8 4 8-4"})]}),plugin:(0,n.jsx)(n.Fragment,{children:(0,n.jsx)("path",{d:"M8 3v5m8-5v5M6 8h12v5a6 6 0 0 1-12 0V8Zm6 11v3"})}),mcp:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("circle",{cx:"6",cy:"6",r:"2"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"2"}),(0,n.jsx)("circle",{cx:"12",cy:"18",r:"2"}),(0,n.jsx)("path",{d:"M8 7.5 11 16m5-8.5L13 16M8 6h8"})]}),access:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"4",y:"10",width:"16",height:"10",rx:"2"}),(0,n.jsx)("path",{d:"M8 10V7a4 4 0 0 1 8 0v3M12 14v2"})]}),trust:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,n.jsx)("path",{d:"m9 12 2 2 4-4"})]}),liveVoice:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,n.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2M12 19v3"})]}),attachments:(0,n.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,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,n.jsx)("path",{d:"M12 3v18M3 12h18"})]}),interaction:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M4 5h16v11H9l-5 4V5Z"}),(0,n.jsx)("path",{d:"M8 9h8m-8 3h5"})]}),context:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M5 3h11l3 3v15H5z"}),(0,n.jsx)("path",{d:"M15 3v4h4M8 11h8m-8 4h8"})]}),memory:(0,n.jsx)(n.Fragment,{children:(0,n.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,n.jsx)(n.Fragment,{children:(0,n.jsx)("path",{d:"M3 6h7l2 2h9v11H3z"})}),shell:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),(0,n.jsx)("path",{d:"m7 9 3 3-3 3m6 0h4"})]}),tools:(0,n.jsx)(n.Fragment,{children:(0,n.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,n.jsx)(n.Fragment,{children:(0,n.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,n.jsx)(n.Fragment,{children:(0,n.jsx)("path",{d:"M7 4h10v5H7zM4 15h6v5H4zm10 0h6v5h-6zM12 9v3m-5 0h10M7 12v3m10-3v3"})})};function dN({kind:e}){return(0,n.jsx)("svg",{className:dv().navIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:dC[e]??dC.tools})}function dI({field:e,busy:t,onSave:r}){let[a,s]=(0,i.useState)("secret"===e.type?"":String(e.value??""));(0,i.useEffect)(()=>{s("secret"===e.type?"":String(e.value??""))},[e.path,e.type,e.value]);let l="secret"===e.type?"":String(e.value??"");return(0,n.jsx)("input",{className:dv().textInput,type:"secret"===e.type?"password":"text",value:a,disabled:t,placeholder:"secret"===e.type&&e.configured?"Configured — enter to replace":void 0,onChange:e=>s(e.target.value),onBlur:()=>{a!==l&&("secret"!==e.type||a.length>0)&&r(a)},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})}function dT({field:e,busy:t,onSave:r}){let a=JSON.stringify(e.value??{},null,2),[s,l]=(0,i.useState)(a),[o,d]=(0,i.useState)(null);return(0,i.useEffect)(()=>{l(a),d(null)},[a]),(0,n.jsxs)("div",{style:{width:"100%"},children:[(0,n.jsx)("textarea",{className:dv().jsonEditor,style:{minHeight:92},value:s,disabled:t,onChange:e=>l(e.target.value),onBlur:()=>{if(s!==a)try{r(JSON.parse(s)),d(null)}catch(e){d(e instanceof Error?e.message:String(e))}}}),o&&(0,n.jsx)("div",{className:dv().error,children:o})]})}function dM({field:e,busy:t,onSave:r}){let i=Array.isArray(e.value)?e.value:[],a=(e,t)=>{let n=e+t;if(n<0||n>=i.length)return;let a=[...i];[a[e],a[n]]=[a[n],a[e]],r(a)};return(0,n.jsx)("div",{className:dv().multiSelect,children:e.options?.map(s=>{let l=i.indexOf(s.value);return(0,n.jsxs)("span",{className:dv().choice,"data-selected":l>=0,title:s.description,children:[(0,n.jsx)("button",{type:"button",className:dv().choiceToggle,disabled:t,onClick:()=>{let e;return e=s.value,r(i.includes(e)?i.filter(t=>t!==e):[...i,e])},children:s.label}),e.ordered&&l>=0&&(0,n.jsxs)("span",{className:dv().reorder,children:[(0,n.jsx)("button",{type:"button",disabled:t||0===l,onClick:()=>a(l,-1),children:"←"}),(0,n.jsx)("button",{type:"button",disabled:t||l===i.length-1,onClick:()=>a(l,1),children:"→"})]})]},s.value)})})}function d$({field:e,busy:t,onSave:r}){return"boolean"===e.type?(0,n.jsx)("button",{type:"button",className:dv().switch,"data-on":!0===e.value,disabled:t,"aria-pressed":!0===e.value,onClick:()=>r(!0!==e.value)}):"select"===e.type?(0,n.jsx)(l7,{value:String(e.value??""),disabled:t,ariaLabel:e.label,options:(e.options??[]).map(e=>({value:e.value,label:e.label,description:e.description})),onChange:t=>r("number"==typeof e.value||"number"==typeof e.defaultValue?Number(t):t)}):"multiselect"===e.type?(0,n.jsx)(dM,{field:e,busy:t,onSave:r}):"providerLimits"===e.type?(0,n.jsx)(dT,{field:e,busy:t,onSave:r}):(0,n.jsx)(dI,{field:e,busy:t,onSave:r})}function dR({field:e,busy:t,error:r,onSave:i}){return(0,n.jsxs)("div",{className:dv().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:dv().settingLabel,children:e.label}),(0,n.jsx)("div",{className:dv().settingDescription,children:e.description}),r&&(0,n.jsx)("div",{className:dv().error,children:r})]}),(0,n.jsx)("div",{className:dv().settingControl,children:(0,n.jsx)(d$,{field:e,busy:t,onSave:i})})]})}function dE({mode:e,palette:t}){let r=t.variables["--omp-md-heading"];return(0,n.jsxs)("div",{className:dv().themePreview,"data-seed-color-mode":"dark"===e?"dark-only":"light-only",children:[(0,n.jsx)("div",{className:dv().themePreviewBar,style:r?{background:r}:void 0}),(0,n.jsxs)("div",{className:dv().themePreviewPanel,children:[(0,n.jsx)("div",{className:dv().themePreviewLine}),(0,n.jsx)("div",{className:dv().themePreviewLine})]})]})}let dL='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',dz=new Set(["hideThinkingBlock"]);function dA({cwd:e,sessionId:t,initialSection:r="models",onClose:a,onModelsChanged:s,onReloaded:l}){let[o,d]=(0,i.useState)(r),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!0),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(""),[v,b]=(0,i.useState)(new Set),[y,w]=(0,i.useState)({}),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),{theme:N,setPreference:I}=tO(),{locale:T,t:M}=(0,R.s)(),$=(0,i.useRef)(null),E=e=>"ko"===T?dj.shell[e]??e:e,L=(0,i.useCallback)(async()=>{h(!0),m(null);try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/settings${t}`,{cache:"no-store"}),n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);u(n)}catch(e){m(e instanceof Error?e.message:String(e))}finally{h(!1)}},[e]);(0,i.useEffect)(()=>{L()},[L]),(0,i.useEffect)(()=>{let e=$.current;if(!e)return;(Array.from(e.querySelectorAll(dL)).find(e=>e.getClientRects().length>0)??e).focus();let t=t=>{if("Tab"!==t.key)return;let r=Array.from(e.querySelectorAll(dL)).filter(e=>e.getClientRects().length>0),n=document.activeElement;if(0===r.length){t.preventDefault(),e.focus();return}let i=r[0],a=r[r.length-1];t.shiftKey&&(n===i||!e.contains(n))?(t.preventDefault(),a.focus()):t.shiftKey||n!==a&&e.contains(n)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)},[]);let z=(0,i.useCallback)(async(t,r)=>{b(e=>new Set(e).add(t.path)),w(e=>{let r={...e};return delete r[t.path],r});try{let n=await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,value:r})}),i=await n.json();if(!n.ok||i.error)throw Error(i.error??`HTTP ${n.status}`);u(e=>e?{...e,fields:e.fields.map(e=>e.path===t.path?{...e,value:i.value??r,configured:!0}:e)}:e),"theme.dark"===t.path||"theme.light"===t.path?(await tH(e),await L()):dz.has(t.path)?await t8(e):j(!0)}catch(e){w(r=>({...r,[t.path]:e instanceof Error?e.message:String(e)}))}finally{b(e=>{let r=new Set(e);return r.delete(t.path),r})}},[e,L]),A=(0,i.useMemo)(()=>new Map(c?.fields.map(e=>[e.path,e.value])??[]),[c?.fields]),P=(0,i.useMemo)(()=>c?.fields.filter(e=>(function(e,t){switch(e.condition){case void 0:default:return!0;case"hasImageProtocol":return!1;case"advisorEnabled":return!0===t.get("advisor.enabled");case"hindsightActive":return"hindsight"===t.get("memory.backend");case"mnemopiActive":return"mnemopi"===t.get("memory.backend");case"autolearnActive":return!0===t.get("autolearn.enabled");case"autoThinkingActive":return"auto"===t.get("defaultThinkingLevel");case"usageAwareFallbackEnabled":return!0===t.get("retry.usageAwareFallback");case"planModeEnabled":return!0===t.get("plan.enabled");case"unexpectedStopDetection":return!0===t.get("features.unexpectedStopDetection")}})(e,A))??[],[c?.fields,A]),W=o.startsWith("settings:")?o.slice(9):null,F=(0,i.useMemo)(()=>{let e=g.trim().toLowerCase();return e?P.filter(t=>`${t.label} ${t.description} ${t.path} ${t.group??""}`.toLowerCase().includes(e)):W?P.filter(e=>e.tab===W&&("appearance"!==W||"Theme"!==e.group)):[]},[W,g,P]),_=(0,i.useCallback)(()=>{s?.(),a()},[a,s]),D=(0,i.useCallback)(async()=>{if(t){C(!0);try{await sz(t,{type:"reload"}),j(!1),l?.()}catch(e){m(e instanceof Error?e.message:String(e))}finally{C(!1)}}},[l,t]),H=c?.tabs.find(e=>e.id===W),O=g.trim()?`${E("Search")} \xb7 ${F.length}`:H?.label??E("Settings"),B=(e,t)=>[...new Set([...t,...e.map(e=>e.group??"General").filter(e=>!t.includes(e))])].map(t=>{let r=e.filter(e=>(e.group??"General")===t);return r.length?(0,n.jsxs)("section",{className:dv().group,children:[(0,n.jsx)("h3",{className:dv().groupTitle,children:t}),r.map(e=>(0,n.jsx)(dR,{field:e,busy:v.has(e.path),error:y[e.path],onSave:t=>void z(e,t)},e.path))]},t):null}),U=()=>p?(0,n.jsx)("div",{className:dv().empty,children:E("Loading omp settings…")}):f||!c?(0,n.jsx)("div",{className:dv().empty,children:f??E("Settings unavailable")}):(0,n.jsxs)("div",{className:dv().scrollContent,children:[(0,n.jsxs)("header",{className:dv().contentHeader,children:[(0,n.jsx)("h2",{className:dv().contentTitle,children:O}),(0,n.jsx)("p",{className:dv().contentDescription,children:E(g.trim()?"Matching canonical /settings entries across every category.":"Canonical omp /settings values. Changes are saved immediately to the shared agent configuration.")}),k&&t&&(0,n.jsxs)("div",{className:dv().reloadNotice,children:[(0,n.jsx)("span",{children:E("Saved. Reload the active session to apply runtime settings.")}),(0,n.jsx)("button",{type:"button",onClick:()=>void D(),disabled:S,children:E(S?"Reloading…":"Reload session")})]})]}),(0,n.jsx)("div",{className:dv().settingsBody,children:F.length?B(F,H?.groups??[]):(0,n.jsx)("div",{className:dv().empty,children:E("No settings match this search.")})})]});return(0,n.jsx)("div",{className:dv().backdrop,onMouseDown:e=>{e.target===e.currentTarget&&_()},children:(0,n.jsxs)("div",{ref:$,tabIndex:-1,className:dv().window,role:"dialog","aria-modal":"true","aria-label":E("Settings"),children:[(0,n.jsxs)("aside",{className:dv().sidebar,children:[(0,n.jsxs)("div",{className:dv().brand,children:[(0,n.jsx)("div",{className:dv().eyebrow,children:"omp /settings"}),(0,n.jsx)("h1",{className:dv().title,children:E("Settings")}),(0,n.jsx)("code",{className:dv().context,title:e??E("Global configuration"),children:e??E("Global configuration")})]}),(0,n.jsxs)("div",{className:dv().searchWrap,children:[(0,n.jsxs)("svg",{className:dv().searchIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,n.jsx)("path",{d:"m20 20-4-4"})]}),(0,n.jsx)("input",{className:dv().search,value:g,"aria-label":E("Search /settings"),placeholder:E("Search /settings"),onChange:e=>x(e.target.value)})]}),(0,n.jsxs)("nav",{className:dv().nav,children:[(0,n.jsx)("div",{className:dv().navLabel,children:E("Configuration")}),dS.map(t=>{let r=t.labelKey?M(t.labelKey):E(t.label);return(0,n.jsxs)("button",{type:"button",className:dv().navButton,"data-active":!g&&o===t.id,disabled:t.requiresCwd&&!e,title:t.requiresCwd&&!e?`${r} ${E("requires a project")}`:r,onClick:()=>{x(""),d(t.id)},children:[(0,n.jsx)(dN,{kind:t.icon}),(0,n.jsx)("span",{children:r})]},t.id)}),(0,n.jsx)("div",{className:dv().navLabel,children:E("OMP settings")}),c?.tabs.map(e=>(0,n.jsxs)("button",{type:"button",className:dv().navButton,"data-active":!g&&W===e.id,onClick:()=>{x(""),d(`settings:${e.id}`)},children:[(0,n.jsx)(dN,{kind:e.id}),(0,n.jsx)("span",{children:e.label})]},e.id))]}),(0,n.jsx)("div",{className:dv().closeRail,children:(0,n.jsxs)("button",{type:"button",className:dv().closeButton,onClick:_,children:[(0,n.jsx)("span",{children:E("Close settings")}),(0,n.jsx)("span",{"aria-hidden":"true",children:"\xd7"})]})})]}),(0,n.jsx)("main",{className:dv().content,children:g.trim()?U():"models"===o?(0,n.jsx)(o2,{cwd:e,embedded:!0,onClose:_,onModelsChanged:s}):"themes"===o?c?(0,n.jsxs)("div",{className:dv().scrollContent,children:[(0,n.jsxs)("header",{className:dv().contentHeader,children:[(0,n.jsx)("h2",{className:dv().contentTitle,children:E("Themes")}),(0,n.jsxs)("p",{className:dv().contentDescription,children:[E("The web interface uses the same dark and light theme mappings as omp. Changes are persisted to "),(0,n.jsx)("code",{children:"~/.omp/agent/config.yml"}),E(" and applied here immediately.")]})]}),(0,n.jsxs)("div",{className:dv().settingsBody,children:[(0,n.jsx)("div",{className:dv().themeGrid,children:["dark","light"].map(e=>{let t=c.fields.find(t=>t.path===`theme.${e}`),r=c.theme.palettes[e];return(0,n.jsxs)("div",{className:dv().themeCard,children:[(0,n.jsx)(dE,{mode:e,palette:r}),(0,n.jsxs)("div",{className:dv().themeCardBody,children:[(0,n.jsxs)("div",{className:dv().themeCardHeader,children:[(0,n.jsxs)("span",{className:dv().themeSlot,children:[e,E(" mapping")]}),N===e&&(0,n.jsx)("span",{className:dv().themeActive,children:E("Active on web")})]}),(0,n.jsx)(l7,{value:String(t.value),disabled:v.has(t.path),ariaLabel:`${e} theme`,options:(t.options??[]).map(e=>({value:e.value,label:e.label,description:e.description})),onChange:e=>void z(t,e)}),N!==e&&(0,n.jsxs)("button",{type:"button",className:dv().closeButton,style:{marginTop:8},onClick:()=>I(e),children:[E("Preview "),e]})]})]},e)})}),B(c.fields.filter(e=>"appearance"===e.tab&&"Theme"===e.group&&!e.path.startsWith("theme.")),["Theme"])]})]}):(0,n.jsx)("div",{className:dv().empty,children:p?E("Loading themes…"):f??E("Themes unavailable")}):"skills"===o&&e?(0,n.jsx)(dt,{cwd:e,embedded:!0,onClose:_}):"plugins"===o&&e?(0,n.jsx)(dg,{cwd:e,sessionId:t,embedded:!0,onClose:_,onReloaded:l}):"mcp"===o?(0,n.jsx)(dP,{cwd:e,sessionId:t,onReloaded:l}):"access"===o?(0,n.jsx)(db,{}):"trust"===o?(0,n.jsx)(dk,{cwd:e}):"live-voice"===o?(0,n.jsx)(dy,{}):"attachments"===o?(0,n.jsx)(dw,{}):U()})]})})}function dP({cwd:e,sessionId:t,onReloaded:r}){let[a,s]=(0,i.useState)(null),[l,o]=(0,i.useState)("user"),[d,c]=(0,i.useState)(0),[u,p]=(0,i.useState)(""),[h,f]=(0,i.useState)(""),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(null),w=(0,i.useCallback)(async()=>{try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/mcp${t}`,{cache:"no-store"}),n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);s(n),g(null)}catch(e){g(e instanceof Error?e.message:String(e))}},[e]);(0,i.useEffect)(()=>{w()},[w]);let k=a?"user"===l?a.user:a.project:null,j=k?.servers[d]??null;(0,i.useEffect)(()=>{f(j?.name??""),p(j?JSON.stringify(j.config,null,2):"")},[j]);let S=e=>{s(t=>{if(!t)return t;let r={..."user"===l?t.user:t.project,servers:e};return"user"===l?{...t,user:r}:{...t,project:r}})},C=async()=>{if(k){v(!0),g(null);try{let t,r=(t=k?.servers??[],(j?.editable===!1?t:t.map((e,t)=>t===d?{...e,name:h,config:JSON.parse(u)}:e)).filter(e=>!1!==e.editable).map(({name:e,config:t})=>({name:e,config:t}))),n=e?`?cwd=${encodeURIComponent(e)}`:"",i=await fetch(`/api/mcp${n}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:l,servers:r})}),a=await i.json();if(!i.ok||a.error)throw Error(a.error??`HTTP ${i.status}`);await w()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(!1)}}},N=async n=>{y(`${l}:${n.name}`),g(null);try{let i=e?`?cwd=${encodeURIComponent(e)}`:"",a=await fetch(`/api/mcp${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:l,name:n.name,enabled:!n.enabled})}),s=await a.json();if(!a.ok||s.error)throw Error(s.error??`HTTP ${a.status}`);await w(),t&&(await sz(t,{type:"reload"}),r?.())}catch(e){g(e instanceof Error?e.message:String(e))}finally{y(null)}};return(0,n.jsxs)("div",{className:dv().scrollContent,children:[(0,n.jsxs)("header",{className:dv().contentHeader,children:[(0,n.jsx)("h2",{className:dv().contentTitle,children:"MCP servers"}),(0,n.jsx)("p",{className:dv().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,n.jsx)("div",{className:dv().settingsBody,children:a?(0,n.jsxs)("div",{className:dv().mcpLayout,children:[(0,n.jsxs)("aside",{className:dv().mcpList,children:[(0,n.jsxs)("div",{className:dv().scopeTabs,children:[(0,n.jsxs)("button",{type:"button",className:dv().scopeButton,"data-active":"user"===l,onClick:()=>{o("user"),c(0)},children:["User \xb7 ",a.user.servers.length]}),(0,n.jsxs)("button",{type:"button",className:dv().scopeButton,"data-active":"project"===l,disabled:!a.project,onClick:()=>{o("project"),c(0)},children:["Project \xb7 ",a.project?.servers.length??0]})]}),k?.error?(0,n.jsx)("div",{className:dv().error,style:{padding:12},children:k.error}):(0,n.jsx)("div",{className:dv().serverRows,children:k?.servers.length?k.servers.map((e,t)=>{let r=`${l}:${e.name}`;return(0,n.jsxs)("div",{className:dv().serverRow,"data-active":d===t,children:[(0,n.jsxs)("button",{type:"button",className:dv().serverSelect,title:e.source?.path,onClick:()=>c(t),children:[(0,n.jsx)("span",{className:dv().statusDot,"data-off":!e.enabled}),(0,n.jsx)("span",{className:dv().serverName,children:e.name}),!1===e.editable&&(0,n.jsx)("span",{className:dv().sourceBadge,children:e.source?.provider??"external"})]}),(0,n.jsx)("button",{type:"button",className:dv().serverToggle,"data-on":e.enabled,disabled:b===r,"aria-pressed":e.enabled,"aria-label":`${e.enabled?"Disable":"Enable"} ${e.name}`,title:`${e.enabled?"Disable":"Enable"} ${e.name}`,onClick:()=>void N(e),children:b===r?"…":e.enabled?"ON":"OFF"})]},`${e.name}-${e.source?.path??t}`)}):(0,n.jsx)("div",{className:dv().serverListEmpty,children:"No servers in this scope."})}),(0,n.jsx)("button",{type:"button",className:dv().addServer,disabled:!!k?.error,onClick:()=>{if(!k)return;let e="new-server",t=2;for(;k.servers.some(t=>t.name===e);)e=`new-server-${t++}`;let r=[...k.servers,{name:e,config:{type:"stdio",command:""},enabled:!0,editable:!0}];S(r),c(r.length-1)},children:"+ Add OMP server"})]}),(0,n.jsx)("section",{className:dv().mcpEditor,children:j?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:dv().editorHeader,children:[(0,n.jsx)("input",{className:dv().textInput,value:h,readOnly:!1===j.editable,onChange:e=>f(e.target.value),placeholder:"server-name"}),!1!==j.editable&&(0,n.jsx)("button",{type:"button",className:dv().dangerButton,onClick:()=>{k&&j&&!1!==j.editable&&(S(k.servers.filter((e,t)=>t!==d)),c(Math.max(0,d-1)))},children:"Delete"})]}),!1===j.editable&&(0,n.jsxs)("div",{className:dv().readOnlyNotice,children:["Configuration read-only \xb7 managed by ",j.source?.provider??"an external provider",". Status can be changed from the server list."]}),(0,n.jsx)("textarea",{className:dv().jsonEditor,value:u,readOnly:!1===j.editable,spellCheck:!1,onChange:e=>p(e.target.value)}),(0,n.jsxs)("div",{className:dv().editorActions,children:[(0,n.jsxs)("div",{children:[m&&(0,n.jsx)("div",{className:dv().error,children:m}),(0,n.jsx)("div",{className:dv().saveState,children:j.source?.path??k?.path})]}),!1!==j.editable&&(0,n.jsx)("button",{type:"button",className:dv().primaryButton,disabled:x,onClick:()=>void C(),children:x?"Saving…":"Save MCP"})]})]}):(0,n.jsx)("div",{className:dv().empty,children:"Add or select an MCP server."})})]}):(0,n.jsx)("div",{className:dv().empty,children:m??"Loading MCP configuration…"})})]})}let dW="cuelo-notification-prompt-dismissed";function dF({variant:e,locale:t,permission:r,dismissed:i,request:a,dismiss:s}){let l="ko"===t;return null===r||"granted"===r?null:"banner"===e?"default"!==r||i?null:(0,n.jsxs)("div",{className:"workspace-update-banner",role:"region","aria-label":l?"알림 권한 안내":"Notification permission",children:[(0,n.jsx)("span",{className:"workspace-update-banner-detail",style:{fontFamily:"inherit",fontSize:"inherit",color:"inherit"},children:l?"백그라운드 작업 완료 알림을 받으세요.":"Get notified when background work finishes."}),(0,n.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:a,children:l?"알림 켜기":"Enable notifications"}),(0,n.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:s,"aria-label":l?"알림 권한 안내 닫기":"Dismiss notification prompt",children:l?"닫기":"Dismiss"})]}):(0,n.jsx)(d.k.Item,{disabled:"denied"===r,onClick:"default"===r?a:void 0,children:(0,n.jsxs)(d.k.ItemBody,{children:[(0,n.jsx)(d.k.ItemLabel,{children:"default"===r?l?"알림 켜기":"Enable notifications":l?"알림 차단됨":"Notifications blocked"}),"denied"===r&&(0,n.jsx)(d.k.ItemDescription,{children:l?"주소창 옆 사이트 설정에서 알림을 허용하세요.":"Allow notifications in site settings beside the address bar."})]})})}function d_({cwd:e,busy:t,scheduled:r,error:a,onCancel:s,onConfirm:l,onCancelSchedule:o}){let{t:d}=(0,R.s)(),c=(0,i.useRef)(null);(0,i.useEffect)(()=>{c.current?.focus()},[r]);let u={height:32,padding:"0 12px",borderRadius:5,cursor:t?"not-allowed":"pointer",fontSize:12};return(0,n.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:e=>{t||e.target!==e.currentTarget||s()},children:(0,n.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,n.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,n.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,n.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),r?(0,n.jsx)("path",{d:"M12 8v4l2 2"}):(0,n.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{id:"project-trust-title",style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:d(r?"trust.scheduledTitle":"trust.dialogTitle")}),(0,n.jsx)("div",{id:"project-trust-body","aria-live":"polite",style:{marginTop:7,fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:d(r?"trust.scheduledBody":"trust.dialogBody")}),(0,n.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:e}),a&&(0,n.jsx)("div",{role:"alert",style:{marginTop:10,color:"#ef4444",fontSize:12,lineHeight:1.5},children:a})]})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[r&&(0,n.jsx)("button",{type:"button",onClick:o,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:d("trust.cancelSchedule")}),(0,n.jsx)("button",{ref:c,type:"button",onClick:s,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:d(r?"trust.close":"trust.cancel")}),!r&&(0,n.jsx)("button",{type:"button",onClick:l,disabled:t,style:{...u,border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:t?"wait":"pointer",opacity:t?.7:1,fontWeight:600},children:d(t?"trust.trusting":"trust.trustProject")})]})]})})}var dD=r(70451),dH=r(54265);let dO={kind:"loading"};function dB(e){return"failed"===e.status?"var(--danger)":"aborted"===e.status||e.progress?.retryState?"var(--warning)":(0,rq.Ch)(e.status)?"var(--accent)":"var(--success)"}function dU(e){return"live-archive"===e.identity?"실시간 + 디스크":"live"===e.identity?"실시간":"디스크 기록"}let dq={bundled:"기본 제공",user:"사용자 정의",project:"프로젝트 정의"};function dK(e){return e.lastUpdate||e.progress?.durationMs||0}function dV(){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 dJ({sessionId:e,sessionCwd:t,record:r,client:a,visible:s,onBack:l}){let o=(0,i.useMemo)(()=>[{key:r.key,liveId:r.live?.id,status:r.live?.status,archiveName:r.archive?.name}],[r.key,r.live?.id,r.live?.status,r.archive?.name]),d=(0,i.useRef)(null),c=(0,rq._Z)(o,{sessionId:e,client:a,enabled:s}).get(r.key)?.state??dO;(0,i.useEffect)(()=>{if(!s||"ready-live"!==c.kind&&"ready-archive"!==c.kind)return;let e=requestAnimationFrame(()=>{let e=d.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[c,s]);let u="ready-live"===c.kind?c.entries:[],p=(0,i.useMemo)(()=>{let e=new Map;for(let t of u)"message"in t&&"toolResult"===t.message.role&&e.set(t.message.toolCallId,t.message);return e},[u]),h=r.live?.id||r.archive?.name||"Subagent";return(0,n.jsxs)("div",{role:"dialog","aria-label":`${h} 기록`,style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("button",{type:"button",onClick:l,"aria-label":"Subagent 목록으로 돌아가기",title:"목록",style:dV(),children:(0,n.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,n.jsx)("path",{d:"m10.5 3-5 5 5 5"})})}),(0,n.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,n.jsx)("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11.5,fontWeight:700},children:h}),(0,n.jsx)("div",{style:{marginTop:2,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9},children:dU(r)})]}),r.live&&(0,n.jsx)("span",{style:{color:dB(r.live),fontFamily:"var(--font-mono)",fontSize:9.5},children:r.live.status})]}),(0,n.jsxs)("div",{ref:d,style:{flex:1,minHeight:0,overflowY:"auto",padding:"10px 12px 18px"},children:["loading"===c.kind&&(0,n.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"기록 불러오는 중…"}),"ready-live"===c.kind&&c.entries.flatMap((e,r)=>{if(!("message"in e))return[];let i=c.entries[r-1];return[(0,n.jsx)(nL,{message:e.message,toolResults:p,cwd:t,showTimestamp:!0,prevTimestamp:i&&"message"in i?i.message.timestamp:void 0},e.id)]}),"ready-archive"===c.kind&&(0,n.jsxs)(n.Fragment,{children:[c.note&&(0,n.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--text-muted)",fontSize:9.5,lineHeight:1.5},children:c.note}),c.truncated&&(0,n.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--warning)",fontSize:9.5},children:"최근 400개 기록만 표시합니다."}),c.entries.map((e,t)=>(0,n.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,n.jsxs)("div",{style:{marginBottom:5,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:8.5,letterSpacing:"0.04em"},children:[e.role," \xb7 ",e.kind]}),e.text||"(내용 없음)"]},`${e.at??0}:${t}`))]}),"empty"===c.kind&&(0,n.jsxs)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:[c.note&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{children:c.note}),(0,n.jsx)("br",{})]}),"대화 내용이 없습니다."]}),"unreachable"===c.kind&&(0,n.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:c.message}),"error"===c.kind&&(0,n.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:c.message})]})]})}function dG({record:e,view:t,onSelect:r}){let{st:a}=rp(),s=(0,i.useId)(),l=e.live,o=e.archive,d=(0,rC.$V)(e),c=!!(l&&(0,rq.Ch)(l.status)),u=c?d.stage:null,p=c&&t?t:null,h=p?.phase?a("phase.current",{phase:a(`phase.${p.phase}`)}):"",f=p?.todo?rZ(a,p.todo):"",m=l?.id||o?.name||"Subagent",g=dU(e),x=(0,rC.wX)(e),v=(0,rC.A7)(e),b=v.modelShort??"모델 미확인",y=v.effort??"추론 미확인",w="known"===x.kind?x.label:"역할 미확인";return(0,n.jsxs)("button",{type:"button",role:"listitem",onClick:r,"data-identity":e.identity,title:`${m}
|
|
20
20
|
${v.model??"모델 미확인"} \xb7 ${y}
|
|
21
21
|
${d.title}${u?`
|
|
22
22
|
현재 단계: ${u}`:""}${h?`
|